
    qiPW                     Z   d dl Z d dlmZ d dlmZ d dlZd dlmZ ddlm	Z
 ddlmZ ddlmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZ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& ddl'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.  G d dej                  j^                        Z0 G d dej^                        Z1 ed      d6d       Z2dejf                  de4dejf                  fdZ5	 d7dej^                  d ejf                  d!ejf                  d"ejf                  d#ejf                  dz  d$e6d%e6d&e#e%   fd'Z7d( Z8 ee2       G d) d*ej^                               Z9 G d+ d,ej^                        Z: G d- d.e      Z;e& G d/ d0e!             Z<e& G d1 d2e<             Z=e& G d3 d4e<e             Z>g d5Z?y)8    N)Callable)Optional   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_func_from_hubuse_kernelized_func)create_causal_mask)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstring)can_return_tuplemaybe_autocastmerge_with_config_defaults)capture_outputs   )NanoChatConfigc                   8     e Zd Zddef fdZd Zd Zd Z xZS )NanoChatRMSNormepsc                 0    t         |           || _        y N)super__init__r    )selfr    	__class__s     `/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/nanochat/modeling_nanochat.pyr$   zNanoChatRMSNorm.__init__.   s        c                     |t        j                  |j                  d      j                  dd      | j                  z         z  S )N   T)keepdim)torchrsqrtpowmeanr    r%   xs     r'   _normzNanoChatRMSNorm._norm2   s4    5;;quuQx}}R}>IJJJr(   c                 ^    | j                  |j                               j                  |      S r"   )r3   floattype_asr1   s     r'   forwardzNanoChatRMSNorm.forward5   s"    zz!'')$,,Q//r(   c                      d| j                    S )Nzeps=r    )r%   s    r'   
extra_reprzNanoChatRMSNorm.extra_repr8   s    dhhZ  r(   )gư>)	__name__
__module____qualname__r5   r$   r3   r7   r:   __classcell__r&   s   @r'   r   r   -   s    E K0!r(   r   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 )NanoChatRotaryEmbedding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defaultrB   F)
persistentoriginal_inv_freq)r#   r$   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrC   rope_parametersrE   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r%   rC   devicerope_init_fnrB   r&   s        r'   r$   z NanoChatRotaryEmbedding.__init__?   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr(   rQ   ztorch.deviceseq_lenreturnztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  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head_dimNg      ?r   r*   dtype)rQ   rY   )	rL   getattrhidden_sizenum_attention_headsr-   arangeint64tor5   )rC   rQ   rS   basedimattention_factorrB   s          r'   rM   z7NanoChatRotaryEmbedding.compute_default_rope_parametersO   s    & %%l3fj$/c63E3EIcIc3c 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   mpscpuF)device_typeenabledr*   ra   rX   )rB   r5   expandshaper_   rQ   
isinstancetypestrr   	transposer-   catcosrN   sinrY   )
r%   r2   position_idsinv_freq_expandedposition_ids_expandedrf   freqsembrp   rq   s
             r'   r7   zNanoChatRotaryEmbedding.forwardm   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)r;   r<   r=   r-   Tensor__annotations__r   r$   staticmethodr   inttupler5   rM   no_gradr   r7   r>   r?   s   @r'   rA   rA   <   s    llV~ V  (,+/"*%*(* t* 
~u$	%	* *: U]]_<  <r(   rA   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||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.
    )	unsqueezerotate_half)qkrp   rq   unsqueeze_dimq_embedk_embeds          r'   apply_rotary_pos_embr   }   sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr(   hidden_statesn_reprT   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slenrW   s         r'   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr(   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr*   r   r+   )ra   rY   )ptrainingr   )r   num_key_value_groupsr-   matmulrn   nn
functionalsoftmaxfloat32r_   rY   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r'   eager_attention_forwardr      s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r(   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  || fd      S )zJRotates half the hidden dims of the input with flipped signs for NanoChat..Nr+   r*   rh   )rj   r-   ro   )r2   x1x2s      r'   r   r      sZ    	
3"!''"+"""	#B	
3q ""	#B99b2#YB''r(   c                       e Zd ZdZdedef fdZ	 	 	 	 ddej                  de	ej                  ej                  f   dz  dej                  dz  d	e
dz  d
ej                  dz  dee   de	ej                  ej                  dz  f   fdZ xZS )NanoChatAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrC   	layer_idxc                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |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                        | _        t)        |j*                        | _        t)        |j*                        | _        y )NrW   g      Tbiasr9   )r#   r$   rC   r   rZ   r[   r\   rW   r   r   r   attention_dropout	is_causalr   Linearattention_biasq_projk_projv_projo_projr   rms_norm_epsq_normk_normr%   rC   r   r&   s      r'   r$   zNanoChatAttention.__init__   ss   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 &&*=*=>%&*=*=>r(   Nr   position_embeddingsr   past_key_valuescache_positionr   rT   c                 \   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
| j                  |	      }	| j                  |
      }
|'|||d}|j                  |
|| j                  |      \  }
}t        j                  | j                  j                  t               } || |	|
||f| j"                  sdn| j$                  | j&                  d|\  }} |j(                  g |d j+                         }| j-                  |      }||fS )Nr+   r   r*   )rq   rp   r           )r   r   )rj   rW   r   viewrn   r   r   r   r   r   updater   r   get_interfacerC   _attn_implementationr   r   r   r   r   r   r   )r%   r   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   rp   rq   cache_kwargsattention_interfacer   r   s                     r'   r7   zNanoChatAttention.forward   s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j {{<0[[,
&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r(   )NNNN)r;   r<   r=   __doc__r   rz   r$   r-   rw   r{   r   
LongTensorr   r   r7   r>   r?   s   @r'   r   r      s    G?~ ?# ?: IM.2(,26-)||-) #5<<#=>E-) t+	-)
 -) ((4/-) +,-) 
u||U\\D00	1-)r(   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )NanoChatMLPc                 $   t         |           || _        t        |j                     | _        t        j                  |j                  |j                  d      | _
        t        j                  |j                  |j                  d      | _        y NFr   )r#   r$   rC   r   
hidden_actactivation_fnr   r   r[   intermediate_sizefc1fc2r%   rC   r&   s     r'   r$   zNanoChatMLP.__init__  sj    #F$5$5699V//1I1IPUV99V55v7I7IPUVr(   r   rT   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r"   )r   r   r   )r%   r   s     r'   r7   zNanoChatMLP.forward  s4    /**=9/r(   )r;   r<   r=   r$   r-   rw   r7   r>   r?   s   @r'   r   r     s$    WU\\ ell r(   r   c                   "    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j                  dz  deej                  ej                  f   dz  dee   dej                  fdZ xZS )NanoChatDecoderLayerrC   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                        | _	        t        |j                        | _
        y )N)rC   r   r9   )r#   r$   r[   r   	self_attnr   mlpr   r   input_layernormpost_attention_layernormr   s      r'   r$   zNanoChatDecoderLayer.__init__!  s\    !--*&INv&.63F3FG(7F<O<O(P%r(   Nr   r   rr   r   	use_cacher   r   r   rT   c                     |}	| j                  |      } | j                  d|||||||d|\  }}
|	|z   }|}	| j                  |      }| j                  |      }|	|z   }|S )N)r   r   rr   r   r   r   r    )r   r   r   r   )r%   r   r   rr   r   r   r   r   r   residual_s              r'   r7   zNanoChatDecoderLayer.forward,  s     !,,];)4>> 	
')%+) 3	
 	
q !=0 !55mD/ =0r(   )NNNFNN)r;   r<   r=   r   rz   r$   r-   rw   r   r   boolr{   r   r   r7   r>   r?   s   @r'   r   r      s    	Q~ 	Q# 	Q /304(,!&26HL|| t+ &&-	
  $; ((4/ #5<<#=>E +, 
r(   r   c                   z     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dZeedZdej$                  dd	f fd
Z xZS )NanoChatPreTrainedModelrC   modelTr   r   )r   
attentionsr   rT   Nc           	          t         |   |       t        |t              rnt	        j
                  |j                  j                  d| j                  j                  t        j                  d| j                  j                  z        z         y y )Nr   r*   )r0   std)r#   _init_weightsrk   r   initnormal_r   weightrC   initializer_rangemathsqrtnum_hidden_layers)r%   r   r&   s     r'   r   z%NanoChatPreTrainedModel._init_weights`  sf    f%f/0LL$$KK11DIIa$++B_B_>_4`` 1r(   )r;   r<   r=   r   rx   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r   _can_record_outputsr   Moduler   r>   r?   s   @r'   r   r   N  sn    &*#/0#4"5N!"&-'
