
    gF                        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 ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZ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&  e#j'        e(          Z)dZ*dZ+ G d de	j,                  Z- G d de-          Z. G d de-          Z/d Z0d0dZ1 G d de	j,                  Z2 G d de	j,                  Z3 G d d e	j,                  Z4d!Z5 e!d"e5           G d# d$e                      Z6d%Z7 e!d"e5           G d& d'e6                      Z8 G d( d)e6e          Z9 e!d*e5           G d+ d,e6                      Z: e!d-e5           G d. d/e6                      Z;dS )1zPyTorch Persimmon model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONS)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )PersimmonConfigzadept/persimmon-8b-baser   c                   v     e Zd Z	 	 	 	 	 	 	 d
dee         f fdZd Z ej                    d	             Z	 xZ
S )PersimmonRotaryEmbeddingN   '        ?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`PersimmonRotaryEmbedding` 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_embeddingsr%   typer"   inv_freqF
persistent)super__init__rope_kwargsloggerwarning_oncer%   max_seq_len_cachedoriginal_max_seq_lenrope_scalinggetr)   r#   r   rope_init_fnattention_scalingregister_bufferr+   original_inv_freq)
selfr'   r)   r(   devicescaling_factorr%   r#   r+   	__class__s
            l/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/persimmon/modeling_persimmon.pyr/   z!PersimmonRotaryEmbedding.__init__<   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!%    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)
torchmaxr3   r7   r#   r0   r8   r9   r4   r:   )r;   position_idsr<   rB   r+   s        r?   _dynamic_frequency_updatez2PersimmonRotaryEmbedding._dynamic_frequency_updateh   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### /.3f3fr@   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r<   r   r   mpscpuF)device_typeenabled   r'   )dtype)r%   rF   r<   r+   floatexpandshaper*   
isinstancestrrC   autocast	transposecatcossinr8   torQ   )
r;   xrE   inv_freq_expandedposition_ids_expandedrM   freqsembrZ   r[   s
             r?   forwardz PersimmonRotaryEmbedding.forwardz   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)Nr   r    Nr!   r"   N)__name__
__module____qualname__r   r   r/   rF   rC   no_gradrb   __classcell__r>   s   @r?   r   r   ;   s          $,0*/ */ )*/ */ */ */ */ */X@ @ @$ U]__< < _< < < < <r@   r   c                   "     e Zd ZdZ fdZ xZS )%PersimmonLinearScalingRotaryEmbeddingz_PersimmonRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                 x    t                               d           d|d<    t                      j        |i | d S )Nz`PersimmonLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use `PersimmonRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__).linearr%   r1   r2   r.   r/   r;   argskwargsr>   s      r?   r/   z.PersimmonLinearScalingRotaryEmbedding.__init__   sO    y	
 	
 	
 '{$)&)))))r@   rc   rd   re   __doc__r/   rg   rh   s   @r?   rj   rj      s>        ii* * * * * * * * *r@   rj   c                   "     e Zd ZdZ fdZ xZS ))PersimmonDynamicNTKScalingRotaryEmbeddingzqPersimmonRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillac                 x    t                               d           d|d<    t                      j        |i | d S )Nz`PersimmonDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use `PersimmonRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to __init__).rH   r%   rm   rn   s      r?   r/   z2PersimmonDynamicNTKScalingRotaryEmbedding.__init__   sN    	
 	
 	

 ({$)&)))))r@   rq   rh   s   @r?   rt   rt      s>        {{* * * * * * * * *r@   rt   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..NrJ   rO   rP   )rT   rC   rY   )r]   x1x2s      r?   rotate_halfry      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r@   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.
    )	unsqueezery   )qkrZ   r[   rE   unsqueeze_dimq_embedk_embeds           r?   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr@   c                   $     e Zd Z fdZd Z xZS )PersimmonMLPc                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          |j	                 | _
        d S N)r.   r/   r   Linearhidden_sizeintermediate_sizedense_h_to_4hdense_4h_to_hr
   
