
    rh                     >   d Z ddlZddlmZmZ ddlZddlmc 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 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*m+Z+ ddl,m-Z-  e*       r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:d7d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. d/eDe      ZF G d0 d1eeD      ZG G d2 d3eeD      ZH G d4 d5eeD      ZIg d6ZJy)8zPyTorch Nemotron model.    N)OptionalUnion)SizeTensornn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)_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is_torch_flex_attn_availablelogging   )NemotronConfig)	BlockMask)make_flex_block_causal_maskc                     t        j                         s|S t        t         d      rt        j                  |       nt        j                         }t         j
                  j                  j                  || |      S )Nget_autocast_dtype)torchis_autocast_enabledhasattrr#   get_autocast_gpu_dtypeampautocast_mode_cast)device_typeargstarget_dtypes      /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/nemotron/modeling_nemotron.py_cast_if_autocast_enabledr/   8   sb    $$&
 u23 $$[1--/ 	
 yy&&,,T;MM    c            	       ^     e Zd Z	 	 	 	 	 d	deeee   ef   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 N)super__init__)selfr3   r4   r5   r6   devicedtype	__class__s          r.   r:   zNemotronLayerNorm1P.__init__F   s     	)30BD&RWXr0   inputreturnc                    |j                   j                  dk7  r|j                   j                  nd}t        ||| j                  | j                  dz   | j
                  | j                        }t        j                  |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)r<   typer/   r3   weightr6   r4   r$   autocastF
layer_norm)r;   r?   r+   r,   s       r.   forwardzNemotronLayerNorm1P.forwardQ   s    +0<<+<+<+Eell''5( 5 5t{{Q		SWS[S[
 ^^(9(95I 	'<<&	' 	' 	's   B44B=)gh㈵>TTNN)__name__
__module____qualname__r   intlistr   floatboolr:   r   rK   __classcell__r>   s   @r.   r2   r2   E   sg     #'	YT#Y 45	Y 	Y !		Y
 	Y'V ' 'r0   r2   c                   `     e Zd Z	 ddef fdZ ej                         ed               Z xZ	S )NemotronRotaryEmbeddingconfigc                 D   t         |           d| _        |j                  | _        |j                  | _        || _        t        | j                     | _        | j                  | j                  |      \  }| _	        | j                  d|d       | j                  | _        y )Ndefaultinv_freqF)
persistent)r9   r:   	rope_typemax_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrW   r   rope_init_fnattention_scalingregister_bufferrZ   original_inv_freq)r;   rW   r<   rZ   r>   s       r.   r:   z NemotronRotaryEmbedding.__init__]   s    
 	""("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r0   c                 b   | 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        j                  |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   rB   rC   FrD      dim)r=   )rZ   rQ   expandshapetor<   
isinstancerF   strr$   rH   	transposecatcosra   sinr=   )
r;   xposition_idsinv_freq_expandedposition_ids_expandedr+   freqsembrp   rq   s
             r.   rK   zNemotronRotaryEmbedding.forwardo   sV    !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.r8   )
rL   rM   rN   r   r:   r$   no_gradr   rK   rS   rT   s   @r.   rV   rV   [   s9    
 //$ U]]_<  <r0   rV   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..Nre   rf   rg   )rj   r$   ro   )rr   x1x2s      r.   rotate_halfr|      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r0   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.
        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.
    re   .Nrg   )	unsqueezerj   r|   r$   ro   )qkrp   rq   rs   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Ur0   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r6   )r9   r:   rW   hidden_sizeintermediate_sizer   Linearmlp_biasup_proj	down_projr	   
