U
    ,È-eÛ  ã                   @   sl  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 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 ddlmZ e  e!¡Z"dZ#dZ$ddg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+ƒ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+ƒZ6G d0d1„ d1eƒZ7d2Z8d3Z9ed4e8ƒG d5d6„ d6e7ƒƒZ:ed7e8ƒG d8d9„ d9e7ƒƒZ;G d:d;„ d;e	j+ƒZ<ed<e8ƒG d=d>„ d>e7ƒƒZ=ed?e8ƒG d@dA„ dAe7ƒƒZ>G dBdC„ dCe	j+ƒZ?dFdDdE„Z@dS )Gz PyTorch ESM model.é    N)ÚListÚOptionalÚTupleÚUnion)Únn)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELossé   )Úadd_code_sample_docstringsÚadd_start_docstringsÚ%add_start_docstrings_to_model_forward)Ú)BaseModelOutputWithPastAndCrossAttentionsÚ,BaseModelOutputWithPoolingAndCrossAttentionsÚMaskedLMOutputÚSequenceClassifierOutputÚTokenClassifierOutput)ÚPreTrainedModelÚ find_pruneable_heads_and_indicesÚprune_linear_layer)Úloggingé   )Ú	EsmConfigzfacebook/esm2_t6_8M_UR50Dr   zfacebook/esm2_t12_35M_UR50Dc                 C   s&   | j ddd\}}tj| |fddS )Né   éÿÿÿÿ©Údim)ÚchunkÚtorchÚcat)ÚxÚx1Zx2© r"   úe/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/esm/modeling_esm.pyÚrotate_half3   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_emb8   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#   Úgelu?   s    r/   c                 C   s   | |   dd¡ S )zJMake layer symmetric in final two dimensions, used for contact prediction.r   r%   )Ú	transposer.   r"   r"   r#   Ú
symmetrizeF   s    r1   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a12ÚavgÚ
normalizedr"   r"   r#   Úaverage_product_correctK   s    
r5   c                       sR   e Zd ZdZedœ‡ fdd„Zddd„Zejeje	ejejf dœ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                    sN   t ƒ  ¡  ddt d|d¡ ¡ |   }|}|  d|¡ d | _d | _d | _d S )Nr*   i'  r   r   Úinv_freq)	ÚsuperÚ__init__r   ÚarangeÚfloatÚregister_bufferÚ_seq_len_cachedÚ_cos_cachedÚ_sin_cached)Úselfr   r7   ©Ú	__class__r"   r#   r9   ^   s    
zRotaryEmbedding.__init__r   c                 C   s¶   |j | }|| jks"| jj|jkrª|| _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>   rD   r   r:   Útype_asr7   Úouterr   Útor'   r(   r?   )r@   r    Úseq_dimensionZseq_lenÚtZfreqsZembr"   r"   r#   Ú_update_cos_sin_tablesi   s    
z&RotaryEmbedding._update_cos_sin_tables)ÚqÚkÚreturnc                 C   s6   | j |dd\| _| _t|| j| jƒt|| j| jƒfS )Nr%   )rH   )rJ   r>   r?   r)   )r@   rK   rL   r"   r"   r#   Úforwardy   s    þzRotaryEmbedding.forward)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úintr9   rJ   r   ÚTensorr   rN   Ú__classcell__r"   r"   rA   r#   r6   W   s   
r6   c                       s2   e Zd ZdZd	eedœ‡ 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   )	r8   r9   rW   rX   r   ÚLinearÚ
regressionZSigmoidÚ
activation)r@   rW   ÚbiasrX   rA   r"   r#   r9   …   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
   )ÚnerX   rG   Ú	unsqueezeÚsizeÚviewrZ   ÚweightrD   r5   r1   Úpermuter[   Úsqueeze)	r@   ÚtokensÚ
