
    gu                       d Z ddlZddlZddlmZmZmZmZ ddl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mZmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(  e#            rddl)m*Z*  e%j+        e,          Z-dZ.dZ/ G d de
j0                  Z1 G d de
j0                  Z2 G d de2          Z3 G d de2          Z4 G d de2          Z5d Z6d=dZ7 G d d e
j0                  Z8d!ej9        d"e:d#ej9        fd$Z; G d% d&e
j0                  Z< G d' d(e<          Z= G d) d*e<          Z>e<e=e>d+Z? G d, d-e
j0                  Z@d.ZA e!d/eA           G d0 d1e                      ZBd2ZC e!d/eA           G d3 d4eB                      ZD G d5 d6eBe          ZE e!d7eA           G d8 d9eB                      ZF e!d:eA           G d; d<eB                      ZGdS )>zPyTorch Phi-3 model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )
Phi3Config)_flash_attention_forwardz microsoft/Phi-3-mini-4k-instructr   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Phi3RMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z:
        Phi3RMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/phi3/modeling_phi3.pyr%   zPhi3RMSNorm.__init__=   sD     	l5:k#:#:;; #    c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )N   T)keepdim)	dtypetor'   float32powmeanrsqrtr*   r)   )r+   hidden_statesinput_dtypevariances       r/   forwardzPhi3RMSNorm.forwardE   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r0   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler)   shaper*   r+   s    r/   
extra_reprzPhi3RMSNorm.extra_reprL   s&    )**II$2GIIIr0   )r"   )__name__
__module____qualname__r%   r>   rC   __classcell__r.   s   @r/   r!   r!   <   sb        $ $ $ $ $ $; ; ;J J J J J J Jr0   r!   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )Phi3RotaryEmbedding   '  Nc                 :   t                                                       || _        || _        || _        d| j        t          j        d| j        dt
          j                                                  | j        z  z  z  }| 	                    d|d           d S )N      ?r   r2   r5   inv_freqF)tensor
persistent)
r$   r%   dimmax_position_embeddingsbaser'   arangeint64floatregister_buffer)r+   rS   rT   rU   devicerP   r.   s         r/   r%   zPhi3RotaryEmbedding.__init__R   s    '>$	$)Q!5;(W(W(W(](](_(_bfbj(jklZUKKKKKr0   c                 "   | j                             |j                   | j         d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                }	|                                }
d d d            n# 1 swxY w Y   |	                    |j        
          |
                    |j        
          fS )Nr   r3   r   mpscpuFdevice_typeenabledr2   rS   rO   )rP   r6   rZ   rX   expandrA   type
isinstancestrr'   autocast	transposecatcossinr5   )r+   xposition_idsseq_leninv_freq_expandedposition_ids_expandedr_   freqsembri   rj   s              r/   r>   zPhi3RotaryEmbedding.forward\   s    	""" M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 vvAGv$$cff17f&;&;;;s   A>EEE)rK   rL   NNrD   rE   rF   r%   r'   no_gradr>   rG   rH   s   @r/   rJ   rJ   Q   sk        L L L L L L U]__< < < _< < < < <r0   rJ   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )Phi3SuScaledRotaryEmbeddingNc                     t          j        dt                     t                                          ||j        |j        |           |j        d         | _        |j        d         | _	        |j
        | _
        d S )NzThe class Phi3SuScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers. Please use Phi3LongRoPEScaledRotaryEmbedding instead.short_factorlong_factorwarningswarnFutureWarningr$   r%   rT   
rope_thetarope_scalingrx   ry    original_max_position_embeddingsr+   rS   configrZ   r.   s       r/   r%   z$Phi3SuScaledRotaryEmbedding.__init__o   sw    >	
 	
 	

 	f<f>OQWXXX"/?!.}=060W---r0   c                 P   t          j        |          dz   }|| j        k    r,t          j        | j        t           j        |j                  }n+t          j        | j        t           j        |j                  }t          j        d| j	        dt           j
        |j                                                  | j	        z  }d|| j        |z  z  z  | _        | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t#          |t$                    r|dk    r|nd}t          j        |d	
          5  |                                |                                z                      dd          }	t          j        |	|	fd          }
| j        | j        z  }|dk    rd}nCt/          j        dt/          j        |          t/          j        | j                  z  z             }|
                                |z  }|
                                |z  }d d d            n# 1 swxY w Y   |                    |j                  |                    |j                  fS Nr   r5   rZ   r   r2   rN   r3   r\   r]   Fr^   ra   rO   r'   maxr   rQ   ry   r7   rZ   rx   rV   rS   rW   rX   rU   rP   rb   rA   rc   rd   re   rf   rg   rh   rT   mathsqrtlogri   rj   r6   r5   r+   rk   rl   rm   ext_factorsinv_freq_shapern   ro   r_   rp   rq   scalescaling_factorri   rj   s                  r/   r>   z#Phi3SuScaledRotaryEmbedding.forward{   s   )L))A-T:::,t'7u}UVU]^^^KK,t'8VWV^___Ka1EKPQPXYYY__aadhdll{TY-FFG M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 		- 		-&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C043XXE||!$!%1tx$JoApAp/p+p!q!q''))n,C''))n,C		- 		- 		- 		- 		- 		- 		- 		- 		- 		- 		- 		- 		- 		- 		- vvAGv$$cff17f&;&;;;s   <CI''I+.I+rr   rs   rH   s   @r/   rv   rv   n   sk        