hidden_actact_fnr;   rW   r>   s     r.   r:   zNemotronMLP.__init__   s    !--!'!9!9yy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r0   c                 `    | j                  | j                  | j                  |                  S r8   )r   r   r   )r;   rr   s     r.   rK   zNemotronMLP.forward   s"    ~~dkk$,,q/:;;r0   )rL   rM   rN   r:   rK   rS   rT   s   @r.   r   r      s    0<r0   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)rj   ri   reshape)r   r   batchnum_key_value_headsslenhead_dims         r.   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr0   c                   b    e Zd ZdZddedee   f f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Z xZS )NemotronAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrW   	layer_idxc                 6   t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        |j                  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        |j                   | _        |j"                  | _        d| _        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.Tr   )r9   r:   rW   r   loggerwarning_oncer>   rL   attention_dropoutr   num_attention_heads	num_headsr   r   num_key_value_groupsr]   
rope_thetapartial_rotary_factor	is_causalr   r   attention_biasq_projk_projv_projo_projr;   rW   r   r>   s      r.   r:   zNemotronAttention.__init__   s   " !8!8 9 :, , "(!9!9!--33#)#=#= $(NNd6N6N$N!'-'E'E$ ++%+%A%A"ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii >@P@PW]WlWlmr0   r   position_embeddingsattention_maskrs   past_key_valueoutput_attentions	use_cachecache_positionr@   c	                 R   |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  }|#|d d d d d d d |j$                  d   f   }||z   }t&        j(                  j+                  |dt        j,                        j/                  |j0                        }t&        j(                  j3                  || j4                  | j6                        }t        j                  ||      }|j                  dd      j9                         }|j;                  |	|
d      }| j=                  |      }|sd }||fS )	Nr   rf   rq   rp   r   r   re   )rh   r=   )ptraining)sizer   r   r   viewr   r   rn   r   r   updater   r   r   r$   matmulmathsqrtrj   r   
functionalsoftmaxfloat32rk   r=   dropoutr   r   
contiguousr   r   )r;   r   r   r   rs   r   r   r   r   bszq_len_query_states
key_statesvalue_statesrp   rq   cache_kwargsattn_weightscausal_maskattn_outputs                        r.   rK   zNemotronAttention.forward   sn    &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm**HC#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$Jz4+D+DE
 t/H/HI||L*2F2Fq!2LMPTPYPYZ^ZgZgPhh%(Aq2HJ4D4DR4H2H)HIK'+5L }},,\r,WZZ[g[m[mn}},,\T=S=S^b^k^k,lll<>!++Aq1<<>!))#ub9kk+. LL((r0   r8   NNNFFN)rL   rM   rN   __doc__r   r   rO   r:   r$   r   tuple
LongTensorr
   rR   rK   rS   rT   s   @r.   r   r      s    Gn~ n(3- n> 2637*."'595)||5) #5<<#=>5) !.	5)
 u//05) !5)  5) 5) !!1!125) 
u||Xell3XeELL>Q5RR	S5)r0   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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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 r8   )r9   r:   r   _flash_attn_uses_top_left_mask)r;   r,   kwargsr>   s      r.   r:   z NemotronFlashAttention2.__init__"  s#    $)&)
 /P.Q+r0   r   r   r   rs   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/        t(        d	      rt)        j0                  |      nt)        j2                         }nMt/        | j4                  d
      r| j4                  j6                  }n | j                  j8                  j"                  }t:        j=                  d| d       |j?                  |      }|j?                  |      }|j?                  |      }tA        |||||
||tC        | dd       | jD                  | jF                  
      }|jI                  |	|
d      jK                         }| jM                  |      }|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   rf   r           rB   rC   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)rs   r   r   use_top_left_maskr   re   )'rl   r   
ValueErrorr   r   r   r   r   r   r   rn   r   r   r   r   r   r   r=   r<   rF   r$   r   r%   r&   r#   r'   rW   r   rG   r   r   rk   r   getattrr   r   r   r   r   )r;   r   r   r   rs   r   r   r   r   r   r   r   r   r   r   rp   rq   r   dropout_rateinput_dtyper+   r-   r   r   s                           r.   rK   zNemotronFlashAttention2.forward+  s    nk2} 
 "%**,UA{{=1[[/
{{=1
 $((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm**HC#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$J $--a3))!Q/
#--a315t--C #((2>2E2E2J2Je2Sl))..Y^%--'((* u&:; ,,[9557  &?@#{{BB#{{1177 >$ (??<8L#|4J'??<8L.% "4)94@"AAnn
 "))#ub9DDFkk+. LL((r0   r   )rL   rM   rN   r   r:   r$   r   r   r   r   r
   rR   rK   rS   rT   s   @r.   r   r     s    R 6:37*."'59d)||d) #5<<#=>d) !!1!12	d)
 u//0d) !d)  d) d) !!1!12d) 
u||Xell3XeELL>Q5RR	Sd)r0   r   c                   J    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Z x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.
    r   r   r   rs   r   r   r   r   r@   c	           
      &   |r,t         j                  d       t        |   ||||||||      S |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   }|j&                  j(                  dk(  r2|0|j+                         }|j+                         }|j+                         }|d u xr |dkD  }t,        j.                  j0                  j3                  ||||| j4                  r| j6                  nd|	      }|j                  dd      j+                         }|j                  |