hidden_actactr;   r#   r>   s     r?   r/   zPersimmonMLP.__init__   s`    Yv'96;STTYv'?ASTT&+,r@   c                     |                      |          }|                     |          }|                     |          }|S r   )r   r   r   )r;   hidden_statess     r?   rb   zPersimmonMLP.forward   s?    **=99//**=99r@   )rc   rd   re   r/   rb   rg   rh   s   @r?   r   r      sG        - - - - -      r@   r   c                       e Zd ZdZddedee         f fdZdej	        de
ej	        ej	        ej	        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 )PersimmonAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr#   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _
        | j        | j
        z  | _        |j        | _        t          | j        |j        z            | _        d| _        | j        | j
        z  | j        k    r t#          d| j         d| j
         d          t%          j        | j        d| j        z  d          | _        t%          j        | j
        | j        z  | j        d          | _        |j        | _        | j        r\t%          j        |j        | j
        z  |j        d	          | _        t%          j        |j        | j
        z  |j        d	          | _        t%          j        |j                  | _        t;          | j        
          | _        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).r	   bias)epselementwise_affiner#   )r.   r/   r#   r   r1   r2   r>   rc   r   num_attention_heads	num_headshead_dim
rope_thetaintpartial_rotary_factorrotary_ndims	is_causal
ValueErrorr   r   query_key_valuedenseqk_layernorm	LayerNormlayer_norm_epsq_layernormk_layernormDropoutattention_dropoutr   
rotary_embr;   r#   r   r>   s      r?   r/   zPersimmonAttention.__init__   s   ",!8 , , ,   "-3(DN: +0L LMMMDN*t/???8RVRb 8 8%)^8 8 8    "y)91t?O;OVZ[[[Yt~=t?OVZ[[[
"/ 	!|"dn4&:Odh     D  "|"dn4&:Odh     D "$F,D!E!E2$+FFFr@   	fused_qkvreturnc                     |j         \  }}}|                    ||| j        d| j                  }|ddddf         |ddddf         |ddddf         fS )a  
        Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory
        storage as `fused_qkv`

        Args:
            fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]

        Returns:
            query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
            value: [batch_size, seq_length, num_heads, head_dim]
        r	   .r   Nr   rO   )rT   viewr   r   )r;   r   
batch_size
seq_lengththree_times_hidden_sizes        r?   _split_headszPersimmonAttention._split_heads  sk     ;D/7
J 7NN:z4>1dm\\	a#YsAqqqy%99S!QQQY;OOOr@   Fr   attention_maskrE   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsc	                    |                                 \  }	}
}|                     |          }|                     |          \  }}}| j        r*|                     |          }|                     |          }|                    dd          }|                    dd          }|                    dd          }|4t                              d           | 	                    ||          \  }}n|\  }}|dd | j
        f         |d| j
        d f         }}|dd | j
        f         |d| j
        d f         }}t          ||||          \  }}t          j        ||fd          }t          j        ||fd          }|,||| j
        |d}|                    ||| j        |          \  }}t          j        ||                    dd                    t#          j        | j                  z  }|$|d d d d d d d |j        d	         f         }||z   }t*          j                            |t          j        d
                              |j                  }|                     |          }t          j        ||          }|                                 |	| j        |
| j        fk    r5t;          d|	| j        |
| j        f d|                                            |                    dd                                          }|                    |	|
| j                   }| !                    |          }|sd }|||fS )Nr   rO   aY  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..rJ   rP   )r[   rZ   partial_rotation_sizer   r	   )rQ   r'   z `attn_output` should be of size z	, but is )"sizer   r   r   r   r   rX   r1   r2   r   r   r   rC   rY   updater   matmulmathsqrtr   rT   r   
functionalsoftmaxfloat32r\   rQ   r   r   r   
contiguousreshaper   r   )r;   r   r   rE   r   r   r   r   r   bszq_len_r   query_states
key_statesvalue_statesrZ   r[   	query_rot
query_passkey_rotkey_passcache_kwargsattn_weightscausal_maskattn_outputs                             r?   rb   zPersimmonAttention.forward  s    &**,,UA ((77	 483D3DY3O3O0z< 	6++L99L))*55J $--a33#--a33))!Q//
&G   |\BBHC*HC 1 1112d/1112 	
 s/d///0sD-///0 
 2)Wc3OO	7 y)Z!8bAAAY2;;;
