
    g                        d dl Z d dlmZmZmZmZ d dlZd dlmZ d dl	Zddl
mZ ddlmZmZmZ ddlmZ ddlmZ ddlmZmZmZmZ dd	lmZ dd
lmZmZ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%  G d dej&                  Z' G d dej&                  Z( G d dej&                  Z) e j*        e+          Z,d Z-d4dZ.dej/        de0dej/        fdZ1 G d dej&                  Z2 G d de2          Z3 G d de2          Z4e2e3e4d Z5 G d! d"ej&                  Z6d#Z7 ed$e7           G d% d&e                      Z8d'Z9d(Z: ed$e7           G d) d*e8                      Z; G d+ d,e8e          Z< ed-e7           G d. d/e8                      Z= ed0e7           G d1 d2e8                      Z>g d3Z?dS )5    N)ListOptionalTupleUnion   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )	GlmConfig)_flash_attention_forwardc                   ,     e Zd Zd fd	Zd Zd Z xZS )
GlmRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z9
        GlmRMSNorm is equivalent to T5LayerNorm
        N)super__init__nn	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      `/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/glm/modeling_glm.pyr!   zGlmRMSNorm.__init__:   sD     	l5:k#:#:;; #    c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )N   T)keepdim)	dtypetor$   float32powmeanrsqrtr'   r&   )r(   hidden_statesinput_dtypevariances       r,   forwardzGlmRMSNorm.forwardB   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r-   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler&   shaper'   r(   s    r,   
extra_reprzGlmRMSNorm.extra_reprI   s&    )**II$2GIIIr-   )r   )__name__
__module____qualname__r!   r;   r@   __classcell__r+   s   @r,   r   r   9   sb        $ $ $ $ $ $; ; ;J J J J J J Jr-   r   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )GlmRotaryEmbedding   '  Nc                 :   t                                                       || _        || _        || _        d| j        t          j        d| j        dt
          j                                                  | j        z  z  z  }| 	                    d|d           d S )Ng      ?r   r/   r2   inv_freqF)tensor
persistent)
r    r!   dimmax_position_embeddingsbaser$   arangeint64floatregister_buffer)r(   rO   rP   rQ   devicerL   r+   s         r,   r!   zGlmRotaryEmbedding.__init__N   s    '>$	$)Q!5;(W(W(W(](](_(_bfbj(jklZUKKKKKr-   c                 "   | j                             |j                   | j         d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                }	|                                }
d d d            n# 1 swxY w Y   |	                    |j        
          |
                    |j        
          fS )Nr   r0   r   mpscpuF)device_typeenabledr/   rO   rK   )rL   r3   rV   rT   expandr>   type
isinstancestrr$   autocast	transposecatcossinr2   )r(   xposition_idsseq_leninv_freq_expandedposition_ids_expandedrZ   freqsembrd   re   s              r,   r;   zGlmRotaryEmbedding.forwardX   s    	""" M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 vvAGv$$cff17f&;&;;;s   A>EEE)rH   rI   NN)rA   rB   rC   r!   r$   no_gradr;   rD   rE   s   @r,   rG   rG   M   sk        L L L L L L U]__< < < _< < < < <r-   rG   c                   B     e Zd Z fdZdej        dej        fdZ xZS )GlmMLPc                 "   t                                                       || _        t          j        |j        d|j        z  d          | _        t          j        |j        |j        d          | _        t          |j
                 | _        d S )Nr/   Fbias)r    r!   configr"   Linearr)   intermediate_sizegate_up_proj	down_projr   
hidden_actactivation_fnr(   rt   r+   s     r,   r!   zGlmMLP.__init__k   sz    If&8!f>V:V]bccc6#;V=OV[\\\#F$56r-   r8   returnc                     |                      |          }|                    dd          \  }}||                     |          z  }|                     |          S )Nr/   r0   r\   )rw   chunkrz   rx   )r(   r8   	up_statesgates       r,   r;   zGlmMLP.forwardt   sX    %%m44	#//!/44i 2 24 8 88	~~i(((r-   )rA   rB   rC   r!   r$   FloatTensorr;   rD   rE   s   @r,   rp   rp   j   s`        7 7 7 7 7)U%6 )5;L ) ) ) ) ) ) ) )r-   rp   c                     | ddddf         }| ddddf         }t          j        | |fd                              d          S )	z*Rotates half the hidden dims of the input..r   Nr/   r   r0   r\   )r$   stackflatten)rf   x1x2s      r,   rotate_halfr      sQ    	
319B	
319B;Ryb)))11"555r-   c                    |                     |          }|                     |          }|dd|j        d         dz  f                             dd          }|dd|j        d         dz  f                             dd          }| dd| j        d         dz  f         | d| j        d         dz  df         }} |dd|j        d         dz  f         |d|j        d         dz  df         }}| |z  t          |           |z  z   }||z  t          |          |z  z   }	t	          j        ||gd          }t	          j        |	|gd          }	||	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.
    .Nr0   r/   r\   )	unsqueezer>   repeat_interleaver   r$   rc   )
