o
    ZŽhdß  ã                   @   sr  d Z ddlZddlmZmZmZmZ ddlZddlZddlm	Z	 ddl
mZmZmZ ddlmZmZmZmZmZ ddlmZmZmZ dd	lmZmZmZmZ d
dlmZ eƒ r]ddlm Z  e !e"¡Z#dd„ Z$dd„ Z%dd„ Z&dd„ Z'dd„ Z(G dd„ dej	j)ƒZ*G dd„ de	j)ƒZ+G dd„ de	j)ƒZ,G dd„ de	j)ƒZ-G dd „ d e	j)ƒZ.G d!d"„ d"e-ƒZ/e-e/d#œZ0G d$d%„ d%e	j)ƒZ1G d&d'„ d'e	j)ƒZ2G d(d)„ d)e	j)ƒZ3G d*d+„ d+e	j)ƒZ4G d,d-„ d-e	j)ƒZ5G d.d/„ d/e	j)ƒZ6eG d0d1„ d1eƒƒZ7eG d2d3„ d3e7ƒƒZ8eG d4d5„ d5e7ƒƒZ9G d6d7„ d7e	j)ƒZ:ed8d9G d:d;„ d;e7ƒƒZ;eG d<d=„ d=e7ƒƒZ<G d>d?„ d?e	j)ƒZ=dCd@dA„Z>g dB¢Z?dS )DzPyTorch ESM model.é    N)ÚListÚOptionalÚTupleÚUnion)Únn)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELossé   )Ú)BaseModelOutputWithPastAndCrossAttentionsÚ,BaseModelOutputWithPoolingAndCrossAttentionsÚMaskedLMOutputÚSequenceClassifierOutputÚTokenClassifierOutput)ÚPreTrainedModelÚ find_pruneable_heads_and_indicesÚprune_linear_layer)Úauto_docstringÚis_flash_attn_2_availableÚ#is_flash_attn_greater_or_equal_2_10Úloggingé   )Ú	EsmConfig)Ú_flash_attention_forwardc                 C   s&   | j ddd\}}tj| |fddS )Né   éÿÿÿÿ©Údim)ÚchunkÚtorchÚcat)ÚxÚx1Zx2© r#   úS/var/www/auris/lib/python3.10/site-packages/transformers/models/esm/modeling_esm.pyÚrotate_half-   s   r%   c                 C   s`   |d d …d d …d | j d …d d …f }|d d …d d …d | j d …d d …f }| | t| ƒ|  S )Néþÿÿÿ)Úshaper%   )r!   ÚcosÚsinr#   r#   r$   Úapply_rotary_pos_emb2   s   &&r*   c                 C   s    | d dt  | t d¡ ¡  S )zo
    This is the gelu implementation from the original ESM repo. Using F.gelu yields subtly wrong results.
    g      à?ç      ð?g       @)r   ÚerfÚmathÚsqrt©r!   r#   r#   r$   Úgelu9   s    r0   c                 C   s   | |   dd¡ S )zJMake layer symmetric in final two dimensions, used for contact prediction.r   r&   )Ú	transposer/   r#   r#   r$   Ú
symmetrize@   s   r2   c                 C   sH   | j ddd}| j ddd}| j ddd}|| }| |¡ | | }|S )z=Perform average product correct, used for contact prediction.r   T)Zkeepdimsr&   )r   r&   )ÚsumZdiv_)r!   Za1Za2Za12ZavgÚ
normalizedr#   r#   r$   Úaverage_product_correctE   s   
r5   c                       sV   e Zd ZdZdef‡ fdd„Zddd„Zdejd	ejd
e	ejejf fdd„Z
‡  ZS )ÚRotaryEmbeddingzå
    Rotary position embeddings based on those in
    [RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer). Query and keys are transformed by rotation
    matrices which depend on their relative positions.
    r   c                    sT   t ƒ  ¡  ddtjd|dtjd ¡ |   }|}|  d|¡ d | _d | _d | _	d S )Nr+   i'  r   r   ©ÚdtypeÚinv_freq)