% )-):"0	 L (6'<'<ZW[Wegs't't$J|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\TV,WWZZ[g[mnn--l;;l<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!))#ud6FGGjj--  	 LL.88r@   r   NNNFFNN)rc   rd   re   rr   r   r   r   r/   rC   Tensorr   r   
LongTensorr   boolrb   rg   rh   s   @r?   r   r      s       GG#G #G #G8C= #G #G #G #G #G #GJPel PuU\5<Y^Ye=e7f P P P P& 2637*."'59KO[9 [9|[9 !.[9 u/0	[9
 ![9  [9 [9 !!12[9 &eEL%,,F&GH[9 
u|Xel3XeEL>Q5RR	S[9 [9 [9 [9 [9 [9 [9 [9r@   r   c                   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 )PersimmonDecoderLayerr#   r   c                    t                                                       |j        | _        t          ||          | _        t          |          | _        t          j        |j        |j	                  | _
        t          j        |j        |j	                  | _        t          j        |j                  | _        d S )N)r#   r   r   )r.   r/   r   r   	self_attnr   mlpr   r   r   input_layernormpost_attention_layernormr   hidden_dropoutdropoutr   s      r?   r/   zPersimmonDecoderLayer.__init__w  s    !-+6YOOO''!|F,>FDYZZZ(*V5GVMb(c(c(c%z&"788r@   NFr   r   rE   r   r   r   r   r   r   c	           
      2   |}	|                      |          }|                     ||||||||          \  }}
}|	|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)
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
                cached past key and value projection states
            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`).
            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.
        )r   r   rE   r   r   r   r   r   )r   r   r   r   r   )r;   r   r   rE   r   r   r   r   r   residualself_attn_weightspresent_key_valueoutputss                r?   rb   zPersimmonDecoderLayer.forward  s    F !,,];; ?Cnn')%)/) 3 ?M 	?
 	?
;(*; !=0 !55mDD//]33%0 " 	,)++G 	,)++Gr@   r   )rc   rd   re   r   r   r/   rC   r   r   r   r   r   FloatTensorrb   rg   rh   s   @r?   r   r   v  sG       9 93 9 9 9 9 9 9 26378<,1$)59KOD D|D !.D u/0	D
 !u|!45D $D>D D>D !!12D &eEL%,,F&GHD 
u (51BEDU1U+V"WW	XD D D D D D D Dr@   r   aN  
    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 ([`PersimmonConfig`]):
            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.
zWThe bare Persimmon Model outputting raw hidden-states without any specific head on top.c                   6    e Zd ZeZdZdZdgZdZdZ	dZ
dZd ZdS )PersimmonPreTrainedModel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 )N        )meanstd)r#   initializer_rangerU   r   r   weightdatanormal_r   zero_	Embeddingpadding_idx)r;   moduler   s      r?   _init_weightsz&PersimmonPreTrainedModel._init_weights  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r@   N)rc   rd   re   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_cache_class_supports_quantized_cache_supports_static_cacher    r@   r?   r   r     sW        
 #L&*#01"3  $!	? 	? 	? 	? 	?r@   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fd            Z xZS )PersimmonModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PersimmonDecoderLayer`]

    Args:
        config: PersimmonConfig
    r#   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        t          j        j        j                  | _        t!                    | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r  )r   ).0r   r#   s     r?   
<listcomp>z+PersimmonModel.__init__.<locals>.<listcomp>P  s$    ggg)"6955gggr@   r   r   F)r.   r/   pad_token_idr   
vocab_sizer   r   r   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   final_layernormr   r   gradient_checkpointing	post_initr   s    `r?   r/   zPersimmonModel.__init__I  s       !. +L):F<NPTP`aamgggguVMeGfGfggg
 
  "|F,>FDYZZZ2&AAA&+#r@   c                     | j         S r   r  r;   s    r?   get_input_embeddingsz#PersimmonModel.get_input_embeddingsZ  s      r@   c                     || _         d S r   r  r;   values     r?   set_input_embeddingsz#PersimmonModel.set_input_embeddings]  s    !r@   N	input_idsr   rE   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   rI   r  )r   rE   r   r   r   r   r   rO   c              3      K   | ]}||V  	d S r   r  )r  vs     r?   	<genexpr>z)PersimmonModel.forward.<locals>.<genexpr>  s(      ttqfgfsfsfsfsfsttr@   )last_hidden_stater   r   
attentions)r#   r   r  r   use_return_dictr   r  trainingr1   r2   rU   r   r   from_legacy_cacher  get_seq_lengthrC   arangerT   r<   r{   _update_causal_maskr   r  _gradient_checkpointing_func__call__r  to_legacy_cachetupler   )r;   r  r   rE   r   r  r   r   r  r  r   return_legacy_cachepast_seen_tokensr   r   r   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                         r?   rb   zPersimmonModel.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,,];;   	2-!11+4>''$
 	6#3355J 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r@   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nflash_attention_2r   r   sdpa)r  past_key_values_lengthis_trainingr   rJ   )sequence_lengthtarget_lengthrQ   r<   r   r   cuda)r#   _attn_implementationr)  rU   r   r   _ignore_causal_mask_sdpar'  rQ   r<   rT   get_max_cache_shaperC   r   5_prepare_4d_causal_attention_mask_with_cache_positionr*   finfomin_unmask_unattended)r;   r   r8  r   r   r   r1  using_static_cacherQ   r<   r>  r?  r   	min_dtypes                 r?   r+  z"PersimmonModel._update_causal_mask  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr@   r>  r?  rQ   r<   r   c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| 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 )	a  
        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.
        N   )
