
    g                       d 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mZmZ ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZ ddlmZ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'm(Z(m)Z)m*Z* ddl+m,Z,  e'            rddl-m.Z.  e)j/        e0          Z1dZ2dZ3 G d de	j4                  Z5 G d de	j4                  Z6d Z7d;dZ8 G d de	j4                  Z9dej:        de;dej:        fdZ< G d  d!e	j4                  Z= G d" d#e=          Z> G d$ d%e=          Z?e=e>e?d&Z@ G d' d(e	j4                  ZAd)ZB e%d*eB           G d+ d,e"                      ZCd-ZD e%d*eB           G d. d/eC                      ZE G d0 d1eCe          ZF e%d2eB           G d3 d4eC                      ZG e%d5eB           G d6 d7eC                      ZH e%d8eB           G d9 d:eC                      ZIdS )<zPyTorch Qwen2 model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONS)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   )Qwen2Config)_flash_attention_forwardzQwen/Qwen2-7Br"   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Qwen2RMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z;
        Qwen2RMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      d/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/qwen2/modeling_qwen2.pyr)   zQwen2RMSNorm.__init__D   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       r3   forwardzQwen2RMSNorm.forwardL   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r4   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler-   shaper.   r/   s    r3   
extra_reprzQwen2RMSNorm.extra_reprS   s&    )**II$2GIIIr4   )r&   )__name__
__module____qualname__r)   rB   rG   __classcell__r2   s   @r3   r%   r%   C   sb        $ $ $ $ $ $; ; ;J J J J J J Jr4   r%   c                   v     e Zd Z	 	 	 	 	 	 	 d
dee         f fdZd Z ej                    d	             Z	 xZ
S )Qwen2RotaryEmbeddingN   '        ?defaultconfigc                 X   t                                                       i | _        |=t                              d           |||||d| _        || _        || _        || _        n_|j        9|j        	                    d|j        	                    d                    | _        nd| _        |j
        | _        |j
        | _        || _        t          | j                 | _         | j        | j        |fi | j        \  }| _        |                     d|d           | j        | _        d S )	Nz`Qwen2RotaryEmbedding` can now be fully parameterized by passing the model config through the `config` argument. All other arguments will be removed in v4.46)	rope_typefactordimbasemax_position_embeddingsrU   typerR   inv_freqF
persistent)r(   r)   rope_kwargsloggerwarning_oncerU   max_seq_len_cachedoriginal_max_seq_lenrope_scalinggetrY   rS   r   rope_init_fnattention_scalingregister_bufferr[   original_inv_freq)
r/   rW   rY   rX   devicescaling_factorrU   rS   r[   r2   s
            r3   r)   zQwen2RotaryEmbedding.__init__Y   sC    	>R  
 '(+B   D 'DN&=D#(?D%% ".!'!4!8!8fFYF]F]^dFeFe!f!f!*&,&DD#(.(FD%/?+<4+<T[&+e+eTXTd+e+e($(ZeDDD!%r4   c                 ^   t          j        |          dz   }|| j        k    rB | j        | j        |fd|i| j        \  }| _        |                     d|d           || _        || j        k     r;| j        | j        k    r-|                     d| j	        d           | j        | _        dS dS dS )a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r!   seq_lenr[   Fr\   N)