|d
      }| j9                  |      }|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.r   r   rs   r   r   r   r   r   r   rf   r   r   cudar   )	attn_mask	dropout_pr   re   )r   r   r9   rK   r   r   r   r   r   r   r   rn   r   r   r   r   r   r   rj   r<   rF   r   r$   r   r   scaled_dot_product_attentionr   r   r   )r;   r   r   r   rs   r   r   r   r   r   r   r   r   r   r   r   rp   rq   r   r   r   r   r>   s                         r.   rK   zNemotronSdpaAttention.forward  s    [ 7?+-)-"3#-$7 # 	 	 &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm**HC#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$Jz4+D+DE
 t/H/HI$%%aA/E1A1A"1E/E&EFK ##v-+2I'224L#..0J'224L  4'5EAI	hh))FF!04d,,3 G 
 "++Aq1<<>!&&sE26kk+.D  r0   r   )rL   rM   rN   r   r$   r   r   r   r   r
   rR   rK   rS   rT   s   @r.   r   r     s     2637*."'59P!||P! #5<<#=>P! !.	P!
 u//0P! !P!  P! P! !!1!12P! 
u||Xell3XeELL>Q5RR	SP! P!r0   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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Z xZS )NemotronDecoderLayerrW   r   c                 :   t         |           |j                  | _        t        |j                     ||      | _        t        |      | _        t        |j                  |j                        | _
        t        |j                  |j                        | _        y )N)rW   r   r4   )r9   r:   r   NEMOTRON_ATTENTION_CLASSES_attn_implementation	self_attnr   mlpr2   norm_epsinput_layernormpost_attention_layernormr   s      r.   r:   zNemotronDecoderLayer.__init__  sx    !--3F4O4OPX^jstv&263E3E6??[(;F<N<NTZTcTc(d%r0   r   r   rs   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_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    )r   r   r   r   )r;   r   r   rs   r   r   r   r   r   r   residualself_attn_weightsoutputss                r.   rK   zNemotronDecoderLayer.forward  s    D !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr0   )NNNFFNN)rL   rM   rN   r   rO   r:   r$   r   r   r   r
   rR   r   FloatTensorrK   rS   rT   s   @r.   r   r     s    e~ e# e 2637*.,1$)59KO?||? !.? u//0	?
 !? $D>? D>? !!1!12? &eELL%,,,F&GH? 
u  (51B1BEDUDU1U+V"WW	X?r0   r   c                   >    e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZd Zy)NemotronPreTrainedModelrW   modelTr   past_key_valuesc                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y t        |t              rJ|j
                  j                  j                  d       |j                  j                  j                          y y )Nr   )meanstdg      ?)rW   initializer_rangerl   r   r   rG   datanormal_r6   zero_	Embeddingpadding_idxr2   fill_)r;   moduler  s      r.   _init_weightsz%NemotronPreTrainedModel._init_weightsR  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . 34MM$$S)KK""$ 5r0   N)rL   rM   rN   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraphr  r   r0   r.   r  r  F  s<    &*#/0#4"5N!%r0   r  c                   
    e Zd ZdZdef f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              Z	 ddee	j                  df   de	j                  de	j                  ded
ef
dZede	j                  dedede	j,                  de	j                  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
    rW   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   )rW   F)r9   r:   pad_token_idr  
vocab_sizer   r  r   embed_tokens
ModuleListrangenum_hidden_layersr   layersr2   r   normrV   
rotary_embgradient_checkpointing	post_initr   s      r.   r:   zNemotronModel.__init__j  s     !.. ++LL):):F<N<NPTP`P`ammFKFLdLdFef!&)4f
 ((:(:P	1@&+# 	 gs   D	input_idsr   rs   r  inputs_embedsr   r   output_hidden_statesr   r@   c
                 j   ||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                  |      }|r|
t               }|	F||j                         nd}
t        j                  |
|
|j                  d   z   |j                        }	||	j!                  d      }| 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<   r   )r   rs   r   r   r   r   r   )last_hidden_stater  r   
attentions)rW   r   r)  r   r   r%  r   r   r   r   r  get_seq_lengthr$   arangerj   r<   r~   _update_causal_maskr$  r"  r#  r   )r;   r'  r   rs   r  r(  r   r   r)  r   past_seen_tokensr   r   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                     r.   rK   zNemotronModel.forwardz  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I0*nO  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]

 & #oom\J #7BD0d![[ 	6M#!m%55!)*)."3#-$7	M *!,M =#3"55%	6( 		-0  -!11&+++%	
 	
r0   r    input_tensorc           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  }|j                  d   }	|r|j                         }
n1t        |t        j
                        r|j                  d	   n||	z   dz   }
