
     `i                     >   d Z ddlZddl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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 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            rddlm,Z,  e#j-        e.          Z/ G d dej0                  Z1d Z2d6dZ3 G d dej0                  Z4 G d dej0                  Z5dej6        de7d ej6        fd!Z8 G d" d#ej0                  Z9 G d$ d%e9          Z: G d& d'e9          Z;e9e:e;d(Z< G d) d*e          Z=e  G d+ d,e                      Z>e  G d- d.e>                      Z? G d/ d0e>e          Z@ G d1 d2ee>          ZA G d3 d4ee>          ZBg d5ZCdS )7zPyTorch StableLM model.    N)OptionalUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available) GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)deprecate_kwarg   )StableLmConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forwardc                   |     e Zd ZU ej        ed<   ddef fdZ ej                    e	d                         Z
 xZS )StableLmRotaryEmbedding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/stablelm/modeling_stablelm.pyr+   z StableLmRotaryEmbedding.__init__B   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tor8   r-   r'   strtorchautocast	transposecatcosr4   sinrE   )
r7   xposition_idsinv_freq_expandedposition_ids_expandedr@   freqsembrO   rP   s
             r:   forwardzStableLmRotaryEmbedding.forwardS   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__rK   Tensor__annotations__r   r+   no_gradr   rW   __classcell__r9   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=   rB   rC   )rH   rK   rN   )rQ   x1x2s      r:   rotate_halfrd   d   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.
    )	unsqueezerd   )qkrO   rP   rR   unsqueeze_dimq_embedk_embeds           r:   apply_rotary_pos_embrl   l   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 )StableLmMLPc                    t                                                       || _        |j        | _        |j        | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _	        t          |j                 | _        d S NFbias)r*   r+   r#   hidden_sizeintermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnr7   r#   r9   s     r:   r+   zStableLmMLP.__init__   s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV./r;   c                     |                      |                     |                     |                    |                     |          z            }|S rX   )rx   rz   rv   rw   )r7   rQ   rx   s      r:   rW   zStableLmMLP.forward   sA    NN4;;t~~a/@/@#A#ADLLQROO#STT	r;   )rY   rZ   r[   r+   rW   r_   r`   s   @r:   rn   rn      sG        0 0 0 0 0      r;   rn   c                   6     e Zd Zd fd	Zdej        fdZ xZS )StableLmLayerNormPerHeadh㈵>Fc                     t                                                       | _        || _        t	          j        fdt          | j                  D                       | _        d S )Nc                 >    g | ]}t          j                   S ))epsrr   )r   	LayerNorm).0_rr   rD   r   s     r:   
<listcomp>z5StableLmLayerNormPerHead.__init__.<locals>.<listcomp>   s*    #i#i#iaBL#D$I$I$I#i#i#ir;   )r*   r+   rD   	num_headsr   
ModuleListrangenorms)r7   rD   r   r   rr   r9   s    ` ``r:   r+   z!StableLmLayerNormPerHead.__init__   sg    "]#i#i#i#i#i#iSXY]YgShSh#i#i#ijj


r;   hidden_statesc                     t          j        |dd          }t          j        d t          | j        |          D             d          S )Nr   rC   c                 *    g | ]\  }} ||          S  r   )r   normr   s      r:   r   z4StableLmLayerNormPerHead.forward.<locals>.<listcomp>   s'    kkk2E$$$}--kkkr;   )rK   splitrN   zipr   )r7   r   states_per_headss      r:   rW   z StableLmLayerNormPerHead.forward   sM     !;}aQ???ykkTZYiIjIjkkkqrssssr;   )r   F)rY   rZ   r[   r+   rK   r\   rW   r_   r`   s   @r:   r~   r~      si        k k k k k ktU\ t t t t t t t tr;   r~   r   n_repreturnc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||z  ||          S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rH   rG   reshape)r   r   batchnum_key_value_headsslenhead_dims         r:   	repeat_kvr      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr;   c                   z    e Zd ZdZddede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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 )StableLmAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr#   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _
        | j        | j
        z  | _        |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        | j
        | j        z  |j                  | _        t)          j        | j        | j        | j        z  |j                  | _        t)          j        | j        | j        | j        z  |j                  | _        t)          j        | j        | j        d          | _        |j        | _        | j        rLt9          | j        | j
        |j        	          | _        t9          | j        | j        |j        	          | _        t)          j         |j!                  | _!        tE          | 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).rq   Fr   r#   )$r*   r+   r#   r   loggerwarning_oncer9   rY   rs   num_attention_headsr   r   r   num_key_value_groups