attentionsZeos_maskÚ
batch_sizeZlayersÚheadsZseqlenÚ_r"   r"   r#   rN   ‘   s    "ÿz EsmContactPredictionHead.forward)Tr   )rO   rP   rQ   rR   rS   r9   rN   rU   r"   r"   rA   r#   rV   ‚   s     üürV   c                       s2   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| _tj|j|j| jd| _|j| _|j| _d S )	N)Úpadding_idx©ZepsÚposition_embedding_typeÚabsoluteÚposition_ids)r   r   F)Ú
persistent)r8   r9   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Úgetattrrl   r<   r   r:   Úmax_position_embeddingsÚexpandrj   Úposition_embeddingsÚtoken_dropoutÚmask_token_id©r@   ÚconfigrA   r"   r#   r9   ª   s(    
  ÿ  ÿzEsmEmbeddings.__init__Nr   c                 C   s   |d kr*|d k	r t || j|ƒ}n
|  |¡}|d kr<|  |¡}|}| jr®| || jk d¡d¡}d}| d¡}|| jk d¡ 	¡ | }	|d|  d|	 d d …d d f   
|j¡}| jdkrÊ|  |¡}
||
 }| jd k	rÞ|  |¡}|d k	rü|| d¡  
|j¡}|S )Nr   ç        g¸…ëQ¸¾?r   rm   )Ú"create_position_ids_from_input_idsrj   Ú&create_position_ids_from_inputs_embedsrs   r~   Zmasked_fillr   r^   r2   r;   rG   Údtyperl   r}   rv   )r@   Ú	input_idsÚattention_maskrn   Úinputs_embedsÚpast_key_values_lengthÚ
embeddingsZmask_ratio_trainZsrc_lengthsZmask_ratio_observedr}   r"   r"   r#   rN   À   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   ©r…   rD   r   )r_   r   r:   rj   ÚlongrD   r^   r|   )r@   rˆ   Úinput_shapeZsequence_lengthrn   r"   r"   r#   r„   í   s    	   ÿz4EsmEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )rO   rP   rQ   rR   r9   rN   r„   rU   r"   r"   rA   r#   ri   ¥   s            ÿ
-ri   c                
       s‚   e Zd Zd‡ fdd„	Zejejdœdd„Zdejeej eej eej eej ee	e	ej   ee
 e	ej dœ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sÖ| 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 (ú)rl   rm   Úrelative_keyÚrelative_key_queryr   r   Úrotaryr   )r8   r9   rr   Únum_attention_headsÚhasattrÚ
ValueErrorrS   Úattention_head_sizeÚall_head_sizer   rY   ÚqueryÚkeyÚvaluerw   Zattention_probs_dropout_probry   rz   rl   Úrotary_embeddingsr{   rp   Údistance_embeddingr6   Ú
is_decoder)r@   r   rl   rA   r"   r#   r9      s0    
ÿ  ÿzEsmSelfAttention.__init__)r    rM   c                 C   s6   |  ¡ d d… | j| jf }| |¡}| dddd¡S )Nr   r   r   r   r
   )r_   r“   r–   r`   rb   )r@   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_attentionsrM   c                 C   s²  |   |¡}|d k	}	|	r4|d k	r4|d }
|d }|}n |	r^|  |  |¡¡}
|  |  |¡¡}|}nv|d k	r´|  |  |¡¡}
|  |  |¡¡}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sB| 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||¡}|| }n4| jd
krt d||¡}t d|
|¡}|| | }|d k	r|| }tjj|dd}|  |¡}|d k	rF|| }t 
||¡}| dddd¡ ¡ }| ¡ d d… | jf }| |¡}|r–||fn|f}| jr®||f }|S )Nr   r   r   r   g      à¿r’   r   r%   r   r‘   r‹   )r…   zbhld,lrd->bhlrzbhrd,lrd->bhlrr
   )r˜   rž   r™   rš   r   r   r–   r   rl   r›   Úmatmulr0   r_   r:   rŒ   rD   r`   rœ   r{   rG   r…   Zeinsumr   Z
functionalZsoftmaxry   rb   Ú
contiguousr—   )r@   rŸ   r‡   r    r¡   r¢   r£   r¤   Zmixed_query_layerZis_cross_attentionZ	key_layerZvalue_layerZ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#   rN   "  sh    








