The MultiMolecule team is aware of a potential risk in reproducing the results of RNABERT.
The original implementation of RNABERT does not prepend <cls> and append <eos> tokens to the input sequence.
This should not affect the performance of the model in most cases, but it can lead to unexpected behavior in some cases.
Please set bos_token=None, cls_token=None, eos_token = None in the tokenizer and set bos_token_id=None, cls_token_id=None, eos_token_id=None in the model configuration if you want the exact behavior of the original implementation.
Tip
The MultiMolecule team has confirmed that the provided model and checkpoints are producing the same intermediate representations as the original implementation.
The team releasing RNABERT did not write this model card for this model so this model card has been written by the MultiMolecule team.
RNABERT is a bert-style model pre-trained on a large corpus of non-coding RNA sequences in a self-supervised fashion. This means that the model was trained on the raw nucleotides of RNA sequences only, with an automatic process to generate inputs and labels from those texts. Please refer to the Training Details section for more information on the training process.
>>>importmultimolecule# you must import multimolecule to register models>>>fromtransformersimportpipeline>>>unmasker=pipeline("fill-mask",model="multimolecule/rnabert")>>>unmasker("gguc<mask>cucugguuagaccagaucugagccu")[{'score':0.03852083534002304,'token':24,'token_str':'-','sequence':'G G U C - C U C U G G U U A G A C C A G A U C U G A G C C U'},{'score':0.03851056098937988,'token':10,'token_str':'N','sequence':'G G U C N C U C U G G U U A G A C C A G A U C U G A G C C U'},{'score':0.03849703073501587,'token':25,'token_str':'I','sequence':'G G U C I C U C U G G U U A G A C C A G A U C U G A G C C U'},{'score':0.03848597779870033,'token':3,'token_str':'<unk>','sequence':'G G U C C U C U G G U U A G A C C A G A U C U G A G C C U'},{'score':0.038484156131744385,'token':5,'token_str':'<null>','sequence':'G G U C C U C U G G U U A G A C C A G A U C U G A G C C U'}]
This model is not fine-tuned for any specific task. You will need to fine-tune the model on a downstream task to use it for sequence classification or regression.
Here is how to use this model as backbone to fine-tune for a sequence-level task in PyTorch:
This model is not fine-tuned for any specific task. You will need to fine-tune the model on a downstream task to use it for token classification or regression.
Here is how to use this model as backbone to fine-tune for a nucleotide-level task in PyTorch:
This model is not fine-tuned for any specific task. You will need to fine-tune the model on a downstream task to use it for contact classification or regression.
Here is how to use this model as backbone to fine-tune for a contact-level task in PyTorch:
RNABERT has two pre-training objectives: masked language modeling (MLM) and structural alignment learning (SAL).
Masked Language Modeling (MLM): taking a sequence, the model randomly masks 15% of the tokens in the input then runs the entire masked sentence through the model and has to predict the masked tokens. This is comparable to the Cloze task in language modeling.
Structural Alignment Learning (SAL): the model learns to predict the structural alignment of two RNA sequences. The model is trained to predict the alignment score of two RNA sequences using the Needleman-Wunsch algorithm.
The RNABERT model was pre-trained on RNAcentral.
RNAcentral is a free, public resource that offers integrated access to a comprehensive and up-to-date set of non-coding RNA sequences provided by a collaborating group of Expert Databases representing a broad range of organisms and RNA types.
RNABERT used a subset of 76, 237 human ncRNA sequences from RNAcentral for pre-training.
RNABERT preprocessed all tokens by replacing “U”s with “T”s.
Note that during model conversions, “T” is replaced with “U”. RnaTokenizer will convert “T”s to “U”s for you, you may disable this behaviour by passing replace_T_with_U=False.
RNABERT preprocess the dataset by applying 10 different mask patterns to the 72, 237 human ncRNA sequences. The final dataset contains 722, 370 sequences. The masking procedure is similar to the one used in BERT:
15% of the tokens are masked.
In 80% of the cases, the masked tokens are replaced by <mask>.
In 10% of the cases, the masked tokens are replaced by a random token (different) from the one they replace.
In the 10% remaining cases, the masked tokens are left as is.
@article{akiyama2022informative,author={Akiyama, Manato and Sakakibara, Yasubumi},title="{Informative RNA base embedding for RNA structural alignment and clustering by deep representation learning}",journal={NAR Genomics and Bioinformatics},volume={4},number={1},pages={lqac012},year={2022},month={02},abstract="{Effective embedding is actively conducted by applying deep learning to biomolecular information. Obtaining better embeddings enhances the quality of downstream analyses, such as DNA sequence motif detection and protein function prediction. In this study, we adopt a pre-training algorithm for the effective embedding of RNA bases to acquire semantically rich representations and apply this algorithm to two fundamental RNA sequence problems: structural alignment and clustering. By using the pre-training algorithm to embed the four bases of RNA in a position-dependent manner using a large number of RNA sequences from various RNA families, a context-sensitive embedding representation is obtained. As a result, not only base information but also secondary structure and context information of RNA sequences are embedded for each base. We call this ‘informative base embedding’ and use it to achieve accuracies superior to those of existing state-of-the-art methods on RNA structural alignment and RNA family clustering tasks. Furthermore, upon performing RNA sequence alignment by combining this informative base embedding with a simple Needleman–Wunsch alignment algorithm, we succeed in calculating structural alignments with a time complexity of O(n2) instead of the O(n6) time complexity of the naive implementation of Sankoff-style algorithm for input RNA sequence of length n.}",issn={2631-9268},doi={10.1093/nargab/lqac012},url={https://doi.org/10.1093/nargab/lqac012},eprint={https://academic.oup.com/nargab/article-pdf/4/1/lqac012/42577168/lqac012.pdf},}
classRnaTokenizer(Tokenizer):""" Tokenizer for RNA sequences. Args: alphabet: alphabet to use for tokenization. - If is `None`, the standard RNA alphabet will be used. - If is a `string`, it should correspond to the name of a predefined alphabet. The options include + `standard` + `extended` + `streamline` + `nucleobase` - If is an alphabet or a list of characters, that specific alphabet will be used. nmers: Size of kmer to tokenize. codon: Whether to tokenize into codons. replace_T_with_U: Whether to replace T with U. do_upper_case: Whether to convert input to uppercase. Examples: >>> from multimolecule import RnaTokenizer >>> tokenizer = RnaTokenizer() >>> tokenizer('<pad><cls><eos><unk><mask><null>ACGUNRYSWKMBDHV.X*-I')["input_ids"] [1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 2] >>> tokenizer('acgu')["input_ids"] [1, 6, 7, 8, 9, 2] >>> tokenizer('acgt')["input_ids"] [1, 6, 7, 8, 9, 2] >>> tokenizer = RnaTokenizer(replace_T_with_U=False) >>> tokenizer('acgt')["input_ids"] [1, 6, 7, 8, 3, 2] >>> tokenizer = RnaTokenizer(nmers=3) >>> tokenizer('uagcuuauc')["input_ids"] [1, 83, 17, 64, 49, 96, 84, 22, 2] >>> tokenizer = RnaTokenizer(codon=True) >>> tokenizer('uagcuuauc')["input_ids"] [1, 83, 49, 22, 2] >>> tokenizer('uagcuuauca')["input_ids"] Traceback (most recent call last): ValueError: length of input sequence must be a multiple of 3 for codon tokenization, but got 10 """model_input_names=["input_ids","attention_mask"]def__init__(self,alphabet:Alphabet|str|List[str]|None=None,nmers:int=1,codon:bool=False,replace_T_with_U:bool=True,do_upper_case:bool=True,additional_special_tokens:List|Tuple|None=None,**kwargs,):ifcodonand(nmers>1andnmers!=3):raiseValueError("Codon and nmers cannot be used together.")ifcodon:nmers=3# set to 3 to get correct vocabifnotisinstance(alphabet,Alphabet):alphabet=get_alphabet(alphabet,nmers=nmers)super().__init__(alphabet=alphabet,nmers=nmers,codon=codon,replace_T_with_U=replace_T_with_U,do_upper_case=do_upper_case,additional_special_tokens=additional_special_tokens,**kwargs,)self.replace_T_with_U=replace_T_with_Uself.nmers=nmersself.codon=codondef_tokenize(self,text:str,**kwargs):ifself.do_upper_case:text=text.upper()ifself.replace_T_with_U:text=text.replace("T","U")ifself.codon:iflen(text)%3!=0:raiseValueError(f"length of input sequence must be a multiple of 3 for codon tokenization, but got {len(text)}")return[text[i:i+3]foriinrange(0,len(text),3)]ifself.nmers>1:return[text[i:i+self.nmers]foriinrange(len(text)-self.nmers+1)]# noqa: E203returnlist(text)
This is the configuration class to store the configuration of a RnaBertModel.
It is used to instantiate a RnaBert model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the RnaBert
mana438/RNABERT architecture.
Configuration objects inherit from PreTrainedConfig and can be used to
control the model outputs. Read the documentation from PreTrainedConfig
for more information.
Vocabulary size of the RnaBert model. Defines the number of different tokens that can be represented by the
inputs_ids passed when calling [RnaBertModel].
>>> frommultimoleculeimportRnaBertConfig,RnaBertModel>>> # Initializing a RNABERT multimolecule/rnabert style configuration>>> configuration=RnaBertConfig()>>> # Initializing a model (with random weights) from the multimolecule/rnabert style configuration>>> model=RnaBertModel(configuration)>>> # Accessing the model configuration>>> configuration=model.config
Source code in multimolecule/models/rnabert/configuration_rnabert.py
classRnaBertConfig(PreTrainedConfig):r""" This is the configuration class to store the configuration of a [`RnaBertModel`][multimolecule.models.RnaBertModel]. It is used to instantiate a RnaBert model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the RnaBert [mana438/RNABERT](https://github.com/mana438/RNABERT) architecture. Configuration objects inherit from [`PreTrainedConfig`][multimolecule.models.PreTrainedConfig] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`][multimolecule.models.PreTrainedConfig] for more information. Args: vocab_size: Vocabulary size of the RnaBert model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`RnaBertModel`]. hidden_size: Dimensionality of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). initializer_range: The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps: The epsilon used by the layer normalization layers. position_embedding_type: Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155). For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658). is_decoder: Whether the model is used as a decoder or not. If `False`, the model is used as an encoder. use_cache: Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. head: The configuration of the head. lm_head: The configuration of the masked language model head. Examples: >>> from multimolecule import RnaBertConfig, RnaBertModel >>> # Initializing a RNABERT multimolecule/rnabert style configuration >>> configuration = RnaBertConfig() >>> # Initializing a model (with random weights) from the multimolecule/rnabert style configuration >>> model = RnaBertModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config """model_type="rnabert"def__init__(self,vocab_size:int=26,ss_vocab_size:int=8,hidden_size:int|None=None,multiple:int|None=None,num_hidden_layers:int=6,num_attention_heads:int=12,intermediate_size:int=40,hidden_act:str="gelu",hidden_dropout:float=0.0,attention_dropout:float=0.0,max_position_embeddings:int=440,initializer_range:float=0.02,layer_norm_eps:float=1e-12,position_embedding_type:str="absolute",is_decoder:bool=False,use_cache:bool=True,head:HeadConfig|None=None,lm_head:MaskedLMHeadConfig|None=None,**kwargs,):super().__init__(**kwargs)ifhidden_sizeisNone:hidden_size=num_attention_heads*multipleifmultipleisnotNoneelse120self.vocab_size=vocab_sizeself.ss_vocab_size=ss_vocab_sizeself.type_vocab_size=2self.hidden_size=hidden_sizeself.num_hidden_layers=num_hidden_layersself.num_attention_heads=num_attention_headsself.intermediate_size=intermediate_sizeself.hidden_act=hidden_actself.hidden_dropout=hidden_dropoutself.attention_dropout=attention_dropoutself.max_position_embeddings=max_position_embeddingsself.initializer_range=initializer_rangeself.layer_norm_eps=layer_norm_epsself.position_embedding_type=position_embedding_typeself.is_decoder=is_decoderself.use_cache=use_cacheself.head=HeadConfig(**head)ifheadisnotNoneelseNoneself.lm_head=MaskedLMHeadConfig(**lm_head)iflm_headisnotNoneelseNone
classRnaBertModel(RnaBertPreTrainedModel):""" Examples: >>> from multimolecule import RnaBertConfig, RnaBertModel, RnaTokenizer >>> config = RnaBertConfig() >>> model = RnaBertModel(config) >>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna") >>> input = tokenizer("ACGUN", return_tensors="pt") >>> output = model(**input) >>> output["last_hidden_state"].shape torch.Size([1, 7, 120]) >>> output["pooler_output"].shape torch.Size([1, 120]) """def__init__(self,config:RnaBertConfig,add_pooling_layer:bool=True):super().__init__(config)self.pad_token_id=config.pad_token_idself.embeddings=RnaBertEmbeddings(config)self.encoder=RnaBertEncoder(config)self.pooler=RnaBertPooler(config)ifadd_pooling_layerelseNone# Initialize weights and apply final processingself.post_init()defget_input_embeddings(self):returnself.embeddings.word_embeddingsdefset_input_embeddings(self,value):self.embeddings.word_embeddings=valuedef_prune_heads(self,heads_to_prune):""" Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """forlayer,headsinheads_to_prune.items():self.encoder.layer[layer].attention.prune_heads(heads)defforward(self,input_ids:Tensor|NestedTensor,attention_mask:Tensor|None=None,position_ids:Tensor|None=None,head_mask:Tensor|None=None,inputs_embeds:Tensor|NestedTensor|None=None,encoder_hidden_states:Tensor|None=None,encoder_attention_mask:Tensor|None=None,past_key_values:Tuple[Tuple[Tensor,Tensor,Tensor,Tensor],...]|None=None,use_cache:bool|None=None,output_attentions:bool|None=None,output_hidden_states:bool|None=None,return_dict:bool|None=None,**kwargs,)->Tuple[Tensor,...]|BaseModelOutputWithPoolingAndCrossAttentions:r""" Args: encoder_hidden_states: Shape: `(batch_size, sequence_length, hidden_size)` 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: Shape: `(batch_size, sequence_length)` 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 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: If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ifkwargs:warn(f"Additional keyword arguments `{', '.join(kwargs)}` are detected in "f"`{self.__class__.__name__}.forward`, they will be ignored.\n""This is provided for backward compatibility and may lead to unexpected behavior.")output_attentions=output_attentionsifoutput_attentionsisnotNoneelseself.config.output_attentionsoutput_hidden_states=(output_hidden_statesifoutput_hidden_statesisnotNoneelseself.config.output_hidden_states)return_dict=return_dictifreturn_dictisnotNoneelseself.config.use_return_dictifself.config.is_decoder:use_cache=use_cacheifuse_cacheisnotNoneelseself.config.use_cacheelse:use_cache=Falseifisinstance(input_ids,NestedTensor):input_ids,attention_mask=input_ids.tensor,input_ids.maskifinput_idsisnotNoneandinputs_embedsisnotNone:raiseValueError("You cannot specify both input_ids and inputs_embeds at the same time")ifinput_idsisnotNone:self.warn_if_padding_and_no_attention_mask(input_ids,attention_mask)input_shape=input_ids.size()elifinputs_embedsisnotNone:input_shape=inputs_embeds.size()[:-1]else:raiseValueError("You have to specify either input_ids or inputs_embeds")batch_size,seq_length=input_shapedevice=input_ids.deviceifinput_idsisnotNoneelseinputs_embeds.device# type: ignore[union-attr]# past_key_values_lengthpast_key_values_length=past_key_values[0][0].shape[2]ifpast_key_valuesisnotNoneelse0ifattention_maskisNone:attention_mask=(input_ids.ne(self.pad_token_id)ifself.pad_token_idisnotNoneelsetorch.ones(((batch_size,seq_length+past_key_values_length)),device=device))# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]# ourselves in which case we just need to make it broadcastable to all heads.extended_attention_mask:Tensor=self.get_extended_attention_mask(attention_mask,input_shape)# If a 2D or 3D attention mask is provided for the cross-attention# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]ifself.config.is_decoderandencoder_hidden_statesisnotNone:encoder_batch_size,encoder_sequence_length,_=encoder_hidden_states.size()encoder_hidden_shape=(encoder_batch_size,encoder_sequence_length)ifencoder_attention_maskisNone:encoder_attention_mask=torch.ones(encoder_hidden_shape,device=device)encoder_extended_attention_mask=self.invert_attention_mask(encoder_attention_mask)else:encoder_extended_attention_mask=None# Prepare head mask if needed# 1.0 in head_mask indicate we keep the head# attention_probs has shape bsz x n_heads x N x N# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]head_mask=self.get_head_mask(head_mask,self.config.num_hidden_layers)embedding_output=self.embeddings(input_ids=input_ids,position_ids=position_ids,inputs_embeds=inputs_embeds,past_key_values_length=past_key_values_length,)encoder_outputs=self.encoder(embedding_output,attention_mask=extended_attention_mask,head_mask=head_mask,encoder_hidden_states=encoder_hidden_states,encoder_attention_mask=encoder_extended_attention_mask,past_key_values=past_key_values,use_cache=use_cache,output_attentions=output_attentions,output_hidden_states=output_hidden_states,return_dict=return_dict,)sequence_output=encoder_outputs[0]pooled_output=self.pooler(sequence_output)ifself.poolerisnotNoneelseNoneifnotreturn_dict:return(sequence_output,pooled_output)+encoder_outputs[1:]returnBaseModelOutputWithPoolingAndCrossAttentions(last_hidden_state=sequence_output,pooler_output=pooled_output,past_key_values=encoder_outputs.past_key_values,hidden_states=encoder_outputs.hidden_states,attentions=encoder_outputs.attentions,cross_attentions=encoder_outputs.cross_attentions,)
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]:
Tuple 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).
defforward(self,input_ids:Tensor|NestedTensor,attention_mask:Tensor|None=None,position_ids:Tensor|None=None,head_mask:Tensor|None=None,inputs_embeds:Tensor|NestedTensor|None=None,encoder_hidden_states:Tensor|None=None,encoder_attention_mask:Tensor|None=None,past_key_values:Tuple[Tuple[Tensor,Tensor,Tensor,Tensor],...]|None=None,use_cache:bool|None=None,output_attentions:bool|None=None,output_hidden_states:bool|None=None,return_dict:bool|None=None,**kwargs,)->Tuple[Tensor,...]|BaseModelOutputWithPoolingAndCrossAttentions:r""" Args: encoder_hidden_states: Shape: `(batch_size, sequence_length, hidden_size)` 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: Shape: `(batch_size, sequence_length)` 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 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: If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). """ifkwargs:warn(f"Additional keyword arguments `{', '.join(kwargs)}` are detected in "f"`{self.__class__.__name__}.forward`, they will be ignored.\n""This is provided for backward compatibility and may lead to unexpected behavior.")output_attentions=output_attentionsifoutput_attentionsisnotNoneelseself.config.output_attentionsoutput_hidden_states=(output_hidden_statesifoutput_hidden_statesisnotNoneelseself.config.output_hidden_states)return_dict=return_dictifreturn_dictisnotNoneelseself.config.use_return_dictifself.config.is_decoder:use_cache=use_cacheifuse_cacheisnotNoneelseself.config.use_cacheelse:use_cache=Falseifisinstance(input_ids,NestedTensor):input_ids,attention_mask=input_ids.tensor,input_ids.maskifinput_idsisnotNoneandinputs_embedsisnotNone:raiseValueError("You cannot specify both input_ids and inputs_embeds at the same time")ifinput_idsisnotNone:self.warn_if_padding_and_no_attention_mask(input_ids,attention_mask)input_shape=input_ids.size()elifinputs_embedsisnotNone:input_shape=inputs_embeds.size()[:-1]else:raiseValueError("You have to specify either input_ids or inputs_embeds")batch_size,seq_length=input_shapedevice=input_ids.deviceifinput_idsisnotNoneelseinputs_embeds.device# type: ignore[union-attr]# past_key_values_lengthpast_key_values_length=past_key_values[0][0].shape[2]ifpast_key_valuesisnotNoneelse0ifattention_maskisNone:attention_mask=(input_ids.ne(self.pad_token_id)ifself.pad_token_idisnotNoneelsetorch.ones(((batch_size,seq_length+past_key_values_length)),device=device))# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]# ourselves in which case we just need to make it broadcastable to all heads.extended_attention_mask:Tensor=self.get_extended_attention_mask(attention_mask,input_shape)# If a 2D or 3D attention mask is provided for the cross-attention# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]ifself.config.is_decoderandencoder_hidden_statesisnotNone:encoder_batch_size,encoder_sequence_length,_=encoder_hidden_states.size()encoder_hidden_shape=(encoder_batch_size,encoder_sequence_length)ifencoder_attention_maskisNone:encoder_attention_mask=torch.ones(encoder_hidden_shape,device=device)encoder_extended_attention_mask=self.invert_attention_mask(encoder_attention_mask)else:encoder_extended_attention_mask=None# Prepare head mask if needed# 1.0 in head_mask indicate we keep the head# attention_probs has shape bsz x n_heads x N x N# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]head_mask=self.get_head_mask(head_mask,self.config.num_hidden_layers)embedding_output=self.embeddings(input_ids=input_ids,position_ids=position_ids,inputs_embeds=inputs_embeds,past_key_values_length=past_key_values_length,)encoder_outputs=self.encoder(embedding_output,attention_mask=extended_attention_mask,head_mask=head_mask,encoder_hidden_states=encoder_hidden_states,encoder_attention_mask=encoder_extended_attention_mask,past_key_values=past_key_values,use_cache=use_cache,output_attentions=output_attentions,output_hidden_states=output_hidden_states,return_dict=return_dict,)sequence_output=encoder_outputs[0]pooled_output=self.pooler(sequence_output)ifself.poolerisnotNoneelseNoneifnotreturn_dict:return(sequence_output,pooled_output)+encoder_outputs[1:]returnBaseModelOutputWithPoolingAndCrossAttentions(last_hidden_state=sequence_output,pooler_output=pooled_output,past_key_values=encoder_outputs.past_key_values,hidden_states=encoder_outputs.hidden_states,attentions=encoder_outputs.attentions,cross_attentions=encoder_outputs.cross_attentions,)
classRnaBertPreTrainedModel(PreTrainedModel):""" An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """config_class=RnaBertConfigbase_model_prefix="rnabert"supports_gradient_checkpointing=True_no_split_modules=["RnaBertLayer","RnaBertEmbeddings"]# Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weightsdef_init_weights(self,module:nn.Module):"""Initialize the weights"""ifisinstance(module,nn.Linear):# Slightly different from the TF version which uses truncated_normal for initialization# cf https://github.com/pytorch/pytorch/pull/5617module.weight.data.normal_(mean=0.0,std=self.config.initializer_range)ifmodule.biasisnotNone:module.bias.data.zero_()elifisinstance(module,nn.Embedding):module.weight.data.normal_(mean=0.0,std=self.config.initializer_range)ifmodule.padding_idxisnotNone:module.weight.data[module.padding_idx].zero_()elifisinstance(module,nn.LayerNorm):module.bias.data.zero_()module.weight.data.fill_(1.0)