r+   maxra   re   rS   r^   rf   rg   rb   rh   )r/   position_idsri   rl   r[   s        r3   _dynamic_frequency_updatez.Qwen2RotaryEmbedding._dynamic_frequency_update   s     )L))A-T,,,/@t/@V0 0-408<8H0 0,Hd,   X% HHH&-D#T...43JTMf3f3f  T-CPU VVV&*&?D### /.3f3fr4   c                 V   d| j         v r|                     ||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        z  }|	| j        z  }	|                    |j                  |	                    |j                  fS )Ndynamicri   r   r7   r!   mpscpuF)device_typeenabledr6   rW   )r9   )rU   ro   ri   r[   floatexpandrE   rZ   
isinstancestrr+   autocast	transposecatcossinrf   r:   r9   )
r/   xrn   inv_freq_expandedposition_ids_expandedru   freqsembr   r   s
             r3   rB   zQwen2RotaryEmbedding.forward   s   &&**<*III !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		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 D**D**vvAGv$$cff17f&;&;;;s   A>EEE)NrO   rP   NrQ   rR   N)rH   rI   rJ   r   r"   r)   ro   r+   no_gradrB   rK   rL   s   @r3   rN   rN   X   s          $(,*/ */ %*/ */ */ */ */ */X@ @ @$ U]__< < _< < < < <r4   rN   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..Nr7   r6   rw   )rE   r+   r~   )r   x1x2s      r3   rotate_halfr      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r4   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kr   r   rn   unsqueeze_dimq_embedk_embeds           r3   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr4   c                   $     e Zd Z fdZd Z xZS )Qwen2MLPc                    t                                                       |j        | _        |j        | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t          |j
                 | _        d S NFbias)r(   r)   r0   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnr/   rS   r2   s     r3   r)   zQwen2MLP.__init__   s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV./r4   c                     |                      |                     |                     |                    |                     |          z            S N)r   r   r   r   )r/   hidden_states     r3   rB   zQwen2MLP.forward   s>    ~~dkk$..*F*FGG$,,WcJdJddeeer4   )rH   rI   rJ   r)   rB   rK   rL   s   @r3   r   r      sN        0 0 0 0 0f f f f f f fr4   r   r?   n_repreturnc                     | 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)rE   ry   reshape)r?   r   batchnum_key_value_headsslenhead_dims         r3   	repeat_kvr      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr4   c                   R    e Zd ZdZddedee         f 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ej	        ej	        f                  deej	        eej	                 eeej	                          f         fdZ xZS )Qwen2Attentionz
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".
    NrS   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _
        | j        | j
        z  | _        |j        | _        | j
        | j        z  | _        |j        | _        |j        | _        d| _        |j        | _        | j        | j
        z  | j        k    r t%          d| j         d| j
         d          t'          j        | j        | j
        | j        z  d          | _        t'          j        | j        | j        | j        z  d          | _        t'          j        | j        | j        | j        z  d          | _        t'          j        | j
        | j        z  | j        d          | _        t3          | j        	          | _        d S )
NzInstantiating z without passing `layer_idx` is not recommended and will 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).r   FrS   )r(   r)   rS   r   r_   r`   r2   rH   r0   num_attention_heads	num_headsr   r   num_key_value_groupsrY   
rope_theta	is_causalattention_dropout
ValueErrorr   r   q_projk_projv_projo_projrN   
rotary_embr/   rS   r   r2   s      r3   r)   zQwen2Attention.__init__   s   ",!8 , , ,   "-3(DN:#)#= $(Nd6N$N!'-'E$ +!'!9MDN*t/???8RVRb 8 8%)^8 8 8   i 0$.4=2PW[\\\i 0$2JT]2Zaefffi 0$2JT]2Zaefffi >@PW\]]].dkBBBr4   Fr?   attention_maskrn   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr   c	                    |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|4t          
                    d           |                     ||          \  }}n|\  }}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   }t,          j                            |dt"          j                                      |j                  }t,          j                            || j        | j        	          }t#          j        ||          }|                                 |	| j        |
| j        fk    r5t?          d
|	| j        |
| j        f d|                                            |                    dd                                           }|!                    |	|
| j"                  }| #                    |          }|sd }|||fS )Nr!   r6   Y  The attention layers in this model are transitioning from computing the RoPE embeddings internally through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed `position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be removed and `position_embeddings` will be mandatory.r   r   r   r   r7   )rW   r9   )ptrainingz `attn_output` should be of size z	, but is )$sizer   r   r   viewr   r   r}   r   r_   r`   r   r   updater   r   r   r+   matmulmathsqrtrE   r   
functionalsoftmaxr;   r:   r9   dropoutr   r   r   
contiguousr   r0   r   )r/   r?   r   rn   r   r   r   r   r   bszq_len_query_states
key_statesvalue_statesr   r   cache_kwargsattn_weightscausal_maskattn_outputs                        r3   rB   zQwen2Attention.forward  sK    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&G   |\BBHC*HC#7jRUWZ#[#[ 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'+5L },,\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8r4   r   NNNFFNN)rH   rI   rJ   __doc__r"   r   intr)   r+   Tensor
LongTensorr   boolr   rB   rK   rL   s   @r3   r   r      sS        
C C{ Cx} C C C C C CH 2637*."'59KOA9 A9|A9 !.A9 u/0	A9
 !A9  A9 A9 !!12A9 &eEL%,,F&GHA9 
u|Xel3XeEL>Q5RR	SA9 A9 A9 A9 A9 A9 A9 A9r4   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ej        ej        f                  fdZ xZS )Qwen2FlashAttention2a  
    Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
    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. Additionally, for sliding window attention, we apply SWA only to the bottom
    config.max_window_layers layers.
    c                 b     t                      j        |i | t                       | _        d S r   )r(   r)   r   _flash_attn_uses_top_left_mask)r/   argskwargsr2   s      r3   r)   zQwen2FlashAttention2.__init__d  s9    $)&)))
 3V2W2W.W+++r4   NFr?   r   rn   r   r   r   r   r   c	                    |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|4t          
                    d           |                     ||          \  }}n|\  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t          || j                  }t          || j                  }| j        sdn| j        }|j        }|t(          j        k    rt)          j                    rt)          j                    }n3t1          | j        d          r| j        j        }n| j        j        j        }t          
                    d| d           |                    |          }|                    |          }|                    |          }|                    dd          }|                    dd          }|                    dd          }| j        j        r8t=          | j        d	d           "| j        | j        j        k    r| j        j         }nd }tC          |||||
|||| j"        | j#        

  
        }|$                    |	|
| j%                  &                                }| '                    |          }|sd }|||fS )Nr!   r6   r   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)rn   r   r   r   use_top_left_mask)(r   r   r   r   r   r   r   r}   r   r_   r`   r   r   r   r   r   r   r   r   r9   r+   r;   is_autocast_enabledget_autocast_gpu_dtypehasattrrS   r   r-   r:   use_sliding_windowgetattrmax_window_layersr   r#   r   r   r   r0   r   r   )r/   r?   r   rn   r   r   r   r   r   r   r   r   r   r   r   r   r   r   dropout_rater@   target_dtyper   r   r   s                           r3   rB   zQwen2FlashAttention2.forwardl  s    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&G   |\BBHC*HC#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J z4+DEE
 t/HII"&-KssT5K
 #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L $--a33))!Q//