zEsmSelfAttention.forward)N)NNNNNF)rO   rP   rQ   r9   r   rT   rž   r   ÚFloatTensorr   ÚboolrN   rU   r"   r"   rA   r#   rŽ   ÿ   s$         ø÷rŽ   c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )ÚEsmSelfOutputc                    s.   t ƒ  ¡  t |j|j¡| _t |j¡| _d S ©N)	r8   r9   r   rY   rr   Údenserw   rx   ry   r€   rA   r"   r#   r9   Š  s    
zEsmSelfOutput.__init__c                 C   s    |   |¡}|  |¡}|| }|S r¬   ©r­   ry   ©r@   rŸ   Zinput_tensorr"   r"   r#   rN     s    

zEsmSelfOutput.forward©rO   rP   rQ   r9   rN   rU   r"   r"   rA   r#   r«   ‰  s   r«   c                       s.   e Zd Z‡ fdd„Zdd„ Zd	dd„Z‡  ZS )
ÚEsmAttentionc                    s>   t ƒ  ¡  t|ƒ| _t|ƒ| _tƒ | _tj	|j
|jd| _	d S )Nrk   )r8   r9   rŽ   r@   r«   ÚoutputÚsetÚpruned_headsr   rt   rr   ru   r€   rA   r"   r#   r9   —  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   r@   r“   r–   r´   r   r˜   r™   rš   r²   r­   r—   Úunion)r@   rg   Úindexr"   r"   r#   Úprune_headsž  s       ÿzEsmAttention.prune_headsNFc              	   C   sF   |   |¡}|  |||||||¡}	|  |	d |¡}
|
f|	dd …  }|S )Nr   r   )rt   r@   r²   )r@   rŸ   r‡   r    r¡   r¢   r£   r¤   Zhidden_states_lnZself_outputsÚattention_outputr¨   r"   r"   r#   rN   °  s    

ù	zEsmAttention.forward)NNNNNF)rO   rP   rQ   r9   r¸   rN   rU   r"   r"   rA   r#   r±   –  s         ør±   c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )ÚEsmIntermediatec                    s    t ƒ  ¡  t |j|j¡| _d S r¬   )r8   r9   r   rY   rr   Úintermediate_sizer­   r€   rA   r"   r#   r9   Ê  s    
zEsmIntermediate.__init__©rŸ   rM   c                 C   s   |   |¡}t|ƒ}|S r¬   )r­   r/   )r@   rŸ   r"   r"   r#   rN   Î  s    
zEsmIntermediate.forward©rO   rP   rQ   r9   r   rT   rN   rU   r"   r"   rA   r#   rº   É  s   rº   c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )Ú	EsmOutputc                    s.   t ƒ  ¡  t |j|j¡| _t |j¡| _	d S r¬   )
r8   r9   r   rY   r»   rr   r­   rw   rx   ry   r€   rA   r"   r#   r9   Õ  s    
zEsmOutput.__init__c                 C   s    |   |¡}|  |¡}|| }|S r¬   r®   r¯   r"   r"   r#   rN   Ú  s    

zEsmOutput.forwardr°   r"   r"   rA   r#   r¾   Ô  s   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rV| jsLt| › dƒ‚t|ƒ| _	t
|ƒ| _t|ƒ| _tj|j|jd| _d S )Nr   z> should be used as a decoder model if cross attention is addedrk   )r8   r9   Zchunk_size_feed_forwardZseq_len_dimr±   Ú	attentionr   Úadd_cross_attentionÚRuntimeErrorÚcrossattentionrº   Úintermediater¾   r²   r   rt   rr   ru   r€   rA   r"   r#   r9   â  s    




zEsmLayer.__init__NFc              	   C   s  |d k	r|d d… nd }| j |||||d}	|	d }
| jrP|	dd… }|	d }n|	dd … }d }| jrÞ|d k	rÞt| dƒsˆtd| › dƒ‚|d k	rœ|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)r@   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#   rN   ñ  sL    û


ÿù	


zEsmLayer.forwardc                 C   s$   |   |¡}|  |¡}|  ||¡}|S r¬   )rt   rÄ   r²   )r@   r¹   Zattention_output_lnZintermediate_outputrÈ   r"   r"   r#   rÇ   0  s    

