o
    Zh5                     @   s<  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mZ ddlmZ dd	lmZ dd
lmZ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 ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& e# r}ddl'm(Z( ddl)m*Z* e rddlm+Z+ e$,e-Z.G dd de	j/Z0dd Z1d9ddZ2G dd de	j/Z3G dd de	j/Z4dej5de6d ej5fd!d"Z7G d#d$ d$e	j/Z8G d%d& d&e8Z9G d'd( d(e8Z:e8e9e:d)Z;G d*d+ d+e	j/Z<e!G d,d- d-eZ=e!G d.d/ d/e=Z>G d0d1 d1e=eZ?e!d2d3G d4d5 d5e=Z@e!G d6d7 d7e=ZAg d8ZBdS ):zPyTorch StableLM model.    N)ListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )StableLmConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forwardc                       s8   e Zd Zddef fddZe edd Z  Z	S )StableLmRotaryEmbeddingN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"   Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenr    r   Zrope_init_fnattention_scalingZregister_bufferr%   Zoriginal_inv_freq)selfr    devicer%   	__class__ ]/var/www/auris/lib/python3.10/site-packages/transformers/models/stablelm/modeling_stablelm.pyr(   =   s   
z StableLmRotaryEmbedding.__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   ZmpscpuF)device_typeenabled   dim)dtype)r%   floatexpandshapetor-   
isinstancer#   strtorchZautocast	transposecatcosr+   sinr9   )
r,   xposition_idsZinv_freq_expandedZposition_ids_expandedr4   ZfreqsZembrC   rD   r0   r0   r1   forwardN   s   0&zStableLmRotaryEmbedding.forwardN)
__name__
__module____qualname__r   r(   r@   Zno_gradr   rG   __classcell__r0   r0   r.   r1   r   <   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..Nr2   r6   r7   )r<   r@   rB   )rE   x1Zx2r0   r0   r1   rotate_half_   s   rN   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.
    )	unsqueezerN   )qkrC   rD   rF   Zunsqueeze_dimZq_embedZk_embedr0   r0   r1   apply_rotary_pos_embg   s
   

rR   c                       s$   e Zd Z fddZdd Z  ZS )StableLmMLPc                    sr   t    || _|j| _|j| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _	t
|j | _d S NFbias)r'   r(   r    hidden_sizeZintermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnr,   r    r.   r0   r1   r(      s   
zStableLmMLP.__init__c                 C   s$   |  | | || | }|S rH   )r[   r\   rY   rZ   )r,   rE   r[   r0   r0   r1   rG      s    zStableLmMLP.forward)rI   rJ   rK   r(   rG   rL   r0   r0   r.   r1   rS      s    
rS   c                       s.   e Zd Zd fdd	ZdejfddZ  ZS )	StableLmLayerNormPerHeadh㈵>Fc                    s>   t    | _|| _t fddt| jD | _d S )Nc                    s   g | ]
}t j d qS ))epsrV   )r   	LayerNorm).0_rV   r8   r`   r0   r1   
<listcomp>   s    z5StableLmLayerNormPerHead.__init__.<locals>.<listcomp>)r'   r(   r8   	num_headsr   
ModuleListrangenorms)r,   r8   rf   r`   rV   r.   rd   r1   r(      s   
(z!StableLmLayerNormPerHead.__init__hidden_statesc                 C   s0   t j|ddd}t jdd t| j|D ddS )Nr   r7   c                 S   s   g | ]\}}||qS r0   r0   )rb   normrj   r0   r0   r1   re      s    z4StableLmLayerNormPerHead.forward.<locals>.<listcomp>)r@   splitrB   zipri   )r,   rj   Zstates_per_headsr0   r0   r1   rG      s    z StableLmLayerNormPerHead.forward)r_   F)rI   rJ   rK   r(   r@   TensorrG   rL   r0   r0   r.   r1   r^      s    r^   rj   n_repreturnc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r<   r;   reshape)rj   ro   batchnum_key_value_headsslenhead_dimr0   r0   r1   	repeat_kv   s
   0rv   c                       s   e Zd ZdZddedee 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j	eej	 eeej	  f fddZ  ZS )StableLmAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr    	layer_idxc                    s~  t    || _|| _|d u rtd| jj d |j| _|j	| _
