跳转至

esm

mindnlp.transformers.models.esm.configuration_esm

ESM model configuration

mindnlp.transformers.models.esm.configuration_esm.EsmConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [ESMModel]. It is used to instantiate a ESM 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 ESM facebook/esm-1b architecture.

Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the documentation from [PretrainedConfig] for more information.

PARAMETER DESCRIPTION
vocab_size

Vocabulary size of the ESM model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [ESMModel].

TYPE: `int`, *optional* DEFAULT: None

mask_token_id

The index of the mask token in the vocabulary. This must be included in the config because of the "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.

TYPE: `int`, *optional* DEFAULT: None

pad_token_id

The index of the padding token in the vocabulary. This must be included in the config because certain parts of the ESM code use this instead of the attention mask.

TYPE: `int`, *optional* DEFAULT: None

hidden_size

Dimensionality of the encoder layers and the pooler layer.

TYPE: `int`, *optional*, defaults to 768 DEFAULT: 768

num_hidden_layers

Number of hidden layers in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 12 DEFAULT: 12

num_attention_heads

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

TYPE: `int`, *optional*, defaults to 12 DEFAULT: 12

intermediate_size

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

TYPE: `int`, *optional*, defaults to 3072 DEFAULT: 3072

hidden_dropout_prob

The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.

TYPE: `float`, *optional*, defaults to 0.1 DEFAULT: 0.1

attention_probs_dropout_prob

The dropout ratio for the attention probabilities.

TYPE: `float`, *optional*, defaults to 0.1 DEFAULT: 0.1

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

TYPE: `int`, *optional*, defaults to 1026 DEFAULT: 1026

initializer_range

The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

TYPE: `float`, *optional*, defaults to 0.02 DEFAULT: 0.02

layer_norm_eps

The epsilon used by the layer normalization layers.

TYPE: `float`, *optional*, defaults to 1e-12 DEFAULT: 1e-12

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.). For more information on "relative_key_query", please refer to Method 4 in Improve Transformer Models with Better Relative Position Embeddings (Huang et al.).

TYPE: `str`, *optional*, defaults to `"absolute"` DEFAULT: 'absolute'

is_decoder

Whether the model is used as a decoder or not. If False, the model is used as an encoder.

TYPE: `bool`, *optional*, defaults to `False`

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.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

emb_layer_norm_before

Whether to apply layer normalization after embeddings but before the main stem of the network.

TYPE: `bool`, *optional* DEFAULT: None

token_dropout

When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.

TYPE: `bool`, defaults to `False` DEFAULT: False

Example
>>> from transformers import EsmModel, EsmConfig
...
>>> # Initializing a ESM facebook/esm-1b style configuration >>> configuration = EsmConfig()
...
>>> # Initializing a model from the configuration >>> model = ESMModel(configuration)
...
>>> # Accessing the model configuration >>> configuration = model.config
Source code in mindnlp\transformers\models\esm\configuration_esm.py
 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
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
class EsmConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`ESMModel`]. It is used to instantiate a ESM 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 ESM
    [facebook/esm-1b](https://hf-mirror.com/facebook/esm-1b) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.


    Args:
        vocab_size (`int`, *optional*):
            Vocabulary size of the ESM model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`ESMModel`].
        mask_token_id (`int`, *optional*):
            The index of the mask token in the vocabulary. This must be included in the config because of the
            "mask-dropout" scaling trick, which will scale the inputs depending on the number of masked tokens.
        pad_token_id (`int`, *optional*):
            The index of the padding token in the vocabulary. This must be included in the config because certain parts
            of the ESM code use this instead of the attention mask.
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (`int`, *optional*, defaults to 3072):
            Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention probabilities.
        max_position_embeddings (`int`, *optional*, defaults to 1026):
            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 (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-12):
            The epsilon used by the layer normalization layers.
        position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
            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 (`bool`, *optional*, defaults to `False`):
            Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
        use_cache (`bool`, *optional*, defaults to `True`):
            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 (`bool`, *optional*):
            Whether to apply layer normalization after embeddings but before the main stem of the network.
        token_dropout (`bool`, defaults to `False`):
            When this is enabled, masked tokens are treated as if they had been dropped out by input dropout.

    Example:
        ```python
        >>> from transformers import EsmModel, EsmConfig
        ...
        >>> # Initializing a ESM facebook/esm-1b style configuration >>> configuration = EsmConfig()
        ...
        >>> # Initializing a model from the configuration >>> model = ESMModel(configuration)
        ...
        >>> # Accessing the model configuration >>> configuration = model.config
        ```
    """
    model_type = "esm"

    def __init__(
        self,
        vocab_size=None,
        mask_token_id=None,
        pad_token_id=None,
        hidden_size=768,
        num_hidden_layers=12,
        num_attention_heads=12,
        intermediate_size=3072,
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=1026,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        position_embedding_type="absolute",
        use_cache=True,
        emb_layer_norm_before=None,
        token_dropout=False,
        is_folding_model=False,
        esmfold_config=None,
        vocab_list=None,
        **kwargs,
    ):
        """
        Initializes an instance of the `EsmConfig` class.

        Args:
            self: The instance of the class.
            vocab_size (int, optional): The size of the vocabulary. Defaults to None.
            mask_token_id (int, optional): The ID of the mask token. Defaults to None.
            pad_token_id (int, optional): The ID of the padding token. Defaults to None.
            hidden_size (int, optional): The size of the hidden layers. Defaults to 768.
            num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
            num_attention_heads (int, optional): The number of attention heads. Defaults to 12.
            intermediate_size (int, optional): The size of the intermediate layers. Defaults to 3072.
            hidden_dropout_prob (float, optional): The dropout probability for hidden layers. Defaults to 0.1.
            attention_probs_dropout_prob (float, optional): The dropout probability for attention layers. Defaults to 0.1.
            max_position_embeddings (int, optional): The maximum position embeddings. Defaults to 1026.
            initializer_range (float, optional): The range for initializer values. Defaults to 0.02.
            layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-12.
            position_embedding_type (str, optional): The type of position embedding. Defaults to 'absolute'.
            use_cache (bool, optional): Whether to use cache. Defaults to True.
            emb_layer_norm_before (bool, optional): Whether to normalize embeddings before layers. Defaults to None.
            token_dropout (bool, optional): Whether to apply token dropout. Defaults to False.
            is_folding_model (bool, optional): Whether the model is a folding model. Defaults to False.
            esmfold_config (EsmFoldConfig, optional): The configuration for the folding model. Defaults to None.
            vocab_list (list, optional): The list of vocabulary tokens. Defaults to None.

        Returns:
            None

        Raises:
            ValueError: If the HuggingFace port of ESMFold does not support `use_esm_attn_map`.
        """
        super().__init__(pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs)

        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_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        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.use_cache = use_cache
        self.emb_layer_norm_before = emb_layer_norm_before
        self.token_dropout = token_dropout
        self.is_folding_model = is_folding_model
        if is_folding_model:
            if esmfold_config is None:
                logger.info("No esmfold_config supplied for folding model, using default values.")
                esmfold_config = EsmFoldConfig()
            elif isinstance(esmfold_config, dict):
                esmfold_config = EsmFoldConfig(**esmfold_config)
            self.esmfold_config = esmfold_config
            if vocab_list is None:
                logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!")
                self.vocab_list = get_default_vocab_list()
            else:
                self.vocab_list = vocab_list
        else:
            self.esmfold_config = None
            self.vocab_list = None
        if self.esmfold_config is not None and getattr(self.esmfold_config, "use_esm_attn_map", False):
            raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!")

    def to_dict(self):
        """
        Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

        Returns:
            `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
        """
        output = super().to_dict()
        if isinstance(self.esmfold_config, EsmFoldConfig):
            output["esmfold_config"] = self.esmfold_config.to_dict()
        return output

mindnlp.transformers.models.esm.configuration_esm.EsmConfig.__init__(vocab_size=None, mask_token_id=None, pad_token_id=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=1026, initializer_range=0.02, layer_norm_eps=1e-12, position_embedding_type='absolute', use_cache=True, emb_layer_norm_before=None, token_dropout=False, is_folding_model=False, esmfold_config=None, vocab_list=None, **kwargs)

Initializes an instance of the EsmConfig class.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_size

The size of the vocabulary. Defaults to None.

TYPE: int DEFAULT: None

mask_token_id

The ID of the mask token. Defaults to None.

TYPE: int DEFAULT: None

pad_token_id

The ID of the padding token. Defaults to None.

TYPE: int DEFAULT: None

hidden_size

The size of the hidden layers. Defaults to 768.

TYPE: int DEFAULT: 768

num_hidden_layers

The number of hidden layers. Defaults to 12.

TYPE: int DEFAULT: 12

num_attention_heads

The number of attention heads. Defaults to 12.

TYPE: int DEFAULT: 12

intermediate_size

The size of the intermediate layers. Defaults to 3072.

TYPE: int DEFAULT: 3072

hidden_dropout_prob

The dropout probability for hidden layers. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

attention_probs_dropout_prob

The dropout probability for attention layers. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

max_position_embeddings

The maximum position embeddings. Defaults to 1026.

TYPE: int DEFAULT: 1026

initializer_range

The range for initializer values. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

layer_norm_eps

The epsilon value for layer normalization. Defaults to 1e-12.

TYPE: float DEFAULT: 1e-12

position_embedding_type

The type of position embedding. Defaults to 'absolute'.

TYPE: str DEFAULT: 'absolute'

use_cache

Whether to use cache. Defaults to True.

TYPE: bool DEFAULT: True

emb_layer_norm_before

Whether to normalize embeddings before layers. Defaults to None.

TYPE: bool DEFAULT: None

token_dropout

Whether to apply token dropout. Defaults to False.

TYPE: bool DEFAULT: False

is_folding_model

Whether the model is a folding model. Defaults to False.

TYPE: bool DEFAULT: False

esmfold_config

The configuration for the folding model. Defaults to None.

TYPE: EsmFoldConfig DEFAULT: None

vocab_list

The list of vocabulary tokens. Defaults to None.

TYPE: list DEFAULT: None

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the HuggingFace port of ESMFold does not support use_esm_attn_map.

Source code in mindnlp\transformers\models\esm\configuration_esm.py
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
def __init__(
    self,
    vocab_size=None,
    mask_token_id=None,
    pad_token_id=None,
    hidden_size=768,
    num_hidden_layers=12,
    num_attention_heads=12,
    intermediate_size=3072,
    hidden_dropout_prob=0.1,
    attention_probs_dropout_prob=0.1,
    max_position_embeddings=1026,
    initializer_range=0.02,
    layer_norm_eps=1e-12,
    position_embedding_type="absolute",
    use_cache=True,
    emb_layer_norm_before=None,
    token_dropout=False,
    is_folding_model=False,
    esmfold_config=None,
    vocab_list=None,
    **kwargs,
):
    """
    Initializes an instance of the `EsmConfig` class.

    Args:
        self: The instance of the class.
        vocab_size (int, optional): The size of the vocabulary. Defaults to None.
        mask_token_id (int, optional): The ID of the mask token. Defaults to None.
        pad_token_id (int, optional): The ID of the padding token. Defaults to None.
        hidden_size (int, optional): The size of the hidden layers. Defaults to 768.
        num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
        num_attention_heads (int, optional): The number of attention heads. Defaults to 12.
        intermediate_size (int, optional): The size of the intermediate layers. Defaults to 3072.
        hidden_dropout_prob (float, optional): The dropout probability for hidden layers. Defaults to 0.1.
        attention_probs_dropout_prob (float, optional): The dropout probability for attention layers. Defaults to 0.1.
        max_position_embeddings (int, optional): The maximum position embeddings. Defaults to 1026.
        initializer_range (float, optional): The range for initializer values. Defaults to 0.02.
        layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-12.
        position_embedding_type (str, optional): The type of position embedding. Defaults to 'absolute'.
        use_cache (bool, optional): Whether to use cache. Defaults to True.
        emb_layer_norm_before (bool, optional): Whether to normalize embeddings before layers. Defaults to None.
        token_dropout (bool, optional): Whether to apply token dropout. Defaults to False.
        is_folding_model (bool, optional): Whether the model is a folding model. Defaults to False.
        esmfold_config (EsmFoldConfig, optional): The configuration for the folding model. Defaults to None.
        vocab_list (list, optional): The list of vocabulary tokens. Defaults to None.

    Returns:
        None

    Raises:
        ValueError: If the HuggingFace port of ESMFold does not support `use_esm_attn_map`.
    """
    super().__init__(pad_token_id=pad_token_id, mask_token_id=mask_token_id, **kwargs)

    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_dropout_prob = hidden_dropout_prob
    self.attention_probs_dropout_prob = attention_probs_dropout_prob
    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.use_cache = use_cache
    self.emb_layer_norm_before = emb_layer_norm_before
    self.token_dropout = token_dropout
    self.is_folding_model = is_folding_model
    if is_folding_model:
        if esmfold_config is None:
            logger.info("No esmfold_config supplied for folding model, using default values.")
            esmfold_config = EsmFoldConfig()
        elif isinstance(esmfold_config, dict):
            esmfold_config = EsmFoldConfig(**esmfold_config)
        self.esmfold_config = esmfold_config
        if vocab_list is None:
            logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!")
            self.vocab_list = get_default_vocab_list()
        else:
            self.vocab_list = vocab_list
    else:
        self.esmfold_config = None
        self.vocab_list = None
    if self.esmfold_config is not None and getattr(self.esmfold_config, "use_esm_attn_map", False):
        raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!")

mindnlp.transformers.models.esm.configuration_esm.EsmConfig.to_dict()

Serializes this instance to a Python dictionary. Override the default [~PretrainedConfig.to_dict].

RETURNS DESCRIPTION

Dict[str, any]: Dictionary of all the attributes that make up this configuration instance,

Source code in mindnlp\transformers\models\esm\configuration_esm.py
192
193
194
195
196
197
198
199
200
201
202
def to_dict(self):
    """
    Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

    Returns:
        `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
    """
    output = super().to_dict()
    if isinstance(self.esmfold_config, EsmFoldConfig):
        output["esmfold_config"] = self.esmfold_config.to_dict()
    return output

mindnlp.transformers.models.esm.configuration_esm.EsmFoldConfig dataclass

Represents the configuration of an ESM (Efficient Speech Model) fold instance.

This class provides methods to initialize the EsmFoldConfig instance and serialize it to a Python dictionary.

The EsmFoldConfig class inherits from a base class and includes methods for post-initialization and dictionary serialization.

METHOD DESCRIPTION
__post_init__

Initializes the EsmFoldConfig instance, setting defaults for any missing attributes.

to_dict

Serializes the EsmFoldConfig instance to a Python dictionary, including the trunk configuration.

ATTRIBUTE DESCRIPTION
trunk

Represents the configuration of the trunk model used in the ESM fold.

TYPE: TrunkConfig

Note

Ensure that the trunk attribute is either set to a TrunkConfig instance or a dictionary that can be converted to a TrunkConfig.

Return

A Python dictionary containing all the attributes of the EsmFoldConfig instance, including the trunk configuration.

Source code in mindnlp\transformers\models\esm\configuration_esm.py
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
261
262
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
@dataclass
class EsmFoldConfig:

    """
    Represents the configuration of an ESM (Efficient Speech Model) fold instance.

    This class provides methods to initialize the EsmFoldConfig instance and serialize it to a Python dictionary.

    The EsmFoldConfig class inherits from a base class and includes methods for post-initialization and dictionary serialization.

    Methods:
        __post_init__(self): Initializes the EsmFoldConfig instance, setting defaults for any missing attributes.
        to_dict(self): Serializes the EsmFoldConfig instance to a Python dictionary, including the trunk configuration.

    Attributes:
        trunk: Represents the configuration of the trunk model used in the ESM fold.

    Note:
        Ensure that the trunk attribute is either set to a TrunkConfig instance or a dictionary that can be converted to a TrunkConfig.

    Return:
        A Python dictionary containing all the attributes of the EsmFoldConfig instance, including the trunk configuration.
    """
    esm_type: str = None
    fp16_esm: bool = True
    use_esm_attn_map: bool = False
    esm_ablate_pairwise: bool = False
    esm_ablate_sequence: bool = False
    esm_input_dropout: float = 0

    embed_aa: bool = True
    bypass_lm: bool = False

    lddt_head_hid_dim: int = 128
    trunk: "TrunkConfig" = None

    def __post_init__(self):
        """
        The '__post_init__' method is used in the 'EsmFoldConfig' class to initialize the 'trunk' attribute.

        Args:
            self: An instance of the 'EsmFoldConfig' class.

        Returns:
            None.

        Raises:
            None.

        Description:
            This method checks if the 'trunk' attribute is None. If it is, a new instance of the 'TrunkConfig' class
            is created and assigned to 'self.trunk'. If the 'trunk' attribute is of type dict, it is unpacked and
            passed as keyword arguments to create a new instance of the 'TrunkConfig' class,  which is then assigned to
            'self.trunk'. This method is typically called after the object is initialized to ensure that the 'trunk'
            attribute is properly set.

        Example:
            ```python
            >>> config = EsmFoldConfig()
            >>> config.__post_init__()
            >>> # The 'trunk' attribute will be initialized with a new instance of the 'TrunkConfig' class.
            ...
            >>> config = EsmFoldConfig(trunk={'option1': True, 'option2': False})
            >>> config.__post_init__()
            >>> # The 'trunk' attribute will be initialized with a new instance of the 'TrunkConfig' class,
            >>> # with 'option1' set to True and 'option2' set to False.
            ```
        """
        if self.trunk is None:
            self.trunk = TrunkConfig()
        elif isinstance(self.trunk, dict):
            self.trunk = TrunkConfig(**self.trunk)

    def to_dict(self):
        """
        Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

        Returns:
            `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
        """
        output = asdict(self)
        output["trunk"] = self.trunk.to_dict()
        return output

mindnlp.transformers.models.esm.configuration_esm.EsmFoldConfig.__post_init__()

The 'post_init' method is used in the 'EsmFoldConfig' class to initialize the 'trunk' attribute.

PARAMETER DESCRIPTION
self

An instance of the 'EsmFoldConfig' class.

RETURNS DESCRIPTION

None.

Description

This method checks if the 'trunk' attribute is None. If it is, a new instance of the 'TrunkConfig' class is created and assigned to 'self.trunk'. If the 'trunk' attribute is of type dict, it is unpacked and passed as keyword arguments to create a new instance of the 'TrunkConfig' class, which is then assigned to 'self.trunk'. This method is typically called after the object is initialized to ensure that the 'trunk' attribute is properly set.

Example
>>> config = EsmFoldConfig()
>>> config.__post_init__()
>>> # The 'trunk' attribute will be initialized with a new instance of the 'TrunkConfig' class.
...
>>> config = EsmFoldConfig(trunk={'option1': True, 'option2': False})
>>> config.__post_init__()
>>> # The 'trunk' attribute will be initialized with a new instance of the 'TrunkConfig' class,
>>> # with 'option1' set to True and 'option2' set to False.
Source code in mindnlp\transformers\models\esm\configuration_esm.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def __post_init__(self):
    """
    The '__post_init__' method is used in the 'EsmFoldConfig' class to initialize the 'trunk' attribute.

    Args:
        self: An instance of the 'EsmFoldConfig' class.

    Returns:
        None.

    Raises:
        None.

    Description:
        This method checks if the 'trunk' attribute is None. If it is, a new instance of the 'TrunkConfig' class
        is created and assigned to 'self.trunk'. If the 'trunk' attribute is of type dict, it is unpacked and
        passed as keyword arguments to create a new instance of the 'TrunkConfig' class,  which is then assigned to
        'self.trunk'. This method is typically called after the object is initialized to ensure that the 'trunk'
        attribute is properly set.

    Example:
        ```python
        >>> config = EsmFoldConfig()
        >>> config.__post_init__()
        >>> # The 'trunk' attribute will be initialized with a new instance of the 'TrunkConfig' class.
        ...
        >>> config = EsmFoldConfig(trunk={'option1': True, 'option2': False})
        >>> config.__post_init__()
        >>> # The 'trunk' attribute will be initialized with a new instance of the 'TrunkConfig' class,
        >>> # with 'option1' set to True and 'option2' set to False.
        ```
    """
    if self.trunk is None:
        self.trunk = TrunkConfig()
    elif isinstance(self.trunk, dict):
        self.trunk = TrunkConfig(**self.trunk)

mindnlp.transformers.models.esm.configuration_esm.EsmFoldConfig.to_dict()

Serializes this instance to a Python dictionary. Override the default [~PretrainedConfig.to_dict].

RETURNS DESCRIPTION

Dict[str, any]: Dictionary of all the attributes that make up this configuration instance,

Source code in mindnlp\transformers\models\esm\configuration_esm.py
278
279
280
281
282
283
284
285
286
287
def to_dict(self):
    """
    Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

    Returns:
        `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
    """
    output = asdict(self)
    output["trunk"] = self.trunk.to_dict()
    return output

mindnlp.transformers.models.esm.configuration_esm.StructureModuleConfig dataclass

PARAMETER DESCRIPTION
sequence_dim

Single representation channel dimension

TYPE: int DEFAULT: 384

pairwise_dim

Pair representation channel dimension

TYPE: int DEFAULT: 128

ipa_dim

IPA hidden channel dimension

TYPE: int DEFAULT: 16

resnet_dim

Angle resnet (Alg. 23 lines 11-14) hidden channel dimension

TYPE: int DEFAULT: 128

num_heads_ipa

Number of IPA heads

TYPE: int DEFAULT: 12

num_qk_points

Number of query/key points to generate during IPA

TYPE: int DEFAULT: 4

num_v_points

Number of value points to generate during IPA

TYPE: int DEFAULT: 8

dropout_rate

Dropout rate used throughout the layer

TYPE: float DEFAULT: 0.1

num_blocks

Number of structure module blocks

TYPE: int DEFAULT: 8

num_transition_layers

Number of layers in the single representation transition (Alg. 23 lines 8-9)

TYPE: int DEFAULT: 1

num_resnet_blocks

Number of blocks in the angle resnet

TYPE: int DEFAULT: 2

num_angles

Number of angles to generate in the angle resnet

TYPE: int DEFAULT: 7

trans_scale_factor

Scale of single representation transition hidden dimension

TYPE: int DEFAULT: 10

epsilon

Small number used in angle resnet normalization

TYPE: float DEFAULT: 1e-08

inf

Large number used for attention masking

TYPE: float DEFAULT: 100000.0

Source code in mindnlp\transformers\models\esm\configuration_esm.py
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
@dataclass
class StructureModuleConfig:
    """
    Args:
        sequence_dim:
            Single representation channel dimension
        pairwise_dim:
            Pair representation channel dimension
        ipa_dim:
            IPA hidden channel dimension
        resnet_dim:
            Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
        num_heads_ipa:
            Number of IPA heads
        num_qk_points:
            Number of query/key points to generate during IPA
        num_v_points:
            Number of value points to generate during IPA
        dropout_rate:
            Dropout rate used throughout the layer
        num_blocks:
            Number of structure module blocks
        num_transition_layers:
            Number of layers in the single representation transition (Alg. 23 lines 8-9)
        num_resnet_blocks:
            Number of blocks in the angle resnet
        num_angles:
            Number of angles to generate in the angle resnet
        trans_scale_factor:
            Scale of single representation transition hidden dimension
        epsilon:
            Small number used in angle resnet normalization
        inf:
            Large number used for attention masking
    """
    sequence_dim: int = 384
    pairwise_dim: int = 128
    ipa_dim: int = 16
    resnet_dim: int = 128
    num_heads_ipa: int = 12
    num_qk_points: int = 4
    num_v_points: int = 8
    dropout_rate: float = 0.1
    num_blocks: int = 8
    num_transition_layers: int = 1
    num_resnet_blocks: int = 2
    num_angles: int = 7
    trans_scale_factor: int = 10
    epsilon: float = 1e-8
    inf: float = 1e5

    def to_dict(self):
        """
        Converts the current instance of the StructureModuleConfig class to a dictionary.

        Args:
            self (StructureModuleConfig): The current instance of the StructureModuleConfig class.

        Returns:
            dict: A dictionary representation of the current StructureModuleConfig instance.

        Raises:
            None.
        """
        return asdict(self)

mindnlp.transformers.models.esm.configuration_esm.StructureModuleConfig.to_dict()

Converts the current instance of the StructureModuleConfig class to a dictionary.

PARAMETER DESCRIPTION
self

The current instance of the StructureModuleConfig class.

TYPE: StructureModuleConfig

RETURNS DESCRIPTION
dict

A dictionary representation of the current StructureModuleConfig instance.

Source code in mindnlp\transformers\models\esm\configuration_esm.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def to_dict(self):
    """
    Converts the current instance of the StructureModuleConfig class to a dictionary.

    Args:
        self (StructureModuleConfig): The current instance of the StructureModuleConfig class.

    Returns:
        dict: A dictionary representation of the current StructureModuleConfig instance.

    Raises:
        None.
    """
    return asdict(self)

mindnlp.transformers.models.esm.configuration_esm.TrunkConfig dataclass

Represents the configuration settings for the Trunk model. This class defines the configuration attributes and their validations for the Trunk model.

ATTRIBUTE DESCRIPTION
structure_module

The configuration for the structure module.

TYPE: StructureModuleConfig

max_recycles

The maximum number of recycles, should be a positive integer.

TYPE: int

sequence_state_dim

The dimension of the sequence state.

TYPE: int

pairwise_state_dim

The dimension of the pairwise state.

TYPE: int

sequence_head_width

The width of the sequence head.

TYPE: int

pairwise_head_width

The width of the pairwise head.

TYPE: int

dropout

The dropout rate, should not be greater than 0.4.

TYPE: float

RAISES DESCRIPTION
ValueError

If any of the following conditions are not met:

  • max_recycles is not a positive integer.
  • sequence_state_dim is not a round multiple of itself.
  • pairwise_state_dim is not a round multiple of itself.
  • sequence_state_dim is not equal to sequence_num_heads * sequence_head_width.
  • pairwise_state_dim is not equal to pairwise_num_heads * pairwise_head_width.
  • pairwise_state_dim is not an even number.
  • dropout is greater than 0.4.
METHOD DESCRIPTION
__post_init__

Performs post-initialization validations for the configuration attributes.

to_dict

Serializes the instance to a Python dictionary, including the structure module configuration.

Overrides

~PretrainedConfig.to_dict: Overrides the default to_dict method to include the structure module configuration in the dictionary output.

Source code in mindnlp\transformers\models\esm\configuration_esm.py
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
327
328
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
@dataclass
class TrunkConfig:

    """
    Represents the configuration settings for the Trunk model.
    This class defines the configuration attributes and their validations for the Trunk model.

    Attributes:
        structure_module (StructureModuleConfig): The configuration for the structure module.
        max_recycles (int): The maximum number of recycles, should be a positive integer.
        sequence_state_dim (int): The dimension of the sequence state.
        pairwise_state_dim (int): The dimension of the pairwise state.
        sequence_head_width (int): The width of the sequence head.
        pairwise_head_width (int): The width of the pairwise head.
        dropout (float): The dropout rate, should not be greater than 0.4.

    Raises:
        ValueError:
            If any of the following conditions are not met:

            - `max_recycles` is not a positive integer.
            - `sequence_state_dim` is not a round multiple of itself.
            - `pairwise_state_dim` is not a round multiple of itself.
            - `sequence_state_dim` is not equal to `sequence_num_heads * sequence_head_width`.
            - `pairwise_state_dim` is not equal to `pairwise_num_heads * pairwise_head_width`.
            - `pairwise_state_dim` is not an even number.
            - `dropout` is greater than 0.4.

    Methods:
        __post_init__(self): Performs post-initialization validations for the configuration attributes.
        to_dict(self): Serializes the instance to a Python dictionary, including the structure module configuration.

    Overrides:
        `~PretrainedConfig.to_dict`: Overrides the default `to_dict` method to include the structure module
        configuration in the dictionary output.
    """
    num_blocks: int = 48
    sequence_state_dim: int = 1024
    pairwise_state_dim: int = 128
    sequence_head_width: int = 32
    pairwise_head_width: int = 32
    position_bins: int = 32
    dropout: float = 0
    layer_drop: float = 0
    cpu_grad_checkpoint: bool = False
    max_recycles: int = 4
    chunk_size: Optional[int] = 128
    structure_module: "StructureModuleConfig" = None

    def __post_init__(self):
        """
        This method initializes the TrunkConfig class after its instantiation.

        Args:
            self: The instance of the TrunkConfig class.

        Returns:
            None.

        Raises:
            ValueError: If `max_recycles` is not a positive value.
            ValueError: If `sequence_state_dim` is not a round multiple of itself.
            ValueError: If `pairwise_state_dim` is not a round multiple of itself.
            ValueError: If `sequence_state_dim` is not equal to `sequence_num_heads * sequence_head_width`.
            ValueError: If `pairwise_state_dim` is not equal to `pairwise_num_heads * pairwise_head_width`.
            ValueError: If `pairwise_state_dim` is not an even number.
            ValueError: If `dropout` is greater than or equal to 0.4.
        """
        if self.structure_module is None:
            self.structure_module = StructureModuleConfig()
        elif isinstance(self.structure_module, dict):
            self.structure_module = StructureModuleConfig(**self.structure_module)

        if self.max_recycles <= 0:
            raise ValueError(f"`max_recycles` should be positive, got {self.max_recycles}.")
        if self.sequence_state_dim % self.sequence_state_dim != 0:
            raise ValueError(
                "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
                f" {self.sequence_state_dim} and {self.sequence_state_dim}."
            )
        if self.pairwise_state_dim % self.pairwise_state_dim != 0:
            raise ValueError(
                "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
                f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
            )

        sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
        pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width

        if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
            raise ValueError(
                "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
                f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
            )
        if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
            raise ValueError(
                "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
                f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
            )
        if self.pairwise_state_dim % 2 != 0:
            raise ValueError(f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.")

        if self.dropout >= 0.4:
            raise ValueError(f"`dropout` should not be greater than 0.4, got {self.dropout}.")

    def to_dict(self):
        """
        Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

        Returns:
            `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
        """
        output = asdict(self)
        output["structure_module"] = self.structure_module.to_dict()
        return output

mindnlp.transformers.models.esm.configuration_esm.TrunkConfig.__post_init__()

This method initializes the TrunkConfig class after its instantiation.

PARAMETER DESCRIPTION
self

The instance of the TrunkConfig class.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If max_recycles is not a positive value.

ValueError

If sequence_state_dim is not a round multiple of itself.

ValueError

If pairwise_state_dim is not a round multiple of itself.

ValueError

If sequence_state_dim is not equal to sequence_num_heads * sequence_head_width.

ValueError

If pairwise_state_dim is not equal to pairwise_num_heads * pairwise_head_width.

ValueError

If pairwise_state_dim is not an even number.

ValueError

If dropout is greater than or equal to 0.4.

Source code in mindnlp\transformers\models\esm\configuration_esm.py
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
391
392
393
def __post_init__(self):
    """
    This method initializes the TrunkConfig class after its instantiation.

    Args:
        self: The instance of the TrunkConfig class.

    Returns:
        None.

    Raises:
        ValueError: If `max_recycles` is not a positive value.
        ValueError: If `sequence_state_dim` is not a round multiple of itself.
        ValueError: If `pairwise_state_dim` is not a round multiple of itself.
        ValueError: If `sequence_state_dim` is not equal to `sequence_num_heads * sequence_head_width`.
        ValueError: If `pairwise_state_dim` is not equal to `pairwise_num_heads * pairwise_head_width`.
        ValueError: If `pairwise_state_dim` is not an even number.
        ValueError: If `dropout` is greater than or equal to 0.4.
    """
    if self.structure_module is None:
        self.structure_module = StructureModuleConfig()
    elif isinstance(self.structure_module, dict):
        self.structure_module = StructureModuleConfig(**self.structure_module)

    if self.max_recycles <= 0:
        raise ValueError(f"`max_recycles` should be positive, got {self.max_recycles}.")
    if self.sequence_state_dim % self.sequence_state_dim != 0:
        raise ValueError(
            "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
            f" {self.sequence_state_dim} and {self.sequence_state_dim}."
        )
    if self.pairwise_state_dim % self.pairwise_state_dim != 0:
        raise ValueError(
            "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
            f" {self.pairwise_state_dim} and {self.pairwise_state_dim}."
        )

    sequence_num_heads = self.sequence_state_dim // self.sequence_head_width
    pairwise_num_heads = self.pairwise_state_dim // self.pairwise_head_width

    if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
        raise ValueError(
            "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
            f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."
        )
    if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
        raise ValueError(
            "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
            f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."
        )
    if self.pairwise_state_dim % 2 != 0:
        raise ValueError(f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.")

    if self.dropout >= 0.4:
        raise ValueError(f"`dropout` should not be greater than 0.4, got {self.dropout}.")

mindnlp.transformers.models.esm.configuration_esm.TrunkConfig.to_dict()

Serializes this instance to a Python dictionary. Override the default [~PretrainedConfig.to_dict].

RETURNS DESCRIPTION

Dict[str, any]: Dictionary of all the attributes that make up this configuration instance,

Source code in mindnlp\transformers\models\esm\configuration_esm.py
395
396
397
398
399
400
401
402
403
404
def to_dict(self):
    """
    Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].

    Returns:
        `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
    """
    output = asdict(self)
    output["structure_module"] = self.structure_module.to_dict()
    return output

mindnlp.transformers.models.esm.configuration_esm.get_default_vocab_list()

This function returns a list of default vocabulary items including special tokens and characters used in natural language processing tasks.

RETURNS DESCRIPTION
List

A list of default vocabulary items including '', '', '', '', 'L', 'A', 'G', 'V', 'S', 'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', 'N', 'F', 'Y', 'M', 'H', 'W', 'C', 'X', 'B', 'U', 'Z', 'O', '.', '-', '', ''.

Source code in mindnlp\transformers\models\esm\configuration_esm.py
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
519
520
521
522
523
524
525
def get_default_vocab_list():
    '''
    This function returns a list of default vocabulary items including special tokens and characters used in natural
    language processing tasks.

    Args:
        None.

    Returns:
        List:
            A list of default vocabulary items including '<cls>', '<pad>', '<eos>', '<unk>', 'L', 'A', 'G', 'V', 'S',
            'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', 'N', 'F', 'Y', 'M', 'H', 'W', 'C', 'X', 'B', 'U',
            'Z', 'O', '.', '-', '<null_1>', '<mask>'.

    Raises:
        None.
    '''
    return (
        "<cls>",
        "<pad>",
        "<eos>",
        "<unk>",
        "L",
        "A",
        "G",
        "V",
        "S",
        "E",
        "R",
        "T",
        "I",
        "D",
        "P",
        "K",
        "Q",
        "N",
        "F",
        "Y",
        "M",
        "H",
        "W",
        "C",
        "X",
        "B",
        "U",
        "Z",
        "O",
        ".",
        "-",
        "<null_1>",
        "<mask>",
    )

mindnlp.transformers.models.esm.modeling_esm.EsmForMaskedLM

Bases: EsmPreTrainedModel

Represents an ESM (Evolutionary Scale Modeling) model for masked language modeling (MLM), inheriting from EsmPreTrainedModel. This class provides the functionality to perform masked language modeling using the ESM model.

The EsmForMaskedLM class contains methods for initializing the model, getting and setting output embeddings, forwarding the model, and predicting contacts. The model architecture includes an ESM model and a language modeling head (lm_head). The forward method takes input_ids, attention_mask, position_ids, head_mask, inputs_embeds, encoder_hidden_states, encoder_attention_mask, labels, output_attentions, output_hidden_states, and return_dict as input arguments and returns the masked language modeling loss and other outputs. The predict_contacts method takes tokens and attention_mask as input and returns the predicted contacts using the ESM model.

Note
  • If using EsmForMaskedLM, ensure config.is_decoder=False for bi-directional self-attention.
  • Labels for computing the masked language modeling loss should be indices in [-100, 0, ..., config.vocab_size]. Tokens with indices set to -100 are ignored (masked), and the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
Source code in mindnlp\transformers\models\esm\modeling_esm.py
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
class EsmForMaskedLM(EsmPreTrainedModel):

    """
    Represents an ESM (Evolutionary Scale Modeling) model for masked language modeling (MLM), inheriting from EsmPreTrainedModel.
    This class provides the functionality to perform masked language modeling using the ESM model.

    The EsmForMaskedLM class contains methods for initializing the model, getting and setting output embeddings,
    forwarding the model, and predicting contacts.
    The model architecture includes an ESM model and a language modeling head (lm_head).
    The forward method takes input_ids, attention_mask, position_ids, head_mask, inputs_embeds, encoder_hidden_states,
    encoder_attention_mask, labels, output_attentions, output_hidden_states, and return_dict as input arguments and
    returns the masked language modeling loss and other outputs.
    The predict_contacts method takes tokens and attention_mask as input and returns the predicted contacts using the
    ESM model.

    Note:
        - If using `EsmForMaskedLM`, ensure `config.is_decoder=False` for bi-directional self-attention.
        - Labels for computing the masked language modeling loss should be indices in `[-100, 0, ..., config.vocab_size]`.
        Tokens with indices set to `-100` are ignored (masked), and the loss is only computed for the tokens with labels
        in `[0, ..., config.vocab_size]`.

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

    def __init__(self, config):
        """
        Initializes an instance of EsmForMaskedLM.

        Args:
            self: The instance of the class.
            config (object): The configuration object containing model hyperparameters.
                It must have attributes like 'is_decoder', 'add_pooling_layer', and 'init_weights'.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)

        if config.is_decoder:
            logger.warning(
                "If you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for "
                "bi-directional self-attention."
            )

        self.esm = EsmModel(config, add_pooling_layer=False)
        self.lm_head = EsmLMHead(config)

        self.init_weights()

    def get_output_embeddings(self):
        """
        This method returns the output embeddings for the language model head.

        Args:
            self: An instance of the EsmForMaskedLM class.

        Returns:
            decoder: The method returns the output embeddings for the language model head.

        Raises:
            None.
        """
        return self.lm_head.decoder

    def set_output_embeddings(self, new_embeddings):
        """
        Set the output embeddings for the ESM model.

        Args:
            self (EsmForMaskedLM): The instance of the EsmForMaskedLM class.
            new_embeddings (torch.nn.Module): The new embeddings to be set as output embeddings for the model.

        Returns:
            None.

        Raises:
            TypeError: If the provided new_embeddings is not of type torch.nn.Module.
            AttributeError: If the lm_head.decoder attribute is not present in the EsmForMaskedLM instance.
        """
        self.lm_head.decoder = new_embeddings

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        encoder_hidden_states: Optional[mindspore.Tensor] = None,
        encoder_attention_mask: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, MaskedLMOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
                config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
                loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
            kwargs (`Dict[str, any]`, optional, defaults to *{}*):
                Used to hide legacy arguments that have been deprecated.
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.esm(
            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,
        )
        sequence_output = outputs[0]
        prediction_scores = self.lm_head(sequence_output)

        masked_lm_loss = None
        if labels is not None:
            masked_lm_loss = F.cross_entropy(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))

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

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

    def predict_contacts(self, tokens, attention_mask):
        """
        This method predicts contacts using the ESM (Evolutionary Scale Modeling) for Masked Language Modeling.

        Args:
            self (EsmForMaskedLM): The instance of the EsmForMaskedLM class.
            tokens (Tensor): The input tokens for prediction.
            attention_mask (Tensor): The attention mask for the input tokens.
                It masks the tokens that should not be attended to, specifying which tokens should be attended to
                and which should not.

        Returns:
            None.

        Raises:
            None.
        """
        return self.esm.predict_contacts(tokens, attention_mask=attention_mask)

mindnlp.transformers.models.esm.modeling_esm.EsmForMaskedLM.__init__(config)

Initializes an instance of EsmForMaskedLM.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object containing model hyperparameters. It must have attributes like 'is_decoder', 'add_pooling_layer', and 'init_weights'.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
def __init__(self, config):
    """
    Initializes an instance of EsmForMaskedLM.

    Args:
        self: The instance of the class.
        config (object): The configuration object containing model hyperparameters.
            It must have attributes like 'is_decoder', 'add_pooling_layer', and 'init_weights'.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)

    if config.is_decoder:
        logger.warning(
            "If you want to use `EsmForMaskedLM` make sure `config.is_decoder=False` for "
            "bi-directional self-attention."
        )

    self.esm = EsmModel(config, add_pooling_layer=False)
    self.lm_head = EsmLMHead(config)

    self.init_weights()

