RNA-FM - MultiMolecule
Author: MultiMolecule
Description: Neural Networks for RNA, DNA, and Protein

跳转至

# 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 Hue, 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.

### Variations

- `multimolecule/rnafm`: The RNA-FM model pre-trained on non-coding RNA sequences.
- `multimolecule/mrnafm`: The RNA-FM model pre-trained on mRNA coding sequences.

### Model Specification

Variants | Num Layers | Hidden Size | Num Heads | Intermediate Size | Num Parameters (M) | FLOPs (G) | MACs (G) | Max Num Tokens
--- | --- | --- | --- | --- | --- | --- | --- | ---
RNA-FM | 12 | 640 | 20 | 5120 | 99.52 | 25.68 | 12.83 | 1024
mRNA-FM | 1280 | 239.25 | 61.43 | 30.7

### Links

- Code: multimolecule.rnafm
- Data: 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: https://github.com/ml4bio/RNA-FM

## Usage

The model file depends on the `multimolecule` library. You can install it using pip:

Bash
    1
    pip install multimolecule

### Direct Use

You can use this model directly with a pipeline for masked language modeling:

Python
     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
    >>> import multimolecule  # you must import multimolecule to register models
    >>> from transformers import pipeline
    >>> unmasker = pipeline('fill-mask', model='multimolecule/rnafm')
    >>> unmasker("uagc<mask>uaucagacugauguuga")

    [{'score': 0.3237496316432953,
      'token': 24,
      'token_str': '*',
      'sequence': 'U A G C * U A U C A G A C U G A U G U U G A'},
     {'score': 0.28286001086235046,
      'token': 11,
      'token_str': 'I',
      'sequence': 'U A G C I U A U C A G A C U G A U G U U G A'},
     {'score': 0.11762786656618118,
      'token': 23,
      'token_str': '.',
      'sequence': 'U A G C. U A U C A G A C U G A U G U U G A'},
     {'score': 0.07875438779592514,
      'token': 6,
      'token_str': 'A',
      'sequence': 'U A G C A U A U C A G A C U G A U G U U G A'},
     {'score': 0.06866674870252609,
      'token': 9,
      'token_str': 'U',
      'sequence': 'U A G C U U A U C A G A C U G A U G U U G A'}]

### Downstream Use

#### Extract Features

Here is how to use this model to get the features of a given sequence in PyTorch:

Python
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    from multimolecule import RnaTokenizer, RnaFmModel

    tokenizer = RnaTokenizer.from_pretrained('multimolecule/rnafm')
    model = RnaFmModel.from_pretrained('multimolecule/rnafm')

    text = "UAGCUUAUCAGACUGAUGUUGA"
    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
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    import torch
    from multimolecule import RnaTokenizer, RnaFmForSequencePrediction

    tokenizer = RnaTokenizer.from_pretrained('multimolecule/rnafm')
    model = RnaFmForSequencePrediction.from_pretrained('multimolecule/rnafm')

    text = "UAGCUUAUCAGACUGAUGUUGA"
    input = tokenizer(text, return_tensors='pt')
    label = torch.tensor([1])

    output = model(**input, labels=label)

#### Nucleotide 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 nucleotide classification or regression.

Here is how to use this model as backbone to fine-tune for a nucleotide-level task in PyTorch:

Python
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    import torch
    from multimolecule import RnaTokenizer, RnaFmForNucleotidePrediction

    tokenizer = RnaTokenizer.from_pretrained('multimolecule/rnafm')
    model = RnaFmForNucleotidePrediction.from_pretrained('multimolecule/rnafm')

    text = "UAGCUUAUCAGACUGAUGUUGA"
    input = tokenizer(text, return_tensors='pt')
    label = torch.randint(2, (len(text), ))

    output = model(**input, labels=label)

#### Contact 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 contact classification or regression.

Here is how to use this model as backbone to fine-tune for a contact-level task in PyTorch:

Python
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    import torch
    from multimolecule import RnaTokenizer, RnaFmForContactPrediction

    tokenizer = RnaTokenizer.from_pretrained('multimolecule/rnafm')
    model = RnaFmForContactPrediction.from_pretrained('multimolecule/rnafm')

    text = "UAGCUUAUCAGACUGAUGUUGA"
    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:

- 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.

#### PreTraining

The model was trained on 8 NVIDIA A100 GPUs with 80GiB memories.

- Learning rate: 1e-4
- Weight decay: 0.01
- Learning rate scheduler: inverse square root
- Learning rate warm-up: 10,000 steps

## Citation

BibTeX:

BibTeX
    1
    2
    3
    4
    5
    6
    @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}
    }

## Contact

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 is licensed under the AGPL-3.0 License.

Text Only
    1
    SPDX-License-Identifier: AGPL-3.0-or-later

## `` multimolecule.models.rnafm

### `` RnaTokenizer

Bases: `Tokenizer`

Tokenizer for RNA sequences.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`alphabet` | `Alphabet | str | List[str] | None` | 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` `iupac` `streamline` `nucleobase` If is an alphabet or a list of characters, that specific alphabet will be used. | `None`
`nmers` | `int` | Size of kmer to tokenize. | `1`
`codon` | `bool` | Whether to tokenize into codons. | `False`
`replace_T_with_U` | `bool` | Whether to replace T with U. | `True`
`do_upper_case` | `bool` | Whether to convert input to uppercase. | `True`

Examples:

Python Console Session

    >>> from multimolecule import RnaTokenizer
    >>> tokenizer = RnaTokenizer()
    >>> tokenizer('<pad><cls><eos><unk><mask><null>ACGUNIXVHDBMRWSYK.*-')["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

Source code in `multimolecule/tokenisers/rna/tokenization_rna.py`

Python
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    class RnaTokenizer(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`
                    + `iupac`
                    + `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>ACGUNIXVHDBMRWSYK.*-')["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,
            additional_special_tokens: List | Tuple | None = None,
            do_upper_case: bool = True,
            **kwargs,
        ):
            if codon and nmers > 1:
                raise ValueError("Codon and nmers cannot be used together.")
            if codon:
                nmers = 3  # set to 3 to get correct vocab
            if not isinstance(alphabet, Alphabet):
                alphabet = get_alphabet(alphabet, nmers=nmers)
            super().__init__(
                alphabet=alphabet,
                additional_special_tokens=additional_special_tokens,
                do_upper_case=do_upper_case,
                **kwargs,
            )
            self.replace_T_with_U = replace_T_with_U
            self.nmers = nmers
            self.condon = codon

        def _tokenize(self, text: str, **kwargs):
            if self.do_upper_case:
                text = text.upper()
            if self.replace_T_with_U:
                text = text.replace("T", "U")
            if self.condon:
                if len(text) % 3 != 0:
                    raise ValueError(
                        f"length of input sequence  must be a multiple of 3 for codon tokenization, but got {len(text)}"
                    )
                return [text[i : i + 3] for i in range(0, len(text), 3)]
            if self.nmers > 1:
                return [text[i : i + self.nmers] for i in range(len(text) - self.nmers + 1)]  # noqa: E203
            return list(text)

### `` 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 `inputs_ids` passed when calling [`RnaFmModel`]. Defaults to 25 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`
`intermediate_size` | `int` | Dimensionality of the “intermediate” (often named feed-forward) layer in the Transformer encoder. | `5120`
`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-12`
`position_embedding_type` | `str` | 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.). For more information on `"relative_key_query"`, please refer to Method 4 in Improve Transformer Models with Better Relative Position Embeddings (Huang et al.). | `'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`
`emb_layer_norm_before` | `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`

Examples:

Python Console Session

    >>> from multimolecule import RnaFmModel, RnaFmConfig

Python Console Session

    >>> # Initializing a RNA-FM multimolecule/rnafm style configuration
    >>> configuration = RnaFmConfig()

Python Console Session

    >>> # Initializing a model (with random weights) from the multimolecule/rnafm style configuration
    >>> model = RnaFmModel(configuration)

Python Console Session

    >>> # Accessing the model configuration
    >>> configuration = model.config

Source code in `multimolecule/models/rnafm/configuration_rnafm.py`