#--a33 K*	"%5t<<H$+"???![7NN!N.% )n"A
 
 
 "))#ud6FGGRRTTkk+..  	 LL.88r4   r   )rH   rI   rJ   r   r)   r+   r   r   r   r   r   r   rB   rK   rL   s   @r3   r   r   Z  s        X X X X X 2637*."'59KOb9 b9|b9 !.b9 u/0	b9
 !b9  b9 b9 !!12b9 &eEL%,,F&GHb9 b9 b9 b9 b9 b9 b9 b9r4   r   c                   4    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
ej        ej        f                  de
ej        eej                 ee
ej                          f         f fdZ xZS )Qwen2SdpaAttentionz
    Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr?   r   rn   r   r   r   r   r   r   c	                    |rAt                               d           t                                          ||||||          S |                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j	        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|4t                               d           |                     ||          \  }}n|\  }}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  Qwen2Model is using Qwen2SdpaAttention, 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   rn   r   r   r   r!   r6   r   r   r   cudaTFr   )	attn_mask	dropout_pr   )r_   r`   r(   rB   r   r   r   r   r   r   r   r}   r   r   r   r   r   r   r   rE   ri   rZ   r   r+   r   r   scaled_dot_product_attentionr   r   r0   r   )r/   r?   r   rn   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r2   s                        r3   rB   zQwen2SdpaAttention.forward  s,     	[   77??+-)-"3# #    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&G   |\BBHC*HC#7jRUWZ#[#[ 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0r4   r   )rH   rI   rJ   r   r+   r   r   r   r   r   r   rB   rK   rL   s   @r3   r   r     s          2637*."'59KOU1 U1|U1 !.U1 u/0	U1
 !U1  U1 U1 !!12U1 &eEL%,,F&GHU1 
u|Xel3XeEL>Q5RR	SU1 U1 U1 U1 U1 U1 U1 U1 U1 U1r4   r   )eagerflash_attention_2sdpac                   d    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
ej        ej        f                  de
ej        ee
ej        ej        f                  f         fdZ xZS )Qwen2DecoderLayerrS   r   c                    t                                                       |j        | _        |j        r.|j        dk    r#t
                              d|j         d           t          |j                 ||          | _        t          |          | _
        t          |j        |j                  | _        t          |j        |j                  | _        d S )Nr  z=Sliding Window Attention is enabled but not implemented for `z)`; unexpected results may be encountered.r1   )r(   r)   r0   r   _attn_implementationr_   r`   QWEN2_ATTENTION_CLASSES	self_attnr   mlpr%   rms_norm_epsinput_layernormpost_attention_layernormr   s      r3   r)   zQwen2DecoderLayer.__init__9  s    !-  	V%@DW%W%W9PVPk 9 9 9   11LMfV_``F##+F,>FDWXXX(4V5GVM`(a(a(a%%%r4   NFr?   r   rn   r   r   r   r   r   r   c	           
         |}
