
     `i                        d Z ddlmZmZm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mZmZ ddlmZmZ ddlmZmZ ddlmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z)  e$            rddl*m+Z+ ddl,m-Z-  e%j.        e/          Z0 G d dej1                  Z2d Z3d4dZ4 G d dej1                  Z5	 d5dej1        dej6        dej6        d ej6        d!eej6                 d"e7d#e7fd$Z8 G d% d&ej1                  Z9 G d' d(e          Z:e" G d) d*e                      Z;e" G d+ d,e;                      Z< G d- d.e;e          Z= G d/ d0ee;          Z> G d1 d2ee;          Z?g d3Z@dS )6zPyTorch Persimmon model.    )CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs) GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)deprecate_kwarg   )PersimmonConfig)	BlockMask)make_flex_block_causal_maskc                   |     e Zd ZU ej        ed<   ddef fdZ ej                    e	d                         Z
 xZS )PersimmonRotaryEmbeddinginv_freqNconfigc                    t                                                       t          |d          rSt          |j        t
                    r9|j                            d|j                            d                    | _        nd| _        |j        | _	        |j        | _
        || _        t          | j                 | _        |                     | j        |          \  }| _        |                     d|d           | j        | _        d S )Nrope_scaling	rope_typetypedefaultr#   F)
persistent)super__init__hasattr
isinstancer&   dict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__s       /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/persimmon/modeling_persimmon.pyr,   z!PersimmonRotaryEmbedding.__init__>   s    6>** 	'z&:Mt/T/T 	'#044[&BUBYBYZ`BaBabbDNN&DN"("@$*$B!/?+/+<+<T[&+Q+Q($(ZeDDD!%    c                 X   | j         d d d d f                                                             |j        d         dd                              |j                  }|d d d d d f                                         }t          |j        j        t                    r|j        j        dk    r|j        j        nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                | j        z  }|                                | j        z  }	d d d            n# 1 swxY w Y   |                    |j        
          |	                    |j        
          fS )Nr   r   mpscpuF)device_typeenabled   dim)dtype)r#   floatexpandshapetor9   r.   r(   strtorchautocast	transposecatcosr5   sinrF   )
r8   xposition_idsinv_freq_expandedposition_ids_expandedrA   freqsembrP   rQ   s
             r;   forwardz PersimmonRotaryEmbedding.forwardO   s    !M$4-8>>@@GGHZ[\H]_acdeehhijiqrr ,QQQaaaZ 8 > > @ @'1!(-'E'Ek!(-[`J`J`ahmmfk^UCCC 	5 	5&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))d44C''))d44C		5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 vvAGv$$cff17f&;&;;;s   BE++E/2E/N)__name__
__module____qualname__rL   Tensor__annotations__r   r,   no_gradr   rX   __classcell__r:   s   @r;   r"   r"   ;   s         l/ / / / / / / /" U]__< <  _< < < < <r<   r"   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..Nr>   rC   rD   )rI   rL   rO   )rR   x1x2s      r;   rotate_halfre   `   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.
    )	unsqueezere   )qkrP   rQ   rS   unsqueeze_dimq_embedk_embeds           r;   apply_rotary_pos_embrm   h   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 rY   )r+   r,   r   Linearhidden_sizeintermediate_sizedense_h_to_4hdense_4h_to_hr   
hidden_actactr8   r$   r:   s     r;   r,   zPersimmonMLP.__init__   s`    Yv'96;STTYv'?ASTT&+,r<   c                     |                      |          }|                     |          }|                     |          }|S rY   )rt   rw   ru   )r8   hidden_statess     r;   rX   zPersimmonMLP.forward   s?    **=99//**=99r<   )rZ   r[   r\   r,   rX   r`   ra   s   @r;   ro   ro      sG        - - - - -      r<   ro           modulequerykeyvalueattention_maskscalingdropoutc                    t          j        ||                    dd                    |z  }|$|d d d d d d d |j        d         f         }	||	z   }t          j                            |dt           j                                      |j	                  }t          j        
                    ||| j                  }t          j        ||          }
|
                    dd                                          }
