o
    wi                     @   s  d Z ddl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mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZ ddlmZmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( e% rddl)m*Z* ddl+m,Z, e&-e.Z/G dd dej0Z1dd Z2d8ddZ3G dd dej0Z4	d9dej0dej5d ej5d!ej5d"eej5 d#e6d$e6fd%d&Z7G d'd( d(ej0Z8G d)d* d*eZ9e#G d+d, d,eZ:e#G d-d. d.e:Z;G d/d0 d0e:eZ<e#d1d2G d3d4 d4e:Z=e#G d5d6 d6e:Z>g d7Z?dS ):zPyTorch Persimmon model.    )CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )PersimmonConfig)	BlockMask)make_flex_block_causal_maskc                       s8   e Zd Zddef fddZe edd Z  Z	S )PersimmonRotaryEmbeddingNconfigc                    s   t    t|dr|jd ur|jd|jd| _nd| _|j| _|j| _|| _	t
| j | _| | j	|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)super__init__hasattrr!   getr"   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr    r   rope_init_fnattention_scalingregister_bufferr%   original_inv_freq)selfr    devicer%   	__class__ m/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/persimmon/modeling_persimmon.pyr(   :   s   
z!PersimmonRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r   mpscpuF)device_typeenabled   dim)dtype)r%   floatexpandshapetor3   
isinstancer#   strtorchautocast	transposecatcosr/   sinr@   )
r2   xposition_idsinv_freq_expandedposition_ids_expandedr;   freqsembrK   rL   r6   r6   r7   forwardK   s   0&z PersimmonRotaryEmbedding.forwardN)
__name__
__module____qualname__r   r(   rG   no_gradr   rS   __classcell__r6   r6   r4   r7   r   9   s
    r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr8   r=   r>   )rC   rG   rJ   )rM   x1x2r6   r6   r7   rotate_half\   s   r\   c                 C   sD   | |}| |}| | t| |  }|| t||  }||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krK   rL   rN   unsqueeze_dimq_embedk_embedr6   r6   r7   apply_rotary_pos_embd   s
   

rc   c                       s$   e Zd Z fddZdd Z  ZS )PersimmonMLPc                    s>   t    t|j|j| _t|j|j| _t|j	 | _
d S rT   )r'   r(   r   Linearhidden_sizeintermediate_sizedense_h_to_4hdense_4h_to_hr   
hidden_actactr2   r    r4   r6   r7   r(      s   
zPersimmonMLP.__init__c                 C   s"   |  |}| |}| |}|S rT   )rh   rk   ri   )r2   hidden_statesr6   r6   r7   rS      s   


zPersimmonMLP.forward)rU   rV   rW   r(   rS   rY   r6   r6   r4   r7   rd      s    rd           modulequerykeyvalueattention_maskscalingdropoutc                 K   s   t ||dd| }|d ur'|d d d d d d d |jd f }	||	 }tjj|dt jd|j	}tjj
||| jd}t ||}
|
dd }
|
|fS )Nr=   r   r8   )r?   r@   )ptrainingr   )rG   matmulrI   rC   r   
functionalsoftmaxfloat32rD   r@   ru   rx   
contiguous)ro   rp   rq   rr   rs   rt   ru   kwargsattn_weightscausal_maskattn_outputr6   r6   r7   eager_attention_forward   s   
&r   c                       s   e Zd ZdZddedee f fddZdej	de
ej	ej	ej	f fd	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 de
ej	eej	 ee
ej	  f fddZ  ZS )PersimmonAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr    	layer_idxc                    sF  t    || _|| _|d u rtd| jj d |j| _|j	| _
| j| j
 | _|j| _t| j|j | _d| _| j| j
 | jkrOtd| j d| j
 dtj| jd| j dd| _tj| j
| j | jdd| _|j| _| jd	 | _| jrtj|j| j
 |jdd
| _tj|j| j
 |jdd