ÚsuperÚ__init__r   ÚarangeZint64ÚfloatÚregister_bufferÚ_seq_len_cachedÚ_cos_cachedÚ_sin_cached)Úselfr   r9   ©Ú	__class__r#   r$   r;   X   s   
$
zRotaryEmbedding.__init__r   c                 C   s¶   |j | }|| jks| jj|jkrU|| _tj|j | |jd | j¡}t || j¡}tj	||fdd 
|j¡}| ¡ d d d d …d d …f | _| ¡ d d d d …d d …f | _| j| jfS )N©Údevicer   r   )r'   r?   r@   rF   r   r<   Útype_asr9   Úouterr    Útor(   r)   rA   )rB   r!   Úseq_dimensionZseq_lenÚtZfreqsZembr#   r#   r$   Ú_update_cos_sin_tablesc   s   
z&RotaryEmbedding._update_cos_sin_tablesÚqÚkÚreturnc                 C   sJ   | j |dd\| _| _t|| j| jƒj|jdt|| j| jƒj|jdfS )Nr&   )rJ   r7   )rL   r@   rA   r*   rI   r8   )rB   rM   rN   r#   r#   r$   Úforwards   s   þzRotaryEmbedding.forward)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úintr;   rL   r   ÚTensorr   rP   Ú__classcell__r#   r#   rC   r$   r6   Q   s
    
.r6   c                       s8   e Zd ZdZ		d
dedef‡ fdd„Zdd	„ Z‡  ZS )ÚEsmContactPredictionHeadzWPerforms symmetrization, apc, and computes a logistic regression on the output featuresTr   Úin_featuresÚeos_idxc                    s4   t ƒ  ¡  || _|| _t |d|¡| _t ¡ | _d S )Nr   )	r:   r;   rY   rZ   r   ÚLinearÚ
regressionZSigmoidÚ
activation)rB   rY   ÚbiasrZ   rC   r#   r$   r;      s
   
z!EsmContactPredictionHead.__init__c           	      C   sÜ   |  | j¡ |¡}| d¡| d¡ }||d d …d d d d …d d …f  }|dd d…d d…f }|ddd …dd …f }| ¡ \}}}}}| ||| ||¡}| | jjj¡}t	t
|ƒƒ}| dddd¡}|  |  |¡ d¡¡S )Nr   r   .r   r   r
   )ÚnerZ   rI   Ú	unsqueezeÚsizeÚviewr\   ÚweightrF   r5   r2   Úpermuter]   Úsqueeze)	rB   ÚtokensÚ
attentionsZeos_maskÚ
batch_sizeZlayersÚheadsZseqlenÚ_r#   r#   r$   rP   ‹   s   "ÿz EsmContactPredictionHead.forward)Tr   )rQ   rR   rS   rT   rU   r;   rP   rW   r#   r#   rC   r$   rX   |   s    üþürX   c                       s4   e Zd ZdZ‡ fdd„Z	d
dd„Zdd	„ Z‡  ZS )ÚEsmEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                    s¼   t ƒ  ¡  tj|j|j|jd| _|jrtj	|j|j
d| _nd | _t |j¡| _t|ddƒ| _| jdt |j¡ d¡dd |j| _| jdkrTtj|j|j| jd| _|j| _|j| _d S )	N)Úpadding_idx©ZepsÚposition_embedding_typeÚabsoluteÚposition_ids)r   r   F)Ú
persistent)r:   r;   r   Ú	EmbeddingÚ
vocab_sizeÚhidden_sizeZpad_token_idÚword_embeddingsZemb_layer_norm_beforeÚ	LayerNormÚlayer_norm_epsÚ
layer_normÚDropoutÚhidden_dropout_probÚdropoutÚgetattrrn   r>   r   r<   Úmax_position_embeddingsÚexpandrl   Úposition_embeddingsÚtoken_dropoutÚmask_token_id©rB   ÚconfigrC   r#   r$   r;   ¤   s"   
ÿ
ÿzEsmEmbeddings.__init__Nr   c                 C   s   |d u r|d urt || j|ƒ}n|  |¡}|d u r|  |¡}|}| jrW| || jk d¡d¡}d}| d¡}|| jk d¡ 	¡ | }	|d|  d|	 d d …d d f   
|j¡}| jdkre|  |¡}
||
 }| jd uro|  |¡}|d ur~|| d¡  
|j¡}|S )Nr   ç        g¸…ëQ¸¾?r   ro   )Ú"create_position_ids_from_input_idsrl   Ú&create_position_ids_from_inputs_embedsru   r€   Zmasked_fillr   r`   r3   r=   rI   r8   rn   r   rx   )rB   Ú	input_idsÚattention_maskrp   Úinputs_embedsÚpast_key_values_lengthÚ
embeddingsZmask_ratio_trainZsrc_lengthsZmask_ratio_observedr   r#   r#   r$   rP   »   s.   

	
"ÿ