BII $  r(   r   c                       e Zd Zdef fdZe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e   defd                     Z xZS )NanoChatModelrC   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr9   rC   F)r#   r$   pad_token_idpadding_idx
vocab_sizer   	Embeddingr[   embed_tokens
ModuleListranger   r   layersr   r   normrA   
rotary_embgradient_checkpointing	post_initr   s      r'   r$   zNanoChatModel.__init__l  s     !.. ++LL):):F<N<NPTP`P`ammFKFLdLdFef!&)4f
 $(;(;<	1@&+# 	 gs   C6N	input_idsr   rr   r   inputs_embedsr   r   r   rT   c           
      d   |d u |d uz  rt        d      || j                  |      }|r|t        | j                        }|E||j	                         nd}	t        j                  |j                  d   |j                        |	z   }||j                  d      }t        | j                  |||||      }
|}| j                  ||      }| j                  |      }| j                  d | j                  j                   D ]  } ||f|
||||d|} | j                  |      }t        ||	      S )
Nz:You must specify exactly one of input_ids or inputs_embedsr   r   r   )rQ   )rC   r  r   r   r   rr   )rr   )r   r   rr   r   r   )last_hidden_stater   )
ValueErrorr  r	   rC   get_seq_lengthr-   r]   rj   rQ   r   r   r	  r  r  r   r   )r%   r  r   rr   r   r  r   r   r   past_seen_tokenscausal_maskr   r   decoder_layers                 r'   r7   zNanoChatModel.forward}  sh    -t";<YZZ *.*;*;I*FM0*$++>O!CRC^==?de]003M<P<PQTdd  )33A6L(;;'))+%
 &"oom,oW		-0![[)H4;;+H+HI 		M)*$7) /- M		 		-0&++
 	
