a
    h                     @   s  d Z ddlZddl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 ddlmZmZmZmZmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZmZm Z m!Z! ddl"m#Z#m$Z$ 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/Z0G dd dej/Z1G dd dej/Z2dGej/ej3ej3ej3eej3 e4e4eej3 ee d!	d"d#Z5G d$d% d%ej/Z6G d&d' d'ej/Z7G d(d) d)ej/Z8G d*d+ d+ej/Z9G d,d- d-ej/Z:G d.d/ d/eZ;G d0d1 d1ej/Z<G d2d3 d3ej/Z=eG d4d5 d5eZ>eG d6d7 d7e>Z?eG d8d9 d9e>Z@G d:d; d;ej/ZAed<d=G d>d? d?e>ZBeG d@dA dAe>ZCG dBdC dCej/ZDdDdE ZEg dFZFdS )HzPyTorch ESM model.    N)CallableOptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )GradientCheckpointingLayer)"BaseModelOutputWithCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentionsMaskedLMOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack) find_pruneable_heads_and_indicesprune_linear_layer)TransformersKwargsauto_docstringcan_return_tuplelogging)OutputRecordercheck_model_inputs   )	EsmConfigc                 C   s&   | j ddd\}}tj| |fddS )N   dim)chunktorchcat)xx1Zx2 r&   `/var/www/html/assistant/venv/lib/python3.9/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    r3   c                 C   s   | |  dd S )zJMake layer symmetric in final two dimensions, used for contact prediction.r   r)   )	transposer2   r&   r&   r'   
symmetrize@   s    r5   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    
r8   c                       s^   e Zd ZU dZejed< 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.
    inv_freqr   c                    sT   t    ddtjd|dtjd |   }|}| d| d | _d | _d | _	d S )Nr.   i'  r   r   dtyper:   )
super__init__r"   arangeZint64floatregister_buffer_seq_len_cached_cos_cached_sin_cached)selfr    r:   	__class__r&   r'   r>   Z   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*   rB   rC   rI   r"   r?   type_asr:   outerr#   tor+   r,   rD   )rE   r$   seq_dimensionZseq_lentZfreqsZembr&   r&   r'   _update_cos_sin_tablese   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)   )rM   r;   )rO   rC   rD   r-   rL   r<   )rE   rP   rQ   r&   r&   r'   forwardu   s    zRotaryEmbedding.forward)r   )__name__
__module____qualname____doc__r"   Tensor__annotations__intr>   rO   tuplerS   __classcell__r&   r&   rF   r'   r9   Q   s
   


r9   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   )	r=   r>   r^   r_   r   Linear
regressionZSigmoid
activation)rE   r^   biasr_   rF   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	   )ner_   rL   	unsqueezesizeviewra   weightrI   r8   r5   Zpermuterb   squeeze)	rE   tokens
attentionsZeos_mask
batch_sizeZlayersheadsZseqlen_r&   r&   r'   rS      s    "z EsmContactPredictionHead.forward)Tr   )rT   rU   rV   rW   rZ   r>   rS   r\   r&   r&   rF   r'   r]   ~   s     r]   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| _| jdkrtj|j|j| jd| _|j| _|j| _d S )	N)padding_idx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getattrrs   rA   r"   r?   max_position_embeddingsexpandrp   position_embeddingstoken_dropoutmask_token_idrE   configrF   r&   r'   r>      s"    

zEsmEmbeddings.__init__Nc           
      C   s  |d u r(|d urt || j}n
| |}|d u r:| |}|}| jr|d ur||| jkdd}d}|d urz|dn|j	d }|| jkd
 | }|d|  d| d d d d f  |j}| jdkr| |}	||	 }| jd ur| |}|d ur||d |j}|S )Nr           gQ?r   rt   )"create_position_ids_from_input_idsrp   &create_position_ids_from_inputs_embedsrz   r   Zmasked_fillr   re   r6   r*   r@   rL   r<   rs   r   r}   )