zEsmEmbeddings.forwardc                 C   sN   |  ¡ dd… }|d }tj| jd || j d tj|jd}| d¡ |¡S )z×
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        Nr   r   ©r8   rF   r   )ra   r   r<   rl   ÚlongrF   r`   r~   )rB   r‰   Úinput_shapeZsequence_lengthrp   r#   r#   r$   r†   è   s   	ÿz4EsmEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )rQ   rR   rS   rT   r;   rP   r†   rW   r#   r#   rC   r$   rk   Ÿ   s    
ÿ-rk   c                       sž   e Zd Zd‡ fdd„	Zdejdejfdd„Z						dd	ejd
eej deej deej deej dee	e	ej   dee
 de	ej fdd„Z‡  ZS )ÚEsmSelfAttentionNc                    s$  t ƒ  ¡  || _|j|j dkr"t|dƒs"td|j› d|j› dƒ‚|j| _t|j|j ƒ| _| j| j | _	t
 |j| j	¡| _t
 |j| j	¡| _t
 |j| j	¡| _t
 |j¡| _|p_t|ddƒ| _d | _| jdksn| jd	kr€|j| _t
 d
|j d | j¡| _n| jdkrŒt| jd| _|j| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads (ú)rn   ro   Úrelative_keyÚrelative_key_queryr   r   Úrotaryr   )r:   r;   rƒ   rt   Únum_attention_headsÚhasattrÚ
ValueErrorrU   Úattention_head_sizeÚall_head_sizer   r[   ÚqueryÚkeyÚvaluery   Úattention_probs_dropout_probr{   r|   rn   Úrotary_embeddingsr}   rr   Údistance_embeddingr6   Ú
is_decoder©rB   rƒ   rn   rC   r#   r$   r;   û   s2   

ÿÿÿ
zEsmSelfAttention.__init__r!   rO   c                 C   s6   |  ¡ d d… | j| jf }| |¡}| dddd¡S )Nr   r   r   r   r
   )ra   r”   r—   rb   rd   )rB   r!   Znew_x_shaper#   r#   r$   Útranspose_for_scores  s   
z%EsmSelfAttention.transpose_for_scoresFÚhidden_statesrˆ   Ú	head_maskÚencoder_hidden_statesÚencoder_attention_maskÚpast_key_valueÚoutput_attentionsc                 C   s°  |   |¡}|d u}	|	r|d ur|d }
|d }|}nP|	r/|  |  |¡¡}
|  |  |¡¡}|}n;|d urZ|  |  |¡¡}
|  |  |¡¡}tj|d |
gdd}
tj|d |gdd}n|  |  |¡¡}
|  |  |¡¡}|  |¡}|| jd  }| jr}|
|f}| jdkrŠ|  	||
¡\}}
t 
||
 dd¡¡}| jd	ksž| jd
krÿ| ¡ d }tj|tj|jd dd¡}tj|tj|jd dd¡}|| }|  || j d ¡}|j|jd}| jd	kræt d||¡}|| }n| jd
krÿt d||¡}t d|
|¡}|| | }|d ur|| }tjj|dd}|  |¡}|d ur|| }t 
| |j¡|¡}| dddd¡ ¡ }| ¡ d d… | jf }| |¡}|rJ||fn|f}| jrV||f }|S )Nr   r   r   r   ç      à¿r“   r   r&   r‘   r’   rŒ   r7   zbhld,lrd->bhlrzbhrd,lrd->bhlrr
   )r™   r¡   rš   r›   r   r    r—   rŸ   rn   r   Úmatmulr1   ra   r<   r   rF   rb   rž   r}   rI   r8   Zeinsumr   Z
functionalZsoftmaxr{   rd   Ú
contiguousr˜   )rB   r¢   rˆ   r£   r¤   r¥   r¦   r§   Zmixed_query_layerZis_cross_attentionÚ	key_layerÚvalue_layerÚquery_layerZattention_scoresÚ
seq_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZnew_context_layer_shapeÚoutputsr#   r#   r$   rP     sh   











zEsmSelfAttention.forward©N©NNNNNF)rQ   rR   rS   r;   r   rV   r¡   r   ÚFloatTensorr   ÚboolrP   rW   r#   r#   rC   r$   r   ú   s4    øþýüûúùø	÷r   c                       ó$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )ÚEsmSelfOutputc                    s.   t ƒ  ¡  t |j|j¡| _t |j¡| _d S r°   )	r:   r;   r   r[   rt   Údensery   rz   r{   r‚   rC   r#   r$   r;   ‡  ó   
zEsmSelfOutput.__init__c                 C   ó    |   |¡}|  |¡}|| }|S r°   ©r¶   r{   ©rB   r¢   Zinput_tensorr#   r#   r$   rP   Œ  ó   

zEsmSelfOutput.forward©rQ   rR   rS   r;   rP   rW   r#   r#   rC   r$   rµ   †  ó    rµ   c                       s   e Zd ZdZd‡ fdd„	Z						ddejdeej deej d	eej d
eej dee	e	ej   dee
 de	ej f‡ fdd„Z‡  ZS )ÚEsmFlashAttention2aF  
    ESM flash attention module. This module inherits from `EsmSelfAttention` 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.
    Nc                    s&   t ƒ j||d tƒ  | _|j| _d S )N)rn   )r:   r;   r   Ú_flash_attn_uses_top_left_maskrœ   Údropout_probr    rC   r#   r$   r;   š  s   
zEsmFlashAttention2.__init__Fr¢   rˆ   r£   r¤   r¥   r¦   r§   rO   c                    sâ  |s
|d us
|d urt  d¡ tƒ  |||||||¡S | ¡ \}}	}
|  |  |¡¡}|  |  |¡¡}|  |  |¡¡}|d urTt	j
|d |gdd}t	j
|d |gdd}|j}|t	jkrt	 ¡ ret	 ¡ }nt| jdƒrp| jj}n| jjj}t  d|› d¡ | |¡}| |¡}| |¡}|| jd	  }| jd
kr¢|  ||¡\}}n| jdks¬| jdkrµtd| j› dƒ‚t| dddd¡| dddd¡| dddd¡||	| jd| jrÖ| jnd| jd	}| ||	d¡}|d f}| jrï||f }|S )NzïEsmFlashAttention2 does not support output_attentions, head_mask, or cross_attention. Falling back to the manual attention implementation. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   r   r   r   Ú_pre_quantization_dtypez¾The 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 Ú.r¨   r“   r‘   r’   z%ESM flash attention does not support z embeddingsr
   r+   r„   )Zquery_lengthZ	is_causalZsoftmax_scaler{   Zuse_top_left_maskr   )ÚloggerÚwarning_oncer:   rP   ra   r¡   r™   rš   r›   r   r    r8   Zfloat32Zis_autocast_enabledZget_autocast_gpu_dtyper•   rƒ   rÁ   rc   rI   r—   rn   r   r–   r   rd   rŸ   ÚtrainingrÀ   r¿   Zreshape)rB   r¢   rˆ   r£   r¤   r¥   r¦   r§   ZbszZq_lenrj   r­   r«   r¬   Zinput_dtypeZtarget_dtypeZattn_outputr¯   rC   r#   r$   rP   £  sp   ÿù




þÿ



÷
zEsmFlashAttention2.forwardr°   r±   )rQ   rR   rS   rT   r;   r   rV   r   r²   r   r³   rP   rW   r#   r#   rC   r$   r¾   “  s4    øþýüûúùø	÷r¾   )ÚeagerÚflash_attention_2c                       s:   e Zd Z‡ fdd„Zdd„ Z						d	dd„Z‡  ZS )
ÚEsmAttentionc                    sD   t ƒ  ¡  t|j |ƒ| _t|ƒ| _tƒ | _t	j
|j|jd| _
d S )Nrm   )r:   r;   ÚESM_ATTENTION_CLASSESÚ_attn_implementationrB   rµ   ÚoutputÚsetÚpruned_headsr   rv   rt   rw   r‚   rC   r#   r$   r;   
  s
   

zEsmAttention.__init__c                 C   s²   t |ƒdkrd S t|| jj| jj| jƒ\}}t| jj|ƒ| j_t| jj|ƒ| j_t| jj	|ƒ| j_	t| j
j|dd| j
_| jjt |ƒ | j_| jj| jj | j_| j |¡| _d S )Nr   r   r   )Úlenr   rB   r”   r—   rÍ   r   r™   rš   r›   rË   r¶   r˜   Úunion)rB   ri   Úindexr#   r#   r$   Úprune_heads  s   ÿzEsmAttention.prune_headsNFc              	   C   sF   |   |¡}|  |||||||¡}	|  |	d |¡}
|
f|	dd …  }|S )Nr   r   )rv   rB   rË   )rB   r¢   rˆ   r£   r¤   r¥   r¦   r§   Zhidden_states_lnZself_outputsÚattention_outputr¯   r#   r#   r$   rP   #  s   

ù	zEsmAttention.forwardr±   )rQ   rR   rS   r;   rÑ   rP   rW   r#   r#   rC   r$   rÈ   	  s    ørÈ   c                       ó2   e Zd Z‡ fdd„Zdejdejfdd„Z‡  ZS )ÚEsmIntermediatec                    s    t ƒ  ¡  t |j|j¡| _d S r°   )r:   r;   r   r[   rt   Úintermediate_sizer¶   r‚   rC   r#   r$   r;   =  s   
zEsmIntermediate.__init__r¢   rO   c                 C   s   |   |¡}t|ƒ}|S r°   )r¶   r0   )rB   r¢   r#   r#   r$   rP   A  s   
zEsmIntermediate.forward©rQ   rR   rS   r;   r   rV   rP   rW   r#   r#   rC   r$   rÔ   <  s    rÔ   c                       r´   )Ú	EsmOutputc                    s.   t ƒ  ¡  t |j|j¡| _t |j¡| _	d S r°   )
r:   r;   r   r[   rÕ   rt   r¶   ry   rz   r{   r‚   rC   r#   r$   r;   H  r·   zEsmOutput.__init__c                 C   r¸   r°   r¹   rº   r#   r#   r$   rP   M  r»   zEsmOutput.forwardr¼   r#   r#   rC   r$   r×   G  r½   r×   c                       s:   e Zd Z‡ fdd„Z						d	dd„Zdd„ Z‡  ZS )
ÚEsmLayerc                    s‚   t ƒ  ¡  |j| _d| _t|ƒ| _|j| _|j| _| jr+| js&t| › dƒ‚t|ƒ| _	t
|ƒ| _t|ƒ| _tj|j|jd| _d S )Nr   z> should be used as a decoder model if cross attention is addedrm   )r:   r;   Zchunk_size_feed_forwardZseq_len_dimrÈ   Ú	attentionrŸ   Úadd_cross_attentionÚRuntimeErrorÚcrossattentionrÔ   Úintermediater×   rË   r   rv   rt   rw   r‚   rC   r#   r$   r;   U  s   




zEsmLayer.__init__NFc              	   C   s  |d ur
|d d… nd }| j |||||d}	|	d }
| jr(|	dd… }|	d }n|	dd … }d }| jro|d urot| dƒsDtd| › dƒ‚|d urN|d	d … nd }|  |
||||||¡}|d }
||dd…  }|d }|| }|  |
¡}|f| }| jr||f }|S )
Nr   )r§   r¦   r   r   r   rÜ   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r&   )rÙ   rŸ   r•   ÚAttributeErrorrÜ   Úfeed_forward_chunk)rB   r¢   rˆ   r£   r¤   r¥   r¦   r§   Zself_attn_past_key_valueZself_attention_outputsrÒ   r¯   Zpresent_key_valueZcross_attn_present_key_valueZcross_attn_past_key_valueZcross_attention_outputsÚlayer_outputr#   r#   r$   rP   d  sL   û


ÿù	


zEsmLayer.forwardc                 C   s$   |   |¡}|  |¡}|  ||¡}|S r°   )rv   rÝ   rË   )rB   rÒ   Zattention_output_lnZintermediate_outputrà   r#   r#   r$   rß   £  s   

zEsmLayer.feed_forward_chunkr±   )rQ   rR   rS   r;   rP   rß   rW   r#   r#   rC   r$   rØ   T  s    
ø?rØ   c                       s8   e Zd Z‡ fdd„Z									ddd„Z‡  ZS )	Ú
EsmEncoderc                    sN   t ƒ  ¡  ˆ | _t ‡ fdd„tˆ jƒD ƒ¡| _tjˆ j	ˆ j
d| _d| _d S )Nc                    s   g | ]}t ˆ ƒ‘qS r#   )rØ   )Ú.0rj   ©rƒ   r#   r$   Ú
<listcomp>®  s    z'EsmEncoder.__init__.<locals>.<listcomp>rm   F)r:   r;   rƒ   r   Z
ModuleListÚrangeÚnum_hidden_layersÚlayerrv   rt   rw   Úemb_layer_norm_afterÚgradient_checkpointingr‚   rC   rã   r$   r;   «  s
   
 
zEsmEncoder.__init__NFTc                 C   sn  | j r| jr|rt d¡ d}|	rdnd }|rdnd }|r#| jjr#dnd }|r)dnd }t| jƒD ]^\}}|	r;||f }|d urC|| nd }|d urM|| nd }| j rc| jrc|  |j	|||||||¡}n
||||||||ƒ}|d }|rz||d f }|rŽ||d f }| jjrŽ||d f }q0| j
r—|  
|¡}|	rž||f }|
s®tdd	„ |||||fD ƒƒS t|||||d
S )Nzh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...Fr#   r   r   r   r   c                 s   s    | ]	}|d ur|V  qd S r°   r#   )râ   Úvr#   r#   r$   Ú	<genexpr>÷  s   € ø÷z%EsmEncoder.forward.<locals>.<genexpr>)Úlast_hidden_stateÚpast_key_valuesr¢   rg   Úcross_attentions)ré   rÅ   rÃ   rÄ   rƒ   rÚ   Ú	enumeraterç   Z_gradient_checkpointing_funcÚ__call__rè   Útupler   )rB   r¢   rˆ   r£   r¤   r¥   rí   Ú	use_cacher§   Úoutput_hidden_statesÚreturn_dictZall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheÚiZlayer_moduleZlayer_head_maskr¦   Zlayer_outputsr#   r#   r$   rP   ²  s~   ÿ
øù
€

ûþûzEsmEncoder.forward)	NNNNNNFFTr¼   r#   r#   rC   r$   rá   ª  s    
õrá   c                       rÓ   )Ú	EsmPoolerc                    s*   t ƒ  ¡  t |j|j¡| _t ¡ | _d S r°   )r:   r;   r   r[   rt   r¶   ZTanhr]   r‚   rC   r#   r$   r;     s   
zEsmPooler.__init__r¢   rO   c                 C   s(   |d d …df }|   |¡}|  |¡}|S ©Nr   )r¶   r]   )rB   r¢   Zfirst_token_tensorÚpooled_outputr#   r#   r$   rP     s   

zEsmPooler.forwardrÖ   r#   r#   rC   r$   rö     s    rö   c                   @   s,   e Zd ZeZdZdZg d¢ZdZdd„ Z	dS )ÚEsmPreTrainedModelÚesmT)rØ   Z#EsmFoldTriangularSelfAttentionBlockrk   c                 C   sÎ   t |tjƒr |jjjd| jjd |jdur|jj 	¡  dS dS t |tj
ƒrC|jjjd| jjd |jdurA|jj|j  	¡  dS dS t |tjƒrX|jj 	¡  |jj d¡ dS t |tƒre|jj 	¡  dS dS )zInitialize the weightsr„   )ÚmeanZstdNr+   )Ú
isinstancer   r[   rc   ÚdataZnormal_rƒ   Zinitializer_ranger^   Zzero_rr   rl   rv   Zfill_Ú	EsmLMHead)rB   Úmoduler#   r#   r$   Ú_init_weights$  s    
ÿ
ÿ
ÿz EsmPreTrainedModel._init_weightsN)
rQ   rR   rS   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_supports_flash_attn_2r   r#   r#   r#   r$   rù     s    rù   c                       sð   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Ze												dde	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	ee
j  de	e de	e de	e de	e deee
j ef fdd„ƒZdd„ Z‡  ZS )ÚEsmModela  

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in [Attention is
    all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
    Tc                    sZ   t ƒ  |¡ || _t|ƒ| _t|ƒ| _|rt|ƒnd| _t	|j
|j dd| _|  ¡  dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        NT)rY   r^   )r:   r;   rƒ   rk   r‹   rá   Úencoderrö   ÚpoolerrX   ræ   r”   Úcontact_headZ	post_init)rB   rƒ   Úadd_pooling_layerrC   r#   r$   r;   E  s   

ÿzEsmModel.__init__c                 C   ó   | j jS r°   ©r‹   ru   ©rB   r#   r#   r$   Úget_input_embeddingsY  ó   zEsmModel.get_input_embeddingsc                 C   ó   || j _d S r°   r  )rB   r›   r#   r#   r$   Úset_input_embeddings\  ó   zEsmModel.set_input_embeddingsc                 C   s*   |  ¡ D ]\}}| jj| j |¡ qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)Úitemsr  rç   rÙ   rÑ   )rB   Zheads_to_prunerç   ri   r#   r#   r$   Ú_prune_heads_  s   ÿzEsmModel._prune_headsNr‡   rˆ   rp   r£   r‰   r¤   r¥   rí   rò   r§   ró   rô   rO   c                 C   s  |
dur|
n| j j}
|dur|n| j j}|dur|n| j j}| j jr-|	dur(|	n| j j}	nd}	|dur;|dur;tdƒ‚|durJ|  ||¡ | ¡ }n|durW| ¡ dd… }ntdƒ‚|\}}|durf|j	n|j	}|durv|d d j
d nd}|du r‡tj||| f|d}| j jd	kr|}n|  ||¡}| j jrº|durº| ¡ \}}}||f}|du r´tj||d}|  |¡}nd}|  || j j¡}| j|||||d
}| j|||||||	|
||d
}|d }| jdurë|  |¡nd}|sù||f|dd…  S t|||j|j|j|jdS )aV  
        input_ids (`torch.LongTensor` of shape `((batch_size, sequence_length))`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        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.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        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.
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embedsr   r   rE   rÇ   )r‡   rp   rˆ   r‰   rŠ   )	rˆ   r£   r¤   r¥   rí   rò   r§   ró   rô   r   )rì   Zpooler_outputrí   r¢   rg   rî   )rƒ   r§   ró   Úuse_return_dictrŸ   rò   r–   Z%warn_if_padding_and_no_attention_maskra   rF   r'   r   ZonesrÊ   Zget_extended_attention_maskZinvert_attention_maskZget_head_maskræ   r‹   r  r  r   rí   r¢   rg   rî   )rB   r‡   rˆ   rp   r£   r‰   r¤   r¥   rí   rò   r§   ró   rô   rŽ   rh   r®   rF   rŠ   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthrj   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsÚsequence_outputrø   r#   r#   r$   rP   g  s|   "ÿ
ûöúzEsmModel.forwardc                 C   s`   | ||dddj }tj|dd}|| d¡ d¡ d¡9 }|| d¡ d¡ d¡9 }|  ||¡S )NT)rˆ   rô   r§   r   r   r   r
   é   )rg   r   Ústackr`   r  )rB   rf   rˆ   Zattnsr#   r#   r$   Úpredict_contactsã  s
   zEsmModel.predict_contacts)T)NNNNNNNNNNNN)rQ   rR   rS   rT   r;   r	  r  r  r   r   r   rV   r   r²   r³   r   r   r   rP   r  rW   r#   r#   rC   r$   r  7  s^    óþýüûúùø	÷
öõôóò{r  c                       sÔ   e Zd ZdgZ‡ fdd„Zdd„ Zdd„ Ze											dd	ee	j
 d
ee	j dee	j
 dee	j dee	j dee	j dee	j dee	j
 dee dee dee deeef fdd„ƒZdd„ Z‡  ZS )ÚEsmForMaskedLMzlm_head.decoder.weightc                    s@   t ƒ  |¡ |jrt d¡ t|dd| _t|ƒ| _|  	¡  d S )NzjIf you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.F©r  )
r:   r;   rŸ   rÃ   Úwarningr  rú   rþ   Úlm_headÚinit_weightsr‚   rC   r#   r$   r;   ó  s   ÿ
zEsmForMaskedLM.__init__c                 C   r  r°   ©r  Údecoderr  r#   r#   r$   Úget_output_embeddings  r
  z$EsmForMaskedLM.get_output_embeddingsc                 C   r  r°   r  )rB   Znew_embeddingsr#   r#   r$   Úset_output_embeddings  r  z$EsmForMaskedLM.set_output_embeddingsNr‡   rˆ   rp   r£   r‰   r¤   r¥   Úlabelsr§   ró   rô   rO   c                 C   s¾   |dur|n| j j}| j||||||||	|
|d
}|d }|  |¡}d}|dur?tƒ }| |j¡}|| d| j j¡| d¡ƒ}|sU|f|dd…  }|durS|f| S |S t	|||j
|jdS )a¢  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (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]`
        N)	rˆ   rp   r£   r‰   r¤   r¥   r§   ró   rô   r   r   r   ©ÚlossÚlogitsr¢   rg   )rƒ   r  rú   r  r   rI   rF   rb   rs   r   r¢   rg   )rB   r‡   rˆ   rp   r£   r‰   r¤   r¥   r  r§   ró   rô   r¯   r  Zprediction_scoresZmasked_lm_lossÚloss_fctrË   r#   r#   r$   rP     s:   ö