zEsmLayer.feed_forward_chunk)NNNNNF)rO   rP   rQ   r9   rN   rÇ   rU   r"   r"   rA   r#   r¿   á  s         ø
?r¿   c                	       s&   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¿   )Ú.0rh   ©r   r"   r#   Ú
<listcomp>;  s     z'EsmEncoder.__init__.<locals>.<listcomp>rk   F)r8   r9   r   r   Z
ModuleListÚrangeÚnum_hidden_layersÚlayerrt   rr   ru   Úemb_layer_norm_afterÚgradient_checkpointingr€   rA   rË   r#   r9   8  s
    
 zEsmEncoder.__init__NFTc              	      s†  | j r| jr|rt d¡ d}|	r&dnd }ˆ r2dnd }ˆ rF| jjrFdnd }|rRdnd }t| jƒD ]Î\}}|	rv||f }|d k	r†|| nd }|d k	rš|| nd ‰| j rÖ| jrÖ‡ ‡fdd„}tj	j
 
||ƒ|||||¡}n||||||ˆˆ ƒ}|d }|r||d f }ˆ r`||d f }| jjr`||d	 f }q`| jrB|  |¡}|	rR||f }|
sttd
d„ |||||fD ƒƒS t|||||dS )Nzh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...Fr"   c                    s   ‡ ‡‡fdd„}|S )Nc                     s   ˆ | ˆˆfžŽ S r¬   r"   )Úinputs)Úmoduler¤   r£   r"   r#   Úcustom_forwardb  s    zIEsmEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr"   )rÓ   rÔ   rÅ   )rÓ   r#   Úcreate_custom_forwarda  s    z1EsmEncoder.forward.<locals>.create_custom_forwardr   r   r   r   c                 s   s   | ]}|d k	r|V  qd S r¬   r"   )rÊ   Úvr"   r"   r#   Ú	<genexpr>‰  s   øz%EsmEncoder.forward.<locals>.<genexpr>)Úlast_hidden_stateÚpast_key_valuesrŸ   re   Úcross_attentions)rÑ   ZtrainingÚloggerZwarning_oncer   rÁ   Ú	enumeraterÏ   r   ÚutilsÚ
checkpointrÐ   Útupler   )r@   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#   rN   ?  sz    ÿ
ú	ù


ûþûzEsmEncoder.forward)	NNNNNNFFTr°   r"   r"   rA   r#   rÉ   7  s   
         õrÉ   c                       s0   e Zd Z‡ fdd„Zejejdœdd„Z‡  ZS )Ú	EsmPoolerc                    s*   t ƒ  ¡  t |j|j¡| _t ¡ | _d S r¬   )r8   r9   r   rY   rr   r­   ZTanhr[   r€   rA   r"   r#   r9   Ÿ  s    
zEsmPooler.__init__r¼   c                 C   s(   |d d …df }|   |¡}|  |¡}|S ©Nr   )r­   r[   )r@   rŸ   Zfirst_token_tensorÚpooled_outputr"   r"   r#   rN   ¤  s    

zEsmPooler.forwardr½   r"   r"   rA   r#   rä   ž  s   rä   c                   @   s8   e Zd ZdZeZdZdZdddgZdd„ Z	dd
d„Z
dS )ÚEsmPreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ÚesmTr¿   Z#EsmFoldTriangularSelfAttentionBlockri   c                 C   s¤   t |tjƒr:|jjjd| jjd |jdk	r |jj 	¡  nft |tj
ƒrz|jjjd| jjd |jdk	r |jj|j  	¡  n&t |tjƒr |jj 	¡  |jj d¡ dS )zInitialize the weightsr‚   )ZmeanZstdNr*   )Ú
isinstancer   rY   ra   ÚdataZnormal_r   Zinitializer_ranger\   Zzero_rp   rj   rt   Zfill_)r@   rÓ   r"   r"   r#   Ú_init_weights¹  s    

z EsmPreTrainedModel._init_weightsFc                 C   s   t |tƒr||_d S r¬   )ré   rÉ   rÑ   )r@   rÓ   rš   r"   r"   r#   Ú_set_gradient_checkpointingÉ  s    
z.EsmPreTrainedModel._set_gradient_checkpointingN)F)rO   rP   rQ   rR   r   Úconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesrë   rì   r"   r"   r"   r#   rç   ­  s   
rç   a=  

    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 ([`EsmConfig`]): 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.
a¼  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            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)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *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)
        position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `({0}, 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.
        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 [`~file_utils.ModelOutput`] instead of a plain tuple.
z]The bare ESM Model transformer outputting raw hidden-states without any specific head on top.c                       sØ   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zee	 
d¡ƒeeeeddeej eej eej eej eej eej eej eeej  ee ee ee ee eeej ef dœ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|ƒ| _|r2t|ƒnd | _t	|j
|j dd| _|  ¡  d S )NT)rW   r\   )r8   r9   r   ri   rŠ   rÉ   Úencoderrä   ÚpoolerrV   rÎ   r“   Úcontact_headÚ	post_init)r@   r   Úadd_pooling_layerrA   r"   r#   r9     s    


 ÿzEsmModel.__init__c                 C   s   | j jS r¬   ©rŠ   rs   ©r@   r"   r"   r#   Úget_input_embeddings)  s    zEsmModel.get_input_embeddingsc                 C   s   || j _d S r¬   rô   )r@   rš   r"   r"   r#   Úset_input_embeddings,  s    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¸   )r@   Zheads_to_prunerÏ   rg   r"   r"   r#   Ú_prune_heads/  s    zEsmModel._prune_headsz(batch_size, sequence_length)©rÞ   Úoutput_typerí   N)r†   r‡   rn   r    rˆ   r¡   r¢   rÙ   rà   r¤   rá   râ   rM   c                 C   s
  |
