RNA-FM
Pre-trained model on non-coding RNA (ncRNA) using a masked language modeling (MLM) objective.
Disclaimer
This is an UNOFFICIAL implementation of the Interpretable RNA Foundation Model from Unannotated Data for Highly Accurate RNA Structure and Function Predictions by Jiayang Chen, Zhihang Hu, Siqi Sun, et al.
The OFFICIAL repository of RNA-FM is at ml4bio/RNA-FM.
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 RNA-FM did not write this model card for this model so this model card has been written by the MultiMolecule team.
Model Details
RNA-FM 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.
Variants
Model Specification
| Variants |
Num Layers |
Hidden Size |
Num Heads |
Intermediate Size |
Num Parameters (M) |
FLOPs (G) |
MACs (G) |
Max Num Tokens |
| mRNA-FM |
12 |
1280 |
20 |
5120 |
239.26 |
258.08 |
128.85 |
1024 |
| RNA-FM |
640 |
99.52 |
109.02 |
54.36 |
Links
- Code: multimolecule.rnafm
- Data: multimolecule/rnacentral
- Paper: Interpretable RNA Foundation Model from Unannotated Data for Highly Accurate RNA Structure and Function Predictions
- Developed by: Jiayang Chen, Zhihang Hu, Siqi Sun, Qingxiong Tan, Yixuan Wang, Qinze Yu, Licheng Zong, Liang Hong, Jin Xiao, Tao Shen, Irwin King, Yu Li
- Model type: BERT - ESM
- Original Repository: ml4bio/RNA-FM
Usage
The model file depends on the multimolecule library. You can install it using pip:
| Bash |
|---|
| pip install multimolecule
|
Direct Use
Masked Language Modeling
You can use this model directly with a pipeline for masked language modeling:
| Python |
|---|
| import multimolecule # you must import multimolecule to register models
from transformers import pipeline
predictor = pipeline("fill-mask", model="multimolecule/rnafm")
output = predictor("gguc<mask>cucugguuagaccagaucugagccu")
|
Downstream Use
Here is how to use this model to get the features of a given sequence in PyTorch:
| Python |
|---|
| from multimolecule import RnaTokenizer, RnaFmModel
tokenizer = RnaTokenizer.from_pretrained("multimolecule/rnafm")
model = RnaFmModel.from_pretrained("multimolecule/rnafm")
text = "UAGCUUAUCAGACUGAUGUUG"
input = tokenizer(text, return_tensors="pt")
output = model(**input)
|
Sequence Classification / Regression
Note
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:
| Python |
|---|
| import torch
from multimolecule import RnaTokenizer, RnaFmForSequencePrediction
tokenizer = RnaTokenizer.from_pretrained("multimolecule/rnafm")
model = RnaFmForSequencePrediction.from_pretrained("multimolecule/rnafm")
text = "UAGCUUAUCAGACUGAUGUUG"
input = tokenizer(text, return_tensors="pt")
label = torch.tensor([1])
output = model(**input, labels=label)
|
Token Classification / Regression
Note
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:
| Python |
|---|
| import torch
from multimolecule import RnaTokenizer, RnaFmForTokenPrediction
tokenizer = RnaTokenizer.from_pretrained("multimolecule/rnafm")
model = RnaFmForTokenPrediction.from_pretrained("multimolecule/rnafm")
text = "UAGCUUAUCAGACUGAUGUUG"
input = tokenizer(text, return_tensors="pt")
label = torch.randint(2, (len(text), ))
output = model(**input, labels=label)
|
Note
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:
| Python |
|---|
| import torch
from multimolecule import RnaTokenizer, RnaFmForContactPrediction
tokenizer = RnaTokenizer.from_pretrained("multimolecule/rnafm")
model = RnaFmForContactPrediction.from_pretrained("multimolecule/rnafm")
text = "UAGCUUAUCAGACUGAUGUUG"
input = tokenizer(text, return_tensors="pt")
label = torch.randint(2, (len(text), len(text)))
output = model(**input, labels=label)
|
Training Details
RNA-FM used Masked Language Modeling (MLM) as the pre-training objective: 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.
Training Data
The RNA-FM 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.
RNA-FM applied CD-HIT (CD-HIT-EST) with a cut-off at 100% sequence identity to remove redundancy from the RNAcentral. The final dataset contains 23.7 million non-redundant RNA sequences.
RNA-FM 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.
Training Procedure
Preprocessing
RNA-FM used masked language modeling (MLM) as the pre-training objective. The masking procedure is similar to the one used in BERT:
- Mask rate: 15%
- Replacement:
<mask> for 80% of masked tokens
- Replacement: random token for 10% of masked tokens
- Replacement: unchanged token for 10% of masked tokens
Pre-training
The model was trained on 8 NVIDIA A100 GPUs with 80GiB memories.
- Learning rate: 1e-4
- Learning rate scheduler: Inverse square root
- Learning rate warm-up: 10,000 steps
- Weight decay: 0.01
Citation
| BibTeX |
|---|
| @article{chen2022interpretable,
title={Interpretable rna foundation model from unannotated data for highly accurate rna structure and function predictions},
author={Chen, Jiayang and Hu, Zhihang and Sun, Siqi and Tan, Qingxiong and Wang, Yixuan and Yu, Qinze and Zong, Licheng and Hong, Liang and Xiao, Jin and King, Irwin and others},
journal={arXiv preprint arXiv:2204.00300},
year={2022}
}
|
Note
The artifacts distributed in this repository are part of the MultiMolecule project.
If MultiMolecule supports your research, please cite the MultiMolecule project as follows:
| BibTeX |
|---|
| @software{chen_2024_12638419,
author = {Chen, Zhiyuan and Zhu, Sophia Y.},
title = {MultiMolecule},
doi = {10.5281/zenodo.12638419},
publisher = {Zenodo},
url = {https://doi.org/10.5281/zenodo.12638419},
year = 2024,
month = may,
day = 4
}
|
Please use GitHub issues of MultiMolecule for any questions or comments on the model card.
Please contact the authors of the RNA-FM paper for questions or comments on the paper/model.
License
This model implementation is licensed under the GNU Affero General Public License.
For additional terms and clarifications, please refer to our License FAQ.
| Text Only |
|---|
| SPDX-License-Identifier: AGPL-3.0-or-later
|
API Reference
RnaFmConfig
Bases: PreTrainedConfig
This is the configuration class to store the configuration of a RnaFmModel.
It is used to instantiate a RNA-FM 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 RNA-FM
ml4bio/RNA-FM architecture.
Configuration objects inherit from PreTrainedConfig and can be used to
control the model outputs. Read the documentation from PreTrainedConfig
for more information.
Parameters:
| Name |
Type |
Description |
Default |
vocab_size
|
int | None
|
Vocabulary size of the RNA-FM model. Defines the number of different tokens that can be represented by the
input_ids passed when calling [RnaFmModel].
Defaults to 26 if codon=False else 131.
|
None
|
codon
|
bool
|
Whether to use codon tokenization.
|
False
|
hidden_size
|
int
|
Dimensionality of the encoder layers and the pooler layer.
|
640
|
num_hidden_layers
|
int
|
Number of hidden layers in the Transformer encoder.
|
12
|
num_attention_heads
|
int
|
Number of attention heads for each attention layer in the Transformer encoder.
|
20
|
|
|
int
|
Dimensionality of the “intermediate” (often named feed-forward) layer in the Transformer encoder.
|
5120
|
hidden_act
|
str
|
The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu",
"relu", "silu" and "gelu_new" are supported.
|
'gelu'
|
hidden_dropout
|
float
|
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
0.1
|
attention_dropout
|
float
|
The dropout ratio for the attention probabilities.
|
0.1
|
max_position_embeddings
|
int
|
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).
|
1026
|
initializer_range
|
float
|
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
0.02
|
layer_norm_eps
|
float
|
The epsilon used by the layer normalization layers.
|
1e-05
|
position_embedding_type
|
str
|
|
'absolute'
|
is_decoder
|
bool
|
Whether the model is used as a decoder or not. If False, the model is used as an encoder.
|
False
|
use_cache
|
bool
|
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if config.is_decoder=True.
|
True
|
embed_norm
|
bool
|
Whether to apply layer normalization after embeddings but before the main stem of the network.
|
True
|
token_dropout
|
bool
|
When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
|
False
|
head
|
HeadConfig | None
|
The configuration of the prediction head.
|
None
|
lm_head
|
MaskedLMHeadConfig | None
|
The configuration of the masked language model head.
|
None
|
add_cross_attention
|
bool
|
Whether to add cross-attention layers when the model is used as a decoder.
|
False
|
Examples:
| Python Console Session |
|---|
| >>> from multimolecule import RnaFmConfig, RnaFmModel
>>> # Initializing a RNA-FM multimolecule/rnafm style configuration
>>> configuration = RnaFmConfig()
>>> # Initializing a model (with random weights) from the multimolecule/rnafm style configuration
>>> model = RnaFmModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
|
Source code in multimolecule/models/rnafm/configuration_rnafm.py
| Python |
|---|
| class RnaFmConfig(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`RnaFmModel`][multimolecule.models.RnaFmModel].
It is used to instantiate a RNA-FM 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 RNA-FM
[ml4bio/RNA-FM](https://github.com/ml4bio/RNA-FM) 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 RNA-FM model. Defines the number of different tokens that can be represented by the
`input_ids` passed when calling [`RnaFmModel`].
Defaults to 26 if `codon=False` else 131.
codon:
Whether to use codon tokenization.
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"`,
`"rotary"`.
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`.
embed_norm:
Whether to apply layer normalization after embeddings but before the main stem of the network.
token_dropout:
When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.
head:
The configuration of the prediction head.
lm_head:
The configuration of the masked language model head.
add_cross_attention:
Whether to add cross-attention layers when the model is used as a decoder.
Examples:
>>> from multimolecule import RnaFmConfig, RnaFmModel
>>> # Initializing a RNA-FM multimolecule/rnafm style configuration
>>> configuration = RnaFmConfig()
>>> # Initializing a model (with random weights) from the multimolecule/rnafm style configuration
>>> model = RnaFmModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
"""
model_type = "rnafm"
def __init__(
self,
vocab_size: int | None = None,
codon: bool = False,
hidden_size: int = 640,
num_hidden_layers: int = 12,
num_attention_heads: int = 20,
intermediate_size: int = 5120,
hidden_act: str = "gelu",
hidden_dropout: float = 0.1,
attention_dropout: float = 0.1,
max_position_embeddings: int = 1026,
initializer_range: float = 0.02,
layer_norm_eps: float = 1e-5,
position_embedding_type: str = "absolute",
is_decoder: bool = False,
use_cache: bool = True,
embed_norm: bool = True,
token_dropout: bool = False,
head: HeadConfig | None = None,
lm_head: MaskedLMHeadConfig | None = None,
add_cross_attention: bool = False,
**kwargs,
):
super().__init__(**kwargs)
expected_vocab_size = 131 if codon else 28
if vocab_size is None:
vocab_size = expected_vocab_size
elif vocab_size != expected_vocab_size:
raise ValueError(f"vocab_size ({vocab_size}) must be {expected_vocab_size} when codon={codon}.")
validate_attention_dimensions(hidden_size, num_attention_heads)
self.vocab_size = vocab_size
self.codon = codon
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout = hidden_dropout
self.attention_dropout = attention_dropout
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.position_embedding_type = position_embedding_type
self.is_decoder = is_decoder
self.use_cache = use_cache
self.embed_norm = embed_norm
self.token_dropout = token_dropout
self.head = HeadConfig(**head) if head is not None else None
lm_head_kwargs = dict(lm_head or {})
lm_head_kwargs.setdefault("layer_norm_eps", layer_norm_eps)
self.lm_head = MaskedLMHeadConfig(**lm_head_kwargs)
self.add_cross_attention = add_cross_attention
|
RnaFmSecondaryStructureHeadConfig
Bases: BaseHeadConfig
Configuration class for a prediction head.
Parameters:
| Name |
Type |
Description |
Default |
num_labels
|
|
Number of labels to use in the last layer added to the model, typically for a classification task.
Head should look for Config.num_labels if is None.
|
required
|
problem_type
|
|
Problem type for XxxForYyyPrediction models. Can be one of "binary", "regression",
"multiclass" or "multilabel".
Head should look for Config.problem_type if is None.
|
required
|
dropout
|
|
The dropout ratio for the hidden states.
|
required
|
kernel_size
|
|
Kernel size of the 1D convolutional layers in the head.
|
required
|
num_layers
|
|
Number of convolutional layers in the head.
|
required
|
num_channels
|
|
Number of channels in the convolutional layers.
|
required
|
bias
|
|
Whether to include bias terms in the convolutional layers.
|
required
|
activation
|
|
Activation function used in the head.
|
required
|
hidden_size
|
|
Hidden size used by the head.
|
required
|
|
|
|
Intermediate size used by the head.
|
required
|
Source code in multimolecule/models/rnafm/configuration_rnafm.py
| Python |
|---|
| class RnaFmSecondaryStructureHeadConfig(BaseHeadConfig):
r"""
Configuration class for a prediction head.
Args:
num_labels:
Number of labels to use in the last layer added to the model, typically for a classification task.
Head should look for [`Config.num_labels`][multimolecule.PreTrainedConfig] if is `None`.
problem_type:
Problem type for `XxxForYyyPrediction` models. Can be one of `"binary"`, `"regression"`,
`"multiclass"` or `"multilabel"`.
Head should look for [`Config.problem_type`][multimolecule.PreTrainedConfig] if is `None`.
dropout:
The dropout ratio for the hidden states.
kernel_size:
Kernel size of the 1D convolutional layers in the head.
num_layers:
Number of convolutional layers in the head.
num_channels:
Number of channels in the convolutional layers.
bias:
Whether to include bias terms in the convolutional layers.
activation:
Activation function used in the head.
hidden_size:
Hidden size used by the head.
intermediate_size:
Intermediate size used by the head.
"""
num_labels: int = 1
problem_type: str | None = None
dropout: float = 0.3
kernel_size: int = 7
num_layers: int = 32
num_channels: int = 64
bias: bool = False
activation: str = "relu"
hidden_size: int = 128
intermediate_size: int = 256
|
Bases: RnaFmPreTrainedModel
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForContactPrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForContactPrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=torch.randint(2, (1, 5, 5)))
>>> output["logits"].shape
torch.Size([1, 5, 5, 1])
>>> output["loss"]
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmForContactPrediction(RnaFmPreTrainedModel):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForContactPrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForContactPrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=torch.randint(2, (1, 5, 5)))
>>> output["logits"].shape
torch.Size([1, 5, 5, 1])
>>> output["loss"] # doctest:+ELLIPSIS
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
"""
def __init__(self, config: RnaFmConfig):
super().__init__(config)
self.model = RnaFmModel(config, add_pooling_layer=False)
self.contact_head = ContactPredictionHead(config)
self.head_config = self.contact_head.config
self.require_attentions = self.contact_head.require_attentions
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
def forward(
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
labels: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[Tensor, ...] | ContactPredictorOutput:
if self.require_attentions:
output_attentions = kwargs.get("output_attentions", self.config.output_attentions)
if output_attentions is False:
warn("output_attentions must be True since prediction head requires attentions.")
kwargs["output_attentions"] = True
outputs = self.model(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
output = self.contact_head(outputs, attention_mask, input_ids, labels)
logits, loss = output.logits, output.loss
return ContactPredictorOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
Bases: RnaFmPreTrainedModel
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForMaskedLM, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForMaskedLM(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=input["input_ids"])
>>> output["logits"].shape
torch.Size([1, 7, 28])
>>> output["loss"]
tensor(..., grad_fn=<NllLossBackward0>)
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmForMaskedLM(RnaFmPreTrainedModel):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForMaskedLM, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForMaskedLM(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=input["input_ids"])
>>> output["logits"].shape
torch.Size([1, 7, 28])
>>> output["loss"] # doctest:+ELLIPSIS
tensor(..., grad_fn=<NllLossBackward0>)
"""
_tied_weights_keys = {
"lm_head.decoder.weight": "model.embeddings.word_embeddings.weight",
"lm_head.decoder.bias": "lm_head.bias",
}
def __init__(self, config: RnaFmConfig):
super().__init__(config)
if config.is_decoder:
warn(
"If you want to use `RnaFmForMaskedLM` make sure `config.is_decoder=False` for "
"bi-directional self-attention."
)
self.model = RnaFmModel(config, add_pooling_layer=False)
self.lm_head = MaskedLMHead(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.lm_head.decoder
def set_output_embeddings(self, embeddings):
self.lm_head.decoder = embeddings
if hasattr(self.lm_head, "bias"):
self.lm_head.bias = embeddings.bias
@can_return_tuple
def forward(
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
encoder_hidden_states: Tensor | None = None,
encoder_attention_mask: Tensor | None = None,
labels: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[Tensor, ...] | MaskedLMOutput:
outputs = self.model(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
return_dict=True,
**kwargs,
)
output = self.lm_head(outputs, labels)
logits, loss = output.logits, output.loss
return MaskedLMOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
RnaFmForPreTraining
Bases: RnaFmForMaskedLM
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForPreTraining, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForPreTraining(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels_lm=input["input_ids"])
>>> output["loss"]
tensor(..., grad_fn=<MeanBackward0>)
>>> output["logits_lm"].shape
torch.Size([1, 7, 28])
>>> output["logits_ss"].shape
torch.Size([1, 5, 5, 1])
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmForPreTraining(RnaFmForMaskedLM):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForPreTraining, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForPreTraining(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels_lm=input["input_ids"])
>>> output["loss"] # doctest:+ELLIPSIS
tensor(..., grad_fn=<MeanBackward0>)
>>> output["logits_lm"].shape
torch.Size([1, 7, 28])
>>> output["logits_ss"].shape
torch.Size([1, 5, 5, 1])
"""
def __init__(self, config: RnaFmConfig):
super().__init__(config)
self.ss_head = ContactAttentionHead(config)
self.require_attentions = self.ss_head.require_attentions
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
def forward( # type: ignore[override]
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
encoder_hidden_states: Tensor | None = None,
encoder_attention_mask: Tensor | None = None,
labels_lm: Tensor | None = None,
labels_ss: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[Tensor, ...] | RnaFmForPreTrainingOutput:
if self.require_attentions:
output_attentions = kwargs.get("output_attentions", self.config.output_attentions)
if output_attentions is False:
warn("output_attentions must be True since prediction head requires attentions.")
kwargs["output_attentions"] = True
outputs = self.model(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
return_dict=True,
**kwargs,
)
output_lm = self.lm_head(outputs, labels=labels_lm)
logits_lm, loss_lm = output_lm.logits, output_lm.loss
output_ss = self.ss_head(outputs, attention_mask, input_ids, labels=labels_ss)
logits_ss, loss_ss = output_ss.logits, output_ss.loss
losses = tuple(l for l in (loss_lm, loss_ss) if l is not None) # noqa: E741
loss = torch.mean(torch.stack(losses)) if losses else None
return RnaFmForPreTrainingOutput(
loss=loss,
logits_lm=logits_lm,
loss_lm=loss_lm,
logits_ss=logits_ss,
loss_ss=loss_ss,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
RnaFmForSecondaryStructurePrediction
Bases: RnaFmForPreTraining
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForSecondaryStructurePrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForSecondaryStructurePrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input)
>>> output["logits"].shape
torch.Size([1, 5, 5, 1])
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmForSecondaryStructurePrediction(RnaFmForPreTraining):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForSecondaryStructurePrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForSecondaryStructurePrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input)
>>> output["logits"].shape
torch.Size([1, 5, 5, 1])
"""
# Note: inherits from RnaFmForPreTraining (rather than RnaFmPreTrainedModel directly) to retain
# `lm_head` in the state dict. The published rnafm-ss checkpoint was saved with lm_head weights
# present; changing the inheritance would break checkpoint loading.
def __init__(self, config: RnaFmConfig):
super().__init__(config)
self.model = RnaFmModel(config, add_pooling_layer=False)
self.ss_head = RnaFmSecondaryStructurePredictionHead(config)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
def forward( # type: ignore[override]
self,
input_ids: Tensor | NestedTensor,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
encoder_hidden_states: Tensor | None = None,
encoder_attention_mask: Tensor | None = None,
labels: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[Tensor, ...] | ContactPredictorOutput:
if self.require_attentions:
output_attentions = kwargs.get("output_attentions", self.config.output_attentions)
if output_attentions is False:
warn("output_attentions must be True since prediction head requires attentions.")
kwargs["output_attentions"] = True
outputs = self.model(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
return_dict=True,
**kwargs,
)
output = self.ss_head(outputs, attention_mask, input_ids, labels=labels)
logits, loss = output.logits, output.loss
return ContactPredictorOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
RnaFmForSequencePrediction
Bases: RnaFmPreTrainedModel
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForSequencePrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForSequencePrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=torch.tensor([[1]]))
>>> output["logits"].shape
torch.Size([1, 1])
>>> output["loss"]
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmForSequencePrediction(RnaFmPreTrainedModel):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForSequencePrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForSequencePrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=torch.tensor([[1]]))
>>> output["logits"].shape
torch.Size([1, 1])
>>> output["loss"] # doctest:+ELLIPSIS
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
"""
def __init__(self, config: RnaFmConfig):
super().__init__(config)
self.model = RnaFmModel(config)
self.sequence_head = SequencePredictionHead(config)
self.head_config = self.sequence_head.config
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
def forward(
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
labels: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[Tensor, ...] | SequencePredictorOutput:
outputs = self.model(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
output = self.sequence_head(outputs, labels)
logits, loss = output.logits, output.loss
return SequencePredictorOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
RnaFmForTokenPrediction
Bases: RnaFmPreTrainedModel
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForTokenPrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForTokenPrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=torch.randint(2, (1, 5)))
>>> output["logits"].shape
torch.Size([1, 5, 1])
>>> output["loss"]
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmForTokenPrediction(RnaFmPreTrainedModel):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmForTokenPrediction, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmForTokenPrediction(config)
>>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
>>> input = tokenizer("ACGUN", return_tensors="pt")
>>> output = model(**input, labels=torch.randint(2, (1, 5)))
>>> output["logits"].shape
torch.Size([1, 5, 1])
>>> output["loss"] # doctest:+ELLIPSIS
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
"""
def __init__(self, config: RnaFmConfig):
super().__init__(config)
self.model = RnaFmModel(config, add_pooling_layer=False)
self.token_head = TokenPredictionHead(config)
self.head_config = self.token_head.config
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
def forward(
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
labels: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[Tensor, ...] | TokenPredictorOutput:
outputs = self.model(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
output = self.token_head(outputs, attention_mask, input_ids, labels)
logits, loss = output.logits, output.loss
return TokenPredictorOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
RnaFmModel
Bases: RnaFmPreTrainedModel
Examples:
| Python Console Session |
|---|
| >>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmModel, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmModel(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, 640])
>>> output["pooler_output"].shape
torch.Size([1, 640])
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmModel(RnaFmPreTrainedModel):
"""
Examples:
>>> import torch
>>> from multimolecule import RnaFmConfig, RnaFmModel, RnaTokenizer
>>> config = RnaFmConfig()
>>> model = RnaFmModel(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, 640])
>>> output["pooler_output"].shape
torch.Size([1, 640])
"""
def __init__(self, config: RnaFmConfig, add_pooling_layer: bool = True):
super().__init__(config)
self.pad_token_id = config.pad_token_id
self.embeddings = RnaFmEmbeddings(config)
self.encoder = RnaFmEncoder(config)
self.pooler = RnaFmPooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
@merge_with_config_defaults
@capture_outputs
def forward(
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
encoder_hidden_states: Tensor | None = None,
encoder_attention_mask: Tensor | None = None,
past_key_values: Cache | None = None,
use_cache: bool | None = None,
cache_position: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> 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.num_hidden_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`).
"""
if self.config.is_decoder:
use_cache = use_cache if use_cache is not None else self.config.use_cache
else:
use_cache = False
if use_cache and past_key_values is None:
past_key_values = (
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
if encoder_hidden_states is not None or self.config.is_encoder_decoder
else DynamicCache(config=self.config)
)
if isinstance(input_ids, NestedTensor) and attention_mask is None:
attention_mask = input_ids.mask
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if input_ids is not None:
device = input_ids.device
seq_length = input_ids.shape[1]
else:
device = inputs_embeds.device # type: ignore[union-attr]
seq_length = inputs_embeds.shape[1] # type: ignore[union-attr]
# past_key_values_length
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
if cache_position is None:
cache_position = torch.arange(past_key_values_length, past_key_values_length + seq_length, device=device)
if attention_mask is None and input_ids is not None and self.pad_token_id is not None:
attention_mask = input_ids.ne(self.pad_token_id)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
)
attention_mask, encoder_attention_mask = self._create_attention_masks(
attention_mask=attention_mask,
encoder_attention_mask=encoder_attention_mask,
embedding_output=embedding_output,
encoder_hidden_states=encoder_hidden_states,
cache_position=cache_position,
past_key_values=past_key_values,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask,
encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_ids=position_ids,
**kwargs,
)
sequence_output = encoder_outputs.last_hidden_state
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
return BaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
past_key_values=encoder_outputs.past_key_values,
)
def _create_attention_masks(
self,
attention_mask,
encoder_attention_mask,
embedding_output,
encoder_hidden_states,
cache_position,
past_key_values,
):
if self.config.is_decoder:
attention_mask = create_causal_mask(
config=self.config,
inputs_embeds=embedding_output,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
)
else:
attention_mask = create_bidirectional_mask(
config=self.config, inputs_embeds=embedding_output, attention_mask=attention_mask
)
if encoder_attention_mask is not None:
encoder_attention_mask = create_bidirectional_mask(
config=self.config,
inputs_embeds=embedding_output,
attention_mask=encoder_attention_mask,
encoder_hidden_states=encoder_hidden_states,
)
return attention_mask, encoder_attention_mask
|
forward
Pythonforward(
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
encoder_hidden_states: Tensor | None = None,
encoder_attention_mask: Tensor | None = None,
past_key_values: Cache | None = None,
use_cache: bool | None = None,
cache_position: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs]
) -> (
tuple[Tensor, ...]
| BaseModelOutputWithPoolingAndCrossAttentions
)
Parameters:
| Name |
Type |
Description |
Default |
encoder_hidden_states
|
Tensor | None
|
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.
|
None
|
encoder_attention_mask
|
Tensor | None
|
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.
|
None
|
past_key_values
|
Cache | None
|
tuple of length config.num_hidden_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).
|
None
|
use_cache
|
bool | None
|
If set to True, past_key_values key value states are returned and can be used to speed up decoding
(see past_key_values).
|
None
|
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| @merge_with_config_defaults
@capture_outputs
def forward(
self,
input_ids: Tensor | NestedTensor | None = None,
attention_mask: Tensor | None = None,
position_ids: Tensor | None = None,
inputs_embeds: Tensor | NestedTensor | None = None,
encoder_hidden_states: Tensor | None = None,
encoder_attention_mask: Tensor | None = None,
past_key_values: Cache | None = None,
use_cache: bool | None = None,
cache_position: Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> 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.num_hidden_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`).
"""
if self.config.is_decoder:
use_cache = use_cache if use_cache is not None else self.config.use_cache
else:
use_cache = False
if use_cache and past_key_values is None:
past_key_values = (
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
if encoder_hidden_states is not None or self.config.is_encoder_decoder
else DynamicCache(config=self.config)
)
if isinstance(input_ids, NestedTensor) and attention_mask is None:
attention_mask = input_ids.mask
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if input_ids is not None:
device = input_ids.device
seq_length = input_ids.shape[1]
else:
device = inputs_embeds.device # type: ignore[union-attr]
seq_length = inputs_embeds.shape[1] # type: ignore[union-attr]
# past_key_values_length
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
if cache_position is None:
cache_position = torch.arange(past_key_values_length, past_key_values_length + seq_length, device=device)
if attention_mask is None and input_ids is not None and self.pad_token_id is not None:
attention_mask = input_ids.ne(self.pad_token_id)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
)
attention_mask, encoder_attention_mask = self._create_attention_masks(
attention_mask=attention_mask,
encoder_attention_mask=encoder_attention_mask,
embedding_output=embedding_output,
encoder_hidden_states=encoder_hidden_states,
cache_position=cache_position,
past_key_values=past_key_values,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask,
encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_ids=position_ids,
**kwargs,
)
sequence_output = encoder_outputs.last_hidden_state
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
return BaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
past_key_values=encoder_outputs.past_key_values,
)
|
RnaFmPreTrainedModel
Bases: PreTrainedModel
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
Source code in multimolecule/models/rnafm/modeling_rnafm.py
| Python |
|---|
| class RnaFmPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = RnaFmConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_record_outputs: dict[str, Any] | None = None
_no_split_modules = ["RnaFmLayer", "RnaFmEmbeddings"]
@torch.no_grad()
def _init_weights(self, module: nn.Module):
super()._init_weights(module)
if isinstance(module, RnaFmEmbeddings):
# `position_ids` is a non-persistent buffer; under transformers v5 meta-init it
# stays on the meta device after `from_pretrained`, so populate it here.
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|