| _t|j| _t| jd| _d S )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   biasg      )epselementwise_affiner    ) r'   r(   r    r   loggerwarning_oncer5   rU   rf   num_attention_heads	num_headshead_dim
rope_thetaintpartial_rotary_factorrotary_ndims	is_causal
ValueErrorr   re   query_key_valuedenseqk_layernormrt   	LayerNormlayer_norm_epsq_layernormk_layernormDropoutattention_dropoutr   
rotary_embr2   r    r   r4   r6   r7   r(      s@   

zPersimmonAttention.__init__	fused_qkvreturnc                 C   sV   |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   r=   )rC   viewr   r   )r2   r   
batch_size
seq_lengththree_times_hidden_sizer6   r6   r7   _split_heads   s   4zPersimmonAttention._split_headsFrm   rs   rN   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr~   c	                 K   s  |  \}
}}| |}| |\}}}| jr!| |}| |}|dd}|dd}|dd}|\}}|dd | jf |d| jd f }}|dd | jf |d| jd f }}t||||\}}t	j
||fdd}t	j
||fdd}|d ur||| j|d}|||| j|\}}t}| jjdkrt| jj }|| ||||f| jsdn| jj| jd	|	\}}||
|d}| |}|sd }|||fS )
Nr   r=   .r8   r>   )rL   rK   partial_rotation_sizer   eagerrn   )ru   rt   )sizer   r   r   r   r   rI   r   rc   rG   rJ   updater   r   r    _attn_implementationr   rx   r   rt   reshaper   )r2   rm   rs   rN   r   r   r   r   r   r~   bszq_len_r   query_states
key_statesvalue_statesrK   rL   	query_rot
query_passkey_rotkey_passcache_kwargsattention_interfacer   r   r6   r6   r7   rS      s\   





zPersimmonAttention.forwardrT   NNNFFNN)rU   rV   rW   __doc__r   r   r   r(   rG   Tensortupler   
LongTensorr   boolr   r   rS   rY   r6   r6   r4   r7   r      s@    $&	
r   c                       s   e Zd Zdedef fd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 de
ejee
ejejf  f fddZ  ZS )PersimmonDecoderLayerr    r   c                    sd   t    |j| _t||d| _t|| _tj|j|j	d| _
tj|j|j	d| _t|j| _d S )N)r    r   r   )r'   r(   rf   r   	self_attnrd   mlpr   r   r   input_layernormpost_attention_layernormr   hidden_dropoutru   r   r4   r6   r7   r(   0  s   

zPersimmonDecoderLayer.__init__NFrm   rs   rN   r   r   r   r   r   r~   r   c	                 K   s   |}
|  |}| jd||||||||d|	\}}}|
| }|}
| |}| |}| |}||
 }|f}|r>||f7 }|rE||f7 }|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.
        )rm   rs   rN   r   r   r   r   r   Nr6   )r   r   r   r   ru   )r2   rm   rs   rN   r   r   r   r   r   r~   residualself_attn_weightspresent_key_valueoutputsr6   r6   r7   rS   9  s4   $
	




zPersimmonDecoderLayer.forwardr   )rU   rV   rW   r   r   r(   rG   r   r   r   r   r   r   r   FloatTensorrS   rY   r6   r6   r4   r7   r   /  s<    	
r   c                   @   sB   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d ZdS )PersimmonPreTrainedModelmodelTr   past_key_valuesc                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rC|jjjd|d |jd urA|jj|j 	  d S d S t|tjrX|jjd |jj	  d S d S )Nrn   )meanstdg      ?)r    initializer_rangerE   r   re   weightdatanormal_r   zero_	Embeddingpadding_idxr   fill_)r2   ro   r   r6   r6   r7   _init_weights  s   