üzEsmForMaskedLM.forwardc                 C   s   | j j||dS )N)rˆ   )rú   r  )rB   rf   rˆ   r#   r#   r$   r  ?  s   zEsmForMaskedLM.predict_contacts)NNNNNNNNNNN)rQ   rR   rS   Z_tied_weights_keysr;   r  r  r   r   r   Ú
LongTensorrV   r²   r³   r   r   r   rP   r  rW   r#   r#   rC   r$   r  ï  sV    ôþýüûúùø	÷
öõô
ó7r  c                       ó(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )rþ   z&ESM Head for masked language modeling.c                    s^   t ƒ  ¡  t |j|j¡| _tj|j|jd| _tj|j|j	dd| _
t t |j	¡¡| _d S )Nrm   F)r^   )r:   r;   r   r[   rt   r¶   rv   rw   rx   rs   r  Ú	Parameterr   Zzerosr^   r‚   rC   r#   r$   r;   F  s
   
zEsmLMHead.__init__c                 K   s0   |   |¡}t|ƒ}|  |¡}|  |¡| j }|S r°   )r¶   r0   rx   r  r^   ©rB   ÚfeaturesÚkwargsr!   r#   r#   r$   rP   N  s
   

zEsmLMHead.forward©rQ   rR   rS   rT   r;   rP   rW   r#   r#   rC   r$   rþ   C  s    rþ   z›
    ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
    output) e.g. for GLUE tasks.
    )Zcustom_introc                       óž   e Zd Z‡ fdd„Ze									ddeej deej deej deej deej	 d	eej d