rope_thetaintpartial_rotary_factorrotary_ndims	is_causal
ValueErrorr   ru   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r7   r#   r   r9   s      r:   r+   zStableLmAttention.__init__   sF   ",!8 , , ,   "-3(DN:#)#= $(Nd6N$N! +0L LMMMDN*t/???8RVRb 8 8%)^8 8 8   i 0$.4=2PW]Wjkkki 0$2JT]2Zagatuuui 0$2JT]2Zagatuuui 0$2BOOO"/ 	7t~[a[pqqqD7t7V=R     D "$F,D!E!E1EEEr;   past_key_valuepast_key_values4.58new_nameversionFr   attention_maskrR   output_attentions	use_cachecache_positionposition_embeddingsr   c	                 H   |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }| j	        r*| 
                    |          }|                     |          }|\  }}|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                  }t%          || j                  }t          j        ||                    dd                    t+          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z  }t0          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   rB   .r=   rC   rP   rO   partial_rotation_sizer   r   )rE   rD   z `attn_output` should be of size z	, but is )$sizer   r   r   viewr   r   rM   r   r   r   r   r   rl   rK   rN   updater   r   r   matmulmathsqrtrH   r   
functionalsoftmaxfloat32rI   rE   r   r   
contiguousr   rs   r   )r7   r   r   rR   r   r   r   r   r   bszq_lenr   query_states
key_statesvalue_statesrO   rP   	query_rot
query_passkey_rotkey_passcache_kwargsattn_weightscausal_maskattn_outputs                            r:   rW   zStableLmAttention.forward   s    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm 	6++L99L))*55J&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 z4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIKK'L },,\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kk+..  	 LL((r;   rX   NNNFFNN)rY   rZ   r[   __doc__r   r   r   r+   r   rK   r\   
LongTensorr   booltuplerW   r_   r`   s   @r:   r   r      sp       GG&F &F~ &F(3- &F &F &F &F &F &FP _%0A6RRR 2637+/"'59KOS) S)|S) !.S) u/0	S)
 "%S)  S) S) !!12S) &eEL%,,F&GHS) 
u|Xel3XeEL>Q5RR	SS) S) S) SRS) S) S) S) S)r;   r   c                   X    e Z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j        eej                 ee
ej                          f         f fd            Z xZS )StableLmSdpaAttentionr   r   r   r   NFr   r   rR   r   r   r   r   r   c	           
         |rCt                               d           t                                          ||||||||          S |                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j	        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }| j        r*|                     |          }|                     |          }|\  }}|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                  }t-          || j                  }|}||d d d d d d d |j        d	         f         }|j        j        d
k    r>|<|                                }|                                }|                                }t9          |d u o|
dk              }t$          j        j                            ||||| j         r| j!        j"        n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.r   r   rR   r   r   r   r   r   r   rB   .r=   rC   r   r   cuda        )	attn_mask	dropout_pr   )%r   r   r*   rW   r   r   r   r   r   r   r   rM   r   r   r   r   r   rl   rK   rN   r   r   r   r   rH   r8   r'   r   r   r   r   scaled_dot_product_attentiontrainingr   prs   r   )r7   r   r   rR   r   r   r   r   r   r   r   r   r   r   r   rO   rP   r   r   r   r   r   r   r   r   r9   s                            r:   rW   zStableLmSdpaAttention.forward7  s     	[   77??+-) /"3#-$7 # 	 	 	 &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm 	6++L99L))*55J&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 z4+DEE
 t/HII$%(AAAqqq2HJ4DR4H2H)HIK #v--.2L'2244L#..00J'2244L
 ,:;;	h)FF!26-Hd,..S G 
 
 "++Aq11<<>>!&&sE43CDDkk+..D  r;   r   )rY   rZ   r[   r   rK   r\   r   r   r   r   r   rW   r_   r`   s   @r:   r   r   6  s5       _%0A6RRR 2637+/"'59KOh! h!|h! !.h! u/0	h!
 "%h!  h! h! !!12h! &eEL%,,F&GHh! 
u|Xel3XeEL>Q5RR	Sh! h! h! h! h! SRh! h! h! h! h!r;   r   c                   b    e Zd ZdZ 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j        eej                 eeej                          f         fd            Z x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                 `     t                      j        |i | t                      | _        d S rX   )r*   r+   r   _flash_attn_uses_top_left_mask)r7   argskwargsr9   s      r:   r+   z StableLmFlashAttention2.__init__  s6    $)&)))
 /P.Q.Q+++r;   r   r   r   r   NFr   r   rR   r   r   r   r   r   c	                 Z   d}|                                 \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }| j	        r*| 
                    |          }|                     |          }|\  }}|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        |          \  }}|                    dd          }|                    dd          }|                    dd          }| j        r| j        j        nd}t+          |||||||| j        | j        		  	        }|                    |
|| j                                                  }|                     |          }|sd }||fS )
NFr   rB   .r=   rC   r   r   )rR   dropoutuse_top_left_maskr   )r   r   r   r   r   r   r   rM   r   r   r   r   r   rl   rK   rN   r   r   r   r   r   r   r   r   r   rs   r   r   )r7   r   r   rR   r   r   r   r   r   r   r   r   r   r   r   r   rO   rP   r   r   r   r   r   dropout_rater   r   s                             r:   rW   zStableLmFlashAttention2.forward  s    "%**,,UA{{=11[[//
{{=11
 $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm 	6++L99L))*55J&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 $--a33))!Q//
#--a3337=It-//c.% "An

 

 

 "))#ud6FGGRRTTkk+..  	 LL((r;   r   )rY   rZ   r[   r   r+   r   rK   r\   r   r   r   r   r   rW   r_   r`   s   @r:   r   r     sT        R R R R R _%0A6RRR 6:37+/"'59KOU) U)|U) !!12U) u/0	U)
 "%U)  U) U) !!12U) &eEL%,,F&GHU) 