z&PersimmonPreTrainedModel._init_weightsN)rU   rV   rW   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_sdpa_supports_flash_attn_2_supports_attention_backendr   r6   r6   r6   r7   r     s    r   c                       s  e Zd ZdZdef fddZdd Zdd Z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 de
e de
e de
ej dee defddZ	d#deejdf dejdejdedef
ddZedejdededejdejdefd d!Z  ZS )$PersimmonModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PersimmonDecoderLayer`]

    Args:
        config: PersimmonConfig
    r    c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _tj j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r6   )r   ).0r   r   r6   r7   
<listcomp>  s    z+PersimmonModel.__init__.<locals>.<listcomp>r   r   F)r'   r(   pad_token_idr   
vocab_sizer   r   rf   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   final_layernormr   r   gradient_checkpointing	post_initrl   r4   r   r7   r(     s   zPersimmonModel.__init__c                 C      | j S rT   r   r2   r6   r6   r7   get_input_embeddings     z#PersimmonModel.get_input_embeddingsc                 C   
   || _ d S rT   r   r2   rr   r6   r6   r7   set_input_embeddings     
z#PersimmonModel.set_input_embeddingsN	input_idsrs   rN   r   inputs_embedsr   r   output_hidden_statesr   r~   r   c
                 K   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u |d uA r*td| jr9| jr9|r9td d}d}|rVt	|t
sVd}|d u rLt }n
t|}td |d u r_| |}|	d u r{|d urk| nd}tj|||jd  |jd}	|d u r|	d}| |||	||}|}| ||}|rd	nd }|rd	nd }d }| jD ]0}|r||f7 }||f||||||	|d
|
}|d }|r||rdnd }|r||d f7 }q| |}|r||f7 }|r|nd }|r| }t||||d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   r3   r6   )rs   rN   r   r   r   r   r   r=   )last_hidden_stater   rm   
attentions)r    r   r  r   r   r   rx   r   r   rE   r   r	   from_legacy_cacher   get_seq_lengthrG   arangerC   r3   r]   _update_causal_maskr   r   r   to_legacy_cacher   )r2   r   rs   rN   r   r   r   r   r  r   r~   return_legacy_cachepast_seen_tokensr   rm   r   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_cacher6   r6   r7   rS     s   





	

zPersimmonModel.forwardFr   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )Nflash_attention_2rn   flex_attentionr   Fsdpa)r   past_key_values_lengthis_trainingr   r8   )sequence_lengthtarget_lengthr@   r   r   )cudaxpunpu)r    r   anyrE   rG   r   r   r  is_compileabler   _ignore_causal_mask_sdparx   r@   rC   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr3   r#   finfomin_unmask_unattended)r2   rs   r  r   r   r   r  using_compilable_cacher@   r  r  r   	min_dtyper6   r6   r7   r  /  sT   




z"PersimmonModel._update_causal_maskr  r  r@   r   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer@   r3   r   )diagonalr  r8   r   )r?   rG   r"  r#  fullr3   triur  r   rB   clonerC   rD   masked_fill)rs   r  r  r@   r   r   r~   r   r&  mask_lengthpadding_maskr6   r6   r7   r!  s  s,    $
6  zDPersimmonModel._prepare_4d_causal_attention_mask_with_cache_position	NNNNNNNNN)F)rU   rV   rW   r   r   r(   r   r   r   r   r   rG   r   r   listr   r   r   r   r   rS   r   r   r  staticmethodr   r@   r!  rY   r6   r6   r4   r7   r     s    	
t
Dr   c                       s   e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
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j deeejf defddZ  ZS )!PersimmonForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S NFr   )
r'   r(   r   r   r   r   re   rf   lm_headr   rl   r4   r6   r7   r(     s
   
zPersimmonForCausalLM.__init__c                 C      | j jS rT   r   r   r   r6   r6   r7   r        z)PersimmonForCausalLM.get_input_embeddingsc                 C      || j _d S rT   r7  r   r6   r6   r7   r        z)PersimmonForCausalLM.set_input_embeddingsc                 C   r   rT   r5  r   r6   r6   r7   get_output_embeddings  r   z*PersimmonForCausalLM.get_output_embeddingsc                 C   r   rT   r;  )r2   new_embeddingsr6   r6   r7   set_output_embeddings  r   z*PersimmonForCausalLM.set_output_embeddingsc                 C   r   rT   r   )r2   decoderr6   r6   r7   set_decoder  r   z PersimmonForCausalLM.set_decoderc                 C   r   rT   r?  r   r6   r6   r7   get_decoder  r   z PersimmonForCausalLM.get_decoderNr   r   rs   rN   r   r   labelsr   r   r  r   logits_to_keepr   c                 K   s   |dur|n| j j}|	dur|	n| j j}	| jd||||||||	|
d	|}|j}t|tr4t| dn|}| |dd|ddf }d}|durX| j	||fd| j j
i|}t|||j|j|jdS )uk  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, 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   rs   rN   r   r   r   r   r  r   r   losslogitsr   rm   r  r6   )r    r   r  r   r  rE   r   slicer5  loss_functionr   r   r   rm   r  )r2   r   rs   rN   r   r   rC  r   r   r  r   rD  r~   r   rm   slice_indicesrG  rF  r6   r6   r7   rS     sH   (
zPersimmonForCausalLM.forward)NNNNNNNNNNr   )rU   rV   rW   _tied_weights_keysr(   r   r   r<  r>  rA  rB  r   r   r   rG   r   r   r1  r   r   r   r   r   rS   rY   r6   r6   r4   r7   r3    s^    
	
r3  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).
    )custom_introc                          e Zd Z fddZdd Zdd Zee									ddee	j
 d	ee	j d
ee	j
 dee dee	j dee	j
 dee dee dee defddZ  ZS )"PersimmonForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r4  )
r'   r(   
num_labelsr   r   r   re   rf   scorer   rl   r4   r6   r7   r(   3  s
   
z+PersimmonForSequenceClassification.__init__c                 C   r6  rT   r7  r   r6   r6   r7   r   <  r8  z7PersimmonForSequenceClassification.get_input_embeddingsc                 C   r9  rT   r7  r   r6   r6   r7   r   ?  r:  z7PersimmonForSequenceClassification.set_input_embeddingsNr   rs   rN   r   r   rC  r   r   r  r   c
              
   C   s(  | j ||||||||	d}
|
j}| |}|dur|jd }n|jd }| jjdu r2|dkr2td| jjdu r;d}n1|dur`|| jjk|jt	j
}t	j|jd |jt	j
d}|| d}nd}t| jj d |t	j||jd	|f }d}|dur| j|||| jd
}t|||
j|
j|
jd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).
        rs   rN   r   r   r   r   r  Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r8   )r3   r@   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r  )rG  rC  pooled_logitsr    rE  )r   r  rP  rC   r    r   r   rD   r3   rG   int32r  argmaxr   r   r5   rU   rI  r   r   rm   r  )r2   r   rs   rN   r   r   rC  r   r   r  transformer_outputsrm   rG  r   last_non_pad_tokennon_pad_masktoken_indicesrS  rF  r6   r6   r7   rS   B  sL   