|                      |          }|                     ||||||||          \  }}}|
|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, sequence_length)` where padding elements are indicated by 0.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence.
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        )r?   r   rn   r   r   r   r   r   )r  r	  r  r
  )r/   r?   r   rn   r   r   r   r   r   r   residualself_attn_weightspresent_key_valueoutputss                 r3   rB   zQwen2DecoderLayer.forwardH  s    D !,,];; ?Cnn')%)/) 3 ?M 	?
 	?
;(*; !=0 !55mDD// =0 " 	,)++G 	,)++Gr4   r   )rH   rI   rJ   r"   r   r)   r+   r   r   r   r   r   FloatTensorrB   rK   rL   s   @r3   r  r  8  sO       b{ bs b b b b b b$ 26378<,1$)59KOA A|A !.A u/0	A
 !u|!45A $D>A D>A !!12A &eEL%,,F&GHA 
u (51BEDU1U+V"WW	XA A A A A A A Ar4   r  aJ  
    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 ([`Qwen2Config`]):
            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 Qwen2 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 ZdS )Qwen2PreTrainedModelmodelTr  past_key_valuesc                    | 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   )r=   std)rS   initializer_rangerz   r   r   r-   datanormal_r   zero_	Embeddingpadding_idx)r/   moduler  s      r3   _init_weightsz"Qwen2PreTrainedModel._init_weights  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r4   N)rH   rI   rJ   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_supports_quantized_cache_supports_static_cacher!   r4   r3   r  r    sb        
 L&*#,-"3!N  $!	? 	? 	? 	? 	?r4   r  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 `decoder_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 )
Qwen2Modelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]

    Args:
        config: Qwen2Config
    rS   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        j        | _        t          j        j                  | _        t#                    | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r,  )r  ).0r   rS   s     r3   
<listcomp>z'Qwen2Model.__init__.<locals>.<listcomp>  s$    cccivy11cccr4   r  r   F)r(   r)   pad_token_idr  
vocab_sizer   r  r0   embed_tokens
ModuleListrangenum_hidden_layerslayersr  r%   r  normrN   r   gradient_checkpointing	post_initr   s    `r3   r)   zQwen2Model.__init__  s       !. +L):F<NPTP`aamcccc5IaCbCbccc
 
 %+$?! !39LMMM	.f===&+#r4   c                     | j         S r   r5  rF   s    r3   get_input_embeddingszQwen2Model.get_input_embeddings!  s      r4   c                     || _         d S r   r>  r/   values     r3   set_input_embeddingszQwen2Model.set_input_embeddings$  s    !r4   N	input_idsr   rn   r  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 ]r}|r||fz  }| j        r*| j        r#|                     |j        |||||||
|	  	        }n ||||||||
|
          }|d         }|r||rdnd         }|r||d         fz  }s|                     |          }|r||fz  }|r|nd }|r|                                }|	st9          d ||||fD                       S t;          ||||          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!   rr   r,  )r   rn   r   r   r   r   r   r6   c              3      K   | ]}||V  	d S r   r,  )r1  vs     r3   	<genexpr>z%Qwen2Model.forward.<locals>.<genexpr>  s(      ttqfgfsfsfsfsfsttr4   )last_hidden_stater  r?   