X 
X 
X 
X 
X 
X U]__< < < _< < < < <r0   rv   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )Phi3YarnScaledRotaryEmbeddingNc                     t          j        dt                     t                                          ||j        |j        |           |j        d         | _        |j        d         | _	        |j
        | _
        d S )NzfThe class Phi3YarnScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformersrx   ry   rz   r   s       r/   r%   z&Phi3YarnScaledRotaryEmbedding.__init__   su    t	
 	
 	
 	f<f>OQWXXX"/?!.}=060W---r0   c                    t          j        |          dz   }|| j        k    r,t          j        | j        t           j        |j                  }n+t          j        | j        t           j        |j                  }t          j        d| j	        dt           j
        |j                                                  | j	        z  }d|| j        |z  z  z  | _        | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t#          |t$                    r|dk    r|nd}t          j        |d	
          5  |                                |                                z                      dd          }	t          j        |	|	fd          }
| j        | j        z  }|dk    rd}ndt/          j        |          z  dz   }|
                                |z  }|
                                |z  }d d d            n# 1 swxY w Y   |                    |j                  |                    |j                  fS )Nr   r   r   r2   rN   r3   r\   r]   Fr^   ra   皙?rO   )r'   r   r   rQ   ry   r7   rZ   rx   rV   rS   rW   rX   rU   rP   rb   rA   rc   rd   re   rf   rg   rh   rT   r   r   ri   rj   r6   r5   r   s                  r/   r>   z%Phi3YarnScaledRotaryEmbedding.forward   s   )L))A-T:::,t'7u}UVU]^^^KK,t'8VWV^___Ka1EKPQPXYYY__aadhdll{TY-FFG M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	- 	-&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C043XXE||!$!$tx!6!<''))n,C''))n,C	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- vvAGv$$cff17f&;&;;;s   <B6H>>IIrr   rs   rH   s   @r/   r   r      sk        	X 	X 	X 	X 	X 	X U]__< < < _< < < < <r0   r   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )!Phi3LongRoPEScaledRotaryEmbeddingNc                     t                                          ||j        |j        |           |j        d         | _        |j        d         | _        |j        | _        d S )Nrx   ry   )r$   r%   rT   r~   r   rx   ry   r   r   s       r/   r%   z*Phi3LongRoPEScaledRotaryEmbedding.__init__   sY    f<f>OQWXXX"/?!.}=060W---r0   c                 T   |pt          j        |          dz   }|| j        k    r,t          j        | j        t           j        |j                  }n+t          j        | j        t           j        |j                  }t          j        d| j	        dt           j
        |j                                                  | j	        z  }d|| j        |z  z  z  | _        | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t#          |t$                    r|dk    r|nd}t          j        |d	
          5  |                                |                                z                      dd          }	t          j        |	|	fd          }
| j        | j        z  }|dk    rd}nCt/          j        dt/          j        |          t/          j        | j                  z  z             }|
                                |z  }|
                                |z  }d d d            n# 1 swxY w Y   |                    |j                  |                    |j                  fS r   r   r   s                  r/   r>   z)Phi3LongRoPEScaledRotaryEmbedding.forward   s   8UY|44q8T:::,t'7u}UVU]^^^KK,t'8VWV^___Ka1EKPQPXYYY__aadhdll{TY-FFG M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	- 	-&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C043XXE||!$!%1tx$JoApAp/p+p!q!q''))n,C''))n,C	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- vvAGv$$cff17f&;&;;;s   >CI))I-0I-rr   rs   rH   s   @r/   r   r      sk        X X X X X X U]__< < < _< < < < <r0   r   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..Nr3   r2   ra   )rA   r'   rh   )rk   x1x2s      r/   rotate_halfr      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r0   c                     |                     |          }|                     |          }| |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.
        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.
    )	unsqueezer   )qkri   rj   rl   unsqueeze_dimq_embedk_embeds           r/   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr0   c                   B     e Zd Z fdZdej        dej        fdZ xZS )Phi3MLPc                 "   t                                                       || _        t          j        |j        d|j        z  d          | _        t          j        |j        |j        d          | _        t          |j
                 | _        d S )Nr2   Fbias)r$   r%   r   r   Linearr,   intermediate_sizegate_up_proj	down_projr
   