ee
 dee
 dee
 deeef fdd„ƒZ‡  ZS )ÚEsmForSequenceClassificationc                    s>   t ƒ  |¡ |j| _|| _t|dd| _t|ƒ| _|  ¡  d S ©NFr  )	r:   r;   Ú
num_labelsrƒ   r  rú   ÚEsmClassificationHeadÚ
classifierr  r‚   rC   r#   r$   r;   _  s   
z%EsmForSequenceClassification.__init__Nr‡   rˆ   rp   r£   r‰   r  r§   ró   rô   rO   c
              
   C   sr  |	dur|	n| j j}	| j||||||||	d}
|
d }|  |¡}d}|dur™| |j¡}| j jdu rV| jdkr<d| j _n| jdkrR|jt	j
ksM|jt	jkrRd| j _nd| j _| j jdkrttƒ }| jdkrn|| ¡ | ¡ ƒ}n+|||ƒ}n%| j jdkr‹tƒ }|| d| j¡| d¡ƒ}n| j jdkr™tƒ }|||ƒ}|	s¯|f|
d	d…  }|dur­|f| S |S t|||
j|
jd
S )a  
        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ˆ   rp   r£   r‰   r§   ró   rô   r   r   r\   Zsingle_label_classificationZmulti_label_classificationr   r   r  )rƒ   r  rú   r/  rI   rF   Zproblem_typer-  r8   r   r   rU   r	   re   r   rb   r   r   r¢   rg   ©rB   r‡   rˆ   rp   r£   r‰   r  r§   ró   rô   r¯   r  r!  r   r"  rË   r#   r#   r$   rP   i  sT   ø