u|Xel3XeEL>Q5RR	SU) U) U) SRU) U) U) U) U)r;   r   )eagersdpaflash_attention_2c                   N    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
         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 )StableLmDecoderLayerr#   r   c                    t                                                       |j        | _        |j        | _        t	          |j                 ||          | _        t          |          | _        t          j
        |j        |j                  | _        d | _        | j        s%t          j
        |j        |j                  | _        t          j        |j                  | _        d S )N)r   r   )r*   r+   use_parallel_residualrs   ATTENTION_CLASSES_attn_implementation	self_attnrn   mlpr   r   r   input_layernormpost_attention_layernormr   hidden_dropoutr   r   s      r:   r+   zStableLmDecoderLayer.__init__  s    %+%A"!-*6+FGZcdddv&&!|F,>FDYZZZ(,%) 	h,.L9KQWQf,g,g,gD)z&"788r;   NFr   r   rR   r   r   r   r   r   r   c	           
         |}	|                      |          }|                     ||||||||          \  }
}| j        r3|                     |          }|                     |          }|	|
z   |z   }nG|	|
z   }	|                     |                     |	                    }|                     |          }|	|z   }|f}|r||fz  }|S )ao  
        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.
        r   )r  r  r   r  r   r  )r7   r   r   rR   r   r   r   r   r   residualself_attn_outputself_attn_weights
mlp_outputoutputss                 r:   rW   zStableLmDecoderLayer.forward  s   H !,,];; /3nn')%+/) 3 /= 	/
 	/
++ % 	2 -00Jj11J$'77*DMM  "22H$"?"?"I"IJJJj11J$z1M " 	,)++Gr;   r   )rY   rZ   r[   r   r   r+   rK   r\   r   r   r   r   r   FloatTensorrW   r_   r`   s   @r:   r   r     s?       
9~ 
9# 
9 
9 
9 
9 
9 
9 2637+/,1$)59KOI I|I !.I u/0	I
 "%I $D>I D>I !!12I &eEL%,,F&GHI 
u (51BEDU1U+V"WW	XI I I I I I I Ir;   r   c                   >    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S )StableLmPreTrainedModelr#   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   ru   weightdatanormal_rr   zero_	Embeddingpadding_idxr   fill_)r7   moduler  s      r:   _init_weightsz%StableLmPreTrainedModel._init_weightsw  s'   k+fbi(( 
	%M&&CS&999{& &&((((( '&-- 	%M&&CS&999!-"6#56<<>>>>> .--- 	%M$$S)))K""$$$$$	% 	%r;   N)rY   rZ   r[   r   r]   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraphr  r   r;   r:   r  r  k  s]         &*#/0"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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 )StableLmModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`StableLmDecoderLayer`]

    Args:
        config: StableLmConfig
    r#   c                     t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        t          j        j        j                  | _        t!                    | _        j        | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r   )r   )r   r   r#   s     r:   r   z*StableLmModel.__init__.<locals>.<listcomp>  s$    fff!&)44fffr;   r   r   F)r*   r+   pad_token_idr  
vocab_sizer   r  rs   embed_tokensr   r   num_hidden_layerslayersr   r   r   r!   r   r  gradient_checkpointing	post_initr{   s    `r:   r+   zStableLmModel.__init__  s       !. +L):F<NPTP`aamffffeFLdFeFefff
 
 L!39NOOO	1@@@$*$?!&+#r;   N	input_idsr   rR   r   inputs_embedsr   r   output_hidden_statesr   r   c
                 P   ||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 ]3}|r||fz  } ||||||||	|	          }|d         }|r||d         fz  }4|                     |          }|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   r8   r   )r   rR   r   r   r   r   r   )last_hidden_stater   r   