hidden_actactivation_fnr+   r   r.   s     r/   r%   zPhi3MLP.__init__  sz    If&8!f>V:V]bccc6#;V=OV[\\\#F$56r0   r;   returnc                     |                      |          }|                    dd          \  }}||                     |          z  }|                     |          S )Nr2   r3   ra   )r   chunkr   r   )r+   r;   	up_statesgates       r/   r>   zPhi3MLP.forward  sX    %%m44	#//!/44i 2 24 8 88	~~i(((r0   )rD   rE   rF   r%   r'   FloatTensorr>   rG   rH   s   @r/   r   r     s`        7 7 7 7 7)U%6 )5;L ) ) ) ) ) ) ) )r0   r   r;   n_repr   c                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||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)rA   rb   reshape)r;   r   batchnum_key_value_headsslenhead_dims         r/   	repeat_kvr   %  s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr0   c                   "    e Zd ZdZddedee         f fdZd Z	 	 	 	 	 	 dde	j
        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 )Phi3Attentionz=Multi-headed attention from 'Attention Is All You Need' paperNr   	layer_idxc                 P   t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _	        |j
        | _        | j	        | j        z  | _        |j        | _        | j        | j        z  | _        |j        | _        |j        | _        |j        | _        |j        | _        d| _        | j        | j        z  | j	        k    r t)          d| j	         d| j         d          | j        | j        z  d| j        | j        z  z  z   }t+          j        | j        | j        z  | j	        d	          | _        t+          j        | j	        |d	          | _        |                                  d S )
NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r2   Fr   )r$   r%   r   r   loggerwarning_oncer.   rD   attention_dropoutr,   num_attention_heads	num_headsr   r   num_key_value_groupsrT   r   r~   r   	is_causal
ValueErrorr   r   o_projqkv_proj
_init_rope)r+   r   r   op_sizer.   s       r/   r%   zPhi3Attention.__init__4  s   ",!8 , , ,   "(!9!-3(DN:#)#= $(Nd6N$N!'-'E$060W- +"/MDN*t/???8RVRb 8 8%)^8 8 8  
 .4=018PSWS`8`3aai >@PW\]]]	$"2G%HHHr0   c                     | j         (t          | j        | j        | j                  | _        d S | j        j         d         }|dk    r!t          | j        | j                  | _        d S t          d|           )N)rT   rU   rc   longropezUnknown RoPE scaling type )	r   rJ   r   rT   r~   
rotary_embr   r   r   )r+   scaling_types     r/   r   zPhi3Attention._init_ropeV  s    $1(,(D_  DOOO  ;3F;Lz))"CDMSWS^"_"_ !Ll!L!LMMMr0   Fr;   attention_maskrl   past_key_valueoutput_attentions	use_cachecache_positionr   c                 x   t                               d           |                                \  }}	}
|                     |          }| j        | j        z  }|dd |f         }|d||| j        | j        z  z   f         }|d|| j        | j        z  z   d f         }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|j	        d         }|B| j
        t          d| j        j         d          ||                    || j
                  z  }|                     |||          \  }}t!          |||||          \  }}|&|||d	}|                    ||| j
        |          \  }}t%          || j                  }t%          || j                  }t)          j        ||                    dd
                    t-          j        | j                  z  }|$|d d d d d d d |j	        d         f         }||z  }t0          j                            |dt(          j                                      |j                  }t0          j                            || j        | j                   }t)          j        ||          }|                                || j        |	| j        fk    r5t          d|| j        |	| j        f d|                                           |                    dd          !                                }|"                    ||	| j#                  }| $                    |          }|sd }|||fS )NzUYou are not running the flash-attention implementation, expect numerical differences..r   r2   FThe cache structure has changed since version v4.36. If you are using v for auto-regressive decoding with k/v caching, please make sure to initialize the attention class with a layer index.rm   rj   ri   r   r	   r3   )rS   r5   )ptrainingz `attn_output` should be of size z	, but is )%r   r   sizer   r   r   r   viewrg   rA   r   r   r.   rD   get_usable_lengthr   r   updater   r   r'   matmulr   r   r   
functionalsoftmaxr7   r6   r5   dropoutr   r   
contiguousr   r,   r   )r+   r;   r   rl   r   r   r   r   bszq_len_qkv	query_posquery_states
key_statesvalue_states
kv_seq_lenri   rj   cache_kwargsattn_weightscausal_maskattn_outputs                          r/   r>   zPhi3Attention.forwardd  s    	sttt%**,,UAmmM**NT]2	3

?+i)d6NQUQ^6^*^^^_
3	D,Dt},T T V VVW#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%b)
%~% *]a]k]t * * *  
 .:::t~VVVJ??<z?RRS#7jRUWZ\h#i#i j%#&snUUL'5'<'<ZW[Wegs't't$J z4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIKK'L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!))#ud6FGGkk+..  	 LL.88r0   rr   NNNFFN)rD   rE   rF   __doc__r   r   intr%   r   r'   Tensor
LongTensorr   boolr   r>   rG   rH   s   @r/   r   r   1  s7       GG   z  hsm            DN N N" 2637*."'59G9 G9|G9 !.G9 u/0	G9
 !G9  G9 G9 !!12G9 
