Skip to content

AMPLIFY

AMPLIFY

Pre-trained model on protein sequences using a masked language modeling (MLM) objective.

Disclaimer

This is an UNOFFICIAL implementation of the Protein Language Models: Is Scaling Necessary? by Quentin Fournier, Robert M. Vernon, Almer van der Sloot, Benjamin Schulz, Sarath Chandar, and Christopher James Langmead.

The OFFICIAL repository of AMPLIFY is at chandar-lab/AMPLIFY.

Tip

The MultiMolecule team has confirmed that the provided model and checkpoints match the original implementation’s logits and attention maps within 1e-4 absolute tolerance on representative protein sequences.

The team releasing AMPLIFY did not write this model card for this model so this model card has been written by the MultiMolecule team.

Model Details

AMPLIFY is a modern encoder-only protein language model with RMSNorm, SwiGLU, and rotary position embeddings. It is pre-trained on UR100P, a corpus derived from UniRef100 and supplemented with paired sequences from the Observed Antibody Space and domains from SCOP, using a masked language modeling objective. 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
AMPLIFY-120M 24 640 10 2560 118.67 137.34 68.58 2048
AMPLIFY-350M 32 960 15 3840 354.91 394.98 197.30

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
1
2
3
4
5
import multimolecule  # you must import multimolecule to register models
from transformers import pipeline

predictor = pipeline("fill-mask", model="multimolecule/amplify-120m")
output = predictor("MVLSPADKTNVKAAW<mask>KVGAHAGEYGAEALER")

Downstream Use

Extract Features

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

Python
from multimolecule import ProteinTokenizer, AmplifyModel


tokenizer = ProteinTokenizer.from_pretrained("multimolecule/amplify-120m")
model = AmplifyModel.from_pretrained("multimolecule/amplify-120m")

text = "MVLSPADKTNVKAAWGKVGAHAGEYGAEALER"
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 ProteinTokenizer, AmplifyForSequencePrediction


tokenizer = ProteinTokenizer.from_pretrained("multimolecule/amplify-120m")
model = AmplifyForSequencePrediction.from_pretrained("multimolecule/amplify-120m")

text = "MVLSPADKTNVKAAWGKVGAHAGEYGAEALER"
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 residue-level task in PyTorch:

Python
import torch
from multimolecule import ProteinTokenizer, AmplifyForTokenPrediction


tokenizer = ProteinTokenizer.from_pretrained("multimolecule/amplify-120m")
model = AmplifyForTokenPrediction.from_pretrained("multimolecule/amplify-120m")

text = "MVLSPADKTNVKAAWGKVGAHAGEYGAEALER"
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
import torch
from multimolecule import ProteinTokenizer, AmplifyForContactPrediction


tokenizer = ProteinTokenizer.from_pretrained("multimolecule/amplify-120m")
model = AmplifyForContactPrediction.from_pretrained("multimolecule/amplify-120m")

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

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

Training Details

AMPLIFY was trained with Masked Language Modeling (MLM) as the pre-training objective: 15% of the residues in the input are randomly selected as prediction targets, and the model is asked to recover the original amino acids from the surrounding context. The model is bidirectional (encoder-only) so the prediction at each masked position attends to the entire sequence.

Training Data

AMPLIFY was pre-trained on the UR100P dataset, which is a curated union of:

  • UniRef100: All UniProt sequences clustered at 100% sequence identity.
  • Observed Antibody Space (OAS): Paired antibody repertoire sequences, represented with heavy and light chains separated by the | chain separator.
  • SCOP: Structurally classified protein domains.

Training Procedure

Preprocessing

AMPLIFY uses masked language modeling (MLM) as the pre-training objective. The masking procedure is similar to the one used in BERT:

  • 15% of the residues are masked.
  • In 80% of the cases, the masked residues are replaced by <mask>.
  • In 10% of the cases, the masked residues are replaced by a random residue (different) from the one they replace.
  • In the 10% remaining cases, the masked residues are left as is.

Pre-training