rE   	input_idsattention_maskru   inputs_embeds
embeddingsZmask_ratio_trainZsrc_lengthsZmask_ratio_observedr   r&   r&   r'   rS      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<   rI   r   )rf   r"   r?   rp   longrI   re   r   )rE   r   input_shapeZsequence_lengthru   r&   r&   r'   r      s    	z4EsmEmbeddings.create_position_ids_from_inputs_embeds)NNNN)rT   rU   rV   rW   r>   rS   r   r\   r&   r&   rF   r'   ro      s       
1ro   r   )	modulequerykeyvaluer   scalingr   	head_maskkwargsc                 K   s  t ||dd| }	t| dr| jdv r|j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rt d
||}n.| jdkrt d
||}t d||}|| }|	| }	|d ur |d d d d d d d |jd f }|	| }	tjj|	dt jd|j}	tjj|	|| jd}	|d urb|	| }	t |	|}|dd }||	fS )Nr   r	   rs   relative_keyrelative_key_queryr   r   r   r;   r   zbhld,lrd->bhlrr   zbhrd,lrd->bhlrr)   )r    r<   )ptraining)r"   matmulr4   hasattrrs   r*   r?   r   rI   rg   distance_embeddingr   rL   r<   Zeinsumr   Z
functionalZsoftmaxZfloat32r   r   
contiguous)r   r   r   r   r   r   r   r   r   attn_weights
seq_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZcausal_maskattn_outputr&   r&   r'   eager_attention_forward   s2    



&
r   c                	       s^   e Zd Zd fdd	Zd	ejeej eej eej eej ee	 e
ej dddZ  ZS )
EsmSelfAttentionNFc                    s<  t    || _|j|j dkrDt|dsDtd|j d|j d|j| _t|j|j | _| j| j | _	t
|j| j	| _t
|j| j	| _t
|j| j	| _|j| _|pt|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| _d| _|j| _|| _| jo4| | _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()rs   rt   r   r   r   r   rotaryr   r.   )r=   r>   r   ry   num_attention_headsr   
ValueErrorrZ   attention_head_sizeall_head_sizer   r`   r   r   r   Zattention_probs_dropout_probr   r   rs   rotary_embeddingsr   rw   r   r9   r   
is_decoder	layer_idxZ	is_causal)rE   r   rs   r   is_cross_attentionrF   r&   r'   r>   3  s8    

zEsmSelfAttention.__init__)hidden_statesr   r   encoder_hidden_statesencoder_attention_maskr   rR   c                 K   s@  |j d d \}}||d| jf}	| ||	dd}
|d u}|rH|n|}|rT|n|}| ||	dd}| ||	dd}|
| jd  }
| jdkr| |
|\}
}t	}| j
jdkr| jdv rtd| j
j d	| j d
t| j
j }|| |
|||f| jsdn| j| j|d|\}}|||d }||fS )Nr   r   r   g      r   eagerr   zESM z attention does not support z^ embeddings. Set attention explicitly to 'eager' with `model.set_attn_implementation('eager')`r   )r   r   r   )r*   r   r   rg   r4   r   r   rs   r   r   r   _attn_implementationr   r   r   r   r   Zreshaper   )rE   r   r   r   r   r   r   rl   r   Zhidden_shapeZquery_layerr   Zcurrent_statesZ	key_layerZvalue_layerZattention_interfacer   r   r&   r&   r'   rS   U  sB    	

	
zEsmSelfAttention.forward)NNF)NNNN)rT   rU   rV   r>   r"   rX   r   FloatTensorr   r   r[   rS   r\   r&   r&   rF   r'   r   2  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)	r=   r>   r   r`   ry   denser~   r   r   r   rF   r&   r'   r>     s    
zEsmSelfOutput.__init__c                 C   s    |  |}| |}|| }|S r   r   r   rE   r   Zinput_tensorr&   r&   r'   rS     s    

zEsmSelfOutput.forwardrT   rU   rV   r>   rS   r\   r&   r&   rF   r'   r     s   r   c                       s:   e Zd Zd
 fdd	Zdd Zdee ddd	Z  ZS )EsmAttentionNFc                    sD   t    t|||d| _t|| _t | _tj	|j
|jd| _	d S )N)r   r   rq   )r=   r>   r   rE   r   outputsetpruned_headsr   r{   ry   r|   )rE   r   r   r   rF   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   rE   r   r   r   r   r   r   r   r   r   r   union)rE   rm   indexr&   r&   r'   prune_heads  s    zEsmAttention.prune_headsr   c           
      K   s:   |  |}| j|f||||d|\}}	| ||}|S )Nr   r   r   r   )r{   rE   r   )