attentions)rS   r   rF  r   use_return_dictr   r;  r   r_   r`   rz   r   r   from_legacy_cacher5  get_seq_lengthr+   arangerE   ri   r   _update_causal_maskr   r9  _gradient_checkpointing_func__call__r:  to_legacy_cacherD   r   )r/   rD  r   rn   r  rE  r   r   rF  rG  r   return_legacy_cachepast_seen_tokensr   r?   r   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                         r3   rB   zQwen2Model.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]
 
 & #oom\JJ #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&+&+%	
 
 
 	
r4   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  )rE  past_key_values_lengthr   is_trainingr!   r7   )sequence_lengthtarget_lengthr9   ri   r   
batch_sizerS   r  r   )rS   r  rP  rz   r   r   r   _ignore_causal_mask_sdpar   r   r9   ri   r+   finfominrE   get_max_cache_shaper   5_prepare_4d_causal_attention_mask_with_cache_positionrZ   _unmask_unattended)r/   r   r^  r   r  r   rW  using_static_cacheusing_sliding_window_cacher9   ri   	min_dtyperb  rc  r   s                  r3   rR  zQwen2Model._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r4   rb  rc  r9   ri   rd  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 )aT  
        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 (`Qwen2Config`):
                The model's configuration class
            past_key_values (`Cache`):
                The cache class that is being used currently to generate
        N   )
fill_valuer9   ri   rr   r7   r!   r   )rW   r+   rf  rg  fullrQ  r   r   rz   r   ry   clonerE   masked_fill)r   rb  rc  r9   ri   r   rd  rS   r  r   rm  diagonal_attend_masksliding_attend_maskmask_lengthpadding_masks                  r3   ri  z@Qwen2Model._prepare_4d_causal_attention_mask_with_cache_position  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 r4   
NNNNNNNNNN)rH   rI   rJ   r   r"   r)   r?  rC  r   QWEN2_INPUTS_DOCSTRINGr+   r   r   r   r   r  r   r   r   r   rB   r   rR  staticmethodr   r9   ri   ri  rK   rL   s   @r3   r.  r.    si       
 {      "! ! !" " " +*+ABB '+1537=A59$(,0/3&*59{
 {
#{
 !.{
 u/0	{

 "$u'8"9:{
   12{
 D>{
 $D>{
 'tn{
 d^{
 !!12{
 
u--	.{
 {
 {
 CB{
|II lI 	I
 I  I I I IV @@@ @ {	@
 @ @ @ @ @ @ @ \@ @ @ @ @r4   r.  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 xZS )Qwen2ForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S r   )
r(   r)   r.  r  r4  r   r   r0   lm_headr<  r   s     r3   r)   zQwen2ForCausalLM.__init__9  sj       ''
 +y!3V5FUSSS 	r4   c                     | j         j        S r   r  r5  rF   s    r3   r?  z%Qwen2ForCausalLM.get_input_embeddingsB      z&&r4   c                     || j         _        d S r   r  rA  s     r3   rC  z%Qwen2ForCausalLM.set_input_embeddingsE      "'
r4   c                     | j         S r   r~  rF   s    r3   get_output_embeddingsz&Qwen2ForCausalLM.get_output_embeddingsH  s
    |r4   c                     || _         d S r   r  )r/   new_embeddingss     r3   set_output_embeddingsz&Qwen2ForCausalLM.set_output_embeddingsK  s    %r4   c                     || _         d S r   r  )r/   decoders     r3   set_decoderzQwen2ForCausalLM.set_decoderN  s    


r4   c                     | j         S r   r  rF   s    r3   get_decoderzQwen2ForCausalLM.get_decoderQ  s
    zr4   )output_typer"  Nr   rD  r   rn   r  rE  labelsr   r   rF  rG  r   num_logits_to_keepr   c                    ||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 )a;  
        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, Qwen2ForCausalLM

        >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
        >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)
rD  r   rn   r  rE  r   r   rF  rG  r   r   r!   losslogitsr  r?   rM  )rS   r   rF  rN  r  r~  loss_functionr4  r   r  r?   rM  )r/   rD  r   rn   r  rE  r  r   r   rF  rG  r   r  loss_kwargsr  r?   r  r  outputs                      r3   rB   zQwen2ForCausalLM.forwardT  sK   b 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!/)
 
 
 	
r4   )NNNNNNNNNNNr   )rH   rI   rJ   _tied_weights_keysr)   r?  rC  r  r  r  r  r   ry  r    r   _CONFIG_FOR_DOCr+   r   r   r   r   r  r   r   r   r   rB   rK   rL   s   @r3   r|  r|  6  s       *+    ' ' '( ( (  & & &     +*+ABB+AP_``` '+1537=A59-1$(,0/3&*59"#U
 U