dk	r|
n| j j}
|dk	r |n| j j}|dk	r4|n| j j}| j jrZ|	dk	rP|	n| j j}	nd}	|dk	rx|dk	rxtdƒ‚n@|dk	r–|  ||¡ | ¡ }n"|dk	r°| ¡ dd… }ntdƒ‚|\}}|dk	rÎ|j	n|j	}|dk	rî|d d j
d nd}|dkrtj||| f|d}|  ||¡}| j jrl|dk	rl| ¡ \}}}||f}|dkr`tj||d}|  |¡}nd}|  || j j¡}| j|||||d	}| j|||||||	|
||d

}|d }| jdk	rÐ|  |¡nd}|sî||f|dd…  S t|||j|j|j|jdS )a  
        encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
            Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        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`).
        NFzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embedsr   r   rC   )r†   rn   r‡   rˆ   r‰   )	r‡   r    r¡   r¢   rÙ   rà   r¤   rá   râ   r   )rØ   Zpooler_outputrÙ   rŸ   re   rÚ   )r   r¤   rá   Úuse_return_dictr   rà   r•   Z%warn_if_padding_and_no_attention_maskr_   rD   r&   r   ZonesZget_extended_attention_maskZinvert_attention_maskZget_head_maskrÎ   rŠ   rï   rð   r   rÙ   rŸ   re   rÚ   )r@   r†   r‡   rn   r    rˆ   r¡   r¢   rÙ   rà   r¤   rá   râ   r   rf   r§   rD   r‰   Zextended_attention_maskZencoder_batch_sizeZencoder_sequence_lengthrh   Zencoder_hidden_shapeZencoder_extended_attention_maskZembedding_outputZencoder_outputsÚsequence_outputræ   r"   r"   r#   rN   7  sx    )ÿ



ûöú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
   é   )re   r   Ústackr^   rñ   )r@   rd   r‡   Zattnsr"   r"   r#   Úpredict_contacts¶  s
    zEsmModel.predict_contacts)T)NNNNNNNNNNNN)rO   rP   rQ   rR   r9   rö   r÷   rù   r   ÚESM_INPUTS_DOCSTRINGÚformatr   Ú_CHECKPOINT_FOR_DOCr   Ú_CONFIG_FOR_DOCr   r   rT   r   r©   rª   r   r   rN   r   rU   r"   r"   rA   r#   rî     sN   ý            óòyrî   z1ESM Model with a `language modeling` head on top.c                       sÂ   e Zd ZdgZ‡ fdd„Zdd„ Zdd„ Zee 	d¡ƒe