rE   r   r   r   r   r   r   Zhidden_states_lnr   rn   r&   r&   r'   rS     s    	

zEsmAttention.forward)NF)NNNN)	rT   rU   rV   r>   r   r   r   rS   r\   r&   r&   rF   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   )r=   r>   r   r`   ry   intermediate_sizer   r   rF   r&   r'   r>     s    
zEsmIntermediate.__init__r   rR   c                 C   s   |  |}t|}|S r   )r   r3   )rE   r   r&   r&   r'   rS     s    
zEsmIntermediate.forwardrT   rU   rV   r>   r"   rX   rS   r\   r&   r&   rF   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   )
r=   r>   r   r`   r   ry   r   r~   r   r   r   rF   r&   r'   r>     s    
zEsmOutput.__init__c                 C   s    |  |}| |}|| }|S r   r   r   r&   r&   r'   rS     s    

zEsmOutput.forwardr   r&   r&   rF   r'   r     s   r   c                       s8   e Zd Z fddZd	ee dddZdd Z  ZS )
EsmLayerc                    s   t    |j| _d| _t|| _|j| _|j| _| jrZ| jsLt|  dt|dd| _	t
|| _t|| _tj|j|jd| _d S )Nr   z> should be used as a decoder model if cross attention is addedT)r   rq   )r=   r>   Zchunk_size_feed_forwardZseq_len_dimr   	attentionr   Zadd_cross_attentionRuntimeErrorcrossattentionr   intermediater   r   r   r{   ry   r|   r   rF   r&   r'   r>     s    



zEsmLayer.__init__Nr   c           	      K   sj   | j |f||d|}| jr\|d ur\t| ds@td|  d| j|f||||d|}| |}|S )N)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)	rE   r   r   r   r   r   r   attention_outputlayer_outputr&   r&   r'   rS     s2    	

	
zEsmLayer.forwardc                 C   s$   |  |}| |}| ||}|S r   )r{   r   r   )rE   r   Zattention_output_lnZintermediate_outputr   r&   r&   r'   r     s    

zEsmLayer.feed_forward_chunk)NNNN)	rT   rU   rV   r>   r   r   rS   r   r\   r&   r&   rF   r'   r     s       #r   c                       s4   e Zd Z fddZedee 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   ).0rn   r   r&   r'   
<listcomp>      z'EsmEncoder.__init__.<locals>.<listcomp>rq   F)r=   r>   r   r   Z
ModuleListrangenum_hidden_layerslayerr{   ry   r|   emb_layer_norm_afterZgradient_checkpointingr   rF   r   r'   r>     s
    
 zEsmEncoder.__init__Nr   c           
      K   s\   t | jD ]6\}}|d ur"|| nd }	||f||	||d|}q
| jrR| |}t|dS )Nr   )last_hidden_state)	enumerater   r   r   )
rE   r   r   r   r   r   r   iZlayer_moduleZlayer_head_maskr&   r&   r'   rS   "  s    
	
zEsmEncoder.forward)NNNN)	rT   rU   rV   r>   r   r   r   rS   r\   r&   r&   rF   r'   r     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   )r=   r>   r   r`   ry   r   ZTanhrb   r   rF   r&   r'   r>   ?  s    
zEsmPooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   rb   )rE   r   Zfirst_token_tensorpooled_outputr&   r&   r'   rS   D  s    

