o
    iV                     @   s6  d dl mZmZmZ d dlZd dlmZ ddlmZ ddl	m
Z
mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZmZ ddlmZmZ ddlmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, G dd dej-Z.G dd deZ/dej0de1dej0fddZ2	d>dej-dej0d ej0d!ej0d"eej0 d#e3d$e3d%e"e$ fd&d'Z4d(d) Z5d?d*d+Z6G d,d- d-ej-Z7ed.G d/d0 d0ej-Z8G d1d2 d2ej-Z9e%G d3d4 d4e Z:e%G d5d6 d6e:Z;e%G d7d8 d8e:eZ<G d9d: d:ee:Z=G d;d< d<ee:Z>g d=Z?dS )@    )CallableOptionalUnionN   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask)FlashAttentionKwargs) GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)deprecate_kwarg)check_model_inputs   )
Glm4Configc                       s2   e Zd Z fddZdejdejfddZ  ZS )Glm4MLPc                    sP   t    || _tj|jd|j dd| _tj|j|jdd| _t	|j
 | _d S )N   Fbias)super__init__confignnLinearhidden_sizeintermediate_sizegate_up_proj	down_projr   
hidden_actactivation_fnselfr$   	__class__ Z/home/ubuntu/.local/lib/python3.10/site-packages/transformers/models/glm4/modeling_glm4.pyr#   1   s
   
zGlm4MLP.__init__hidden_statesreturnc                 C   s4   |  |}|jddd\}}|| | }| |S )Nr   dim)r)   chunkr,   r*   )r.   r3   	up_statesgater1   r1   r2   forward9   s   

zGlm4MLP.forward)__name__
__module____qualname__r#   torchFloatTensorr;   __classcell__r1   r1   r/   r2   r   0   s    r   c                       s   e Zd Zdedef fddZedddd							
				ddejde	ej de	ej
 de	e de	e de	ej
 de	eejejf  dee deeje	eejejf  f fddZ  ZS )Glm4DecoderLayerr$   	layer_idxc                    sv   t    |j| _t||d| _t|| _t|j|jd| _	t|j|jd| _
t|j|jd| _t|j|jd| _d S )N)r$   rC   eps)r"   r#   r'   Glm4Attention	self_attnr   mlpGlm4RMSNormrms_norm_epsinput_layernormpost_attention_layernormpost_self_attn_layernormpost_mlp_layernormr.   r$   rC   r/   r1   r2   r#   C   s   

zGlm4DecoderLayer.__init__past_key_valuepast_key_values4.58new_nameversionNFr3   attention_maskposition_ids	use_cachecache_positionposition_embeddingskwargsr4   c              
   K   sr   |}	|  |}| jd|||||||d|\}}
| |}|	| }|}	| |}| |}| |}|	| }|S )N)r3   rV   rW   rQ   rX   rY   rZ   r1   )rK   rG   rM   rL   rH   rN   )r.   r3   rV   rW   rQ   rX   rY   rZ   r[   residual_r1   r1   r2   r;   N   s*   





zGlm4DecoderLayer.forward)NNNFNN)r<   r=   r>   r   intr#   r   r?   Tensorr   
LongTensorr   booltupler   r   r@   r;   rA   r1   r1   r/   r2   rB   B   s8    	
rB   r3   n_repr4   c                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)shapeexpandreshape)r3   rc   batchnum_key_value_headsslenhead_dimr1   r1   r2   	repeat_kvs   s
   0rk           modulequerykeyvaluerV   scalingdropoutr[   c                 K   s   t || j}t || j}	t||dd| }
|d ur3|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr   r   r5   )r7   dtype)ptrainingr   )rk   num_key_value_groupsr?   matmul	transposerd   r%   
functionalsoftmaxfloat32tort   rr   rv   
contiguous)rm   rn   ro   rp   rV   rq   rr   r[   
key_statesvalue_statesattn_weightscausal_maskattn_outputr1   r1   r2   eager_attention_forward   s   
&r   c                 C   s>   | ddddf }| ddddf }t j| |fdddS )	z*Rotates half the hidden dims of the input..r   Nr   r   r5   r6   rs   )r?   stackflatten)xx1x2r1   r1   r2   rotate_half   s   r   c                 C   s   | |}| |}|dd|jd d f jddd}|dd|jd d f jddd}|jd }| dd|f | d|df }}|dd|f |d|df }	}
|| t||  }|	| t|	|  }tj||gdd}tj||
gd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.
    .Nr5   r   r6   )	unsqueezerd   repeat_interleaver   r?   cat)qkcossinrW   unsqueeze_dim