u|Xel3XeEL>Q5RR	SG9 G9 G9 G9 G9 G9 G9 G9r0   r   c                       e Zd ZdZ fdZ	 	 	 	 	 	 ddej        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 )Phi3FlashAttention2aE  
    Phi-3 flash attention module. This module inherits from `Phi3Attention` 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                      j        |i | t                       | _        d S rr   )r$   r%   r   _flash_attn_uses_top_left_mask)r+   argskwargsr.   s      r/   r%   zPhi3FlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r0   NFr;   r   rl   r   r   r   r   r   c                    d}|                                 \  }}	}
|                     |          }| j        | j        z  }|dd |f         }|d||| j        | j        z  z   f         }|d|| j        | j        z  z   d f         }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|j        d         }|B| j        t          d| j
        j         d          ||                    || j                  z  }|At          ||d d df                                                                         dz             n|}|                     |||	          \  }}t!          |||||          \  }}|&|||d
}|                    ||| j        |          \  }}t%          || j                  }t%          || j                  }| j        r| j        nd}|j        t.          j        k    rt/          j                    rt/          j                    }n3t7          | j        d          r| j        j        }n| j        j        j        }t>                               d| d           |!                    |          }|!                    |          }|!                    |          }|                    dd          }|                    dd          }|                    dd          }tE          |||||	||tG          | j        dd           | j$        | j%        
  
        }|&                    ||	| j'                  (                                }| )                    |          }|sd }|||fS )NF.r   r2   r   r   r   r3   )rm   rl   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)rl   r   r  use_top_left_maskr   )*r   r   r   r   r   r   rg   rA   r   r   r.   rD   r   r   itemr   r   r   r   r   r   r   r5   r'   r7   is_autocast_enabledget_autocast_gpu_dtypehasattrr   r  r)   r   r   r6   r   getattrr   r   r   r,   r   r   )r+   r;   r   rl   r   r   r   r   r   r   r   r   r   r   r   r   r   rotary_seq_lenri   rj   r   attn_dropouttarget_dtyper   r   s                            r/   r>   zPhi3FlashAttention2.forward  s)    "%**,,UAmmM**NT]2	3

?+i)d6NQUQ^6^*^^^_
3	D,Dt},T T V VVW
 $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%b)
%~% *]a]k]t * * *  
 .:::t~VVVJ FRE]C
LB/3355::<<q@AAAcm 	 ??<Vb?ccS#7jRUWZ\h#i#i j%#&snUUL'5'<'<ZW[Wegs't't$J z4+DEE
 t/HII15Gt--C ..(** :$;==&?@@ :#{B#}39$ $ $ $   (??<88L#|44J'??<88L $--a33))!Q//
#--a33.% "4;0@$GG"An
 
 
 "))#ud6FGGRRTTkk+..  	 LL.88r0   r   )rD   rE   rF   r   r%   r'   r   r   r   r   r   r   r>   rG   rH   s   @r/   r   r     s        X X X X X 6:37*."'59k9 k9|k9 !!12k9 u/0	k9
 !k9  k9 k9 !!12k9 
u|Xel3XeEL>Q5RR	Sk9 k9 k9 k9 k9 k9 k9 k9r0   r   c                        e Zd ZdZ	 	 	 	 	 	 ddej        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 )Phi3SdpaAttentionz
    Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr;   r   rl   r   r   r   r   r   c                 T   |rAt                               d           t                                          ||||||          S |                                \  }}	}
|                     |          }| j        | j        z  }|dd |f         }|d||| j        | j        z  z   f         }|d|| j        | j        z  z   d f         }|	                    ||	| j        | j                  
                    dd          }|	                    ||	| j        | j                  
                    dd          }|	                    ||	| j        | j                  
                    dd          }|j        d         }|||                    || j                  z  }|                     |||          \  }}t          |||||          \  }}|&|||d}|                    ||| j        |          \  }}t#          || j                  }t#          || j                  }|}||d d d d d d d |j        d         f         }|j        j        d	k    r>|<|                                }|                                }|                                }||	dk    rd
nd}t,          j        j                            ||||| j        r| j        nd|          }|
                    dd                                          }|	                    ||	| j                  }|                     |          }|d |fS )Na  Phi3Model is using Phi3SdpaAttention, 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   rl   r   r   r   .r   r2   r   r   r   cudaTFr  )	attn_mask	dropout_pr   )r   r   r$   r>   r   r   r   r   r   r   rg   rA   r   r   r   r   r   r   r   rZ   rc   r   r'   r   r   scaled_dot_product_attentionr   r   r,   r   )r+   r;   r   rl   r   r   r   r   r   r   r   r   r   r   r   r   r   ri   rj   r   r   r   r   r.   s                          r/   r>   zPhi3SdpaAttention.forward6  sx     	[   77??+-)-"3# #    &**,,UAmmM**NT]2	3