eeed	d
deej eej eej eej eej eej eej eej ee ee ee eeef dœ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ó   )
r8   r9   r   rÛ   Úwarningrî   rè   Ú	EsmLMHeadÚlm_headÚinit_weightsr€   rA   r"   r#   r9   Æ  s    ÿ
zEsmForMaskedLM.__init__c                 C   s   | j jS r¬   ©r	  Údecoderrõ   r"   r"   r#   Úget_output_embeddingsÔ  s    z$EsmForMaskedLM.get_output_embeddingsc                 C   s   || j _d S r¬   r  )r@   Znew_embeddingsr"   r"   r#   Úset_output_embeddings×  s    z$EsmForMaskedLM.set_output_embeddingsúbatch_size, sequence_lengthz<mask>)rÞ   rû   rí   ÚmaskN)r†   r‡   rn   r    rˆ   r¡   r¢   Úlabelsr¤   rá   râ   rM   c                 C   s¾   |dk	r|n| j j}| j||||||||	|
|d
}|d }|  |¡}d}|dk	r~tƒ }| |j¡}|| d| j j¡| d¡ƒ}|sª|f|dd…  }|dk	r¦|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]`
        kwargs (`Dict[str, any]`, optional, defaults to *{}*):
            Used to hide legacy arguments that have been deprecated.
        N)	r‡   rn   r    rˆ   r¡   r¢   r¤   rá   râ   r   r   r   ©ÚlossÚlogitsrŸ   re   )r   rü   rè   r	  r   rG   rD   r`   rq   r   rŸ   re   )r@   r†   r‡   rn   r    rˆ   r¡   r¢   r  r¤   rá   râ   r¨   rý   Zprediction_scoresZmasked_lm_lossÚloss_fctr²   r"   r"   r#   rN   Ú  s:    ö
üzEsmForMaskedLM.forwardc                 C   s   | j j||dS )N)r‡   )rè   r   )r@   rd   r‡   r"   r"   r#   r     s    zEsmForMaskedLM.predict_contacts)NNNNNNNNNNN)rO   rP   rQ   Z_tied_weights_keysr9   r  r  r   r  r  r   r  r   r  r   r   Ú
LongTensorrT   r©   rª   r   r   rN   r   rU   r"   r"   rA   r#   r  Â  sJ   ü           ô
ó9r  c                       s(   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 )Nrk   F)r\   )r8   r9   r   rY   rr   r­   rt   ru   rv   rq   r  Ú	Parameterr   Zzerosr\   r€   rA   r"   r#   r9   !  s
    
zEsmLMHead.__init__c                 K   s0   |   |¡}t|ƒ}|  |¡}|  |¡| j }|S r¬   )r­   r/   rv   r  r\   ©r@   ÚfeaturesÚkwargsr    r"   r"   r#   rN   )  s
    

zEsmLMHead.forward©rO   rP   rQ   rR   r9   rN   rU   r"   r"   rA   r#   r    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.
    c                       s’   e Zd Z‡ fdd„Zee d¡ƒeee	e
dd	eej eej eej eej eej eej ee ee ee eee	f dœ
dd„ƒƒZ‡  ZS )
ÚEsmForSequenceClassificationc                    s>   t ƒ  |¡ |j| _|| _t|dd| _t|ƒ| _|  ¡  d S ©NFr  )	r8   r9   Ú
num_labelsr   rî   rè   ÚEsmClassificationHeadÚ
classifierr
  r€   rA   r"   r#   r9   ;  s    
z%EsmForSequenceClassification.__init__r  rú   N©
r†   r‡   rn   r    rˆ   r  r¤   rá   râ   rM   c
              
   C   s|  |	dk	r|	n| j j}	| j||||||||	d}