Training is performed in two stages, both on the UR100P dataset:

  • Stage 1: trained for 1,000,000 steps at a maximum length of 512 residues with a peak learning rate of 1e-3, cosine-decayed to 1e-4.
  • Stage 2: trained for an additional 25,000 (120M) or 50,000 (350M) steps at a maximum length of 2,048 residues with a constant learning rate of 1e-4.

Both stages use AdamW with betas (0.9, 0.95), weight decay 0.01, gradient clipping 1.0, mixed-precision bf16 with tf32, a total batch size of 4,096 sequences, and DeepSpeed ZeRO stage 3.

Citation

BibTeX
1
2
3
4
5
6
7
8
9
@article{Fournier2024.09.23.614603,
  title     = {Protein Language Models: Is Scaling Necessary?},
  author    = {Fournier, Quentin and Vernon, Robert M. and van der Sloot, Almer and Schulz, Benjamin and Chandar, Sarath and Langmead, Christopher James},
  year      = {2024},
  journal   = {bioRxiv},
  publisher = {Cold Spring Harbor Laboratory},
  doi       = {10.1101/2024.09.23.614603},
  url       = {https://www.biorxiv.org/content/early/2024/09/23/2024.09.23.614603},
}

Note

The artifacts distributed in this repository are part of the MultiMolecule project. If you use MultiMolecule in your research, you must 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
}

Contact

Please use GitHub issues of MultiMolecule for any questions or comments on the model card.

Please contact the authors of the AMPLIFY 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

multimolecule.models.amplify

ProteinTokenizer

Bases: Tokenizer

Tokenizer for Protein 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
  • If is an alphabet or a list of characters, that specific alphabet will be used.
None

do_upper_case

bool

Whether to convert input to uppercase.

True

Examples:

Python Console Session
1
2
3
4
5
6
7
8
>>> from multimolecule import ProteinTokenizer
>>> tokenizer = ProteinTokenizer()
>>> tokenizer('ACDEFGHIKLMNPQRSTVWYXZBJUO')["input_ids"]
[1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 2]
>>> tokenizer('<pad><cls><eos><unk><mask><null>|.*-?')["input_ids"]
[1, 0, 1, 2, 3, 4, 5, 32, 33, 34, 35, 36, 2]
>>> tokenizer('manlgcwmlv')["input_ids"]
[1, 16, 6, 17, 15, 11, 7, 24, 16, 15, 23, 2]
Source code in multimolecule/tokenisers/protein/tokenization_protein.py
Python
class ProteinTokenizer(Tokenizer):
    """
    Tokenizer for Protein 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`
            - If is an alphabet or a list of characters, that specific alphabet will be used.
        do_upper_case: Whether to convert input to uppercase.

    Examples:
        >>> from multimolecule import ProteinTokenizer
        >>> tokenizer = ProteinTokenizer()
        >>> tokenizer('ACDEFGHIKLMNPQRSTVWYXZBJUO')["input_ids"]
        [1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 2]
        >>> tokenizer('<pad><cls><eos><unk><mask><null>|.*-?')["input_ids"]
        [1, 0, 1, 2, 3, 4, 5, 32, 33, 34, 35, 36, 2]
        >>> tokenizer('manlgcwmlv')["input_ids"]
        [1, 16, 6, 17, 15, 11, 7, 24, 16, 15, 23, 2]
    """

    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        alphabet: Alphabet | str | List[str] | None = None,
        do_upper_case: bool = True,
        additional_special_tokens: List | Tuple | None = None,
        **kwargs,
    ):
        if not isinstance(alphabet, Alphabet):
            alphabet = get_alphabet(alphabet)
        super().__init__(
            alphabet=alphabet,
            additional_special_tokens=additional_special_tokens,
            do_upper_case=do_upper_case,
            **kwargs,
        )

    def _tokenize(self, text: str, **kwargs):
        if self.do_upper_case:
            text = text.upper()
        return list(text)

AmplifyConfig

Bases: PreTrainedConfig