| j                  ||	|
|||j                  d   
      }| j                   j                  dk(  rQ|O|j                   j"                  dv r7|s5t	        j$                  |      j&                  }t        j(                  ||      }|S )Nr   r   flex_attentionr   Fr   )r(  past_key_values_lengthis_trainingr   re   )sequence_lengthtarget_lengthr=   r   
batch_size)r   xpunpu)rW   r   anyrl   r$   r   r!   r.  is_compileabler   _ignore_causal_mask_sdpar   r=   rj   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr<   rF   finfomin_unmask_unattended)r;   r   r6  r   r  r   r1  using_compilable_cacher=   r;  r<  r   	min_dtypes                r.   r0  z!NemotronModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCKQZ[Kr0   r;  r<  r=   r=  c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |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   )
fill_valuer=   r<   r   )diagonalr+  re   r   )rh   r$   rE  rF  fullr<   triur/  r   ri   clonerj   rk   masked_fill)r   r;  r<  r=   r   r=  r   r   rI  mask_lengthpadding_masks              r.   rD  zCNemotronModel._prepare_4d_causal_attention_mask_with_cache_position  s   > %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r0   )	NNNNNNNNN)F)rL   rM   rN   r   r   r:   r   r   r   r$   r   r   r   r
   rP   r   rR   r   rK   r0  staticmethodrO   r=   rD  rS   rT   s   @r.   r  r  a  s   ~    151537KO59$(,0/359Y
E,,-Y
 !.Y
 u//0	Y

 "%tE4E4E/F(F"GHY
   1 12Y
 D>Y
 $D>Y
 'tnY
 !!1!12Y
 
!Y
  Y
D #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r0   r  c                       e Zd ZdgZ fdZd Z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              Z xZS )NemotronForCausalLMzlm_head.weightc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y )NFr   )
r9   r:   r  r  r  r   r   r   lm_headr&  r   s     r.   r:   zNemotronForCausalLM.__init__Y  sU     "6*
 ++yy!3!3V5F5FUS 	r0   c                     || _         y r8   r  )r;   decoders     r.   set_decoderzNemotronForCausalLM.set_decoderb  s	    
r0   c                     | j                   S r8   rZ  )r;   s    r.   get_decoderzNemotronForCausalLM.get_decodere  s    zzr0   r'  r   rs   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   rs   r  r(  r   r   r)  r   )losslogitsr  r   r-  )rW   r   r)  r  r,  rl   rO   slicerX  loss_functionr  r   r  r   r-  )r;   r'  r   rs   r  r(  r_  r   r   r)  r   r`  r   r   r   slice_indicesrc  rb  s                     r.   rK   zNemotronForCausalLM.forwardh  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!//))
 	
r0   )NNNNNNNNNNr   )rL   rM   rN   _tied_weights_keysr:   r\  r^  r   r   r   r$   r   r   r   r
   rP   r   rR   rO   r   rK   rS   rT   s   @r.   rV  rV  V  sR   *+  151537KO59-1$(,0/35934F
E,,-F
 !.F
 u//0	F

 "%tE4E4E/F(F"GHF
   1 12F
 ))*F
 D>F
 $D>F
 'tnF
 !!1!12F
 c5<</0F
 
 F
  F
r0   rV  c                       e Zd Zy)!NemotronForSequenceClassificationNrL   rM   rN   r   r0   r.   ri  ri        r0   ri  c                       e Zd ZdZy)NemotronForQuestionAnsweringtransformerN)rL   rM   rN   r  r   r0   r.   rm  rm    s    %r0   rm  c                       e Zd Zy)NemotronForTokenClassificationNrj  r   r0   r.   rp  rp    rk  r0   rp  )rm  rV  r  r  ri  rp  )Nr   )Kr   r   typingr   r   r$   torch.nn.functionalr   r   rI   torch.utils.checkpointr   r   activationsr	   cache_utilsr
   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   r   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   r   r   configuration_nemotronr   !torch.nn.attention.flex_attentionr    integrations.flex_attentionr!   
get_loggerrL   r   r/   	LayerNormr2   ModulerV   r|   r   r   rO   r   r   r   r   r   r   r  r  rV  ri  rm  rp  __all__r   r0   r.   <module>r     s      "     " " ! ; ; ) > i  L - \ \ 2  !;J 
		H	%
N'",, ',!<bii !<J(VB<")) <	UU\\ 	U# 	U%,, 	US)		 S)pt)/ t)rX!- X!x 0! K5 K\ %o % %4 p+ p phZ
1? Z
z h(HJa g&#>@W & b%BD[ ar0   