mindnlp.transformers.models.esm.modeling_esm.EsmForMaskedLM.forward(input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the masked language modeling loss. Indices should be in [-100, 0, ..., config.vocab_size] (see input_ids docstring) Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size]

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional* DEFAULT: None

kwargs

Used to hide legacy arguments that have been deprecated.

TYPE: `Dict[str, any]`, optional, defaults to *{}*

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    encoder_hidden_states: Optional[mindspore.Tensor] = None,
    encoder_attention_mask: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, MaskedLMOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        kwargs (`Dict[str, any]`, optional, defaults to *{}*):
            Used to hide legacy arguments that have been deprecated.
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.esm(
        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,
    )
    sequence_output = outputs[0]
    prediction_scores = self.lm_head(sequence_output)

    masked_lm_loss = None
    if labels is not None:
        masked_lm_loss = F.cross_entropy(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))

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

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

mindnlp.transformers.models.esm.modeling_esm.EsmForMaskedLM.get_output_embeddings()

This method returns the output embeddings for the language model head.

PARAMETER DESCRIPTION
self

An instance of the EsmForMaskedLM class.

RETURNS DESCRIPTION
decoder

The method returns the output embeddings for the language model head.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
def get_output_embeddings(self):
    """
    This method returns the output embeddings for the language model head.

    Args:
        self: An instance of the EsmForMaskedLM class.

    Returns:
        decoder: The method returns the output embeddings for the language model head.

    Raises:
        None.
    """
    return self.lm_head.decoder

mindnlp.transformers.models.esm.modeling_esm.EsmForMaskedLM.predict_contacts(tokens, attention_mask)

This method predicts contacts using the ESM (Evolutionary Scale Modeling) for Masked Language Modeling.

PARAMETER DESCRIPTION
self

The instance of the EsmForMaskedLM class.

TYPE: EsmForMaskedLM

tokens

The input tokens for prediction.

TYPE: Tensor

attention_mask

The attention mask for the input tokens. It masks the tokens that should not be attended to, specifying which tokens should be attended to and which should not.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
def predict_contacts(self, tokens, attention_mask):
    """
    This method predicts contacts using the ESM (Evolutionary Scale Modeling) for Masked Language Modeling.

    Args:
        self (EsmForMaskedLM): The instance of the EsmForMaskedLM class.
        tokens (Tensor): The input tokens for prediction.
        attention_mask (Tensor): The attention mask for the input tokens.
            It masks the tokens that should not be attended to, specifying which tokens should be attended to
            and which should not.

    Returns:
        None.

    Raises:
        None.
    """
    return self.esm.predict_contacts(tokens, attention_mask=attention_mask)

mindnlp.transformers.models.esm.modeling_esm.EsmForMaskedLM.set_output_embeddings(new_embeddings)

Set the output embeddings for the ESM model.

PARAMETER DESCRIPTION
self

The instance of the EsmForMaskedLM class.

TYPE: EsmForMaskedLM

new_embeddings

The new embeddings to be set as output embeddings for the model.

TYPE: Module

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the provided new_embeddings is not of type torch.nn.Module.

AttributeError

If the lm_head.decoder attribute is not present in the EsmForMaskedLM instance.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
def set_output_embeddings(self, new_embeddings):
    """
    Set the output embeddings for the ESM model.

    Args:
        self (EsmForMaskedLM): The instance of the EsmForMaskedLM class.
        new_embeddings (torch.nn.Module): The new embeddings to be set as output embeddings for the model.

    Returns:
        None.

    Raises:
        TypeError: If the provided new_embeddings is not of type torch.nn.Module.
        AttributeError: If the lm_head.decoder attribute is not present in the EsmForMaskedLM instance.
    """
    self.lm_head.decoder = new_embeddings

mindnlp.transformers.models.esm.modeling_esm.EsmForSequenceClassification

Bases: EsmPreTrainedModel

This class represents an ESM (Evoformer) model for sequence classification tasks. It is a subclass of EsmPreTrainedModel, which provides the underlying architecture and functionality.

ATTRIBUTE DESCRIPTION
num_labels

The number of labels for the classification task.

TYPE: int

config

The configuration object for the ESM model.

TYPE: EsmConfig

esm

The ESM model instance.

TYPE: EsmModel

classifier

The classification head for the ESM model.

TYPE: EsmClassificationHead

METHOD DESCRIPTION
__init__

Initializes the EsmForSequenceClassification instance.

forward

Constructs the ESM model for sequence classification.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
class EsmForSequenceClassification(EsmPreTrainedModel):

    """
    This class represents an ESM (Evoformer) model for sequence classification tasks.
    It is a subclass of EsmPreTrainedModel, which provides the underlying architecture and functionality.

    Attributes:
        num_labels (int): The number of labels for the classification task.
        config (EsmConfig): The configuration object for the ESM model.
        esm (EsmModel): The ESM model instance.
        classifier (EsmClassificationHead): The classification head for the ESM model.

    Methods:
        __init__: Initializes the EsmForSequenceClassification instance.
        forward: Constructs the ESM model for sequence classification.

    """
    def __init__(self, config):
        """
        Initializes an instance of EsmForSequenceClassification.

        Args:
            self: The instance of the class.
            config:
                An object containing the configuration parameters for the model.

                - Type: object
                - Purpose: To configure the model and its components.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.config = config

        self.esm = EsmModel(config, add_pooling_layer=False)
        self.classifier = EsmClassificationHead(config)

        self.init_weights()

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, SequenceClassifierOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
                config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
                `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.esm(
            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,
        )
        sequence_output = outputs[0]
        logits = self.classifier(sequence_output)

        loss = None
        if labels is not None:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and labels.dtype in (mindspore.int64, mindspore.int32):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                if self.num_labels == 1:
                    loss = F.mse_loss(logits.squeeze(), labels.squeeze())
                else:
                    loss = F.mse_loss(logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss = F.binary_cross_entropy_with_logits(logits, labels)

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

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

mindnlp.transformers.models.esm.modeling_esm.EsmForSequenceClassification.__init__(config)

Initializes an instance of EsmForSequenceClassification.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration parameters for the model.

  • Type: object
  • Purpose: To configure the model and its components.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
def __init__(self, config):
    """
    Initializes an instance of EsmForSequenceClassification.

    Args:
        self: The instance of the class.
        config:
            An object containing the configuration parameters for the model.

            - Type: object
            - Purpose: To configure the model and its components.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.config = config

    self.esm = EsmModel(config, add_pooling_layer=False)
    self.classifier = EsmClassificationHead(config)

    self.init_weights()