This is the configuration class to store the configuration of a AmplifyModel. It is used to instantiate an AMPLIFY 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 AMPLIFY chandar-lab/AMPLIFY_120M 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

Vocabulary size of the AMPLIFY model. Defines the number of different tokens that can be represented by the input_ids passed when calling [AmplifyModel].

37

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.

24

num_attention_heads

int

Number of attention heads for each attention layer in the Transformer encoder.

10

intermediate_size

int

Dimensionality of the “intermediate” (often named feed-forward) layer in the Transformer encoder.

2560

hidden_act

str

The non-linear activation function used in the feed-forward layer. AMPLIFY uses "swiglu".

'swiglu'

hidden_dropout

float

The dropout probability applied to residual connections and feed-forward outputs.

0.0

attention_dropout

float

The dropout ratio applied to attention probabilities.

0.0

max_position_embeddings

int

The maximum sequence length that this model might ever be used with. Used to precompute rotary frequencies.

2048

initializer_range

float

The standard deviation (or half-range, for uniform init) of the initializer for initializing all weight matrices.

0.02

layer_norm_eps

float

The epsilon used by the RMSNorm/LayerNorm layers.

1e-05

rms_norm

bool

Whether to use RMSNorm instead of LayerNorm.

True

layer_norm_after_embedding

bool

Whether to apply a normalization layer right after the token embedding.

False

layer_norm_before_last_layer

bool

Whether to apply a normalization layer before the output projection.

True

attention_bias

bool

Whether to use bias terms in the attention projections.

False

feedforward_bias

bool

Whether to use bias terms in the feed-forward projections.

False

head

HeadConfig | None

The configuration of the head.

None

lm_head

MaskedLMHeadConfig | None

The configuration of the masked language model head.

None

Examples:

Python Console Session
1
2
3
4
5
6
7
>>> from multimolecule import AmplifyConfig, AmplifyModel
>>> # Initializing an AMPLIFY 120M style configuration
>>> configuration = AmplifyConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = AmplifyModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in multimolecule/models/amplify/configuration_amplify.py
Python
class AmplifyConfig(PreTrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`AmplifyModel`][multimolecule.models.AmplifyModel].
    It is used to instantiate an AMPLIFY 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 AMPLIFY
    [chandar-lab/AMPLIFY_120M](https://huggingface.co/chandar-lab/AMPLIFY_120M) 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 AMPLIFY model. Defines the number of different tokens that can be represented by the
            `input_ids` passed when calling [`AmplifyModel`].
        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 used in the feed-forward layer. AMPLIFY uses `"swiglu"`.
        hidden_dropout:
            The dropout probability applied to residual connections and feed-forward outputs.
        attention_dropout:
            The dropout ratio applied to attention probabilities.
        max_position_embeddings:
            The maximum sequence length that this model might ever be used with. Used to precompute rotary
            frequencies.
        initializer_range:
            The standard deviation (or half-range, for uniform init) of the initializer for initializing all
            weight matrices.
        layer_norm_eps:
            The epsilon used by the RMSNorm/LayerNorm layers.
        rms_norm:
            Whether to use RMSNorm instead of LayerNorm.
        layer_norm_after_embedding:
            Whether to apply a normalization layer right after the token embedding.
        layer_norm_before_last_layer:
            Whether to apply a normalization layer before the output projection.
        attention_bias:
            Whether to use bias terms in the attention projections.
        feedforward_bias:
            Whether to use bias terms in the feed-forward projections.
        head:
            The configuration of the head.
        lm_head:
            The configuration of the masked language model head.

    Examples:
        >>> from multimolecule import AmplifyConfig, AmplifyModel
        >>> # Initializing an AMPLIFY 120M style configuration
        >>> configuration = AmplifyConfig()
        >>> # Initializing a model (with random weights) from the configuration
        >>> model = AmplifyModel(configuration)
        >>> # Accessing the model configuration
        >>> configuration = model.config
    """

    model_type = "amplify"

    def __init__(
        self,
        vocab_size: int = 37,
        hidden_size: int = 640,
        num_hidden_layers: int = 24,
        num_attention_heads: int = 10,
        intermediate_size: int = 2560,
        hidden_act: str = "swiglu",
        hidden_dropout: float = 0.0,
        attention_dropout: float = 0.0,
        max_position_embeddings: int = 2048,
        initializer_range: float = 0.02,
        layer_norm_eps: float = 1.0e-5,
        rms_norm: bool = True,
        layer_norm_after_embedding: bool = False,
        layer_norm_before_last_layer: bool = True,
        attention_bias: bool = False,
        feedforward_bias: bool = False,
        pad_token_id: int = 0,
        bos_token_id: int = 1,
        eos_token_id: int = 2,
        unk_token_id: int = 3,
        mask_token_id: int = 4,
        null_token_id: int = 5,
        head: HeadConfig | None = None,
        lm_head: MaskedLMHeadConfig | None = None,
        **kwargs,
    ):
        # AMPLIFY stores ``encoder.weight`` and ``decoder.weight`` as separate
        # parameters; weight tying must remain disabled to preserve checkpoint
        # behaviour.
        kwargs.setdefault("tie_word_embeddings", False)
        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            unk_token_id=unk_token_id,
            mask_token_id=mask_token_id,
            null_token_id=null_token_id,
            **kwargs,
        )
        validate_attention_dimensions(hidden_size, num_attention_heads)
        if (hidden_size // num_attention_heads) % 2 != 0:
            raise ValueError(
                "Rotary embeddings require an even head dimension; got "
                f"hidden_size={hidden_size}, num_attention_heads={num_attention_heads}."
            )
        hidden_act = hidden_act.lower()
        if hidden_act != "swiglu":
            raise ValueError(f"AMPLIFY only supports hidden_act='swiglu'; got {hidden_act!r}.")
        self.vocab_size = vocab_size
        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.rms_norm = rms_norm
        self.layer_norm_after_embedding = layer_norm_after_embedding
        self.layer_norm_before_last_layer = layer_norm_before_last_layer
        self.attention_bias = attention_bias
        self.feedforward_bias = feedforward_bias
        self.head = HeadConfig(**head) if head is not None else None
        # AMPLIFY's LM head is a single ``Linear`` with bias; no projection/norm
        # transform sits between the encoder output and the decoder.
        self.lm_head = (
            MaskedLMHeadConfig(**lm_head)
            if lm_head is not None
            else MaskedLMHeadConfig(transform=None, transform_act=None, bias=True)
        )

AmplifyForContactPrediction

Bases: AmplifyPreTrainedModel

Examples:

Python Console Session
>>> import torch
>>> from multimolecule import AmplifyConfig, AmplifyForContactPrediction, ProteinTokenizer
>>> config = AmplifyConfig()
>>> model = AmplifyForContactPrediction(config)
>>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
>>> input = tokenizer("MVLSPADKT", return_tensors="pt")
>>> output = model(**input, labels=torch.randint(2, (1, 9, 9)))
>>> output["logits"].shape
torch.Size([1, 9, 9, 1])
>>> output["loss"]
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
Source code in multimolecule/models/amplify/modeling_amplify.py
Python
class AmplifyForContactPrediction(AmplifyPreTrainedModel):
    """
    Examples:
        >>> import torch
        >>> from multimolecule import AmplifyConfig, AmplifyForContactPrediction, ProteinTokenizer
        >>> config = AmplifyConfig()
        >>> model = AmplifyForContactPrediction(config)
        >>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
        >>> input = tokenizer("MVLSPADKT", return_tensors="pt")
        >>> output = model(**input, labels=torch.randint(2, (1, 9, 9)))
        >>> output["logits"].shape
        torch.Size([1, 9, 9, 1])
        >>> output["loss"]  # doctest:+ELLIPSIS
        tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
    """

    def __init__(self, config: AmplifyConfig):
        super().__init__(config)
        self.model = AmplifyModel(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,
        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,
            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,
        )

AmplifyForMaskedLM

Bases: AmplifyPreTrainedModel

Examples:

Python Console Session
>>> import torch
>>> from multimolecule import AmplifyConfig, AmplifyForMaskedLM, ProteinTokenizer
>>> config = AmplifyConfig()
>>> model = AmplifyForMaskedLM(config)
>>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
>>> input = tokenizer("MVLSPADKT", return_tensors="pt")
>>> output = model(**input, labels=input["input_ids"])
>>> output["logits"].shape
torch.Size([1, 11, 37])
>>> output["loss"]
tensor(..., grad_fn=<NllLossBackward0>)
Source code in multimolecule/models/amplify/modeling_amplify.py
Python
class AmplifyForMaskedLM(AmplifyPreTrainedModel):
    """
    Examples:
        >>> import torch
        >>> from multimolecule import AmplifyConfig, AmplifyForMaskedLM, ProteinTokenizer
        >>> config = AmplifyConfig()
        >>> model = AmplifyForMaskedLM(config)
        >>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
        >>> input = tokenizer("MVLSPADKT", return_tensors="pt")
        >>> output = model(**input, labels=input["input_ids"])
        >>> output["logits"].shape
        torch.Size([1, 11, 37])
        >>> output["loss"]  # doctest:+ELLIPSIS
        tensor(..., grad_fn=<NllLossBackward0>)
    """

    # AMPLIFY does NOT tie the input/output embeddings: ``encoder.weight`` and
    # ``decoder.weight`` are independently learned in the upstream checkpoint.
    _tied_weights_keys = {
        "lm_head.decoder.bias": "lm_head.bias",
    }

    def get_expanded_tied_weights_keys(self, all_submodels: bool = False) -> dict:
        tied_weights = super().get_expanded_tied_weights_keys(all_submodels=all_submodels)
        if all_submodels:
            return tied_weights
        return tied_weights | self._tied_weights_keys

    def __init__(self, config: AmplifyConfig):
        super().__init__(config)
        self.model = AmplifyModel(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,
        inputs_embeds: Tensor | NestedTensor | None = None,
        labels: Tensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> Tuple[Tensor, ...] | MaskedLMOutput:
        outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            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,
        )

AmplifyForSequencePrediction

Bases: AmplifyPreTrainedModel

Examples:

Python Console Session
>>> import torch
>>> from multimolecule import AmplifyConfig, AmplifyForSequencePrediction, ProteinTokenizer
>>> config = AmplifyConfig()
>>> model = AmplifyForSequencePrediction(config)
>>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
>>> input = tokenizer("MVLSPADKT", 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/amplify/modeling_amplify.py
Python
class AmplifyForSequencePrediction(AmplifyPreTrainedModel):
    """
    Examples:
        >>> import torch
        >>> from multimolecule import AmplifyConfig, AmplifyForSequencePrediction, ProteinTokenizer
        >>> config = AmplifyConfig()
        >>> model = AmplifyForSequencePrediction(config)
        >>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
        >>> input = tokenizer("MVLSPADKT", 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: AmplifyConfig):
        super().__init__(config)
        self.model = AmplifyModel(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,
        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,
            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,
        )

AmplifyForTokenPrediction

Bases: AmplifyPreTrainedModel

Examples:

Python Console Session
>>> import torch
>>> from multimolecule import AmplifyConfig, AmplifyForTokenPrediction, ProteinTokenizer
>>> config = AmplifyConfig()
>>> model = AmplifyForTokenPrediction(config)
>>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
>>> input = tokenizer("MVLSPADKT", return_tensors="pt")
>>> output = model(**input, labels=torch.randint(2, (1, 9)))
>>> output["logits"].shape
torch.Size([1, 9, 1])
>>> output["loss"]
tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
Source code in multimolecule/models/amplify/modeling_amplify.py
Python
class AmplifyForTokenPrediction(AmplifyPreTrainedModel):
    """
    Examples:
        >>> import torch
        >>> from multimolecule import AmplifyConfig, AmplifyForTokenPrediction, ProteinTokenizer
        >>> config = AmplifyConfig()
        >>> model = AmplifyForTokenPrediction(config)
        >>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
        >>> input = tokenizer("MVLSPADKT", return_tensors="pt")
        >>> output = model(**input, labels=torch.randint(2, (1, 9)))
        >>> output["logits"].shape
        torch.Size([1, 9, 1])
        >>> output["loss"]  # doctest:+ELLIPSIS
        tensor(..., grad_fn=<BinaryCrossEntropyWithLogitsBackward0>)
    """

    def __init__(self, config: AmplifyConfig):
        super().__init__(config)
        self.model = AmplifyModel(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,
        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,
            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,
        )

AmplifyModel

Bases: AmplifyPreTrainedModel

Examples:

Python Console Session
>>> import torch
>>> from multimolecule import AmplifyConfig, AmplifyModel, ProteinTokenizer
>>> config = AmplifyConfig()
>>> model = AmplifyModel(config)
>>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
>>> input = tokenizer("MVLSPADKT", return_tensors="pt")
>>> output = model(**input)
>>> output["last_hidden_state"].shape
torch.Size([1, 11, 640])
>>> output["pooler_output"].shape
torch.Size([1, 640])
Source code in multimolecule/models/amplify/modeling_amplify.py
Python
class AmplifyModel(AmplifyPreTrainedModel):
    """
    Examples:
        >>> import torch
        >>> from multimolecule import AmplifyConfig, AmplifyModel, ProteinTokenizer
        >>> config = AmplifyConfig()
        >>> model = AmplifyModel(config)
        >>> tokenizer = ProteinTokenizer.from_pretrained("multimolecule/protein")
        >>> input = tokenizer("MVLSPADKT", return_tensors="pt")
        >>> output = model(**input)
        >>> output["last_hidden_state"].shape
        torch.Size([1, 11, 640])
        >>> output["pooler_output"].shape
        torch.Size([1, 640])
    """

    def __init__(self, config: AmplifyConfig, add_pooling_layer: bool = True):
        super().__init__(config)
        self.pad_token_id = config.pad_token_id
        self.gradient_checkpointing = False
        self.embeddings = AmplifyEmbeddings(config)
        self.encoder = AmplifyEncoder(config)
        self.pooler = AmplifyPooler(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,
        inputs_embeds: Tensor | NestedTensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> Tuple[Tensor, ...] | BaseModelOutputWithPoolingAndCrossAttentions:
        if isinstance(input_ids, NestedTensor) and attention_mask is None:
            attention_mask = input_ids.mask
        if isinstance(inputs_embeds, NestedTensor) and attention_mask is None:
            attention_mask = inputs_embeds.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 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, inputs_embeds=inputs_embeds)

        attn_mask = create_bidirectional_mask(
            config=self.config, inputs_embeds=embedding_output, attention_mask=attention_mask
        )

        encoder_outputs = self.encoder(embedding_output, attention_mask=attn_mask, **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,
        )

AmplifyPreTrainedModel

Bases: PreTrainedModel

An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.

Source code in multimolecule/models/amplify/modeling_amplify.py
Python
class AmplifyPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """

    config_class = AmplifyConfig
    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 = ["AmplifyLayer"]

    @torch.no_grad()
    def _init_weights(self, module: nn.Module):
        # AMPLIFY uses uniform initialization for both embeddings and linears, scaled by ``initializer_range``.
        # Falling through to the parent ``_init_weights`` would apply normal-distribution init instead.
        std = self.config.initializer_range
        if isinstance(module, nn.Linear):
            init.uniform_(module.weight, -std, std)
            if module.bias is not None:
                init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            init.uniform_(module.weight, -std, std)
            if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
                init.zeros_(module.weight[module.padding_idx])
        elif "RMSNorm" in module.__class__.__name__ or "LayerNorm" in module.__class__.__name__:
            if getattr(module, "weight", None) is not None:
                init.ones_(module.weight)
            if getattr(module, "bias", None) is not None:
                init.zeros_(module.bias)