|
|fS )NrC   r   r>   )rE   rF   )ptrainingr   )rL   matmulrN   rI   r   
functionalsoftmaxfloat32rJ   rF   r   r   
contiguous)r|   r}   r~   r   r   r   r   kwargsattn_weightscausal_maskattn_outputs              r;   eager_attention_forwardr      s     <s}}Q':':;;gEL!$QQQ111o	"o%=>#k1=((2U](SSVVW\WbccL=((6?([[L,|U33K''1--88::K$$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 ed	d
d          	 	 	 	 	 	 	 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            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        d	z  | _        | 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   biasg      )epselementwise_affiner$   ) r+   r,   r$   r   loggerwarning_oncer:   rZ   rr   num_attention_heads	num_headshead_dim
rope_thetaintpartial_rotary_factorrotary_ndims	is_causal
ValueErrorr   rq   query_key_valuedenseqk_layernormr   	LayerNormlayer_norm_epsq_layernormk_layernormDropoutattention_dropoutr"   
rotary_embr8   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[[[
"/}d* 	!|"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   rC   )rI   viewr   r   )r8   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<   past_key_valuepast_key_values4.58new_nameversionFrz   r   rS   output_attentions	use_cachecache_positionposition_embeddingsr   c	                    |                                 \  }
}}|                     |          }|                     |          \  }}}| 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          }t          j
        ||fd          }|,||| j        |d}|                    ||| j        |          \  }}t          }| j        j        dk    rt           | j        j                 } || ||||f| j        sdn| j        j        | j        d	|	\  }}|                    |