mindnlp.transformers.models.esm.modeling_esm.EsmForSequenceClassification.forward(input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

TYPE: `mindspore.Tensor` of shape `(batch_size,)`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, SequenceClassifierOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.esm(
        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,
    )
    sequence_output = outputs[0]
    logits = self.classifier(sequence_output)

    loss = None
    if labels is not None:
        if self.config.problem_type is None:
            if self.num_labels == 1:
                self.config.problem_type = "regression"
            elif self.num_labels > 1 and labels.dtype in (mindspore.int64, mindspore.int32):
                self.config.problem_type = "single_label_classification"
            else:
                self.config.problem_type = "multi_label_classification"

        if self.config.problem_type == "regression":
            if self.num_labels == 1:
                loss = F.mse_loss(logits.squeeze(), labels.squeeze())
            else:
                loss = F.mse_loss(logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
        elif self.config.problem_type == "multi_label_classification":
            loss = F.binary_cross_entropy_with_logits(logits, labels)

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

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

mindnlp.transformers.models.esm.modeling_esm.EsmForTokenClassification

Bases: EsmPreTrainedModel

EsmForTokenClassification is a class that represents a token classification model based on the ESM (Evoformer Sequence Model) architecture. This class extends EsmPreTrainedModel to leverage pre-trained weights and configurations for efficient token classification tasks. It includes methods for initializing the model, forwarding the forward pass, and computing the token classification loss.

The init method initializes the EsmForTokenClassification model with configurable parameters such as the number of labels, dropout probability, and hidden layer sizes. It also sets up the ESM model, dropout layer, and the classifier for token classification.

The forward method defines the forward pass of the model, taking input tensors such as input_ids, attention_mask, position_ids, etc., and returning the token classification output. It computes the logits for token classification based on the sequence_output from the ESM model and calculates the cross-entropy loss if labels are provided. The method allows for returning additional outputs like hidden states and attentions based on the return_dict parameter.

Note

This docstring is a high-level summary and does not include method signatures or implementation details.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
class EsmForTokenClassification(EsmPreTrainedModel):

    """
    EsmForTokenClassification is a class that represents a token classification model based on the ESM
    (Evoformer Sequence Model) architecture. This class extends EsmPreTrainedModel to leverage pre-trained
    weights and configurations for efficient token classification tasks. It includes methods for initializing the model,
    forwarding the forward pass, and computing the token classification loss.

    The __init__ method initializes the EsmForTokenClassification model with configurable parameters such as the number
    of labels, dropout probability, and hidden layer sizes. It also sets up the ESM model, dropout layer, and the
    classifier for token classification.

    The forward method defines the forward pass of the model, taking input tensors such as input_ids, attention_mask,
    position_ids, etc., and returning the token classification output.
    It computes the logits for token classification based on the sequence_output from the ESM model and calculates the
    cross-entropy loss if labels are provided. The method allows for returning additional outputs like hidden states and
    attentions based on the return_dict parameter.

    Note:
        This docstring is a high-level summary and does not include method signatures or implementation details.
    """
    def __init__(self, config):
        """
        Initializes an instance of the EsmForTokenClassification class.

        Args:
            self: The instance of the EsmForTokenClassification class.
            config:
                An instance of the configuration class containing the model configuration parameters.

                - Type: object
                - Purpose: Specifies the configuration settings for the model.
                - Restrictions: Must be a valid instance of the configuration class.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of the correct type.
            ValueError: If the config.num_labels is not provided or is invalid.
            RuntimeError: If an error occurs during the initialization process.
        """
        super().__init__(config)
        self.num_labels = config.num_labels

        self.esm = EsmModel(config, add_pooling_layer=False)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        self.init_weights()

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, TokenClassifierOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.esm(
            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,
        )

        sequence_output = outputs[0]

        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_output)

        loss = None
        if labels is not None:
            loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

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

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

mindnlp.transformers.models.esm.modeling_esm.EsmForTokenClassification.__init__(config)

Initializes an instance of the EsmForTokenClassification class.

PARAMETER DESCRIPTION
self

The instance of the EsmForTokenClassification class.

config

An instance of the configuration class containing the model configuration parameters.

  • Type: object
  • Purpose: Specifies the configuration settings for the model.
  • Restrictions: Must be a valid instance of the configuration class.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of the correct type.

ValueError

If the config.num_labels is not provided or is invalid.

RuntimeError

If an error occurs during the initialization process.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
def __init__(self, config):
    """
    Initializes an instance of the EsmForTokenClassification class.

    Args:
        self: The instance of the EsmForTokenClassification class.
        config:
            An instance of the configuration class containing the model configuration parameters.

            - Type: object
            - Purpose: Specifies the configuration settings for the model.
            - Restrictions: Must be a valid instance of the configuration class.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of the correct type.
        ValueError: If the config.num_labels is not provided or is invalid.
        RuntimeError: If an error occurs during the initialization process.
    """
    super().__init__(config)
    self.num_labels = config.num_labels

    self.esm = EsmModel(config, add_pooling_layer=False)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

    self.init_weights()

mindnlp.transformers.models.esm.modeling_esm.EsmForTokenClassification.forward(input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the token classification loss. Indices should be in [0, ..., config.num_labels - 1].

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\esm\modeling_esm.py
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, TokenClassifierOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.esm(
        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,
    )

    sequence_output = outputs[0]

    sequence_output = self.dropout(sequence_output)
    logits = self.classifier(sequence_output)

    loss = None
    if labels is not None:
        loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

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

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

mindnlp.transformers.models.esm.modeling_esm.EsmModel

Bases: EsmPreTrainedModel

The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in Attention is all you need by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

To behave as an decoder the model needs to be initialized with the is_decoder argument of the configuration set to True. To be used in a Seq2Seq model, the model needs to initialized with both is_decoder argument and add_cross_attention set to True; an encoder_hidden_states is then expected as an input to the forward pass.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
class EsmModel(EsmPreTrainedModel):
    """

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in [Attention is
    all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

    To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
    to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
    `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
    """
    def __init__(self, config, add_pooling_layer=True):
        """
        Initializes an instance of the EsmModel class.

        Args:
            self: The instance of the class.
            config (object): The configuration object containing various settings for the model.
            add_pooling_layer (bool, optional): A flag indicating whether to include a pooling layer in the model.
                Default is True.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.config = config

        self.embeddings = EsmEmbeddings(config)
        self.encoder = EsmEncoder(config)

        self.pooler = EsmPooler(config) if add_pooling_layer else None

        self.contact_head = EsmContactPredictionHead(
            in_features=config.num_hidden_layers * config.num_attention_heads, bias=True
        )

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

    def get_input_embeddings(self):
        """
        This method returns the input embeddings for the ESMM model.

        Args:
            self: An instance of the EsmModel class.

        Returns:
            word_embeddings: This method returns the word embeddings for input data, represented as a tensor.

        Raises:
            None.
        """
        return self.embeddings.word_embeddings

    def set_input_embeddings(self, value):
        """
        Sets the input embeddings for the EsmModel.

        Args:
            self (EsmModel): The instance of the EsmModel class.
            value: The input embeddings to be set. This should be of type `torch.Tensor`.

        Returns:
            None.

        Raises:
            None.
        """
        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: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        encoder_hidden_states: Optional[mindspore.Tensor] = None,
        encoder_attention_mask: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple[mindspore.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
        r"""
        Args:
            encoder_hidden_states  (`mindspore.Tensor` 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 (`mindspore.Tensor` 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(mindspore.Tensor))` 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`).
        """
        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 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.shape
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.shape[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        batch_size, seq_length = input_shape

        # 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 = ops.ones(((batch_size, seq_length + past_key_values_length)))

        # 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: mindspore.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.shape
            encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
            if encoder_attention_mask is None:
                encoder_attention_mask = ops.ones(encoder_hidden_shape)
            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,
        )

    def predict_contacts(self, tokens, attention_mask):
        """
        Predicts contacts using the EsmModel.

        Args:
            self (EsmModel): An instance of the EsmModel class.
            tokens (Tensor): The input tokens for prediction.
            attention_mask (Tensor): The attention mask for the input tokens.

        Returns:
            None.

        Raises:
            None.
        """
        attns = self(tokens, attention_mask=attention_mask, return_dict=True, output_attentions=True).attentions
        attns = ops.stack(attns, dim=1)  # Matches the original model layout
        # In the original model, attentions for padding tokens are completely zeroed out.
        # This makes no difference most of the time because the other tokens won't attend to them,
        # but it does for the contact prediction task, which takes attentions as input,
        # so we have to mimic that here.
        attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(3)
        attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(4)
        return self.contact_head(tokens, attns)

mindnlp.transformers.models.esm.modeling_esm.EsmModel.__init__(config, add_pooling_layer=True)

Initializes an instance of the EsmModel class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object containing various settings for the model.

TYPE: object

add_pooling_layer

A flag indicating whether to include a pooling layer in the model. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
def __init__(self, config, add_pooling_layer=True):
    """
    Initializes an instance of the EsmModel class.

    Args:
        self: The instance of the class.
        config (object): The configuration object containing various settings for the model.
        add_pooling_layer (bool, optional): A flag indicating whether to include a pooling layer in the model.
            Default is True.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.config = config

    self.embeddings = EsmEmbeddings(config)
    self.encoder = EsmEncoder(config)

    self.pooler = EsmPooler(config) if add_pooling_layer else None

    self.contact_head = EsmContactPredictionHead(
        in_features=config.num_hidden_layers * config.num_attention_heads, bias=True
    )

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

mindnlp.transformers.models.esm.modeling_esm.EsmModel.forward(input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
encoder_hidden_states

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.

TYPE: (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional* DEFAULT: None

encoder_attention_mask

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.

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional* DEFAULT: None

use_cache

If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

TYPE: `bool`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    encoder_hidden_states: Optional[mindspore.Tensor] = None,
    encoder_attention_mask: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple[mindspore.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
    r"""
    Args:
        encoder_hidden_states  (`mindspore.Tensor` 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 (`mindspore.Tensor` 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(mindspore.Tensor))` 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`).
    """
    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 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.shape
    elif inputs_embeds is not None:
        input_shape = inputs_embeds.shape[:-1]
    else:
        raise ValueError("You have to specify either input_ids or inputs_embeds")

    batch_size, seq_length = input_shape

    # 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 = ops.ones(((batch_size, seq_length + past_key_values_length)))

    # 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: mindspore.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.shape
        encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
        if encoder_attention_mask is None:
            encoder_attention_mask = ops.ones(encoder_hidden_shape)
        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,
    )

mindnlp.transformers.models.esm.modeling_esm.EsmModel.get_input_embeddings()

This method returns the input embeddings for the ESMM model.

PARAMETER DESCRIPTION
self

An instance of the EsmModel class.

RETURNS DESCRIPTION
word_embeddings

This method returns the word embeddings for input data, represented as a tensor.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
def get_input_embeddings(self):
    """
    This method returns the input embeddings for the ESMM model.

    Args:
        self: An instance of the EsmModel class.

    Returns:
        word_embeddings: This method returns the word embeddings for input data, represented as a tensor.

    Raises:
        None.
    """
    return self.embeddings.word_embeddings

mindnlp.transformers.models.esm.modeling_esm.EsmModel.predict_contacts(tokens, attention_mask)

Predicts contacts using the EsmModel.

PARAMETER DESCRIPTION
self

An instance of the EsmModel class.

TYPE: EsmModel

tokens

The input tokens for prediction.

TYPE: Tensor

attention_mask

The attention mask for the input tokens.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
def predict_contacts(self, tokens, attention_mask):
    """
    Predicts contacts using the EsmModel.

    Args:
        self (EsmModel): An instance of the EsmModel class.
        tokens (Tensor): The input tokens for prediction.
        attention_mask (Tensor): The attention mask for the input tokens.

    Returns:
        None.

    Raises:
        None.
    """
    attns = self(tokens, attention_mask=attention_mask, return_dict=True, output_attentions=True).attentions
    attns = ops.stack(attns, dim=1)  # Matches the original model layout
    # In the original model, attentions for padding tokens are completely zeroed out.
    # This makes no difference most of the time because the other tokens won't attend to them,
    # but it does for the contact prediction task, which takes attentions as input,
    # so we have to mimic that here.
    attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(3)
    attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(4)
    return self.contact_head(tokens, attns)

mindnlp.transformers.models.esm.modeling_esm.EsmModel.set_input_embeddings(value)

Sets the input embeddings for the EsmModel.

PARAMETER DESCRIPTION
self

The instance of the EsmModel class.

TYPE: EsmModel

value

The input embeddings to be set. This should be of type torch.Tensor.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
def set_input_embeddings(self, value):
    """
    Sets the input embeddings for the EsmModel.

    Args:
        self (EsmModel): The instance of the EsmModel class.
        value: The input embeddings to be set. This should be of type `torch.Tensor`.

    Returns:
        None.

    Raises:
        None.
    """
    self.embeddings.word_embeddings = value

mindnlp.transformers.models.esm.modeling_esm.EsmPreTrainedModel

Bases: PreTrainedModel

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

Source code in mindnlp\transformers\models\esm\modeling_esm.py
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
class EsmPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = EsmConfig
    base_model_prefix = "esm"
    supports_gradient_checkpointing = True
    _no_split_modules = ["EsmLayer", "EsmFoldTriangularSelfAttentionBlock", "EsmEmbeddings"]

    # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
    def _init_weights(self, cell):
        """Initialize the weights"""
        if isinstance(cell, nn.Linear):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            cell.weight.set_data(initializer(Normal(self.config.initializer_range),
                                                    cell.weight.shape, cell.weight.dtype))
            if cell.bias is not None:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.Embedding):
            weight = np.random.normal(0.0, self.config.initializer_range, cell.weight.shape)
            if cell.padding_idx:
                weight[cell.padding_idx] = 0

            cell.weight.set_data(Tensor(weight, cell.weight.dtype))
        elif isinstance(cell, nn.LayerNorm):
            cell.weight.set_data(initializer('ones', cell.weight.shape, cell.weight.dtype))
            cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))

mindnlp.transformers.models.esm.modeling_esmfold

MindSpore ESMFold model

mindnlp.transformers.models.esm.modeling_esmfold.EsmCategoricalMixture

EsmCategoricalMixture represents a categorical mixture distribution for probability calculations based on given logits.

This class provides methods for initializing the distribution, calculating the log probability of a given value, and computing the mean of the distribution.

ATTRIBUTE DESCRIPTION
param

The logits parameter for the categorical mixture distribution.

bins

The number of bins for the distribution (default is 50).

start

The starting value for the bins (default is 0).

end

The ending value for the bins (default is 1).

METHOD DESCRIPTION
__init__

Initializes the categorical mixture distribution with the given parameters.

log_prob

Calculates the log probability of a given value within the distribution.

mean

Computes the mean of the categorical mixture distribution.

Note

This class inherits from an unspecified parent class.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
class EsmCategoricalMixture:

    """
    EsmCategoricalMixture represents a categorical mixture distribution for probability calculations based on given logits.

    This class provides methods for initializing the distribution, calculating the log probability of a given value,
    and computing the mean of the distribution.

    Attributes:
        param: The logits parameter for the categorical mixture distribution.
        bins: The number of bins for the distribution (default is 50).
        start: The starting value for the bins (default is 0).
        end: The ending value for the bins (default is 1).

    Methods:
        __init__: Initializes the categorical mixture distribution with the given parameters.
        log_prob: Calculates the log probability of a given value within the distribution.
        mean: Computes the mean of the categorical mixture distribution.

    Note:
        This class inherits from an unspecified parent class.
    """
    def __init__(self, param, bins=50, start=0, end=1):
        """
        Initializes an instance of the EsmCategoricalMixture class.

        Args:
            self: Instance of the EsmCategoricalMixture class.
            param: The logits parameter to be assigned to the instance.
            bins: Number of bins for creating the v_bins attribute. Default is 50.
            start: The starting value for the linspace function. Default is 0.
            end: The ending value for the linspace function. Default is 1.

        Returns:
            None.

        Raises:
            ValueError: If the start value is greater than or equal to the end value.
            TypeError: If the param or bins parameter types are incompatible.
            ValueError: If the bins parameter is less than 1.
        """
        # All tensors are of shape ..., bins.
        self.logits = param
        bins = ops.linspace(start, end, bins + 1).astype(self.logits.dtype)
        self.v_bins = (bins[:-1] + bins[1:]) / 2

    def log_prob(self, true):
        """
        This method calculates the log probability of a given true value in the context of a categorical mixture model.

        Args:
            self: EsmCategoricalMixture
                The instance of the EsmCategoricalMixture class.
            true: torch.Tensor
                The true value for which the log probability needs to be calculated.
                It should be a tensor of shape (batch_size,) where batch_size is the number of samples.
                The true values should be within the range of valid classes for the categorical mixture model.

        Returns:
            None:
                This method does not return any value. The log probability is calculated and stored internally within
                the EsmCategoricalMixture instance.

        Raises:
            ValueError: If the true tensor does not have the expected shape or if it contains values outside the
                range of valid classes for the categorical mixture model.
            IndexError: If the true tensor index is out of bounds.
        """
        # Shapes are:
        #     self.probs: ... x bins
        #     true      : ...
        true_index = (true.unsqueeze(-1) - self.v_bins[[None] * true.ndim]).abs().argmin(-1)
        nll = self.logits.log_softmax(-1)
        return ops.gather_elements(nll, -1, true_index.unsqueeze(-1)).squeeze(-1)

    def mean(self):
        """
        Method 'mean' calculates the mean value of the categorical mixture distribution in the EsmCategoricalMixture class.

        Args:
            self: The instance of the EsmCategoricalMixture class.

        Returns:
            None.

        Raises:
            NotImplementedError: If the method is called without implementing it in a subclass.
            ValueError: If the input data is not in the expected format.
            RuntimeError: If the operation fails due to unforeseen circumstances.
        """
        return (ops.softmax(self.logits, -1) @ self.v_bins.unsqueeze(1)).squeeze(-1)

mindnlp.transformers.models.esm.modeling_esmfold.EsmCategoricalMixture.__init__(param, bins=50, start=0, end=1)

Initializes an instance of the EsmCategoricalMixture class.

PARAMETER DESCRIPTION
self

Instance of the EsmCategoricalMixture class.

param

The logits parameter to be assigned to the instance.

bins

Number of bins for creating the v_bins attribute. Default is 50.

DEFAULT: 50

start

The starting value for the linspace function. Default is 0.

DEFAULT: 0

end

The ending value for the linspace function. Default is 1.

DEFAULT: 1

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the start value is greater than or equal to the end value.

TypeError

If the param or bins parameter types are incompatible.

ValueError

If the bins parameter is less than 1.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
def __init__(self, param, bins=50, start=0, end=1):
    """
    Initializes an instance of the EsmCategoricalMixture class.

    Args:
        self: Instance of the EsmCategoricalMixture class.
        param: The logits parameter to be assigned to the instance.
        bins: Number of bins for creating the v_bins attribute. Default is 50.
        start: The starting value for the linspace function. Default is 0.
        end: The ending value for the linspace function. Default is 1.

    Returns:
        None.

    Raises:
        ValueError: If the start value is greater than or equal to the end value.
        TypeError: If the param or bins parameter types are incompatible.
        ValueError: If the bins parameter is less than 1.
    """
    # All tensors are of shape ..., bins.
    self.logits = param
    bins = ops.linspace(start, end, bins + 1).astype(self.logits.dtype)
    self.v_bins = (bins[:-1] + bins[1:]) / 2

mindnlp.transformers.models.esm.modeling_esmfold.EsmCategoricalMixture.log_prob(true)

This method calculates the log probability of a given true value in the context of a categorical mixture model.

PARAMETER DESCRIPTION
self

EsmCategoricalMixture The instance of the EsmCategoricalMixture class.

true

torch.Tensor The true value for which the log probability needs to be calculated. It should be a tensor of shape (batch_size,) where batch_size is the number of samples. The true values should be within the range of valid classes for the categorical mixture model.

RETURNS DESCRIPTION
None

This method does not return any value. The log probability is calculated and stored internally within the EsmCategoricalMixture instance.

RAISES DESCRIPTION
ValueError

If the true tensor does not have the expected shape or if it contains values outside the range of valid classes for the categorical mixture model.

IndexError

If the true tensor index is out of bounds.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
def log_prob(self, true):
    """
    This method calculates the log probability of a given true value in the context of a categorical mixture model.

    Args:
        self: EsmCategoricalMixture
            The instance of the EsmCategoricalMixture class.
        true: torch.Tensor
            The true value for which the log probability needs to be calculated.
            It should be a tensor of shape (batch_size,) where batch_size is the number of samples.
            The true values should be within the range of valid classes for the categorical mixture model.

    Returns:
        None:
            This method does not return any value. The log probability is calculated and stored internally within
            the EsmCategoricalMixture instance.

    Raises:
        ValueError: If the true tensor does not have the expected shape or if it contains values outside the
            range of valid classes for the categorical mixture model.
        IndexError: If the true tensor index is out of bounds.
    """
    # Shapes are:
    #     self.probs: ... x bins
    #     true      : ...
    true_index = (true.unsqueeze(-1) - self.v_bins[[None] * true.ndim]).abs().argmin(-1)
    nll = self.logits.log_softmax(-1)
    return ops.gather_elements(nll, -1, true_index.unsqueeze(-1)).squeeze(-1)

mindnlp.transformers.models.esm.modeling_esmfold.EsmCategoricalMixture.mean()

Method 'mean' calculates the mean value of the categorical mixture distribution in the EsmCategoricalMixture class.

PARAMETER DESCRIPTION
self

The instance of the EsmCategoricalMixture class.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
NotImplementedError

If the method is called without implementing it in a subclass.

ValueError

If the input data is not in the expected format.

RuntimeError

If the operation fails due to unforeseen circumstances.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
def mean(self):
    """
    Method 'mean' calculates the mean value of the categorical mixture distribution in the EsmCategoricalMixture class.

    Args:
        self: The instance of the EsmCategoricalMixture class.

    Returns:
        None.

    Raises:
        NotImplementedError: If the method is called without implementing it in a subclass.
        ValueError: If the input data is not in the expected format.
        RuntimeError: If the operation fails due to unforeseen circumstances.
    """
    return (ops.softmax(self.logits, -1) @ self.v_bins.unsqueeze(1)).squeeze(-1)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAngleResnet

Bases: Module

Implements Algorithm 20, lines 11-14

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
class EsmFoldAngleResnet(nn.Module):
    """
    Implements Algorithm 20, lines 11-14
    """
    def __init__(self, config):
        '''
        Initializes the EsmFoldAngleResnet class.

        Args:
            self (EsmFoldAngleResnet): The instance of the EsmFoldAngleResnet class.
            config:
                The configuration object containing parameters for the EsmFoldAngleResnet initialization.

                - Type: object
                - Purpose: Specifies the configuration settings for the EsmFoldAngleResnet class.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            None
        '''
        super().__init__()
        self.config = config

        self.linear_in = EsmFoldLinear(config.sequence_dim, config.resnet_dim)
        self.linear_initial = EsmFoldLinear(config.sequence_dim, config.resnet_dim)

        self.layers = nn.ModuleList()
        for _ in range(config.num_resnet_blocks):
            layer = EsmFoldAngleResnetBlock(config)
            self.layers.append(layer)

        self.linear_out = EsmFoldLinear(config.resnet_dim, config.num_angles * 2)

        self.relu = nn.ReLU()

    def forward(self, s: mindspore.Tensor, s_initial: mindspore.Tensor) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
        """
        Args:
            s:
                [*, C_hidden] single embedding
            s_initial:
                [*, C_hidden] single embedding as of the start of the StructureModule
        Returns:
            [*, no_angles, 2] predicted angles
        """
        # NOTE: The ReLU's applied to the inputs are absent from the supplement
        # pseudocode but present in the source. For maximal compatibility with
        # the pretrained weights, I'm going with the source.

        # [*, C_hidden]
        s_initial = self.relu(s_initial)
        s_initial = self.linear_initial(s_initial)
        s = self.relu(s)
        s = self.linear_in(s)
        s = s + s_initial

        for l in self.layers:
            s = l(s)

        s = self.relu(s)

        # [*, no_angles * 2]
        s = self.linear_out(s)

        # [*, no_angles, 2]
        s = s.view(s.shape[:-1] + (-1, 2))

        unnormalized_s = s
        norm_denom = ops.sqrt(
            ops.clamp(
                ops.sum(s**2, dim=-1, keepdim=True),
                min=self.config.epsilon,
            )
        )

        s = s / norm_denom

        return unnormalized_s, s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAngleResnet.__init__(config)

Initializes the EsmFoldAngleResnet class.

PARAMETER DESCRIPTION
self

The instance of the EsmFoldAngleResnet class.

TYPE: EsmFoldAngleResnet

config

The configuration object containing parameters for the EsmFoldAngleResnet initialization.

  • Type: object
  • Purpose: Specifies the configuration settings for the EsmFoldAngleResnet class.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
def __init__(self, config):
    '''
    Initializes the EsmFoldAngleResnet class.

    Args:
        self (EsmFoldAngleResnet): The instance of the EsmFoldAngleResnet class.
        config:
            The configuration object containing parameters for the EsmFoldAngleResnet initialization.

            - Type: object
            - Purpose: Specifies the configuration settings for the EsmFoldAngleResnet class.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        None
    '''
    super().__init__()
    self.config = config

    self.linear_in = EsmFoldLinear(config.sequence_dim, config.resnet_dim)
    self.linear_initial = EsmFoldLinear(config.sequence_dim, config.resnet_dim)

    self.layers = nn.ModuleList()
    for _ in range(config.num_resnet_blocks):
        layer = EsmFoldAngleResnetBlock(config)
        self.layers.append(layer)

    self.linear_out = EsmFoldLinear(config.resnet_dim, config.num_angles * 2)

    self.relu = nn.ReLU()

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAngleResnet.forward(s, s_initial)

PARAMETER DESCRIPTION
s

[*, C_hidden] single embedding

TYPE: Tensor

s_initial

[*, C_hidden] single embedding as of the start of the StructureModule

TYPE: Tensor

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
def forward(self, s: mindspore.Tensor, s_initial: mindspore.Tensor) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
    """
    Args:
        s:
            [*, C_hidden] single embedding
        s_initial:
            [*, C_hidden] single embedding as of the start of the StructureModule
    Returns:
        [*, no_angles, 2] predicted angles
    """
    # NOTE: The ReLU's applied to the inputs are absent from the supplement
    # pseudocode but present in the source. For maximal compatibility with
    # the pretrained weights, I'm going with the source.

    # [*, C_hidden]
    s_initial = self.relu(s_initial)
    s_initial = self.linear_initial(s_initial)
    s = self.relu(s)
    s = self.linear_in(s)
    s = s + s_initial

    for l in self.layers:
        s = l(s)

    s = self.relu(s)

    # [*, no_angles * 2]
    s = self.linear_out(s)

    # [*, no_angles, 2]
    s = s.view(s.shape[:-1] + (-1, 2))

    unnormalized_s = s
    norm_denom = ops.sqrt(
        ops.clamp(
            ops.sum(s**2, dim=-1, keepdim=True),
            min=self.config.epsilon,
        )
    )

    s = s / norm_denom

    return unnormalized_s, s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAngleResnetBlock

Bases: Module

This class represents an EsmFoldAngleResnetBlock, which is a block used in the forwardion of an EsmFold model. It inherits from the nn.Module class.

ATTRIBUTE DESCRIPTION
linear_1

A linear layer used in the block, initialized with a rectified linear unit (ReLU) activation function.

TYPE: EsmFoldLinear

linear_2

Another linear layer used in the block, initialized with a final activation function.

TYPE: EsmFoldLinear

relu

An instance of the ReLU activation function.

TYPE: ReLU

METHOD DESCRIPTION
__init__

Initializes the EsmFoldAngleResnetBlock with the given configuration.

forward

Constructs the EsmFoldAngleResnetBlock using the input tensor.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
class EsmFoldAngleResnetBlock(nn.Module):

    """
    This class represents an EsmFoldAngleResnetBlock, which is a block used in the forwardion of an EsmFold model.
    It inherits from the nn.Module class.

    Attributes:
        linear_1 (EsmFoldLinear):
            A linear layer used in the block, initialized with a rectified linear unit (ReLU) activation function.
        linear_2 (EsmFoldLinear):
            Another linear layer used in the block, initialized with a final activation function.
        relu (nn.ReLU): An instance of the ReLU activation function.

    Methods:
        __init__: Initializes the EsmFoldAngleResnetBlock with the given configuration.
        forward: Constructs the EsmFoldAngleResnetBlock using the input tensor.

    """
    def __init__(self, config):
        """
        Initializes an EsmFoldAngleResnetBlock object.

        Args:
            self (EsmFoldAngleResnetBlock): The current instance of the EsmFoldAngleResnetBlock class.
            config (object):
                A configuration object containing the parameters for initializing the EsmFoldAngleResnetBlock.

                - resnet_dim (int): The dimension of the resnet block.
                - init (str): The initialization method for the linear layers. Possible values are 'relu' and 'final'.

        Returns:
            None.

        Raises:
            TypeError: If the provided config object is not of the expected type.
            ValueError: If the config object does not contain the required parameters.
        """
        super().__init__()

        self.linear_1 = EsmFoldLinear(config.resnet_dim, config.resnet_dim, init="relu")
        self.linear_2 = EsmFoldLinear(config.resnet_dim, config.resnet_dim, init="final")

        self.relu = nn.ReLU()

    def forward(self, a: mindspore.Tensor) -> mindspore.Tensor:
        """
        This method forwards a computation graph for the EsmFoldAngleResnetBlock.

        Args:
            self (EsmFoldAngleResnetBlock): The instance of the EsmFoldAngleResnetBlock class.
            a (mindspore.Tensor): The input tensor for the computation graph.

        Returns:
            mindspore.Tensor: The output tensor resulting from the computation graph.

        Raises:
            None
        """
        s_initial = a

        a = self.relu(a)
        a = self.linear_1(a)
        a = self.relu(a)
        a = self.linear_2(a)

        return a + s_initial

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAngleResnetBlock.__init__(config)

Initializes an EsmFoldAngleResnetBlock object.

PARAMETER DESCRIPTION
self

The current instance of the EsmFoldAngleResnetBlock class.

TYPE: EsmFoldAngleResnetBlock

config

A configuration object containing the parameters for initializing the EsmFoldAngleResnetBlock.

  • resnet_dim (int): The dimension of the resnet block.
  • init (str): The initialization method for the linear layers. Possible values are 'relu' and 'final'.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the provided config object is not of the expected type.

ValueError

If the config object does not contain the required parameters.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
def __init__(self, config):
    """
    Initializes an EsmFoldAngleResnetBlock object.

    Args:
        self (EsmFoldAngleResnetBlock): The current instance of the EsmFoldAngleResnetBlock class.
        config (object):
            A configuration object containing the parameters for initializing the EsmFoldAngleResnetBlock.

            - resnet_dim (int): The dimension of the resnet block.
            - init (str): The initialization method for the linear layers. Possible values are 'relu' and 'final'.

    Returns:
        None.

    Raises:
        TypeError: If the provided config object is not of the expected type.
        ValueError: If the config object does not contain the required parameters.
    """
    super().__init__()

    self.linear_1 = EsmFoldLinear(config.resnet_dim, config.resnet_dim, init="relu")
    self.linear_2 = EsmFoldLinear(config.resnet_dim, config.resnet_dim, init="final")

    self.relu = nn.ReLU()

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAngleResnetBlock.forward(a)

This method forwards a computation graph for the EsmFoldAngleResnetBlock.

PARAMETER DESCRIPTION
self

The instance of the EsmFoldAngleResnetBlock class.

TYPE: EsmFoldAngleResnetBlock

a

The input tensor for the computation graph.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The output tensor resulting from the computation graph.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
def forward(self, a: mindspore.Tensor) -> mindspore.Tensor:
    """
    This method forwards a computation graph for the EsmFoldAngleResnetBlock.

    Args:
        self (EsmFoldAngleResnetBlock): The instance of the EsmFoldAngleResnetBlock class.
        a (mindspore.Tensor): The input tensor for the computation graph.

    Returns:
        mindspore.Tensor: The output tensor resulting from the computation graph.

    Raises:
        None
    """
    s_initial = a

    a = self.relu(a)
    a = self.linear_1(a)
    a = self.relu(a)
    a = self.linear_2(a)

    return a + s_initial

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAttention

Bases: Module

Standard multi-head attention using AlphaFold's default layer initialization. Allows multiple bias vectors.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
391
392
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
455
456
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
class EsmFoldAttention(nn.Module):
    """
    Standard multi-head attention using AlphaFold's default layer initialization. Allows multiple bias vectors.
    """
    def __init__(
        self,
        c_q: int,
        c_k: int,
        c_v: int,
        c_hidden: int,
        no_heads: int,
        gating: bool = True,
    ):
        """
        Args:
            c_q:
                Input dimension of query data
            c_k:
                Input dimension of key data
            c_v:
                Input dimension of value data
            c_hidden:
                Per-head hidden dimension
            no_heads:
                Number of attention heads
            gating:
                Whether the output should be gated using query data
        """
        super().__init__()

        self.c_q = c_q
        self.c_k = c_k
        self.c_v = c_v
        self.c_hidden = c_hidden
        self.no_heads = no_heads
        self.gating = gating

        # DISCREPANCY: c_hidden is not the per-head channel dimension, as
        # stated in the supplement, but the overall channel dimension.

        self.linear_q = EsmFoldLinear(self.c_q, self.c_hidden * self.no_heads, bias=False, init="glorot")
        self.linear_k = EsmFoldLinear(self.c_k, self.c_hidden * self.no_heads, bias=False, init="glorot")
        self.linear_v = EsmFoldLinear(self.c_v, self.c_hidden * self.no_heads, bias=False, init="glorot")
        self.linear_o = EsmFoldLinear(self.c_hidden * self.no_heads, self.c_q, init="final")

        self.linear_g = None
        if self.gating:
            self.linear_g = EsmFoldLinear(self.c_q, self.c_hidden * self.no_heads, init="gating")

        self.sigmoid = nn.Sigmoid()

    def _prep_qkv(self, q_x: mindspore.Tensor, kv_x: mindspore.Tensor) -> Tuple[mindspore.Tensor, mindspore.Tensor, mindspore.Tensor]:
        """
        Prepares the query, key, and value tensors for the EsmFoldAttention module.

        Args:
            self (EsmFoldAttention): The instance of the EsmFoldAttention module.
            q_x (mindspore.Tensor): The query tensor.
                It should have a shape of (batch_size, seq_length, hidden_size).
            kv_x (mindspore.Tensor): The key-value tensor.
                It should have a shape of (batch_size, seq_length, hidden_size).

        Returns:
            Tuple[mindspore.Tensor, mindspore.Tensor, mindspore.Tensor]:
                A tuple containing the query, key, and value tensors.

                - q: The transformed query tensor with a shape of (batch_size, seq_length, no_heads, hidden_size//no_heads).
                - k: The transformed key tensor with a shape of (batch_size, seq_length, no_heads, hidden_size//no_heads).
                - v: The transformed value tensor with a shape of (batch_size, seq_length, no_heads, hidden_size//no_heads).

        Raises:
            None.
        """
        # [*, Q/K/V, H * C_hidden]
        q = self.linear_q(q_x)
        k = self.linear_k(kv_x)
        v = self.linear_v(kv_x)

        # [*, Q/K, H, C_hidden]
        q = q.view(q.shape[:-1] + (self.no_heads, -1))
        k = k.view(k.shape[:-1] + (self.no_heads, -1))
        v = v.view(v.shape[:-1] + (self.no_heads, -1))

        # [*, H, Q/K, C_hidden]
        q = q.swapaxes(-2, -3)
        k = k.swapaxes(-2, -3)
        v = v.swapaxes(-2, -3)

        q /= math.sqrt(self.c_hidden)

        return q, k, v

    def _wrap_up(self, o: mindspore.Tensor, q_x: mindspore.Tensor) -> mindspore.Tensor:
        """
        This method '_wrap_up' in the class 'EsmFoldAttention' performs a wrapping up operation on the input tensors.

        Args:
            self: An instance of the 'EsmFoldAttention' class.
            o (mindspore.Tensor): Input tensor representing the output from previous layers.
                Shape should be compatible with the subsequent operations.
            q_x (mindspore.Tensor): Input tensor representing the query tensor.
                Shape should be compatible with the subsequent operations.

        Returns:
            mindspore.Tensor: A tensor resulting from the wrapping up operation.
                The shape and content of the tensor depend on the operations performed within the method.

        Raises:
            No specific exceptions are documented to be raised by this method under normal operation.
        """
        if self.linear_g is not None:
            g = self.sigmoid(self.linear_g(q_x))

            # [*, Q, H, C_hidden]
            g = g.view(g.shape[:-1] + (self.no_heads, -1))
            o = o * g

        # [*, Q, H * C_hidden]
        o = flatten_final_dims(o, 2)

        # [*, Q, C_q]
        o = self.linear_o(o)

        return o

    def forward(
        self,
        q_x: mindspore.Tensor,
        kv_x: mindspore.Tensor,
        biases: Optional[List[mindspore.Tensor]] = None,
        use_memory_efficient_kernel: bool = False,
        use_lma: bool = False,
        lma_q_chunk_size: int = 1024,
        lma_kv_chunk_size: int = 4096,
        use_flash: bool = False,
        flash_mask: Optional[mindspore.Tensor] = None,
    ) -> mindspore.Tensor:
        """
        Args:
            q_x:
                [*, Q, C_q] query data
            kv_x:
                [*, K, C_k] key data
            biases:
                List of biases that broadcast to [*, H, Q, K]
            use_memory_efficient_kernel:
                Whether to use a custom memory-efficient attention kernel. This should be the default choice for most.
                If none of the "use_<...>" flags are True, a stock PyTorch implementation is used instead
            use_lma:
                Whether to use low-memory attention (Staats & Rabe 2021). If none of the "use_<...>" flags are True, a
                stock PyTorch implementation is used instead
            lma_q_chunk_size:
                Query chunk size (for LMA)
            lma_kv_chunk_size:
                Key/Value chunk size (for LMA)
        Returns
            [*, Q, C_q] attention update
        """
        if use_lma and (lma_q_chunk_size is None or lma_kv_chunk_size is None):
            raise ValueError("If use_lma is specified, lma_q_chunk_size and lma_kv_chunk_size must be provided")

        if use_flash and biases is not None:
            raise ValueError("use_flash is incompatible with the bias option. For masking, use flash_mask instead")

        attn_options = [use_memory_efficient_kernel, use_lma, use_flash]
        if sum(attn_options) > 1:
            raise ValueError("Choose at most one alternative attention algorithm")

        if biases is None:
            biases = []

        # [*, H, Q/K, C_hidden]
        query, key, value = self._prep_qkv(q_x, kv_x)
        key = permute_final_dims(key, (1, 0))

        # [*, H, Q, K]
        output = ops.matmul(query, key)
        for b in biases:
            output += b
        output = softmax_no_cast(output, -1)

        # [*, H, Q, C_hidden]
        output = ops.matmul(output, value)
        output = output.swapaxes(-2, -3)
        output = self._wrap_up(output, q_x)

        return output

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAttention.__init__(c_q, c_k, c_v, c_hidden, no_heads, gating=True)

PARAMETER DESCRIPTION
c_q

Input dimension of query data

TYPE: int

c_k

Input dimension of key data

TYPE: int

c_v

Input dimension of value data

TYPE: int

c_hidden

Per-head hidden dimension

TYPE: int

no_heads

Number of attention heads

TYPE: int

gating

Whether the output should be gated using query data

TYPE: bool DEFAULT: True

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
391
392
393
394
395
396
397
def __init__(
    self,
    c_q: int,
    c_k: int,
    c_v: int,
    c_hidden: int,
    no_heads: int,
    gating: bool = True,
):
    """
    Args:
        c_q:
            Input dimension of query data
        c_k:
            Input dimension of key data
        c_v:
            Input dimension of value data
        c_hidden:
            Per-head hidden dimension
        no_heads:
            Number of attention heads
        gating:
            Whether the output should be gated using query data
    """
    super().__init__()

    self.c_q = c_q
    self.c_k = c_k
    self.c_v = c_v
    self.c_hidden = c_hidden
    self.no_heads = no_heads
    self.gating = gating

    # DISCREPANCY: c_hidden is not the per-head channel dimension, as
    # stated in the supplement, but the overall channel dimension.

    self.linear_q = EsmFoldLinear(self.c_q, self.c_hidden * self.no_heads, bias=False, init="glorot")
    self.linear_k = EsmFoldLinear(self.c_k, self.c_hidden * self.no_heads, bias=False, init="glorot")
    self.linear_v = EsmFoldLinear(self.c_v, self.c_hidden * self.no_heads, bias=False, init="glorot")
    self.linear_o = EsmFoldLinear(self.c_hidden * self.no_heads, self.c_q, init="final")

    self.linear_g = None
    if self.gating:
        self.linear_g = EsmFoldLinear(self.c_q, self.c_hidden * self.no_heads, init="gating")

    self.sigmoid = nn.Sigmoid()

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldAttention.forward(q_x, kv_x, biases=None, use_memory_efficient_kernel=False, use_lma=False, lma_q_chunk_size=1024, lma_kv_chunk_size=4096, use_flash=False, flash_mask=None)

PARAMETER DESCRIPTION
q_x

[*, Q, C_q] query data

TYPE: Tensor

kv_x

[*, K, C_k] key data

TYPE: Tensor

biases

List of biases that broadcast to [*, H, Q, K]

TYPE: Optional[List[Tensor]] DEFAULT: None

use_memory_efficient_kernel

Whether to use a custom memory-efficient attention kernel. This should be the default choice for most. If none of the "use_<...>" flags are True, a stock PyTorch implementation is used instead

TYPE: bool DEFAULT: False

use_lma

Whether to use low-memory attention (Staats & Rabe 2021). If none of the "use_<...>" flags are True, a stock PyTorch implementation is used instead

TYPE: bool DEFAULT: False

lma_q_chunk_size

Query chunk size (for LMA)

TYPE: int DEFAULT: 1024

lma_kv_chunk_size

Key/Value chunk size (for LMA)

TYPE: int DEFAULT: 4096

Returns [*, Q, C_q] attention update

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
def forward(
    self,
    q_x: mindspore.Tensor,
    kv_x: mindspore.Tensor,
    biases: Optional[List[mindspore.Tensor]] = None,
    use_memory_efficient_kernel: bool = False,
    use_lma: bool = False,
    lma_q_chunk_size: int = 1024,
    lma_kv_chunk_size: int = 4096,
    use_flash: bool = False,
    flash_mask: Optional[mindspore.Tensor] = None,
) -> mindspore.Tensor:
    """
    Args:
        q_x:
            [*, Q, C_q] query data
        kv_x:
            [*, K, C_k] key data
        biases:
            List of biases that broadcast to [*, H, Q, K]
        use_memory_efficient_kernel:
            Whether to use a custom memory-efficient attention kernel. This should be the default choice for most.
            If none of the "use_<...>" flags are True, a stock PyTorch implementation is used instead
        use_lma:
            Whether to use low-memory attention (Staats & Rabe 2021). If none of the "use_<...>" flags are True, a
            stock PyTorch implementation is used instead
        lma_q_chunk_size:
            Query chunk size (for LMA)
        lma_kv_chunk_size:
            Key/Value chunk size (for LMA)
    Returns
        [*, Q, C_q] attention update
    """
    if use_lma and (lma_q_chunk_size is None or lma_kv_chunk_size is None):
        raise ValueError("If use_lma is specified, lma_q_chunk_size and lma_kv_chunk_size must be provided")

    if use_flash and biases is not None:
        raise ValueError("use_flash is incompatible with the bias option. For masking, use flash_mask instead")

    attn_options = [use_memory_efficient_kernel, use_lma, use_flash]
    if sum(attn_options) > 1:
        raise ValueError("Choose at most one alternative attention algorithm")

    if biases is None:
        biases = []

    # [*, H, Q/K, C_hidden]
    query, key, value = self._prep_qkv(q_x, kv_x)
    key = permute_final_dims(key, (1, 0))

    # [*, H, Q, K]
    output = ops.matmul(query, key)
    for b in biases:
        output += b
    output = softmax_no_cast(output, -1)

    # [*, H, Q, C_hidden]
    output = ops.matmul(output, value)
    output = output.swapaxes(-2, -3)
    output = self._wrap_up(output, q_x)

    return output

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldBackboneUpdate

Bases: Module

Implements part of Algorithm 23.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
class EsmFoldBackboneUpdate(nn.Module):
    """
    Implements part of Algorithm 23.
    """
    def __init__(self, config):
        """
        Initializes the EsmFoldBackboneUpdate class.

        Args:
            self: The instance of the class.
            config: A dictionary containing configuration parameters for the backbone update.
                It should include the 'sequence_dim' parameter representing the dimension of the input sequence.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided or is not a dictionary.
            ValueError: If the 'sequence_dim' parameter is missing in the config dictionary.
            ValueError: If the 'sequence_dim' parameter in the config dictionary is not a positive integer.
        """
        super().__init__()

        self.linear = EsmFoldLinear(config.sequence_dim, 6, init="final")

    def forward(self, s: mindspore.Tensor) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
        """
        Args:
            [*, N_res, C_s] single representation
        Returns:
            [*, N_res, 6] update vector
        """
        # [*, 6]
        update = self.linear(s)

        return update

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldBackboneUpdate.__init__(config)

Initializes the EsmFoldBackboneUpdate class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

A dictionary containing configuration parameters for the backbone update. It should include the 'sequence_dim' parameter representing the dimension of the input sequence.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided or is not a dictionary.

ValueError

If the 'sequence_dim' parameter is missing in the config dictionary.

ValueError

If the 'sequence_dim' parameter in the config dictionary is not a positive integer.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
def __init__(self, config):
    """
    Initializes the EsmFoldBackboneUpdate class.

    Args:
        self: The instance of the class.
        config: A dictionary containing configuration parameters for the backbone update.
            It should include the 'sequence_dim' parameter representing the dimension of the input sequence.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided or is not a dictionary.
        ValueError: If the 'sequence_dim' parameter is missing in the config dictionary.
        ValueError: If the 'sequence_dim' parameter in the config dictionary is not a positive integer.
    """
    super().__init__()

    self.linear = EsmFoldLinear(config.sequence_dim, 6, init="final")

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldBackboneUpdate.forward(s)

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
def forward(self, s: mindspore.Tensor) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
    """
    Args:
        [*, N_res, C_s] single representation
    Returns:
        [*, N_res, 6] update vector
    """
    # [*, 6]
    update = self.linear(s)

    return update

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldDropout

Bases: Module

Implementation of dropout with the ability to share the dropout mask along a particular dimension.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
class EsmFoldDropout(nn.Module):
    """
    Implementation of dropout with the ability to share the dropout mask along a particular dimension.
    """
    def __init__(self, r: float, batch_dim: Union[int, List[int]]):
        """
        Initializes an instance of the EsmFoldDropout class.

        Args:
            self: The instance of the class.
            r (float): The dropout rate value.
            batch_dim (Union[int, List[int]]):
                The dimension(s) of the input batch.
                If an integer is provided, it will be converted to a list with that integer as the only element.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()

        self.r = r
        if isinstance(batch_dim, int):
            batch_dim = [batch_dim]
        self.batch_dim = batch_dim
        self.dropout = nn.Dropout(p=self.r)

    def forward(self, x: mindspore.Tensor) -> mindspore.Tensor:
        """
        This method forwards a modified tensor with dropout for the EsmFoldDropout class.

        Args:
            self: An instance of the EsmFoldDropout class.
            x (mindspore.Tensor): The input tensor for which the modified tensor is forwarded.

        Returns:
            mindspore.Tensor: Returns a new tensor, which is the result of applying dropout to the input tensor.

        Raises:
            TypeError: If the input x is not of type mindspore.Tensor.
            ValueError: If the shape manipulation encounters an error during the forwardion process.
            RuntimeError: If there is a runtime issue during the execution of the method.
        """
        shape = list(x.shape)
        if self.batch_dim is not None:
            for bd in self.batch_dim:
                shape[bd] = 1
        return x * self.dropout(x.new_ones(shape))

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldDropout.__init__(r, batch_dim)

Initializes an instance of the EsmFoldDropout class.

PARAMETER DESCRIPTION
self

The instance of the class.

r

The dropout rate value.

TYPE: float

batch_dim

The dimension(s) of the input batch. If an integer is provided, it will be converted to a list with that integer as the only element.

TYPE: Union[int, List[int]]

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
def __init__(self, r: float, batch_dim: Union[int, List[int]]):
    """
    Initializes an instance of the EsmFoldDropout class.

    Args:
        self: The instance of the class.
        r (float): The dropout rate value.
        batch_dim (Union[int, List[int]]):
            The dimension(s) of the input batch.
            If an integer is provided, it will be converted to a list with that integer as the only element.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()

    self.r = r
    if isinstance(batch_dim, int):
        batch_dim = [batch_dim]
    self.batch_dim = batch_dim
    self.dropout = nn.Dropout(p=self.r)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldDropout.forward(x)

This method forwards a modified tensor with dropout for the EsmFoldDropout class.

PARAMETER DESCRIPTION
self

An instance of the EsmFoldDropout class.

x

The input tensor for which the modified tensor is forwarded.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: Returns a new tensor, which is the result of applying dropout to the input tensor.

RAISES DESCRIPTION
TypeError

If the input x is not of type mindspore.Tensor.

ValueError

If the shape manipulation encounters an error during the forwardion process.

RuntimeError

If there is a runtime issue during the execution of the method.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
def forward(self, x: mindspore.Tensor) -> mindspore.Tensor:
    """
    This method forwards a modified tensor with dropout for the EsmFoldDropout class.

    Args:
        self: An instance of the EsmFoldDropout class.
        x (mindspore.Tensor): The input tensor for which the modified tensor is forwarded.

    Returns:
        mindspore.Tensor: Returns a new tensor, which is the result of applying dropout to the input tensor.

    Raises:
        TypeError: If the input x is not of type mindspore.Tensor.
        ValueError: If the shape manipulation encounters an error during the forwardion process.
        RuntimeError: If there is a runtime issue during the execution of the method.
    """
    shape = list(x.shape)
    if self.batch_dim is not None:
        for bd in self.batch_dim:
            shape[bd] = 1
    return x * self.dropout(x.new_ones(shape))

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldInvariantPointAttention

Bases: Module

Implements Algorithm 22.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
class EsmFoldInvariantPointAttention(nn.Module):
    """
    Implements Algorithm 22.
    """
    def __init__(self, config):
        '''
        Initializes an instance of the EsmFoldInvariantPointAttention class.

        Args:
            self: The instance of the class.
            config: An object containing the configuration settings.

        Returns:
            None

        Raises:
            None

        Description:
            This method initializes the EsmFoldInvariantPointAttention instance by setting various parameters and
            creating necessary objects.

        Parameters:
            self: The instance of the class.
            config: An object containing the configuration settings.

        The config object must have the following attributes:

        - sequence_dim: An integer representing the dimension of the sequence.
        - pairwise_dim: An integer representing the dimension of the pairwise data.
        - ipa_dim: An integer representing the dimension of the ipa data.
        - num_heads_ipa: An integer representing the number of heads for the ipa.
        - num_qk_points: An integer representing the number of query and key points.
        - num_v_points: An integer representing the number of value points.

        Attributes:
            hidden_dim: An integer representing the ipa dimension.
            num_heads: An integer representing the number of ipa heads.
            num_qk_points: An integer representing the number of query and key points.
            num_v_points: An integer representing the number of value points.
            linear_q: An instance of the EsmFoldLinear class with input dimension c_s and output dimension hc.
            linear_kv: An instance of the EsmFoldLinear class with input dimension c_s and output dimension 2 * hc.
            linear_q_points: An instance of the EsmFoldLinear class with input dimension c_s and output dimension hpq.
            linear_kv_points: An instance of the EsmFoldLinear class with input dimension c_s and output dimension hpkv.
            linear_b: An instance of the EsmFoldLinear class with input dimension c_z and output dimension num_heads_ipa.
            head_weights: A Parameter object representing the weights of the ipa heads.
            linear_out: An instance of the EsmFoldLinear class with input dimension concat_out_dim and output dimension c_s.
            softmax: An instance of the Softmax class used for softmax activation.
            softplus: An instance of the Softplus class used for softplus activation.
        '''
        super().__init__()
        self.config = config

        c_s = config.sequence_dim
        c_z = config.pairwise_dim
        self.hidden_dim = config.ipa_dim
        self.num_heads = config.num_heads_ipa
        self.num_qk_points = config.num_qk_points
        self.num_v_points = config.num_v_points

        # These linear layers differ from their specifications in the
        # supplement. There, they lack bias and use Glorot initialization.
        # Here as in the official source, they have bias and use the default
        # Lecun initialization.
        hc = config.ipa_dim * config.num_heads_ipa
        self.linear_q = EsmFoldLinear(c_s, hc)
        self.linear_kv = EsmFoldLinear(c_s, 2 * hc)

        hpq = config.num_heads_ipa * config.num_qk_points * 3
        self.linear_q_points = EsmFoldLinear(c_s, hpq)

        hpkv = config.num_heads_ipa * (config.num_qk_points + config.num_v_points) * 3
        self.linear_kv_points = EsmFoldLinear(c_s, hpkv)

        self.linear_b = EsmFoldLinear(c_z, config.num_heads_ipa)

        self.head_weights = Parameter(ops.zeros((config.num_heads_ipa)))

        concat_out_dim = config.num_heads_ipa * (c_z + config.ipa_dim + config.num_v_points * 4)
        self.linear_out = EsmFoldLinear(concat_out_dim, c_s, init="final")

        self.softmax = nn.Softmax(dim=-1)
        self.softplus = nn.Softplus()

    def forward(
        self,
        s: mindspore.Tensor,
        z: Optional[mindspore.Tensor],
        r: Rigid,
        mask: mindspore.Tensor,
    ) -> mindspore.Tensor:
        """
        Args:
            s:
                [*, N_res, C_s] single representation
            z:
                [*, N_res, N_res, C_z] pair representation
            r:
                [*, N_res] transformation object
            mask:
                [*, N_res] mask
        Returns:
            [*, N_res, C_s] single representation update
        """
        z = [z]

        #######################################
        # Generate scalar and point activations
        #######################################
        # [*, N_res, H * C_hidden]
        q = self.linear_q(s)
        kv = self.linear_kv(s)

        # [*, N_res, H, C_hidden]
        q = q.view(q.shape[:-1] + (self.num_heads, -1))

        # [*, N_res, H, 2 * C_hidden]
        kv = kv.view(kv.shape[:-1] + (self.num_heads, -1))

        # [*, N_res, H, C_hidden]
        k, v = ops.split(kv, self.hidden_dim, dim=-1)

        # [*, N_res, H * P_q * 3]
        q_pts = self.linear_q_points(s)

        # This is kind of clunky, but it's how the original does it
        # [*, N_res, H * P_q, 3]
        q_pts = ops.split(q_pts, q_pts.shape[-1] // 3, dim=-1)
        q_pts = ops.stack(q_pts, dim=-1)
        q_pts = r[..., None].apply(q_pts)

        # [*, N_res, H, P_q, 3]
        q_pts = q_pts.view(q_pts.shape[:-2] + (self.num_heads, self.num_qk_points, 3))

        # [*, N_res, H * (P_q + P_v) * 3]
        kv_pts = self.linear_kv_points(s)

        # [*, N_res, H * (P_q + P_v), 3]
        kv_pts = ops.split(kv_pts, kv_pts.shape[-1] // 3, dim=-1)
        kv_pts = ops.stack(kv_pts, dim=-1)
        kv_pts = r[..., None].apply(kv_pts)

        # [*, N_res, H, (P_q + P_v), 3]
        kv_pts = kv_pts.view(kv_pts.shape[:-2] + (self.num_heads, -1, 3))

        # [*, N_res, H, P_q/P_v, 3]
        k_pts, v_pts = ops.split(kv_pts, [self.num_qk_points, self.num_v_points], dim=-2)

        ##########################
        # Compute attention scores
        ##########################
        # [*, N_res, N_res, H]
        b = self.linear_b(z[0])
        # [*, H, N_res, N_res]
        a = ops.matmul(
            permute_final_dims(q, (1, 0, 2)),  # [*, H, N_res, C_hidden]
            permute_final_dims(k, (1, 2, 0)),  # [*, H, C_hidden, N_res]
        )

        a *= math.sqrt(1.0 / (3 * self.hidden_dim))
        a += math.sqrt(1.0 / 3) * permute_final_dims(b, (2, 0, 1))

        # [*, N_res, N_res, H, P_q, 3]
        pt_att = q_pts.unsqueeze(-4) - k_pts.unsqueeze(-5)
        pt_att = pt_att**2

        # [*, N_res, N_res, H, P_q]
        pt_att = sum(ops.unbind(pt_att, dim=-1))
        head_weights = self.softplus(self.head_weights).view(*((1,) * len(pt_att.shape[:-2]) + (-1, 1)))
        head_weights = head_weights * math.sqrt(1.0 / (3 * (self.num_qk_points * 9.0 / 2)))
        pt_att = pt_att * head_weights

        # [*, N_res, N_res, H]
        pt_att = ops.sum(pt_att, dim=-1) * (-0.5)
        # [*, N_res, N_res]
        square_mask = mask.unsqueeze(-1) * mask.unsqueeze(-2)
        square_mask = self.config.inf * (square_mask - 1)

        # [*, H, N_res, N_res]
        pt_att = permute_final_dims(pt_att, (2, 0, 1))

        a = a + pt_att
        a = a + square_mask.unsqueeze(-3)
        a = self.softmax(a)

        ################
        # Compute output
        ################
        # [*, N_res, H, C_hidden]
        o = ops.matmul(a, v.swapaxes(-2, -3).to(dtype=a.dtype)).swapaxes(-2, -3)

        # [*, N_res, H * C_hidden]
        o = flatten_final_dims(o, 2)

        # [*, H, 3, N_res, P_v]
        o_pt = ops.sum(
            (a[..., None, :, :, None] * permute_final_dims(v_pts, (1, 3, 0, 2))[..., None, :, :]),
            dim=-2,
        )

        # [*, N_res, H, P_v, 3]
        o_pt = permute_final_dims(o_pt, (2, 0, 3, 1))
        o_pt = r[..., None, None].invert_apply(o_pt)

        # [*, N_res, H * P_v]
        o_pt_norm = flatten_final_dims(ops.sqrt(ops.sum(o_pt**2, dim=-1) + self.config.epsilon), 2)

        # [*, N_res, H * P_v, 3]
        o_pt = o_pt.reshape(*o_pt.shape[:-3], -1, 3)

        # [*, N_res, H, C_z]
        o_pair = ops.matmul(a.swapaxes(-2, -3), z[0].to(dtype=a.dtype))

        # [*, N_res, H * C_z]
        o_pair = flatten_final_dims(o_pair, 2)

        # [*, N_res, C_s]
        s = self.linear_out(
            ops.cat((o, *ops.unbind(o_pt, dim=-1), o_pt_norm, o_pair), dim=-1).to(dtype=z[0].dtype)
        )

        return s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldInvariantPointAttention.__init__(config)

Initializes an instance of the EsmFoldInvariantPointAttention class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration settings.

RETURNS DESCRIPTION

None

Description

This method initializes the EsmFoldInvariantPointAttention instance by setting various parameters and creating necessary objects.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration settings.

The config object must have the following attributes:

  • sequence_dim: An integer representing the dimension of the sequence.
  • pairwise_dim: An integer representing the dimension of the pairwise data.
  • ipa_dim: An integer representing the dimension of the ipa data.
  • num_heads_ipa: An integer representing the number of heads for the ipa.
  • num_qk_points: An integer representing the number of query and key points.
  • num_v_points: An integer representing the number of value points.
ATTRIBUTE DESCRIPTION
hidden_dim

An integer representing the ipa dimension.

num_heads

An integer representing the number of ipa heads.

num_qk_points

An integer representing the number of query and key points.

num_v_points

An integer representing the number of value points.

linear_q

An instance of the EsmFoldLinear class with input dimension c_s and output dimension hc.

linear_kv

An instance of the EsmFoldLinear class with input dimension c_s and output dimension 2 * hc.

linear_q_points

An instance of the EsmFoldLinear class with input dimension c_s and output dimension hpq.

linear_kv_points

An instance of the EsmFoldLinear class with input dimension c_s and output dimension hpkv.

linear_b

An instance of the EsmFoldLinear class with input dimension c_z and output dimension num_heads_ipa.

head_weights

A Parameter object representing the weights of the ipa heads.

linear_out

An instance of the EsmFoldLinear class with input dimension concat_out_dim and output dimension c_s.

softmax

An instance of the Softmax class used for softmax activation.

softplus

An instance of the Softplus class used for softplus activation.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
def __init__(self, config):
    '''
    Initializes an instance of the EsmFoldInvariantPointAttention class.

    Args:
        self: The instance of the class.
        config: An object containing the configuration settings.

    Returns:
        None

    Raises:
        None

    Description:
        This method initializes the EsmFoldInvariantPointAttention instance by setting various parameters and
        creating necessary objects.

    Parameters:
        self: The instance of the class.
        config: An object containing the configuration settings.

    The config object must have the following attributes:

    - sequence_dim: An integer representing the dimension of the sequence.
    - pairwise_dim: An integer representing the dimension of the pairwise data.
    - ipa_dim: An integer representing the dimension of the ipa data.
    - num_heads_ipa: An integer representing the number of heads for the ipa.
    - num_qk_points: An integer representing the number of query and key points.
    - num_v_points: An integer representing the number of value points.

    Attributes:
        hidden_dim: An integer representing the ipa dimension.
        num_heads: An integer representing the number of ipa heads.
        num_qk_points: An integer representing the number of query and key points.
        num_v_points: An integer representing the number of value points.
        linear_q: An instance of the EsmFoldLinear class with input dimension c_s and output dimension hc.
        linear_kv: An instance of the EsmFoldLinear class with input dimension c_s and output dimension 2 * hc.
        linear_q_points: An instance of the EsmFoldLinear class with input dimension c_s and output dimension hpq.
        linear_kv_points: An instance of the EsmFoldLinear class with input dimension c_s and output dimension hpkv.
        linear_b: An instance of the EsmFoldLinear class with input dimension c_z and output dimension num_heads_ipa.
        head_weights: A Parameter object representing the weights of the ipa heads.
        linear_out: An instance of the EsmFoldLinear class with input dimension concat_out_dim and output dimension c_s.
        softmax: An instance of the Softmax class used for softmax activation.
        softplus: An instance of the Softplus class used for softplus activation.
    '''
    super().__init__()
    self.config = config

    c_s = config.sequence_dim
    c_z = config.pairwise_dim
    self.hidden_dim = config.ipa_dim
    self.num_heads = config.num_heads_ipa
    self.num_qk_points = config.num_qk_points
    self.num_v_points = config.num_v_points

    # These linear layers differ from their specifications in the
    # supplement. There, they lack bias and use Glorot initialization.
    # Here as in the official source, they have bias and use the default
    # Lecun initialization.
    hc = config.ipa_dim * config.num_heads_ipa
    self.linear_q = EsmFoldLinear(c_s, hc)
    self.linear_kv = EsmFoldLinear(c_s, 2 * hc)

    hpq = config.num_heads_ipa * config.num_qk_points * 3
    self.linear_q_points = EsmFoldLinear(c_s, hpq)

    hpkv = config.num_heads_ipa * (config.num_qk_points + config.num_v_points) * 3
    self.linear_kv_points = EsmFoldLinear(c_s, hpkv)

    self.linear_b = EsmFoldLinear(c_z, config.num_heads_ipa)

    self.head_weights = Parameter(ops.zeros((config.num_heads_ipa)))

    concat_out_dim = config.num_heads_ipa * (c_z + config.ipa_dim + config.num_v_points * 4)
    self.linear_out = EsmFoldLinear(concat_out_dim, c_s, init="final")

    self.softmax = nn.Softmax(dim=-1)
    self.softplus = nn.Softplus()

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldInvariantPointAttention.forward(s, z, r, mask)

PARAMETER DESCRIPTION
s

[*, N_res, C_s] single representation

TYPE: Tensor

z

[*, N_res, N_res, C_z] pair representation

TYPE: Optional[Tensor]

r

[*, N_res] transformation object

TYPE: Rigid

mask

[*, N_res] mask

TYPE: Tensor

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
def forward(
    self,
    s: mindspore.Tensor,
    z: Optional[mindspore.Tensor],
    r: Rigid,
    mask: mindspore.Tensor,
) -> mindspore.Tensor:
    """
    Args:
        s:
            [*, N_res, C_s] single representation
        z:
            [*, N_res, N_res, C_z] pair representation
        r:
            [*, N_res] transformation object
        mask:
            [*, N_res] mask
    Returns:
        [*, N_res, C_s] single representation update
    """
    z = [z]

    #######################################
    # Generate scalar and point activations
    #######################################
    # [*, N_res, H * C_hidden]
    q = self.linear_q(s)
    kv = self.linear_kv(s)

    # [*, N_res, H, C_hidden]
    q = q.view(q.shape[:-1] + (self.num_heads, -1))

    # [*, N_res, H, 2 * C_hidden]
    kv = kv.view(kv.shape[:-1] + (self.num_heads, -1))

    # [*, N_res, H, C_hidden]
    k, v = ops.split(kv, self.hidden_dim, dim=-1)

    # [*, N_res, H * P_q * 3]
    q_pts = self.linear_q_points(s)

    # This is kind of clunky, but it's how the original does it
    # [*, N_res, H * P_q, 3]
    q_pts = ops.split(q_pts, q_pts.shape[-1] // 3, dim=-1)
    q_pts = ops.stack(q_pts, dim=-1)
    q_pts = r[..., None].apply(q_pts)

    # [*, N_res, H, P_q, 3]
    q_pts = q_pts.view(q_pts.shape[:-2] + (self.num_heads, self.num_qk_points, 3))

    # [*, N_res, H * (P_q + P_v) * 3]
    kv_pts = self.linear_kv_points(s)

    # [*, N_res, H * (P_q + P_v), 3]
    kv_pts = ops.split(kv_pts, kv_pts.shape[-1] // 3, dim=-1)
    kv_pts = ops.stack(kv_pts, dim=-1)
    kv_pts = r[..., None].apply(kv_pts)

    # [*, N_res, H, (P_q + P_v), 3]
    kv_pts = kv_pts.view(kv_pts.shape[:-2] + (self.num_heads, -1, 3))

    # [*, N_res, H, P_q/P_v, 3]
    k_pts, v_pts = ops.split(kv_pts, [self.num_qk_points, self.num_v_points], dim=-2)

    ##########################
    # Compute attention scores
    ##########################
    # [*, N_res, N_res, H]
    b = self.linear_b(z[0])
    # [*, H, N_res, N_res]
    a = ops.matmul(
        permute_final_dims(q, (1, 0, 2)),  # [*, H, N_res, C_hidden]
        permute_final_dims(k, (1, 2, 0)),  # [*, H, C_hidden, N_res]
    )

    a *= math.sqrt(1.0 / (3 * self.hidden_dim))
    a += math.sqrt(1.0 / 3) * permute_final_dims(b, (2, 0, 1))

    # [*, N_res, N_res, H, P_q, 3]
    pt_att = q_pts.unsqueeze(-4) - k_pts.unsqueeze(-5)
    pt_att = pt_att**2

    # [*, N_res, N_res, H, P_q]
    pt_att = sum(ops.unbind(pt_att, dim=-1))
    head_weights = self.softplus(self.head_weights).view(*((1,) * len(pt_att.shape[:-2]) + (-1, 1)))
    head_weights = head_weights * math.sqrt(1.0 / (3 * (self.num_qk_points * 9.0 / 2)))
    pt_att = pt_att * head_weights

    # [*, N_res, N_res, H]
    pt_att = ops.sum(pt_att, dim=-1) * (-0.5)
    # [*, N_res, N_res]
    square_mask = mask.unsqueeze(-1) * mask.unsqueeze(-2)
    square_mask = self.config.inf * (square_mask - 1)

    # [*, H, N_res, N_res]
    pt_att = permute_final_dims(pt_att, (2, 0, 1))

    a = a + pt_att
    a = a + square_mask.unsqueeze(-3)
    a = self.softmax(a)

    ################
    # Compute output
    ################
    # [*, N_res, H, C_hidden]
    o = ops.matmul(a, v.swapaxes(-2, -3).to(dtype=a.dtype)).swapaxes(-2, -3)

    # [*, N_res, H * C_hidden]
    o = flatten_final_dims(o, 2)

    # [*, H, 3, N_res, P_v]
    o_pt = ops.sum(
        (a[..., None, :, :, None] * permute_final_dims(v_pts, (1, 3, 0, 2))[..., None, :, :]),
        dim=-2,
    )

    # [*, N_res, H, P_v, 3]
    o_pt = permute_final_dims(o_pt, (2, 0, 3, 1))
    o_pt = r[..., None, None].invert_apply(o_pt)

    # [*, N_res, H * P_v]
    o_pt_norm = flatten_final_dims(ops.sqrt(ops.sum(o_pt**2, dim=-1) + self.config.epsilon), 2)

    # [*, N_res, H * P_v, 3]
    o_pt = o_pt.reshape(*o_pt.shape[:-3], -1, 3)

    # [*, N_res, H, C_z]
    o_pair = ops.matmul(a.swapaxes(-2, -3), z[0].to(dtype=a.dtype))

    # [*, N_res, H * C_z]
    o_pair = flatten_final_dims(o_pair, 2)

    # [*, N_res, C_s]
    s = self.linear_out(
        ops.cat((o, *ops.unbind(o_pt, dim=-1), o_pt_norm, o_pair), dim=-1).to(dtype=z[0].dtype)
    )

    return s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldLinear

Bases: Linear

A Linear layer with built-in nonstandard initializations. Called just like torch.nn.Linear.

Implements the initializers in 1.11.4, plus some additional ones found in the code.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
class EsmFoldLinear(nn.Linear):
    """
    A Linear layer with built-in nonstandard initializations. Called just like torch.nn.Linear.

    Implements the initializers in 1.11.4, plus some additional ones found in the code.
    """
    def __init__(
        self,
        in_dim: int,
        out_dim: int,
        bias: bool = True,
        init: str = "default",
        init_fn: Optional[Callable[[mindspore.Tensor, mindspore.Tensor], None]] = None,
    ):
        """
        Args:
            in_dim:
                The final dimension of inputs to the layer
            out_dim:
                The final dimension of layer outputs
            bias:
                Whether to learn an additive bias. True by default
            init:
                The initializer to use. Choose from:

                "default": LeCun fan-in truncated normal initialization "relu": He initialization w/ truncated normal
                distribution "glorot": Fan-average Glorot uniform initialization "gating": Weights=0, Bias=1 "normal":
                Normal initialization with std=1/sqrt(fan_in) "final": Weights=0, Bias=0

                Overridden by init_fn if the latter is not None.
            init_fn:
                A custom initializer taking weight and bias as inputs. Overrides init if not None.
        """
        super().__init__(in_dim, out_dim, bias=bias)

        self.init = init
        self.init_fn = init_fn
        if bias:
            self.bias.set_data(ops.zeros_like(self.bias))

        if init not in ["default", "relu", "glorot", "gating", "normal", "final"]:
            raise ValueError("Invalid init string.")

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldLinear.__init__(in_dim, out_dim, bias=True, init='default', init_fn=None)

PARAMETER DESCRIPTION
in_dim

The final dimension of inputs to the layer

TYPE: int

out_dim

The final dimension of layer outputs

TYPE: int

bias

Whether to learn an additive bias. True by default

TYPE: bool DEFAULT: True

init

The initializer to use. Choose from:

"default": LeCun fan-in truncated normal initialization "relu": He initialization w/ truncated normal distribution "glorot": Fan-average Glorot uniform initialization "gating": Weights=0, Bias=1 "normal": Normal initialization with std=1/sqrt(fan_in) "final": Weights=0, Bias=0

Overridden by init_fn if the latter is not None.

TYPE: str DEFAULT: 'default'

init_fn

A custom initializer taking weight and bias as inputs. Overrides init if not None.

TYPE: Optional[Callable[[Tensor, Tensor], None]] DEFAULT: None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
def __init__(
    self,
    in_dim: int,
    out_dim: int,
    bias: bool = True,
    init: str = "default",
    init_fn: Optional[Callable[[mindspore.Tensor, mindspore.Tensor], None]] = None,
):
    """
    Args:
        in_dim:
            The final dimension of inputs to the layer
        out_dim:
            The final dimension of layer outputs
        bias:
            Whether to learn an additive bias. True by default
        init:
            The initializer to use. Choose from:

            "default": LeCun fan-in truncated normal initialization "relu": He initialization w/ truncated normal
            distribution "glorot": Fan-average Glorot uniform initialization "gating": Weights=0, Bias=1 "normal":
            Normal initialization with std=1/sqrt(fan_in) "final": Weights=0, Bias=0

            Overridden by init_fn if the latter is not None.
        init_fn:
            A custom initializer taking weight and bias as inputs. Overrides init if not None.
    """
    super().__init__(in_dim, out_dim, bias=bias)

    self.init = init
    self.init_fn = init_fn
    if bias:
        self.bias.set_data(ops.zeros_like(self.bias))

    if init not in ["default", "relu", "glorot", "gating", "normal", "final"]:
        raise ValueError("Invalid init string.")

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldPairToSequence

Bases: Module

EsmFoldPairToSequence class represents a neural network module for converting pairwise features to sequence features using self-attention mechanism.

This class inherits from nn.Module and includes methods for initializing the module and forwarding the forward pass.

ATTRIBUTE DESCRIPTION
pairwise_state_dim

Dimension of the pairwise state features.

TYPE: int

num_heads

Number of attention heads.

TYPE: int

METHOD DESCRIPTION
__init__

Initializes the EsmFoldPairToSequence module with the given pairwise_state_dim and num_heads.

forward

Applies self-attention mechanism to the input pairwise_state tensor to generate pairwise_bias tensor.

PARAMETER DESCRIPTION
pairwise_state_dim

Dimension of the pairwise state features.

TYPE: int

num_heads

Number of attention heads.

TYPE: int

Inputs

pairwise_state (tensor): Input tensor of shape B x L x L x pairwise_state_dim.

Outputs

pairwise_bias (tensor): Output tensor of shape B x L x L x num_heads.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
class EsmFoldPairToSequence(nn.Module):

    """
    EsmFoldPairToSequence class represents a neural network module for converting pairwise features to sequence features
    using self-attention mechanism.

    This class inherits from nn.Module and includes methods for initializing the module and forwarding the forward pass.

    Attributes:
        pairwise_state_dim (int): Dimension of the pairwise state features.
        num_heads (int): Number of attention heads.

    Methods:
        __init__:
            Initializes the EsmFoldPairToSequence module with the given pairwise_state_dim and num_heads.

        forward:
            Applies self-attention mechanism to the input pairwise_state tensor to generate pairwise_bias tensor.

    Args:
        pairwise_state_dim (int): Dimension of the pairwise state features.
        num_heads (int): Number of attention heads.

    Inputs:
        pairwise_state (tensor): Input tensor of shape B x L x L x pairwise_state_dim.

    Outputs:
        pairwise_bias (tensor): Output tensor of shape B x L x L x num_heads.
    """
    def __init__(self, pairwise_state_dim, num_heads):
        """
        Initializes an instance of the EsmFoldPairToSequence class.

        Args:
            self: The instance of the class.
            pairwise_state_dim (int): The dimension of the pairwise state.
            num_heads (int): The number of attention heads to use.

        Returns:
            None.

        Raises:
            ValueError: If pairwise_state_dim or num_heads is not a positive integer.
            AttributeError: If the attributes layernorm or linear cannot be initialized.
        """
        super().__init__()

        self.layernorm = nn.LayerNorm(pairwise_state_dim)
        self.linear = nn.Linear(pairwise_state_dim, num_heads, bias=False)

    def forward(self, pairwise_state):
        """
        Inputs:
            pairwise_state: B x L x L x pairwise_state_dim

        Output:
            pairwise_bias: B x L x L x num_heads
        """
        assert len(pairwise_state.shape) == 4
        z = self.layernorm(pairwise_state)
        pairwise_bias = self.linear(z)
        return pairwise_bias

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldPairToSequence.__init__(pairwise_state_dim, num_heads)

Initializes an instance of the EsmFoldPairToSequence class.

PARAMETER DESCRIPTION
self

The instance of the class.

pairwise_state_dim

The dimension of the pairwise state.

TYPE: int

num_heads

The number of attention heads to use.

TYPE: int

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If pairwise_state_dim or num_heads is not a positive integer.

AttributeError

If the attributes layernorm or linear cannot be initialized.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
def __init__(self, pairwise_state_dim, num_heads):
    """
    Initializes an instance of the EsmFoldPairToSequence class.

    Args:
        self: The instance of the class.
        pairwise_state_dim (int): The dimension of the pairwise state.
        num_heads (int): The number of attention heads to use.

    Returns:
        None.

    Raises:
        ValueError: If pairwise_state_dim or num_heads is not a positive integer.
        AttributeError: If the attributes layernorm or linear cannot be initialized.
    """
    super().__init__()

    self.layernorm = nn.LayerNorm(pairwise_state_dim)
    self.linear = nn.Linear(pairwise_state_dim, num_heads, bias=False)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldPairToSequence.forward(pairwise_state)

Inputs
Output
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
def forward(self, pairwise_state):
    """
    Inputs:
        pairwise_state: B x L x L x pairwise_state_dim

    Output:
        pairwise_bias: B x L x L x num_heads
    """
    assert len(pairwise_state.shape) == 4
    z = self.layernorm(pairwise_state)
    pairwise_bias = self.linear(z)
    return pairwise_bias

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldPreTrainedModel

Bases: EsmPreTrainedModel

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

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
class EsmFoldPreTrainedModel(EsmPreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    # Subclass `EsMPreTrainedModel` to deal with special init
    def _init_weights(self, cell):
        """Initialize the weights"""
        if isinstance(cell, EsmFoldLinear):
            if cell.init_fn is not None:
                cell.init_fn(cell.weight, cell.bias)
            elif cell.init == "default":
                trunc_normal_init_(cell.weight, scale=1.0)
            elif cell.init == "relu":
                trunc_normal_init_(cell.weight, scale=2.0)
            elif cell.init == "glorot":
                cell.weight.set_data(initializer(XavierUniform(), cell.weight.shape, cell.weight.dtype))
            elif cell.init == "gating":
                cell.weight[:] = 0
                if cell.bias is not None:
                    cell.bias[:] = 1
            elif cell.init == "normal":
                cell.weight.set_data(initializer(HeNormal(nonlinearity="linear"), cell.weight.shape, cell.weight.dtype))
            elif cell.init == "final":
                cell.weight[:] = 0
        elif isinstance(cell, EsmFoldInvariantPointAttention):
            ipa_point_weights_init_(cell.head_weights)
        elif isinstance(cell, EsmFoldTriangularSelfAttentionBlock):
            cell.tri_mul_in.linear_z.weight[:] = 0
            cell.tri_mul_in.linear_z.bias[:] = 0
            cell.tri_mul_out.linear_z.weight[:] = 0
            cell.tri_mul_out.linear_z.bias[:] = 0
            cell.tri_att_start.mha.linear_o.weight[:] = 0
            cell.tri_att_start.mha.linear_o.bias[:] = 0
            cell.tri_att_end.mha.linear_o.weight[:] = 0
            cell.tri_att_end.mha.linear_o.bias[:] = 0

            cell.sequence_to_pair.o_proj.weight[:] = 0
            cell.sequence_to_pair.o_proj.bias[:] = 0
            cell.pair_to_sequence.linear.weight[:] = 0
            cell.seq_attention.o_proj.weight[:] = 0
            cell.seq_attention.o_proj.bias[:] = 0
            cell.mlp_seq.mlp[-2].weight[:] = 0
            cell.mlp_seq.mlp[-2].bias[:] = 0
            cell.mlp_pair.mlp[-2].weight[:] = 0
            cell.mlp_pair.mlp[-2].bias[:] = 0
        else:
            super()._init_weights(cell)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldRelativePosition

Bases: Module

Represents a class for forwarding relative position embeddings for protein folding using the ESM (Evolutionary Scale Modeling) framework.

This class inherits from the nn.Module class and provides methods for initializing the class and forwarding pairwise state embeddings based on residue indices and optional masking.

ATTRIBUTE DESCRIPTION
bins

An integer representing the number of position bins used for forwarding the embeddings.

embedding

An instance of nn.Embedding used for creating the embeddings based on the position differences.

METHOD DESCRIPTION
__init__

Initializes the EsmFoldRelativePosition class with the provided configuration.

forward

Constructs pairwise state embeddings based on the given residue indices and optional mask.

PARAMETER DESCRIPTION
config

An object containing configuration parameters for initializing the class.

residue_index

A B x L tensor of indices (dtype=torch.long) representing the residue indices.

mask

A B x L tensor of booleans representing an optional mask.

RETURNS DESCRIPTION
pairwise_state

A B x L x L x pairwise_state_dim tensor of embeddings based on the input residue indices and mask.

RAISES DESCRIPTION
ValueError

If the dtype of residue_index is not torch.long or if the shapes of residue_index and mask are inconsistent.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
class EsmFoldRelativePosition(nn.Module):

    """
    Represents a class for forwarding relative position embeddings for protein folding using the ESM
    (Evolutionary Scale Modeling) framework.

    This class inherits from the nn.Module class and provides methods for initializing the class and forwarding pairwise
    state embeddings based on residue indices and optional masking.

    Attributes:
        bins: An integer representing the number of position bins used for forwarding the embeddings.
        embedding: An instance of nn.Embedding used for creating the embeddings based on the position differences.

    Methods:
        __init__: Initializes the EsmFoldRelativePosition class with the provided configuration.
        forward: Constructs pairwise state embeddings based on the given residue indices and optional mask.

    Args:
        config: An object containing configuration parameters for initializing the class.
        residue_index: A B x L tensor of indices (dtype=torch.long) representing the residue indices.
        mask: A B x L tensor of booleans representing an optional mask.

    Returns:
        pairwise_state: A B x L x L x pairwise_state_dim tensor of embeddings based on the input residue indices and mask.

    Raises:
        ValueError:
            If the dtype of residue_index is not torch.long or if the shapes of residue_index and mask are inconsistent.
    """
    def __init__(self, config):
        """
        Initializes an instance of the EsmFoldRelativePosition class.

        Args:
            self (EsmFoldRelativePosition): The current instance of the class.
            config: The configuration object containing the necessary parameters.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.bins = config.position_bins

        # Note an additional offset is used so that the 0th position
        # is reserved for masked pairs.
        self.embedding = nn.Embedding(2 * self.bins + 2, config.pairwise_state_dim)

    def forward(self, residue_index, mask=None):
        """
        Input:
            residue_index: B x L tensor of indices (dytpe=torch.long) mask: B x L tensor of booleans

        Output:
            pairwise_state: B x L x L x pairwise_state_dim tensor of embeddings
        """
        if residue_index.dtype != mindspore.int64:
            raise ValueError(f"`residue_index` has dtype {residue_index.dtype}, it should be `torch.long`.")
        if mask is not None and residue_index.shape != mask.shape:
            raise ValueError(
                f"`residue_index` and `mask` have inconsistent shapes: {residue_index.shape} != {mask.shape}."
            )

        diff = residue_index[:, None, :] - residue_index[:, :, None]
        diff = diff.clamp(-self.bins, self.bins)
        diff = diff + self.bins + 1  # Add 1 to adjust for padding index.

        if mask is not None:
            mask = mask[:, None, :] * mask[:, :, None]
            diff[mask == False] = 0  # noqa: E712

        output = self.embedding(diff)
        return output

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldRelativePosition.__init__(config)

Initializes an instance of the EsmFoldRelativePosition class.

PARAMETER DESCRIPTION
self

The current instance of the class.

TYPE: EsmFoldRelativePosition

config

The configuration object containing the necessary parameters.

RETURNS DESCRIPTION

None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
def __init__(self, config):
    """
    Initializes an instance of the EsmFoldRelativePosition class.

    Args:
        self (EsmFoldRelativePosition): The current instance of the class.
        config: The configuration object containing the necessary parameters.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.bins = config.position_bins

    # Note an additional offset is used so that the 0th position
    # is reserved for masked pairs.
    self.embedding = nn.Embedding(2 * self.bins + 2, config.pairwise_state_dim)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldRelativePosition.forward(residue_index, mask=None)

Input
Output
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
def forward(self, residue_index, mask=None):
    """
    Input:
        residue_index: B x L tensor of indices (dytpe=torch.long) mask: B x L tensor of booleans

    Output:
        pairwise_state: B x L x L x pairwise_state_dim tensor of embeddings
    """
    if residue_index.dtype != mindspore.int64:
        raise ValueError(f"`residue_index` has dtype {residue_index.dtype}, it should be `torch.long`.")
    if mask is not None and residue_index.shape != mask.shape:
        raise ValueError(
            f"`residue_index` and `mask` have inconsistent shapes: {residue_index.shape} != {mask.shape}."
        )

    diff = residue_index[:, None, :] - residue_index[:, :, None]
    diff = diff.clamp(-self.bins, self.bins)
    diff = diff + self.bins + 1  # Add 1 to adjust for padding index.

    if mask is not None:
        mask = mask[:, None, :] * mask[:, :, None]
        diff[mask == False] = 0  # noqa: E712

    output = self.embedding(diff)
    return output

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldResidueMLP

Bases: Module

This class represents a multi-layer perceptron (MLP) used for folding residues in the ESM (Evolutionary Scale Modeling) framework. It inherits from the nn.Module class.

The EsmFoldResidueMLP class implements a MLP architecture with layer normalization, dense layers, ReLU activation, and dropout. The MLP takes an input tensor and applies a series of linear transformations to produce an output tensor. The output tensor is then added element-wise to the input tensor, resulting in the folded residue representation.

ATTRIBUTE DESCRIPTION
embed_dim

The dimensionality of the input and output tensors.

TYPE: int

inner_dim

The dimensionality of the intermediate hidden layer in the MLP.

TYPE: int

dropout

The dropout probability applied after the ReLU activation. Defaults to 0.

TYPE: float

METHOD DESCRIPTION
__init__

Initializes an instance of the EsmFoldResidueMLP class.

  • embed_dim (int): The dimensionality of the input and output tensors.
  • inner_dim (int): The dimensionality of the intermediate hidden layer in the MLP.
  • dropout (float, optional): The dropout probability applied after the ReLU activation. Defaults to 0.
forward

Applies the MLP to the input tensor x and returns the folded residue representation.

  • x (Tensor): The input tensor of shape (batch_size, embed_dim).
Example
>>> embed_dim = 128
>>> inner_dim = 256
>>> dropout = 0.2
...
>>> mlp = EsmFoldResidueMLP(embed_dim, inner_dim, dropout)
>>> input_tensor = torch.randn(batch_size, embed_dim)
...
>>> output = mlp.forward(input_tensor)
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
class EsmFoldResidueMLP(nn.Module):

    """
    This class represents a multi-layer perceptron (MLP) used for folding residues in the ESM
    (Evolutionary Scale Modeling) framework. It inherits from the nn.Module class.

    The EsmFoldResidueMLP class implements a MLP architecture with layer normalization, dense layers, ReLU activation,
    and dropout. The MLP takes an input tensor and applies a series of linear transformations to produce an output
    tensor. The output tensor is then added element-wise to the input tensor, resulting in the folded residue
    representation.

    Attributes:
        embed_dim (int): The dimensionality of the input and output tensors.
        inner_dim (int): The dimensionality of the intermediate hidden layer in the MLP.
        dropout (float, optional): The dropout probability applied after the ReLU activation. Defaults to 0.

    Methods:
        __init__:
            Initializes an instance of the EsmFoldResidueMLP class.

            - embed_dim (int): The dimensionality of the input and output tensors.
            - inner_dim (int): The dimensionality of the intermediate hidden layer in the MLP.
            - dropout (float, optional): The dropout probability applied after the ReLU activation. Defaults to 0.

        forward(self, x):
            Applies the MLP to the input tensor x and returns the folded residue representation.

            - x (Tensor): The input tensor of shape (batch_size, embed_dim).

    Example:
        ```python
        >>> embed_dim = 128
        >>> inner_dim = 256
        >>> dropout = 0.2
        ...
        >>> mlp = EsmFoldResidueMLP(embed_dim, inner_dim, dropout)
        >>> input_tensor = torch.randn(batch_size, embed_dim)
        ...
        >>> output = mlp.forward(input_tensor)
        ```
    """
    def __init__(self, embed_dim, inner_dim, dropout=0):
        """
        Initializes the EsmFoldResidueMLP class.

        Args:
            self (object): The instance of the class.
            embed_dim (int): The dimension of the input embeddings.
            inner_dim (int): The dimension of the inner layer.
            dropout (float, optional): The dropout probability. Defaults to 0.

        Returns:
            None.

        Raises:
            TypeError: If embed_dim or inner_dim is not an integer, or if dropout is not a float.
            ValueError: If embed_dim or inner_dim is less than or equal to 0, or if dropout is not within the range [0, 1].
        """
        super().__init__()

        self.mlp = nn.Sequential(
            nn.LayerNorm(embed_dim),
            nn.Linear(embed_dim, inner_dim),
            nn.ReLU(),
            nn.Linear(inner_dim, embed_dim),
            nn.Dropout(p=dropout),
        )

    def forward(self, x):
        """
        Constructs an output value by adding the input value with the result of the multi-layer perceptron (MLP) operation.

        Args:
            self (EsmFoldResidueMLP): Instance of the EsmFoldResidueMLP class.
            x (any): Input value to be used in the forwardion process.

        Returns:
            None: The forwarded value is returned as the result of adding the input value with the MLP operation.

        Raises:
            TypeError: If the input value 'x' is not compatible for addition with the MLP operation.
            ValueError: If the MLP operation encounters any unexpected issues during computation.
        """
        return x + self.mlp(x)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldResidueMLP.__init__(embed_dim, inner_dim, dropout=0)

Initializes the EsmFoldResidueMLP class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

embed_dim

The dimension of the input embeddings.

TYPE: int

inner_dim

The dimension of the inner layer.

TYPE: int

dropout

The dropout probability. Defaults to 0.

TYPE: float DEFAULT: 0

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If embed_dim or inner_dim is not an integer, or if dropout is not a float.

ValueError

If embed_dim or inner_dim is less than or equal to 0, or if dropout is not within the range [0, 1].

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
def __init__(self, embed_dim, inner_dim, dropout=0):
    """
    Initializes the EsmFoldResidueMLP class.

    Args:
        self (object): The instance of the class.
        embed_dim (int): The dimension of the input embeddings.
        inner_dim (int): The dimension of the inner layer.
        dropout (float, optional): The dropout probability. Defaults to 0.

    Returns:
        None.

    Raises:
        TypeError: If embed_dim or inner_dim is not an integer, or if dropout is not a float.
        ValueError: If embed_dim or inner_dim is less than or equal to 0, or if dropout is not within the range [0, 1].
    """
    super().__init__()

    self.mlp = nn.Sequential(
        nn.LayerNorm(embed_dim),
        nn.Linear(embed_dim, inner_dim),
        nn.ReLU(),
        nn.Linear(inner_dim, embed_dim),
        nn.Dropout(p=dropout),
    )

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldResidueMLP.forward(x)

Constructs an output value by adding the input value with the result of the multi-layer perceptron (MLP) operation.

PARAMETER DESCRIPTION
self

Instance of the EsmFoldResidueMLP class.

TYPE: EsmFoldResidueMLP

x

Input value to be used in the forwardion process.

TYPE: any

RETURNS DESCRIPTION
None

The forwarded value is returned as the result of adding the input value with the MLP operation.

RAISES DESCRIPTION
TypeError

If the input value 'x' is not compatible for addition with the MLP operation.

ValueError

If the MLP operation encounters any unexpected issues during computation.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
def forward(self, x):
    """
    Constructs an output value by adding the input value with the result of the multi-layer perceptron (MLP) operation.

    Args:
        self (EsmFoldResidueMLP): Instance of the EsmFoldResidueMLP class.
        x (any): Input value to be used in the forwardion process.

    Returns:
        None: The forwarded value is returned as the result of adding the input value with the MLP operation.

    Raises:
        TypeError: If the input value 'x' is not compatible for addition with the MLP operation.
        ValueError: If the MLP operation encounters any unexpected issues during computation.
    """
    return x + self.mlp(x)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldSelfAttention

Bases: Module

This class represents a self-attention mechanism for processing sequences, specifically designed for handling sequences of varying lengths. It implements a multi-head self-attention mechanism with optional gating, bias, and masking capabilities.

ATTRIBUTE DESCRIPTION
embed_dim

The dimension of the input embedding.

TYPE: int

num_heads

The number of attention heads.

TYPE: int

head_width

The width of each attention head.

TYPE: int

gated

Indicates whether the attention mechanism uses gating.

TYPE: bool

proj

Linear projection layer for processing input sequences.

TYPE: Linear

o_proj

Output projection layer.

TYPE: Linear

g_proj

Gating projection layer (if gated is True).

TYPE: Linear

rescale_factor

Scaling factor for the attention weights.

TYPE: float

METHOD DESCRIPTION
forward

Performs self-attention on the input batch of sequences with optional mask and external pairwise bias.

Inputs:

  • x (Tensor): Batch of input sequences of shape (B x L x C).
  • mask (Tensor, optional): Batch of boolean masks where 1 denotes valid positions and 0 denotes padding positions of shape (B x L_k).
  • bias (Tensor, optional): Batch of scalar pairwise attention biases of shape (B x Lq x Lk x num_heads).
  • indices (Tensor, optional): Additional indices for attention computation.

Outputs:

  • y (Tensor): Sequence projection of shape (B x L x embed_dim).
  • attention_maps (Tensor): Attention maps of shape (B x L x L x num_heads).
Note
  • Gating mechanism is applied if 'gated' is set to True.
  • The attention weights are softmax normalized.
  • The attention computation is based on the query, key, and value projections.
  • Masking is supported to handle sequences of different lengths.
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
class EsmFoldSelfAttention(nn.Module):

    """
    This class represents a self-attention mechanism for processing sequences, specifically designed for handling
    sequences of varying lengths.
    It implements a multi-head self-attention mechanism with optional gating, bias, and masking capabilities.

    Attributes:
        embed_dim (int): The dimension of the input embedding.
        num_heads (int): The number of attention heads.
        head_width (int): The width of each attention head.
        gated (bool): Indicates whether the attention mechanism uses gating.
        proj (nn.Linear): Linear projection layer for processing input sequences.
        o_proj (nn.Linear): Output projection layer.
        g_proj (nn.Linear): Gating projection layer (if gated is True).
        rescale_factor (float): Scaling factor for the attention weights.

    Methods:
        forward(self, x, mask=None, bias=None, indices=None):
            Performs self-attention on the input batch of sequences with optional mask and external pairwise bias.

            Inputs:

            - x (Tensor): Batch of input sequences of shape (B x L x C).
            - mask (Tensor, optional): Batch of boolean masks where 1 denotes valid positions and 0 denotes padding positions of shape (B x L_k).
            - bias (Tensor, optional): Batch of scalar pairwise attention biases of shape (B x Lq x Lk x num_heads).
            - indices (Tensor, optional): Additional indices for attention computation.

            Outputs:

            - y (Tensor): Sequence projection of shape (B x L x embed_dim).
            - attention_maps (Tensor): Attention maps of shape (B x L x L x num_heads).

    Note:
        - Gating mechanism is applied if 'gated' is set to True.
        - The attention weights are softmax normalized.
        - The attention computation is based on the query, key, and value projections.
        - Masking is supported to handle sequences of different lengths.
    """
    def __init__(self, embed_dim, num_heads, head_width, gated=False):
        """
        Initializes the EsmFoldSelfAttention class.

        Args:
            self: The instance of the class.
            embed_dim (int): The dimension of the input embeddings.
            num_heads (int): The number of attention heads.
            head_width (int): The width of each attention head.
            gated (bool, optional): Specifies whether the attention mechanism is gated. Defaults to False.

        Returns:
            None.

        Raises:
            AssertionError: If embed_dim is not equal to the product of num_heads and head_width.

        """
        super().__init__()
        assert embed_dim == num_heads * head_width

        self.embed_dim = embed_dim
        self.num_heads = num_heads
        self.head_width = head_width

        self.proj = nn.Linear(embed_dim, embed_dim * 3, bias=False)
        self.o_proj = nn.Linear(embed_dim, embed_dim, bias=True)
        self.gated = gated
        if gated:
            self.g_proj = nn.Linear(embed_dim, embed_dim)
            self.g_proj.weight.set_data(ops.zeros_like(self.g_proj.weight))
            self.g_proj.bias.set_data(ops.ones_like(self.g_proj.bias))

        self.rescale_factor = self.head_width**-0.5

        self.o_proj.bias.set_data(ops.zeros_like(self.o_proj.bias))

    def forward(self, x, mask=None, bias=None, indices=None):
        """
        Basic self attention with optional mask and external pairwise bias. To handle sequences of different lengths,
        use mask.

        Inputs:
            x: batch of input sequneces (.. x L x C) mask: batch of boolean masks where 1=valid, 0=padding position (..
                x L_k) bias: batch of scalar pairwise attention biases (.. x Lq x Lk x num_heads)

        Outputs:
            sequence projection (B x L x embed_dim), attention maps (B x L x L x num_heads)
        """
        t = self.proj(x).view(*x.shape[:2], self.num_heads, -1)
        t = t.permute(0, 2, 1, 3)
        q, k, v = t.chunk(3, axis=-1)

        q = self.rescale_factor * q
        a = ops.einsum("...qc, ...kc -> ...qk", q, k)

        # Add external attention bias.
        if bias is not None:
            a = a + bias.permute(0, 3, 1, 2)

        # Do not attend to padding tokens.
        if mask is not None:
            mask = mask[:, None, None]
            a = a.masked_fill(mask == False, -np.inf)

        a = ops.softmax(a, dim=-1)

        y = ops.einsum("...hqk,...hkc->...qhc", a, v)
        y = y.reshape(*y.shape[:2], -1)

        if self.gated:
            y = self.g_proj(x).sigmoid() * y
        y = self.o_proj(y)

        return y, a.permute(0, 3, 1, 2)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldSelfAttention.__init__(embed_dim, num_heads, head_width, gated=False)

Initializes the EsmFoldSelfAttention class.

PARAMETER DESCRIPTION
self

The instance of the class.

embed_dim

The dimension of the input embeddings.

TYPE: int

num_heads

The number of attention heads.

TYPE: int

head_width

The width of each attention head.

TYPE: int

gated

Specifies whether the attention mechanism is gated. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
AssertionError

If embed_dim is not equal to the product of num_heads and head_width.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
def __init__(self, embed_dim, num_heads, head_width, gated=False):
    """
    Initializes the EsmFoldSelfAttention class.

    Args:
        self: The instance of the class.
        embed_dim (int): The dimension of the input embeddings.
        num_heads (int): The number of attention heads.
        head_width (int): The width of each attention head.
        gated (bool, optional): Specifies whether the attention mechanism is gated. Defaults to False.

    Returns:
        None.

    Raises:
        AssertionError: If embed_dim is not equal to the product of num_heads and head_width.

    """
    super().__init__()
    assert embed_dim == num_heads * head_width

    self.embed_dim = embed_dim
    self.num_heads = num_heads
    self.head_width = head_width

    self.proj = nn.Linear(embed_dim, embed_dim * 3, bias=False)
    self.o_proj = nn.Linear(embed_dim, embed_dim, bias=True)
    self.gated = gated
    if gated:
        self.g_proj = nn.Linear(embed_dim, embed_dim)
        self.g_proj.weight.set_data(ops.zeros_like(self.g_proj.weight))
        self.g_proj.bias.set_data(ops.ones_like(self.g_proj.bias))

    self.rescale_factor = self.head_width**-0.5

    self.o_proj.bias.set_data(ops.zeros_like(self.o_proj.bias))

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldSelfAttention.forward(x, mask=None, bias=None, indices=None)

Basic self attention with optional mask and external pairwise bias. To handle sequences of different lengths, use mask.

Inputs
Outputs

sequence projection (B x L x embed_dim), attention maps (B x L x L x num_heads)

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
def forward(self, x, mask=None, bias=None, indices=None):
    """
    Basic self attention with optional mask and external pairwise bias. To handle sequences of different lengths,
    use mask.

    Inputs:
        x: batch of input sequneces (.. x L x C) mask: batch of boolean masks where 1=valid, 0=padding position (..
            x L_k) bias: batch of scalar pairwise attention biases (.. x Lq x Lk x num_heads)

    Outputs:
        sequence projection (B x L x embed_dim), attention maps (B x L x L x num_heads)
    """
    t = self.proj(x).view(*x.shape[:2], self.num_heads, -1)
    t = t.permute(0, 2, 1, 3)
    q, k, v = t.chunk(3, axis=-1)

    q = self.rescale_factor * q
    a = ops.einsum("...qc, ...kc -> ...qk", q, k)

    # Add external attention bias.
    if bias is not None:
        a = a + bias.permute(0, 3, 1, 2)

    # Do not attend to padding tokens.
    if mask is not None:
        mask = mask[:, None, None]
        a = a.masked_fill(mask == False, -np.inf)

    a = ops.softmax(a, dim=-1)

    y = ops.einsum("...hqk,...hkc->...qhc", a, v)
    y = y.reshape(*y.shape[:2], -1)

    if self.gated:
        y = self.g_proj(x).sigmoid() * y
    y = self.o_proj(y)

    return y, a.permute(0, 3, 1, 2)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldSequenceToPair

Bases: Module

This class represents a neural network model for transforming sequence states into pairwise states using an attention mechanism.

This class inherits from nn.Module and includes methods for initialization and forwarding the pairwise states from sequence states.

ATTRIBUTE DESCRIPTION
layernorm

A layer normalization module for normalizing the sequence state dimensions.

TYPE: LayerNorm

proj

A fully connected layer for projecting the sequence state into an inner dimension space.

TYPE: Linear

o_proj

A fully connected layer for projecting the inner dimension space into pairwise state dimensions.

TYPE: Linear

METHOD DESCRIPTION
__init__

Initializes the EsmFoldSequenceToPair instance with the specified dimensions.

forward

Transforms the input sequence state tensor into pairwise state tensor.

PARAMETER DESCRIPTION
sequence_state_dim

Dimension of the input sequence state.

TYPE: int

inner_dim

Dimension of the inner representation used in the transformation.

TYPE: int

pairwise_state_dim

Dimension of the output pairwise state.

TYPE: int

Inputs

sequence_state (Tensor): Input sequence state tensor with shape B x L x sequence_state_dim.

Output

pairwise_state (Tensor): Output pairwise state tensor with shape B x L x L x pairwise_state_dim.

Intermediate state

Intermediate state tensor with shape B x L x L x 2*inner_dim, used during the transformation process.

RETURNS DESCRIPTION
Tensor

Pairwise state tensor representing the relationships between elements in the input sequence state.

RAISES DESCRIPTION
AssertionError

If the input sequence state tensor does not have the expected shape.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
class EsmFoldSequenceToPair(nn.Module):

    """
    This class represents a neural network model for transforming sequence states into pairwise states
    using an attention mechanism.

    This class inherits from nn.Module and includes methods for initialization and forwarding the pairwise states
    from sequence states.

    Attributes:
        layernorm (nn.LayerNorm): A layer normalization module for normalizing the sequence state dimensions.
        proj (nn.Linear): A fully connected layer for projecting the sequence state into an inner dimension space.
        o_proj (nn.Linear): A fully connected layer for projecting the inner dimension space into pairwise state dimensions.

    Methods:
        __init__: Initializes the EsmFoldSequenceToPair instance with the specified dimensions.

        forward: Transforms the input sequence state tensor into pairwise state tensor.

    Args:
        sequence_state_dim (int): Dimension of the input sequence state.
        inner_dim (int): Dimension of the inner representation used in the transformation.
        pairwise_state_dim (int): Dimension of the output pairwise state.

    Inputs:
        sequence_state (Tensor): Input sequence state tensor with shape B x L x sequence_state_dim.

    Output:
        pairwise_state (Tensor): Output pairwise state tensor with shape B x L x L x pairwise_state_dim.

    Intermediate state:
        Intermediate state tensor with shape B x L x L x 2*inner_dim, used during the transformation process.

    Returns:
        Tensor: Pairwise state tensor representing the relationships between elements in the input sequence state.

    Raises:
        AssertionError: If the input sequence state tensor does not have the expected shape.

    """
    def __init__(self, sequence_state_dim, inner_dim, pairwise_state_dim):
        """
        Initializes the EsmFoldSequenceToPair class.

        Args:
            sequence_state_dim (int): The dimension of the input sequence state.
            inner_dim (int): The inner dimension used for projection.
            pairwise_state_dim (int): The dimension of the pairwise state.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()

        self.layernorm = nn.LayerNorm(sequence_state_dim)
        self.proj = nn.Linear(sequence_state_dim, inner_dim * 2, bias=True)
        self.o_proj = nn.Linear(2 * inner_dim, pairwise_state_dim, bias=True)
        self.proj.bias.set_data(ops.zeros_like(self.proj.bias))
        self.o_proj.bias.set_data(ops.zeros_like(self.o_proj.bias))

    def forward(self, sequence_state):
        """
        Inputs:
            sequence_state: B x L x sequence_state_dim

        Output:
            pairwise_state: B x L x L x pairwise_state_dim

        Intermediate state:
          B x L x L x 2*inner_dim
        """
        assert len(sequence_state.shape) == 3

        s = self.layernorm(sequence_state)
        s = self.proj(s)
        q, k = s.chunk(2, axis=-1)

        prod = q[:, None, :, :] * k[:, :, None, :]
        diff = q[:, None, :, :] - k[:, :, None, :]

        x = ops.cat([prod, diff], dim=-1)
        x = self.o_proj(x)

        return x

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldSequenceToPair.__init__(sequence_state_dim, inner_dim, pairwise_state_dim)

Initializes the EsmFoldSequenceToPair class.

PARAMETER DESCRIPTION
sequence_state_dim

The dimension of the input sequence state.

TYPE: int

inner_dim

The inner dimension used for projection.

TYPE: int

pairwise_state_dim

The dimension of the pairwise state.

TYPE: int

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
def __init__(self, sequence_state_dim, inner_dim, pairwise_state_dim):
    """
    Initializes the EsmFoldSequenceToPair class.

    Args:
        sequence_state_dim (int): The dimension of the input sequence state.
        inner_dim (int): The inner dimension used for projection.
        pairwise_state_dim (int): The dimension of the pairwise state.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()

    self.layernorm = nn.LayerNorm(sequence_state_dim)
    self.proj = nn.Linear(sequence_state_dim, inner_dim * 2, bias=True)
    self.o_proj = nn.Linear(2 * inner_dim, pairwise_state_dim, bias=True)
    self.proj.bias.set_data(ops.zeros_like(self.proj.bias))
    self.o_proj.bias.set_data(ops.zeros_like(self.o_proj.bias))

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldSequenceToPair.forward(sequence_state)

Inputs
Output
Intermediate state

B x L x L x 2*inner_dim

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
def forward(self, sequence_state):
    """
    Inputs:
        sequence_state: B x L x sequence_state_dim

    Output:
        pairwise_state: B x L x L x pairwise_state_dim

    Intermediate state:
      B x L x L x 2*inner_dim
    """
    assert len(sequence_state.shape) == 3

    s = self.layernorm(sequence_state)
    s = self.proj(s)
    q, k = s.chunk(2, axis=-1)

    prod = q[:, None, :, :] * k[:, :, None, :]
    diff = q[:, None, :, :] - k[:, :, None, :]

    x = ops.cat([prod, diff], dim=-1)
    x = self.o_proj(x)

    return x

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModule

Bases: Module

The EsmFoldStructureModule class represents a module for predicting protein structure using Evolutionary Structure Model (ESM) and folding techniques. It inherits from the nn.Module class.

The class includes methods for initializing the module, forwarding the protein structure prediction, and converting torsion angles to frames and literature positions to atom14 positions. The forward method takes evolutionary formers' output, amino acid indices, and optional sequence mask as input and returns a dictionary of predicted outputs. The _init_residue_constants method initializes constants used in the module for calculating torsion angles to frames and literature positions to atom14 positions.

The class also includes the code for initializing the default frames, group indices, atom masks, and literature positions, and for converting torsion angles to frames and frames and literature positions to atom14 positions.

Please note that the detailed implementation and usage of the class methods are described in the code provided.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
class EsmFoldStructureModule(nn.Module):

    """
    The EsmFoldStructureModule class represents a module for predicting protein structure using Evolutionary Structure
    Model (ESM) and folding techniques. It inherits from the nn.Module class.

    The class includes methods for initializing the module, forwarding the protein structure prediction, and
    converting torsion angles to frames and literature positions to atom14 positions.
    The forward method takes evolutionary formers' output, amino acid indices, and optional sequence mask as input and
    returns a dictionary of predicted outputs. The _init_residue_constants method initializes constants used
    in the module for calculating torsion angles to frames and literature positions to atom14 positions.

    The class also includes the code for initializing the default frames, group indices, atom masks, and literature
    positions, and for converting torsion angles to frames and frames and literature positions to atom14 positions.

    Please note that the detailed implementation and usage of the class methods are described in the code provided.
    """
    def __init__(self, config):
        '''
        Initializes an instance of the EsmFoldStructureModule class.

        Args:
            self (EsmFoldStructureModule): The instance of the class itself.
            config:
                A configuration object containing parameters for initializing the module.

                - Type: Custom configuration object
                - Purpose: Stores various configuration parameters for the module.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            None
        '''
        super().__init__()
        self.config = config

        # Buffers to be lazily initialized later
        # self.default_frames
        # self.group_idx
        # self.atom_mask
        # self.lit_positions

        self.layer_norm_s = nn.LayerNorm(config.sequence_dim)
        self.layer_norm_z = nn.LayerNorm(config.pairwise_dim)

        self.linear_in = EsmFoldLinear(config.sequence_dim, config.sequence_dim)

        self.ipa = EsmFoldInvariantPointAttention(config)

        self.ipa_dropout = nn.Dropout(p=config.dropout_rate)
        self.layer_norm_ipa = nn.LayerNorm(config.sequence_dim)

        self.transition = EsmFoldStructureModuleTransition(config)
        self.bb_update = EsmFoldBackboneUpdate(config)
        self.angle_resnet = EsmFoldAngleResnet(config)

    def forward(
        self,
        evoformer_output_dict,
        aatype,
        mask=None,
        _offload_inference=False,
    ):
        """

        Args:
            evoformer_output_dict:
                Dictionary containing:

                - "single": [*, N_res, C_s] single representation
                - "pair": [*, N_res, N_res, C_z] pair representation
            aatype:
                [*, N_res] amino acid indices
            mask:
                Optional [*, N_res] sequence mask

        Returns:
            A dictionary of outputs
        """
        s = evoformer_output_dict["single"]

        if mask is None:
            # [*, N]
            mask = s.new_ones(s.shape[:-1])

        # [*, N, C_s]
        s = self.layer_norm_s(s)

        # [*, N, N, C_z]
        z = self.layer_norm_z(evoformer_output_dict["pair"])

        z_reference_list = None
        if _offload_inference:
            assert sys.getrefcount(evoformer_output_dict["pair"]) == 2
            evoformer_output_dict["pair"] = evoformer_output_dict["pair"].cpu()
            z_reference_list = [z]
            z = None

        # [*, N, C_s]
        s_initial = s
        s = self.linear_in(s)

        # [*, N]
        rigids = Rigid.identity(
            s.shape[:-1],
            s.dtype,
            fmt="quat",
        )
        outputs = []
        for _ in range(self.config.num_blocks):
            # [*, N, C_s]
            s = s + self.ipa(
                s,
                z,
                rigids,
                mask,
            )
            s = self.ipa_dropout(s)
            s = self.layer_norm_ipa(s)
            s = self.transition(s)

            # [*, N]
            rigids = rigids.compose_q_update_vec(self.bb_update(s))

            # To hew as closely as possible to AlphaFold, we convert our
            # quaternion-based transformations to rotation-matrix ones
            # here
            backb_to_global = Rigid(
                Rotation(rot_mats=rigids.get_rots().get_rot_mats(), quats=None),
                rigids.get_trans(),
            )

            backb_to_global = backb_to_global.scale_translation(self.config.trans_scale_factor)

            # [*, N, 7, 2]
            unnormalized_angles, angles = self.angle_resnet(s, s_initial)

            all_frames_to_global = self.torsion_angles_to_frames(backb_to_global, angles, aatype)

            pred_xyz = self.frames_and_literature_positions_to_atom14_pos(all_frames_to_global, aatype)

            scaled_rigids = rigids.scale_translation(self.config.trans_scale_factor)

            preds = {
                "frames": scaled_rigids.to_tensor_7(),
                "sidechain_frames": all_frames_to_global.to_tensor_4x4(),
                "unnormalized_angles": unnormalized_angles,
                "angles": angles,
                "positions": pred_xyz,
                "states": s,
            }

            outputs.append(preds)

            rigids = rigids.stop_rot_gradient()

        del z, z_reference_list

        outputs = dict_multimap(ops.stack, outputs)
        outputs["single"] = s

        return outputs

    def _init_residue_constants(self, float_dtype):
        """
        Initializes the residue constants required for EsmFoldStructureModule.

        Args:
            self (EsmFoldStructureModule): An instance of the EsmFoldStructureModule class.
            float_dtype (dtype): The data type of the floating point values.

        Returns:
            None

        Raises:
            None

        Description:
            This method initializes the following residue constants:

            - default_frames: A tensor containing the default frames for rigid groups.
            If not already initialized, it is created using the 'restype_rigid_group_default_frame' constant and the
            provided float_dtype.
            - group_idx: A tensor mapping atom14 indices to rigid group indices.
            If not already initialized, it is created using the 'restype_atom14_to_rigid_group' constant.
            - atom_mask: A tensor containing the atom14 mask.
            If not already initialized, it is created using the 'restype_atom14_mask' constant and the provided
            float_dtype.
            - lit_positions: A tensor containing the positions of atom14 rigid groups.
            If not already initialized, it is created using the 'restype_atom14_rigid_group_positions' constant and
            the provided float_dtype.

        Note:
            - This method should be called before using any other functionality of the EsmFoldStructureModule class.
            - The 'float_dtype' parameter determines the precision of the floating point values used in the tensors.
        """
        if not hasattr(self, "default_frames"):
            self.default_frames = mindspore.tensor(
                    residue_constants.restype_rigid_group_default_frame,
                    dtype=float_dtype,
                )
        if not hasattr(self, "group_idx"):
            self.group_idx = mindspore.tensor(
                    residue_constants.restype_atom14_to_rigid_group,
                )
        if not hasattr(self, "atom_mask"):
            self.atom_mask = mindspore.tensor(
                    residue_constants.restype_atom14_mask,
                    dtype=float_dtype,
                )
        if not hasattr(self, "lit_positions"):
            self.lit_positions = mindspore.tensor(
                    residue_constants.restype_atom14_rigid_group_positions,
                    dtype=float_dtype,
                )

    def torsion_angles_to_frames(self, r, alpha, f):
        """
        Converts torsion angles to frames using the given parameters.

        Args:
            self (EsmFoldStructureModule): The instance of the EsmFoldStructureModule class.
            r (numpy.ndarray): The input array of shape (N, 3) containing the residue atoms' coordinates in angstroms.
            alpha (numpy.ndarray): The input array of shape (N, 3) containing the residue angles in radians.
            f (numpy.ndarray): The input array of shape (N, 3, 3) containing the reference frames.

        Returns:
            None.

        Raises:
            ValueError: If the input arrays have incompatible shapes or types.
            TypeError: If the input parameters are not of the expected types.
            RuntimeError: If an unexpected error occurs during the conversion process.
        """
        # Lazily initialize the residue constants on the correct device
        self._init_residue_constants(alpha.dtype)
        # Separated purely to make testing less annoying
        return torsion_angles_to_frames(r, alpha, f, self.default_frames)

    def frames_and_literature_positions_to_atom14_pos(self, r, f):  # [*, N, 8]  # [*, N]
        """
        Converts frames and literature positions to atom14 positions.

        Args:
            self (EsmFoldStructureModule): The instance of the EsmFoldStructureModule class.
            r (object): The 'r' parameter representing some variable.
            f (object): The 'f' parameter representing some variable.

        Returns:
            None.

        Raises:
            None.
        """
        # Lazily initialize the residue constants on the correct device
        self._init_residue_constants(r.get_rots().dtype)
        return frames_and_literature_positions_to_atom14_pos(
            r,
            f,
            self.default_frames,
            self.group_idx,
            self.atom_mask,
            self.lit_positions,
        )

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModule.__init__(config)

Initializes an instance of the EsmFoldStructureModule class.

PARAMETER DESCRIPTION
self

The instance of the class itself.

TYPE: EsmFoldStructureModule

config

A configuration object containing parameters for initializing the module.

  • Type: Custom configuration object
  • Purpose: Stores various configuration parameters for the module.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
def __init__(self, config):
    '''
    Initializes an instance of the EsmFoldStructureModule class.

    Args:
        self (EsmFoldStructureModule): The instance of the class itself.
        config:
            A configuration object containing parameters for initializing the module.

            - Type: Custom configuration object
            - Purpose: Stores various configuration parameters for the module.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        None
    '''
    super().__init__()
    self.config = config

    # Buffers to be lazily initialized later
    # self.default_frames
    # self.group_idx
    # self.atom_mask
    # self.lit_positions

    self.layer_norm_s = nn.LayerNorm(config.sequence_dim)
    self.layer_norm_z = nn.LayerNorm(config.pairwise_dim)

    self.linear_in = EsmFoldLinear(config.sequence_dim, config.sequence_dim)

    self.ipa = EsmFoldInvariantPointAttention(config)

    self.ipa_dropout = nn.Dropout(p=config.dropout_rate)
    self.layer_norm_ipa = nn.LayerNorm(config.sequence_dim)

    self.transition = EsmFoldStructureModuleTransition(config)
    self.bb_update = EsmFoldBackboneUpdate(config)
    self.angle_resnet = EsmFoldAngleResnet(config)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModule.forward(evoformer_output_dict, aatype, mask=None, _offload_inference=False)

PARAMETER DESCRIPTION
evoformer_output_dict

Dictionary containing:

  • "single": [*, N_res, C_s] single representation
  • "pair": [*, N_res, N_res, C_z] pair representation

aatype

[*, N_res] amino acid indices

mask

Optional [*, N_res] sequence mask

DEFAULT: None

RETURNS DESCRIPTION

A dictionary of outputs

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
def forward(
    self,
    evoformer_output_dict,
    aatype,
    mask=None,
    _offload_inference=False,
):
    """

    Args:
        evoformer_output_dict:
            Dictionary containing:

            - "single": [*, N_res, C_s] single representation
            - "pair": [*, N_res, N_res, C_z] pair representation
        aatype:
            [*, N_res] amino acid indices
        mask:
            Optional [*, N_res] sequence mask

    Returns:
        A dictionary of outputs
    """
    s = evoformer_output_dict["single"]

    if mask is None:
        # [*, N]
        mask = s.new_ones(s.shape[:-1])

    # [*, N, C_s]
    s = self.layer_norm_s(s)

    # [*, N, N, C_z]
    z = self.layer_norm_z(evoformer_output_dict["pair"])

    z_reference_list = None
    if _offload_inference:
        assert sys.getrefcount(evoformer_output_dict["pair"]) == 2
        evoformer_output_dict["pair"] = evoformer_output_dict["pair"].cpu()
        z_reference_list = [z]
        z = None

    # [*, N, C_s]
    s_initial = s
    s = self.linear_in(s)

    # [*, N]
    rigids = Rigid.identity(
        s.shape[:-1],
        s.dtype,
        fmt="quat",
    )
    outputs = []
    for _ in range(self.config.num_blocks):
        # [*, N, C_s]
        s = s + self.ipa(
            s,
            z,
            rigids,
            mask,
        )
        s = self.ipa_dropout(s)
        s = self.layer_norm_ipa(s)
        s = self.transition(s)

        # [*, N]
        rigids = rigids.compose_q_update_vec(self.bb_update(s))

        # To hew as closely as possible to AlphaFold, we convert our
        # quaternion-based transformations to rotation-matrix ones
        # here
        backb_to_global = Rigid(
            Rotation(rot_mats=rigids.get_rots().get_rot_mats(), quats=None),
            rigids.get_trans(),
        )

        backb_to_global = backb_to_global.scale_translation(self.config.trans_scale_factor)

        # [*, N, 7, 2]
        unnormalized_angles, angles = self.angle_resnet(s, s_initial)

        all_frames_to_global = self.torsion_angles_to_frames(backb_to_global, angles, aatype)

        pred_xyz = self.frames_and_literature_positions_to_atom14_pos(all_frames_to_global, aatype)

        scaled_rigids = rigids.scale_translation(self.config.trans_scale_factor)

        preds = {
            "frames": scaled_rigids.to_tensor_7(),
            "sidechain_frames": all_frames_to_global.to_tensor_4x4(),
            "unnormalized_angles": unnormalized_angles,
            "angles": angles,
            "positions": pred_xyz,
            "states": s,
        }

        outputs.append(preds)

        rigids = rigids.stop_rot_gradient()

    del z, z_reference_list

    outputs = dict_multimap(ops.stack, outputs)
    outputs["single"] = s

    return outputs

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModule.frames_and_literature_positions_to_atom14_pos(r, f)

Converts frames and literature positions to atom14 positions.

PARAMETER DESCRIPTION
self

The instance of the EsmFoldStructureModule class.

TYPE: EsmFoldStructureModule

r

The 'r' parameter representing some variable.

TYPE: object

f

The 'f' parameter representing some variable.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
def frames_and_literature_positions_to_atom14_pos(self, r, f):  # [*, N, 8]  # [*, N]
    """
    Converts frames and literature positions to atom14 positions.

    Args:
        self (EsmFoldStructureModule): The instance of the EsmFoldStructureModule class.
        r (object): The 'r' parameter representing some variable.
        f (object): The 'f' parameter representing some variable.

    Returns:
        None.

    Raises:
        None.
    """
    # Lazily initialize the residue constants on the correct device
    self._init_residue_constants(r.get_rots().dtype)
    return frames_and_literature_positions_to_atom14_pos(
        r,
        f,
        self.default_frames,
        self.group_idx,
        self.atom_mask,
        self.lit_positions,
    )

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModule.torsion_angles_to_frames(r, alpha, f)

Converts torsion angles to frames using the given parameters.

PARAMETER DESCRIPTION
self

The instance of the EsmFoldStructureModule class.

TYPE: EsmFoldStructureModule

r

The input array of shape (N, 3) containing the residue atoms' coordinates in angstroms.

TYPE: ndarray

alpha

The input array of shape (N, 3) containing the residue angles in radians.

TYPE: ndarray

f

The input array of shape (N, 3, 3) containing the reference frames.

TYPE: ndarray

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the input arrays have incompatible shapes or types.

TypeError

If the input parameters are not of the expected types.

RuntimeError

If an unexpected error occurs during the conversion process.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
def torsion_angles_to_frames(self, r, alpha, f):
    """
    Converts torsion angles to frames using the given parameters.

    Args:
        self (EsmFoldStructureModule): The instance of the EsmFoldStructureModule class.
        r (numpy.ndarray): The input array of shape (N, 3) containing the residue atoms' coordinates in angstroms.
        alpha (numpy.ndarray): The input array of shape (N, 3) containing the residue angles in radians.
        f (numpy.ndarray): The input array of shape (N, 3, 3) containing the reference frames.

    Returns:
        None.

    Raises:
        ValueError: If the input arrays have incompatible shapes or types.
        TypeError: If the input parameters are not of the expected types.
        RuntimeError: If an unexpected error occurs during the conversion process.
    """
    # Lazily initialize the residue constants on the correct device
    self._init_residue_constants(alpha.dtype)
    # Separated purely to make testing less annoying
    return torsion_angles_to_frames(r, alpha, f, self.default_frames)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModuleTransition

Bases: Module

The EsmFoldStructureModuleTransition class represents a module for transitioning the fold structure in a neural network. This class inherits from the nn.Module class and is used to forward transition layers for the fold structure module.

ATTRIBUTE DESCRIPTION
config

A configuration object containing parameters for the module.

layers

A CellList containing the transition layers for the module.

dropout

A dropout layer with a specified dropout rate.

layer_norm

A layer normalization layer for normalizing the output.

METHOD DESCRIPTION
__init__

Initializes the EsmFoldStructureModuleTransition with the given configuration.

forward

Constructs the transition layers for the fold structure module using the input s.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
class EsmFoldStructureModuleTransition(nn.Module):

    """
    The EsmFoldStructureModuleTransition class represents a module for transitioning the fold structure in a neural network.
    This class inherits from the nn.Module class and is used to forward transition layers for the fold structure module.

    Attributes:
        config: A configuration object containing parameters for the module.
        layers: A CellList containing the transition layers for the module.
        dropout: A dropout layer with a specified dropout rate.
        layer_norm: A layer normalization layer for normalizing the output.

    Methods:
        __init__: Initializes the EsmFoldStructureModuleTransition with the given configuration.
        forward: Constructs the transition layers for the fold structure module using the input s.

    """
    def __init__(self, config):
        """
        Initializes an instance of the EsmFoldStructureModuleTransition class.

        Args:
            self: The instance of the class.
            config: An object of type 'Config' that holds the configuration settings for the module.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.config = config

        self.layers = nn.ModuleList()
        for _ in range(config.num_transition_layers):
            l = EsmFoldStructureModuleTransitionLayer(config)
            self.layers.append(l)

        self.dropout = nn.Dropout(p=config.dropout_rate)
        self.layer_norm = nn.LayerNorm(config.sequence_dim)

    def forward(self, s):
        """
        Constructs the EsmFoldStructureModuleTransition.

        This method takes in two parameters: self and s.

        Args:
            self (EsmFoldStructureModuleTransition): An instance of the EsmFoldStructureModuleTransition class.
            s (unknown type): The input data.

        Returns:
            None.

        Raises:
            None.
        """
        for l in self.layers:
            s = l(s)

        s = self.dropout(s)
        s = self.layer_norm(s)

        return s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModuleTransition.__init__(config)

Initializes an instance of the EsmFoldStructureModuleTransition class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object of type 'Config' that holds the configuration settings for the module.

RETURNS DESCRIPTION

None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
def __init__(self, config):
    """
    Initializes an instance of the EsmFoldStructureModuleTransition class.

    Args:
        self: The instance of the class.
        config: An object of type 'Config' that holds the configuration settings for the module.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.config = config

    self.layers = nn.ModuleList()
    for _ in range(config.num_transition_layers):
        l = EsmFoldStructureModuleTransitionLayer(config)
        self.layers.append(l)

    self.dropout = nn.Dropout(p=config.dropout_rate)
    self.layer_norm = nn.LayerNorm(config.sequence_dim)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModuleTransition.forward(s)

Constructs the EsmFoldStructureModuleTransition.

This method takes in two parameters: self and s.

PARAMETER DESCRIPTION
self

An instance of the EsmFoldStructureModuleTransition class.

TYPE: EsmFoldStructureModuleTransition

s

The input data.

TYPE: unknown type

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
def forward(self, s):
    """
    Constructs the EsmFoldStructureModuleTransition.

    This method takes in two parameters: self and s.

    Args:
        self (EsmFoldStructureModuleTransition): An instance of the EsmFoldStructureModuleTransition class.
        s (unknown type): The input data.

    Returns:
        None.

    Raises:
        None.
    """
    for l in self.layers:
        s = l(s)

    s = self.dropout(s)
    s = self.layer_norm(s)

    return s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModuleTransitionLayer

Bases: Module

EsmFoldStructureModuleTransitionLayer

Represents a transition layer for the EsmFold structure module, inheriting from nn.Module.

This class initializes with the provided configuration and forwards a transition layer for the EsmFold structure module using the specified linear layers and activation functions.

ATTRIBUTE DESCRIPTION
linear_1

The first linear layer for the transition.

TYPE: EsmFoldLinear

linear_2

The second linear layer for the transition.

TYPE: EsmFoldLinear

linear_3

The third linear layer for the transition.

TYPE: EsmFoldLinear

relu

The rectified linear unit activation function.

TYPE: ReLU

METHOD DESCRIPTION
forward

Constructs the transition layer for the EsmFold structure module using the input tensor 's'.

RETURNS DESCRIPTION

The output tensor after applying the transition layer to the input tensor 's'.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
class EsmFoldStructureModuleTransitionLayer(nn.Module):

    """
    EsmFoldStructureModuleTransitionLayer

    Represents a transition layer for the EsmFold structure module, inheriting from nn.Module.

    This class initializes with the provided configuration and forwards a transition layer for the EsmFold structure
    module using the specified linear layers and activation functions.

    Attributes:
        linear_1 (EsmFoldLinear): The first linear layer for the transition.
        linear_2 (EsmFoldLinear): The second linear layer for the transition.
        linear_3 (EsmFoldLinear): The third linear layer for the transition.
        relu (nn.ReLU): The rectified linear unit activation function.

    Methods:
        forward(s): Constructs the transition layer for the EsmFold structure module using the input tensor 's'.

    Returns:
        The output tensor after applying the transition layer to the input tensor 's'.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the EsmFoldStructureModuleTransitionLayer class.

        Args:
            self: The instance of the class.
            config:
                The configuration object containing the parameters for initializing the transition layer.

                - Type: object
                - Purpose: Specifies the configuration parameters required for initializing the transition layer.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()

        self.linear_1 = EsmFoldLinear(config.sequence_dim, config.sequence_dim, init="relu")
        self.linear_2 = EsmFoldLinear(config.sequence_dim, config.sequence_dim, init="relu")
        self.linear_3 = EsmFoldLinear(config.sequence_dim, config.sequence_dim, init="final")

        self.relu = nn.ReLU()

    def forward(self, s):
        """Constructs a new EsmFoldStructureModuleTransitionLayer.

        This method takes in two parameters, self and s.

        Args:
            self (EsmFoldStructureModuleTransitionLayer): An instance of the EsmFoldStructureModuleTransitionLayer class.
            s (Tensor): The input tensor.

        Returns:
            Tensor: The output tensor after applying linear transformations and element-wise addition.

        Raises:
            None.
        """
        s_initial = s
        s = self.linear_1(s)
        s = self.relu(s)
        s = self.linear_2(s)
        s = self.relu(s)
        s = self.linear_3(s)

        s = s + s_initial

        return s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModuleTransitionLayer.__init__(config)

Initializes a new instance of the EsmFoldStructureModuleTransitionLayer class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object containing the parameters for initializing the transition layer.

  • Type: object
  • Purpose: Specifies the configuration parameters required for initializing the transition layer.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
def __init__(self, config):
    """
    Initializes a new instance of the EsmFoldStructureModuleTransitionLayer class.

    Args:
        self: The instance of the class.
        config:
            The configuration object containing the parameters for initializing the transition layer.

            - Type: object
            - Purpose: Specifies the configuration parameters required for initializing the transition layer.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()

    self.linear_1 = EsmFoldLinear(config.sequence_dim, config.sequence_dim, init="relu")
    self.linear_2 = EsmFoldLinear(config.sequence_dim, config.sequence_dim, init="relu")
    self.linear_3 = EsmFoldLinear(config.sequence_dim, config.sequence_dim, init="final")

    self.relu = nn.ReLU()

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldStructureModuleTransitionLayer.forward(s)

Constructs a new EsmFoldStructureModuleTransitionLayer.

This method takes in two parameters, self and s.

PARAMETER DESCRIPTION
self

An instance of the EsmFoldStructureModuleTransitionLayer class.

TYPE: EsmFoldStructureModuleTransitionLayer

s

The input tensor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The output tensor after applying linear transformations and element-wise addition.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
def forward(self, s):
    """Constructs a new EsmFoldStructureModuleTransitionLayer.

    This method takes in two parameters, self and s.

    Args:
        self (EsmFoldStructureModuleTransitionLayer): An instance of the EsmFoldStructureModuleTransitionLayer class.
        s (Tensor): The input tensor.

    Returns:
        Tensor: The output tensor after applying linear transformations and element-wise addition.

    Raises:
        None.
    """
    s_initial = s
    s = self.linear_1(s)
    s = self.relu(s)
    s = self.linear_2(s)
    s = self.relu(s)
    s = self.linear_3(s)

    s = s + s_initial

    return s

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangleAttention

Bases: Module

This class represents an attention mechanism called EsmFoldTriangleAttention, which is used in the ESMFold model. It is designed to calculate attention weights between pairs of elements in a tensor.

The EsmFoldTriangleAttention class inherits from the nn.Module class and has the following attributes:

ATTRIBUTE DESCRIPTION
c_in

Input channel dimension.

c_hidden

Overall hidden channel dimension (not per-head).

no_heads

Number of attention heads.

starting

Flag indicating if the attention is applied to the starting point of a pair.

inf

Value used as infinity for masking.

layer_norm

Layer normalization module applied to the input tensor.

linear

Linear transformation layer used for computing triangle biases.

mha

EsmFoldAttention module used for calculating attention weights.

METHOD DESCRIPTION
__init__

Initializes an instance of the EsmFoldTriangleAttention class.

_chunk

Splits the input tensor into chunks and applies the EsmFoldAttention module to each chunk.

forward

Applies the attention mechanism to the input tensor and returns the output tensor.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
593
594
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
class EsmFoldTriangleAttention(nn.Module):

    """
    This class represents an attention mechanism called EsmFoldTriangleAttention, which is used in the ESMFold model.
    It is designed to calculate attention weights between pairs of elements in a tensor.

    The EsmFoldTriangleAttention class inherits from the nn.Module class and has the following attributes:

    Attributes:
        c_in:
            Input channel dimension.
        c_hidden:
            Overall hidden channel dimension (not per-head).
        no_heads:
            Number of attention heads.
        starting:
            Flag indicating if the attention is applied to the starting point of a pair.
        inf:
            Value used as infinity for masking.
        layer_norm:
            Layer normalization module applied to the input tensor.
        linear:
            Linear transformation layer used for computing triangle biases.
        mha:
            EsmFoldAttention module used for calculating attention weights.

    Methods:
        __init__:
            Initializes an instance of the EsmFoldTriangleAttention class.

        _chunk:
            Splits the input tensor into chunks and applies the EsmFoldAttention module to each chunk.

        forward:
            Applies the attention mechanism to the input tensor and returns the output tensor.
    """
    def __init__(self, c_in, c_hidden, no_heads, starting=True, inf=1e9):
        """
        Args:
            c_in:
                Input channel dimension
            c_hidden:
                Overall hidden channel dimension (not per-head)
            no_heads:
                Number of attention heads
        """
        super().__init__()

        self.c_in = c_in
        self.c_hidden = c_hidden
        self.no_heads = no_heads
        self.starting = starting
        self.inf = inf

        self.layer_norm = nn.LayerNorm(self.c_in)

        self.linear = EsmFoldLinear(c_in, self.no_heads, bias=False, init="normal")

        self.mha = EsmFoldAttention(self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads)

    def _chunk(
        self,
        x: mindspore.Tensor,
        biases: List[mindspore.Tensor],
        chunk_size: int,
        use_memory_efficient_kernel: bool = False,
        use_lma: bool = False,
        inplace_safe: bool = False,
    ) -> mindspore.Tensor:
        "triangle! triangle!"
        mha_inputs = {
            "q_x": x,
            "kv_x": x,
            "biases": biases,
        }

        return chunk_layer(
            partial(self.mha, use_memory_efficient_kernel=use_memory_efficient_kernel, use_lma=use_lma),
            mha_inputs,
            chunk_size=chunk_size,
            no_batch_dims=len(x.shape[:-2]),
            _out=x if inplace_safe else None,
        )

    def forward(
        self,
        x: mindspore.Tensor,
        mask: Optional[mindspore.Tensor] = None,
        chunk_size: Optional[int] = None,
        use_memory_efficient_kernel: bool = False,
        use_lma: bool = False,
        inplace_safe: bool = False,
    ) -> mindspore.Tensor:
        """
        Args:
            x:
                [*, I, J, C_in] input tensor (e.g. the pair representation)
        Returns:
            [*, I, J, C_in] output tensor
        """
        if mask is None:
            # [*, I, J]
            mask = x.new_ones(
                x.shape[:-1],
            )

        if not self.starting:
            x = x.swapaxes(-2, -3)
            mask = mask.swapaxes(-1, -2)

        # [*, I, J, C_in]
        x = self.layer_norm(x)

        # [*, I, 1, 1, J]
        mask_bias = (self.inf * (mask - 1))[..., :, None, None, :]

        # [*, H, I, J]
        triangle_bias = permute_final_dims(self.linear(x), (2, 0, 1))

        # [*, 1, H, I, J]
        triangle_bias = triangle_bias.unsqueeze(-4)

        biases = [mask_bias, triangle_bias]

        if chunk_size is not None:
            x = self._chunk(
                x,
                biases,
                chunk_size,
                use_memory_efficient_kernel=use_memory_efficient_kernel,
                use_lma=use_lma,
                inplace_safe=inplace_safe,
            )
        else:
            x = self.mha(
                q_x=x, kv_x=x, biases=biases, use_memory_efficient_kernel=use_memory_efficient_kernel, use_lma=use_lma
            )

        if not self.starting:
            x = x.swapaxes(-2, -3)

        return x

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangleAttention.__init__(c_in, c_hidden, no_heads, starting=True, inf=1000000000.0)

PARAMETER DESCRIPTION
c_in

Input channel dimension

c_hidden

Overall hidden channel dimension (not per-head)

no_heads

Number of attention heads

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def __init__(self, c_in, c_hidden, no_heads, starting=True, inf=1e9):
    """
    Args:
        c_in:
            Input channel dimension
        c_hidden:
            Overall hidden channel dimension (not per-head)
        no_heads:
            Number of attention heads
    """
    super().__init__()

    self.c_in = c_in
    self.c_hidden = c_hidden
    self.no_heads = no_heads
    self.starting = starting
    self.inf = inf

    self.layer_norm = nn.LayerNorm(self.c_in)

    self.linear = EsmFoldLinear(c_in, self.no_heads, bias=False, init="normal")

    self.mha = EsmFoldAttention(self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangleAttention.forward(x, mask=None, chunk_size=None, use_memory_efficient_kernel=False, use_lma=False, inplace_safe=False)

PARAMETER DESCRIPTION
x

[*, I, J, C_in] input tensor (e.g. the pair representation)

TYPE: Tensor

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
def forward(
    self,
    x: mindspore.Tensor,
    mask: Optional[mindspore.Tensor] = None,
    chunk_size: Optional[int] = None,
    use_memory_efficient_kernel: bool = False,
    use_lma: bool = False,
    inplace_safe: bool = False,
) -> mindspore.Tensor:
    """
    Args:
        x:
            [*, I, J, C_in] input tensor (e.g. the pair representation)
    Returns:
        [*, I, J, C_in] output tensor
    """
    if mask is None:
        # [*, I, J]
        mask = x.new_ones(
            x.shape[:-1],
        )

    if not self.starting:
        x = x.swapaxes(-2, -3)
        mask = mask.swapaxes(-1, -2)

    # [*, I, J, C_in]
    x = self.layer_norm(x)

    # [*, I, 1, 1, J]
    mask_bias = (self.inf * (mask - 1))[..., :, None, None, :]

    # [*, H, I, J]
    triangle_bias = permute_final_dims(self.linear(x), (2, 0, 1))

    # [*, 1, H, I, J]
    triangle_bias = triangle_bias.unsqueeze(-4)

    biases = [mask_bias, triangle_bias]

    if chunk_size is not None:
        x = self._chunk(
            x,
            biases,
            chunk_size,
            use_memory_efficient_kernel=use_memory_efficient_kernel,
            use_lma=use_lma,
            inplace_safe=inplace_safe,
        )
    else:
        x = self.mha(
            q_x=x, kv_x=x, biases=biases, use_memory_efficient_kernel=use_memory_efficient_kernel, use_lma=use_lma
        )

    if not self.starting:
        x = x.swapaxes(-2, -3)

    return x

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangleMultiplicativeUpdate

Bases: Module

Implements Algorithms 11 and 12.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
class EsmFoldTriangleMultiplicativeUpdate(nn.Module):
    """
    Implements Algorithms 11 and 12.
    """
    def __init__(self, config, _outgoing=True):
        """
        Initializes an instance of the EsmFoldTriangleMultiplicativeUpdate class.

        Args:
            self: The instance of the class.
            config: An object containing configuration parameters.
            _outgoing (bool): A boolean indicating whether the update is outgoing (default is True).

        Returns:
            None.

        Raises:
            TypeError: If config is not provided or is not of the expected type.
            ValueError: If config.pairwise_state_dim is not accessible or does not have the expected value.
            RuntimeError: If an issue occurs during the initialization of linear layers or normalization layers.
        """
        super().__init__()
        c_hidden = config.pairwise_state_dim
        self._outgoing = _outgoing

        self.linear_a_p = EsmFoldLinear(c_hidden, c_hidden)
        self.linear_a_g = EsmFoldLinear(c_hidden, c_hidden, init="gating")
        self.linear_b_p = EsmFoldLinear(c_hidden, c_hidden)
        self.linear_b_g = EsmFoldLinear(c_hidden, c_hidden, init="gating")
        self.linear_g = EsmFoldLinear(c_hidden, c_hidden, init="gating")
        self.linear_z = EsmFoldLinear(c_hidden, c_hidden, init="final")

        self.layer_norm_in = nn.LayerNorm(c_hidden)
        self.layer_norm_out = nn.LayerNorm(c_hidden)

        self.sigmoid = nn.Sigmoid()

    def _combine_projections(
        self, a: mindspore.Tensor, b: mindspore.Tensor, _inplace_chunk_size: Optional[int] = None
    ) -> mindspore.Tensor:
        """
        Combines two projections using a multiplicative update method.

        Args:
            self (EsmFoldTriangleMultiplicativeUpdate): The instance of the EsmFoldTriangleMultiplicativeUpdate class.
            a (mindspore.Tensor): The first projection tensor.
            b (mindspore.Tensor): The second projection tensor.
            _inplace_chunk_size (Optional[int], optional): The size of the chunk for in-place computation.
                Defaults to None.

        Returns:
            mindspore.Tensor: The combined projection tensor.

        Raises:
            None.
        """
        if self._outgoing:
            a = permute_final_dims(a, (2, 0, 1))
            b = permute_final_dims(b, (2, 1, 0))
        else:
            a = permute_final_dims(a, (2, 1, 0))
            b = permute_final_dims(b, (2, 0, 1))

        if _inplace_chunk_size is not None:
            # To be replaced by torch vmap
            for i in range(0, a.shape[-3], _inplace_chunk_size):
                a_chunk = a[..., i : i + _inplace_chunk_size, :, :]
                b_chunk = b[..., i : i + _inplace_chunk_size, :, :]
                a[..., i : i + _inplace_chunk_size, :, :] = ops.matmul(
                    a_chunk,
                    b_chunk,
                )

            p = a
        else:
            p = ops.matmul(a, b)

        return permute_final_dims(p, (1, 2, 0))

    def _inference_forward(
        self,
        z: mindspore.Tensor,
        mask: Optional[mindspore.Tensor] = None,
        inplace_chunk_size: Optional[int] = None,
        with_add: bool = True,
    ):
        """
        Args:
            z:
                A [*, N, N, C_z] pair representation
            mask:
                A [*, N, N] pair mask
            inplace_chunk_size:
                Size of chunks used in the main computation. Increase to trade memory for speed.
            with_add:
                If True, z is overwritten with (z + update). Otherwise, it is overwritten with (update).
        Returns:
            A reference to the overwritten z

        More memory-efficient, inference-only version of the forward function. Uses in-place operations, fusion of the
        addition that happens after this module in the Evoformer, a smidge of recomputation, and a cache of overwritten
        values to lower peak memory consumption of this module from 5x the size of the input tensor z to 2.5x its size.
        Useful for inference on extremely long sequences.

        It works as follows. We will make reference to variables used in the default forward implementation below.
        Naively, triangle multiplication attention requires the manifestation of 5 tensors the size of z: 1) z, the
        "square" input tensor, 2) a, the first projection of z, 3) b, the second projection of b, 4) g, a z-sized mask,
        and 5) a z-sized tensor for intermediate computations. For large N, this is prohibitively expensive; for
        N=4000, for example, z is more than 8GB alone. To avoid this problem, we compute b, g, and all intermediate
        tensors in small chunks, noting that the chunks required to compute a chunk of the output depend only on the
        tensor a and corresponding vertical and horizontal chunks of z. This suggests an algorithm that loops over
        pairs of chunks of z: hereafter "columns" and "rows" of z, even though each "column" and "row" in fact contains
        inplace_chunk_size contiguous true columns and rows of z. Writing output chunks to a new tensor would bring
        total memory consumption down to 3x the size of z. However, more memory can be saved by writing output chunks
        directly to z in-place. WLOG, we choose to write output chunks vertically, overwriting the ith "column" of z at
        the end of the ith iteration of the main loop. Despite this overwriting, the ith column is always one column
        ahead of previously overwritten columns and can be recovered directly from z. After the first iteration,
        however, the ith row of z is always at least partially overwritten. For this reason, we introduce the z-cache,
        a tensor one-half the size of z. The z-cache initially contains the left half (2nd and 3rd quadrants) of z. For
        0 < i < N/2, the missing left part of the ith row of z is recovered from this cache at the beginning of the ith
        iteration. Once i exceeds n/2, the cache is "reoriented" to encompass the 3rd and 4th quadrants of z instead.
        Though the 3rd quadrant of the original z is entirely overwritten at this point, it can be recovered from the
        z-cache itself. Thereafter, the ith row of z can be recovered in its entirety from the reoriented z-cache.
        After the final iteration, z has been completely overwritten and contains the triangular multiplicative update.
        If with_add is True, it instead contains the sum of z and the triangular multiplicative update. In either case,
        peak memory consumption is just 2.5x the size of z, disregarding memory used for chunks and other small
        variables.
        """
        if mask is None:
            mask = z.new_ones(z.shape[:-1])

        mask = mask.unsqueeze(-1)

        def compute_projection_helper(pair, mask, a=True):
            if a:
                linear_g = self.linear_a_g
                linear_p = self.linear_a_p
            else:
                linear_g = self.linear_b_g
                linear_p = self.linear_b_p

            pair = self.layer_norm_in(pair)
            p = linear_g(pair)
            p = p.sigmoid()
            p *= linear_p(pair)
            p *= mask
            p = permute_final_dims(p, (2, 0, 1))
            return p

        def compute_projection(pair, mask, a=True, chunked=True):
            need_transpose = self._outgoing ^ a
            if not chunked:
                p = compute_projection_helper(pair, mask, a)
                if need_transpose:
                    p = p.swapaxes(-1, -2)
            else:
                # This computation is chunked so as not to exceed our 2.5x
                # budget with a large intermediate tensor
                linear_g = self.linear_a_g if a else self.linear_b_g
                c = linear_g.bias.shape[-1]
                out_shape = pair.shape[:-3] + (c,) + pair.shape[-3:-1]
                p = pair.new_zeros(out_shape)
                for i in range(0, pair.shape[-3], inplace_chunk_size):
                    pair_chunk = pair[..., i : i + inplace_chunk_size, :, :]
                    pair_chunk = compute_projection_helper(
                        pair[..., i : i + inplace_chunk_size, :, :],
                        mask[..., i : i + inplace_chunk_size, :, :],
                        a,
                    )
                    if need_transpose:
                        pair_chunk = pair_chunk.swapaxes(-1, -2)
                        p[..., i : i + inplace_chunk_size] = pair_chunk
                    else:
                        p[..., i : i + inplace_chunk_size, :] = pair_chunk

                    del pair_chunk

            return p

        # We start by fully manifesting a. In addition to the input, this
        # brings total memory consumption to 2x z (disregarding size of chunks)
        # [*, N, N, c]
        a = compute_projection(z, mask, True, chunked=True)

        if inplace_chunk_size is not None:
            n = a.shape[-1]
            half_n = n // 2 + n % 2
            row_dim = -3
            col_dim = -2
            b_chunk_dim = row_dim if self._outgoing else col_dim

            def empty_slicer(t):
                return [slice(None) for _ in t.shape]

            def slice_tensor(t, start, end, dim):
                # Slices start:end from the dim dimension of t
                s = empty_slicer(t)
                s[dim] = slice(start, end)
                return t[s]

            def flip_z_cache_(z_cache, z):
                # "Reorient" the z_cache (see below), filling it with quadrants
                # 3---recovered from the z_cache---and 4---recovered from z---
                # of the input tensor z.
                quadrant_3 = slice_tensor(z_cache, half_n, None, row_dim)
                z_cache = z_cache.swapaxes(row_dim, col_dim)

                # If n is odd, we need to shrink the z_cache by one row
                z_cache = z_cache[..., : (n // 2), :, :]

                # Move the 3rd quadrant of z into the
                first_half_slicer = empty_slicer(z_cache)
                first_half_slicer[col_dim] = slice(0, half_n)
                z_cache[first_half_slicer] = quadrant_3

                # Get the fourth quadrant of z
                quadrant_4 = slice_tensor(z, half_n, None, row_dim)
                quadrant_4 = slice_tensor(quadrant_4, half_n, None, col_dim)

                # Insert said quadrant into the rotated z-cache
                quadrant_3_slicer = empty_slicer(z_cache)
                quadrant_3_slicer[col_dim] = slice(half_n, None)

                z_cache[quadrant_3_slicer] = quadrant_4

                return z_cache

            # Initialize the z cache to the left half of z.
            z_cache_shape = list(z.shape)
            z_cache_shape[col_dim] = half_n
            z_cache = z.new_zeros(z_cache_shape)
            z_cache_slicer = empty_slicer(z_cache)
            z_cache_slicer[col_dim] = slice(0, half_n)
            z_cache[:] = z[z_cache_slicer]
            z_cache_rotated = False

            # We need to reorient the z-cache at the halfway point, and we
            # don't want a single chunk to straddle that point. We contract one
            # of the chunks in the middle to address that problem.
            i_range = list(range(0, half_n, inplace_chunk_size))
            initial_offsets = [i_2 - i_1 for i_1, i_2 in zip(i_range, i_range[1:] + [half_n])]
            after_half = list(range(half_n, n, inplace_chunk_size))
            after_half_offsets = [inplace_chunk_size for _ in after_half]
            combined_range_with_offsets = zip(i_range + after_half, initial_offsets + after_half_offsets)
            for i, offset in combined_range_with_offsets:
                if not z_cache_rotated and i >= half_n:
                    z_cache = flip_z_cache_(z_cache, z)
                    z_cache_rotated = True

                z_chunk_b = slice_tensor(z, i, i + offset, b_chunk_dim)
                mask_chunk = slice_tensor(mask, i, i + offset, b_chunk_dim)

                z_chunk_b = z_chunk_b.copy()
                if b_chunk_dim == col_dim:
                    z_chunk_b = slice_tensor(z, i, i + offset, col_dim)
                else:  # b_chunk_dim == row_dim
                    # In this case, the b-dimension (b_chunk_dim) is partially
                    # overwritten at the end of each iteration. We need to
                    # restore the missing component from the z-cache.
                    if not z_cache_rotated:
                        z_chunk_slicer = empty_slicer(z_chunk_b)
                        z_chunk_slicer[col_dim] = slice(0, half_n)
                        z_chunk_b[z_chunk_slicer] = slice_tensor(z_cache, i, i + offset, row_dim)
                    else:
                        z_cache_offset = i - half_n
                        z_chunk_b = slice_tensor(z_cache, z_cache_offset, z_cache_offset + offset, row_dim)

                b_chunk = compute_projection(z_chunk_b, mask_chunk, a=False, chunked=False)
                del z_chunk_b

                x_chunk = ops.matmul(a, b_chunk)
                x_chunk = permute_final_dims(x_chunk, (1, 2, 0))
                x_chunk = self.layer_norm_out(x_chunk)
                x_chunk = self.linear_z(x_chunk)

                # The g dimension (col_dim) is parallel to and ahead of the
                # overwrites in z. We can extract the g chunk normally.
                z_chunk_g = slice_tensor(z, i, i + offset, col_dim)
                g_chunk = self.linear_g(self.layer_norm_in(z_chunk_g))
                g_chunk = g_chunk.sigmoid()
                del z_chunk_g

                x_chunk *= g_chunk

                # Write the columns into z in-place
                z_slicer = empty_slicer(z)
                z_slicer[col_dim] = slice(i, i + offset)
                if with_add:
                    z[z_slicer] += x_chunk
                else:
                    z[z_slicer] = x_chunk
        else:
            b = compute_projection(z, mask, False, False)
            x = ops.matmul(a, b)
            x = self.layer_norm_out(x)
            x = self.linear_z(x)
            g = self.linear_g(z)
            g = g.sigmoid()
            x *= g
            if with_add:
                z += x
            else:
                z = x

        return z

    def forward(
        self,
        z: mindspore.Tensor,
        mask: Optional[mindspore.Tensor] = None,
        inplace_safe: bool = False,
        _add_with_inplace: bool = False,
        _inplace_chunk_size: Optional[int] = 256,
    ) -> mindspore.Tensor:
        """
        Args:
            x:
                [*, N_res, N_res, C_z] input tensor
            mask:
                [*, N_res, N_res] input mask
        Returns:
            [*, N_res, N_res, C_z] output tensor
        """
        if inplace_safe:
            x = self._inference_forward(
                z,
                mask,
                inplace_chunk_size=_inplace_chunk_size,
                with_add=_add_with_inplace,
            )
            return x

        if mask is None:
            mask = z.new_ones(z.shape[:-1])

        mask = mask.unsqueeze(-1)

        z = self.layer_norm_in(z)
        a = mask
        a = a * self.sigmoid(self.linear_a_g(z))
        a = a * self.linear_a_p(z)
        b = mask
        b = b * self.sigmoid(self.linear_b_g(z))
        b = b * self.linear_b_p(z)

        x = self._combine_projections(a, b)

        del a, b
        x = self.layer_norm_out(x)
        x = self.linear_z(x)
        g = self.sigmoid(self.linear_g(z))
        x = x * g

        return x

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangleMultiplicativeUpdate.__init__(config, _outgoing=True)

Initializes an instance of the EsmFoldTriangleMultiplicativeUpdate class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing configuration parameters.

_outgoing

A boolean indicating whether the update is outgoing (default is True).

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If config is not provided or is not of the expected type.

ValueError

If config.pairwise_state_dim is not accessible or does not have the expected value.

RuntimeError

If an issue occurs during the initialization of linear layers or normalization layers.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
def __init__(self, config, _outgoing=True):
    """
    Initializes an instance of the EsmFoldTriangleMultiplicativeUpdate class.

    Args:
        self: The instance of the class.
        config: An object containing configuration parameters.
        _outgoing (bool): A boolean indicating whether the update is outgoing (default is True).

    Returns:
        None.

    Raises:
        TypeError: If config is not provided or is not of the expected type.
        ValueError: If config.pairwise_state_dim is not accessible or does not have the expected value.
        RuntimeError: If an issue occurs during the initialization of linear layers or normalization layers.
    """
    super().__init__()
    c_hidden = config.pairwise_state_dim
    self._outgoing = _outgoing

    self.linear_a_p = EsmFoldLinear(c_hidden, c_hidden)
    self.linear_a_g = EsmFoldLinear(c_hidden, c_hidden, init="gating")
    self.linear_b_p = EsmFoldLinear(c_hidden, c_hidden)
    self.linear_b_g = EsmFoldLinear(c_hidden, c_hidden, init="gating")
    self.linear_g = EsmFoldLinear(c_hidden, c_hidden, init="gating")
    self.linear_z = EsmFoldLinear(c_hidden, c_hidden, init="final")

    self.layer_norm_in = nn.LayerNorm(c_hidden)
    self.layer_norm_out = nn.LayerNorm(c_hidden)

    self.sigmoid = nn.Sigmoid()

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangleMultiplicativeUpdate.forward(z, mask=None, inplace_safe=False, _add_with_inplace=False, _inplace_chunk_size=256)

PARAMETER DESCRIPTION
x

[*, N_res, N_res, C_z] input tensor

mask

[*, N_res, N_res] input mask

TYPE: Optional[Tensor] DEFAULT: None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def forward(
    self,
    z: mindspore.Tensor,
    mask: Optional[mindspore.Tensor] = None,
    inplace_safe: bool = False,
    _add_with_inplace: bool = False,
    _inplace_chunk_size: Optional[int] = 256,
) -> mindspore.Tensor:
    """
    Args:
        x:
            [*, N_res, N_res, C_z] input tensor
        mask:
            [*, N_res, N_res] input mask
    Returns:
        [*, N_res, N_res, C_z] output tensor
    """
    if inplace_safe:
        x = self._inference_forward(
            z,
            mask,
            inplace_chunk_size=_inplace_chunk_size,
            with_add=_add_with_inplace,
        )
        return x

    if mask is None:
        mask = z.new_ones(z.shape[:-1])

    mask = mask.unsqueeze(-1)

    z = self.layer_norm_in(z)
    a = mask
    a = a * self.sigmoid(self.linear_a_g(z))
    a = a * self.linear_a_p(z)
    b = mask
    b = b * self.sigmoid(self.linear_b_g(z))
    b = b * self.linear_b_p(z)

    x = self._combine_projections(a, b)

    del a, b
    x = self.layer_norm_out(x)
    x = self.linear_z(x)
    g = self.sigmoid(self.linear_g(z))
    x = x * g

    return x

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangularSelfAttentionBlock

Bases: Module

This class represents a block of Triangular Self-Attention for the EsmFold model. It is used to process sequence and pairwise states in the EsmFold model.

ATTRIBUTE DESCRIPTION
layernorm_1

A layer normalization module for the sequence state dimension.

TYPE: LayerNorm

sequence_to_pair

A module that converts the sequence state to pairwise state.

TYPE: EsmFoldSequenceToPair

pair_to_sequence

A module that converts the pairwise state to sequence state.

TYPE: EsmFoldPairToSequence

seq_attention

A self-attention module for the sequence state.

TYPE: EsmFoldSelfAttention

tri_mul_out

A module that performs triangular multiplicative update on the pairwise state.

TYPE: EsmFoldTriangleMultiplicativeUpdate

tri_mul_in

A module that performs triangular multiplicative update on the pairwise state.

TYPE: EsmFoldTriangleMultiplicativeUpdate

tri_att_start

A module that performs triangular attention on the pairwise state starting from a specific position.

TYPE: EsmFoldTriangleAttention

tri_att_end

A module that performs triangular attention on the pairwise state ending at a specific position.

TYPE: EsmFoldTriangleAttention

mlp_seq

A multilayer perceptron module for the sequence state.

TYPE: EsmFoldResidueMLP

mlp_pair

A multilayer perceptron module for the pairwise state.

TYPE: EsmFoldResidueMLP

drop

A dropout module.

TYPE: Dropout

row_drop

A dropout module that applies dropout on rows of the pairwise state.

TYPE: EsmFoldDropout

col_drop

A dropout module that applies dropout on columns of the pairwise state.

TYPE: EsmFoldDropout

METHOD DESCRIPTION
forward

Process the sequence and pairwise states.

Args:

  • sequence_state (torch.Tensor): Input sequence state tensor of shape (batch_size, sequence_length, sequence_state_dim).
  • pairwise_state (torch.Tensor): Input pairwise state tensor of shape (batch_size, sequence_length, sequence_length, pairwise_state_dim).
  • mask (torch.Tensor, optional): Boolean tensor of valid positions, with shape (batch_size, sequence_length). Defaults to None.
  • chunk_size (int, optional): The size of the attention chunks. Defaults to None.

Returns:

  • sequence_state (torch.Tensor): Processed sequence state tensor of shape (batch_size, sequence_length, sequence_state_dim).
  • pairwise_state (torch.Tensor): Processed pairwise state tensor of shape (batch_size, sequence_length, sequence_length, pairwise_state_dim).
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
class EsmFoldTriangularSelfAttentionBlock(nn.Module):

    """
    This class represents a block of Triangular Self-Attention for the EsmFold model.
    It is used to process sequence and pairwise states in the EsmFold model.

    Attributes:
        layernorm_1 (nn.LayerNorm): A layer normalization module for the sequence state dimension.
        sequence_to_pair (EsmFoldSequenceToPair): A module that converts the sequence state to pairwise state.
        pair_to_sequence (EsmFoldPairToSequence): A module that converts the pairwise state to sequence state.
        seq_attention (EsmFoldSelfAttention): A self-attention module for the sequence state.
        tri_mul_out (EsmFoldTriangleMultiplicativeUpdate):
            A module that performs triangular multiplicative update on the pairwise state.
        tri_mul_in (EsmFoldTriangleMultiplicativeUpdate):
            A module that performs triangular multiplicative update on the pairwise state.
        tri_att_start (EsmFoldTriangleAttention):
            A module that performs triangular attention on the pairwise state starting from a specific position.
        tri_att_end (EsmFoldTriangleAttention):
            A module that performs triangular attention on the pairwise state ending at a specific position.
        mlp_seq (EsmFoldResidueMLP): A multilayer perceptron module for the sequence state.
        mlp_pair (EsmFoldResidueMLP): A multilayer perceptron module for the pairwise state.
        drop (nn.Dropout): A dropout module.
        row_drop (EsmFoldDropout): A dropout module that applies dropout on rows of the pairwise state.
        col_drop (EsmFoldDropout): A dropout module that applies dropout on columns of the pairwise state.

    Methods:
        forward(sequence_state, pairwise_state, mask=None, chunk_size=None, **__kwargs):
            Process the sequence and pairwise states.

            Args:

            - sequence_state (torch.Tensor): Input sequence state tensor of shape
            (batch_size, sequence_length, sequence_state_dim).
            - pairwise_state (torch.Tensor): Input pairwise state tensor of shape
            (batch_size, sequence_length, sequence_length, pairwise_state_dim).
            - mask (torch.Tensor, optional): Boolean tensor of valid positions, with shape
            (batch_size, sequence_length). Defaults to None.
            - chunk_size (int, optional): The size of the attention chunks. Defaults to None.

            Returns:

            - sequence_state (torch.Tensor): Processed sequence state tensor of shape
            (batch_size, sequence_length, sequence_state_dim).
            - pairwise_state (torch.Tensor): Processed pairwise state tensor of shape
            (batch_size, sequence_length, sequence_length, pairwise_state_dim).
    """
    def __init__(self, config):
        """
        This method initializes an instance of the EsmFoldTriangularSelfAttentionBlock class.

        Args:
            self: The instance of the EsmFoldTriangularSelfAttentionBlock class.
            config: The configuration object containing parameters for the attention block.

        Returns:
            None.

        Raises:
            NotImplementedError: If the method is not implemented for any reason.
            ValueError: If the provided configuration object is invalid or missing required parameters.
            TypeError: If the provided configuration object is of incorrect type.
        """
        super().__init__()
        self.config = config

        sequence_state_dim = config.sequence_state_dim
        pairwise_state_dim = config.pairwise_state_dim
        sequence_num_heads = sequence_state_dim // config.sequence_head_width
        pairwise_num_heads = pairwise_state_dim // config.pairwise_head_width

        self.layernorm_1 = nn.LayerNorm(sequence_state_dim)

        self.sequence_to_pair = EsmFoldSequenceToPair(sequence_state_dim, pairwise_state_dim // 2, pairwise_state_dim)
        self.pair_to_sequence = EsmFoldPairToSequence(pairwise_state_dim, sequence_num_heads)

        self.seq_attention = EsmFoldSelfAttention(
            sequence_state_dim, sequence_num_heads, config.sequence_head_width, gated=True
        )
        self.tri_mul_out = EsmFoldTriangleMultiplicativeUpdate(config, _outgoing=True)
        self.tri_mul_in = EsmFoldTriangleMultiplicativeUpdate(config, _outgoing=False)

        self.tri_att_start = EsmFoldTriangleAttention(
            pairwise_state_dim, config.pairwise_head_width, pairwise_num_heads, inf=1e9, starting=True
        )
        self.tri_att_end = EsmFoldTriangleAttention(
            pairwise_state_dim, config.pairwise_head_width, pairwise_num_heads, inf=1e9, starting=False
        )

        self.mlp_seq = EsmFoldResidueMLP(sequence_state_dim, 4 * sequence_state_dim, dropout=config.dropout)
        self.mlp_pair = EsmFoldResidueMLP(pairwise_state_dim, 4 * pairwise_state_dim, dropout=config.dropout)

        self.drop = nn.Dropout(p=config.dropout)
        self.row_drop = EsmFoldDropout(config.dropout * 2, 2)
        self.col_drop = EsmFoldDropout(config.dropout * 2, 1)

    def forward(self, sequence_state, pairwise_state, mask=None, chunk_size=None, **__kwargs):
        """
        Inputs:
          sequence_state: B x L x sequence_state_dim pairwise_state: B x L x L x pairwise_state_dim mask: B x L boolean
          tensor of valid positions

        Output:
          sequence_state: B x L x sequence_state_dim pairwise_state: B x L x L x pairwise_state_dim
        """
        if len(sequence_state.shape) != 3:
            raise ValueError(f"`sequence_state` should be a 3d-tensor, got {len(sequence_state.shape)} dims.")
        if len(pairwise_state.shape) != 4:
            raise ValueError(f"`pairwise_state` should be a 4d-tensor, got {len(pairwise_state.shape)} dims.")
        if mask is not None and len(mask.shape) != 2:
            raise ValueError(f"`mask` should be a 2d-tensor, got {len(mask.shape)} dims.")

        batch_dim, seq_dim, sequence_state_dim = sequence_state.shape
        pairwise_state_dim = pairwise_state.shape[3]

        if sequence_state_dim != self.config.sequence_state_dim:
            raise ValueError(
                "`sequence_state` last dimension should be equal to `self.sequence_state_dim`. Got "
                f"{sequence_state_dim} != {self.config.sequence_state_dim}."
            )
        if pairwise_state_dim != self.config.pairwise_state_dim:
            raise ValueError(
                "`pairwise_state` last dimension should be equal to `self.pairwise_state_dim`. Got "
                f"{pairwise_state_dim} != {self.config.pairwise_state_dim}."
            )
        if batch_dim != pairwise_state.shape[0]:
            raise ValueError(
                f"`sequence_state` and `pairwise_state` have inconsistent batch size: {batch_dim} != "
                f"{pairwise_state.shape[0]}."
            )
        if seq_dim != pairwise_state.shape[1] or seq_dim != pairwise_state.shape[2]:
            raise ValueError(
                f"`sequence_state` and `pairwise_state` have inconsistent sequence length: {seq_dim} != "
                f"{pairwise_state.shape[1]} or {pairwise_state.shape[2]}."
            )

        # Update sequence state
        bias = self.pair_to_sequence(pairwise_state)

        # Self attention with bias + mlp.
        y = self.layernorm_1(sequence_state)
        y, _ = self.seq_attention(y, mask=mask, bias=bias)
        sequence_state = sequence_state + self.drop(y)
        sequence_state = self.mlp_seq(sequence_state)

        # Update pairwise state
        pairwise_state = pairwise_state + self.sequence_to_pair(sequence_state)

        # Axial attention with triangular bias.
        tri_mask = mask.unsqueeze(2) * mask.unsqueeze(1) if mask is not None else None
        pairwise_state = pairwise_state + self.row_drop(self.tri_mul_out(pairwise_state, mask=tri_mask))
        pairwise_state = pairwise_state + self.col_drop(self.tri_mul_in(pairwise_state, mask=tri_mask))
        pairwise_state = pairwise_state + self.row_drop(
            self.tri_att_start(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
        )
        pairwise_state = pairwise_state + self.col_drop(
            self.tri_att_end(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
        )

        # MLP over pairs.
        pairwise_state = self.mlp_pair(pairwise_state)

        return sequence_state, pairwise_state

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangularSelfAttentionBlock.__init__(config)

This method initializes an instance of the EsmFoldTriangularSelfAttentionBlock class.

PARAMETER DESCRIPTION
self

The instance of the EsmFoldTriangularSelfAttentionBlock class.

config

The configuration object containing parameters for the attention block.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
NotImplementedError

If the method is not implemented for any reason.

ValueError

If the provided configuration object is invalid or missing required parameters.

TypeError

If the provided configuration object is of incorrect type.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
def __init__(self, config):
    """
    This method initializes an instance of the EsmFoldTriangularSelfAttentionBlock class.

    Args:
        self: The instance of the EsmFoldTriangularSelfAttentionBlock class.
        config: The configuration object containing parameters for the attention block.

    Returns:
        None.

    Raises:
        NotImplementedError: If the method is not implemented for any reason.
        ValueError: If the provided configuration object is invalid or missing required parameters.
        TypeError: If the provided configuration object is of incorrect type.
    """
    super().__init__()
    self.config = config

    sequence_state_dim = config.sequence_state_dim
    pairwise_state_dim = config.pairwise_state_dim
    sequence_num_heads = sequence_state_dim // config.sequence_head_width
    pairwise_num_heads = pairwise_state_dim // config.pairwise_head_width

    self.layernorm_1 = nn.LayerNorm(sequence_state_dim)

    self.sequence_to_pair = EsmFoldSequenceToPair(sequence_state_dim, pairwise_state_dim // 2, pairwise_state_dim)
    self.pair_to_sequence = EsmFoldPairToSequence(pairwise_state_dim, sequence_num_heads)

    self.seq_attention = EsmFoldSelfAttention(
        sequence_state_dim, sequence_num_heads, config.sequence_head_width, gated=True
    )
    self.tri_mul_out = EsmFoldTriangleMultiplicativeUpdate(config, _outgoing=True)
    self.tri_mul_in = EsmFoldTriangleMultiplicativeUpdate(config, _outgoing=False)

    self.tri_att_start = EsmFoldTriangleAttention(
        pairwise_state_dim, config.pairwise_head_width, pairwise_num_heads, inf=1e9, starting=True
    )
    self.tri_att_end = EsmFoldTriangleAttention(
        pairwise_state_dim, config.pairwise_head_width, pairwise_num_heads, inf=1e9, starting=False
    )

    self.mlp_seq = EsmFoldResidueMLP(sequence_state_dim, 4 * sequence_state_dim, dropout=config.dropout)
    self.mlp_pair = EsmFoldResidueMLP(pairwise_state_dim, 4 * pairwise_state_dim, dropout=config.dropout)

    self.drop = nn.Dropout(p=config.dropout)
    self.row_drop = EsmFoldDropout(config.dropout * 2, 2)
    self.col_drop = EsmFoldDropout(config.dropout * 2, 1)

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldTriangularSelfAttentionBlock.forward(sequence_state, pairwise_state, mask=None, chunk_size=None, **__kwargs)

Inputs

tensor of valid positions

Output
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
def forward(self, sequence_state, pairwise_state, mask=None, chunk_size=None, **__kwargs):
    """
    Inputs:
      sequence_state: B x L x sequence_state_dim pairwise_state: B x L x L x pairwise_state_dim mask: B x L boolean
      tensor of valid positions

    Output:
      sequence_state: B x L x sequence_state_dim pairwise_state: B x L x L x pairwise_state_dim
    """
    if len(sequence_state.shape) != 3:
        raise ValueError(f"`sequence_state` should be a 3d-tensor, got {len(sequence_state.shape)} dims.")
    if len(pairwise_state.shape) != 4:
        raise ValueError(f"`pairwise_state` should be a 4d-tensor, got {len(pairwise_state.shape)} dims.")
    if mask is not None and len(mask.shape) != 2:
        raise ValueError(f"`mask` should be a 2d-tensor, got {len(mask.shape)} dims.")

    batch_dim, seq_dim, sequence_state_dim = sequence_state.shape
    pairwise_state_dim = pairwise_state.shape[3]

    if sequence_state_dim != self.config.sequence_state_dim:
        raise ValueError(
            "`sequence_state` last dimension should be equal to `self.sequence_state_dim`. Got "
            f"{sequence_state_dim} != {self.config.sequence_state_dim}."
        )
    if pairwise_state_dim != self.config.pairwise_state_dim:
        raise ValueError(
            "`pairwise_state` last dimension should be equal to `self.pairwise_state_dim`. Got "
            f"{pairwise_state_dim} != {self.config.pairwise_state_dim}."
        )
    if batch_dim != pairwise_state.shape[0]:
        raise ValueError(
            f"`sequence_state` and `pairwise_state` have inconsistent batch size: {batch_dim} != "
            f"{pairwise_state.shape[0]}."
        )
    if seq_dim != pairwise_state.shape[1] or seq_dim != pairwise_state.shape[2]:
        raise ValueError(
            f"`sequence_state` and `pairwise_state` have inconsistent sequence length: {seq_dim} != "
            f"{pairwise_state.shape[1]} or {pairwise_state.shape[2]}."
        )

    # Update sequence state
    bias = self.pair_to_sequence(pairwise_state)

    # Self attention with bias + mlp.
    y = self.layernorm_1(sequence_state)
    y, _ = self.seq_attention(y, mask=mask, bias=bias)
    sequence_state = sequence_state + self.drop(y)
    sequence_state = self.mlp_seq(sequence_state)

    # Update pairwise state
    pairwise_state = pairwise_state + self.sequence_to_pair(sequence_state)

    # Axial attention with triangular bias.
    tri_mask = mask.unsqueeze(2) * mask.unsqueeze(1) if mask is not None else None
    pairwise_state = pairwise_state + self.row_drop(self.tri_mul_out(pairwise_state, mask=tri_mask))
    pairwise_state = pairwise_state + self.col_drop(self.tri_mul_in(pairwise_state, mask=tri_mask))
    pairwise_state = pairwise_state + self.row_drop(
        self.tri_att_start(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
    )
    pairwise_state = pairwise_state + self.col_drop(
        self.tri_att_end(pairwise_state, mask=tri_mask, chunk_size=chunk_size)
    )

    # MLP over pairs.
    pairwise_state = self.mlp_pair(pairwise_state)

    return sequence_state, pairwise_state

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldingTrunk

Bases: Module

EsmFoldingTrunk is a neural network cell that represents the trunk of the ESM-Fold model. It inherits from the nn.Module class and contains methods for initializing and forwarding the model, as well as a static method for computing distograms.

ATTRIBUTE DESCRIPTION
config

A configuration object specifying the dimensions and parameters for the ESM-Fold model.

METHOD DESCRIPTION
__init__

Initializes the EsmFoldingTrunk instance with the provided configuration.

set_chunk_size

Sets the chunk size for processing sequences and pair features.

forward

Constructs the ESM-Fold model using the provided input tensors and parameters, and returns the

distogram

A static method that computes distograms based on the input coordinates and bin parameters.

Note

This class assumes the presence of the required modules and dependencies for the ESM-Fold model.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
class EsmFoldingTrunk(nn.Module):

    """
    EsmFoldingTrunk is a neural network cell that represents the trunk of the ESM-Fold model.
    It inherits from the nn.Module class and contains methods for initializing and forwarding the model, as well as a
    static method for computing distograms.

    Attributes:
        config: A configuration object specifying the dimensions and parameters for the ESM-Fold model.

    Methods:
        __init__: Initializes the EsmFoldingTrunk instance with the provided configuration.

        set_chunk_size: Sets the chunk size for processing sequences and pair features.

        forward: Constructs the ESM-Fold model using the provided input tensors and parameters, and returns the
        predicted structure wrapped in a Coordinates object.

        distogram(coords, min_bin, max_bin, num_bins):
            A static method that computes distograms based on the input coordinates and bin parameters.

    Note:
        This class assumes the presence of the required modules and dependencies for the ESM-Fold model.
    """
    def __init__(self, config):
        '''
        Initializes an instance of the EsmFoldingTrunk class.

        Args:
            self: The instance of the class.
            config:
                An object containing the configuration parameters for the EsmFoldingTrunk.

                - sequence_state_dim: An integer representing the dimension of the sequence state.
                - pairwise_state_dim: An integer representing the dimension of the pairwise state.
                - num_blocks: An integer specifying the number of blocks.
                - structure_module: An object containing the configuration parameters for the structure module.

                    - sequence_dim: An integer representing the dimension of the sequence.
                    - pairwise_dim: An integer representing the dimension of the pairwise.

        Returns:
            None

        Raises:
            None
        '''
        super().__init__()
        self.config = config

        c_s = config.sequence_state_dim
        c_z = config.pairwise_state_dim

        self.pairwise_positional_embedding = EsmFoldRelativePosition(config)

        self.blocks = nn.ModuleList([EsmFoldTriangularSelfAttentionBlock(config) for _ in range(config.num_blocks)])

        self.recycle_bins = 15
        self.recycle_s_norm = nn.LayerNorm(c_s)
        self.recycle_z_norm = nn.LayerNorm(c_z)
        self.recycle_disto = nn.Embedding(self.recycle_bins, c_z)
        self.recycle_disto.weight[0] = 0

        self.structure_module = EsmFoldStructureModule(config.structure_module)
        self.trunk2sm_s = nn.Linear(c_s, config.structure_module.sequence_dim)
        self.trunk2sm_z = nn.Linear(c_z, config.structure_module.pairwise_dim)

        self.chunk_size = config.chunk_size

    def set_chunk_size(self, chunk_size):
        """
        Sets the chunk size for the EsmFoldingTrunk.

        Args:
            self: The instance of the EsmFoldingTrunk class.
            chunk_size (int): The size of the chunk to be set. It should be a positive integer.

        Returns:
            None.

        Raises:
            None.
        """
        # This parameter means the axial attention will be computed
        # in a chunked manner. This should make the memory used more or less O(L) instead of O(L^2).
        # It's equivalent to running a for loop over chunks of the dimension we're iterative over,
        # where the chunk_size is the size of the chunks, so 128 would mean to parse 128-length chunks.
        self.chunk_size = chunk_size

    def forward(self, seq_feats, pair_feats, true_aa, residx, mask, no_recycles):
        """
        Inputs:
            seq_feats: B x L x C tensor of sequence features pair_feats: B x L x L x C tensor of pair features residx: B
            x L long tensor giving the position in the sequence mask: B x L boolean tensor indicating valid residues

        Output:
            predicted_structure: B x L x (num_atoms_per_residue * 3) tensor wrapped in a Coordinates object
        """
        s_s_0 = seq_feats
        s_z_0 = pair_feats

        if no_recycles is None:
            no_recycles = self.config.max_recycles
        else:
            if no_recycles < 0:
                raise ValueError("Number of recycles must not be negative.")
            no_recycles += 1  # First 'recycle' is just the standard forward pass through the model.

        def trunk_iter(s, z, residx, mask):
            z = z + self.pairwise_positional_embedding(residx, mask=mask)

            for block in self.blocks:
                s, z = block(s, z, mask=mask, residue_index=residx, chunk_size=self.chunk_size)
            return s, z

        s_s = s_s_0
        s_z = s_z_0
        recycle_s = ops.zeros_like(s_s)
        recycle_z = ops.zeros_like(s_z)
        recycle_bins = ops.zeros(*s_z.shape[:-1], dtype=mindspore.int64)

        for _ in range(no_recycles):
            with ContextManagers([]):
                # === Recycling ===
                recycle_s = self.recycle_s_norm(recycle_s)
                recycle_z = self.recycle_z_norm(recycle_z)
                recycle_z += self.recycle_disto(recycle_bins)

                s_s, s_z = trunk_iter(s_s_0 + recycle_s, s_z_0 + recycle_z, residx, mask)

                # === Structure module ===
                structure = self.structure_module(
                    {"single": self.trunk2sm_s(s_s), "pair": self.trunk2sm_z(s_z)},
                    true_aa,
                    mask.float(),
                )

                recycle_s = s_s
                recycle_z = s_z
                # Distogram needs the N, CA, C coordinates, and bin constants same as alphafold.
                recycle_bins = EsmFoldingTrunk.distogram(
                    structure["positions"][-1][:, :, :3],
                    3.375,
                    21.375,
                    self.recycle_bins,
                )

        structure["s_s"] = s_s
        structure["s_z"] = s_z

        return structure

    @staticmethod
    def distogram(coords, min_bin, max_bin, num_bins):
        """
        Method to calculate the distance histogram based on the provided coordinates.

        Args:
            coords (Tensor): A tensor containing the coordinates of atoms in the structure.
                Expected shape should be (N, 3, L), where N is the number of atoms, 3 represents x, y, z coordinates,
                and L is the length of the structure.
            min_bin (int): The minimum distance value for binning the distances.
            max_bin (int): The maximum distance value for binning the distances.
            num_bins (int): The number of bins to divide the distance range into.

        Returns:
            None: The method calculates the distance histogram and returns the histogram bins.

        Raises:
            ValueError: If the input coordinates tensor is not in the expected shape or if any of the distance
                parameters (min_bin, max_bin, num_bins) are invalid.
            RuntimeError: If there is an issue with the calculation process.
        """
        # Coords are [... L x 3 x 3], where it's [N, CA, C] x 3 coordinates.
        boundaries = ops.linspace(
            min_bin,
            max_bin,
            num_bins - 1,
        )
        boundaries = boundaries**2
        N, CA, C = [x.squeeze(-2) for x in coords.chunk(3, axis=-2)]
        # Infer CB coordinates.
        b = CA - N
        c = C - CA
        a = mindspore.numpy.cross(b, c, axis=-1)
        CB = -0.58273431 * a + 0.56802827 * b - 0.54067466 * c + CA
        dists = (CB[..., None, :, :] - CB[..., :, None, :]).pow(2).sum(axis=-1, keepdims=True)
        bins = ops.sum(dists > boundaries, dim=-1)  # [..., L, L]
        return bins

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldingTrunk.__init__(config)

Initializes an instance of the EsmFoldingTrunk class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration parameters for the EsmFoldingTrunk.

  • sequence_state_dim: An integer representing the dimension of the sequence state.
  • pairwise_state_dim: An integer representing the dimension of the pairwise state.
  • num_blocks: An integer specifying the number of blocks.
  • structure_module: An object containing the configuration parameters for the structure module.

    • sequence_dim: An integer representing the dimension of the sequence.
    • pairwise_dim: An integer representing the dimension of the pairwise.

RETURNS DESCRIPTION

None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
def __init__(self, config):
    '''
    Initializes an instance of the EsmFoldingTrunk class.

    Args:
        self: The instance of the class.
        config:
            An object containing the configuration parameters for the EsmFoldingTrunk.

            - sequence_state_dim: An integer representing the dimension of the sequence state.
            - pairwise_state_dim: An integer representing the dimension of the pairwise state.
            - num_blocks: An integer specifying the number of blocks.
            - structure_module: An object containing the configuration parameters for the structure module.

                - sequence_dim: An integer representing the dimension of the sequence.
                - pairwise_dim: An integer representing the dimension of the pairwise.

    Returns:
        None

    Raises:
        None
    '''
    super().__init__()
    self.config = config

    c_s = config.sequence_state_dim
    c_z = config.pairwise_state_dim

    self.pairwise_positional_embedding = EsmFoldRelativePosition(config)

    self.blocks = nn.ModuleList([EsmFoldTriangularSelfAttentionBlock(config) for _ in range(config.num_blocks)])

    self.recycle_bins = 15
    self.recycle_s_norm = nn.LayerNorm(c_s)
    self.recycle_z_norm = nn.LayerNorm(c_z)
    self.recycle_disto = nn.Embedding(self.recycle_bins, c_z)
    self.recycle_disto.weight[0] = 0

    self.structure_module = EsmFoldStructureModule(config.structure_module)
    self.trunk2sm_s = nn.Linear(c_s, config.structure_module.sequence_dim)
    self.trunk2sm_z = nn.Linear(c_z, config.structure_module.pairwise_dim)

    self.chunk_size = config.chunk_size

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldingTrunk.distogram(coords, min_bin, max_bin, num_bins) staticmethod

Method to calculate the distance histogram based on the provided coordinates.

PARAMETER DESCRIPTION
coords

A tensor containing the coordinates of atoms in the structure. Expected shape should be (N, 3, L), where N is the number of atoms, 3 represents x, y, z coordinates, and L is the length of the structure.

TYPE: Tensor

min_bin

The minimum distance value for binning the distances.

TYPE: int

max_bin

The maximum distance value for binning the distances.

TYPE: int

num_bins

The number of bins to divide the distance range into.

TYPE: int

RETURNS DESCRIPTION
None

The method calculates the distance histogram and returns the histogram bins.

RAISES DESCRIPTION
ValueError

If the input coordinates tensor is not in the expected shape or if any of the distance parameters (min_bin, max_bin, num_bins) are invalid.

RuntimeError

If there is an issue with the calculation process.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
@staticmethod
def distogram(coords, min_bin, max_bin, num_bins):
    """
    Method to calculate the distance histogram based on the provided coordinates.

    Args:
        coords (Tensor): A tensor containing the coordinates of atoms in the structure.
            Expected shape should be (N, 3, L), where N is the number of atoms, 3 represents x, y, z coordinates,
            and L is the length of the structure.
        min_bin (int): The minimum distance value for binning the distances.
        max_bin (int): The maximum distance value for binning the distances.
        num_bins (int): The number of bins to divide the distance range into.

    Returns:
        None: The method calculates the distance histogram and returns the histogram bins.

    Raises:
        ValueError: If the input coordinates tensor is not in the expected shape or if any of the distance
            parameters (min_bin, max_bin, num_bins) are invalid.
        RuntimeError: If there is an issue with the calculation process.
    """
    # Coords are [... L x 3 x 3], where it's [N, CA, C] x 3 coordinates.
    boundaries = ops.linspace(
        min_bin,
        max_bin,
        num_bins - 1,
    )
    boundaries = boundaries**2
    N, CA, C = [x.squeeze(-2) for x in coords.chunk(3, axis=-2)]
    # Infer CB coordinates.
    b = CA - N
    c = C - CA
    a = mindspore.numpy.cross(b, c, axis=-1)
    CB = -0.58273431 * a + 0.56802827 * b - 0.54067466 * c + CA
    dists = (CB[..., None, :, :] - CB[..., :, None, :]).pow(2).sum(axis=-1, keepdims=True)
    bins = ops.sum(dists > boundaries, dim=-1)  # [..., L, L]
    return bins

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldingTrunk.forward(seq_feats, pair_feats, true_aa, residx, mask, no_recycles)

Inputs

x L long tensor giving the position in the sequence mask: B x L boolean tensor indicating valid residues

Output
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
def forward(self, seq_feats, pair_feats, true_aa, residx, mask, no_recycles):
    """
    Inputs:
        seq_feats: B x L x C tensor of sequence features pair_feats: B x L x L x C tensor of pair features residx: B
        x L long tensor giving the position in the sequence mask: B x L boolean tensor indicating valid residues

    Output:
        predicted_structure: B x L x (num_atoms_per_residue * 3) tensor wrapped in a Coordinates object
    """
    s_s_0 = seq_feats
    s_z_0 = pair_feats

    if no_recycles is None:
        no_recycles = self.config.max_recycles
    else:
        if no_recycles < 0:
            raise ValueError("Number of recycles must not be negative.")
        no_recycles += 1  # First 'recycle' is just the standard forward pass through the model.

    def trunk_iter(s, z, residx, mask):
        z = z + self.pairwise_positional_embedding(residx, mask=mask)

        for block in self.blocks:
            s, z = block(s, z, mask=mask, residue_index=residx, chunk_size=self.chunk_size)
        return s, z

    s_s = s_s_0
    s_z = s_z_0
    recycle_s = ops.zeros_like(s_s)
    recycle_z = ops.zeros_like(s_z)
    recycle_bins = ops.zeros(*s_z.shape[:-1], dtype=mindspore.int64)

    for _ in range(no_recycles):
        with ContextManagers([]):
            # === Recycling ===
            recycle_s = self.recycle_s_norm(recycle_s)
            recycle_z = self.recycle_z_norm(recycle_z)
            recycle_z += self.recycle_disto(recycle_bins)

            s_s, s_z = trunk_iter(s_s_0 + recycle_s, s_z_0 + recycle_z, residx, mask)

            # === Structure module ===
            structure = self.structure_module(
                {"single": self.trunk2sm_s(s_s), "pair": self.trunk2sm_z(s_z)},
                true_aa,
                mask.float(),
            )

            recycle_s = s_s
            recycle_z = s_z
            # Distogram needs the N, CA, C coordinates, and bin constants same as alphafold.
            recycle_bins = EsmFoldingTrunk.distogram(
                structure["positions"][-1][:, :, :3],
                3.375,
                21.375,
                self.recycle_bins,
            )

    structure["s_s"] = s_s
    structure["s_z"] = s_z

    return structure

mindnlp.transformers.models.esm.modeling_esmfold.EsmFoldingTrunk.set_chunk_size(chunk_size)

Sets the chunk size for the EsmFoldingTrunk.

PARAMETER DESCRIPTION
self

The instance of the EsmFoldingTrunk class.

chunk_size

The size of the chunk to be set. It should be a positive integer.

TYPE: int

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
def set_chunk_size(self, chunk_size):
    """
    Sets the chunk size for the EsmFoldingTrunk.

    Args:
        self: The instance of the EsmFoldingTrunk class.
        chunk_size (int): The size of the chunk to be set. It should be a positive integer.

    Returns:
        None.

    Raises:
        None.
    """
    # This parameter means the axial attention will be computed
    # in a chunked manner. This should make the memory used more or less O(L) instead of O(L^2).
    # It's equivalent to running a for loop over chunks of the dimension we're iterative over,
    # where the chunk_size is the size of the chunks, so 128 would mean to parse 128-length chunks.
    self.chunk_size = chunk_size

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding

Bases: EsmPreTrainedModel

EsmForProteinFolding is a class that represents a model for protein folding using the ESM (Evolutionary Scale Modeling) approach. It inherits from EsmPreTrainedModel and implements methods for protein structure prediction and inference.

The class includes methods for initializing the model, converting input sequences to protein structures, and generating Protein Data Bank (PDB) files from model outputs. It also provides functionality for language model representations, masking input sequences, and inferring protein structures from input sequences.

Example
>>> from transformers import AutoTokenizer, EsmForProteinFolding
...
>>> model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
>>> inputs = tokenizer(["MLKNVQVQLV"], return_tensors="ms", add_special_tokens=False)  # A tiny random peptide
>>> outputs = model(**inputs)
>>> folded_positions = outputs.positions
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
class EsmForProteinFolding(EsmPreTrainedModel):

    """
    EsmForProteinFolding is a class that represents a model for protein folding using the ESM
    (Evolutionary Scale Modeling) approach.
    It inherits from EsmPreTrainedModel and implements methods for protein structure prediction and inference.

    The class includes methods for initializing the model, converting input sequences to protein structures,
    and generating Protein Data Bank (PDB) files from model outputs. It also provides functionality for
    language model representations, masking input sequences, and inferring protein structures from input sequences.

    Example:
        ```python
        >>> from transformers import AutoTokenizer, EsmForProteinFolding
        ...
        >>> model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
        >>> inputs = tokenizer(["MLKNVQVQLV"], return_tensors="ms", add_special_tokens=False)  # A tiny random peptide
        >>> outputs = model(**inputs)
        >>> folded_positions = outputs.positions
        ```
    """
    _no_split_modules = ["EsmFoldStructureModule", "EsmFoldTriangularSelfAttentionBlock"]

    def __init__(self, config):
        """Initializes an instance of the EsmForProteinFolding class.

        Args:
            self: The instance of the class.
            config: An object containing configuration settings for the model.

        Returns:
            None

        Raises:
            None
        """
        super().__init__(config)

        self.config = config

        self.distogram_bins = 64

        self.esm = EsmModel(config, add_pooling_layer=False)

        if self.config.esmfold_config.fp16_esm:
            self.esm.half()

        self.esm_feats = self.config.hidden_size
        self.esm_attns = self.config.num_hidden_layers * self.config.num_attention_heads
        self.esm_layers = self.config.num_hidden_layers
        self.af2_to_esm = self._af2_to_esm_from_vocab_list(config.vocab_list)
        self.esm_s_combine = Parameter(ops.zeros((self.esm_layers + 1,)))

        trunk_config = self.config.esmfold_config.trunk
        c_s = trunk_config.sequence_state_dim
        c_z = trunk_config.pairwise_state_dim
        self.esm_s_mlp = nn.Sequential(
            nn.LayerNorm(self.esm_feats),
            nn.Linear(self.esm_feats, c_s),
            nn.ReLU(),
            nn.Linear(c_s, c_s),
        )

        # 0 is padding, N is unknown residues, N + 1 is mask.
        self.n_tokens_embed = residue_constants.restype_num + 3
        self.pad_idx = 0
        self.unk_idx = self.n_tokens_embed - 2
        self.mask_idx = self.n_tokens_embed - 1
        self.esm_dict_cls_idx = self.config.vocab_list.index("<cls>")
        self.esm_dict_mask_idx = self.config.vocab_list.index("<mask>")
        self.esm_dict_eos_idx = self.config.vocab_list.index("<eos>")
        self.esm_dict_padding_idx = self.config.vocab_list.index("<pad>")
        if self.config.esmfold_config.embed_aa:
            self.embedding = nn.Embedding(self.n_tokens_embed, c_s, padding_idx=0)

        self.trunk = EsmFoldingTrunk(trunk_config)

        self.distogram_head = nn.Linear(c_z, self.distogram_bins)
        self.ptm_head = nn.Linear(c_z, self.distogram_bins)
        self.lm_head = nn.Linear(c_s, self.n_tokens_embed)
        self.lddt_bins = 50
        structure_module_config = trunk_config.structure_module
        self.lddt_head = nn.Sequential(
            nn.LayerNorm(structure_module_config.sequence_dim),
            nn.Linear(structure_module_config.sequence_dim, self.config.esmfold_config.lddt_head_hid_dim),
            nn.Linear(self.config.esmfold_config.lddt_head_hid_dim, self.config.esmfold_config.lddt_head_hid_dim),
            nn.Linear(self.config.esmfold_config.lddt_head_hid_dim, 37 * self.lddt_bins),
        )

    @staticmethod
    def _af2_to_esm_from_vocab_list(vocab_list: List[str]) -> mindspore.Tensor:
        """
        Converts a vocabulary list to a mindspore Tensor, specifically for the ESM (Evolutionary Scale Modeling)
        implementation, in the context of protein folding.

        Args:
            vocab_list (List[str]): A list of strings representing the vocabulary.
                Each string corresponds to a specific residue or token.

        Returns:
            mindspore.Tensor: The resulting Tensor representing the reordered vocabulary list.
                The Tensor contains the indices of the vocabulary list elements, with the first element being the index
                of '<pad>' and the following elements being the indices of the residues from the 'restypes_with_x' list.

        Raises:
            None.

        Note:
            - The '<pad>' element is a special token used for padding sequences.
            - 'residue_constants.restypes_with_x' is a predefined list of residue types with an additional 'x' type.

        Example:
            ```python
            >>> vocab_list = ['<pad>', 'A', 'C', 'D', 'E', 'F', 'G']
            >>> EsmForProteinFolding._af2_to_esm_from_vocab_list(vocab_list)
            Tensor(shape=[8], dtype=Int32, value=
            [0, 1, 2, 3, 4, 5, 6])
            ```
        """
        # Remember that t is shifted from residue_constants by 1 (0 is padding).
        esm_reorder = [vocab_list.index("<pad>")] + [vocab_list.index(v) for v in residue_constants.restypes_with_x]
        return mindspore.tensor(esm_reorder)

    def forward(
        self,
        input_ids: mindspore.Tensor,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        masking_pattern: Optional[mindspore.Tensor] = None,
        num_recycles: Optional[int] = None,
    ) -> EsmForProteinFoldingOutput:
        r"""
        Returns:
            EsmForProteinFoldingOutput

        Example:
            ```python
            >>> from transformers import AutoTokenizer, EsmForProteinFolding
            ...
            >>> model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1")
            >>> tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
            >>> inputs = tokenizer(["MLKNVQVQLV"], return_tensors="ms", add_special_tokens=False)  # A tiny random peptide
            >>> outputs = model(**inputs)
            >>> folded_positions = outputs.positions
            ```

        """
        cfg = self.config.esmfold_config

        aa = input_ids  # B x L
        B = aa.shape[0]
        L = aa.shape[1]
        if attention_mask is None:
            attention_mask = ops.ones_like(aa)
        if position_ids is None:
            position_ids = ops.arange(L).expand_as(input_ids)

        # === ESM ===
        esmaa = self.af2_idx_to_esm_idx(aa, attention_mask)

        if masking_pattern is not None:
            masked_aa, esmaa, mlm_targets = self.bert_mask(aa, esmaa, attention_mask, masking_pattern)
        else:
            masked_aa = aa
            mlm_targets = None

        # We get sequence and pair representations from whatever version of ESM /
        # configuration we are using. The sequence representation esm_s is always
        # present. The pair embedding esm_z may be present depending on the
        # configuration of the model. If esm_z is not used by the model then it
        # is returned as None here.
        esm_s = self.compute_language_model_representations(esmaa)

        # Convert esm_s and esm_z, if present, to the precision used by the trunk and
        # the structure module. These tensors may be a lower precision if, for example,
        # we're running the language model in fp16 precision.
        esm_s = esm_s.to(self.esm_s_combine.dtype)

        if cfg.esm_ablate_sequence:
            esm_s = esm_s * 0

        # === preprocessing ===
        esm_s = (ops.softmax((self.esm_s_combine + 1e-8), 0).unsqueeze(0) @ esm_s).squeeze(2)
        s_s_0 = self.esm_s_mlp(esm_s)

        s_z_0 = s_s_0.new_zeros((B, L, L, cfg.trunk.pairwise_state_dim))

        if self.config.esmfold_config.embed_aa:
            s_s_0 += self.embedding(masked_aa)

        structure: dict = self.trunk(s_s_0, s_z_0, aa, position_ids, attention_mask, no_recycles=num_recycles)
        # Documenting what we expect:
        structure = {
            k: v
            for k, v in structure.items()
            if k
            in [
                "s_z",
                "s_s",
                "frames",
                "sidechain_frames",
                "unnormalized_angles",
                "angles",
                "positions",
                "states",
            ]
        }

        # Add BERT mask for the loss to use, if available.
        if mlm_targets:
            structure["mlm_targets"] = mlm_targets

        disto_logits = self.distogram_head(structure["s_z"])
        disto_logits = (disto_logits + disto_logits.swapaxes(1, 2)) / 2
        structure["distogram_logits"] = disto_logits

        lm_logits = self.lm_head(structure["s_s"])
        structure["lm_logits"] = lm_logits

        structure["aatype"] = aa
        make_atom14_masks(structure)
        # Of course, this doesn't respect the true mask because it doesn't know about it...
        # We're not going to properly mask change of index tensors:
        #    "residx_atom14_to_atom37",
        #    "residx_atom37_to_atom14",
        for k in [
            "atom14_atom_exists",
            "atom37_atom_exists",
        ]:
            structure[k] *= attention_mask.unsqueeze(-1)
        structure["residue_index"] = position_ids

        lddt_head = self.lddt_head(structure["states"]).reshape(structure["states"].shape[0], B, L, -1, self.lddt_bins)
        structure["lddt_head"] = lddt_head
        plddt = categorical_lddt(lddt_head[-1], bins=self.lddt_bins)
        structure["plddt"] = plddt

        ptm_logits = self.ptm_head(structure["s_z"])
        structure["ptm_logits"] = ptm_logits
        structure["ptm"] = compute_tm(ptm_logits, max_bin=31, no_bins=self.distogram_bins)
        structure.update(compute_predicted_aligned_error(ptm_logits, max_bin=31, no_bins=self.distogram_bins))

        return EsmForProteinFoldingOutput(**structure)

    def af2_idx_to_esm_idx(self, aa, mask):
        """
        This method 'af2_idx_to_esm_idx' is defined in the class 'EsmForProteinFolding' and is used to convert the
        input indices from one representation to another.

        Args:
            self: The instance of the class. It is automatically passed as the first argument. Used to access the
                attributes and methods of the class.
            aa:
                A tensor representing the input indices.

                - Type: torch.Tensor.
                - Purpose: It is used to calculate the converted indices. Restrictions: Should be a tensor of indices.
            mask:
                A tensor representing the mask.

                - Type: torch.Tensor.
                - Purpose: It is used to mask the input indices. Restrictions: Should be a tensor of masks.

        Returns:
            None: This method does not return any value.
                The converted indices are updated in the instance attribute 'af2_to_esm'.

        Raises:
            None.
        """
        aa = (aa + 1).masked_fill(mask != 1, 0)
        return self.af2_to_esm[aa]

    def compute_language_model_representations(self, esmaa: mindspore.Tensor) -> mindspore.Tensor:
        ''' 
        The method 'compute_language_model_representations' in the class 'EsmForProteinFolding' computes the
        representations of the language model.

        Args:
            self: The instance of the class.
            esmaa (mindspore.Tensor): A tensor representing the input data with shape (B, L), where B is the batch size
                and L is the sequence length.

        Returns:
            mindspore.Tensor: A tensor representing the language model representations.

        Raises:
            None.
        '''
        B, L = esmaa.shape  # B = batch size, L = sequence length.

        if self.config.esmfold_config.bypass_lm:
            esm_s = ops.zeros(B, L, self.esm_s_combine.size[0], -1, self.esm_feats)
            return esm_s

        bosi, eosi = self.esm_dict_cls_idx, self.esm_dict_eos_idx
        bos = ops.ones((B, 1), dtype=esmaa.dtype) * bosi
        eos = ops.ones((B, 1), dtype=esmaa.dtype) * self.esm_dict_padding_idx
        esmaa = ops.cat([bos, esmaa, eos], dim=1)
        # Use the first padding index as eos during inference.
        esmaa[ops.arange(B), (esmaa != 1).sum(1)] = eosi

        # _, esm_z, esm_s = self.esm(esmaa, return_pairs=self.config.esmfold_config.use_esm_attn_map)
        # Because we do not support use_esm_attn_map in the HF port as it is not used in any public models,
        # esm_z is always None
        esm_hidden_states = self.esm(esmaa, attention_mask=esmaa != 1, output_hidden_states=True)["hidden_states"]
        esm_s = ops.stack(esm_hidden_states, dim=2)

        esm_s = esm_s[:, 1:-1]  # B, L, nLayers, C

        return esm_s

    def bert_mask(self, aa, esmaa, mask, pattern):
        """
        This method 'bert_mask' in the class 'EsmForProteinFolding' masks specific elements in the input arrays based on
        the provided pattern.

        Args:
            self: The instance of the class.
            aa (numpy array): The input array of amino acids.
            esmaa (numpy array): The input array of ESMs for amino acids.
            mask (int): The mask index to be applied to 'aa' where pattern equals 1.
            pattern (numpy array): The pattern array used to determine which elements to mask.

        Returns:
            None: This method does not return any explicit value but modifies the input arrays in-place. It returns None.

        Raises:
            None.
        """
        new_aa = aa.copy()
        target = aa.copy()
        new_esmaa = esmaa.copy()
        new_aa[pattern == 1] = self.mask_idx
        target[pattern != 1] = 0
        new_esmaa[pattern == 1] = self.esm_dict_mask_idx
        return new_aa, new_esmaa, target

    def infer(
        self,
        seqs: Union[str, List[str]],
        position_ids=None,
    ):
        """
        Performs inference on protein folding using the ESM model.

        Args:
            self (EsmForProteinFolding): An instance of the EsmForProteinFolding class.
            seqs (Union[str, List[str]]): The protein sequences to perform inference on.
                It can be a single sequence as a string or a list of multiple sequences.
                Each sequence should be a string.
            position_ids (Optional[Tensor]): The position IDs for the sequences.
                If None, default position IDs will be used. Default is None.

        Returns:
            None.

        Raises:
            None.
        """
        if isinstance(seqs, str):
            lst = [seqs]
        else:
            lst = seqs
        # Returns the raw outputs of the model given an input sequence.
        aatype = collate_dense_tensors(
            [
                mindspore.Tensor.from_numpy(
                    residue_constants.sequence_to_onehot(
                        sequence=seq,
                        mapping=residue_constants.restype_order_with_x,
                        map_unknown_to_x=True,
                    )
                )
                .argmax(axis=1)
                for seq in lst
            ]
        )  # B=1 x L
        mask = collate_dense_tensors([aatype.new_ones(len(seq)) for seq in lst])
        position_ids = (
            ops.arange(aatype.shape[1]).broadcast_to((len(lst), -1))
            if position_ids is None
            else position_ids
        )
        if position_ids.ndim == 1:
            position_ids = position_ids.unsqueeze(0)
        return self.forward(
            aatype,
            mask,
            position_ids=position_ids,
        )

    @staticmethod
    def output_to_pdb(output: Dict) -> List[str]:
        """Returns the pbd (file) string from the model given the model output."""
        output = {k: v.asnumpy() for k, v in output.items()}
        pdbs = []
        final_atom_positions = atom14_to_atom37(output["positions"][-1], output)
        final_atom_mask = output["atom37_atom_exists"]
        for i in range(output["aatype"].shape[0]):
            aa = output["aatype"][i]
            pred_pos = final_atom_positions[i]
            mask = final_atom_mask[i]
            resid = output["residue_index"][i] + 1
            pred = OFProtein(
                aatype=aa,
                atom_positions=pred_pos,
                atom_mask=mask,
                residue_index=resid,
                b_factors=output["plddt"][i],
            )
            pdbs.append(to_pdb(pred))
        return pdbs

    def infer_pdb(self, seqs, *args, **kwargs) -> str:
        """Returns the pdb (file) string from the model given an input sequence."""
        assert isinstance(seqs, str)
        output = self.infer(seqs, *args, **kwargs)
        return self.output_to_pdb(output)[0]

    def infer_pdbs(self, seqs: List[str], *args, **kwargs) -> List[str]:
        """Returns the pdb (file) string from the model given an input sequence."""
        output = self.infer(seqs, *args, **kwargs)
        return self.output_to_pdb(output)

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.__init__(config)

Initializes an instance of the EsmForProteinFolding class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing configuration settings for the model.

RETURNS DESCRIPTION

None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
def __init__(self, config):
    """Initializes an instance of the EsmForProteinFolding class.

    Args:
        self: The instance of the class.
        config: An object containing configuration settings for the model.

    Returns:
        None

    Raises:
        None
    """
    super().__init__(config)

    self.config = config

    self.distogram_bins = 64

    self.esm = EsmModel(config, add_pooling_layer=False)

    if self.config.esmfold_config.fp16_esm:
        self.esm.half()

    self.esm_feats = self.config.hidden_size
    self.esm_attns = self.config.num_hidden_layers * self.config.num_attention_heads
    self.esm_layers = self.config.num_hidden_layers
    self.af2_to_esm = self._af2_to_esm_from_vocab_list(config.vocab_list)
    self.esm_s_combine = Parameter(ops.zeros((self.esm_layers + 1,)))

    trunk_config = self.config.esmfold_config.trunk
    c_s = trunk_config.sequence_state_dim
    c_z = trunk_config.pairwise_state_dim
    self.esm_s_mlp = nn.Sequential(
        nn.LayerNorm(self.esm_feats),
        nn.Linear(self.esm_feats, c_s),
        nn.ReLU(),
        nn.Linear(c_s, c_s),
    )

    # 0 is padding, N is unknown residues, N + 1 is mask.
    self.n_tokens_embed = residue_constants.restype_num + 3
    self.pad_idx = 0
    self.unk_idx = self.n_tokens_embed - 2
    self.mask_idx = self.n_tokens_embed - 1
    self.esm_dict_cls_idx = self.config.vocab_list.index("<cls>")
    self.esm_dict_mask_idx = self.config.vocab_list.index("<mask>")
    self.esm_dict_eos_idx = self.config.vocab_list.index("<eos>")
    self.esm_dict_padding_idx = self.config.vocab_list.index("<pad>")
    if self.config.esmfold_config.embed_aa:
        self.embedding = nn.Embedding(self.n_tokens_embed, c_s, padding_idx=0)

    self.trunk = EsmFoldingTrunk(trunk_config)

    self.distogram_head = nn.Linear(c_z, self.distogram_bins)
    self.ptm_head = nn.Linear(c_z, self.distogram_bins)
    self.lm_head = nn.Linear(c_s, self.n_tokens_embed)
    self.lddt_bins = 50
    structure_module_config = trunk_config.structure_module
    self.lddt_head = nn.Sequential(
        nn.LayerNorm(structure_module_config.sequence_dim),
        nn.Linear(structure_module_config.sequence_dim, self.config.esmfold_config.lddt_head_hid_dim),
        nn.Linear(self.config.esmfold_config.lddt_head_hid_dim, self.config.esmfold_config.lddt_head_hid_dim),
        nn.Linear(self.config.esmfold_config.lddt_head_hid_dim, 37 * self.lddt_bins),
    )

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.af2_idx_to_esm_idx(aa, mask)

This method 'af2_idx_to_esm_idx' is defined in the class 'EsmForProteinFolding' and is used to convert the input indices from one representation to another.

PARAMETER DESCRIPTION
self

The instance of the class. It is automatically passed as the first argument. Used to access the attributes and methods of the class.

aa

A tensor representing the input indices.

  • Type: torch.Tensor.
  • Purpose: It is used to calculate the converted indices. Restrictions: Should be a tensor of indices.

mask

A tensor representing the mask.

  • Type: torch.Tensor.
  • Purpose: It is used to mask the input indices. Restrictions: Should be a tensor of masks.

RETURNS DESCRIPTION
None

This method does not return any value. The converted indices are updated in the instance attribute 'af2_to_esm'.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
def af2_idx_to_esm_idx(self, aa, mask):
    """
    This method 'af2_idx_to_esm_idx' is defined in the class 'EsmForProteinFolding' and is used to convert the
    input indices from one representation to another.

    Args:
        self: The instance of the class. It is automatically passed as the first argument. Used to access the
            attributes and methods of the class.
        aa:
            A tensor representing the input indices.

            - Type: torch.Tensor.
            - Purpose: It is used to calculate the converted indices. Restrictions: Should be a tensor of indices.
        mask:
            A tensor representing the mask.

            - Type: torch.Tensor.
            - Purpose: It is used to mask the input indices. Restrictions: Should be a tensor of masks.

    Returns:
        None: This method does not return any value.
            The converted indices are updated in the instance attribute 'af2_to_esm'.

    Raises:
        None.
    """
    aa = (aa + 1).masked_fill(mask != 1, 0)
    return self.af2_to_esm[aa]

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.bert_mask(aa, esmaa, mask, pattern)

This method 'bert_mask' in the class 'EsmForProteinFolding' masks specific elements in the input arrays based on the provided pattern.

PARAMETER DESCRIPTION
self

The instance of the class.

aa

The input array of amino acids.

TYPE: numpy array

esmaa

The input array of ESMs for amino acids.

TYPE: numpy array

mask

The mask index to be applied to 'aa' where pattern equals 1.

TYPE: int

pattern

The pattern array used to determine which elements to mask.

TYPE: numpy array

RETURNS DESCRIPTION
None

This method does not return any explicit value but modifies the input arrays in-place. It returns None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
def bert_mask(self, aa, esmaa, mask, pattern):
    """
    This method 'bert_mask' in the class 'EsmForProteinFolding' masks specific elements in the input arrays based on
    the provided pattern.

    Args:
        self: The instance of the class.
        aa (numpy array): The input array of amino acids.
        esmaa (numpy array): The input array of ESMs for amino acids.
        mask (int): The mask index to be applied to 'aa' where pattern equals 1.
        pattern (numpy array): The pattern array used to determine which elements to mask.

    Returns:
        None: This method does not return any explicit value but modifies the input arrays in-place. It returns None.

    Raises:
        None.
    """
    new_aa = aa.copy()
    target = aa.copy()
    new_esmaa = esmaa.copy()
    new_aa[pattern == 1] = self.mask_idx
    target[pattern != 1] = 0
    new_esmaa[pattern == 1] = self.esm_dict_mask_idx
    return new_aa, new_esmaa, target

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.compute_language_model_representations(esmaa)

The method 'compute_language_model_representations' in the class 'EsmForProteinFolding' computes the representations of the language model.

PARAMETER DESCRIPTION
self

The instance of the class.

esmaa

A tensor representing the input data with shape (B, L), where B is the batch size and L is the sequence length.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: A tensor representing the language model representations.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
def compute_language_model_representations(self, esmaa: mindspore.Tensor) -> mindspore.Tensor:
    ''' 
    The method 'compute_language_model_representations' in the class 'EsmForProteinFolding' computes the
    representations of the language model.

    Args:
        self: The instance of the class.
        esmaa (mindspore.Tensor): A tensor representing the input data with shape (B, L), where B is the batch size
            and L is the sequence length.

    Returns:
        mindspore.Tensor: A tensor representing the language model representations.

    Raises:
        None.
    '''
    B, L = esmaa.shape  # B = batch size, L = sequence length.

    if self.config.esmfold_config.bypass_lm:
        esm_s = ops.zeros(B, L, self.esm_s_combine.size[0], -1, self.esm_feats)
        return esm_s

    bosi, eosi = self.esm_dict_cls_idx, self.esm_dict_eos_idx
    bos = ops.ones((B, 1), dtype=esmaa.dtype) * bosi
    eos = ops.ones((B, 1), dtype=esmaa.dtype) * self.esm_dict_padding_idx
    esmaa = ops.cat([bos, esmaa, eos], dim=1)
    # Use the first padding index as eos during inference.
    esmaa[ops.arange(B), (esmaa != 1).sum(1)] = eosi

    # _, esm_z, esm_s = self.esm(esmaa, return_pairs=self.config.esmfold_config.use_esm_attn_map)
    # Because we do not support use_esm_attn_map in the HF port as it is not used in any public models,
    # esm_z is always None
    esm_hidden_states = self.esm(esmaa, attention_mask=esmaa != 1, output_hidden_states=True)["hidden_states"]
    esm_s = ops.stack(esm_hidden_states, dim=2)

    esm_s = esm_s[:, 1:-1]  # B, L, nLayers, C

    return esm_s

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.forward(input_ids, attention_mask=None, position_ids=None, masking_pattern=None, num_recycles=None)

RETURNS DESCRIPTION
EsmForProteinFoldingOutput

EsmForProteinFoldingOutput

Example
>>> from transformers import AutoTokenizer, EsmForProteinFolding
...
>>> model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
>>> inputs = tokenizer(["MLKNVQVQLV"], return_tensors="ms", add_special_tokens=False)  # A tiny random peptide
>>> outputs = model(**inputs)
>>> folded_positions = outputs.positions
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
def forward(
    self,
    input_ids: mindspore.Tensor,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    masking_pattern: Optional[mindspore.Tensor] = None,
    num_recycles: Optional[int] = None,
) -> EsmForProteinFoldingOutput:
    r"""
    Returns:
        EsmForProteinFoldingOutput

    Example:
        ```python
        >>> from transformers import AutoTokenizer, EsmForProteinFolding
        ...
        >>> model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/esmfold_v1")
        >>> inputs = tokenizer(["MLKNVQVQLV"], return_tensors="ms", add_special_tokens=False)  # A tiny random peptide
        >>> outputs = model(**inputs)
        >>> folded_positions = outputs.positions
        ```

    """
    cfg = self.config.esmfold_config

    aa = input_ids  # B x L
    B = aa.shape[0]
    L = aa.shape[1]
    if attention_mask is None:
        attention_mask = ops.ones_like(aa)
    if position_ids is None:
        position_ids = ops.arange(L).expand_as(input_ids)

    # === ESM ===
    esmaa = self.af2_idx_to_esm_idx(aa, attention_mask)

    if masking_pattern is not None:
        masked_aa, esmaa, mlm_targets = self.bert_mask(aa, esmaa, attention_mask, masking_pattern)
    else:
        masked_aa = aa
        mlm_targets = None

    # We get sequence and pair representations from whatever version of ESM /
    # configuration we are using. The sequence representation esm_s is always
    # present. The pair embedding esm_z may be present depending on the
    # configuration of the model. If esm_z is not used by the model then it
    # is returned as None here.
    esm_s = self.compute_language_model_representations(esmaa)

    # Convert esm_s and esm_z, if present, to the precision used by the trunk and
    # the structure module. These tensors may be a lower precision if, for example,
    # we're running the language model in fp16 precision.
    esm_s = esm_s.to(self.esm_s_combine.dtype)

    if cfg.esm_ablate_sequence:
        esm_s = esm_s * 0

    # === preprocessing ===
    esm_s = (ops.softmax((self.esm_s_combine + 1e-8), 0).unsqueeze(0) @ esm_s).squeeze(2)
    s_s_0 = self.esm_s_mlp(esm_s)

    s_z_0 = s_s_0.new_zeros((B, L, L, cfg.trunk.pairwise_state_dim))

    if self.config.esmfold_config.embed_aa:
        s_s_0 += self.embedding(masked_aa)

    structure: dict = self.trunk(s_s_0, s_z_0, aa, position_ids, attention_mask, no_recycles=num_recycles)
    # Documenting what we expect:
    structure = {
        k: v
        for k, v in structure.items()
        if k
        in [
            "s_z",
            "s_s",
            "frames",
            "sidechain_frames",
            "unnormalized_angles",
            "angles",
            "positions",
            "states",
        ]
    }

    # Add BERT mask for the loss to use, if available.
    if mlm_targets:
        structure["mlm_targets"] = mlm_targets

    disto_logits = self.distogram_head(structure["s_z"])
    disto_logits = (disto_logits + disto_logits.swapaxes(1, 2)) / 2
    structure["distogram_logits"] = disto_logits

    lm_logits = self.lm_head(structure["s_s"])
    structure["lm_logits"] = lm_logits

    structure["aatype"] = aa
    make_atom14_masks(structure)
    # Of course, this doesn't respect the true mask because it doesn't know about it...
    # We're not going to properly mask change of index tensors:
    #    "residx_atom14_to_atom37",
    #    "residx_atom37_to_atom14",
    for k in [
        "atom14_atom_exists",
        "atom37_atom_exists",
    ]:
        structure[k] *= attention_mask.unsqueeze(-1)
    structure["residue_index"] = position_ids

    lddt_head = self.lddt_head(structure["states"]).reshape(structure["states"].shape[0], B, L, -1, self.lddt_bins)
    structure["lddt_head"] = lddt_head
    plddt = categorical_lddt(lddt_head[-1], bins=self.lddt_bins)
    structure["plddt"] = plddt

    ptm_logits = self.ptm_head(structure["s_z"])
    structure["ptm_logits"] = ptm_logits
    structure["ptm"] = compute_tm(ptm_logits, max_bin=31, no_bins=self.distogram_bins)
    structure.update(compute_predicted_aligned_error(ptm_logits, max_bin=31, no_bins=self.distogram_bins))

    return EsmForProteinFoldingOutput(**structure)

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.infer(seqs, position_ids=None)

Performs inference on protein folding using the ESM model.

PARAMETER DESCRIPTION
self

An instance of the EsmForProteinFolding class.

TYPE: EsmForProteinFolding

seqs

The protein sequences to perform inference on. It can be a single sequence as a string or a list of multiple sequences. Each sequence should be a string.

TYPE: Union[str, List[str]]

position_ids

The position IDs for the sequences. If None, default position IDs will be used. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
def infer(
    self,
    seqs: Union[str, List[str]],
    position_ids=None,
):
    """
    Performs inference on protein folding using the ESM model.

    Args:
        self (EsmForProteinFolding): An instance of the EsmForProteinFolding class.
        seqs (Union[str, List[str]]): The protein sequences to perform inference on.
            It can be a single sequence as a string or a list of multiple sequences.
            Each sequence should be a string.
        position_ids (Optional[Tensor]): The position IDs for the sequences.
            If None, default position IDs will be used. Default is None.

    Returns:
        None.

    Raises:
        None.
    """
    if isinstance(seqs, str):
        lst = [seqs]
    else:
        lst = seqs
    # Returns the raw outputs of the model given an input sequence.
    aatype = collate_dense_tensors(
        [
            mindspore.Tensor.from_numpy(
                residue_constants.sequence_to_onehot(
                    sequence=seq,
                    mapping=residue_constants.restype_order_with_x,
                    map_unknown_to_x=True,
                )
            )
            .argmax(axis=1)
            for seq in lst
        ]
    )  # B=1 x L
    mask = collate_dense_tensors([aatype.new_ones(len(seq)) for seq in lst])
    position_ids = (
        ops.arange(aatype.shape[1]).broadcast_to((len(lst), -1))
        if position_ids is None
        else position_ids
    )
    if position_ids.ndim == 1:
        position_ids = position_ids.unsqueeze(0)
    return self.forward(
        aatype,
        mask,
        position_ids=position_ids,
    )

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.infer_pdb(seqs, *args, **kwargs)

Returns the pdb (file) string from the model given an input sequence.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3302
3303
3304
3305
3306
def infer_pdb(self, seqs, *args, **kwargs) -> str:
    """Returns the pdb (file) string from the model given an input sequence."""
    assert isinstance(seqs, str)
    output = self.infer(seqs, *args, **kwargs)
    return self.output_to_pdb(output)[0]

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.infer_pdbs(seqs, *args, **kwargs)

Returns the pdb (file) string from the model given an input sequence.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3308
3309
3310
3311
def infer_pdbs(self, seqs: List[str], *args, **kwargs) -> List[str]:
    """Returns the pdb (file) string from the model given an input sequence."""
    output = self.infer(seqs, *args, **kwargs)
    return self.output_to_pdb(output)

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFolding.output_to_pdb(output) staticmethod

Returns the pbd (file) string from the model given the model output.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
@staticmethod
def output_to_pdb(output: Dict) -> List[str]:
    """Returns the pbd (file) string from the model given the model output."""
    output = {k: v.asnumpy() for k, v in output.items()}
    pdbs = []
    final_atom_positions = atom14_to_atom37(output["positions"][-1], output)
    final_atom_mask = output["atom37_atom_exists"]
    for i in range(output["aatype"].shape[0]):
        aa = output["aatype"][i]
        pred_pos = final_atom_positions[i]
        mask = final_atom_mask[i]
        resid = output["residue_index"][i] + 1
        pred = OFProtein(
            aatype=aa,
            atom_positions=pred_pos,
            atom_mask=mask,
            residue_index=resid,
            b_factors=output["plddt"][i],
        )
        pdbs.append(to_pdb(pred))
    return pdbs

mindnlp.transformers.models.esm.modeling_esmfold.EsmForProteinFoldingOutput dataclass

Bases: ModelOutput

Output type of [EsmForProteinFoldingOutput].

PARAMETER DESCRIPTION
frames

Output frames.

TYPE: `mindspore.Tensor` DEFAULT: None

sidechain_frames

Output sidechain frames.

TYPE: `mindspore.Tensor` DEFAULT: None

unnormalized_angles

Predicted unnormalized backbone and side chain torsion angles.

TYPE: `mindspore.Tensor` DEFAULT: None

angles

Predicted backbone and side chain torsion angles.

TYPE: `mindspore.Tensor` DEFAULT: None

positions

Predicted positions of the backbone and side chain atoms.

TYPE: `mindspore.Tensor` DEFAULT: None

states

Hidden states from the protein folding trunk.

TYPE: `mindspore.Tensor` DEFAULT: None

s_s

Per-residue embeddings derived by concatenating the hidden states of each layer of the ESM-2 LM stem.

TYPE: `mindspore.Tensor` DEFAULT: None

s_z

Pairwise residue embeddings.

TYPE: `mindspore.Tensor` DEFAULT: None

distogram_logits

Input logits to the distogram used to compute residue distances.

TYPE: `mindspore.Tensor` DEFAULT: None

lm_logits

Logits output by the ESM-2 protein language model stem.

TYPE: `mindspore.Tensor` DEFAULT: None

aatype

Input amino acids (AlphaFold2 indices).

TYPE: `mindspore.Tensor` DEFAULT: None

atom14_atom_exists

Whether each atom exists in the atom14 representation.

TYPE: `mindspore.Tensor` DEFAULT: None

residx_atom14_to_atom37

Mapping between atoms in the atom14 and atom37 representations.

TYPE: `mindspore.Tensor` DEFAULT: None

residx_atom37_to_atom14

Mapping between atoms in the atom37 and atom14 representations.

TYPE: `mindspore.Tensor` DEFAULT: None

atom37_atom_exists

Whether each atom exists in the atom37 representation.

TYPE: `mindspore.Tensor` DEFAULT: None

residue_index

The index of each residue in the protein chain. Unless internal padding tokens are used, this will just be a sequence of integers from 0 to sequence_length.

TYPE: `mindspore.Tensor` DEFAULT: None

lddt_head

Raw outputs from the lddt head used to compute plddt.

TYPE: `mindspore.Tensor` DEFAULT: None

plddt

Per-residue confidence scores. Regions of low confidence may indicate areas where the model's prediction is uncertain, or where the protein structure is disordered.

TYPE: `mindspore.Tensor` DEFAULT: None

ptm_logits

Raw logits used for computing ptm.

TYPE: `mindspore.Tensor` DEFAULT: None

ptm

TM-score output representing the model's high-level confidence in the overall structure.

TYPE: `mindspore.Tensor` DEFAULT: None

aligned_confidence_probs

Per-residue confidence scores for the aligned structure.

TYPE: `mindspore.Tensor` DEFAULT: None

predicted_aligned_error

Predicted error between the model's prediction and the ground truth.

TYPE: `mindspore.Tensor` DEFAULT: None

max_predicted_aligned_error

Per-sample maximum predicted error.

TYPE: `mindspore.Tensor` DEFAULT: None

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
 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
@dataclass
class EsmForProteinFoldingOutput(ModelOutput):
    """
    Output type of [`EsmForProteinFoldingOutput`].

    Args:
        frames (`mindspore.Tensor`):
            Output frames.
        sidechain_frames (`mindspore.Tensor`):
            Output sidechain frames.
        unnormalized_angles (`mindspore.Tensor`):
            Predicted unnormalized backbone and side chain torsion angles.
        angles (`mindspore.Tensor`):
            Predicted backbone and side chain torsion angles.
        positions (`mindspore.Tensor`):
            Predicted positions of the backbone and side chain atoms.
        states (`mindspore.Tensor`):
            Hidden states from the protein folding trunk.
        s_s (`mindspore.Tensor`):
            Per-residue embeddings derived by concatenating the hidden states of each layer of the ESM-2 LM stem.
        s_z (`mindspore.Tensor`):
            Pairwise residue embeddings.
        distogram_logits (`mindspore.Tensor`):
            Input logits to the distogram used to compute residue distances.
        lm_logits (`mindspore.Tensor`):
            Logits output by the ESM-2 protein language model stem.
        aatype (`mindspore.Tensor`):
            Input amino acids (AlphaFold2 indices).
        atom14_atom_exists (`mindspore.Tensor`):
            Whether each atom exists in the atom14 representation.
        residx_atom14_to_atom37 (`mindspore.Tensor`):
            Mapping between atoms in the atom14 and atom37 representations.
        residx_atom37_to_atom14 (`mindspore.Tensor`):
            Mapping between atoms in the atom37 and atom14 representations.
        atom37_atom_exists (`mindspore.Tensor`):
            Whether each atom exists in the atom37 representation.
        residue_index (`mindspore.Tensor`):
            The index of each residue in the protein chain. Unless internal padding tokens are used, this will just be
            a sequence of integers from 0 to `sequence_length`.
        lddt_head (`mindspore.Tensor`):
            Raw outputs from the lddt head used to compute plddt.
        plddt (`mindspore.Tensor`):
            Per-residue confidence scores. Regions of low confidence may indicate areas where the model's prediction is
            uncertain, or where the protein structure is disordered.
        ptm_logits (`mindspore.Tensor`):
            Raw logits used for computing ptm.
        ptm (`mindspore.Tensor`):
            TM-score output representing the model's high-level confidence in the overall structure.
        aligned_confidence_probs (`mindspore.Tensor`):
            Per-residue confidence scores for the aligned structure.
        predicted_aligned_error (`mindspore.Tensor`):
            Predicted error between the model's prediction and the ground truth.
        max_predicted_aligned_error (`mindspore.Tensor`):
            Per-sample maximum predicted error.
    """
    frames: mindspore.Tensor = None
    sidechain_frames: mindspore.Tensor = None
    unnormalized_angles: mindspore.Tensor = None
    angles: mindspore.Tensor = None
    positions: mindspore.Tensor = None
    states: mindspore.Tensor = None
    s_s: mindspore.Tensor = None
    s_z: mindspore.Tensor = None
    distogram_logits: mindspore.Tensor = None
    lm_logits: mindspore.Tensor = None
    aatype: mindspore.Tensor = None
    atom14_atom_exists: mindspore.Tensor = None
    residx_atom14_to_atom37: mindspore.Tensor = None
    residx_atom37_to_atom14: mindspore.Tensor = None
    atom37_atom_exists: mindspore.Tensor = None
    residue_index: mindspore.Tensor = None
    lddt_head: mindspore.Tensor = None
    plddt: mindspore.Tensor = None
    ptm_logits: mindspore.Tensor = None
    ptm: mindspore.Tensor = None
    aligned_confidence_probs: mindspore.Tensor = None
    predicted_aligned_error: mindspore.Tensor = None
    max_predicted_aligned_error: mindspore.Tensor = None

mindnlp.transformers.models.esm.modeling_esmfold.categorical_lddt(logits, bins=50)

This function calculates the average log-likelihood of a categorical distribution.

PARAMETER DESCRIPTION
logits

The logits representing the categorical distribution. It should be a 2-dimensional array-like object with shape (n_samples, n_classes), where n_samples is the number of samples and n_classes is the number of classes.

TYPE: array - like

bins

The number of bins used for discretizing the logits. Defaults to 50.

TYPE: int DEFAULT: 50

RETURNS DESCRIPTION
float

The average log-likelihood of the categorical distribution.

RAISES DESCRIPTION
ValueError

If the logits parameter is not a 2-dimensional array-like object.

ValueError

If the bins parameter is not a positive integer.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
def categorical_lddt(logits, bins=50):
    """
    This function calculates the average log-likelihood of a categorical distribution.

    Args:
        logits (array-like): The logits representing the categorical distribution.
            It should be a 2-dimensional array-like object with shape (n_samples, n_classes),
            where n_samples is the number of samples and n_classes is the number of classes.
        bins (int, optional): The number of bins used for discretizing the logits. Defaults to 50.

    Returns:
        float: The average log-likelihood of the categorical distribution.

    Raises:
        ValueError: If the logits parameter is not a 2-dimensional array-like object.
        ValueError: If the bins parameter is not a positive integer.

    """
    # Logits are ..., 37, bins.
    return EsmCategoricalMixture(logits, bins=bins).mean()

mindnlp.transformers.models.esm.modeling_esmfold.collate_dense_tensors(samples, pad_v=0)

Takes a list of tensors with the following dimensions:

[(d_11, ..., d_1K), (d_21, ..., d_2K), ..., (d_N1, ..., d_NK)]

and stack + pads them into a single tensor of:

(N, max_i=1,N { d_i1 }, ..., max_i=1,N {diK})

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def collate_dense_tensors(samples: List[mindspore.Tensor], pad_v: float = 0) -> mindspore.Tensor:
    """
    Takes a list of tensors with the following dimensions:

    ```[(d_11, ..., d_1K),
     (d_21, ..., d_2K), ..., (d_N1, ..., d_NK)]```

    and stack + pads them into a single tensor of:

    ```(N, max_i=1,N { d_i1 }, ..., max_i=1,N {diK})```
    """
    if len(samples) == 0:
        return mindspore.Tensor()
    if len({x.dim() for x in samples}) != 1:
        raise RuntimeError(f"Samples has varying dimensions: {[x.dim() for x in samples]}")

    max_shape = [max(lst) for lst in zip(*[x.shape for x in samples])]
    result = ops.full((len(samples), *max_shape), pad_v, dtype=samples[0].dtype)
    for i, t in enumerate(samples):
        result_i = result[i]
        result_i[tuple(slice(0, k) for k in t.shape)] = t
    return result

mindnlp.transformers.models.esm.modeling_esmfold.dict_multimap(fn, dicts)

This function takes two parameters:

  • fn: A function that will be applied to the values of the dictionaries.
  • dicts: A list of dictionaries.

The function returns a new dictionary with the same keys as the first dictionary in the input list, where the values are the result of applying the given function to the corresponding values from all the input dictionaries.

RAISES DESCRIPTION
KeyError

If a key is not found in the dictionaries.

TypeError

If the values are not suitable for the given function.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
def dict_multimap(fn, dicts):
    """
    This function takes two parameters: 

    - fn: A function that will be applied to the values of the dictionaries.
    - dicts: A list of dictionaries.

    The function returns a new dictionary with the same keys as the first dictionary in the input list,
    where the values are the result of applying the given function to the corresponding values from all the
    input dictionaries.

    Raises:
        KeyError: If a key is not found in the dictionaries.
        TypeError: If the values are not suitable for the given function.
    """
    first = dicts[0]
    new_dict = {}
    for k, v in first.items():
        all_v = [d[k] for d in dicts]
        if isinstance(v, dict):
            new_dict[k] = dict_multimap(fn, all_v)
        else:
            new_dict[k] = fn(all_v)

    return new_dict

mindnlp.transformers.models.esm.modeling_esmfold.flatten_final_dims(t, no_dims)

Flatten the final dimensions of a tensor.

PARAMETER DESCRIPTION
t

The input tensor to be flattened.

TYPE: Tensor

no_dims

The number of dimensions to be flattened.

TYPE: int

RETURNS DESCRIPTION

mindspore.Tensor: A tensor with the specified number of final dimensions flattened.

RAISES DESCRIPTION
ValueError

If the input tensor does not have enough dimensions to flatten.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def flatten_final_dims(t: mindspore.Tensor, no_dims: int):
    """
    Flatten the final dimensions of a tensor.

    Args:
        t (mindspore.Tensor): The input tensor to be flattened.
        no_dims (int): The number of dimensions to be flattened.

    Returns:
        mindspore.Tensor: A tensor with the specified number of final dimensions flattened.

    Raises:
        ValueError: If the input tensor does not have enough dimensions to flatten.
    """
    return t.reshape(t.shape[:-no_dims] + (-1,))

mindnlp.transformers.models.esm.modeling_esmfold.get_axial_mask(mask)

Helper to convert B x L mask of valid positions to axial mask used in row column attentions.

Input
Output
Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
def get_axial_mask(mask):
    """
    Helper to convert B x L mask of valid positions to axial mask used in row column attentions.

    Input:
        mask: B x L tensor of booleans

    Output:
        mask: B x L x L tensor of booleans
    """
    if mask is None:
        return None

    if len(mask.shape) != 2:
        raise ValueError(f"`mask` should be a 2d-tensor, got {len(mask.shape)} dims.")
    batch_dim, seq_dim = mask.shape
    m = mask.unsqueeze(1).broadcast_to((batch_dim, seq_dim, seq_dim))
    m = m.reshape(batch_dim * seq_dim, seq_dim)
    return m

mindnlp.transformers.models.esm.modeling_esmfold.ipa_point_weights_init_(weights)

Initializes the IPA (International Phonetic Alphabet) point weights.

PARAMETER DESCRIPTION
weights

A list of weights to be initialized.

TYPE: list

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def ipa_point_weights_init_(weights):
    """
    Initializes the IPA (International Phonetic Alphabet) point weights.

    Args:
        weights (list): A list of weights to be initialized.

    Returns:
        None.

    Raises:
        None.
    """
    softplus_inverse_1 = 0.541324854612918
    weights[:] = softplus_inverse_1

mindnlp.transformers.models.esm.modeling_esmfold.permute_final_dims(tensor, inds)

This function permutes the final dimensions of the input tensor based on the provided indices.

PARAMETER DESCRIPTION
tensor

The input tensor to be permuted.

TYPE: Tensor

inds

A list of integers representing the indices of the dimensions to be permuted. The dimensions are 0-indexed.

TYPE: List[int]

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the indices provided in 'inds' are out of bounds or not in the correct format.

TypeError

If the input tensor is not of type mindspore.Tensor.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def permute_final_dims(tensor: mindspore.Tensor, inds: List[int]):
    """
    This function permutes the final dimensions of the input tensor based on the provided indices.

    Args:
        tensor (mindspore.Tensor): The input tensor to be permuted.
        inds (List[int]):
            A list of integers representing the indices of the dimensions to be permuted. The dimensions are 0-indexed.

    Returns:
        None.

    Raises:
        ValueError: If the indices provided in 'inds' are out of bounds or not in the correct format.
        TypeError: If the input tensor is not of type mindspore.Tensor.
    """
    zero_index = -1 * len(inds)
    first_inds = list(range(len(tensor.shape[:zero_index])))
    return tensor.permute(first_inds + [zero_index + i for i in inds])

mindnlp.transformers.models.esm.modeling_esmfold.softmax_no_cast(t, dim=-1)

Softmax, but without automatic casting to fp32 when the input is of type bfloat16

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
339
340
341
342
343
344
345
def softmax_no_cast(t: mindspore.Tensor, dim: int = -1) -> mindspore.Tensor:
    """
    Softmax, but without automatic casting to fp32 when the input is of type bfloat16
    """
    s = ops.softmax(t, dim=dim)

    return s

mindnlp.transformers.models.esm.modeling_esmfold.trunc_normal_init_(weights, scale=1.0, fan='fan_in')

This function initializes weights with a truncated normal distribution.

PARAMETER DESCRIPTION
weights

The weights to be initialized.

TYPE: Tensor

scale

The scale factor for the standard deviation. Defaults to 1.0.

TYPE: float DEFAULT: 1.0

fan

Specifies the mode for computing the fan. Defaults to 'fan_in'.

TYPE: str DEFAULT: 'fan_in'

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the shape of the weights is not valid.

ImportError

If scipy is not available and it is required for the initialization.

Source code in mindnlp\transformers\models\esm\modeling_esmfold.py
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
def trunc_normal_init_(weights, scale=1.0, fan="fan_in"):
    """
    This function initializes weights with a truncated normal distribution.

    Args:
        weights (Tensor): The weights to be initialized.
        scale (float, optional): The scale factor for the standard deviation. Defaults to 1.0.
        fan (str, optional): Specifies the mode for computing the fan. Defaults to 'fan_in'.

    Returns:
        None.

    Raises:
        ValueError: If the shape of the weights is not valid.
        ImportError: If scipy is not available and it is required for the initialization.
    """
    shape = weights.shape
    scale = scale / max(1, shape[1])

    if not is_scipy_available():
        logger.warning(
            "This init requires scipy, but scipy was not found, default to an approximation that might not be"
            " equivalent."
        )
        std = math.sqrt(scale)
        weights.set_data(initializer(Normal(std), weights.shape, weights.dtype).clamp(min=0.0, max=2.0 * std))

    else:
        from scipy.stats import truncnorm

        std = math.sqrt(scale) / truncnorm.std(a=-2, b=2, loc=0, scale=1)
        samples = truncnorm.rvs(a=-2, b=2, loc=0, scale=std, size=weights.numel())
        samples = np.reshape(samples, shape)
        weights.set_data(mindspore.tensor(samples))

mindnlp.transformers.models.esm.tokenization_esm

Tokenization classes for ESM.

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer

Bases: PreTrainedTokenizer

Constructs an ESM tokenizer.

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
 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
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
261
262
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
327
328
329
330
class EsmTokenizer(PreTrainedTokenizer):
    """
    Constructs an ESM tokenizer.
    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        unk_token="<unk>",
        cls_token="<cls>",
        pad_token="<pad>",
        mask_token="<mask>",
        eos_token="<eos>",
        **kwargs,
    ):
        """
        Initializes an instance of the EsmTokenizer class.

        Args:
            self: The instance of the class itself.
            vocab_file (str): The path to the vocabulary file.
            unk_token (str, optional): The token to represent unknown words. Defaults to '<unk>'.
            cls_token (str, optional): The token to represent the start of a sequence. Defaults to '<cls>'.
            pad_token (str, optional): The token to represent padding. Defaults to '<pad>'.
            mask_token (str, optional): The token to represent masked values. Defaults to '<mask>'.
            eos_token (str, optional): The token to represent the end of a sequence. Defaults to '<eos>'.

        Returns:
            None.

        Raises:
            None.
        """
        self.all_tokens = load_vocab_file(vocab_file)
        self._id_to_token = dict(enumerate(self.all_tokens))
        self._token_to_id = {tok: ind for ind, tok in enumerate(self.all_tokens)}
        super().__init__(
            unk_token=unk_token,
            cls_token=cls_token,
            pad_token=pad_token,
            mask_token=mask_token,
            eos_token=eos_token,
            **kwargs,
        )

        # TODO, all the tokens are added? But they are also part of the vocab... bit strange.
        # none of them are special, but they all need special splitting.

        self.unique_no_split_tokens = self.all_tokens
        self._update_trie(self.unique_no_split_tokens)

    def _convert_id_to_token(self, index: int) -> str:
        """
        Converts an index to a token using the mapping stored in the EsmTokenizer instance.

        Args:
            self (EsmTokenizer): The instance of the EsmTokenizer class.
                This parameter is used to access the mapping between indices and tokens.
            index (int): The index of the token to be converted.
                This parameter specifies the index of the token for which the conversion is needed.
                It must be an integer representing the position of the token in the mapping.

        Returns:
            str: The token corresponding to the provided index.
                Returns the token associated with the provided index in the mapping.
                If the index is not found in the mapping, the method returns the unknown token (unk_token).

        Raises:
            None
        """
        return self._id_to_token.get(index, self.unk_token)

    def _convert_token_to_id(self, token: str) -> int:
        """
        Converts a token to its corresponding ID using the provided token string.

        Args:
            self (EsmTokenizer): An instance of the EsmTokenizer class.
            token (str): The token to be converted to its corresponding ID.

        Returns:
            int: The ID corresponding to the input token. If the token is not found in the token-to-ID mapping, 
                 the ID corresponding to the unknown token (unk_token) is returned as a fallback.

        Raises:
            None
        """
        return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))

    def _tokenize(self, text, **kwargs):
        """
        Method _tokenize in the EsmTokenizer class tokenizes the input text.

        Args:
            self (EsmTokenizer): An instance of the EsmTokenizer class.
            text (str): The input text to be tokenized.

        Returns:
            None.

        Raises:
            None.
        """
        return text.split()

    def get_vocab(self):
        """
        Method to retrieve the vocabulary from the EsmTokenizer instance.

        Args:
            self (EsmTokenizer):
                The EsmTokenizer instance itself.

                - Type: EsmTokenizer object
                - Purpose: Represents the current instance of the EsmTokenizer class.

        Returns:
            dict:
                A dictionary containing the combined vocabulary.

                - Type: dict
                - Purpose: Represents the vocabulary with the base vocabulary and any added tokens.

        Raises:
            None.
        """
        base_vocab = self._token_to_id.copy()
        base_vocab.update(self.added_tokens_encoder)
        return base_vocab

    def token_to_id(self, token: str) -> int:
        """
        Method to retrieve the ID corresponding to a given token from the EsmTokenizer instance.

        Args:
            self (EsmTokenizer): The EsmTokenizer instance on which the method is called.
            token (str): The input token for which the corresponding ID needs to be retrieved. It should be a string.

        Returns:
            int: Returns the ID corresponding to the input token from the EsmTokenizer instance.
                If the token is not found in the internal token-to-ID mapping,
                the method returns the ID associated with the unknown token (unk_token) if defined.

        Raises:
            None
        """
        return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))

    def id_to_token(self, index: int) -> str:
        """
        Retrieve the token associated with the provided index from the EsmTokenizer.

        Args:
            self (EsmTokenizer): The instance of the EsmTokenizer class.
            index (int): The index of the token to retrieve.
                Must be a non-negative integer corresponding to a valid token index.

        Returns:
            str: The token associated with the provided index.
                If the index is not found in the mapping, the unknown token (unk_token) is returned.

        Raises:
            None
        """
        return self._id_to_token.get(index, self.unk_token)

    def build_inputs_with_special_tokens(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        This method builds inputs with special tokens for the EsmTokenizer class.

        Args:
            self: The instance of the EsmTokenizer class.
            token_ids_0 (List[int]): List of token IDs for the first sequence.
            token_ids_1 (Optional[List[int]]): List of token IDs for the second sequence, if present. Defaults to None.

        Returns:
            List[int]: A list of token IDs representing the input sequences with special tokens added.

        Raises:
            ValueError: Raised if token_ids_1 is not None and self.eos_token_id is None,
                indicating that multiple sequences cannot be tokenized when the EOS token is not set.
        """
        cls = [self.cls_token_id]
        sep = [self.eos_token_id]  # No sep token in ESM vocabulary
        if token_ids_1 is None:
            if self.eos_token_id is None:
                return cls + token_ids_0
            return cls + token_ids_0 + sep
        if self.eos_token_id is None:
            raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!")
        return cls + token_ids_0 + sep + token_ids_1 + sep  # Multiple inputs always have an EOS token

    def get_special_tokens_mask(
        self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
    ) -> List[int]:
        """
        Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

        Args:
            token_ids_0 (`List[int]`):
                List of ids of the first sequence.
            token_ids_1 (`List[int]`, *optional*):
                List of ids of the second sequence.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        """
        if already_has_special_tokens:
            if token_ids_1 is not None:
                raise ValueError(
                    "You should not supply a second sequence if the provided sequence of "
                    "ids is already formatted with special tokens for the model."
                )

            return [1 if token in self.all_special_ids else 0 for token in token_ids_0]
        mask = [1] + ([0] * len(token_ids_0)) + [1]
        if token_ids_1 is not None:
            mask += [0] * len(token_ids_1) + [1]
        return mask

    def save_vocabulary(self, save_directory, filename_prefix):
        """
        Save the vocabulary to a text file.

        Args:
            self (EsmTokenizer): The instance of the EsmTokenizer class.
            save_directory (str): The directory path where the vocabulary file will be saved.
            filename_prefix (str): A prefix to be added to the vocabulary file name. If None, no prefix is added.

        Returns:
            None.

        Raises:
            FileNotFoundError: If the specified save_directory does not exist.
            PermissionError: If the method does not have permission to write to the save_directory.
            OSError: If an error occurs while opening or writing to the vocabulary file.
        """
        vocab_file = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + "vocab.txt")
        with open(vocab_file, "w", encoding='utf-8') as f:
            f.write("\n".join(self.all_tokens))
        return (vocab_file,)

    @property
    def vocab_size(self) -> int:
        """
        This method, vocab_size, in the class EsmTokenizer calculates the size of the vocabulary based on the
        number of unique tokens present.

        Args:
            self (EsmTokenizer): The instance of the EsmTokenizer class.
                This parameter represents the current instance of the EsmTokenizer class.

        Returns:
            int: The method returns an integer value representing the size of the vocabulary, which is determined
                by the number of unique tokens present in the instance.

        Raises:
            No specific exceptions are raised by this method.
        """
        return len(self.all_tokens)

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.vocab_size: int property

This method, vocab_size, in the class EsmTokenizer calculates the size of the vocabulary based on the number of unique tokens present.

PARAMETER DESCRIPTION
self

The instance of the EsmTokenizer class. This parameter represents the current instance of the EsmTokenizer class.

TYPE: EsmTokenizer

RETURNS DESCRIPTION
int

The method returns an integer value representing the size of the vocabulary, which is determined by the number of unique tokens present in the instance.

TYPE: int

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.__init__(vocab_file, unk_token='<unk>', cls_token='<cls>', pad_token='<pad>', mask_token='<mask>', eos_token='<eos>', **kwargs)

Initializes an instance of the EsmTokenizer class.

PARAMETER DESCRIPTION
self

The instance of the class itself.

vocab_file

The path to the vocabulary file.

TYPE: str

unk_token

The token to represent unknown words. Defaults to ''.

TYPE: str DEFAULT: '<unk>'

cls_token

The token to represent the start of a sequence. Defaults to ''.

TYPE: str DEFAULT: '<cls>'

pad_token

The token to represent padding. Defaults to ''.

TYPE: str DEFAULT: '<pad>'

mask_token

The token to represent masked values. Defaults to ''.

TYPE: str DEFAULT: '<mask>'

eos_token

The token to represent the end of a sequence. Defaults to ''.

TYPE: str DEFAULT: '<eos>'

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
 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
def __init__(
    self,
    vocab_file,
    unk_token="<unk>",
    cls_token="<cls>",
    pad_token="<pad>",
    mask_token="<mask>",
    eos_token="<eos>",
    **kwargs,
):
    """
    Initializes an instance of the EsmTokenizer class.

    Args:
        self: The instance of the class itself.
        vocab_file (str): The path to the vocabulary file.
        unk_token (str, optional): The token to represent unknown words. Defaults to '<unk>'.
        cls_token (str, optional): The token to represent the start of a sequence. Defaults to '<cls>'.
        pad_token (str, optional): The token to represent padding. Defaults to '<pad>'.
        mask_token (str, optional): The token to represent masked values. Defaults to '<mask>'.
        eos_token (str, optional): The token to represent the end of a sequence. Defaults to '<eos>'.

    Returns:
        None.

    Raises:
        None.
    """
    self.all_tokens = load_vocab_file(vocab_file)
    self._id_to_token = dict(enumerate(self.all_tokens))
    self._token_to_id = {tok: ind for ind, tok in enumerate(self.all_tokens)}
    super().__init__(
        unk_token=unk_token,
        cls_token=cls_token,
        pad_token=pad_token,
        mask_token=mask_token,
        eos_token=eos_token,
        **kwargs,
    )

    # TODO, all the tokens are added? But they are also part of the vocab... bit strange.
    # none of them are special, but they all need special splitting.

    self.unique_no_split_tokens = self.all_tokens
    self._update_trie(self.unique_no_split_tokens)

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

This method builds inputs with special tokens for the EsmTokenizer class.

PARAMETER DESCRIPTION
self

The instance of the EsmTokenizer class.

token_ids_0

List of token IDs for the first sequence.

TYPE: List[int]

token_ids_1

List of token IDs for the second sequence, if present. Defaults to None.

TYPE: Optional[List[int]] DEFAULT: None

RETURNS DESCRIPTION
List[int]

List[int]: A list of token IDs representing the input sequences with special tokens added.

RAISES DESCRIPTION
ValueError

Raised if token_ids_1 is not None and self.eos_token_id is None, indicating that multiple sequences cannot be tokenized when the EOS token is not set.

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
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
def build_inputs_with_special_tokens(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    This method builds inputs with special tokens for the EsmTokenizer class.

    Args:
        self: The instance of the EsmTokenizer class.
        token_ids_0 (List[int]): List of token IDs for the first sequence.
        token_ids_1 (Optional[List[int]]): List of token IDs for the second sequence, if present. Defaults to None.

    Returns:
        List[int]: A list of token IDs representing the input sequences with special tokens added.

    Raises:
        ValueError: Raised if token_ids_1 is not None and self.eos_token_id is None,
            indicating that multiple sequences cannot be tokenized when the EOS token is not set.
    """
    cls = [self.cls_token_id]
    sep = [self.eos_token_id]  # No sep token in ESM vocabulary
    if token_ids_1 is None:
        if self.eos_token_id is None:
            return cls + token_ids_0
        return cls + token_ids_0 + sep
    if self.eos_token_id is None:
        raise ValueError("Cannot tokenize multiple sequences when EOS token is not set!")
    return cls + token_ids_0 + sep + token_ids_1 + sep  # Multiple inputs always have an EOS token

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.get_special_tokens_mask(token_ids_0, token_ids_1=None, already_has_special_tokens=False)

Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model or encode_plus methods.

PARAMETER DESCRIPTION
token_ids_0

List of ids of the first sequence.

TYPE: `List[int]`

token_ids_1

List of ids of the second sequence.

TYPE: `List[int]`, *optional* DEFAULT: None

already_has_special_tokens

Whether or not the token list is already formatted with special tokens for the model.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

RETURNS DESCRIPTION
List[int]

A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
260
261
262
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
def get_special_tokens_mask(
    self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
) -> List[int]:
    """
    Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
    special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

    Args:
        token_ids_0 (`List[int]`):
            List of ids of the first sequence.
        token_ids_1 (`List[int]`, *optional*):
            List of ids of the second sequence.
        already_has_special_tokens (`bool`, *optional*, defaults to `False`):
            Whether or not the token list is already formatted with special tokens for the model.

    Returns:
        A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
    """
    if already_has_special_tokens:
        if token_ids_1 is not None:
            raise ValueError(
                "You should not supply a second sequence if the provided sequence of "
                "ids is already formatted with special tokens for the model."
            )

        return [1 if token in self.all_special_ids else 0 for token in token_ids_0]
    mask = [1] + ([0] * len(token_ids_0)) + [1]
    if token_ids_1 is not None:
        mask += [0] * len(token_ids_1) + [1]
    return mask

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.get_vocab()

Method to retrieve the vocabulary from the EsmTokenizer instance.

PARAMETER DESCRIPTION
self

The EsmTokenizer instance itself.

  • Type: EsmTokenizer object
  • Purpose: Represents the current instance of the EsmTokenizer class.

TYPE: EsmTokenizer

RETURNS DESCRIPTION
dict

A dictionary containing the combined vocabulary.

  • Type: dict
  • Purpose: Represents the vocabulary with the base vocabulary and any added tokens.
Source code in mindnlp\transformers\models\esm\tokenization_esm.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def get_vocab(self):
    """
    Method to retrieve the vocabulary from the EsmTokenizer instance.

    Args:
        self (EsmTokenizer):
            The EsmTokenizer instance itself.

            - Type: EsmTokenizer object
            - Purpose: Represents the current instance of the EsmTokenizer class.

    Returns:
        dict:
            A dictionary containing the combined vocabulary.

            - Type: dict
            - Purpose: Represents the vocabulary with the base vocabulary and any added tokens.

    Raises:
        None.
    """
    base_vocab = self._token_to_id.copy()
    base_vocab.update(self.added_tokens_encoder)
    return base_vocab

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.id_to_token(index)

Retrieve the token associated with the provided index from the EsmTokenizer.

PARAMETER DESCRIPTION
self

The instance of the EsmTokenizer class.

TYPE: EsmTokenizer

index

The index of the token to retrieve. Must be a non-negative integer corresponding to a valid token index.

TYPE: int

RETURNS DESCRIPTION
str

The token associated with the provided index. If the index is not found in the mapping, the unknown token (unk_token) is returned.

TYPE: str

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def id_to_token(self, index: int) -> str:
    """
    Retrieve the token associated with the provided index from the EsmTokenizer.

    Args:
        self (EsmTokenizer): The instance of the EsmTokenizer class.
        index (int): The index of the token to retrieve.
            Must be a non-negative integer corresponding to a valid token index.

    Returns:
        str: The token associated with the provided index.
            If the index is not found in the mapping, the unknown token (unk_token) is returned.

    Raises:
        None
    """
    return self._id_to_token.get(index, self.unk_token)

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.save_vocabulary(save_directory, filename_prefix)

Save the vocabulary to a text file.

PARAMETER DESCRIPTION
self

The instance of the EsmTokenizer class.

TYPE: EsmTokenizer

save_directory

The directory path where the vocabulary file will be saved.

TYPE: str

filename_prefix

A prefix to be added to the vocabulary file name. If None, no prefix is added.

TYPE: str

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
FileNotFoundError

If the specified save_directory does not exist.

PermissionError

If the method does not have permission to write to the save_directory.

OSError

If an error occurs while opening or writing to the vocabulary file.

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def save_vocabulary(self, save_directory, filename_prefix):
    """
    Save the vocabulary to a text file.

    Args:
        self (EsmTokenizer): The instance of the EsmTokenizer class.
        save_directory (str): The directory path where the vocabulary file will be saved.
        filename_prefix (str): A prefix to be added to the vocabulary file name. If None, no prefix is added.

    Returns:
        None.

    Raises:
        FileNotFoundError: If the specified save_directory does not exist.
        PermissionError: If the method does not have permission to write to the save_directory.
        OSError: If an error occurs while opening or writing to the vocabulary file.
    """
    vocab_file = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + "vocab.txt")
    with open(vocab_file, "w", encoding='utf-8') as f:
        f.write("\n".join(self.all_tokens))
    return (vocab_file,)

mindnlp.transformers.models.esm.tokenization_esm.EsmTokenizer.token_to_id(token)

Method to retrieve the ID corresponding to a given token from the EsmTokenizer instance.

PARAMETER DESCRIPTION
self

The EsmTokenizer instance on which the method is called.

TYPE: EsmTokenizer

token

The input token for which the corresponding ID needs to be retrieved. It should be a string.

TYPE: str

RETURNS DESCRIPTION
int

Returns the ID corresponding to the input token from the EsmTokenizer instance. If the token is not found in the internal token-to-ID mapping, the method returns the ID associated with the unknown token (unk_token) if defined.

TYPE: int

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def token_to_id(self, token: str) -> int:
    """
    Method to retrieve the ID corresponding to a given token from the EsmTokenizer instance.

    Args:
        self (EsmTokenizer): The EsmTokenizer instance on which the method is called.
        token (str): The input token for which the corresponding ID needs to be retrieved. It should be a string.

    Returns:
        int: Returns the ID corresponding to the input token from the EsmTokenizer instance.
            If the token is not found in the internal token-to-ID mapping,
            the method returns the ID associated with the unknown token (unk_token) if defined.

    Raises:
        None
    """
    return self._token_to_id.get(token, self._token_to_id.get(self.unk_token))

mindnlp.transformers.models.esm.tokenization_esm.load_vocab_file(vocab_file)

Loads a vocabulary file and returns a list of stripped lines.

PARAMETER DESCRIPTION
vocab_file

The path of the vocabulary file to be loaded.

TYPE: str

RETURNS DESCRIPTION
list

A list of strings representing each line in the vocabulary file, with leading and trailing whitespaces removed.

RAISES DESCRIPTION
FileNotFoundError

If the specified vocabulary file does not exist.

PermissionError

If there is a permission issue with accessing the vocabulary file.

OSError

If there is an error while reading the vocabulary file.

Source code in mindnlp\transformers\models\esm\tokenization_esm.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def load_vocab_file(vocab_file):
    """
    Loads a vocabulary file and returns a list of stripped lines.

    Args:
        vocab_file (str): The path of the vocabulary file to be loaded.

    Returns:
        list: A list of strings representing each line in the vocabulary file,
            with leading and trailing whitespaces removed.

    Raises:
        FileNotFoundError: If the specified vocabulary file does not exist.
        PermissionError: If there is a permission issue with accessing the vocabulary file.
        OSError: If there is an error while reading the vocabulary file.
    """
    with open(vocab_file, "r", encoding='utf-8') as f:
        lines = f.read().splitlines()
        return [l.strip() for l in lines]