#U
 !.U
 u/0	U

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

    [`Qwen2ForSequenceClassification`] 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                   Z    e Zd Z 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j	                 de
e         de
e         de
e         de
e         deeef         fd            Z xZS )Qwen2ForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S r   )
r(   r)   
num_labelsr.  r  r   r   r0   scorer<  r   s     r3   r)   z'Qwen2ForSequenceClassification.__init__  si        +''
Yv14?OOO
 	r4   c                     | j         j        S r   r  rF   s    r3   r?  z3Qwen2ForSequenceClassification.get_input_embeddings  r  r4   c                     || j         _        d S r   r  rA  s     r3   rC  z3Qwen2ForSequenceClassification.set_input_embeddings  r  r4   NrD  r   rn   r  rE  r  r   r   rF  rG  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}|t|                    |j                  }| j         j        f| j        dk    rd| j         _        nN| j        dk    r7|j        t          j        k    s|j        t          j	        k    rd	| j         _        nd
| j         _        | j         j        dk    rWt%                      }| j        dk    r1 ||                                |                                          }n |||          }n| j         j        d	k    rGt)                      } ||                    d| j                  |                    d                    }n*| j         j        d
k    rt-                      } |||          }|
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   rn   r  rE  r   r   rF  rG  r   r!   z=Cannot handle batch sizes > 1 if no padding token is defined.r7   rr   
regressionsingle_label_classificationmulti_label_classificationr  )rS   rN  r  r  rE   r3  r   r+   eqr   argmaxr:   ri   rQ  problem_typer  r9   longr
   squeezer	   r   r   r   r  r?   rM  )r/   rD  r   rn   r  rE  r  r   r   rF  rG  transformer_outputsr?   r  rd  sequence_lengthspooled_logitsr  loss_fctr  s                       r3   rB   z&Qwen2ForSequenceClassification.forward  s   ( &1%<kk$+B]"jj)%+'/!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__`YYv}--F{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8M$9$9$;$;V^^=M=MNNDD#8M6::DD)-JJJ+--x 2 22t G GUWYY)-III,..xv66 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r4   rx  )rH   rI   rJ   r)   r?  rC  r   ry  r+   r   r   r   r   r  r   r   r   r   rB   rK   rL   s   @r3   r  r    ss            ' ' '( ( ( +*+ABB '+1537=A59-1$(,0/3&*X
 X
#X
 !.X
 u/0	X

 "$u'8"9:X
   12X
 )*X
 D>X
 $D>X
 'tnX
 d^X
 
u66	7X
 X
 X
 CBX
 X
 X
 X
 X
r4   r  z
    The Qwen2 Model transformer 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 fdZd Zd Z ee           ee	e
e          	 	 	 	 	 	 	 	 	 	 dde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e
f         fd                        Z xZS )Qwen2ForTokenClassificationc                    t                                          |           |j        | _        t          |          | _        t          |dd           |j        }nt          |dd           |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropouthidden_dropoutg?)r(   r)   r  r.  r  r   r  r  r   Dropoutr   r   r0   r  r<  )r/   rS   r  r2   s      r3   r)   z$Qwen2ForTokenClassification.__init__2  s        +''
6/66B!'!:V-t44@!'!6!$z"455Yv163DEE
 	r4   c                     | j         j        S r   r  rF   s    r3   r?  z0Qwen2ForTokenClassification.get_input_embeddingsB  r  r4   c                     || j         _        d S r   r  rA  s     r3   rC  z0Qwen2ForTokenClassification.set_input_embeddingsE  r  r4   )
checkpointr  r"  NrD  r   rn   r  rE  r  r   r   rF  rG  r   c                 p   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}||                     ||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j                  S )r  Nr  r   r6   )r  r  r?   rM  )	rS   rN  r  r   r  r  r   r?   rM  )r/   rD  r   rn   r  rE  r  r   r   rF  rG  r  sequence_outputr  r  r  s                   r3   rB   z#Qwen2ForTokenClassification.forwardH  s    2 &1%<kk$+B]**)%+'/!5#  

 

 "!*,,77O,,%%ffdkBBD 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r4   rx  )rH   rI   rJ   r)   r?  rC  r   ry  r   _CHECKPOINT_FOR_DOCr   r  r   r+   r   r   r   r  r   r   r   rB   rK   rL   s   @r3   r  r  )  s            ' ' '( ( ( +*+ABB&)$   151537=A59-1$(,0/3&*1
 1