r(   )NNNNNNN)r;   r<   r=   r   r$   r   r   r   r-   r   rw   r   FloatTensorr   r   r   r   r7   r>   r?   s   @r'   r   r   j  s    ~ "   .2.204(,2626!%9
##d*9
 t+9
 &&-	9

 9
 ((4/9
 ((4/9
 $;9
 +,9
 
!9
    9
r(   r   c                   b    e Zd ZddiZddiZddgdgf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	j                  dz  dee	j                  z  dee   defd              Z xZS )NanoChatForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r   )
r#   r$   r   r   r  r   r   r[   r  r  r   s     r'   r$   zNanoChatForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r(   Nr  r   rr   r   r  labelsr   r   logits_to_keepr   rT   c
                     | j                   d|||||||d|
}|j                  }t        |	t              rt	        |	 d      n|	}| j                  |dd|ddf         }| j                  j                  G|| j                  j                  z  }t        j                  |      }|| j                  j                  z  }d}| | j                  ||| j                  fi |
}t        |||j                  |j                  |j                        S )ak  
        Example:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForCausalLM

        >>> model = AutoModelForCausalLM.from_pretrained("karpathy/nanochat-d32")

        >>> tokenizer = AutoTokenizer.from_pretrained("karpathy/nanochat-d32")

        >>> conversation = [
                {"role": "user", "content": "What is the capital of France?"},
            ]

        >>> inputs = tokenizer.apply_chat_template(
                conversation, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
            ).to(device)

        >>> with torch.no_grad():
        >>>     outputs = model.generate(**inputs, max_new_tokens=64, do_sample=False)

        >>> generated_tokens = outputs[0, inputs["input_ids"].shape[1] :]
        >>> output = tokenizer.decode(generated_tokens, skip_special_tokens=True)
        ```)r  r   rr   r   r  r   r   N)lossr  r   r   r   r   )r   r  rk   rz   slicer  rC   final_logit_softcappingr-   tanhloss_functionr  r   r   r   r   )r%   r  r   rr   r   r  r  r   r   r  r   outputsr   slice_indicesr  r  s                   r'   r7   zNanoChatForCausalLM.forward  s   P ,64:: 	,
)%+')	,
 	,
  118B>SV8W~ot4]kmA}a,?@A;;..:dkkAAAFZZ'FdkkAAAF%4%%ffdooPPD%#33!//))
 	
r(   )	NNNNNNNNr   )r;   r<   r=   _tied_weights_keys_tp_plan_pp_planr$   r   r   r-   r   rw   r   r  r   rz   r   r   r   r7   r>   r?   s   @r'   r  r    s<   *,GH23H_-z:;H  .2.204(,26*.!%26-.D
##d*D
 t+D
 &&-	D

 D
 ((4/D
   4'D
 $;D
 ((4/D
 ell*D
 +,D
 
 D
  D
r(   r  )r   r   r  )r   )r   )@r   collections.abcr   typingr   r-   torch.nnr    r   r   activationsr   cache_utilsr   r	   
generationr
   integrationsr   r   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.genericr   r   r   utils.output_capturingr   configuration_nanochatr   r   r   rA   r   rw   rz   r   r5   r   r   r   r   r   r   r   r  __all__r   r(   r'   <module>r<     s  *  $    & ! . ) I / 9 O K F & 7 Y Y 5 2!ehhoo !><bii ><B *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2( )*J)		 J) +J)Z")) +5 +\ o  6 N
+ N
 N
b T
1? T
 T
n Nr(   