qkrd   re   rg   unsqueeze_dimq_passk_passq_embedk_embeds
             r,   apply_rotary_pos_embr      s   ( --
&
&C
--
&
&C c'SYr]a'''
(
:
:1"
:
E
EC
c'SYr]a'''
(
:
:1"
:
E
EC #))))*Ac172;!3C3E3E.E,FvA#))))*Ac172;!3C3E3E.E,FvA 3w;q>>C/0G3w;q>>C/0G i&)r222Gi&)r222GGr-   r8   n_repr|   c                     | 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)r>   r]   reshape)r8   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                   R    e Zd ZdZddedee         f fdZ	 	 	 	 	 	 	 ddej	        deej	                 d	eej
                 d
ee         dededeej
                 deeej	        ej	        f                  deej	        eej	                 eeej	                          f         fdZ xZS )GlmAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrt   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _	        |j
        | _        | j	        | j        z  | _        |j        | _        | j        | j        z  | _        d| _        dt!          j        | j                  z  | _        | 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	          | _        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.Tr   z?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).rr   F)r    r!   rt   r   loggerwarning_oncer+   rA   attention_dropoutr)   num_attention_heads	num_headsr   r   num_key_value_groups	is_causalmathsqrtscaling
ValueErrorr"   ru   attention_biasq_projk_projv_projo_projr(   rt   r   r+   s      r,   r!   zGlmAttention.__init__   s   ",!8 , , ,   "(!9!-3(DN:#)#= $(Nd6N$N!49T]333MDN*t/???8RVRb 8 8%)^8 8 8  
 i 0$.4=2PW]Wlmmmi 0$2JT]2Zagavwwwi 0$2JT]2Zagavwwwi 0$2BOOOr-   Fr8   attention_maskrg   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr|   c	                    |                                 \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|\  }}t          ||||          \  }}|&|||d}|
                    ||| j        |          \  }}t          || j                  }t          || j                  }t          j        ||                    dd                    | j        z  }|$|d d d d d d d |j        d         f         }||z   }t$          j                            |dt          j                                      |j                  }t$          j                            || j        | j                  }t          j        ||          }|                                 |
| j        || j        fk    r5t7          d	|
| j        || j        f d
|                                            |                    dd                                          }|                    |
|d          }|                     |          }|sd }|||fS )Nr   r/   re   rd   r   r   r   r0   )rO   r2   )ptrainingz `attn_output` should be of size z	, but is )sizer   r   r   viewr   r   rb   r   r   updater   r   r   r$   matmulr   r>   r"   
functionalsoftmaxr4   r3   r2   dropoutr   r   r   
contiguousr   )r(   r8   r   rg   r   r   r   r   r   kwargsbszq_len_query_states
key_statesvalue_statesrd   re   cache_kwargsattn_weightscausal_maskattn_outputs                         r,   r;   zGlmAttention.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&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTP\\%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!&&sE266kk+..  	 LL.88r-   rm   NNNFFNN)rA   rB   rC   __doc__r   r   intr!   r$   Tensor
LongTensorr	   boolr   r;   rD   rE   s   @r,   r   r      s=       GGP Py PXc] P P P P P PD 2637*."'59KO:9 :9|:9 !.:9 u/0	:9
 !:9  :9 :9 !!12:9 &eEL%,,F&GH:9 