zEsmPooler.forwardr   r&   r&   rF   r'   r   >  s   r   c                   @   sp   e Zd ZU eed< dZdZg dZdgZdZ	dZ
dZdZeeedddgeedd	dgd
Zdd Zdd ZdS )EsmPreTrainedModelr   esmT)r   Z#EsmFoldTriangularSelfAttentionBlockro   zposition_embeddings.weightr   r   )r   Z
layer_namer   )r   rk   Zcross_attentionsc                 C   s   t |tjr:|jjjd| jjd |jdur|jj	  n~t |tj
rz|jjjd| jjd |jdur|jj|j 	  n>t |tjr|jj	  |jjd nt |tr|jj	  dS )zInitialize the weightsr   )meanZstdNr.   )
isinstancer   r`   rh   dataZnormal_r   Zinitializer_rangerc   Zzero_rw   rp   r{   Zfill_	EsmLMHead)rE   r   r&   r&   r'   _init_weightsb  s    


z EsmPreTrainedModel._init_weightsc                 C   s   d S r   r&   rE   r&   r&   r'   get_output_embeddingst  s    z(EsmPreTrainedModel.get_output_embeddingsN)rT   rU   rV   r   rY   Zbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ"_keys_to_ignore_on_load_unexpectedZ_supports_flash_attnZ_supports_sdpaZ_supports_flex_attnZ_supports_attention_backendr   r   r   Z_can_record_outputsr   r   r&   r&   r&   r'   r   M  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e	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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://huggingface.co/papers/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 )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        NT)r^   rc   )r=   r>   r   ro   r   r   encoderr   poolerr]   r   r   contact_head	post_init)rE   r   add_pooling_layerrF   r&   r'   r>     s    

zEsmModel.__init__c                 C   s   | j jS r   r   rz   r   r&   r&   r'   get_input_embeddings  s    zEsmModel.get_input_embeddingsc                 C   s   || j _d S r   r   )rE   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   )rE   Zheads_to_pruner   rm   r&   r&   r'   _prune_heads  s    zEsmModel._prune_headsN)	r   r   ru   r   r   r   r   r   rR   c                 K   s"  |du |duA rt d|du r.| j||d}| jjdkrz|jdd \}	}
|du rhtj|	|
f|jd}| j||	|
fd}| jj	r|dur|
 \}}}||f}|du rtj||jd}| |}nd}| || jj}| j|f||||d|}|d	 }| jdur| |nd}t||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.
        Nz:You must specify exactly one of input_ids or inputs_embeds)r   ru   Zflash_attention_2r   rH   )r   r   r   )r   Zpooler_output)r   r   r   r   r*   r"   ZonesrI   Zget_extended_attention_maskr   rf   Zinvert_attention_maskZget_head_maskr   r   r   r   )rE   r   r   ru   r   r   r   r   r   rl   r   Zencoder_batch_sizeZencoder_sequence_lengthrn   Zencoder_hidden_shapeZencoder_extended_attention_maskZencoder_outputssequence_outputr   r&   r&   r'   rS     sL    zEsmModel.forwardc                 C   s`   | ||dddj }tj|dd}||ddd9 }||ddd9 }| ||S )NT)r   Zreturn_dictZoutput_attentionsr   r   r   r	      )rk   r"   stackre   r   )rE   rj   r   Zattnsr&   r&   r'   predict_contacts  s
    zEsmModel.predict_contacts)T)NNNNNNN)rT   rU   rV   rW   r>   r   r   r   r   r   r   r"   rX   r   r   r   r[   r   rS   r   r\   r&   r&   rF   r'   r   z  s4          Qr   c                       s   e Zd ZdgZ fddZdd Zdd Zee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f d	
d
dZdd Z  ZS )EsmForMaskedLMzlm_head.decoder.weightc                    sH   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   loggerwarningr   r   r   lm_headinit_weightsr   r   rF   r&   r'   r>     s    
zEsmForMaskedLM.__init__c                 C   s   | j jS r   r  decoderr   r&   r&   r'   r     s    z$EsmForMaskedLM.get_output_embeddingsc                 C   s   || j _d S r   r  )rE   Znew_embeddingsr&   r&   r'   set_output_embeddings   s    z$EsmForMaskedLM.set_output_embeddingsN)
r   r   ru   r   r   r   r   labelsr   rR   c	              	   K   s   | j |f||||||d|	}
|
d }| |}d}|durlt }||j}||d| jj|d}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]`
        )r   ru   r   r   r   r   r   Nr   losslogitsr   rk   )r   r  r   rL   rI   rg   r   rx   r   r   rk   )rE   r   r   ru   r   r   r   r   r  r   outputsr   Zprediction_scoresZmasked_lm_lossloss_fctr&   r&   r'   rS   #  s2    

zEsmForMaskedLM.forwardc                 C   s   | j j||dS )N)r   )r   r   )rE   rj   r   r&   r&   r'   r   S  s    zEsmForMaskedLM.predict_contacts)NNNNNNNN)rT   rU   rV   Z_tied_weights_keysr>   r   r  r   r   r   r"   
LongTensorrX   r   r   r   r   r[   r   rS   r   r\   r&   r&   rF   r'   r   	  s6           
.r   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 )Nrq   F)rc   )r=   r>   r   r`   ry   r   r{   r|   r}   rx   r  	Parameterr"   Zzerosrc   r   rF   r&   r'   r>   Z  s
    