attentions)r#   r   r2  r   r   r.  r   r   r   r	   r+  get_seq_lengthrK   arangerH   r8   rf   _update_causal_maskr   r-  r   r   )r7   r0  r   rR   r   r1  r   r   r2  r   past_seen_tokensr   r   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                     r:   rW   zStableLmModel.forward  sy    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		-00   	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 )Nr   r   flex_attentionr   Fr   )r1  past_key_values_lengthis_trainingr   r=   )sequence_lengthtarget_lengthrE   r   
batch_size)r   xpunpu)r#   r  anyr-   rK   r\   r   r7  is_compileabler   _ignore_causal_mask_sdpar   rE   rH   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr8   r'   finfomin_unmask_unattended)r7   r   r?  r   r   r   r:  using_compilable_cacherE   rD  rE  r   	min_dtypes                r:   r9  z!StableLmModel._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;   rD  rE  rE   rF  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_valuerE   r8   r   )diagonalr4  r=   r   )rD   rK   rN  rO  fullr8   triur8  r   rG   clonerH   rI   masked_fill)r   rD  rE  rE   r   rF  r   r   rR  mask_lengthpadding_masks              r:   rM  zCStableLmModel._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)rY   rZ   r[   r   r   r+   r   r   r   rK   r   r\   r   r  r   r   rW   r   r9  staticmethodr   rE   rM  r_   r`   s   @r:   r&  r&    s        ~      "  151537+/59$(,0/359V
 V
E,-V
 !.V
 u/0	V

 "%V
   12V
 D>V
 $D>V
 'tnV
 !!12V
 
!V
 V
 V
 ^ V
~ #(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 )StableLmForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S rp   )
r*   r+   r&  r  r*  r   ru   rs   lm_headr/  r{   s     r:   r+   zStableLmForCausalLM.__init__}  sj       "6**
 +y!3V5FUSSS 	r;   Nr   r0  r   rR   r   r1  labelsr   r   r2  r   logits_to_keepr   c                    ||n| j         j        }|	|	n| j         j        }	|                     ||||||||	|
	  	        }|j        }t          |t                    rt          | d          n|}|                     |dd|ddf                   }d}| | j	        ||fd| j         j
        i|}t          |||j        |j        |j                  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)	r0  r   rR   r   r1  r   r   r2  r   r*  )losslogitsr   r   r6  )r#   r   r2  r  r5  r-   r   slicera  loss_functionr*  r   r   r   r6  )r7   r0  r   rR   r   r1  rb  r   r   r2  r   rc  r   r  r   slice_indicesrf  re  s                     r:   rW   zStableLmForCausalLM.forward  s5   R 2C1N--TXT_Tq$8$D  $+Jj 	
 ,0::)%+'/!5) ,6 
,
 
,
  18B>SV8W8Wk~ot444]kmAAA}aaa,?@AA%4%   ;1 	 D &#3!/)
 
 
 	
r;   )NNNNNNNNNNr   )rY   rZ   r[   _tied_weights_keysr+   r   r   r   rK   r   r\   r   r  r   r   r   r   rW   r_   r`   s   @r:   r_  r_  y  sj       *+      151537+/59-1$(,0/35934L
 L
E,-L
 !.L
 u/0	L

 "%L
   12L
 )*L
 D>L
 $D>L
 'tnL
 !!12L
 c5</0L
 
 L
 L
 L
 ^ L
 L
 L
 L
 L
r;   r_  c                       e Zd ZdS )!StableLmForSequenceClassificationNrY   rZ   r[   r   r;   r:   rl  rl              r;   rl  c                       e Zd ZdS )StableLmForTokenClassificationNrm  r   r;   r:   rp  rp    rn  r;   rp  )r_  r&  r  rl  rp  )Nr   )Dr   r   typingr   r   rK   r   activationsr   cache_utilsr   r	   
generationr
   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   r   r   utils.deprecationr   configuration_stablelmr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   r   
get_loggerrY   r   Moduler!   rd   rl   rn   r~   r\   r   r   r   r   r   r   r   r  r&  r_  rl  rp  __all__r   r;   r:   <module>r     s  (    " " " " " " " "        ! ! ! ! ! ! . . . . . . . . ) ) ) ) ) ) > > > > > > h h h h h h h h         
        L K K K K K K K - - - - - - \ \ \ \ \ \ \ \ \ \ \ \ 0 0 0 0 0 0 2 2 2 2 2 2  !! K;;;;;;JJJJJJ  KJJJJJJ 
	H	%	%!< !< !< !< !<bi !< !< !<J( ( (   8    ")    t t t t try t t t 	UU\ 	U# 	U%, 	U 	U 	U 	U) ) ) ) )	 ) ) )Dj! j! j! j! j!- j! j! j!Ze) e) e) e) e)/ e) e) e)R !0  V V V V V5 V V Vr % % % % %o % % %4 n n n n n+ n n nd\
 \
 \
 \
 \
1? \
 \
 \
~ h g g g g(HJa g g g b a a a a%BD[ a a a  r;   