| j| j
 | _|j| _| j
| j | _|j| _t| j|j | _d| _| j| j
 | jkrZtd| j d| j
 dtj| j| j
| j |jd| _tj| j| j| j |jd| _tj| j| j| j |jd| _tj| j| jdd| _|j| _| jrt| j| j
|jd	| _t| j| j|j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).rU   Fr`   r    )$r'   r(   r    rx   loggerwarning_oncer/   rI   rW   Znum_attention_headsrf   ru   rs   num_key_value_groupsZ
rope_thetaintZpartial_rotary_factorrotary_ndims	is_causal
ValueErrorr   rX   Zuse_qkv_biasq_projk_projv_projo_projqk_layernormr^   layer_norm_epsq_layernormk_layernormDropoutattention_dropoutr   
rotary_embr,   r    rx   r.   r0   r1   r(      sB   

zStableLmAttention.__init__Frj   attention_maskrF   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsrp   c	                 C   sn  |  \}	}
}| |}| |}| |}||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}| j	rM| 
|}| |}|\}}|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}t|| j}t||ddt| j }|d ur|d d d d d d d |jd f }||7 }tjj|tjdd	|j}| |}t||}|  |	| j|
| jfkrtd
|	| j|
| jf d|   |dd  }|!|	|
| j"}| #|}|s2d }|||fS )Nr   r6   .r2   r7   rD   rC   Zpartial_rotation_sizer   r   )r9   r8   z `attn_output` should be of size z	, but is )$sizer   r   r   viewrf   ru   rA   rs   r   r   r   r   rR   r@   rB   updaterx   rv   r}   matmulmathsqrtr<   r   
functionalZsoftmaxZfloat32r=   r9   r   r   
contiguousrq   rW   r   )r,   rj   r   rF   r   r   r   r   r   bszq_lenrc   query_states
key_statesvalue_statesrC   rD   	query_rot
query_passkey_rotkey_passcache_kwargsattn_weightscausal_maskattn_outputr0   r0   r1   rG      s`   




 &


zStableLmAttention.forwardrH   NNNFFNN)rI   rJ   rK   __doc__r   r   r~   r(   r@   rn   
LongTensorr	   boolr   rG   rL   r0   r0   r.   r1   rw      s:    +	
rw   c                       s   e Zd Z							ddejdeej deej dee deded	eej d
ee	ejejf  de	ejeej ee	ej  f f fddZ
  ZS )StableLmSdpaAttentionNFrj   r   rF   r   r   r   r   r   rp   c	              
      sl  |rt d t j||||||||dS | \}	}
}| |}| |}| |}||	|
| j	| j
dd}||	|
| j| j
dd}||	|
| j| j
dd}| jrb| |}| |}|\}}|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}t|| j}|}|d ur|d d d d d d d |jd	 f }|jjd
kr|d ur| }| }| }|d u r|
dkrdnd}tjjj||||| jr| j j!nd|d}|dd }||	|
| j"}| #|}|d |fS )Na  StableLmModel is using StableLmSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rj   r   rF   r   r   r   r   r   r   r6   .r2   r7   r   r   cudaTF        )Z	attn_maskZ	dropout_pr   )$r{   r|   r'   rG   r   r   r   r   r   rf   ru   rA   rs   r   r   r   r   rR   r@   rB   r   rx   rv   r}   r<   r-   r#   r   r   r   Zscaled_dot_product_attentiontrainingr   prW   r   )r,   rj   r   rF   r   r   r   r   r   r   r   rc   r   r   r   rC   rD   r   r   r   r   r   r   r   r   r.   r0   r1   rG   1  s~   