u|Xel3XeEL>Q5RR	S:9 :9 :9 :9 :9 :9 :9 :9r-   r   c                   :    e Zd ZdZ fdZ	 	 	 	 	 	 	 ddej        deej                 deej                 dee	         d	e
d
e
deej                 deeej        ej        f                  deej        eej                 eeej                          f         fdZ xZS )GlmFlashAttention2aB  
    Glm flash attention module. This module inherits from `GlmAttention` 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                 b     t                      j        |i | t                       | _        d S rm   )r    r!   r   _flash_attn_uses_top_left_mask)r(   argsr   r+   s      r,   r!   zGlmFlashAttention2.__init__"  s9    $)&)))
 3V2W2W.W+++r-   NFr8   r   rg   r   r   r   r   r   r|   c	                    d}|                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|\  }}t          ||||          \  }}|&|||d}|
                    ||| j        |          \  }}|                    dd          }|                    dd          }|                    dd          }| j        r| j        nd}|j        }|t          j        k    rt          j                    rt          j                    }n3t'          | j        d          r| j        j        }n| j        j        j        }t.                              d| d           |                    |          }|                    |          }|                    |          }t5          |||||
||| j        t9          | d	d           | j        | j        
          }|                    |	|
d                                           }| !                    |          }|sd }|||fS )NFr   r/   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)rg   r   softmax_scaler   use_top_left_maskr   r0   )"r   r   r   r   r   r   r   rb   r   r   r   r   r   r   r2   r$   r4   is_autocast_enabledget_autocast_gpu_dtypehasattrrt   r   r&   r   r   r3   r   r   getattrr   r   r   r   r   )r(   r8   r   rg   r   r   r   r   r   r   r   r   r   r   r   rd   re   r   dropout_rater9   target_dtyper   r   s                          r,   r;   zGlmFlashAttention2.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&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J $--a33))!Q//
#--a3315Gt--C #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.% ,"4)94@@"An
 
 
 "))#ub99DDFFkk+..  	 LL.88r-   r   )rA   rB   rC   r   r!   r$   r   r   r   r	   r   r   r;   rD   rE   s   @r,   r   r     s3        X X X X X 6:37*."'59KOX9 X9|X9 !!12X9 u/0	X9
 !X9  X9 X9 !!12X9 &eEL%,,F&GHX9 
u|Xel3XeEL>Q5RR	SX9 X9 X9 X9 X9 X9 X9 X9r-   r   c                   4    e Zd 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Z xZS )GlmSdpaAttentionz
    Glm attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `GlmAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr8   r   rg   r   r   r   r   r   r|   c	           
         |rCt                               d           t                                          ||||||||          S |                                \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j	        | j
                                      dd          }|                    |
|| j        | j
                                      dd          }|                    |
|| j        | j
                                      dd          }|\  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t!          || j                  }t!          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||dk    rdnd	}t,          j        j                            ||||| j        r| j        nd
|| j                  }|                    dd                                          }|                    |
|d          }|                     |          }|d |fS )Na  GlmModel is using GlmSdpaAttention, 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.r8   r   rg   r   r   r   r   r   r   r/   r   r   cudaTFr   )	attn_mask	dropout_pr   scaler0   )r   r   r    r;   r   r   r   r   r   r   r   rb   r   r   r   r   r   r   r>   rV   r^   r   r$   r"   r   scaled_dot_product_attentionr   r   r   r   )r(   r8   r   rg   r   r   r   r   r   r   r   r   r   r   r   r   rd   re   r   r   r   r   r+   s                         r,   r;   zGlmSdpaAttention.forward  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&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!04Fd,,3, G 
 
 "++Aq11<<>>!&&sE266kk+..D.00r-   r   )rA   rB   rC   r   r$   r   r   r   r	   r   r   r;   rD   rE   s   @r,   r   r     s          2637*."'59KOP1 P1|P1 !.P1 u/0	P1
 !P1  P1 P1 !!12P1 &eEL%,,F&GHP1 
u|Xel3XeEL>Q5RR	SP1 P1 P1 P1 P1 P1 P1 P1 P1 P1r-   r   )eagerflash_attention_2sdpac                   \    e Zd Zddede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 )GlmDecoderLayerNrt   r   c                 J   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        d S )N)rt   r   r*   )r    r!   r)   GLM_ATTENTION_CLASSES_attn_implementation	self_attnrp   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr   s      r,   r!   zGlmDecoderLayer.__init__  s    !-.v/JKSYenooo&>>)&*<&BUVVV(263E6K^(_(_(_%%%r-   Fr8   r   rg   r   r   r   r   r   r|   c	                     |}
|                      |          } | j        d||||||||d|	\  }}}|
|z   }|}
|                     |          }|                     |          }|
|z   }|f}|r||fz  }|r||fz  }|S )a.  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            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`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            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.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r    )r   r   r   r   )r(   r8   r   rg   r   r   r   r   r   r   residualself_attn_weightspresent_key_valueoutputss                 r,   r;   zGlmDecoderLayer.forward  s    D !,,];; ?Mdn 
?
')%)/) 3
?
 