E,-1
 !.1
 u/0	1

 "$u'8"9:1
   121
 )*1
 D>1
 $D>1
 'tn1
 d^1
 
u++	,1
 1
 1
  CB1
 1
 1
 1
 1
r4   r  z
The Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       e Zd 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
j                 de	e         de	e         de	e         deeef         fd            Z xZS )Qwen2ForQuestionAnsweringr  c                     t                                          |           t          |          | _        t	          j        |j        d          | _        |                                  d S )Nr6   )	r(   r)   r.  r  r   r   r0   
qa_outputsr<  r   s     r3   r)   z"Qwen2ForQuestionAnswering.__init__  sX       ''
)F$6:: 	r4   c                     | j         j        S r   r  rF   s    r3   r?  z.Qwen2ForQuestionAnswering.get_input_embeddings  r  r4   c                     || j         _        d S r   r  rA  s     r3   rC  z.Qwen2ForQuestionAnswering.set_input_embeddings  r  r4   NrD  r   rn   r  rE  start_positionsend_positionsr   rF  rG  r   c           
         |
|
n| j         j        }
|                     |||||||	|
          }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}|| | j        ||||fi |}|
s||f|dd         z   }||f|z   n|S t          ||||j	        |j
                  S )	a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        N)r   rn   r  rE  r   rF  rG  r   r!   r7   rw   r6   )r  start_logits
end_logitsr?   rM  )rS   rN  r  r  splitr  r   r  r   r?   rM  )r/   rD  r   rn   r  rE  r  r  r   rF  rG  r   r  r  r  r  r  r  r  s                      r3   rB   z!Qwen2ForQuestionAnswering.forward  sP   2 &1%<kk$+B]**)%+'/!5#  	
 	
 "!*11#)<<r<#:#: j#++B//::<<''++6688
&=+D%4%lJQ^iibhiiD 	F"J/'!""+=F)-)9TGf$$vE+%!!/)
 
 
 	
r4   rx  )rH   rI   rJ   r#  r)   r?  rC  r   ry  r   r+   r   r  r   r   r   r   r   r   rB   rK   rL   s   @r3   r  r    s{             ' ' '( ( ( +*+ABB 156:37KO596:48,0/3&*:
 :
E,-:
 !!23:
 u/0	:

 "%tE4E/F(F"GH:
   12:
 "%"23:
   01:
 $D>:
 'tn:
 d^:
 
u22	3:
 :
 :
 CB:
 :
 :
 :
 :
r4   r  )Nr!   )Jr   r   typingr   r   r   r   r+   torch.utils.checkpointr   torch.nnr   r	   r
   activationsr   cache_utilsr   r   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   modeling_utilsr   utilsr   r   r   r   r   r   r    configuration_qwen2r"   modeling_flash_attention_utilsr#   
get_loggerrH   r_   r  r  Moduler%   rN   r   r   r   r   r   r   r   r   r   r  r  QWEN2_START_DOCSTRINGr  ry  r.  r|  r  r  r  r,  r4   r3   <module>r     s  (    / / / / / / / / / / / /            A A A A A A A A A A ! ! ! ! ! ! O O O O O O O O O O O O ) ) ) ) ) ) > > > > > >              7 6 6 6 6 6 - - - - - -                  - , , , , ,  KJJJJJJ 
	H	%	% & J J J J J29 J J J*T< T< T< T< T<29 T< T< T<p( ( (   8f f f f fry f f f	UU\ 	U# 	U%, 	U 	U 	U 	Uh9 h9 h9 h9 h9RY h9 h9 h9Vt9 t9 t9 t9 t9> t9 t9 t9n]1 ]1 ]1 ]1 ]1 ]1 ]1 ]1B -  Q Q Q Q Q	 Q Q Qh " Y ? ? ? ? ?? ? ?	 ?0H V Y k k k k k% k k	 k\	u
 u
 u
 u
 u
+_ u
 u
 u
p   i
 i
 i
 i
 i
%9 i
 i
 i
X   N
 N
 N
 N
 N
"6 N
 N
 N
b   M
 M
 M
 M
 M
 4 M
 M
 M
 M
 M
r4   