?+i)d6NQUQ^6^*^^^_
3	D,Dt},T T V VVW#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%b)
%.:::t~VVVJ??<z?RRS#7jRUWZ\h#i#i j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%(AAAqqq2HJ4DR4H2H)HIK #v--.2L'2244L#..00J'2244L
 (/EAIIDD5	h)FF!04Fd,,3 G 
 
 "++Aq11<<>>!&&sE43CDDkk+..D.00r0   r   )rD   rE   rF   r   r'   r   r   r   r   r   r   r>   rG   rH   s   @r/   r  r  .  s          2637*."'59Q1 Q1|Q1 !.Q1 u/0	Q1
 !Q1  Q1 Q1 !!12Q1 
u|Xel3XeEL>Q5RR	SQ1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1r0   r  )eagerflash_attention_2sdpac                   .    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
ej                          d
ee         dee         deej	                 de
ej        ee
ej        ej        f                  f         fdZ xZS )Phi3DecoderLayerr   r   c                    t                                                       || _        t          |j                 ||          | _        t          |          | _        t          |j	        |j
                  | _        t          j        |j                  | _        t          j        |j                  | _        t          |j	        |j
                  | _        d S )N)r   r-   )r$   r%   r   PHI3_ATTENTION_CLASSES_attn_implementation	self_attnr   mlpr!   r,   rms_norm_epsinput_layernormr   Dropoutresid_pdropresid_attn_dropoutresid_mlp_dropoutpost_attention_layernorm)r+   r   r   r.   s      r/   r%   zPhi3DecoderLayer.__init__  s    /0KLV_hiii6??*6+=6CVWWW"$*V-?"@"@!#F,>!?!?(3F4FFL_(`(`(`%%%r0   NFr;   r   rl   r   r   r   r   r   c           	      R   |}	|                      |          }|                     |||||||          \  }
}}|	|                     |
          z   }|}	|                     |          }|                     |          }|	|                     |          z   }|f}|r||fz  }|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, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
                Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
                `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
            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
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        )r;   r   rl   r   r   r   r   )r#  r   r&  r(  r!  r'  )r+   r;   r   rl   r   r   r   r   r  residualattn_outputsself_attn_weightspresent_key_valueoutputss                 r/   r>   zPhi3DecoderLayer.forward  s    D !,,];; >B^^')%)/) >L >
 >
:'): !4#:#:<#H#HH 55mDD// 4#9#9-#H#HH " 	,)++G 	,)++Gr0   r   )rD   rE   rF   r   r   r%   r'   r   r   r   r   r   r   r>   rG   rH   s   @r/   r  r    s.       az ac a a a a a a  26378<,1$)59@ @|@ !.@ u/0	@
 !u|!45@ $D>@ D>@ !!12@ 
u (51BEDU1U+V"WW	X@ @ @ @ @ @ @ @r0   r  aI  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`Phi3Config`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zSThe bare Phi-3 model outputting raw hidden-states without any specific head on top.c                   :    e Zd ZeZdZdZdgZdZdZ	dZ
dZdZd ZdS )Phi3PreTrainedModelmodelTr  past_key_valuesz0.0.5c                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr  )r9   std)r   initializer_rangerd   r   r   r)   datanormal_r   zero_	Embeddingpadding_idx)r+   moduler4  s      r/   _init_weightsz!Phi3PreTrainedModel._init_weights  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r0   N)rD   rE   rF   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_versionr<   r0   r/   r0  r0    s[        
 L&*#+,"3!N H	? 	? 	? 	? 	?r0   r0  a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        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`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                       e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 dde
j        dee
j                 d	ee
j                 d
eee
j                          dee
j                 dee         dee         dee         dee         dee
j                 deeef         fd            Zde
j        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
j        deded
efd            Z xZS )	Phi3Modelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]

    Args:
        config: Phi3Config
    r   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        j
                  | _        t          j        fdt          j                  D                       | _        j        | _        t#          j        j                  | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S rF  )r  ).0r   r   s     r/   
<listcomp>z&Phi3Model.__init__.<locals>.<listcomp>n  s$    bbbYfi00bbbr0   r  F)r$   r%   pad_token_idr:  
vocab_sizer   r9  r,   embed_tokensr$  
embd_pdropembed_dropout
ModuleListrangenum_hidden_layerslayersr  r!   r"  normgradient_checkpointing	post_initr   s    `r/   r%   zPhi3Model.__init__f  s       !. +L):F<NPTP`aaZ(9::mbbbb%H`BaBabbb
 
 %+$?! 28KLLL	&+#r0   c                     | j         S rr   rO  rB   s    r/   get_input_embeddingszPhi3Model.get_input_embeddingsw  s      r0   c                     || _         d S rr   rZ  r+   values     r/   set_input_embeddingszPhi3Model.set_input_embeddingsz  s    !r0   N	input_idsr   rl   r2  inputs_embedsr   r   output_hidden_statesreturn_dictr   r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|	|	n| j         j        }	|d u |d uz  rt          d          | j        r%| j        r|rt          	                    d           d}d}|rVt          |t                    sAd}|t                      }n.t          j        |          }t          	                    d           ||                     |          }|
B||                                nd}t!          j        |||j        d         z   |j                  }
||
                    d          }|                     |||