|
d }|  |¡}d}|dk	r8| |j¡}| j jdkr®| jdkrzd| j _n4| jdkr¦|jt	j
ksœ|jt	jkr¦d| j _nd| j _| j jdkrêtƒ }| jdkrÞ|| ¡ | ¡ ƒ}n
|||ƒ}nN| j jdkrtƒ }|| d| j¡| d¡ƒ}n| j jdkr8tƒ }|||ƒ}|	sh|f|
d	d…  }|dk	rd|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‡   rn   r    rˆ   r¤   rá   râ   r   r   rZ   Zsingle_label_classificationZmulti_label_classificationr   r   r  )r   rü   rè   r   rG   rD   Zproblem_typer  r…   r   rŒ   rS   r	   rc   r   r`   r   r   rŸ   re   ©r@   r†   r‡   rn   r    rˆ   r  r¤   rá   râ   r¨   rý   r  r  r  r²   r"   r"   r#   rN   E  sT    ø




"


üz$EsmForSequenceClassification.forward)	NNNNNNNNN)rO   rP   rQ   r9   r   r  r  r   r  r   r  r   r   r  rT   r©   rª   r   r   rN   rU   r"   r"   rA   r#   r  3  s8   
ý         ö
õr  z¢
    ESM Model 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                       s’   e Zd Z‡ fdd„Zee d¡ƒeee	e
dd	eej eej eej eej eej eej ee ee ee eee	f dœ
dd„ƒƒZ‡  ZS )
ÚEsmForTokenClassificationc                    sN   t ƒ  |¡ |j| _t|dd| _t |j¡| _t 	|j
|j¡| _|  ¡  d S r  )r8   r9   r  rî   rè   r   rw   rx   ry   rY   rr   r   r
  r€   rA   r"   r#   r9   ™  s    z"EsmForTokenClassification.__init__r  rú   Nr!  c
              
   C   sÂ   |	dk	r|	n| j j}	| j||||||||	d}
|
d }|  |¡}|  |¡}d}|dk	r‚tƒ }| |j¡}|| d| j	¡| d¡ƒ}|	s®|f|
dd…  }|dk	rª|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]`.
        Nr"  r   r   r   r  )r   rü   rè   ry   r   r   rG   rD   r`   r  r   rŸ   re   r#  r"   r"   r#   rN   £  s8    ø

üz!EsmForTokenClassification.forward)	NNNNNNNNN)rO   rP   rQ   r9   r   r  r  r   r  r   r  r   r   r  rT   r©   rª   r   r   rN   rU   r"   r"   rA   r#   r$  ‘  s8   
ý         ö
õr$  c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )r  z-Head for sentence-level classification tasks.c                    s@   t ƒ  ¡  t |j|j¡| _t |j¡| _t |j|j	¡| _
d S r¬   )r8   r9   r   rY   rr   r­   rw   rx   ry   r  Úout_projr€   rA   r"   r#   r9   á  s    
zEsmClassificationHead.__init__c                 K   sL   |d d …dd d …f }|   |¡}|  |¡}t |¡}|   |¡}|  |¡}|S rå   )ry   r­   r   Útanhr%  r  r"   r"   r#   rN   ç  s    




zEsmClassificationHead.forwardr  r"   r"   rA   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]   rS   r   ZcumsumrE   rŒ   )r†   rj   r‰   r  Zincremental_indicesr"   r"   r#   rƒ   ñ  s    rƒ   )r   )ArR   r,   Útypingr   r   r   r   r   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Z
file_utilsr   r   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r   r   rÝ   r   Zconfiguration_esmr   Z
get_loggerrO   rÛ   r  r  Z!ESM_PRETRAINED_MODEL_ARCHIVE_LISTr$   r)   r/   r1   r5   ÚModuler6   rV   ri   rŽ   r«   r±   rº   r¾   r¿   rÉ   rä   rç   ZESM_START_DOCSTRINGr  rî   r  r  r  r$  r  rƒ   r"   r"   r"   r#   Ú<module>   st   
þ+#Z 3Vg!*þ 7[ûWûF