|d          }|                     |          }|sd }||fS )
Nr   rC   .r>   rD   )rQ   rP   partial_rotation_sizer   eagerr{   )r   r   )sizer   r   r   r   r   rN   r   rm   rL   rO   updater   r   r$   _attn_implementationr   r   r   r   reshaper   )r8   rz   r   rS   r   r   r   r   r   r   bszq_len_r   query_states
key_statesvalue_statesrP   rQ   	query_rot
query_passkey_rotkey_passcache_kwargsattention_interfacer   r   s                              r;   rX   zPersimmonAttention.forward   s    &**,,UA ((77	 483D3DY3O3O0z< 	6++L99L))*55J $--a33#--a33))!Q//
&S 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 (7'='=j,X\Xfht'u'u$J(?;+w66"9$+:Z"[$7$7	%
  $}OCC$+2OL	%
 	%
 	%
 	%
!\ "))#ub99jj--  	 LL((r<   rY   NNNFFNN)rZ   r[   r\   __doc__r   r   r   r,   rL   r]   tupler   r   
LongTensorr	   boolr   r   rX   r`   ra   s   @r;   r   r      s       GG$G $G $G8C= $G $G $G $G $G $GLPel PuU\5<Y^Ye=e7f P P P P  _%0A6RRR 2637+/"'59KON) N)|N) !.N) u/0	N)
 "%N)  N) N) !!12N) &eEL%,,F&GHN) -.N) 
u|Xel3XeEL>Q5RR	SN) N) N) SRN) N) N) N) N)r<   r   c                       e Zd Zdedef fdZ eddd          	 	 	 	 	 	 	 dd
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        ej        f                  dee         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,   rr   r   	self_attnro   mlpr   r   r   input_layernormpost_attention_layernormr   hidden_dropoutr   r   s      r;   r,   zPersimmonDecoderLayer.__init__5  s    !-+6YOOO''!|F,>FDYZZZ(*V5GVMb(c(c(c%z&"788r<   r   r   r   r   NFrz   r   rS   r   r   r   r   r   r   c	                    |}
|                      |          } | j        d||||||||d|	\  }}|
|z   }|}
|                     |          }|                     |          }|                     |          }||
z   }|f}|r||fz  }|S )an  
        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_values (`Cache`, *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.
        )rz   r   rS   r   r   r   r   r    )r   r   r   r   r   )r8   rz   r   rS   r   r   r   r   r   r   residualself_attn_weightsoutputss                r;   rX   zPersimmonDecoderLayer.forward>  s    J !,,];; ,:4> 
,
')%+/) 3
,
 
,
 
,
 
,
(( !=0 !55mDD//]33%0 " 	,)++Gr<   r   )rZ   r[   r\   r   r   r,   r   rL   r]   r   r   r	   r   r   r   r   FloatTensorrX   r`   ra   s   @r;   r   r   4  sq       9 93 9 9 9 9 9 9 _%0A6RRR 2637+/,1$)59KOC C|C !.C u/0	C
 "%C $D>C D>C !!12C &eEL%,,F&GHC -.C 
u (51BEDU1U+V"WW	XC C C SRC C C C Cr<   r   c                   B    e Zd ZU eed<   dZdZdgZdZdZ	dZ
dZdZd ZdS )PersimmonPreTrainedModelr$   modelTr   r   c                 v   | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rU|j        j                            d|           |j        +|j        j        |j                 	                                 d S d S t          |t          j                  r?|j        j                            d           |j        j        	                                 d S d S )Nr{   )meanstdg      ?)r$   initializer_ranger.   r   rq   weightdatanormal_r   zero_	Embeddingpadding_idxr   fill_)r8   r|   r   s      r;   _init_weightsz&PersimmonPreTrainedModel._init_weights  s'   k+fbi(( 
	%M&&CS&999{& &&((((( '&-- 	%M&&CS&999!-"6#56<<>>>>> .--- 	%M$$S)))K""$$$$$	% 	%r<   N)rZ   r[   r\   r   r^   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_can_compile_fullgraph_supports_sdpa_supports_flash_attn_supports_attention_backendr   r   r<   r;   r   r     sc         &*#01"3!N"&% % % % %r<   r   c                       e Zd ZdZdef f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         dee         dee         dee	j
                 dee         defd                        Z	 ddee	j        df         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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>  s$    ggg)"6955gggr<   r   r   F)r+   r,   pad_token_idr   
vocab_sizer   r   rr   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   final_layernormr"   r   gradient_checkpointing	post_initrx   s    `r;   r,   zPersimmonModel.__init__  s       !. +L):F<NPTP`aamgggguVMeGfGfggg
 
  "|F,>FDYZZZ2&AAA&+#r<   N	input_idsr   rS   r   inputs_embedsr   r   output_hidden_statesr   r   r   c
                 L   ||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}|r|t          | j                   }|| 
                    |          }|	B||                                nd}t          j        |||j        d         z   |j                  }	||	                    d          }|                     |||	||          }|}|                     ||          }|rdnd }|rdnd }| j        D ]1}|r||fz  } ||f||||||	|d	|
}|d         }|r||d         fz  }2|                     |          }|r||fz  }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`...Fr   r   r   r9   r   )r   rS   r   r   r   r   r   )last_hidden_stater   rz   
attentions)r$   r   r  r   r   r  r   r   r   r
   r  get_seq_lengthrL   arangerI   r9   rg   _update_causal_maskr   r  r  r   )r8   r  r   rS   r   r  r   r   r  r   r   past_seen_tokensr   rz   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r;   rX   zPersimmonModel.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	-t";< 	[YZZZ& 	"4= 	" "##p   "	 	?0*$+>>>O  --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!)M
*) /"3#-$7
 
 
 
M *!,M  6=#3"55,,];;   	2-!11&+++%	
 
 
 	
r<   Fr   input_tensorc           	      $   | j         j        dk    r||dk                                    r|S d S | j         j        dk    r+t          |t          j                  rt          |          }|S ||                                nd}||j        nd}| j         j        dk    r#|s!|st          j
        |||| j                  rd S |j        }|j        d         }	|r|                                }
n/t          |t          j                  r|j        d	         n||	z   dz   }
|                     ||	|
|||j        d         
          }| j         j        dk    r@|>|j        j        dv r0|s.t	          j        |          j        }t          j        ||          }|S )Nflash_attention_2r{   flex_attentionr   Fsdpa)r  past_key_values_lengthis_trainingr   r>   )sequence_lengthtarget_lengthrF   r   r   )cudaxpunpu)r$   r   anyr.   rL   r]   r    r  is_compileabler   _ignore_causal_mask_sdpar   rF   rI   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr9   r(   finfomin_unmask_unattended)r8   r   r  r   r   r   r  using_compilable_cacherF   r&  r'  r   	min_dtypes                r;   r  z"PersimmonModel._update_causal_mask  s    ;+/BBB)~/D.I.I.K.K)%%4;+/???.%,77 M!<^!L!L!!
 @O?Z?99;;;`aCRC^!?!?di ;+v55>T5]n5%>*'7 M	    t"&,Q/! 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*.DDD% E E**.I0CKQZ[[Kr<   r&  r'  rF   r   c                    | |                                  dk    r| }nMt          j        |          j        }t          j        ||f|||j                  }|dk    rt          j        |d          }|t          j        ||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                             |j                  z   }