||          }|}|rd	nd }|rd	nd }d }| j        D ]p}|r||fz  }| j        r)| j        r"|                     |j        |||||||
          }n ||||||||

          }|d         }|r||rdnd         }|r||d         fz  }q|                     |          }|r||fz  }|r|nd }|r|                                }|	st7          d ||||fD                       S t9          ||||          S )Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   rZ   rF  )r   rl   r   r   r   r   r2   c              3      K   | ]}||V  	d S rr   rF  )rK  vs     r/   	<genexpr>z$Phi3Model.forward.<locals>.<genexpr>  s(      ttqfgfsfsfsfsfsttr0   )last_hidden_stater2  r;   
attentions)r   r   rb  r   use_return_dictr   rW  r   r   r   rd   r   r   from_legacy_cacherO  get_seq_lengthr'   rV   rA   rZ   r   _update_causal_maskrU  _gradient_checkpointing_func__call__rV  to_legacy_cacher@   r   )r+   r`  r   rl   r2  ra  r   r   rb  rc  r   return_legacy_cachepast_seen_tokensr   r;   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                        r/   r>   zPhi3Model.forward}  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	"4= 	" "##p   "	 $ 
	Z?? 
	"&&"..."."@"Q"Q##^     --i88M!CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 
 & #7@BBD0:d!![  	6  	6M# 6!m%55!* t}  $ A A!*! #%"	! 	! !.!#.!-#2&7'#1! ! ! *!,M R%28I3P11q%Q"  6=#3"55		-00   	2-!11+4>''$
 	6#3355J 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r0   input_tensorc                    | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }t          |t
                    }| j         j        dk    r0|s.|s,|s*t          j        |||| j         j        | j	                  rd S |j
        |j        }
}	t          j        |	          j        }|j        d         }|s|r|                                }n/t          |t          j                  r|j        d         n||z   dz   }|                     ||||	|
||j        d         | j         |	  	        }| j         j        dk    r)|'|j        j        d	k    r|st          j        ||          }|S )
Nr  r  r   r  )ra  past_key_values_lengthr  is_trainingr   r3   )sequence_lengthtarget_lengthr5   rZ   r   
batch_sizer   r2  r  )r   r  rm  rd   r   r   r   _ignore_causal_mask_sdpar  r   r5   rZ   r'   finfominrA   get_max_cache_shaper   5_prepare_4d_causal_attention_mask_with_cache_positionrc   _unmask_unattended)r+   r   rz  r   r2  r   rs  using_static_cacheusing_sliding_window_cacher5   rZ   	min_dtyper~  r  r   s                  r/   rn  zPhi3Model._update_causal_mask  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE%/AS%T%T" K,66' 7+E 7% 7 &>*'7#{9 M    t$*L,?vK&&*	&,Q/% 	); 	+??AAMM
 nel;;<$R((%7!;  PP+')#)!,;+ Q 

 

 K,66*%*f44% 5 1CKQZ[[Kr0   r~  r  r5   rZ   r  c	                 \   | |                                  dk    r| }	nt          j        |          j        }
t          j        ||f|
||          }	t          j        ||          |                    dd          k    }|j        Vt          |t                    r||k    r;t          j        ||          |                    dd          |j        z
  k    }||z  }|	|z  }	|	ddddddf         
                    |ddd          }	| |	                                }	| j        d         |k    r| ddd|f         } | j        d         }|	ddddddd|f         | ddddddf         z   }|dk    }|	ddddddd|f                             ||
          |	ddddddd|f<   |	S )aS  
        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.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
            config (`Phi3Config`):
                The model's configuration class
            past_key_values (`Cache`):
                The cache class that is being used currently to generate
        N   )
fill_valuer5   rZ   re  r3   r   r   )rS   r'   r  r  fullrV   r   r  rd   r   rb   clonerA   masked_fill)r   r~  r  r5   rZ   r   r  r   r2  r   r  diagonal_attend_masksliding_attend_maskmask_lengthpadding_masks                  r/   r  z?Phi3Model._prepare_4d_causal_attention_mask_with_cache_positionA  s2   J %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K $)<f#M#M#MP^PfPfgiklPmPm#m $0 "/3EFF @/\iJiJi*/,}V*T*T*T&..r1558MM+' ),??(//K%dD!!!QQQ&67>>z1bRTUUK))//11!'+m;;%3AAA~~4E%FN,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r0   
NNNNNNNNNN)rD   rE   rF   r   r   r%   r[  r_  r   PHI3_INPUTS_DOCSTRINGr'   r   r   r   r   r   r   r   r   r   r>   r   rn  staticmethodr   r5   rZ   r  rG   rH   s   @r/   rH  rH  Z  si       
 z      "! ! !" " " +*+@AA '+1537=A59$(,0/3&*59v
 v
#v
 !.v
 u/0	v

 "$u'8"9:v
   12v
 D>v
 $D>v
 'tnv
 d^v
 !!12v
 
u--	.v
 v
 v
 BAv
pII lI 	I
 I  I I I IV @@@ @ {	@
 @ @ @ @ @ @ @ \@ @ @ @ @r0   rH  c                       e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 ee           eee	          	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deeej                          deej                 deej                 dee         dee         dee         dee         deej                 dedeeef         fd                        Z	 	 	 	 	 	 	 d fd	Z xZS )Phi3ForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S NFr   )