rotary_dimq_rotq_passk_rotk_passq_embedk_embedr1   r1   r2   apply_rotary_pos_emb   s   

$$
""r   c                       s   e Zd ZdZddedee f fddZeddd	d
		dde	j
dee	j
e	j
f dee	j
 dee dee	j dee dee	j
e	j
f fddZ  ZS )rF   z=Multi-headed attention from 'Attention Is All You Need' paperNr$   rC   c                    s   t    || _|| _t|d|j|j | _|j|j | _	| jd | _
|j| _d| _tj|j|j| j |jd| _tj|j|j| j |jd| _tj|j|j| j |jd| _tj|j| j |jdd| _d S )Nrj   g      Tr    F)r"   r#   r$   rC   getattrr'   num_attention_headsrj   rh   rw   rq   attention_dropout	is_causalr%   r&   attention_biasq_projk_projv_projo_projrO   r/   r1   r2   r#      s$   
 zGlm4Attention.__init__rP   rQ   rR   rS   r3   rZ   rV   rY   r[   r4   c                 K   s$  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
}| jjdkret| jj }|| |	|
||f| jsqdn| j| jd|\}}|jg |dR   }| |}||fS )Nr5   r   r   )r   r   rY   eagerrl   )rr   rq   )rd   rj   r   viewry   r   r   r   updaterC   r   r$   _attn_implementationr   rv   r   rq   rf   r~   r   )r.   r3   rZ   rV   rQ   rY   r[   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   r1   r1   r2   r;      s8   


zGlm4Attention.forwardN)NN)r<   r=   r>   __doc__r   r   r^   r#   r   r?   r_   rb   r   r`   r   r   r;   rA   r1   r1   r/   r2   rF      s*    rF   RMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	rI   ư>c                    s&   t    tt|| _|| _dS )z:
        Glm4RMSNorm is equivalent to T5LayerNorm
        N)r"   r#   r%   	Parameterr?   onesweightvariance_epsilon)r.   r'   rE   r/   r1   r2   r#     s   

zGlm4RMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr   r5   T)keepdim)	rt   r}   r?   r|   powmeanrsqrtr   r   )r.   r3   input_dtypevariancer1   r1   r2   r;     s
   zGlm4RMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)rb   r   rd   r   )r.   r1   r1   r2   
extra_repr   s   zGlm4RMSNorm.extra_repr)r   )r<   r=   r>   r#   r;   r   rA   r1   r1   r/   r2   rI     s    rI   c                       sD   e Zd ZU ejed< ddef fddZe e	dd Z
  ZS )	Glm4RotaryEmbeddinginv_freqNr$   c                    s   t    t|drt|jtr|jd|jd| _nd| _|j| _	|j| _
|| _t| j | _| | j|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultr   F)
persistent)r"   r#   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)r.   r$   devicer   r/   r1   r2   r#   '  s   
zGlm4RotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r5   r   mpscpuF)device_typeenabledr   r6   )rt   )r   floatre   rd   r}   r   r   r   strr?   autocastry   r   r   r   r   rt   )
r.   r   rW   inv_freq_expandedposition_ids_expandedr   freqsembr   r   r1   r1   r2   r;   8  s   0&zGlm4RotaryEmbedding.forwardr   )r<   r=   r>   r?   r_   __annotations__r   r#   no_gradr   r;   rA   r1   r1   r/   r2   r   $  s   
 
r   c                   @   sH   e Zd ZU eed< dZdZdgZdgZdZ	dZ
dZdZdZeedZdS )Glm4PreTrainedModelr$   modelTrB   rQ   )r3   
attentionsN)r<   r=   r>   r   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendrB   rF   _can_record_outputsr1   r1   r1   r2   r   H  s   
 