|
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_valuerF   r9   r   )diagonalr  r>   r   )rE   rL   r0  r1  fullr9   triur  r   rH   clonerI   rJ   masked_fill)r   r&  r'  rF   r   r   r   r   r4  mask_lengthpadding_masks              r;   r/  zDPersimmonModel._prepare_4d_causal_attention_mask_with_cache_position\  s   > %.*<*<*>*>!*C*C(KKE**.I* -0Ye\j\q  K !###jqAAA5<n>STTTWeWmWmnprsWtWtttK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdDgDg&E E    ,q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r<   )	NNNNNNNNN)F)rZ   r[   r\   r   r   r,   r   r   r   rL   r   r]   r	   r   r   r   r   r   rX   r   r  staticmethodr   rF   r/  r`   ra   s   @r;   r  r    s              "  151537+/59$(,0/359X
 X
E,-X
 !.X
 u/0	X

 "%X
   12X
 D>X
 $D>X
 'tnX
 !!12X
 -.X
 
!X
 X
 X
 ^ X
B #(B BelK78B lB 	B
 B  B B B BH 444 4 {	4
 4 4 4 4 \4 4 4 4 4r<   r  c                   b    e Zd ZdgZ f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ej	                 deeej
        f         de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   rq   rr   lm_headr  rx   s     r;   r,   zPersimmonForCausalLM.__init__  sj       #F++
 +y!3V5FUSSS 	r<   Nr   r  r   rS   r   r  labelsr   r   r  r   logits_to_keepr   c                    ||n| j         j        }|	|	n| j         j        }	 | j        d||||||||	|
d	|}|j        }t          |t                    rt          | d          n|}|                     |dd|ddf                   }d}| | j	        ||fd| j         j
        i|}t          |||j        |j        |j                  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  r   rS   r   r  r   r   r  r   r  )losslogitsr   rz   r  r   )r$   r   r  r   r  r.   r   slicerC  loss_functionr  r   r   rz   r  )r8   r  r   rS   r   r  rD  r   r   r  r   rE  r   r   rz   slice_indicesrH  rG  s                     r;   rX   zPersimmonForCausalLM.forward  sD   P 2C1N--TXT_Tq$8$D  $+Jj 	
 ,64: ,
)%+'/!5),
 ,
 ,
 ,
  18B>SV8W8Wk~ot444]kmAAA}aaa,?@AA%4%   ;1 	 D &#3!/)
 
 
 	
r<   )NNNNNNNNNNr   )rZ   r[   r\   _tied_weights_keysr,   r   r   r   rL   r   r]   r	   r   r   r   r   r   rX   r`   ra   s   @r;   rA  rA    sj       *+      151537+/59-1$(,0/35934M
 M
E,-M
 !.M
 u/0	M

 "%M
   12M
 )*M
 D>M
 $D>M
 'tnM
 !!12M
 c5</0M
 
 M
 M
 M
 ^ M
 M
 M
 M
 M
r<   rA  c                       e Zd ZdS )"PersimmonForSequenceClassificationNrZ   r[   r\   r   r<   r;   rN  rN              r<   rN  c                       e Zd ZdS )PersimmonForTokenClassificationNrO  r   r<   r;   rR  rR    rP  r<   rR  )rA  r  r   rN  rR  )Nr   )r{   )Ar   typingr   r   r   rL   r   activationsr   cache_utilsr	   r
   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.deprecationr   configuration_persimmonr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr    
get_loggerrZ   r   Moduler"   re   rm   ro   r]   rG   r   r   r   r   r  rA  rN  rR  __all__r   r<   r;   <module>rf     s0  (   , , , , , , , , , ,        ! ! ! ! ! ! . . . . . . . . ) ) ) ) ) ) > > > > > > B B B B B B         
        L K K K K K K K F F F F F F F F & & & & & & \ \ \ \ \ \ \ \ \ \ \ \ 0 0 0 0 0 0 4 4 4 4 4 4  !! K;;;;;;JJJJJJ 
	H	%	%!< !< !< !< !<ry !< !< !<J( ( (   8    29   * % %I%<% 
% <	%
 U\*% % % % % %.H) H) H) H) H) H) H) H)VN N N N N6 N N Nb % % % % % % % %6 p p p p p- p p pf\
 \
 \
 \
 \
3_ \
 \
 \
~ j i i i i)IKc i i i d c c c c&CE] c c c  r<   