r$   r%   rH  r1  rN  r   r   r,   lm_headrX  r   s     r/   r%   zPhi3ForCausalLM.__init__  sj       v&&
 +y!3V5FUSSS 	r0   c                     | j         j        S rr   r1  rO  rB   s    r/   r[  z$Phi3ForCausalLM.get_input_embeddings      z&&r0   c                     || j         _        d S rr   r  r]  s     r/   r_  z$Phi3ForCausalLM.set_input_embeddings      "'
r0   c                     | j         S rr   r  rB   s    r/   get_output_embeddingsz%Phi3ForCausalLM.get_output_embeddings  s
    |r0   c                     || _         d S rr   r  )r+   new_embeddingss     r/   set_output_embeddingsz%Phi3ForCausalLM.set_output_embeddings  s    %r0   c                     || _         d S rr   r1  )r+   decoders     r/   set_decoderzPhi3ForCausalLM.set_decoder  s    


r0   c                     | j         S rr   r  rB   s    r/   get_decoderzPhi3ForCausalLM.get_decoder  s
    zr0   )output_typer=  Nr   r`  r   rl   r2  ra  labelsr   r   rb  rc  r   num_logits_to_keepr   c                 @   |rL| j         j        r@|>|d         | j         j        k    r(t                              d| j         j         d           ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }| 	                    |dd| dddf                   }d}| | j
        ||| j        fi |}|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j                  S )aa  
        Args:
            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]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

        Returns:

        Example:

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

        >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")

        >>> prompt = "This is an example script ."
        >>> 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]
        'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
        ```Nr   zZIf you are not using the generate method, you may encounter nonsensical outputs after the z1th token, as the KV cache needs to be recomputed.)	r`  r   rl   r2  ra  r   r   rb  rc  r   losslogitsr2  r;   rj  )r   r   r   r   warningr   rb  rk  r1  r  loss_functionrN  r   r2  r;   rj  )r+   r`  r   rl   r2  ra  r  r   r   rb  rc  r   r  loss_kwargsr.  r;   r  r  outputs                      r/   r>   zPhi3ForCausalLM.forward  s   b 	(	 *q!T[%QQQNN Mmqmx  nZ  M  M  M   2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **)%+'/!5#  

 

  
mAAA0B/B/C/CQQQ,FGHH%4%ffdoUUUUD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r0   Tc	                     |rD| j         j        r8|j        d         | j         j        dz   k    r|d         }
|
| j         j        k    rd } t	                      j        d||||||||d|	}|S )Nr   r   )r`  r2  r   ra  r   rl   r   r  rF  )r   r   rA   r   r$   prepare_inputs_for_generation)r+   r`  r2  r   ra  r   rl   r   r  r  past_lengthmodel_inputsr.   s               r/   r  z-Phi3ForCausalLM.prepare_inputs_for_generation  s    $ 	'(	' "dk&RUV&VVV(+KdkJJJ"&<uww< 