&	

zStableLmSdpaAttention.forwardr   )rI   rJ   rK   r@   rn   r   r   r	   r   r   rG   rL   r0   r0   r.   r1   r   0  s6    	
r   c                       s   e Zd ZdZ 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jeej eeej  f fddZ  ZS )StableLmFlashAttention2aL  
    StableLM flash attention module. This module inherits from `StableLmAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|i | t | _d S rH   )r'   r(   r   _flash_attn_uses_top_left_mask)r,   argskwargsr.   r0   r1   r(     s   z StableLmFlashAttention2.__init__NFrj   r   rF   r   r   r   r   r   rp   c	                 K   s  d}|  \}
}}| |}| |}| |}||
|| j| jdd}||
|| j| jdd}||
|| j| jdd}| j	rO| 
|}| |}|\}}|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|\}}|dd}|dd}|dd}| jr| jjnd}t|||||||| j| jd		}||
|| j }| |}|sd }|||fS )
NFr   r6   .r2   r7   r   r   )rF   dropoutZuse_top_left_maskr   )r   r   r   r   r   rf   ru   rA   rs   r   r   r   r   rR   r@   rB   r   rx   r   r   r   r   r   r   rq   rW   r   r   )r,   rj   r   rF   r   r   r   r   r   r   r   r   rc   r   r   r   rC   rD   r   r   r   r   r   Zdropout_rater   r   r0   r0   r1   rG     s`   






zStableLmFlashAttention2.forwardr   )rI   rJ   rK   r   r(   r@   rn   r   r   r	   r   r   rG   rL   r0   r0   r.   r1   r     s:    	r   )eagersdpaflash_attention_2c                       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jee
ejejf  f fddZ  ZS )StableLmDecoderLayerr    rx   c                    s~   t    |j| _|j| _t|j ||d| _t|| _t	j
|j|jd| _d | _| js6t	j
|j|jd| _t	|j| _d S )N)rx   ry   )r'   r(   use_parallel_residualrW   ATTENTION_CLASSES_attn_implementation	self_attnrS   mlpr   ra   r   input_layernormpost_attention_layernormr   hidden_dropoutr   r   r.   r0   r1   r(     s   

zStableLmDecoderLayer.__init__NFrj   r   rF   r   r   r   r   r   rp   c	              
   C   s   |}	|  |}| j||||||||d\}
}}| jr+| |}| |}|	|
 | }n|	|
 }	| | |	}| |}|	| }|f}|rJ||f7 }|rQ||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.
        r   )r   r   r   r   r   r   )r,   rj   r   rF   r   r   r   r   r   ZresidualZself_attn_outputZself_attn_weightsZpresent_key_valueZ
mlp_outputoutputsr0   r0   r1   rG     s4   $





zStableLmDecoderLayer.forwardr   )rI   rJ   rK   r   r~   r(   r@   rn   r   r   r   r   FloatTensorrG   rL   r0   r0   r.   r1   r   
  s8    	
r   c                   @   s>   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d ZdS )StableLmPreTrainedModel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 )Nr   )meanstdg      ?)r    Zinitializer_ranger>   r   rX   weightdataZnormal_rV   Zzero_	Embeddingpadding_idxra   Zfill_)r,   moduler   r0   r0   r1   _init_weightss  s   

z%StableLmPreTrainedModel._init_weightsN)rI   rJ   rK   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_cache_classZ_supports_sdpaZ_supports_quantized_cacheZ_supports_static_cacher   r0   r0   r0   r1   r   f  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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 )#StableLmModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`StableLmDecoderLayer`]

    Args:
        config: StableLmConfig
    r    c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _tj j jd| _t d| _ j| _d| _|   d S )Nc                    s   g | ]}t  |qS r0   )r   )rb   rx   rz   r0   r1   re     s    z*StableLmModel.__init__.<locals>.<listcomp>ry   rz   F)r'   r(   pad_token_idr   