"


üz$EsmForSequenceClassification.forward©	NNNNNNNNN)rQ   rR   rS   r;   r   r   r   r#  rV   r²   r³   r   r   r   rP   rW   r#   r#   rC   r$   r+  X  sB    
öþýüûúùø	÷
ö
õr+  c                       r*  )ÚEsmForTokenClassificationc                    sN   t ƒ  |¡ |j| _t|dd| _t |j¡| _t 	|j
|j¡| _|  ¡  d S r,  )r:   r;   r-  r  rú   r   ry   rz   r{   r[   rt   r/  r  r‚   rC   r#   r$   r;   ²  s   z"EsmForTokenClassification.__init__Nr‡   rˆ   rp   r£   r‰   r  r§   ró   rô   rO   c
              
   C   sÂ   |	dur|	n| j j}	| j||||||||	d}
|
d }|  |¡}|  |¡}d}|durAtƒ }| |j¡}|| d| j	¡| d¡ƒ}|	sW|f|
dd…  }|durU|f| S |S t
|||
j|
jdS )zÛ
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr0  r   r   r   r  )rƒ   r  rú   r{   r/  r   rI   rF   rb   r-  r   r¢   rg   r1  r#   r#   r$   rP   ¼  s8   ø

üz!EsmForTokenClassification.forwardr2  )rQ   rR   rS   r;   r   r   r   r#  rV   r²   r³   r   r   r   rP   rW   r#   r#   rC   r$   r3  °  sB    
öþýüûúùø	÷
ö
õr3  c                       r$  )r.  z-Head for sentence-level classification tasks.c                    s@   t ƒ  ¡  t |j|j¡| _t |j¡| _t |j|j	¡| _
d S r°   )r:   r;   r   r[   rt   r¶   ry   rz   r{   r-  Úout_projr‚   rC   r#   r$   r;   õ  s   
zEsmClassificationHead.__init__c                 K   sL   |d d …dd d …f }|   |¡}|  |¡}t |¡}|   |¡}|  |¡}|S r÷   )r{   r¶   r   Útanhr4  r&  r#   r#   r$   rP   û  s   




zEsmClassificationHead.forwardr)  r#   r#   rC   r$   r.  ò  s    r.  c                 C   s6   |   |¡ ¡ }tj|dd |¡| | }| ¡ | S )a  
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's `utils.make_positions`.

    Args:
        x: torch.Tensor x:

    Returns: torch.Tensor
    r   r   )r_   rU   r   ZcumsumrG   r   )r‡   rl   rŠ   ÚmaskZincremental_indicesr#   r#   r$   r…     s   r…   )r  r+  r3  r  rù   )r   )@rT   r-   Útypingr   r   r   r   r   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r   r   Úutilsr   r   r   r   Zconfiguration_esmr   Zmodeling_flash_attention_utilsr   Z
get_loggerrQ   rÃ   r%   r*   r0   r2   r5   ÚModuler6   rX   rk   r   rµ   r¾   rÉ   rÈ   rÔ   r×   rØ   rá   rö   rù   r  r  rþ   r+  r3  r.  r…   Ú__all__r#   r#   r#   r$   Ú<module>   sh   
+#[ qþ3Vb 8SÿRA