Python
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    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
                `inputs_ids` passed when calling [`RnaFmModel`].
                Defaults to 25 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_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`.
            emb_layer_norm_before:
                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.

        Examples:
            >>> from multimolecule import RnaFmModel, RnaFmConfig

            >>> # 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-12,
            position_embedding_type: str = "absolute",
            is_decoder: bool = False,
            use_cache: bool = True,
            emb_layer_norm_before: bool = True,
            token_dropout: bool = False,
            head: HeadConfig | None = None,
            lm_head: MaskedLMHeadConfig | None = None,
            **kwargs,
        ):
            super().__init__(**kwargs)
            if vocab_size is None:
                vocab_size = 131 if codon else 26
            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.emb_layer_norm_before = emb_layer_norm_before
            self.token_dropout = token_dropout
            self.head = HeadConfig(**head if head is not None else {})
            self.lm_head = MaskedLMHeadConfig(**lm_head if lm_head is not None else {})

### `` RnaFmForContactPrediction

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> 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, 2])
    >>> output["loss"]
    tensor(..., grad_fn=<NllLossBackward0>)

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    class RnaFmForContactPrediction(RnaFmPreTrainedModel):
        """
        Examples:
            >>> 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, 2])
            >>> output["loss"]  # doctest:+ELLIPSIS
            tensor(..., grad_fn=<NllLossBackward0>)
        """

        def __init__(self, config: RnaFmConfig):
            super().__init__(config)
            self.rnafm = RnaFmModel(config, add_pooling_layer=True)
            self.contact_head = ContactPredictionHead(config)
            self.head_config = self.contact_head.config

            # Initialize weights and apply final processing
            self.post_init()

        def forward(
            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,
            labels: Tensor | None = None,
            output_attentions: bool | None = None,
            output_hidden_states: bool | None = None,
            return_dict: bool | None = None,
            **kwargs,
        ) -> Tuple[Tensor, ...] | ContactPredictorOutput:
            if output_attentions is False:
                warn("output_attentions must be True for contact classification and will be ignored.")
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
            outputs = self.rnafm(
                input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                output_attentions=True,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                **kwargs,
            )
            output = self.contact_head(outputs, attention_mask, input_ids, labels)
            logits, loss = output.logits, output.loss

            if not return_dict:
                output = (logits,) + outputs[2:]
                return ((loss,) + output) if loss is not None else output

            return ContactPredictorOutput(
                loss=loss,
                logits=logits,
                hidden_states=outputs.hidden_states,
                attentions=outputs.attentions,
            )

### `` RnaFmForMaskedLM

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> 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, 26])
    >>> output["loss"]
    tensor(..., grad_fn=<NllLossBackward0>)

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    class RnaFmForMaskedLM(RnaFmPreTrainedModel):
        """
        Examples:
            >>> 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, 26])
            >>> output["loss"]  # doctest:+ELLIPSIS
            tensor(..., grad_fn=<NllLossBackward0>)
        """

        _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]

        def __init__(self, config: RnaFmConfig):
            super().__init__(config)
            if config.is_decoder:
                logger.warning(
                    "If you want to use `RnaFmForMaskedLM` make sure `config.is_decoder=False` for "
                    "bi-directional self-attention."
                )
            self.rnafm = RnaFmModel(config, add_pooling_layer=False)
            self.lm_head = MaskedLMHead(config)

            # Initialize weights and apply final processing
            self.post_init()

        def forward(
            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,
            labels: Tensor | None = None,
            output_attentions: bool | None = None,
            output_hidden_states: bool | None = None,
            return_dict: bool | None = None,
            **kwargs,
        ) -> Tuple[Tensor, ...] | MaskedLMOutput:
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
            outputs = self.rnafm(
                input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                encoder_hidden_states=encoder_hidden_states,
                encoder_attention_mask=encoder_attention_mask,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                **kwargs,
            )
            output = self.lm_head(outputs, labels)
            logits, loss = output.logits, output.loss

            if not return_dict:
                output = (logits,) + outputs[2:]
                return ((loss,) + output) if loss is not None else output

            return MaskedLMOutput(
                loss=loss,
                logits=logits,
                hidden_states=outputs.hidden_states,
                attentions=outputs.attentions,
            )

### `` RnaFmForNucleotidePrediction

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> from multimolecule import RnaFmConfig, RnaFmForNucleotidePrediction, RnaTokenizer
    >>> config = RnaFmConfig()
    >>> model = RnaFmForNucleotidePrediction(config)
    >>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
    >>> input = tokenizer("ACGUN", return_tensors="pt")
    >>> output = model(**input, labels=torch.randn(1, 5, 2))
    >>> output["logits"].shape
    torch.Size([1, 5, 2])
    >>> output["loss"]
    tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    class RnaFmForNucleotidePrediction(RnaFmPreTrainedModel):
        """
        Examples:
            >>> from multimolecule import RnaFmConfig, RnaFmForNucleotidePrediction, RnaTokenizer
            >>> config = RnaFmConfig()
            >>> model = RnaFmForNucleotidePrediction(config)
            >>> tokenizer = RnaTokenizer.from_pretrained("multimolecule/rna")
            >>> input = tokenizer("ACGUN", return_tensors="pt")
            >>> output = model(**input, labels=torch.randn(1, 5, 2))
            >>> output["logits"].shape
            torch.Size([1, 5, 2])
            >>> output["loss"]  # doctest:+ELLIPSIS
            tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
        """

        def __init__(self, config: RnaFmConfig):
            super().__init__(config)
            self.rnafm = RnaFmModel(config, add_pooling_layer=True)
            self.nucleotide_head = NucleotidePredictionHead(config)
            self.head_config = self.nucleotide_head.config

            # Initialize weights and apply final processing
            self.post_init()

        def forward(
            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,
            labels: Tensor | None = None,
            output_attentions: bool | None = None,
            output_hidden_states: bool | None = None,
            return_dict: bool | None = None,
            **kwargs,
        ) -> Tuple[Tensor, ...] | NucleotidePredictorOutput:
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
            outputs = self.rnafm(
                input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                **kwargs,
            )
            output = self.nucleotide_head(outputs, attention_mask, input_ids, labels)
            logits, loss = output.logits, output.loss

            if not return_dict:
                output = (logits,) + outputs[2:]
                return ((loss,) + output) if loss is not None else output

            return NucleotidePredictorOutput(
                loss=loss,
                logits=logits,
                hidden_states=outputs.hidden_states,
                attentions=outputs.attentions,
            )

### `` RnaFmForPreTraining

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> 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_mlm=input["input_ids"])
    >>> output["loss"]
    tensor(..., grad_fn=<AddBackward0>)
    >>> output["logits"].shape
    torch.Size([1, 7, 26])
    >>> output["contact_map"].shape
    torch.Size([1, 5, 5, 2])

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    class RnaFmForPreTraining(RnaFmPreTrainedModel):
        """
        Examples:
            >>> 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_mlm=input["input_ids"])
            >>> output["loss"]  # doctest:+ELLIPSIS
            tensor(..., grad_fn=<AddBackward0>)
            >>> output["logits"].shape
            torch.Size([1, 7, 26])
            >>> output["contact_map"].shape
            torch.Size([1, 5, 5, 2])
        """

        _tied_weights_keys = [
            "lm_head.decoder.weight",
            "lm_head.decoder.bias",
            "pretrain.predictions.decoder.weight",
            "pretrain.predictions.decoder.bias",
            "pretrain.predictions_ss.decoder.weight",
            "pretrain.predictions_ss.decoder.bias",
        ]

        def __init__(self, config: RnaFmConfig):
            super().__init__(config)
            if config.is_decoder:
                logger.warning(
                    "If you want to use `RnaFmForPreTraining` make sure `config.is_decoder=False` for "
                    "bi-directional self-attention."
                )
            self.rnafm = RnaFmModel(config, add_pooling_layer=False)
            self.pretrain = RnaFmPreTrainingHeads(config)

            # Initialize weights and apply final processing
            self.post_init()

        def get_output_embeddings(self):
            return self.pretrain.predictions.decoder

        def set_output_embeddings(self, embeddings):
            self.pretrain.predictions.decoder = embeddings

        def forward(
            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,
            labels_mlm: Tensor | None = None,
            labels_contact: Tensor | None = None,
            output_attentions: bool | None = None,
            output_hidden_states: bool | None = None,
            return_dict: bool | None = None,
            **kwargs,
        ) -> Tuple[Tensor, ...] | RnaFmForPreTrainingOutput:
            if output_attentions is False:
                warn("output_attentions must be True for contact classification and will be ignored.")
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
            outputs = self.rnafm(
                input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                encoder_hidden_states=encoder_hidden_states,
                encoder_attention_mask=encoder_attention_mask,
                output_attentions=True,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                **kwargs,
            )
            total_loss, logits, contact_map = self.pretrain(
                outputs, attention_mask, input_ids, labels_mlm=labels_mlm, labels_contact=labels_contact
            )

            if not return_dict:
                output = (logits,) + outputs[2:]
                return ((total_loss,) + output) if total_loss is not None else output

            return RnaFmForPreTrainingOutput(
                loss=total_loss,
                logits=logits,
                contact_map=contact_map,
                hidden_states=outputs.hidden_states,
                attentions=outputs.attentions,
            )

### `` RnaFmForSequencePrediction

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> 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, 2])
    >>> output["loss"]
    tensor(..., grad_fn=<NllLossBackward0>)

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    class RnaFmForSequencePrediction(RnaFmPreTrainedModel):
        """
        Examples:
            >>> 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, 2])
            >>> output["loss"]  # doctest:+ELLIPSIS
            tensor(..., grad_fn=<NllLossBackward0>)
        """

        def __init__(self, config: RnaFmConfig):
            super().__init__(config)
            self.rnafm = RnaFmModel(config, add_pooling_layer=True)
            self.sequence_head = SequencePredictionHead(config)
            self.head_config = self.sequence_head.config

            # Initialize weights and apply final processing
            self.post_init()

        def forward(
            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,
            labels: Tensor | None = None,
            output_attentions: bool | None = None,
            output_hidden_states: bool | None = None,
            return_dict: bool | None = None,
            **kwargs,
        ) -> Tuple[Tensor, ...] | SequencePredictorOutput:
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
            outputs = self.rnafm(
                input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                **kwargs,
            )
            output = self.sequence_head(outputs, labels)
            logits, loss = output.logits, output.loss

            if not return_dict:
                output = (logits,) + outputs[2:]
                return ((loss,) + output) if loss is not None else output

            return SequencePredictorOutput(
                loss=loss,
                logits=logits,
                hidden_states=outputs.hidden_states,
                attentions=outputs.attentions,
            )

### `` RnaFmForTokenPrediction

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> 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, 7)))
    >>> output["logits"].shape
    torch.Size([1, 7, 2])
    >>> output["loss"]
    tensor(..., grad_fn=<NllLossBackward0>)

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    class RnaFmForTokenPrediction(RnaFmPreTrainedModel):
        """
        Examples:
            >>> 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, 7)))
            >>> output["logits"].shape
            torch.Size([1, 7, 2])
            >>> output["loss"]  # doctest:+ELLIPSIS
            tensor(..., grad_fn=<NllLossBackward0>)
        """

        def __init__(self, config: RnaFmConfig):
            super().__init__(config)
            self.rnafm = RnaFmModel(config, add_pooling_layer=True)
            self.token_head = TokenPredictionHead(config)
            self.head_config = self.token_head.config

            # Initialize weights and apply final processing
            self.post_init()

        def forward(
            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,
            labels: Tensor | None = None,
            output_attentions: bool | None = None,
            output_hidden_states: bool | None = None,
            return_dict: bool | None = None,
            **kwargs,
        ) -> Tuple[Tensor, ...] | TokenPredictorOutput:
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
            outputs = self.rnafm(
                input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                **kwargs,
            )
            output = self.token_head(outputs, attention_mask, input_ids, labels)
            logits, loss = output.logits, output.loss

            if not return_dict:
                output = (logits,) + outputs[2:]
                return ((loss,) + output) if loss is not None else output

            return TokenPredictorOutput(
                loss=loss,
                logits=logits,
                hidden_states=outputs.hidden_states,
                attentions=outputs.attentions,
            )

### `` RnaFmModel

Bases: `RnaFmPreTrainedModel`

Examples:

Python Console Session

    >>> 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
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    class RnaFmModel(RnaFmPreTrainedModel):
        """
        Examples:
            >>> 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

        def _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
            """
            for layer, heads in heads_to_prune.items():
                self.encoder.layer[layer].attention.prune_heads(heads)

        def forward(
            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[torch.FloatTensor, torch.FloatTensor], ...] | 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"""
            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`).
            """
            if kwargs:
                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_attentions if output_attentions is not None else self.config.output_attentions
            output_hidden_states = (
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict

            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 isinstance(input_ids, NestedTensor):
                input_ids, attention_mask = input_ids.tensor, input_ids.mask
            if input_ids is not None and inputs_embeds is not None:
                raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
            if input_ids is not None:
                self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
                input_shape = input_ids.size()
            elif inputs_embeds is not None:
                input_shape = inputs_embeds.size()[:-1]
            else:
                raise ValueError("You have to specify either input_ids or inputs_embeds")

            batch_size, seq_length = input_shape
            device = input_ids.device if input_ids is not None else inputs_embeds.device  # type: ignore[union-attr]

            # past_key_values_length
            past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0

            if attention_mask is None:
                attention_mask = (
                    input_ids.ne(self.pad_token_id)
                    if self.pad_token_id is not None
                    else torch.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]
            if self.config.is_decoder and encoder_hidden_states is not None:
                encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
                encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
                if encoder_attention_mask is None:
                    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,
                attention_mask=attention_mask,
                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) if self.pooler is not None else None

            if not return_dict:
                return (sequence_output, pooled_output) + encoder_outputs[1:]

            return BaseModelOutputWithPoolingAndCrossAttentions(
                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,
            )

#### `` forward

Python
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    forward(
        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[FloatTensor, FloatTensor], ...] | 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
    )

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]`:

Text Only
    1
    2
    - 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.

Text Only
    1
    2
    3
    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`).

Source code in `multimolecule/models/rnafm/modeling_rnafm.py`

Python
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    def forward(
        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[torch.FloatTensor, torch.FloatTensor], ...] | 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"""
        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`).
        """
        if kwargs:
            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_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        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 isinstance(input_ids, NestedTensor):
            input_ids, attention_mask = input_ids.tensor, input_ids.mask
        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
        if input_ids is not None:
            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
            input_shape = input_ids.size()
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.size()[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        batch_size, seq_length = input_shape
        device = input_ids.device if input_ids is not None else inputs_embeds.device  # type: ignore[union-attr]

        # past_key_values_length
        past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0

        if attention_mask is None:
            attention_mask = (
                input_ids.ne(self.pad_token_id)
                if self.pad_token_id is not None
                else torch.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]
        if self.config.is_decoder and encoder_hidden_states is not None:
            encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
            encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
            if encoder_attention_mask is None:
                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,
            attention_mask=attention_mask,
            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) if self.pooler is not None else None

        if not return_dict:
            return (sequence_output, pooled_output) + encoder_outputs[1:]

        return BaseModelOutputWithPoolingAndCrossAttentions(
            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,
        )

### `` 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
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    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 = "rnafm"
        supports_gradient_checkpointing = True
        _no_split_modules = ["RnaFmLayer", "RnaFmEmbeddings"]

        # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
        def _init_weights(self, module: nn.Module):
            """Initialize the weights"""
            if isinstance(module, nn.Linear):
                # Slightly different from the TF version which uses truncated_normal for initialization
                # cf https://github.com/pytorch/pytorch/pull/5617
                module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
                if module.bias is not None:
                    module.bias.data.zero_()
            elif isinstance(module, nn.Embedding):
                module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
                if module.padding_idx is not None:
                    module.weight.data[module.padding_idx].zero_()
            elif isinstance(module, nn.LayerNorm):
                module.bias.data.zero_()
                module.weight.data.fill_(1.0)

2024-07-10 01:11:47

#### Cookie Consent

We use cookies to recognize your repeated visits and preferences, as well as to measure the effectiveness of our documentation and whether users find what they're searching for. With your consent, you're helping us to make our documentation better. Please check out our Privacy Notice for more information.

- Google Analytics
- GitHub

管理设定