zEsmLMHead.__init__c                 K   s0   |  |}t|}| |}| || j }|S r   )r   r3   r}   r  rc   rE   featuresr   r$   r&   r&   r'   rS   b  s
    

zEsmLMHead.forwardrT   rU   rV   rW   r>   rS   r\   r&   r&   rF   r'   r   W  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                       sr   e Zd Z fddZeedeej eej	 eej eej	 eej
 eej ee eeef dddZ  ZS )EsmForSequenceClassificationc                    sF   t  | |j| _|| _t|dd| _t|| _|   | 	  d S NFr   )
r=   r>   
num_labelsr   r   r   EsmClassificationHead
classifierr  r   r   rF   r&   r'   r>   s  s    
z%EsmForSequenceClassification.__init__Nr   r   ru   r   r   r  r   rR   c                 K   s:  | j |f||||d|}|d }	| |	}
d}|dur&||
j}| jjdu r| jdkrhd| j_n4| jdkr|jtj	ks|jtj
krd| j_nd| j_| jjdkrt }| jdkr||
 | }n
||
|}nN| jjdkrt }||
d| j|d}n| jjdkr&t }||
|}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).
        r   ru   r   r   r   Nr   ra   Zsingle_label_classificationZmulti_label_classificationr   r  )r   r  rL   rI   r   Zproblem_typer  r<   r"   r   rZ   r   ri   r   rg   r   r   r   rk   rE   r   r   ru   r   r   r  r   r
  r   r	  r  r  r&   r&   r'   rS     sL    



"


z$EsmForSequenceClassification.forward)NNNNNN)rT   rU   rV   r>   r   r   r   r"   r  rX   r   r   r   r   r[   r   rS   r\   r&   r&   rF   r'   r  l  s&         
r  c                       sr   e Zd Z fddZeedeej eej	 eej eej	 eej
 eej ee eeef dddZ  ZS )EsmForTokenClassificationc                    sV   t  | |j| _t|dd| _t|j| _t	|j
|j| _|   |   d S r  )r=   r>   r  r   r   r   r~   r   r   r`   ry   r  r  r   r   rF   r&   r'   r>     s    z"EsmForTokenClassification.__init__Nr  c                 K   s   | j |f||||d|}|d }	| |	}	| |	}
d}|durpt }||
j}||
d| j|d}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]`.
        r  r   Nr   r  )r   r   r  r   rL   rI   rg   r  r   r   rk   r  r&   r&   r'   rS     s0    	

z!EsmForTokenClassification.forward)NNNNNN)rT   rU   rV   r>   r   r   r   r"   r  rX   r   r   r   r   r[   r   rS   r\   r&   r&   rF   r'   r    s&         
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   )r=   r>   r   r`   ry   r   r~   r   r   r  out_projr   rF   r&   r'   r>     s    
zEsmClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r   )r   r   r"   tanhr  r  r&   r&   r'   rS     s    




zEsmClassificationHead.forwardr  r&   r&   rF   r'   r    s   r  c                 C   s2   |  | }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   )rd   rZ   r"   ZcumsumrJ   r   )r   rp   maskZincremental_indicesr&   r&   r'   r     s    r   )r   r  r  r   r   )r   N)GrW   r0   typingr   r   r   r"   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zmodeling_layersr
   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r   Zprocessing_utilsr   Zpytorch_utilsr   r   utilsr   r   r   r   Zutils.genericr   r   Zconfiguration_esmr   Z
get_loggerrT   r   r(   r-   r3   r5   r8   Moduler9   r]   ro   rX   r@   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   __all__r&   r&   r&   r'   <module>   sz   
-#f  2Y0:$, ML;