?
 
?
 
?
;(*; !=0 !55mDD// =0 " 	,)++G 	,)++Gr-   rm   r   )rA   rB   rC   r   r   r   r!   r$   r   r   r	   r   r   r   r;   rD   rE   s   @r,   r   r     sQ       ` `y `Xc] ` ` ` ` ` ` 2637*.,1$)59KOB B|B !.B u/0	B
 !B $D>B D>B !!12B &eEL%,,F&GHB 
u (51BEDU1U+V"WW	XB B B B B B B Br-   r   aH  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`GlmConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zQThe bare Glm Model outputting raw hidden-states without any specific head on top.c                   @    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZd ZdS )GlmPreTrainedModelmodelTr   past_key_valuesc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr   )r6   std)rt   initializer_ranger_   r"   ru   r&   datanormal_rs   zero_	Embeddingpadding_idx)r(   moduler  s      r,   _init_weightsz GlmPreTrainedModel._init_weightsX  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r-   N)rA   rB   rC   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacher  r   r-   r,   r  r  H  se        
 L&*#*+#4"5!N  $!	? 	? 	? 	? 	?r-   r  r   a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   
    e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 dde
j        dee
j                 d	ee
j                 d
eeeee
j                 f                  dee
j                 dee         dee         dee         dee         dee
j                 deeef         fd            Zde
j        de
j        de
j        d
edef
dZede
j        dedede
j        de
j        de
j        defd            Z xZS )GlmModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GlmDecoderLayer`]

    Args:
        config: GlmConfig
    rt   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        t          j        j                  | _        t!          j        dz  j        j                  | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r   )r   ).0r   rt   s     r,   
<listcomp>z%GlmModel.__init__.<locals>.<listcomp>  s#    aaaI_VY//aaar-   r   r/   )rO   rP   rQ   F)r    r!   pad_token_idr  
vocab_sizer"   r  r)   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   normrG   r   rP   
rope_theta
rotary_embgradient_checkpointing	post_initr{   s    `r,   r!   zGlmModel.__init__  s       !. +L):F<NPTP`aamaaaavG_A`A`aaa
 
 v1v7JKKK	,1$f>\cict
 
 
 ',# 	r-   c                     | j         S rm   r#  r?   s    r,   get_input_embeddingszGlmModel.get_input_embeddings  s      r-   c                     || _         d S rm   r.  r(   values     r,   set_input_embeddingszGlmModel.set_input_embeddings  s    !r-   N	input_idsr   rg   r  inputs_embedsr   r   output_hidden_statesreturn_dictr   r|   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|	|	n| j         j        }	|d u |d uz  rt          d          | j        r%| j        r|rt          	                    d           d}|| 
                    |          }d}|rVt          |t                    sAd}|t                      }n.t          j        |          }t          	                    d           |
B||                                nd}t!          j        |||j        d         z   |j                  }
||
                    d          }|                     |||
||          }|}|                     ||          }|rd	nd }|rd	nd }d }| j        D ]r}|r||fz  }| j        r*| j        r#|                     |j        |||||||
|	  	        }n ||||||||
|
          }|d         }|r||rdnd         }|r||d         fz  }s|                     |          }|r||fz  }|r|nd }|r|                                }|	st9          d ||||fD                       S t;          ||||          S )Nz:You must specify exactly one of input_ids or inputs_embedszX`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   rV   r   )r   rg   r   r   r   r   r   r/   c              3      K   | ]}||V  	d S rm   r   )r  vs     r,   	<genexpr>z#GlmModel.forward.<locals>.<genexpr>I  s(      ttqfgfsfsfsfsfsttr-   )last_hidden_stater  r8   