r   c                       s   e Zd Zdef fddZee							ddeej	 deej
 deej	 dee d	eej d
eej	 dee dee defddZ  ZS )	Glm4Modelr$   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r1   )rB   ).0rC   r$   r1   r2   
<listcomp>d  s    z&Glm4Model.__init__.<locals>.<listcomp>rD   r   F)r"   r#   pad_token_idpadding_idx
vocab_sizer%   	Embeddingr'   embed_tokens
ModuleListrangenum_hidden_layerslayersrI   rJ   normr   
rotary_embgradient_checkpointing	post_initr-   r/   r   r2   r#   ]  s   zGlm4Model.__init__N	input_idsrV   rW   rQ   inputs_embedsrY   rX   r[   r4   c              	   K   s   |d u |d uA rt d|d u r| |}|r!|d u r!t| jd}|d u r=|d ur-| nd}	tj|	|	|jd  |jd}|d u rF|	d}t
| j|||||d}
|}| ||}| jd | jj D ]}||f|
||||d|}qb| |}t||dS )	Nz:You must specify exactly one of input_ids or inputs_embedsr   r   r   )r   )r$   input_embedsrV   rY   rQ   rW   )rV   rW   rQ   rY   rZ   )last_hidden_staterQ   )
ValueErrorr   r   r$   get_seq_lengthr?   arangerd   r   r   r   r   r   r   r   r   )r.   r   rV   rW   rQ   r   rY   rX   r[   past_seen_tokensr   r3   rZ   decoder_layerr1   r1   r2   r;   m  sP   

	

zGlm4Model.forward)NNNNNNN)r<   r=   r>   r   r#   r   r   r   r?   r`   r_   r   r@   ra   r   r   r   r;   rA   r1   r1   r/   r2   r   [  s<    	
r   c                       s   e Zd ZdgZddiZddgdgfiZ fddZee										dd
e	e
j de	e
j de	e
j de	e de	e
j de	e
j de	e de	e
j deee
jf dee deeef fddZ  ZS )Glm4ForCausalLMzlm_head.weightlm_headcolwise_repr3   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S )NFr    )
r"   r#   r   r   r   r%   r&   r'   r  r   r-   r/   r1   r2   r#     s
   
zGlm4ForCausalLM.__init__Nr   r   rV   rW   rQ   r   labelsrX   rY   logits_to_keepr[   r4   c
              
   K   s   | j d|||||||d|
}|j}t|	trt|	 dn|	}| |dd|ddf }d}|durB| jd||| jjd|
}t	|||j
|j|jdS )ah  
        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, Glm4ForCausalLM

        >>> model = Glm4ForCausalLM.from_pretrained("THUDM/GLM-4-9B-0414")
        >>> tokenizer = AutoTokenizer.from_pretrained("THUDM/GLM-4-9B-0414")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> 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]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```)r   rV   rW   rQ   r   rX   rY   N)r  r  r   )lossr  rQ   r3   r   r1   )r   r   r   r^   slicer  loss_functionr$   r   r   rQ   r3   r   )r.   r   rV   rW   rQ   r   r  rX   rY   r  r[   outputsr3   slice_indicesr  r	  r1   r1   r2   r;     s0   %zGlm4ForCausalLM.forward)	NNNNNNNNr   )r<   r=   r>   _tied_weights_keys_tp_plan_pp_planr#   r   r   r   r?   r`   r_   r   r@   ra   r   r^   r   r   rb   r   r;   rA   r1   r1   r/   r2   r    sN    		

r  c                   @      e Zd ZdS )Glm4ForSequenceClassificationNr<   r=   r>   r1   r1   r1   r2   r        r  c                   @   r  )Glm4ForTokenClassificationNr  r1   r1   r1   r2   r    r  r  )r   r   r  r  r  )rl   )Nr   )@typingr   r   r   r?   torch.nnr%   activationsr   cache_utilsr   r   
generationr	   integrationsr
   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.deprecationr   utils.genericr   configuration_glm4r   Moduler   rB   r_   r^   rk   r   r   r   r   rF   rI   r   r   r   r  r  r  __all__r1   r1   r1   r2   <module>   sl   1

*E$NP