+)')%1

 

 

 

 r0   )NNNNNNNNNNNr   )NNNNNTN)rD   rE   rF   _tied_weights_keysr%   r[  r_  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr'   r   r   r   r   r   r   r   r   r   r>   r  rG   rH   s   @r/   r  r    s,       *+    ' ' '( ( (  & & &     +*+@AA+AP_``` '+1537=A59-1$(,0/3&*59"#]
 ]
#]
 !.]
 u/0	]

 "$u'8"9:]
   12]
 )*]
 D>]
 $D>]
 'tn]
 d^]
 !!12]
  ]
 
u,,	-]
 ]
 ]
 a` BA]
D % % % % % % % % % %r0   r  a  
    The [`Phi3Model`] with a sequence classification head on top (linear layer).

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

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                   v    e Zd 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         deeef         fd            Z xZS )Phi3ForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S r  )
r$   r%   
num_labelsrH  r1  r   r   r,   scorerX  r   s     r/   r%   z&Phi3ForSequenceClassification.__init__F  si        +v&&
Yv14?OOO
 	r0   c                     | j         j        S rr   r  rB   s    r/   r[  z2Phi3ForSequenceClassification.get_input_embeddingsO  r  r0   c                     || j         _        d S rr   r  r]  s     r/   r_  z2Phi3ForSequenceClassification.set_input_embeddingsR  r  r0   Nr`  r   rl   r2  ra  r  r   r   rb  rc  r   c                 "   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}nv|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }nd}|t          j        ||j                  |f         }d}||                     |||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          S )
  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N)r   rl   r2  ra  r   r   rb  rc  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r3   re  )r  r  pooled_logitsr   r  )r   rk  r1  r  rA   rM  r   r'   eqr   argmaxr6   rZ   rV   r  r   r2  r;   rj  )r+   r`  r   rl   r2  ra  r  r   r   rb  rc  model_outputsr;   r  r  sequence_lengthsr  r  r  s                      r/   r>   z%Phi3ForSequenceClassification.forwardU  s   ( &1%<kk$+B]

)%+'/!5# # 

 

 &a(M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% u|Jv}MMMO__`%%VFR_hlhs%ttD 	F#%abb(99F)-)9TGf$$vE/ )9'5$/
 
 
 	
r0   r  )rD   rE   rF   r%   r[  r_  r   r  r   r'   r   r   r   r   r   r   r   r   r   r>   rG   rH   s   @r/   r  r  5  s       "    ' ' '( ( ( +*+@AA 151537KO59-1$(,0/3&*E
 E
E,-E
 !.E
 u/0	E

 "%tE4E/F(F"GHE
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 E
 E
 BAE
 E
 E
 E
 E
r0   r  z
    [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       e Zd Zdef fdZ ee           eee	e
          	 	 	 	 	 	 	 	 	 ddeej                 deeeej        ej        f         df                  deej                 d	eej                 d
eej                 dee         dee         dee         dee         deeej                 e	f         fd                        Z xZS )Phi3ForTokenClassificationr   c                    t                                          |           |j        | _        t          |          | _        t          |d          r|j        |j        }n!t          |d          r|j        |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropouthidden_dropoutr   )r$   r%   r  rH  r1  r  r  r  r   r$  r   r   r,   
classifierrX  )r+   r   r  r.   s      r/   r%   z#Phi3ForTokenClassification.__init__  s        +v&&
6/00 	%V5N5Z!'!:V-.. 	%63H3T!'!6!$z"455)F$68IJJ 	r0   )
checkpointr  r=  Nr`  r2  .r   ra  r  r   r   rb  rc  r   c
           
         |	|	n| j         j        }	|                     ||||||||	          }|d         }|                     |          }|                     |          }d}|p|                    |j                  }|j        \  }}t                      } ||	                    ||z  | j
                  |	                    ||z                      }|	s|f|dd         z   }||f|z   n|S t          |||j        |j                  S )r  N)r2  r   ra  r   r   rb  rc  r   r2   )r  r  r;   rj  )r   rk  r1  r   r  r6   rZ   rA   r   r   r  r   r;   rj  )r+   r`  r2  r   ra  r  r   r   rb  rc  deprecated_argumentsr  r;   r  r  r  
seq_lengthloss_fctr  s                      r/   r>   z"Phi3ForTokenClassification.forward  sH   2 &1%<kk$+B]

+)'/!5# # 	
 	
 &a(]33//YYv}--F%+\"J
'))H8J3T_EEv{{S]`jSjGkGk D  	FYqrr!22F)-)9TGf$$vE$'5$/	
 
 
 	
r0   )	NNNNNNNNN)rD   rE   rF   r   r%   r   r  r   _CHECKPOINT_FOR_DOCr   r  r   r'   r   r   r   r   r   r>   rG   rH   s   @r/   r  r    sz       z      " +*+@AA&)$   15SW1504)-$(,0/3&*7
 7
E,-7
 "%elEL.H(I3(N"OP7
 !.	7

  -7
 &7
 D>7
 $D>7
 'tn7
 d^7
 
uU\"$99	:7
 7
 7
  BA7
 7
 7
 7
 7
r0   r  )Nr   )Hr   r   r{   typingr   r   r   r   r'   torch.utils.checkpointr   torch.nnr   activationsr
   cache_utilsr   r   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r   configuration_phi3r   modeling_flash_attention_utilsr   
get_loggerrD   r   r  r  Moduler!   rJ   rv   r   r   r   r   r   r   r   r   r   r   r  r  r  PHI3_START_DOCSTRINGr0  r  rH  r  r  r  rF  r0   r/   <module>r     s        / / / / / / / / / / / /            % % % % % % ! ! ! ! ! ! O O O O O O O O O O O O ) ) ) ) ) ) > > > > > >            . - - - - -                  + * * * * *  KJJJJJJ		H	%	%8 J J J J J") J J J*< < < < <") < < <:&< &< &< &< &<"5 &< &< &<R*< *< *< *< *<$7 *< *< *<Z&< &< &< &< &<(; &< &< &<T( ( (   6) ) ) ) )bi ) ) )(	UU\ 	U# 	U%, 	U 	U 	U 	Uz9 z9 z9 z9 z9BI z9 z9 z9z{9 {9 {9 {9 {9- {9 {9 {9@Y1 Y1 Y1 Y1 Y1 Y1 Y1 Y1z ,  N N N N Nry N N Nb " Y ? ? ? ? ?/ ? ?	 ?0H V Y e e e e e# e e	 eP	l l l l l)? l l l^    V
 V
 V
 V
 V
$7 V
 V
!  V
r   O
 O
 O
 O
 O
!4 O
 O
 O
 O
 O
r0   