attentions)rt   r   r6  r   use_return_dictr   r+  r   r   r   r#  r_   r	   r
   from_legacy_cacheget_seq_lengthr$   rR   r>   rV   r   _update_causal_maskr*  r'  _gradient_checkpointing_func__call__r(  to_legacy_cacher=   r   )r(   r4  r   rg   r  r5  r   r   r6  r7  r   return_legacy_cachepast_seen_tokensr   r8   r   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                         r,   r;   zGlmModel.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M $ 
	Z?? 
	"&&"..."."@"Q"Q##^   !CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 
 & #oom\JJ #7@BBD0:d!![ "	6 "	6M# 6!m%55!* t}  $ A A!*! #%"'
! 
! !.!#.!-#2&7'#1(;	! 	! 	! *!,M R%28I3P11q%Q"  6=#3"55		-00   	2-!11+4>''$
 	6#3355J 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r-   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nr   r   r   r   )r5  past_key_values_lengthis_trainingr   r0   )sequence_lengthtarget_lengthr2   rV   r   
batch_sizer   )rt   r   rA  r_   r   r   _ignore_causal_mask_sdpar   r2   rV   r>   get_max_cache_shaper$   r   5_prepare_4d_causal_attention_mask_with_cache_positionr^   finfomin_unmask_unattended)r(   r   rN  r   r  r   rG  using_static_cacher2   rV   rR  rS  r   	min_dtypes                 r,   rB  zGlmModel._update_causal_maskQ  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr-   rR  rS  r2   rV   rT  c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer2   rV   r   )diagonalr9  r0   r   )rO   r$   rX  rY  fulltriurR   r   r]   cloner>   masked_fill)r   rR  rS  r2   rV   r   rT  r   r   r\  mask_lengthpadding_masks               r,   rW  z>GlmModel._prepare_4d_causal_attention_mask_with_cache_position  s   B %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r-   
NNNNNNNNNN)rA   rB   rC   r   r   r!   r/  r3  r   GLM_INPUTS_DOCSTRINGr$   r   r   r   r   r	   r   r   r   r   r   r;   rB  staticmethodr   r2   rV   rW  rD   rE   s   @r,   r  r    sE       
 y      $! ! !" " " +*+?@@ '+1537KO59$(,0/3&*59x
 x
#x
 !.x
 u/0	x

 "%tE4E/F(F"GHx
   12x
 D>x
 $D>x
 'tnx
 d^x
 !!12x
 
u--	.x
 x
 x
 A@x
t?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r-   r  c                       e Zd ZdgZdef fdZd Zd Zd Zd Z	d Z
d	 Z ee           eee
          	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deeeeej                 f                  deej                 deej                 dee         dee         dee         dee         deej                 dedeeef         fd                        Z xZS )GlmForCausalLMzlm_head.weightrt   c                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S NFrr   )