vocab_sizer   r   rW   embed_tokensrg   rh   Znum_hidden_layerslayersra   r   rk   r   r   r   gradient_checkpointing	post_initr]   r.   rz   r1   r(     s   zStableLmModel.__init__c                 C      | j S rH   r   r,   r0   r0   r1   get_input_embeddings     z"StableLmModel.get_input_embeddingsc                 C   
   || _ d S rH   r   r,   valuer0   r0   r1   set_input_embeddings     
z"StableLmModel.set_input_embeddingsN	input_idsr   rF   r   inputs_embedsr   r   output_hidden_statesr   rp   c
                 C   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 ]A}|r||f7 }| jr| jr| |j|||||||	|	}n||||||||	|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   r-   r0   )r   rF   r   r   r   r   r   r6   )last_hidden_stater   rj   
attentions)r    r   r   r   r   r   r   r{   r|   r>   r	   r
   Zfrom_legacy_cacher   get_seq_lengthr@   aranger<   r-   rO   _update_causal_maskr   r   Z_gradient_checkpointing_func__call__rk   Zto_legacy_cacher   )r,   r   r   rF   r   r   r   r   r   r   Zreturn_legacy_cachepast_seen_tokensr   rj   r   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheZdecoder_layerZlayer_outputsZ
next_cacher0   r0   r1   rG     s   







zStableLmModel.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 )Nr   r   Zflex_attentionr   Fr   )r   Zpast_key_values_lengthZis_trainingr   r2   )sequence_lengthtarget_lengthr9   r   
batch_size)r   ZxpuZnpu)r    r   anyr>   r@   rn   r   r   Zis_compileabler   Z_ignore_causal_mask_sdpar   r9   r<   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr-   r#   finfominZ_unmask_unattended)r,   r   r   r   r   r   r   Zusing_compilable_cacher9   r   r   r   	min_dtyper0   r0   r1   r     sT   




z!StableLmModel._update_causal_maskr   r   r9   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   )Z
fill_valuer9   r-   r   )Zdiagonalr   r2   r   )r8   r@   r   r   fullr-   Ztriur   rq   r;   cloner<   r=   Zmasked_fill)r   r   r   r9   r   r   r   r   r   Zmask_lengthZpadding_maskr0   r0   r1   r   a  s,    $
6  zCStableLmModel._prepare_4d_causal_attention_mask_with_cache_position	NNNNNNNNN)F)rI   rJ   rK   r   r   r(   r   r   r   r   r   r@   r   rn   r   r   r   r   rG   r   r	   r   staticmethodr~   r9   r   rL   r0   r0   r.   r1   r     s~    	

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 )!StableLmForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S rT   )
r'   r(   r   r   r   r   rX   rW   lm_headr   r]   r.   r0   r1   r(     s
   
zStableLmForCausalLM.__init__c                 C      | j jS rH   r   r   r   r0   r0   r1   r        z(StableLmForCausalLM.get_input_embeddingsc                 C      || j _d S rH   r   r   r0   r0   r1   r        z(StableLmForCausalLM.set_input_embeddingsc                 C   r   rH   r   r   r0   r0   r1   get_output_embeddings  r   z)StableLmForCausalLM.get_output_embeddingsc                 C   r   rH   r  )r,   Znew_embeddingsr0   r0   r1   set_output_embeddings  r   z)StableLmForCausalLM.set_output_embeddingsc                 C   r   rH   r   )r,   decoderr0   r0   r1   set_decoder  r   zStableLmForCausalLM.set_decoderc                 C   r   rH   r  r   r0   r0   r1   get_decoder  r   zStableLmForCausalLM.get_decoderNr   r   r   rF   r   r   labelsr   r   r   r   logits_to_keeprp   c                 K   s   |dur|n| j j}|	dur|	n| j j}	| j||||||||	|
d	}|j}t|tr0t| dn|}| |dd|ddf }d}|durT| j	||fd| j j
i|}t|||j|j|jdS )ui  
        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, StableLmForCausalLM

        >>> model = StableLmForCausalLM.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   rF   r   r   r   r   r   r   r   losslogitsr   rj   r   )r    r   r   r   r   r>   r~   slicer   loss_functionr   r   r   rj   r   )r,   r   r   rF   r   r   r  r   r   r   r   r  r   r   rj   Zslice_indicesr  r  r0   r0   r1   rG     sD   )zStableLmForCausalLM.forward)NNNNNNNNNNr   )rI   rJ   rK   Z_tied_weights_keysr(   r   r   r  r  r	  r
  r   r   r   r@   r   rn   r   r   r   r   r~   r   rG   rL   r0   r0   r.   r1   r     s^    
	
r   a  
    The StableLm transformer with a sequence classification head on top (linear layer).

    [`StableLmForSequenceClassification`] 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).
    )Z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 )!StableLmForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S rT   )