z*PersimmonForSequenceClassification.forwardr0  )rU   rV   rW   r(   r   r   r   r   r   rG   r   r   r   r   r   r   rS   rY   r6   r6   r4   r7   rN  #  sH    		
rN  c                       rM  )PersimmonForTokenClassificationc                    s|   t  | |j| _t|| _t|dd d ur|j}nt|dd d ur'|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropoutr   g?)r'   r(   rO  r   r   getattrr[  r   r   r   ru   re   rf   rP  r   )r2   r    r[  r4   r6   r7   r(     s   
z(PersimmonForTokenClassification.__init__c                 C   r6  rT   r7  r   r6   r6   r7   r     r8  z4PersimmonForTokenClassification.get_input_embeddingsc                 C   r9  rT   r7  r   r6   r6   r7   r     r:  z4PersimmonForTokenClassification.set_input_embeddingsNr   rs   rN   r   r   rC  r   r   r  r   c
              
   C   sd   | j ||||||||	d}
|
j}| |}| |}d}|dur(| ||| j}t|||
j|
jdS )rQ  rR  N)rF  rG  rm   r  )	r   r  ru   rP  rI  r    r   rm   r  )r2   r   rs   rN   r   r   rC  r   r   r  r   sequence_outputrG  rF  r6   r6   r7   rS     s,   


z'PersimmonForTokenClassification.forwardr0  )rU   rV   rW   r(   r   r   r   r   r   rG   r   r   r   r   r   r   rS   rY   r6   r6   r4   r7   rZ    sH    	
rZ  )r3  r   r   rN  rZ  )Nr   )rn   )@r   typingr   r   r   rG   torch.utils.checkpointr   activationsr   cache_utilsr   r	   
generationr
   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   configuration_persimmonr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerrU   r   Moduler   r\   rc   rd   r   rA   r   r   r   r   r   r3  rN  rZ  __all__r6   r6   r6   r7   <module>   st   
#

 S  wVF