fill_valuerQ   r<   r   )diagonalrI   rJ   r   )r'   rC   rE  rF  fulltriur*  r   rS   clonerT   masked_fill)r   r>  r?  rQ   r<   r   r   rp   r   rI  mask_lengthpadding_masks               r?   rD  zDPersimmonModel._prepare_4d_causal_attention_mask_with_cache_position   s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r@   
NNNNNNNNNN)rc   rd   re   rr   r   r/   r  r  r   PERSIMMON_INPUTS_DOCSTRINGrC   r   r   r   r   r   r   r   r   r   rb   r   r+  staticmethodr   rQ   r<   rD  rg   rh   s   @r?   r  r  =  s;       
       "! ! !" " " +*+EFF '+1537=A59$(,0/3&*59{
 {
#{
 !.{
 u/0	{

 "$u'8"9:{
   12{
 D>{
 $D>{
 'tn{
 d^{
 !!12{
 
u--	.{
 {
 {
 GF{
|?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r@   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 )PersimmonForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S NFr   )
r.   r/   r  r   r  r   r   r   lm_headr  r   s     r?   r/   zPersimmonForCausalLM.__init__^  sj       #F++
 +y!3V5FUSSS 	r@   c                     | j         j        S r   r   r  r  s    r?   r  z)PersimmonForCausalLM.get_input_embeddingsh      z&&r@   c                     || j         _        d S r   r]  r  s     r?   r  z)PersimmonForCausalLM.set_input_embeddingsl      "'
r@   c                     | j         S r   r[  r  s    r?   get_output_embeddingsz*PersimmonForCausalLM.get_output_embeddingsp  s
    |r@   c                     || _         d S r   rb  )r;   new_embeddingss     r?   set_output_embeddingsz*PersimmonForCausalLM.set_output_embeddingst  s    %r@   c                     || _         d S r   r   )r;   decoders     r?   set_decoderz PersimmonForCausalLM.set_decoderx  s    


r@   c                     | j         S r   rh  r  s    r?   get_decoderz PersimmonForCausalLM.get_decoder|  s
    zr@   )output_typer   Nr   r  r   rE   r   r  labelsr   r   r  r  r   num_logits_to_keepr   c                    ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
|                     ||||||||	|
|
  
        }|d         }|                     |dd| dddf                   }d}||dddddf                                         }|dddf                                         }t                      }|                    d| j         j	                  }|                    d          }|
                    |j                  } |||          }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j                  S )u2  
        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, PersimmonForCausalLM

        >>> model = PersimmonForCausalLM.from_pretrained("adept/persimmon-8b-base")
        >>> tokenizer = AutoTokenizer.from_pretrained("adept/persimmon-8b-base")

        >>> prompt = "human: Hey, what should I eat for dinner?"
        >>> 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]
        'human: Hey, what should I eat for dinner?\n\ncat: 🐱\n\nhuman: 😐\n\n'
        ```N)
r  r   rE   r   r  r   r   r  r  r   r   .rJ   r   losslogitsr   r   r%  )r#   r   r  r&  r   r[  r   r   r   r  r\   r<   r   r   r   r%  )r;   r  r   rE   r   r  rn  r   r   r  r  r   ro  r   r   rs  rr  shift_logitsshift_labelsloss_fctoutputs                        r?   rb   zPersimmonForCausalLM.forward  s   ` 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **)%+'/!5#)  
 
  
mAAA0B/B/C/CQQQ,FGHH!#ssAAA+.99;;L!#qrr'?5577L'))H',,R1GHHL',,R00L'??<+>??L8L,77D 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r@   )NNNNNNNNNNNr   )rc   rd   re   _tied_weights_keysr/   r  r  rc  rf  rj  rl  r   rU  r   r   _CONFIG_FOR_DOCrC   r   r   r   r   r   r   r   r   r   rb   rg   rh   s   @r?   rX  rX  Z  s       *+    ' ' '( ( (  & & &     +*+EFF+AP_``` '+1537=A59-1$(,0/3&*59"#]
 ]