r'   r(   
num_labelsr   r   r   rX   rW   scorer   r]   r.   r0   r1   r(   "  s
   
z*StableLmForSequenceClassification.__init__c                 C   r   rH   r   r   r0   r0   r1   r   +  r  z6StableLmForSequenceClassification.get_input_embeddingsc                 C   r  rH   r   r   r0   r0   r1   r   .  r  z6StableLmForSequenceClassification.set_input_embeddingsNr   r   rF   r   r   r  r   r   r   rp   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).
        r   rF   r   r   r   r   r   Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r2   )r-   r9   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   )r  r  pooled_logitsr    r  )r   r   r  r<   r    r   r   r=   r-   r@   Zint32r   Zargmaxr{   r|   r/   rI   r  r   r   rj   r   )r,   r   r   rF   r   r   r  r   r   r   Ztransformer_outputsrj   r  r   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesr  r  r0   r0   r1   rG   1  sL   


z)StableLmForSequenceClassification.forwardr   )rI   rJ   rK   r(   r   r   r   r   r   r@   r   rn   r	   r   r   r   rG   rL   r0   r0   r.   r1   r    sH    		
r  c                       r  )StableLmForTokenClassificationc                    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(   r  r   r   getattrr  r   r   r   r   rX   rW   r  r   )r,   r    r  r.   r0   r1   r(   z  s   
z'StableLmForTokenClassification.__init__c                 C   r   rH   r   r   r0   r0   r1   r     r  z3StableLmForTokenClassification.get_input_embeddingsc                 C   r  rH   r   r   r0   r0   r1   r     r  z3StableLmForTokenClassification.set_input_embeddingsNr   r   rF   r   r   r  r   r   r   rp   c
              
   C   sd   | j ||||||||	d}
|
j}| |}| |}d}|dur(| ||| j}t|||
j|
jdS )r  r  N)r  r  rj   r   )	r   r   r   r  r  r    r   rj   r   )r,   r   r   rF   r   r   r  r   r   r   r   Zsequence_outputr  r  r0   r0   r1   rG     s,   


z&StableLmForTokenClassification.forwardr   )rI   rJ   rK   r(   r   r   r   r   r   r@   r   rn   r	   r   r   r   rG   rL   r0   r0   r.   r1   r  w  sH    	
r  )r   r   r   r  r  )Nr   )Cr   r   typingr   r   r   r   r@   Ztorch.utils.checkpointr   Zactivationsr   Zcache_utilsr	   r
   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   utilsr   r   r   r   Zconfiguration_stablelmr   Z!torch.nn.attention.flex_attentionr   Zintegrations.flex_attentionr   r   Z
get_loggerrI   r{   Moduler   rN   rR   rS   r^   rn   r~   rv   rw   r   r   r   r   r   r   r   r  r  __all__r0   r0   r0   r1   <module>   sf   
#
 lh\  wVF