r    r!   r  r  r"  r"   ru   r)   lm_headr,  r{   s     r,   r!   zGlmForCausalLM.__init__  sj       f%%
 +y!3V5FUSSS 	r-   c                     | j         j        S rm   r  r#  r?   s    r,   r/  z#GlmForCausalLM.get_input_embeddings      z&&r-   c                     || j         _        d S rm   rp  r1  s     r,   r3  z#GlmForCausalLM.set_input_embeddings      "'
r-   c                     | j         S rm   rn  r?   s    r,   get_output_embeddingsz$GlmForCausalLM.get_output_embeddings  s
    |r-   c                     || _         d S rm   ru  )r(   new_embeddingss     r,   set_output_embeddingsz$GlmForCausalLM.set_output_embeddings  s    %r-   c                     || _         d S rm   r  )r(   decoders     r,   set_decoderzGlmForCausalLM.set_decoder  s    


r-   c                     | j         S rm   r{  r?   s    r,   get_decoderzGlmForCausalLM.get_decoder  s
    zr-   )output_typer  Nr   r4  r   rg   r  r5  labelsr   r   r6  r7  r   num_logits_to_keepr|   c                    ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
|                     ||||||||	|
|
  
        }|d         }|                     |dd| dddf                   }d}| | j        ||| j        fi |}|
s|f|dd         z   }||f|z   n|S t          |||j	        |j
        |j                  S )a  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, GlmForCausalLM

        >>> model = GlmForCausalLM.from_pretrained("google/glm-7b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/glm-7b")

        >>> prompt = "What is your favorite condiment?"
        >>> 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]
        "What is your favorite condiment?"
        ```N)
r4  r   rg   r  r5  r   r   r6  r7  r   r   r   losslogitsr  r8   r>  )rt   r   r6  r?  r  rn  loss_functionr"  r   r  r8   r>  )r(   r4  r   rg   r  r5  r  r   r   r6  r7  r   r  loss_kwargsr  r8   r  r  outputs                      r,   r;   zGlmForCausalLM.forward  sK   ` 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **)%+'/!5#)  
 
  
mAAA0B/B/C/CQQQ,FGHH%4%ffdoUUUUD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r-   )NNNNNNNNNNNr   )rA   rB   rC   _tied_weights_keysr   r!   r/  r3  rv  ry  r}  r  r   rh  r   r   _CONFIG_FOR_DOCr$   r   r   r   r   r	   r   r   r   r   r   r;   rD   rE   s   @r,   rk  rk    s       *+y      ' ' '( ( (  & & &     +*+?@@+AP_``` '+1537KO59-1$(,0/3&*59"#T
 T
#T
 !.T
 u/0	T

 "%tE4E/F(F"GHT
   12T
 )*T
 D>T
 $D>T
 'tnT
 d^T
 !!12T
  T
 
u,,	-T
 T
 T
 a` A@T
 T
 T
 T
 T
r-   rk  a  
    The Glm Model transformer with a sequence classification head on top (linear layer).

    [`GlmForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                   |    e Zd Zdef fdZd Zd Z ee          	 	 	 	 	 	 	 	 	 	 dde	e