#]
 !.]
 u/0	]

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

    [`PersimmonForSequenceClassification`] 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 )"PersimmonForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S rZ  )
r.   r/   
num_labelsr  r   r   r   r   scorer  r   s     r?   r/   z+PersimmonForSequenceClassification.__init__  si        +#F++
Yv14?OOO
 	r@   c                     | j         j        S r   r]  r  s    r?   r  z7PersimmonForSequenceClassification.get_input_embeddings  r^  r@   c                     || j         _        d S r   r]  r  s     r?   r  z7PersimmonForSequenceClassification.set_input_embeddings  r`  r@   Nr  r   rE   r   r  rn  r   r   r  r  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   rE   r   r  r   r   r  r  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.rJ   rI   )rs  rn  pooled_logitsr#   rq  )r#   r&  r   r~  rT   r
  r   rC   eqr   argmaxr\   r<   r*  loss_functionr   r   r   r%  )r;   r  r   rE   r   r  rn  r   r   r  r  transformer_outputsr   rs  r   sequence_lengthsr  rr  rw  s                      r?   rb   z*PersimmonForSequenceClassification.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__`%%VFR_hlhs%ttD 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r@   rT  )rc   rd   re   r/   r  r  r   rU  r   rC   r   r   r   r   r   r   r   r   r   rb   rg   rh   s   @r?   r{  r{    s       "    ' ' '( ( ( +*+EFF 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
 GFE
 E
 E
 E
 E
r@   r{  z
    The Persimmon 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 )PersimmonForTokenClassificationc                    t                                          |           |j        | _        t          |          | _        t          |dd           |j        }nt          |dd           |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropoutr   g?)r.   r/   r}  r  r   getattrr  r   r   r   r   r   r   r~  r  )r;   r#   r  r>   s      r?   r/   z(PersimmonForTokenClassification.__init__S  s        +#F++
6/66B!'!:V-t44@!'!6!$z"455Yv163DEE
 	r@   c                     | j         j        S r   r]  r  s    r?   r  z4PersimmonForTokenClassification.get_input_embeddingsc  r^  r@   c                     || j         _        d S r   r]  r  s     r?   r  z4PersimmonForTokenClassification.set_input_embeddingsf  r`  r@   )
checkpointrm  r   Nr  r   rE   r   r  rn  r   r   r  r  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   rO   )rr  rs  r   r%  )	r#   r&  r   r   r~  r  r   r   r%  )r;   r  r   rE   r   r  rn  r   r   r  r  r   sequence_outputrs  rr  rw  s                   r?   rb   z'PersimmonForTokenClassification.forwardi  s    2 &1%<kk$+B]**)%+'/!5#  

 

 "!*,,77O,,%%ffdkBBD 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r@   rT  )rc   rd   re   r/   r  r  r   rU  r   _CHECKPOINT_FOR_DOCr   ry  r   rC   r   r   r   r   r   r   r   rb   rg   rh   s   @r?   r  r  J  s            ' ' '( ( ( +*+EFF&)$   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
  GF1
 1
 1
 1
 1
r@   r  )Nr   )<rr   r   typingr   r   r   r   rC   torch.utils.checkpointr   torch.nnr   activationsr
   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   r   modeling_rope_utilsr   modeling_utilsr   utilsr   r   r   r   r   configuration_persimmonr   
get_loggerrc   r1   r  ry  Moduler   rj   rt   ry   r   r   r   r   PERSIMMON_START_DOCSTRINGr   rU  r  rX  r{  r  r  r@   r?   <module>r     s  (    / / / / / / / / / / / /            % % % % % % ! ! ! ! ! ! ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) > > > > > >            7 6 6 6 6 6 - - - - - -              5 4 4 4 4 4 
	H	%	%/ #T< T< T< T< T<ry T< T< T<p	* 	* 	* 	* 	*,D 	* 	* 	*
* 
* 
* 
* 
*0H 
* 
* 
*( ( (   8    29   S9 S9 S9 S9 S9 S9 S9 S9lN N N N NBI N N Nb " ] ? ? ? ? ? ? ?	 ?,H V ] V V V V V- V V	 VrD
 D
 D
 D
 D
3_ D
 D
 D
N    V
 V
 V
 V
 V
)A V
 V
!  V
r   N
 N
 N
 N
 N
&> N
 N
 N
 N
 N
r@   