
    g                         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j         e!          Z"dZ#dZ$d Z%d Z&d Z'd Z(d Z) G d dej	        j*                  Z+ G d de	j*                  Z, G d de	j*                  Z- G d de	j*                  Z. G d de	j*                  Z/ G d de	j*                  Z0 G d  d!e	j*                  Z1 G d" d#e	j*                  Z2 G d$ d%e	j*                  Z3 G d& d'e	j*                  Z4 G d( d)e	j*                  Z5 G d* d+e          Z6d,Z7d-Z8 ed.e7           G d/ d0e6                      Z9 ed1e7           G d2 d3e6                      Z: G d4 d5e	j*                  Z; ed6e7           G d7 d8e6                      Z< ed9e7           G d: d;e6                      Z= G d< d=e	j*                  Z>d?d>Z?dS )@z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   c                 h    |                      dd          \  }}t          j        | |fd          S )N   dim)chunktorchcat)xx1x2s      `/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/esm/modeling_esm.pyrotate_halfr&   ,   s6    WWQBWFB9rc2YB''''    c                     |d d d d d | j         d         d d f         }|d d d d d | j         d         d d f         }| |z  t          |           |z  z   S )N)shaper&   )r"   cossins      r%   apply_rotary_pos_embr-   1   sn    
aaaMagbkM111$
%C
aaaMagbkM111$
%CGA,--r'   c                 f    | dz  dt          j        | t          j        d          z            z   z  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"   s    r%   gelur4   8   s/     s7cEIa$)C..&8999::r'   c                 4    | |                      dd          z   S )zJMake layer symmetric in final two dimensions, used for contact prediction.r   r)   )	transposer3   s    r%   
symmetrizer7   ?   s    q{{2r""""r'   c                     |                      dd          }|                      dd          }|                      dd          }||z  }|                    |           | |z
  }|S )z=Perform average product correct, used for contact prediction.r   T)keepdimsr)   )r   r)   )sumdiv_)r"   a1a2a12avg
normalizeds         r%   average_product_correctrA   D   sh    	
rD	!	!B	
rD	!	!B
%%4%
(
(C
r'CHHSMMMSJr'   c                   |     e Zd ZdZdef fdZd
dZdej        dej        de	ej        ej        f         fd	Z
 x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                    t                                                       ddt          j        d|dt          j                                                  |z  z  z  }|}|                     d|           d | _        d | _        d | _	        d S )Nr/   i'  r   r   dtypeinv_freq)
super__init__r    arangeint64floatregister_buffer_seq_len_cached_cos_cached_sin_cached)selfr   rG   	__class__s      r%   rI   zRotaryEmbedding.__init__W   s    %ELC%+$N$N$N$T$T$V$VY\$\]^Z222#r'   r   c                 2   |j         |         }|| j        k    s| j        j        |j        k    r|| _        t	          j        |j         |         |j                                      | j                  }t	          j        || j                  }t	          j	        ||fd          
                    |j                  }|                                d d d d d d f         | _        |                                d d d d d d f         | _        | j        | j        fS )Ndevicer   r   )r*   rN   rO   rU   r    rJ   type_asrG   outerr!   tor+   r,   rP   )rQ   r"   seq_dimensionseq_lentfreqsembs          r%   _update_cos_sin_tablesz&RotaryEmbedding._update_cos_sin_tablesb   s    '-( d***d.>.E.Q.Q#*D QW]3AHEEEMMdm\\AK4=11E)UEN33366qx@@C"wwyytQQQ)9:D"wwyytQQQ)9:D!111r'   qkreturnc                     |                      |d          \  | _        | _        t          || j        | j                  t          || j        | j                  fS )Nr)   )rY   )r^   rO   rP   r-   )rQ   r_   r`   s      r%   forwardzRotaryEmbedding.forwardr   s\    -1-H-HZ\-H-]-]*$* !D$4d6FGG D$4d6FGG
 	
r'   )r   )__name__
__module____qualname____doc__intrI   r^   r    Tensorr   rc   __classcell__rR   s   @r%   rC   rC   P   s         	 C 	  	  	  	  	  	 2 2 2 2 
 
%, 
5u|A[;\ 
 
 
 
 
 
 
 
r'   rC   c                   8     e Zd ZdZ	 	 ddedef fdZd Z xZS )	EsmContactPredictionHeadzWPerforms symmetrization, apc, and computes a logistic regression on the output featuresTr   in_featureseos_idxc                     t                                                       || _        || _        t	          j        |d|          | _        t	          j                    | _        d S )Nr   )	rH   rI   rn   ro   r   Linear
regressionSigmoid
activation)rQ   rn   biasro   rR   s       r%   rI   z!EsmContactPredictionHead.__init__~   sP     	&)KD99*,,r'   c                    |                     | j                                      |          }|                    d          |                    d          z  }||d d d d d d d d f         z  }|dd dd df         }|ddd dd f         }|                                \  }}}}}|                    |||z  ||          }|                    | j        j        j                  }t          t          |                    }|                    dddd          }|                     |                     |                              d                    S )Nr   r   .r   r   r   )nero   rX   	unsqueezesizeviewrr   weightrU   rA   r7   permutert   squeeze)	rQ   tokens
attentionseos_mask
batch_sizelayersheadsseqlen_s	            r%   rc   z EsmContactPredictionHead.forward   sP   99T\**--j99%%a((8+=+=a+@+@@(111dD!!!QQQ+>"??
SbS#2#.
QRR,
/9/@/@,
FE61__Z%PP
  ]]O")
 

 -Z
-C-CDD
''1a33
tz::BB1EEFFFr'   )Tr   )rd   re   rf   rg   rh   rI   rc   rj   rk   s   @r%   rm   rm   {   sx        aa
 	
' 
'
' 	
' 
' 
' 
' 
' 
'G G G G G G Gr'   rm   c                   2     e Zd ZdZ fdZ	 ddZd Z xZS )EsmEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                    t                                                       t          j        |j        |j        |j                  | _        |j        r&t          j	        |j        |j
                  | _        nd | _        t          j        |j                  | _        t          |dd          | _        |                     dt%          j        |j                                      d          d           |j        | _        t          j        |j        |j        | j                  | _        |j        | _        |j        | _        d S )	N)padding_idxepsposition_embedding_typeabsoluteposition_ids)r   r   F)
persistent)rH   rI   r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsemb_layer_norm_before	LayerNormlayer_norm_eps
layer_normDropouthidden_dropout_probdropoutgetattrr   rM   r    rJ   max_position_embeddingsexpandr   position_embeddingstoken_dropoutmask_token_idrQ   configrR   s     r%   rI   zEsmEmbeddings.__init__   s+   !|F,=v?Q_e_rsss' 	# l6+=6CXYYYDOO"DOz&"<=='.v7PR\']']$EL)GHHOOPWXXej 	 	
 	
 	
 ".#%<*F,>DL\$
 $
 $
  $1#1r'   Nr   c                    |.|t          || j        |          }n|                     |          }||                     |          }|}| j        r|                    || j        k                        d          d          }d}|                    d          }|| j        k                        d          	                                |z  }	|d|z
  z  d|	z
  d d d d f         z  
                    |j                  }| j        dk    r|                     |          }
||
z   }| j        |                     |          }|0||                    d          z  
                    |j                  }|S )Nr           gQ?r   r   )"create_position_ids_from_input_idsr   &create_position_ids_from_inputs_embedsr   r   masked_fillr   rx   r:   rL   rX   rF   r   r   r   )rQ   	input_idsattention_maskr   inputs_embedspast_key_values_length
embeddingsmask_ratio_trainsrc_lengthsmask_ratio_observedr   s              r%   rc   zEsmEmbeddings.forward   s    $A)TM]_uvv#JJ=YY  00;;M #
  	#//d>P1P0[0[\^0_0_adeeJ)(,,R00K#,0B#B"G"G"K"K"Q"Q"S"SVa"a$,<(<=EXAXZ[Z[Z[]acgZg@hhll  J ':55"&":":<"H"H#&99J?&44J%$~'?'?'C'CCGG
HXYYJ r'   c                    |                                 dd         }|d         }t          j        | j        dz   || j        z   dz   t          j        |j                  }|                    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   rF   rU   r   )ry   r    rJ   r   longrU   rx   r   )rQ   r   input_shapesequence_lengthr   s        r%   r   z4EsmEmbeddings.create_position_ids_from_inputs_embeds   s     $((**3B3/%a.|q /D4D"Dq"HPUPZcpcw
 
 
 %%a((//<<<r'   )NNNNr   )rd   re   rf   rg   rI   rc   r   rj   rk   s   @r%   r   r      sm         2 2 2 2 2. rs+ + + +Z= = = = = = =r'   r   c                   ,    e Zd Zd fd	Zdej        dej        f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Z xZS )EsmSelfAttentionNc                    t                                                       |j        |j        z  dk    r0t	          |d          s t          d|j         d|j         d          |j        | _        t          |j        |j        z            | _        | j        | j        z  | _        t          j
        |j        | j                  | _        t          j
        |j        | j                  | _        t          j
        |j        | j                  | _        t          j        |j                  | _        |pt#          |dd          | _        d | _        | j        dk    s| j        d	k    r7|j        | _        t          j        d
|j        z  dz
  | j                  | _        n%| j        dk    rt/          | j                  | _        |j        | _        d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r   r   relative_keyrelative_key_queryr   r   rotaryr   )rH   rI   r   num_attention_headshasattr
ValueErrorrh   attention_head_sizeall_head_sizer   rq   querykeyvaluer   attention_probs_dropout_probr   r   r   rotary_embeddingsr   r   distance_embeddingrC   
is_decoder)rQ   r   r   rR   s      r%   rI   zEsmSelfAttention.__init__   s    ::a??PVXhHiHi?8F$6 8 8 48 8 8  
 $*#= #&v'9F<V'V#W#W !58PPYv143EFF
9V/1CDDYv143EFF
z&"EFF'> (
'-zC
 C
$ "&'>99T=Y]q=q=q+1+ID(&(l1v7U3UXY3Y[_[s&t&tD##)X55%49Q%R%R%RD" +r'   r"   ra   c                     |                                 d d         | j        | j        fz   }|                    |          }|                    dddd          S )Nr   r   r   r   r   )ry   r   r   rz   r|   )rQ   r"   new_x_shapes      r%   transpose_for_scoresz%EsmSelfAttention.transpose_for_scores  sP    ffhhssmt'?AY&ZZFF;yyAq!$$$r'   Fhidden_statesr   	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsc                 0   |                      |          }|d u}	|	r||d         }
|d         }|}n4|	rS|                     |                     |                    }
|                     |                     |                    }|}n||                     |                     |                    }
|                     |                     |                    }t	          j        |d         |
gd          }
t	          j        |d         |gd          }nP|                     |                     |                    }
|                     |                     |                    }|                     |          }|| j        dz  z  }| j        r|
|f}| j        dk    r| 	                    ||
          \  }}
t	          j
        ||
                    dd                    }| j        d	k    s| j        d
k    r4|                                d         }t	          j        |t          j        |j                                      dd          }t	          j        |t          j        |j                                      dd          }||z
  }|                     || j        z   dz
            }|                    |j                  }| j        d	k    rt	          j        d||          }||z   }n?| j        d
k    r4t	          j        d||          }t	          j        d|
|          }||z   |z   }|||z   }t,          j                            |d          }|                     |          }|||z  }t	          j
        |                    |j                  |          }|                    dddd                                          }|                                d d         | j        fz   }|                    |          }|r||fn|f}| j        r||fz   }|S )Nr   r   r   r   g      r   r   r)   r   r   r   rE   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   )r   r   r   r   r    r!   r   r   r   r   matmulr6   ry   rJ   r   rU   rz   r   r   rX   rF   einsumr   
functionalsoftmaxr   r|   
contiguousr   )rQ   r   r   r   r   r   r   r   mixed_query_layeris_cross_attention	key_layervalue_layerquery_layerattention_scores
seq_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keyattention_probscontext_layernew_context_layer_shapeoutputss                             r%   rc   zEsmSelfAttention.forward  s@    !JJ}55
 3$> 	O."<&q)I(+K3NN 	O11$((;P2Q2QRRI33DJJ?T4U4UVVK3NN'11$((=2I2IJJI33DJJ}4M4MNNK	>!#4i"@aHHHI)^A%6$D!LLLKK11$((=2I2IJJI33DJJ}4M4MNNK//0ABB "D$<d$BB? 	6 (5N'833%)%;%;K%S%S"K !<Y5H5HR5P5PQQ'>99T=Y]q=q=q&++--a0J"\*EJ}OcdddiijlnoppN"\*EJ}OcdddiijkmoppN%6H#'#:#:8dFb;bef;f#g#g #7#:#:AR#:#S#S +~==+0<8H+Wk+l+l(#36N#N  -1EEE16>NP[]q1r1r./4|<LiYm/n/n,#36T#TWs#s %/.@ -//0@b/II ,,77  -	9O_%7%78I%J%JKXX%--aAq99DDFF"/"4"4"6"6ss";t?Q>S"S%**+BCC6G]=/22mM]? 	2 11Gr'   NNNNNNF)rd   re   rf   rI   r    ri   r   r   FloatTensorr   boolrc   rj   rk   s   @r%   r   r      s.       , , , , , ,:%el %u| % % % % 7;15=A>BDH,1d d|d !!23d E-.	d
  ((9:d !)): ;d !uU->'?!@Ad $D>d 
u|	d d d d d d d dr'   r   c                   $     e Zd Z fdZd Z xZS )EsmSelfOutputc                     t                                                       t          j        |j        |j                  | _        t          j        |j                  | _        d S r   )	rH   rI   r   rq   r   denser   r   r   r   s     r%   rI   zEsmSelfOutput.__init__  sJ    Yv163EFF
z&"<==r'   c                 d    |                      |          }|                     |          }||z   }|S r   r   r   rQ   r   input_tensors      r%   rc   zEsmSelfOutput.forward  4    

=11]33%4r'   rd   re   rf   rI   rc   rj   rk   s   @r%   r   r     G        > > > > >
      r'   r   c                   8     e Zd Z fdZd Z	 	 	 	 	 	 ddZ xZS )EsmAttentionc                    t                                                       t          |          | _        t	          |          | _        t                      | _        t          j	        |j
        |j                  | _	        d S )Nr   )rH   rI   r   rQ   r   outputsetpruned_headsr   r   r   r   r   s     r%   rI   zEsmAttention.__init__  sc    $V,,	#F++EEf&8f>STTTr'   c                    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          | j
        _        | j        j        t          |          z
  | j        _        | j        j        | j        j        z  | j        _        | j                            |          | _        d S )Nr   r   r   )lenr   rQ   r   r   r   r   r   r   r   r   r   r   union)rQ   r   indexs      r%   prune_headszEsmAttention.prune_heads  s    u::??F7490$)2OQUQb
 
u
 -TY_eDD	*49=%@@	,TY_eDD	.t{/@%QOOO )-	(EE

(R	%"&)"?$)B_"_	 -33E::r'   NFc           	          |                      |          }|                     |||||||          }	|                     |	d         |          }
|
f|	dd          z   }|S )Nr   r   )r   rQ   r   )rQ   r   r   r   r   r   r   r   hidden_states_lnself_outputsattention_outputr   s               r%   rc   zEsmAttention.forward  ss      >>-88yy!"
 
  ;;|AFF#%QRR(88r'   r   )rd   re   rf   rI   r  rc   rj   rk   s   @r%   r   r     st        U U U U U; ; ;* "#       r'   r   c                   B     e Zd Z fdZdej        dej        fdZ xZS )EsmIntermediatec                     t                                                       t          j        |j        |j                  | _        d S r   )rH   rI   r   rq   r   intermediate_sizer   r   s     r%   rI   zEsmIntermediate.__init__  s6    Yv163KLL


r'   r   ra   c                 N    |                      |          }t          |          }|S r   )r   r4   )rQ   r   s     r%   rc   zEsmIntermediate.forward  s&    

=11]++r'   rd   re   rf   rI   r    ri   rc   rj   rk   s   @r%   r
  r
    sc        M M M M MU\ el        r'   r
  c                   $     e Zd Z fdZd Z xZS )	EsmOutputc                     t                                                       t          j        |j        |j                  | _        t          j        |j                  | _	        d S r   )
rH   rI   r   rq   r  r   r   r   r   r   r   s     r%   rI   zEsmOutput.__init__  sJ    Yv79KLL
z&"<==r'   c                 d    |                      |          }|                     |          }||z   }|S r   r   r   s      r%   rc   zEsmOutput.forward  r   r'   r   rk   s   @r%   r  r    r   r'   r  c                   8     e Zd Z fdZ	 	 	 	 	 	 ddZd Z xZS )EsmLayerc                    t                                                       |j        | _        d| _        t	          |          | _        |j        | _        |j        | _        | j        r-| j        st          |  d          t	          |          | _	        t          |          | _        t          |          | _        t          j        |j        |j                  | _        d S )Nr   z> should be used as a decoder model if cross attention is addedr   )rH   rI   chunk_size_feed_forwardseq_len_dimr   	attentionr   add_cross_attentionRuntimeErrorcrossattentionr
  intermediater  r   r   r   r   r   r   s     r%   rI   zEsmLayer.__init__  s    '-'E$%f-- +#)#= # 	7? l"d#j#j#jkkk".v"6"6D+F33''f&8f>STTTr'   NFc           	         |
|d d         nd }|                      |||||          }	|	d         }
| j        r|	dd         }|	d         }n
|	dd          }d }| j        rp|nt          | d          st          d|  d          |
|d	d          nd }|                     |
||||||          }|d         }
||dd         z   }|d         }||z   }|                     |
          }|f|z   }| j        r||fz   }|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)rQ   r   r   r   r   r   r   r   self_attn_past_key_valueself_attention_outputsr  r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputslayer_outputs                    r%   rc   zEsmLayer.forward  s    :H9S>"1"#5#5Y] !%/3 "0 "
 "
 2!4 ? 	1,QrT2G 6r :,QRR0G'+$? 	Q4@4!122 $`d ` ` `   @N?Yrss(;(;_c%&*&9&9 %&)!' '#  7q9 7" ==G ,C2+F( 14P P../?@@/G+ ? 	5!2 44Gr'   c                     |                      |          }|                     |          }|                     ||          }|S r   )r   r  r   )rQ   r  attention_output_lnintermediate_outputr&  s        r%   r  zEsmLayer.feed_forward_chunk)  sE    "nn-=>>"//0CDD{{#68HIIr'   r   )rd   re   rf   rI   rc   r  rj   rk   s   @r%   r  r    su        U U U U U$ "#= = = =~      r'   r  c                   8     e Zd Z fdZ	 	 	 	 	 	 	 	 	 ddZ xZS )
EsmEncoderc                    t                                                       | _        t          j        fdt          j                  D                       | _        t          j        j	        j
                  | _        d| _        d S )Nc                 .    g | ]}t                    S  )r  ).0r   r   s     r%   
<listcomp>z'EsmEncoder.__init__.<locals>.<listcomp>4  s!    #^#^#^HV$4$4#^#^#^r'   r   F)rH   rI   r   r   
ModuleListrangenum_hidden_layerslayerr   r   r   emb_layer_norm_aftergradient_checkpointingr   s    `r%   rI   zEsmEncoder.__init__1  s}    ]#^#^#^#^eFD\>]>]#^#^#^__
$&L1CI^$_$_$_!&+###r'   NFTc                    | 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z   }|||         nd }|||         nd }| j         r)| j        r"|                     |j	        |||||||          }n ||||||||          }|d         }|r||d         fz   }|r$||d         fz   }| j        j        r||d         fz   }| j
        r| 
                    |          }|	r||fz   }|
st          d |||||fD                       S t          |||||	          S )
Nzh`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting `use_cache=False`...Fr.  r   r   r   r   c              3      K   | ]}||V  	d S r   r.  )r/  vs     r%   	<genexpr>z%EsmEncoder.forward.<locals>.<genexpr>}  s4       
 
 =  !===
 
r'   )last_hidden_statepast_key_valuesr   r   cross_attentions)r6  trainingloggerwarning_oncer   r  	enumerater4  _gradient_checkpointing_func__call__r5  tupler   )rQ   r   r   r   r   r   r<  	use_cacher   output_hidden_statesreturn_dictall_hidden_statesall_self_attentionsall_cross_attentionsnext_decoder_cacheilayer_modulelayer_head_maskr   layer_outputss                       r%   rc   zEsmEncoder.forward8  sd    & 	"4= 	" "##+   "	"6@BBD$5?bb4%6d4;;Zdrr`d#,6RR$(44 #	V #	VOA|# I$58H$H!.7.CillO3B3N_Q//TXN* t}  $ A A )!"#)*"%	! 	! !-!"#)*"%! ! *!,M O%7=;L:N%N"  V&9]1=M<O&O#;2 V+?=QRCSBU+U($ 	E 55mDDM 	E 1]4D D 	 
 
 "&%'(
 
 
 
 
 
 9+.+*1
 
 
 	
r'   )	NNNNNNFFTr   rk   s   @r%   r+  r+  0  sq        , , , , , "#"V
 V
 V
 V
 V
 V
 V
 V
r'   r+  c                   B     e Zd Z fdZdej        dej        fdZ xZS )	EsmPoolerc                     t                                                       t          j        |j        |j                  | _        t          j                    | _        d S r   )rH   rI   r   rq   r   r   Tanhrt   r   s     r%   rI   zEsmPooler.__init__  sC    Yv163EFF
'))r'   r   ra   c                 r    |d d df         }|                      |          }|                     |          }|S Nr   )r   rt   )rQ   r   first_token_tensorpooled_outputs       r%   rc   zEsmPooler.forward  s@     +111a40

#56666r'   r  rk   s   @r%   rQ  rQ    s^        $ $ $ $ $
U\ el        r'   rQ  c                   ,    e Zd ZdZeZdZdZg dZd Z	dS )EsmPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    esmT)r  #EsmFoldTriangularSelfAttentionBlockr   c                    t          |t          j                  rT|j        j                            d| j        j                   |j         |j        j        	                                 dS dS t          |t          j
                  r_|j        j                            d| j        j                   |j        +|j        j        |j                 	                                 dS dS t          |t          j                  r?|j        j        	                                 |j        j                            d           dS dS )zInitialize the weightsr   )meanstdNr/   )
isinstancer   rq   r{   datanormal_r   initializer_rangeru   zero_r   r   r   fill_)rQ   modules     r%   _init_weightsz EsmPreTrainedModel._init_weights  s)   fbi(( 	* M&&CT[5R&SSS{& &&((((( '&-- 	*M&&CT[5R&SSS!-"6#56<<>>>>> .--- 	*K""$$$M$$S)))))	* 	*r'   N)
rd   re   rf   rg   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modulesrf  r.  r'   r%   rY  rY    sL         
 L&*#\\\* * * * *r'   rY  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                       e Zd ZdZd fd	Zd Zd Zd Z ee	
                    d                     eee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                        Zd Z x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                 F   t                                          |           || _        t          |          | _        t          |          | _        |rt          |          nd | _        t          |j
        |j        z  d          | _        |                                  d S )NT)rn   ru   )rH   rI   r   r   r   r+  encoderrQ  poolerrm   r3  r   contact_head	post_init)rQ   r   add_pooling_layerrR   s      r%   rI   zEsmModel.__init__	  s       '//!&))+<Fi'''$4063MMTX
 
 

 	r'   c                     | j         j        S r   r   r   rQ   s    r%   get_input_embeddingszEsmModel.get_input_embeddings  s    ..r'   c                     || j         _        d S r   rt  )rQ   r   s     r%   set_input_embeddingszEsmModel.set_input_embeddings  s    */'''r'   c                     |                                 D ]/\  }}| j        j        |         j                            |           0d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)itemsrn  r4  r  r  )rQ   heads_to_pruner4  r   s       r%   _prune_headszEsmModel._prune_heads  sU    
 +0022 	C 	CLE5Lu%/;;EBBBB	C 	Cr'   z(batch_size, sequence_length)
checkpointoutput_typerg  Nr   r   r   r   r   r   r   r<  rE  r   rF  rG  ra   c                 l   |
|
n| j         j        }
||n| j         j        }||n| j         j        }| j         j        r|	|	n| j         j        }	nd}	||t          d          |+|                     ||           |                                }n.||                                dd         }nt          d          |\  }}||j	        n|j	        }||d         d         j
        d         nd}|t          j        |||z   f|          }|                     ||          }| j         j        rL|J|                                \  }}}||f}|t          j        ||          }|                     |          }nd}|                     || j         j                  }|                     |||||	          }|                     |||||||	|
||

  
        }|d         }| j        |                     |          nd}|s||f|dd         z   S t)          |||j        |j        |j        |j                  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   rT   )r   r   r   r   r   )	r   r   r   r   r<  rE  r   rF  rG  r   )r;  pooler_outputr<  r   r   r=  )r   r   rF  use_return_dictr   rE  r   %warn_if_padding_and_no_attention_maskry   rU   r*   r    onesget_extended_attention_maskinvert_attention_maskget_head_maskr3  r   rn  ro  r   r<  r   r   r=  )rQ   r   r   r   r   r   r   r   r<  rE  r   rF  rG  r   r   r   rU   r   extended_attention_maskencoder_batch_sizeencoder_sequence_lengthr   encoder_hidden_shapeencoder_extended_attention_maskembedding_outputencoder_outputssequence_outputrW  s                               r%   rc   zEsmModel.forward'  s   R 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B];! 	%.%:		@UIII ]%>cddd"66y.QQQ#..**KK&',,..ss3KKTUUU!,
J%.%:!!@T DSC^!3A!6!<Q!?!?de!"Z*jCY6Y)ZdjkkkN 150P0PQ_al0m0m ;! 	3&;&G=R=W=W=Y=Y: 7$68O#P %-).4HQW)X)X)X&.2.H.HI_.`.`++.2+ &&y$+2OPP	??%)'#9 + 
 
 ,,2"7#B+/!5# ' 
 
 *!,8<8OO444UY 	J#]3oabb6III;-'+;)7&1,=
 
 
 	
r'   c                 z    | ||dd          j         }t          j        |d          }||                    d                              d                              d          z  }||                    d                              d                              d          z  }|                     ||          S )NT)r   rG  r   r   r   r   r      )r   r    stackrx   rp  )rQ   r~   r   attnss       r%   predict_contactszEsmModel.predict_contacts  s    VN`deeepEq)))
 	))!,,66q99CCAFFF))!,,66q99CCAFFF  ///r'   )T)NNNNNNNNNNNN)rd   re   rf   rg   rI   rv  rx  r|  r   ESM_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r    ri   r   r   r   r   r   rc   r  rj   rk   s   @r%   rl  rl    s	       

 
      / / /0 0 0C C C +*+?+F+FGf+g+ghh&@$   -115/3,0048<9==A$(,0/3&*w
 w
EL)w
 !.w
 u|,	w

 EL)w
  -w
  (5w
 !) 6w
 "$u'8"9:w
 D>w
 $D>w
 'tnw
 d^w
 
uU\"$PP	Qw
 w
 w
  ihw
r	0 	0 	0 	0 	0 	0 	0r'   rl  z1ESM Model with a `language modeling` head on top.c                       e Zd ZdgZ fdZd Zd Z ee	                    d                     e
eeed          	 	 	 	 	 	 	 	 	 	 	 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                        Zd Z xZS )EsmForMaskedLMzlm_head.decoder.weightc                    t                                          |           |j        rt                              d           t          |d          | _        t          |          | _        | 	                                 d S )NzjIf you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Frr  )
rH   rI   r   r?  warningrl  rZ  	EsmLMHeadlm_headinit_weightsr   s     r%   rI   zEsmForMaskedLM.__init__  s~        	NN1  
 Fe<<< ((r'   c                     | j         j        S r   r  decoderru  s    r%   get_output_embeddingsz$EsmForMaskedLM.get_output_embeddings  s    |##r'   c                     || j         _        d S r   r  )rQ   new_embeddingss     r%   set_output_embeddingsz$EsmForMaskedLM.set_output_embeddings  s    -r'   batch_size, sequence_lengthz<mask>)r~  r  rg  maskNr   r   r   r   r   r   r   labelsr   rF  rG  ra   c                    ||n| j         j        }|                     ||||||||	|
|
  
        }|d         }|                     |          }d}|et	                      }|                    |j                  } ||                    d| j         j                  |                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j
        |j                  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   r   r   r   r   r   r   rF  rG  r   r   r   losslogitsr   r   )r   r  rZ  r  r	   rX   rU   rz   r   r   r   r   )rQ   r   r   r   r   r   r   r   r  r   rF  rG  r   r  prediction_scoresmasked_lm_lossloss_fctr   s                     r%   rc   zEsmForMaskedLM.forward  s,   : &1%<kk$+B](()%'"7#9/!5#  
 
 "!* LL99'))HYY0788F%X&7&<&<RAW&X&XZ`ZeZefhZiZijjN 	Z')GABBK7F3A3M^%..SYY$!/)	
 
 
 	
r'   c                 :    | j                             ||          S )N)r   )rZ  r  )rQ   r~   r   s      r%   r  zEsmForMaskedLM.predict_contacts
  s    x(((OOOr'   )NNNNNNNNNNN)rd   re   rf   _tied_weights_keysrI   r  r  r   r  r  r   r  r   r  r   r    
LongTensorri   r   r   r   r   rc   r  rj   rk   s   @r%   r  r    s       23    $ $ $. . . +*+?+F+FGd+e+eff&"$	   151537,059=A9=-1,0/3&*7
 7
E,-7
 !.7
 u/0	7

 EL)7
   127
  ((9:7
 !) 67
 )*7
 $D>7
 'tn7
 d^7
 
un$	%7
 7
 7
  gf7
rP P P P P P Pr'   r  c                   (     e Zd ZdZ fdZd Z xZS )r  z&ESM Head for masked language modeling.c                    t                                                       t          j        |j        |j                  | _        t          j        |j        |j                  | _        t          j        |j        |j	        d          | _
        t          j        t          j        |j	                            | _        d S )Nr   F)ru   )rH   rI   r   rq   r   r   r   r   r   r   r  	Parameterr    zerosru   r   s     r%   rI   zEsmLMHead.__init__  s    Yv163EFF
,v'9v?TUUUy!3V5FUSSSLV->!?!?@@			r'   c                     |                      |          }t          |          }|                     |          }|                     |          | j        z   }|S r   )r   r4   r   r  ru   rQ   featureskwargsr"   s       r%   rc   zEsmLMHead.forward  sL    JJx  GGOOA LLOOdi'r'   rd   re   rf   rg   rI   rc   rj   rk   s   @r%   r  r    sR        00A A A A A      r'   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                       e Zd Z fdZ ee                    d                     eee	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                        Z xZS )EsmForSequenceClassificationc                     t                                          |           |j        | _        || _        t	          |d          | _        t          |          | _        |                                  d S NFr  )	rH   rI   
num_labelsr   rl  rZ  EsmClassificationHead
classifierr  r   s     r%   rI   z%EsmForSequenceClassification.__init__+  sg        +Fe<<</77r'   r  r}  Nr   r   r   r   r   r  r   rF  rG  ra   c
           
         |	|	n| j         j        }	|                     ||||||||	          }
|
d         }|                     |          }d}|t|                    |j                  }| j         j        f| j        dk    rd| j         _        nN| j        dk    r7|j        t          j
        k    s|j        t          j        k    rd| j         _        nd| j         _        | j         j        dk    rWt                      }| j        dk    r1 ||                                |                                          }n |||          }n| j         j        dk    rGt                      } ||                    d| j                  |                    d                    }n*| j         j        dk    rt!                      } |||          }|	s|f|
d	d         z   }||f|z   n|S t#          |||
j        |
j        
          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   r   r   r   r   rF  rG  r   r   rr   single_label_classificationmulti_label_classificationr   r   r  )r   r  rZ  r  rX   rU   problem_typer  rF   r    r   rh   r
   r}   r	   rz   r   r   r   r   rQ   r   r   r   r   r   r  r   rF  rG  r   r  r  r  r  r   s                   r%   rc   z$EsmForSequenceClassification.forward5  s   0 &1%<kk$+B](()%'/!5#  	
 	
 "!*11YYv}--F{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8FNN$4$4fnn6F6FGGDD#8FF33DD)-JJJ+--xB @ @&++b//RR)-III,..x// 	FY,F)-)9TGf$$vE'!/)	
 
 
 	
r'   	NNNNNNNNN)rd   re   rf   rI   r   r  r  r   r  r   r  r   r    r  ri   r   r   r   r   rc   rj   rk   s   @r%   r  r  #  sy            +*+?+F+FGd+e+eff&,$   151537,059-1,0/3&*C
 C
E,-C
 !.C
 u/0	C

 EL)C
   12C
 )*C
 $D>C
 'tnC
 d^C
 
u..	/C
 C
 C
  gfC
 C
 C
 C
 C
r'   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                       e Zd Z fdZ ee                    d                     eee	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                        Z xZS )EsmForTokenClassificationc                 :   t                                          |           |j        | _        t          |d          | _        t          j        |j                  | _        t          j	        |j
        |j                  | _        |                                  d S r  )rH   rI   r  rl  rZ  r   r   r   r   rq   r   r  r  r   s     r%   rI   z"EsmForTokenClassification.__init__  s~        +Fe<<<z&"<==)F$68IJJr'   r  r}  Nr   r   r   r   r   r  r   rF  rG  ra   c
           
         |	|	n| j         j        }	|                     ||||||||	          }
|
d         }|                     |          }|                     |          }d}|`t                      }|                    |j                  } ||                    d| j	                  |                    d                    }|	s|f|
dd         z   }||f|z   n|S t          |||
j        |
j                  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  rZ  r   r  r	   rX   rU   rz   r  r   r   r   r  s                   r%   rc   z!EsmForTokenClassification.forward  s%   , &1%<kk$+B](()%'/!5#  	
 	
 "!*,,7711'))HYYv}--F8FKKDO<<fkk"ooNND 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r'   r  )rd   re   rf   rI   r   r  r  r   r  r   r  r   r    r  ri   r   r   r   r   rc   rj   rk   s   @r%   r  r    sf            +*+?+F+FGd+e+eff&)$   151537,059-1,0/3&*2
 2
E,-2
 !.2
 u/0	2

 EL)2
   122
 )*2
 $D>2
 'tn2
 d^2
 
u++	,2
 2
 2
  gf2
 2
 2
 2
 2
r'   r  c                   (     e Zd ZdZ fdZd Z xZS )r  z-Head for sentence-level classification tasks.c                    t                                                       t          j        |j        |j                  | _        t          j        |j                  | _        t          j        |j        |j	                  | _
        d S r   )rH   rI   r   rq   r   r   r   r   r   r  out_projr   s     r%   rI   zEsmClassificationHead.__init__  sc    Yv163EFF
z&"<==	&"4f6GHHr'   c                     |d d dd d f         }|                      |          }|                     |          }t          j        |          }|                      |          }|                     |          }|S rU  )r   r   r    tanhr  r  s       r%   rc   zEsmClassificationHead.forward  sj    QQQ111WLLOOJJqMMJqMMLLOOMM!r'   r  rk   s   @r%   r  r    sR        77I I I I I      r'   r  c                     |                      |                                          }t          j        |d                              |          |z   |z  }|                                |z   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   )rw   rh   r    cumsumrV   r   )r   r   r   r  incremental_indicess        r%   r   r     sg     <<$$((**D <!444<<TBBE[[_cc##%%33r'   )r   )@rg   r1   typingr   r   r   r   r    torch.utils.checkpointr   torch.nnr   r	   r
   
file_utilsr   r   r   modeling_outputsr   r   r   r   r   modeling_utilsr   r   r   utilsr   configuration_esmr   
get_loggerrd   r?  r  r  r&   r-   r4   r7   rA   ModulerC   rm   r   r   r   r   r
  r  r  r+  rQ  rY  ESM_START_DOCSTRINGr  rl  r  r  r  r  r  r   r.  r'   r%   <module>r     s      / / / / / / / / / / / /            A A A A A A A A A A q q q q q q q q q q              d c c c c c c c c c       ( ( ( ( ( ( 
	H	%	%1 ( ( (
. . .; ; ;# # #
	 	 	(
 (
 (
 (
 (
eho (
 (
 (
V G  G  G  G  Gry  G  G  GFW= W= W= W= W=BI W= W= W=tG G G G Gry G G GT
 
 
 
 
BI 
 
 
0 0 0 0 029 0 0 0f    bi   
 
 
 
 
	 
 
 
S S S S Sry S S Sl^
 ^
 ^
 ^
 ^
 ^
 ^
 ^
D    	   * * * * * * * *:  ' T c s0 s0 s0 s0 s0! s0 s0	 s0l MObccXP XP XP XP XP' XP XP dcXPv    	   *   T
 T
 T
 T
 T
#5 T
 T
 T
n   C
 C
 C
 C
 C
 2 C
 C
 C
L    BI   &4 4 4 4 4 4r'   