j                 de	e
j                 de	e
j                 d	e	eeee
j                 f                  d
e	e
j                 de	e
j                 de	e         de	e         de	e         de	e         deeef         fd            Z xZS )GlmForSequenceClassificationrt   c                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S rm  )
r    r!   
num_labelsr  r  r"   ru   r)   scorer,  r{   s     r,   r!   z%GlmForSequenceClassification.__init__R  si        +f%%
Yv14?OOO
 	r-   c                     | j         j        S rm   rp  r?   s    r,   r/  z1GlmForSequenceClassification.get_input_embeddings[  rq  r-   c                     || j         _        d S rm   rp  r1  s     r,   r3  z1GlmForSequenceClassification.set_input_embeddings^  rs  r-   Nr4  r   rg   r  r5  r  r   r   r6  r7  r|   c                 "   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}nv|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }nd}|t          j        ||j                  |f         }d}||                     |||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          S )
  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr   rg   r  r5  r   r   r6  r7  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r0   r9  )r  r  pooled_logitsrt   r  )rt   r?  r  r  r>   r!  r   r$   eqr   argmaxr3   rV   rR   r  r   r  r8   r>  )r(   r4  r   rg   r  r5  r  r   r   r6  r7  transformer_outputsr8   r  rT  sequence_lengthsr  r  r  s                      r,   r;   z$GlmForSequenceClassification.forwarda  s   ( &1%<kk$+B]"jj)%+'/!5# ) 

 

 ,A.M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% u|Jv}MMMO__`%%VFR_hlhs%ttD 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r-   rg  )rA   rB   rC   r   r!   r/  r3  r   rh  r   r$   r   r   r   r	   r   r   r   r   r   r;   rD   rE   s   @r,   r  r  B  s        y      ' ' '( ( ( +*+?@@ 151537KO59-1$(,0/3&*E
 E
E,-E
 !.E
 u/0	E

 "%tE4E/F(F"GHE
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 E
 E
 A@E
 E
 E
 E
 E
r-   r  z
    The Glm Model transformer with a token classification head on top (a linear layer on top of the hidden-states
    output) e.g. for Named-Entity-Recognition (NER) tasks.
    c                   l    e Zd Zdef fdZd Zd Z ee          	 	 	 	 	 	 	 	 	 	 dde	e
j                 de	e
j                 de	e
j                 d	e	ee
j                          d
e	e
j                 de	e
j                 de	e         de	e         de	e         de	e         deeef         fd            Z xZS )GlmForTokenClassificationrt   c                    t                                          |           |j        | _        t          |          | _        t          |dd           |j        }nt          |dd           |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropouthidden_dropoutg?)r    r!   r  r  r  r   r  r  r"   Dropoutr   ru   r)   r  r,  )r(   rt   r  r+   s      r,   r!   z"GlmForTokenClassification.__init__  s        +f%%
6/66B!'!:V-t44@!'!6!$z"455Yv163DEE
 	r-   c                     | j         j        S rm   rp  r?   s    r,   r/  z.GlmForTokenClassification.get_input_embeddings  rq  r-   c                     || j         _        d S rm   rp  r1  s     r,   r3  z.GlmForTokenClassification.set_input_embeddings  rs  r-   Nr4  r   rg   r  r5  r  r   r   r6  r7  r|   c                 p   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}||                     ||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j                  S )r  Nr  r   r/   )r  r  r8   r>  )	rt   r?  r  r   r  r  r   r8   r>  )r(   r4  r   rg   r  r5  r  r   r   r6  r7  r  sequence_outputr  r  r  s                   r,   r;   z!GlmForTokenClassification.forward  s    ( &1%<kk$+B]**)%+'/!5#  

 

 "!*,,77O,,%%ffdkBBD 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r-   rg  )rA   rB   rC   r   r!   r/  r3  r   rh  r   r$   r   r   r   r   r   r   r   r   r;   rD   rE   s   @r,   r  r    sp       y       ' ' '( ( ( +*+?@@ 151537=A59-1$(,0/3&*1
 1
E,-1
 !.1
 u/0	1

 "$u'8"9:1
   121
 )*1
 D>1
 $D>1
 'tn1
 d^1
 
u++	,1
 1
 1
 A@1
 1
 1
 1
 1
r-   r  )r  r  rk  r  r  )Nr   )@r   typingr   r   r   r   r$   torch.nnr"   torch.utils.checkpointactivationsr   cache_utilsr	   r
   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   configuration_glmr   modeling_flash_attention_utilsr   Moduler   rG   rp   
get_loggerrA   r   r   r   r   r   r   r   r   r   r   r   GLM_START_DOCSTRINGr  r  rh  r  rk  r  r  __all__r   r-   r,   <module>r     s5  ,  / / / / / / / / / / / /            ! ! ! ! ! ! ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) > > > > > >            . - - - - -                ) ( ( ( ( (  KJJJJJJ F F F F F FJ J J J J J J J(< < < < < < < <:) ) ) ) )RY ) ) )& 
	H	%	%6 6 6& & & &R	UU\ 	U# 	U%, 	U 	U 	U 	U\9 \9 \9 \9 \929 \9 \9 \9~g9 g9 g9 g9 g9 g9 g9 g9TX1 X1 X1 X1 X1| X1 X1 X1x +  M M M M Mbi M M M` " W ? ? ? ? ? ? ?	 ?0 H V W R R R R R! R R	 Rjt
 t
 t
 t
 t
' t
 t
 t
n   V
 V
 V
 V
 V
#5 V
 V
 V
r   I
 I
 I
 I
 I
 2 I
 I
 I
X  r-   