Skip to content

mpt

mindnlp.transformers.models.mpt.configuration_mpt

Mpt configuration

mindnlp.transformers.models.mpt.configuration_mpt.DeprecatedList

Bases: list

Represents a list class that issues a warning about deprecated features when accessed.

This class inherits from the built-in list class and overrides the getitem method to issue a warning message when accessing elements. The warning message alerts users that archive maps are deprecated and will be removed in version v4.40.0 as they are no longer relevant. It also provides a recommendation for an alternative method to retrieve all checkpoints for a given architecture using the huggingface_hub library with the list_models method.

Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class DeprecatedList(list):

    """
    Represents a list class that issues a warning about deprecated features when accessed.

    This class inherits from the built-in list class and overrides the __getitem__ method to issue a warning message
    when accessing elements. The warning message alerts users that archive maps are deprecated and will be removed in
    version v4.40.0 as they are no longer relevant. It also provides a recommendation for an alternative method to
    retrieve all checkpoints for a given architecture using the `huggingface_hub` library with the `list_models` method.
    """
    def __getitem__(self, item):
        """
        Get an item from the DeprecatedList object.

        Args:
            self (DeprecatedList): The instance of the DeprecatedList class.
            item (Any): The key to retrieve an item from the DeprecatedList.

        Returns:
            None.

        Raises:
            None.
        """
        logger.warning_once(
            "Archive maps are deprecated and will be removed in version v4.40.0 as they are no longer relevant. "
            "If looking to get all checkpoints for a given architecture, we recommend using `huggingface_hub` "
            "with the `list_models` method."
        )
        return super().__getitem__(item)

mindnlp.transformers.models.mpt.configuration_mpt.DeprecatedList.__getitem__(item)

Get an item from the DeprecatedList object.

PARAMETER DESCRIPTION
self

The instance of the DeprecatedList class.

TYPE: DeprecatedList

item

The key to retrieve an item from the DeprecatedList.

TYPE: Any

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def __getitem__(self, item):
    """
    Get an item from the DeprecatedList object.

    Args:
        self (DeprecatedList): The instance of the DeprecatedList class.
        item (Any): The key to retrieve an item from the DeprecatedList.

    Returns:
        None.

    Raises:
        None.
    """
    logger.warning_once(
        "Archive maps are deprecated and will be removed in version v4.40.0 as they are no longer relevant. "
        "If looking to get all checkpoints for a given architecture, we recommend using `huggingface_hub` "
        "with the `list_models` method."
    )
    return super().__getitem__(item)

mindnlp.transformers.models.mpt.configuration_mpt.MptAttentionConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [MptAttention] class. It is used to instantiate attention layers according to the specified arguments, defining the layers architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the MPT mosaicml/mpt-7b architecture. Most of the arguments are kept for backward compatibility with previous MPT models that are hosted on the Hub (previously with trust_remote_code=True).

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

PARAMETER DESCRIPTION
attn_type

type of attention to use. Options: "multihead_attention", "multiquery_attention".

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

attn_pdrop

The dropout probability for the attention layers.

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

attn_impl

The attention implementation to use. One of "torch", "flash", or "triton".

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

clip_qkv

If not None, clip the queries, keys, and values in the attention layer to this value.

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

softmax_scale

If not None, scale the softmax in the attention layer by this value. If None, will default to 1/sqrt(hidden_size).

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

prefix_lm

Whether the model should operate as a Prefix LM. This requires passing an extra prefix_mask argument which indicates which tokens belong to the prefix. Tokens in the prefix can attend to one another bi-directionally. Tokens outside the prefix use causal attention.

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

qk_ln

Whether to apply layer normalization to the queries and keys in the attention layer.

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

attn_uses_sequence_id

Whether to restrict attention to tokens that have the same token_type_ids. When the model is in train mode, this requires passing an extra token_type_ids argument which indicates which sub-sequence each token belongs to. Defaults to False meaning any provided token_type_ids will be ignored.

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

alibi

Whether or not to use the alibi bias instead of positional embedding.

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

alibi_bias_max

The maximum value of the alibi bias.

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

Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
 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
class MptAttentionConfig(PretrainedConfig):
    """
    This is the configuration class to store the configuration of a [`MptAttention`] class. It is used to instantiate
    attention layers according to the specified arguments, defining the layers architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the MPT
    [mosaicml/mpt-7b](https://huggingface.co/mosaicml/mpt-7b) architecture. Most of the arguments are kept for backward
    compatibility with previous MPT models that are hosted on the Hub (previously with `trust_remote_code=True`).

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

    Args:
        attn_type (`str`, *optional*, defaults to `"multihead_attention"`):
            type of attention to use. Options: `"multihead_attention"`, `"multiquery_attention"`.
        attn_pdrop (`float`, *optional*, defaults to 0.0):
            The dropout probability for the attention layers.
        attn_impl (`str`, *optional*, defaults to `"torch"`):
            The attention implementation to use. One of `"torch"`, `"flash"`, or `"triton"`.
        clip_qkv (`float`, *optional*):
            If not `None`, clip the queries, keys, and values in the attention layer to this value.
        softmax_scale (`float`, *optional*, defaults to `None`):
            If not `None`, scale the softmax in the attention layer by this value. If `None`, will default to
            `1/sqrt(hidden_size)`.
        prefix_lm (`bool`, *optional*, defaults to `False`)):
            Whether the model should operate as a Prefix LM. This requires passing an extra `prefix_mask` argument
            which indicates which tokens belong to the prefix. Tokens in the prefix can attend to one another
            bi-directionally. Tokens outside the prefix use causal attention.
        qk_ln (`bool`, *optional*, defaults to `False`):
            Whether to apply layer normalization to the queries and keys in the attention layer.
        attn_uses_sequence_id (`bool`, *optional*, defaults to `False`)):
            Whether to restrict attention to tokens that have the same token_type_ids. When the model is in `train`
            mode, this requires passing an extra *token_type_ids* argument which indicates which sub-sequence each
            token belongs to. Defaults to `False` meaning any provided *token_type_ids* will be ignored.
        alibi (`bool`, *optional*, defaults to `True`):
            Whether or not to use the alibi bias instead of positional embedding.
        alibi_bias_max (`int`, *optional*, defaults to 8):
            The maximum value of the alibi bias.
    """
    def __init__(
        self,
        attn_type="multihead_attention",
        attn_pdrop=0.0,
        attn_impl="torch",
        clip_qkv=None,
        softmax_scale=None,
        prefix_lm=False,
        qk_ln=False,
        attn_uses_sequence_id=False,
        alibi=True,
        alibi_bias_max=8,
        **kwargs,
    ):
        """
        Initializes a new instance of the MptAttentionConfig class.

        Args:
            self: The instance of the class.
            attn_type (str): The type of attention. Must be either 'multihead_attention' or 'multiquery_attention'.
            attn_pdrop (float): The dropout probability for attention weights. Default is 0.0.
            attn_impl (str): The implementation of attention. Default is 'torch'.
            clip_qkv: Not specified.
            softmax_scale: Not specified.
            prefix_lm (bool): Indicates if prefix language model is used. Default is False.
            qk_ln (bool): Indicates if layer normalization is applied to query and key. Default is False.
            attn_uses_sequence_id (bool): Indicates if sequence ID is used in attention. Default is False.
            alibi (bool): Indicates if alibi bias is used. Default is True.
            alibi_bias_max: Not specified.
            **kwargs: Additional keyword arguments.

        Returns:
            None.

        Raises:
            ValueError: If 'attn_type' is not either 'multihead_attention' or 'multiquery_attention'.

        """
        super().__init__()
        self.attn_type = attn_type
        self.attn_pdrop = attn_pdrop
        self.attn_impl = attn_impl
        self.clip_qkv = clip_qkv
        self.softmax_scale = softmax_scale
        self.prefix_lm = prefix_lm
        self.attn_uses_sequence_id = attn_uses_sequence_id
        self.alibi = alibi
        self.qk_ln = qk_ln
        self.alibi_bias_max = alibi_bias_max

        if attn_type not in ["multihead_attention", "multiquery_attention"]:
            raise ValueError(
                f"`attn_type` has to be either `multihead_attention` or `multiquery_attention`. Received: {attn_type}"
            )

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path, **kwargs) -> "PretrainedConfig":
        """
        Instantiates a new instance of the MptAttentionConfig class from a pre-trained model.

        Args:
            cls: The class object that the method was called on.
            pretrained_model_name_or_path (str): The name or path of the pre-trained model to load.

        Returns:
            PretrainedConfig:
                An instance of the PretrainedConfig class instantiated with the configuration of the pre-trained model.

        Raises:
            None.
        """
        cls._set_token_in_kwargs(kwargs)

        config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)

        if config_dict.get("model_type") == "mpt":
            config_dict = config_dict["attn_config"]

        if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
            logger.warning(
                f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
                f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
            )

        return cls.from_dict(config_dict, **kwargs)

mindnlp.transformers.models.mpt.configuration_mpt.MptAttentionConfig.__init__(attn_type='multihead_attention', attn_pdrop=0.0, attn_impl='torch', clip_qkv=None, softmax_scale=None, prefix_lm=False, qk_ln=False, attn_uses_sequence_id=False, alibi=True, alibi_bias_max=8, **kwargs)

Initializes a new instance of the MptAttentionConfig class.

PARAMETER DESCRIPTION
self

The instance of the class.

attn_type

The type of attention. Must be either 'multihead_attention' or 'multiquery_attention'.

TYPE: str DEFAULT: 'multihead_attention'

attn_pdrop

The dropout probability for attention weights. Default is 0.0.

TYPE: float DEFAULT: 0.0

attn_impl

The implementation of attention. Default is 'torch'.

TYPE: str DEFAULT: 'torch'

clip_qkv

Not specified.

DEFAULT: None

softmax_scale

Not specified.

DEFAULT: None

prefix_lm

Indicates if prefix language model is used. Default is False.

TYPE: bool DEFAULT: False

qk_ln

Indicates if layer normalization is applied to query and key. Default is False.

TYPE: bool DEFAULT: False

attn_uses_sequence_id

Indicates if sequence ID is used in attention. Default is False.

TYPE: bool DEFAULT: False

alibi

Indicates if alibi bias is used. Default is True.

TYPE: bool DEFAULT: True

alibi_bias_max

Not specified.

DEFAULT: 8

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If 'attn_type' is not either 'multihead_attention' or 'multiquery_attention'.

Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
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
def __init__(
    self,
    attn_type="multihead_attention",
    attn_pdrop=0.0,
    attn_impl="torch",
    clip_qkv=None,
    softmax_scale=None,
    prefix_lm=False,
    qk_ln=False,
    attn_uses_sequence_id=False,
    alibi=True,
    alibi_bias_max=8,
    **kwargs,
):
    """
    Initializes a new instance of the MptAttentionConfig class.

    Args:
        self: The instance of the class.
        attn_type (str): The type of attention. Must be either 'multihead_attention' or 'multiquery_attention'.
        attn_pdrop (float): The dropout probability for attention weights. Default is 0.0.
        attn_impl (str): The implementation of attention. Default is 'torch'.
        clip_qkv: Not specified.
        softmax_scale: Not specified.
        prefix_lm (bool): Indicates if prefix language model is used. Default is False.
        qk_ln (bool): Indicates if layer normalization is applied to query and key. Default is False.
        attn_uses_sequence_id (bool): Indicates if sequence ID is used in attention. Default is False.
        alibi (bool): Indicates if alibi bias is used. Default is True.
        alibi_bias_max: Not specified.
        **kwargs: Additional keyword arguments.

    Returns:
        None.

    Raises:
        ValueError: If 'attn_type' is not either 'multihead_attention' or 'multiquery_attention'.

    """
    super().__init__()
    self.attn_type = attn_type
    self.attn_pdrop = attn_pdrop
    self.attn_impl = attn_impl
    self.clip_qkv = clip_qkv
    self.softmax_scale = softmax_scale
    self.prefix_lm = prefix_lm
    self.attn_uses_sequence_id = attn_uses_sequence_id
    self.alibi = alibi
    self.qk_ln = qk_ln
    self.alibi_bias_max = alibi_bias_max

    if attn_type not in ["multihead_attention", "multiquery_attention"]:
        raise ValueError(
            f"`attn_type` has to be either `multihead_attention` or `multiquery_attention`. Received: {attn_type}"
        )

mindnlp.transformers.models.mpt.configuration_mpt.MptAttentionConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) classmethod

Instantiates a new instance of the MptAttentionConfig class from a pre-trained model.

PARAMETER DESCRIPTION
cls

The class object that the method was called on.

pretrained_model_name_or_path

The name or path of the pre-trained model to load.

TYPE: str

RETURNS DESCRIPTION
PretrainedConfig

An instance of the PretrainedConfig class instantiated with the configuration of the pre-trained model.

TYPE: PretrainedConfig

Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
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
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs) -> "PretrainedConfig":
    """
    Instantiates a new instance of the MptAttentionConfig class from a pre-trained model.

    Args:
        cls: The class object that the method was called on.
        pretrained_model_name_or_path (str): The name or path of the pre-trained model to load.

    Returns:
        PretrainedConfig:
            An instance of the PretrainedConfig class instantiated with the configuration of the pre-trained model.

    Raises:
        None.
    """
    cls._set_token_in_kwargs(kwargs)

    config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)

    if config_dict.get("model_type") == "mpt":
        config_dict = config_dict["attn_config"]

    if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
        logger.warning(
            f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
            f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
        )

    return cls.from_dict(config_dict, **kwargs)

mindnlp.transformers.models.mpt.configuration_mpt.MptConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [MptModel]. It is used to instantiate a Mpt model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to the Mpt-7b architecture mosaicml/mpt-7b.

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

PARAMETER DESCRIPTION
d_model

Dimensionality of the embeddings and hidden states.

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

n_heads

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

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

n_layers

Number of hidden layers in the Transformer encoder.

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

expansion_ratio

The ratio of the up/down scale in the MLP.

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

max_seq_len

The maximum sequence length of the model.

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

vocab_size

Vocabulary size of the Mpt model. Defines the maximum number of different tokens that can be represented by the inputs_ids passed when calling [MptModel]. Check this discussion on how the vocab_size has been defined.

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

resid_pdrop

The dropout probability applied to the attention output before combining with residual.

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

layer_norm_epsilon

The epsilon to use in the layer normalization layers.

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

emb_pdrop

The dropout probability for the embedding layer.

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

learned_pos_emb

Whether to use learned positional embeddings.

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

attn_config

A dictionary used to configure the model's attention module.

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

init_device

The device to use for parameter initialization. Defined for backward compatibility

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

logit_scale

If not None, scale the logits by this value.

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

no_bias

Whether to use bias in all linear layers.

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

verbose

The verbosity level to use for logging. Used in the previous versions of MPT models for logging. This argument is deprecated.

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

embedding_fraction

The fraction to scale the gradients of the embedding layer by.

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

norm_type

Type of layer norm to use. All MPT models uses the same layer norm implementation. Defined for backward compatibility.

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

use_cache

Whether or not the model should return the last key/values attentions (not used by all models).

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

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

Example
>>> from transformers import MptConfig, MptModel
...
>>> # Initializing a Mpt configuration
>>> configuration = MptConfig()
...
>>> # Initializing a model (with random weights) from the configuration
>>> model = MptModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
class MptConfig(PretrainedConfig):
    """
    This is the configuration class to store the configuration of a [`MptModel`]. It is used to instantiate a Mpt model
    according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to the Mpt-7b architecture
    [mosaicml/mpt-7b](https://huggingface.co/mosaicml/mpt-7b).

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


    Args:
        d_model (`int`, *optional*, defaults to 2048):
            Dimensionality of the embeddings and hidden states.
        n_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        n_layers (`int`, *optional*, defaults to 24):
            Number of hidden layers in the Transformer encoder.
        expansion_ratio (`int`, *optional*, defaults to 4):
            The ratio of the up/down scale in the MLP.
        max_seq_len (`int`, *optional*, defaults to 2048):
            The maximum sequence length of the model.
        vocab_size (`int`, *optional*, defaults to 50368):
            Vocabulary size of the Mpt model. Defines the maximum number of different tokens that can be represented by
            the `inputs_ids` passed when calling [`MptModel`]. Check [this
            discussion](https://huggingface.co/bigscience/mpt/discussions/120#633d28389addb8530b406c2a) on how the
            `vocab_size` has been defined.
        resid_pdrop (`float`, *optional*, defaults to 0.0):
            The dropout probability applied to the attention output before combining with residual.
        layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
            The epsilon to use in the layer normalization layers.
        emb_pdrop (`float`, *optional*, defaults to 0.0):
            The dropout probability for the embedding layer.
        learned_pos_emb (`bool`, *optional*, defaults to `True`):
            Whether to use learned positional embeddings.
        attn_config (`dict`, *optional*):
            A dictionary used to configure the model's attention module.
        init_device (`str`, *optional*, defaults to `"cpu"`):
            The device to use for parameter initialization. Defined for backward compatibility
        logit_scale (`float`, *optional*):
            If not None, scale the logits by this value.
        no_bias (`bool`, *optional*, defaults to `True`):
            Whether to use bias in all linear layers.
        verbose (`int`, *optional*, defaults to 0):
            The verbosity level to use for logging. Used in the previous versions of MPT models for logging. This
            argument is deprecated.
        embedding_fraction (`float`, *optional*, defaults to 1.0):
            The fraction to scale the gradients of the embedding layer by.
        norm_type (`str`, *optional*, defaults to `"low_precision_layernorm"`):
            Type of layer norm to use. All MPT models uses the same layer norm implementation. Defined for backward
            compatibility.
        use_cache (`bool`, *optional*, defaults to `False`):
            Whether or not the model should return the last key/values attentions (not used by all models).
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

    Example:
        ```python
        >>> from transformers import MptConfig, MptModel
        ...
        >>> # Initializing a Mpt configuration
        >>> configuration = MptConfig()
        ...
        >>> # Initializing a model (with random weights) from the configuration
        >>> model = MptModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "mpt"
    attribute_map = {
        "num_attention_heads": "n_heads",
        "hidden_size": "d_model",
        "num_hidden_layers": "n_layers",
    }

    def __init__(
        self,
        d_model: int = 2048,
        n_heads: int = 16,
        n_layers: int = 24,
        expansion_ratio: int = 4,
        max_seq_len: int = 2048,
        vocab_size: int = 50368,
        resid_pdrop: float = 0.0,
        layer_norm_epsilon: float = 1e-5,
        emb_pdrop: float = 0.0,
        learned_pos_emb: bool = True,
        attn_config: MptAttentionConfig = None,
        init_device: str = "cpu",
        logit_scale: Optional[Union[float, str]] = None,
        no_bias: bool = True,
        verbose: int = 0,
        embedding_fraction: float = 1.0,
        norm_type: str = "low_precision_layernorm",
        use_cache: bool = False,
        initializer_range=0.02,
        **kwargs,
    ):
        """
        Initializes an instance of the MptConfig class.

        Args:
            self: The object instance.
            d_model (int, optional): The dimensionality of the model's hidden states. Defaults to 2048.
            n_heads (int, optional): The number of attention heads. Defaults to 16.
            n_layers (int, optional): The number of layers in the model. Defaults to 24.
            expansion_ratio (int, optional): The expansion ratio for feed-forward layers. Defaults to 4.
            max_seq_len (int, optional): The maximum sequence length. Defaults to 2048.
            vocab_size (int, optional): The size of the vocabulary. Defaults to 50368.
            resid_pdrop (float, optional): The dropout probability for residual connections. Defaults to 0.0.
            layer_norm_epsilon (float, optional): The epsilon value for layer normalization. Defaults to 1e-05.
            emb_pdrop (float, optional): The dropout probability for token embeddings. Defaults to 0.0.
            learned_pos_emb (bool, optional): Whether to use learned positional embeddings. Defaults to True.
            attn_config (MptAttentionConfig or dict, optional): The attention configuration. Defaults to None.
            init_device (str, optional): The device to initialize the model on. Defaults to 'cpu'.
            logit_scale (float or str, optional): The scale factor for logits or 'none' to disable scaling. Defaults to None.
            no_bias (bool, optional): Whether to exclude biases in the model. Defaults to True.
            verbose (int, optional): The verbosity level. Defaults to 0.
            embedding_fraction (float, optional): The fraction of the embedding table to use. Defaults to 1.0.
            norm_type (str, optional): The type of layer normalization. Defaults to 'low_precision_layernorm'.
            use_cache (bool, optional): Whether to use caching in the model. Defaults to False.
            initializer_range (float, optional): The range for weight initialization. Defaults to 0.02.

        Returns:
            None.

        Raises:
            None.
        """
        if attn_config is None:
            self.attn_config = MptAttentionConfig()
        elif isinstance(attn_config, dict):
            self.attn_config = MptAttentionConfig(**attn_config)
        else:
            self.attn_config = attn_config
        self.d_model = d_model
        self.n_heads = n_heads
        self.n_layers = n_layers
        self.expansion_ratio = expansion_ratio
        self.max_seq_len = max_seq_len
        self.vocab_size = vocab_size
        self.resid_pdrop = resid_pdrop
        self.emb_pdrop = emb_pdrop
        self.learned_pos_emb = learned_pos_emb
        self.init_device = init_device
        self.logit_scale = logit_scale
        self.no_bias = no_bias
        self.verbose = verbose
        self.embedding_fraction = embedding_fraction
        self.norm_type = norm_type
        self.layer_norm_epsilon = layer_norm_epsilon
        self.use_cache = use_cache
        self.initializer_range = initializer_range
        super().__init__(**kwargs)

mindnlp.transformers.models.mpt.configuration_mpt.MptConfig.__init__(d_model=2048, n_heads=16, n_layers=24, expansion_ratio=4, max_seq_len=2048, vocab_size=50368, resid_pdrop=0.0, layer_norm_epsilon=1e-05, emb_pdrop=0.0, learned_pos_emb=True, attn_config=None, init_device='cpu', logit_scale=None, no_bias=True, verbose=0, embedding_fraction=1.0, norm_type='low_precision_layernorm', use_cache=False, initializer_range=0.02, **kwargs)

Initializes an instance of the MptConfig class.

PARAMETER DESCRIPTION
self

The object instance.

d_model

The dimensionality of the model's hidden states. Defaults to 2048.

TYPE: int DEFAULT: 2048

n_heads

The number of attention heads. Defaults to 16.

TYPE: int DEFAULT: 16

n_layers

The number of layers in the model. Defaults to 24.

TYPE: int DEFAULT: 24

expansion_ratio

The expansion ratio for feed-forward layers. Defaults to 4.

TYPE: int DEFAULT: 4

max_seq_len

The maximum sequence length. Defaults to 2048.

TYPE: int DEFAULT: 2048

vocab_size

The size of the vocabulary. Defaults to 50368.

TYPE: int DEFAULT: 50368

resid_pdrop

The dropout probability for residual connections. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

layer_norm_epsilon

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

TYPE: float DEFAULT: 1e-05

emb_pdrop

The dropout probability for token embeddings. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

learned_pos_emb

Whether to use learned positional embeddings. Defaults to True.

TYPE: bool DEFAULT: True

attn_config

The attention configuration. Defaults to None.

TYPE: MptAttentionConfig or dict DEFAULT: None

init_device

The device to initialize the model on. Defaults to 'cpu'.

TYPE: str DEFAULT: 'cpu'

logit_scale

The scale factor for logits or 'none' to disable scaling. Defaults to None.

TYPE: float or str DEFAULT: None

no_bias

Whether to exclude biases in the model. Defaults to True.

TYPE: bool DEFAULT: True

verbose

The verbosity level. Defaults to 0.

TYPE: int DEFAULT: 0

embedding_fraction

The fraction of the embedding table to use. Defaults to 1.0.

TYPE: float DEFAULT: 1.0

norm_type

The type of layer normalization. Defaults to 'low_precision_layernorm'.

TYPE: str DEFAULT: 'low_precision_layernorm'

use_cache

Whether to use caching in the model. Defaults to False.

TYPE: bool DEFAULT: False

initializer_range

The range for weight initialization. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/configuration_mpt.py
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def __init__(
    self,
    d_model: int = 2048,
    n_heads: int = 16,
    n_layers: int = 24,
    expansion_ratio: int = 4,
    max_seq_len: int = 2048,
    vocab_size: int = 50368,
    resid_pdrop: float = 0.0,
    layer_norm_epsilon: float = 1e-5,
    emb_pdrop: float = 0.0,
    learned_pos_emb: bool = True,
    attn_config: MptAttentionConfig = None,
    init_device: str = "cpu",
    logit_scale: Optional[Union[float, str]] = None,
    no_bias: bool = True,
    verbose: int = 0,
    embedding_fraction: float = 1.0,
    norm_type: str = "low_precision_layernorm",
    use_cache: bool = False,
    initializer_range=0.02,
    **kwargs,
):
    """
    Initializes an instance of the MptConfig class.

    Args:
        self: The object instance.
        d_model (int, optional): The dimensionality of the model's hidden states. Defaults to 2048.
        n_heads (int, optional): The number of attention heads. Defaults to 16.
        n_layers (int, optional): The number of layers in the model. Defaults to 24.
        expansion_ratio (int, optional): The expansion ratio for feed-forward layers. Defaults to 4.
        max_seq_len (int, optional): The maximum sequence length. Defaults to 2048.
        vocab_size (int, optional): The size of the vocabulary. Defaults to 50368.
        resid_pdrop (float, optional): The dropout probability for residual connections. Defaults to 0.0.
        layer_norm_epsilon (float, optional): The epsilon value for layer normalization. Defaults to 1e-05.
        emb_pdrop (float, optional): The dropout probability for token embeddings. Defaults to 0.0.
        learned_pos_emb (bool, optional): Whether to use learned positional embeddings. Defaults to True.
        attn_config (MptAttentionConfig or dict, optional): The attention configuration. Defaults to None.
        init_device (str, optional): The device to initialize the model on. Defaults to 'cpu'.
        logit_scale (float or str, optional): The scale factor for logits or 'none' to disable scaling. Defaults to None.
        no_bias (bool, optional): Whether to exclude biases in the model. Defaults to True.
        verbose (int, optional): The verbosity level. Defaults to 0.
        embedding_fraction (float, optional): The fraction of the embedding table to use. Defaults to 1.0.
        norm_type (str, optional): The type of layer normalization. Defaults to 'low_precision_layernorm'.
        use_cache (bool, optional): Whether to use caching in the model. Defaults to False.
        initializer_range (float, optional): The range for weight initialization. Defaults to 0.02.

    Returns:
        None.

    Raises:
        None.
    """
    if attn_config is None:
        self.attn_config = MptAttentionConfig()
    elif isinstance(attn_config, dict):
        self.attn_config = MptAttentionConfig(**attn_config)
    else:
        self.attn_config = attn_config
    self.d_model = d_model
    self.n_heads = n_heads
    self.n_layers = n_layers
    self.expansion_ratio = expansion_ratio
    self.max_seq_len = max_seq_len
    self.vocab_size = vocab_size
    self.resid_pdrop = resid_pdrop
    self.emb_pdrop = emb_pdrop
    self.learned_pos_emb = learned_pos_emb
    self.init_device = init_device
    self.logit_scale = logit_scale
    self.no_bias = no_bias
    self.verbose = verbose
    self.embedding_fraction = embedding_fraction
    self.norm_type = norm_type
    self.layer_norm_epsilon = layer_norm_epsilon
    self.use_cache = use_cache
    self.initializer_range = initializer_range
    super().__init__(**kwargs)

mindnlp.transformers.models.mpt.modeling_mpt

PyTorch MPT model.

mindnlp.transformers.models.mpt.modeling_mpt.MptAttention

Bases: Module

Multi-head self attention. Using torch or triton attention implemetation enables user to also use additive bias.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
 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
class MptAttention(nn.Module):
    """Multi-head self attention.
    Using torch or triton attention implemetation enables user to also use additive bias.
    """
    def __init__(self, config: MptConfig):
        """
        Initializes an instance of the MptAttention class.

        Args:
            self: The object instance.
            config (MptConfig):
                An object of type MptConfig that contains the configuration parameters for the MptAttention.

        Returns:
            None

        Raises:
            None

        Description:
            This method is used to initialize the MptAttention class. It sets various attributes of the class instance
            based on the provided configuration.

            The 'self' parameter refers to the object instance itself. It is automatically passed when calling the method.

            The 'config' parameter is an instance of the MptConfig class which contains the following attributes:

            - hidden_size (int): The size of the hidden state.
            - n_heads (int): The number of attention heads.
            - max_seq_length (int): The maximum sequence length.
            - attn_config (AttnConfig): An object of type AttnConfig that contains attention configuration parameters.

                - softmax_scale (float): The scale factor for the softmax function.
                If not provided, it is set to 1 / sqrt(hidden_size / n_heads).
                - attn_pdrop (float): The dropout probability for attention weights.

            The method performs the following steps:

            1. Calls the __init__ method of the parent class using the 'super()' function.
            2. Sets the 'hidden_size', 'n_heads', 'max_seq_length', and 'head_dim' attributes based on the values
            from the 'config' parameter.
            3. Sets the 'softmax_scale' attribute based on the 'softmax_scale' attribute of the 'attn_config' attribute
            from the 'config' parameter. If not provided, it is calculated as 1 / sqrt(hidden_size / n_heads).
            4. Sets the 'attn_dropout_p' attribute based on the 'attn_pdrop' attribute of the 'attn_config' attribute
            from the 'config' parameter.
            5. Initializes the 'Wqkv' attribute as a dense layer with input size 'hidden_size' and output size
            '3 * hidden_size', with no bias.
            6. Initializes the 'out_proj' attribute as a dense layer with input size 'hidden_size' and output size
            'hidden_size', with no bias.
        """
        super().__init__()
        self.hidden_size = config.hidden_size
        self.n_heads = config.n_heads
        self.max_seq_length = config.max_seq_len
        self.head_dim = self.hidden_size // self.n_heads
        self.softmax_scale = config.attn_config.softmax_scale
        if self.softmax_scale is None:
            self.softmax_scale = 1 / math.sqrt(self.hidden_size / self.n_heads)

        self.attn_dropout_p = config.attn_config.attn_pdrop
        self.Wqkv = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
        self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        position_bias: mindspore.Tensor,
        past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
    ):
        """
        Constructs the attention mechanism.

        Args:
            self (MptAttention): The instance of the MptAttention class.
            hidden_states (mindspore.Tensor): The input tensor of shape (batch_size, seq_length, hidden_size)
                representing the hidden states.
            position_bias (mindspore.Tensor): The input tensor of shape (batch_size, seq_length, seq_length)
                representing the position bias.
            past_key_value (Optional[Tuple[mindspore.Tensor]]): The optional tuple of past key-value states.
                Default is None.
            attention_mask (Optional[mindspore.Tensor]): The optional input tensor of shape (batch_size, seq_length)
                representing the attention mask. Default is None.

        Returns:
            Tuple[mindspore.Tensor, mindspore.Tensor, Tuple[mindspore.Tensor]]: A tuple containing the attention
                output tensor of shape (batch_size, seq_length, hidden_size), the attention weights tensor of
                shape (batch_size, num_heads, seq_length, seq_length), and the updated past key-value states tuple.

        Raises:
            ValueError: If the position_bias tensor does not have 3 dimensions.
        """
        batch_size, seq_length = hidden_states.shape[:2]

        mixed_qkv = self.Wqkv(hidden_states)
        query_states, key_states, value_states = mixed_qkv.chunk(3, axis=2)
        query_states = query_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).swapaxes(1, 2)
        key_states = key_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).swapaxes(1, 2)
        value_states = value_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).swapaxes(1, 2)

        if past_key_value is not None:
            if len(past_key_value) != 0:
                key_states = ops.cat([past_key_value[0], key_states], axis=2)
                value_states = ops.cat([past_key_value[1], value_states], axis=2)
            past_key_value = (key_states, value_states)
        else:
            past_key_value = (key_states, value_states)

        attention_scores = ops.matmul(query_states, key_states.swapaxes(-1, -2)) * self.softmax_scale

        query_length = seq_length if past_key_value is None else seq_length + past_key_value[0].shape[2]

        if position_bias is not None:
            if len(position_bias.shape) != 3:
                raise ValueError(f"Expecting position_bias shape to be 3 dimensions, got {len(position_bias.shape)}")
            key_length = key_states.shape[-2]

            position_bias_query_index = max(0, position_bias.shape[1] - query_length)
            position_bias_key_index = max(0, position_bias.shape[2] - key_length)

            position_bias = position_bias[:, position_bias_query_index:, position_bias_key_index:]

            attention_scores = attention_scores + position_bias

        if attention_mask is not None:
            attention_scores = attention_scores.masked_fill(attention_mask, finfo(query_states.dtype, 'min'))

        # (batch_size, n_heads, seq_length, key_length)
        attn_weights = ops.softmax(attention_scores.float(), axis=-1).to(dtype=value_states.dtype)
        attn_weights = ops.dropout(attn_weights, p=self.attn_dropout_p, training=self.training)

        context_states = ops.matmul(attn_weights, value_states)
        context_states = context_states.permute(0, 2, 1, 3).view(batch_size, seq_length, -1)
        attn_output = self.out_proj(context_states)

        return attn_output, attn_weights, past_key_value

mindnlp.transformers.models.mpt.modeling_mpt.MptAttention.__init__(config)

Initializes an instance of the MptAttention class.

PARAMETER DESCRIPTION
self

The object instance.

config

An object of type MptConfig that contains the configuration parameters for the MptAttention.

TYPE: MptConfig

RETURNS DESCRIPTION

None

Description

This method is used to initialize the MptAttention class. It sets various attributes of the class instance based on the provided configuration.

The 'self' parameter refers to the object instance itself. It is automatically passed when calling the method.

The 'config' parameter is an instance of the MptConfig class which contains the following attributes:

  • hidden_size (int): The size of the hidden state.
  • n_heads (int): The number of attention heads.
  • max_seq_length (int): The maximum sequence length.
  • attn_config (AttnConfig): An object of type AttnConfig that contains attention configuration parameters.

    • softmax_scale (float): The scale factor for the softmax function. If not provided, it is set to 1 / sqrt(hidden_size / n_heads).
    • attn_pdrop (float): The dropout probability for attention weights.

The method performs the following steps:

  1. Calls the init method of the parent class using the 'super()' function.
  2. Sets the 'hidden_size', 'n_heads', 'max_seq_length', and 'head_dim' attributes based on the values from the 'config' parameter.
  3. Sets the 'softmax_scale' attribute based on the 'softmax_scale' attribute of the 'attn_config' attribute from the 'config' parameter. If not provided, it is calculated as 1 / sqrt(hidden_size / n_heads).
  4. Sets the 'attn_dropout_p' attribute based on the 'attn_pdrop' attribute of the 'attn_config' attribute from the 'config' parameter.
  5. Initializes the 'Wqkv' attribute as a dense layer with input size 'hidden_size' and output size '3 * hidden_size', with no bias.
  6. Initializes the 'out_proj' attribute as a dense layer with input size 'hidden_size' and output size 'hidden_size', with no bias.
Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
 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
def __init__(self, config: MptConfig):
    """
    Initializes an instance of the MptAttention class.

    Args:
        self: The object instance.
        config (MptConfig):
            An object of type MptConfig that contains the configuration parameters for the MptAttention.

    Returns:
        None

    Raises:
        None

    Description:
        This method is used to initialize the MptAttention class. It sets various attributes of the class instance
        based on the provided configuration.

        The 'self' parameter refers to the object instance itself. It is automatically passed when calling the method.

        The 'config' parameter is an instance of the MptConfig class which contains the following attributes:

        - hidden_size (int): The size of the hidden state.
        - n_heads (int): The number of attention heads.
        - max_seq_length (int): The maximum sequence length.
        - attn_config (AttnConfig): An object of type AttnConfig that contains attention configuration parameters.

            - softmax_scale (float): The scale factor for the softmax function.
            If not provided, it is set to 1 / sqrt(hidden_size / n_heads).
            - attn_pdrop (float): The dropout probability for attention weights.

        The method performs the following steps:

        1. Calls the __init__ method of the parent class using the 'super()' function.
        2. Sets the 'hidden_size', 'n_heads', 'max_seq_length', and 'head_dim' attributes based on the values
        from the 'config' parameter.
        3. Sets the 'softmax_scale' attribute based on the 'softmax_scale' attribute of the 'attn_config' attribute
        from the 'config' parameter. If not provided, it is calculated as 1 / sqrt(hidden_size / n_heads).
        4. Sets the 'attn_dropout_p' attribute based on the 'attn_pdrop' attribute of the 'attn_config' attribute
        from the 'config' parameter.
        5. Initializes the 'Wqkv' attribute as a dense layer with input size 'hidden_size' and output size
        '3 * hidden_size', with no bias.
        6. Initializes the 'out_proj' attribute as a dense layer with input size 'hidden_size' and output size
        'hidden_size', with no bias.
    """
    super().__init__()
    self.hidden_size = config.hidden_size
    self.n_heads = config.n_heads
    self.max_seq_length = config.max_seq_len
    self.head_dim = self.hidden_size // self.n_heads
    self.softmax_scale = config.attn_config.softmax_scale
    if self.softmax_scale is None:
        self.softmax_scale = 1 / math.sqrt(self.hidden_size / self.n_heads)

    self.attn_dropout_p = config.attn_config.attn_pdrop
    self.Wqkv = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
    self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)

mindnlp.transformers.models.mpt.modeling_mpt.MptAttention.forward(hidden_states, position_bias, past_key_value=None, attention_mask=None)

Constructs the attention mechanism.

PARAMETER DESCRIPTION
self

The instance of the MptAttention class.

TYPE: MptAttention

hidden_states

The input tensor of shape (batch_size, seq_length, hidden_size) representing the hidden states.

TYPE: Tensor

position_bias

The input tensor of shape (batch_size, seq_length, seq_length) representing the position bias.

TYPE: Tensor

past_key_value

The optional tuple of past key-value states. Default is None.

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

attention_mask

The optional input tensor of shape (batch_size, seq_length) representing the attention mask. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

RETURNS DESCRIPTION

Tuple[mindspore.Tensor, mindspore.Tensor, Tuple[mindspore.Tensor]]: A tuple containing the attention output tensor of shape (batch_size, seq_length, hidden_size), the attention weights tensor of shape (batch_size, num_heads, seq_length, seq_length), and the updated past key-value states tuple.

RAISES DESCRIPTION
ValueError

If the position_bias tensor does not have 3 dimensions.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def forward(
    self,
    hidden_states: mindspore.Tensor,
    position_bias: mindspore.Tensor,
    past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
):
    """
    Constructs the attention mechanism.

    Args:
        self (MptAttention): The instance of the MptAttention class.
        hidden_states (mindspore.Tensor): The input tensor of shape (batch_size, seq_length, hidden_size)
            representing the hidden states.
        position_bias (mindspore.Tensor): The input tensor of shape (batch_size, seq_length, seq_length)
            representing the position bias.
        past_key_value (Optional[Tuple[mindspore.Tensor]]): The optional tuple of past key-value states.
            Default is None.
        attention_mask (Optional[mindspore.Tensor]): The optional input tensor of shape (batch_size, seq_length)
            representing the attention mask. Default is None.

    Returns:
        Tuple[mindspore.Tensor, mindspore.Tensor, Tuple[mindspore.Tensor]]: A tuple containing the attention
            output tensor of shape (batch_size, seq_length, hidden_size), the attention weights tensor of
            shape (batch_size, num_heads, seq_length, seq_length), and the updated past key-value states tuple.

    Raises:
        ValueError: If the position_bias tensor does not have 3 dimensions.
    """
    batch_size, seq_length = hidden_states.shape[:2]

    mixed_qkv = self.Wqkv(hidden_states)
    query_states, key_states, value_states = mixed_qkv.chunk(3, axis=2)
    query_states = query_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).swapaxes(1, 2)
    key_states = key_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).swapaxes(1, 2)
    value_states = value_states.reshape(batch_size, seq_length, self.n_heads, self.head_dim).swapaxes(1, 2)

    if past_key_value is not None:
        if len(past_key_value) != 0:
            key_states = ops.cat([past_key_value[0], key_states], axis=2)
            value_states = ops.cat([past_key_value[1], value_states], axis=2)
        past_key_value = (key_states, value_states)
    else:
        past_key_value = (key_states, value_states)

    attention_scores = ops.matmul(query_states, key_states.swapaxes(-1, -2)) * self.softmax_scale

    query_length = seq_length if past_key_value is None else seq_length + past_key_value[0].shape[2]

    if position_bias is not None:
        if len(position_bias.shape) != 3:
            raise ValueError(f"Expecting position_bias shape to be 3 dimensions, got {len(position_bias.shape)}")
        key_length = key_states.shape[-2]

        position_bias_query_index = max(0, position_bias.shape[1] - query_length)
        position_bias_key_index = max(0, position_bias.shape[2] - key_length)

        position_bias = position_bias[:, position_bias_query_index:, position_bias_key_index:]

        attention_scores = attention_scores + position_bias

    if attention_mask is not None:
        attention_scores = attention_scores.masked_fill(attention_mask, finfo(query_states.dtype, 'min'))

    # (batch_size, n_heads, seq_length, key_length)
    attn_weights = ops.softmax(attention_scores.float(), axis=-1).to(dtype=value_states.dtype)
    attn_weights = ops.dropout(attn_weights, p=self.attn_dropout_p, training=self.training)

    context_states = ops.matmul(attn_weights, value_states)
    context_states = context_states.permute(0, 2, 1, 3).view(batch_size, seq_length, -1)
    attn_output = self.out_proj(context_states)

    return attn_output, attn_weights, past_key_value

mindnlp.transformers.models.mpt.modeling_mpt.MptBlock

Bases: Module

MptBlock represents a block within a Multi-Head Transformer model. This block consists of layers for self-attention and feed-forward networks. Inherits from nn.Module.

ATTRIBUTE DESCRIPTION
config

MptConfig object containing configuration parameters for the block.

METHOD DESCRIPTION
__init__

Initializes the MptBlock with the provided configuration.

forward

Constructs the block by applying self-attention and feed-forward operations on the input hidden states.

Example
>>> config = MptConfig(...)
>>> block = MptBlock(config)
>>> outputs = block.forward(hidden_states, position_bias, attention_mask)
Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
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
class MptBlock(nn.Module):

    """
    MptBlock represents a block within a Multi-Head Transformer model. This block consists of layers for
    self-attention and feed-forward networks. Inherits from nn.Module.

    Attributes:
        config: MptConfig object containing configuration parameters for the block.

    Methods:
        __init__: Initializes the MptBlock with the provided configuration.
        forward: Constructs the block by applying self-attention and feed-forward operations on the input hidden states.

    Example:
        ```python
        >>> config = MptConfig(...)
        >>> block = MptBlock(config)
        >>> outputs = block.forward(hidden_states, position_bias, attention_mask)
        ```
    """
    def __init__(self, config: MptConfig):
        """
        Initializes an instance of the MptBlock class.

        Args:
            self: The object itself.
            config (MptConfig): An instance of the MptConfig class representing the configuration settings.

        Returns:
            None

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

        self.norm_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon, elementwise_affine=False)
        # backward compatibility with weights on the Hub
        self.norm_1.bias = None

        self.num_heads = config.n_heads
        self.attn = MptAttention(config)

        self.norm_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon, elementwise_affine=False)
        # backward compatibility with weights on the Hub
        self.norm_2.bias = None

        self.ffn = MptMLP(config)

        self.dropout_rate = config.attn_config.attn_pdrop
        self.resid_attn_dropout = nn.Dropout(p=self.dropout_rate)

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        position_bias: mindspore.Tensor,
        attention_mask: mindspore.Tensor,
        layer_past: Optional[Tuple[mindspore.Tensor, mindspore.Tensor]] = None,
        use_cache: bool = False,
        output_attentions: bool = False,
    ):
        """
        This method forwards a multi-head self-attention block within the MptBlock class.

        Args:
            self: The instance of the class.
            hidden_states (mindspore.Tensor): The input tensor representing the hidden states.
            position_bias (mindspore.Tensor): The tensor containing positional bias information.
            attention_mask (mindspore.Tensor): The tensor used for masking the attention scores.
            layer_past (Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]):
                A tuple containing the past key and value tensors, default is None.
            use_cache (bool): A boolean flag indicating whether to use caching, default is False.
            output_attentions (bool): A boolean flag indicating whether to output attention weights, default is False.

        Returns:
            tuple:
                A tuple containing the output tensor of the multi-head self-attention block.

                - If 'use_cache' is True, the tuple also includes the past key and value tensors.
                - If 'output_attentions' is True, the tuple additionally includes the attention weights tensor.

        Raises:
            None
        """
        # hidden_states: [batch_size, seq_length, hidden_size]
        # Layer norm at the beginning of the transformer layer.
        layernorm_output = self.norm_1(hidden_states)

        residual = hidden_states

        # Self attention.
        attn_outputs, attn_weights, past_key_value = self.attn(
            layernorm_output,
            position_bias=position_bias,
            attention_mask=attention_mask,
            past_key_value=layer_past,
        )

        hidden_states = self.resid_attn_dropout(attn_outputs) + residual

        layernorm_output = self.norm_2(hidden_states)

        # Get residual
        residual = hidden_states

        # MLP.
        output = self.ffn(layernorm_output, residual)
        outputs = (output,)

        if use_cache:
            outputs += (past_key_value,)

        if output_attentions:
            outputs += (attn_weights,)

        return outputs  # hidden_states, present, attentions

mindnlp.transformers.models.mpt.modeling_mpt.MptBlock.__init__(config)

Initializes an instance of the MptBlock class.

PARAMETER DESCRIPTION
self

The object itself.

config

An instance of the MptConfig class representing the configuration settings.

TYPE: MptConfig

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def __init__(self, config: MptConfig):
    """
    Initializes an instance of the MptBlock class.

    Args:
        self: The object itself.
        config (MptConfig): An instance of the MptConfig class representing the configuration settings.

    Returns:
        None

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

    self.norm_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon, elementwise_affine=False)
    # backward compatibility with weights on the Hub
    self.norm_1.bias = None

    self.num_heads = config.n_heads
    self.attn = MptAttention(config)

    self.norm_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon, elementwise_affine=False)
    # backward compatibility with weights on the Hub
    self.norm_2.bias = None

    self.ffn = MptMLP(config)

    self.dropout_rate = config.attn_config.attn_pdrop
    self.resid_attn_dropout = nn.Dropout(p=self.dropout_rate)

mindnlp.transformers.models.mpt.modeling_mpt.MptBlock.forward(hidden_states, position_bias, attention_mask, layer_past=None, use_cache=False, output_attentions=False)

This method forwards a multi-head self-attention block within the MptBlock class.

PARAMETER DESCRIPTION
self

The instance of the class.

hidden_states

The input tensor representing the hidden states.

TYPE: Tensor

position_bias

The tensor containing positional bias information.

TYPE: Tensor

attention_mask

The tensor used for masking the attention scores.

TYPE: Tensor

layer_past

A tuple containing the past key and value tensors, default is None.

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

use_cache

A boolean flag indicating whether to use caching, default is False.

TYPE: bool DEFAULT: False

output_attentions

A boolean flag indicating whether to output attention weights, default is False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple

A tuple containing the output tensor of the multi-head self-attention block.

  • If 'use_cache' is True, the tuple also includes the past key and value tensors.
  • If 'output_attentions' is True, the tuple additionally includes the attention weights tensor.
Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def forward(
    self,
    hidden_states: mindspore.Tensor,
    position_bias: mindspore.Tensor,
    attention_mask: mindspore.Tensor,
    layer_past: Optional[Tuple[mindspore.Tensor, mindspore.Tensor]] = None,
    use_cache: bool = False,
    output_attentions: bool = False,
):
    """
    This method forwards a multi-head self-attention block within the MptBlock class.

    Args:
        self: The instance of the class.
        hidden_states (mindspore.Tensor): The input tensor representing the hidden states.
        position_bias (mindspore.Tensor): The tensor containing positional bias information.
        attention_mask (mindspore.Tensor): The tensor used for masking the attention scores.
        layer_past (Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]):
            A tuple containing the past key and value tensors, default is None.
        use_cache (bool): A boolean flag indicating whether to use caching, default is False.
        output_attentions (bool): A boolean flag indicating whether to output attention weights, default is False.

    Returns:
        tuple:
            A tuple containing the output tensor of the multi-head self-attention block.

            - If 'use_cache' is True, the tuple also includes the past key and value tensors.
            - If 'output_attentions' is True, the tuple additionally includes the attention weights tensor.

    Raises:
        None
    """
    # hidden_states: [batch_size, seq_length, hidden_size]
    # Layer norm at the beginning of the transformer layer.
    layernorm_output = self.norm_1(hidden_states)

    residual = hidden_states

    # Self attention.
    attn_outputs, attn_weights, past_key_value = self.attn(
        layernorm_output,
        position_bias=position_bias,
        attention_mask=attention_mask,
        past_key_value=layer_past,
    )

    hidden_states = self.resid_attn_dropout(attn_outputs) + residual

    layernorm_output = self.norm_2(hidden_states)

    # Get residual
    residual = hidden_states

    # MLP.
    output = self.ffn(layernorm_output, residual)
    outputs = (output,)

    if use_cache:
        outputs += (past_key_value,)

    if output_attentions:
        outputs += (attn_weights,)

    return outputs  # hidden_states, present, attentions

mindnlp.transformers.models.mpt.modeling_mpt.MptForCausalLM

Bases: MptPreTrainedModel

This class represents a model for Causal Language Modeling based on the Mpt architecture. It provides methods for preparing inputs, generating outputs, and reordering cache for beam search.

The class includes methods such as initializing the model, getting and setting output embeddings, preparing inputs for generation, forwarding the model, and reordering cache for beam search.

The 'MptForCausalLM' class inherits from 'MptPreTrainedModel' and utilizes a transformer model along with specific configurations for language modeling tasks.

Key methods:

  • init: Initialize the model with the provided configuration.
  • get_output_embeddings: Get the output embeddings of the model.
  • set_output_embeddings: Set new output embeddings for the model.
  • prepare_inputs_for_generation: Prepare inputs for text generation.
  • forward: Construct the model for language modeling.
  • _reorder_cache: Reorder the cache for beam search operations.

The 'MptForCausalLM' class is designed to facilitate language modeling tasks with a focus on generating coherent text sequences in a causal manner.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
class MptForCausalLM(MptPreTrainedModel):

    """
    This class represents a model for Causal Language Modeling based on the Mpt architecture.
    It provides methods for preparing inputs, generating outputs, and reordering cache for beam search.

    The class includes methods such as initializing the model, getting and setting output embeddings, preparing inputs
    for generation, forwarding the model, and reordering cache for beam search.

    The 'MptForCausalLM' class inherits from 'MptPreTrainedModel' and utilizes a transformer model along with
    specific configurations for language modeling tasks.

    Key methods:

    - __init__: Initialize the model with the provided configuration.
    - get_output_embeddings: Get the output embeddings of the model.
    - set_output_embeddings: Set new output embeddings for the model.
    - prepare_inputs_for_generation: Prepare inputs for text generation.
    - forward: Construct the model for language modeling.
    - _reorder_cache: Reorder the cache for beam search operations.

    The 'MptForCausalLM' class is designed to facilitate language modeling tasks with a focus on generating coherent
    text sequences in a causal manner.
    """
    _tied_weights_keys = ["lm_head.weight"]

    def __init__(self, config: MptConfig):
        """
        Initializes an instance of the MptForCausalLM class.

        Args:
            self: The instance of the MptForCausalLM class.
            config (MptConfig): An instance of the MptConfig class containing configuration parameters.
                This parameter is required for initializing various components within the MptForCausalLM instance.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type MptConfig.
            ValueError: If any required configuration parameter is missing or invalid.
        """
        super().__init__(config)
        self.transformer = MptModel(config)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

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

    def get_output_embeddings(self):
        """
        Returns the output embeddings for the MptForCausalLM model.

        Args:
            self: An instance of the MptForCausalLM class.

        Returns:
            embeddings: The output embeddings which are stored in the `lm_head` attribute of the MptForCausalLM instance.

        Raises:
            None.

        This method retrieves and returns the output embeddings of the MptForCausalLM model.
        The output embeddings are stored in the `lm_head` attribute of the instance.
        The `lm_head` attribute represents the final layer of the language model, responsible for generating the
        output predictions.

        Note that the output embeddings are specific to the MptForCausalLM model and are derived from the language
        model's internal representation. The embeddings capture the semantic meaning and contextual information of the
        input text, enabling downstream tasks such as text generation, completion, or classification.

        Example:
            ```python
            >>> model = MptForCausalLM()
            >>> output_embeddings = model.get_output_embeddings()
            ```
        """
        return self.lm_head

    def set_output_embeddings(self, new_embeddings: mindspore.Tensor):
        """
        Method to set new output embeddings for the language model.

        Args:
            self (MptForCausalLM): The instance of the MptForCausalLM class.
            new_embeddings (mindspore.Tensor): The new embeddings to be set as the output embeddings for the language model.
                It should be a Tensor object containing the embeddings to be used for the output layer.

        Returns:
            None:
                This method updates the 'lm_head' attribute of the MptForCausalLM instance with the new embeddings
                provided.

        Raises:
            None.
        """
        self.lm_head = new_embeddings

    def prepare_inputs_for_generation(
        self,
        input_ids: mindspore.Tensor,
        past_key_values: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        **kwargs,
    ) -> dict:
        """
        Prepares inputs for generation in the MptForCausalLM class.

        Args:
            self: The object instance.
            input_ids (mindspore.Tensor): The input tensor containing the tokenized input sequence.
            past_key_values (Optional[mindspore.Tensor]): The tensor containing the past key values for
                auto-regressive generation. Default is None.
            attention_mask (Optional[mindspore.Tensor]): The tensor specifying which tokens should be attended to.
                Default is None.
            inputs_embeds (Optional[mindspore.Tensor]): The tensor containing the embeddings of the input sequence.
                Default is None.
            use_cache (Optional[bool]): Specifies whether to use cache for faster generation. Default is None.
            **kwargs: Additional keyword arguments.

        Returns:
            dict: A dictionary containing the prepared model inputs, including 'input_ids', 'inputs_embeds',
                'past_key_values', 'use_cache', and 'attention_mask'.

        Raises:
            None.
        """
        # only last tokens for input_ids if past is not None
        if past_key_values is not None:
            past_length = past_key_values[0][0].shape[2]

            # Some generation methods already pass only the last input ID
            if input_ids.shape[1] > past_length:
                remove_prefix_length = past_length
            else:
                # Default to old behavior: keep only final ID
                remove_prefix_length = input_ids.shape[1] - 1

            input_ids = input_ids[:, remove_prefix_length:]

        # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
        if inputs_embeds is not None and past_key_values is None:
            model_inputs = {"inputs_embeds": inputs_embeds}
        else:
            model_inputs = {"input_ids": input_ids}

        model_inputs.update(
            {
                "past_key_values": past_key_values,  # NITS should it be layer_past?
                "use_cache": use_cache,
                "attention_mask": attention_mask,
            }
        )
        return model_inputs

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[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], CausalLMOutputWithCrossAttentions]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
                `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
                are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        transformer_outputs = self.transformer(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        hidden_states = transformer_outputs[0]

        lm_logits = self.lm_head(hidden_states)

        loss = None
        if labels is not None:
            # Shift so that tokens < n predict n
            shift_logits = lm_logits[..., :-1, :]
            shift_labels = labels[..., 1:]
            batch_size, seq_length, vocab_size = shift_logits.shape
            # Flatten the tokens
            loss = ops.cross_entropy(
                shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
            )

        if not return_dict:
            output = (lm_logits,) + transformer_outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return CausalLMOutputWithCrossAttentions(
            loss=loss,
            logits=lm_logits,
            past_key_values=transformer_outputs.past_key_values,
            hidden_states=transformer_outputs.hidden_states,
            attentions=transformer_outputs.attentions,
        )

    def _reorder_cache(
        self, past: Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...], beam_idx: mindspore.Tensor
    ) -> Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]:
        """
        This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
        [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
        beam_idx at every generation step.

        Output shares the same memory storage as `past`.
        """
        # Get a copy of `beam_idx` on all the devices where we need those indices.
        reordered_past = tuple(
            (
                layer_past[0].index_select(0, beam_idx),
                layer_past[1].index_select(0, beam_idx),
            )
            for layer_past in past
        )

        return reordered_past

mindnlp.transformers.models.mpt.modeling_mpt.MptForCausalLM.__init__(config)

Initializes an instance of the MptForCausalLM class.

PARAMETER DESCRIPTION
self

The instance of the MptForCausalLM class.

config

An instance of the MptConfig class containing configuration parameters. This parameter is required for initializing various components within the MptForCausalLM instance.

TYPE: MptConfig

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type MptConfig.

ValueError

If any required configuration parameter is missing or invalid.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def __init__(self, config: MptConfig):
    """
    Initializes an instance of the MptForCausalLM class.

    Args:
        self: The instance of the MptForCausalLM class.
        config (MptConfig): An instance of the MptConfig class containing configuration parameters.
            This parameter is required for initializing various components within the MptForCausalLM instance.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type MptConfig.
        ValueError: If any required configuration parameter is missing or invalid.
    """
    super().__init__(config)
    self.transformer = MptModel(config)
    self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

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

mindnlp.transformers.models.mpt.modeling_mpt.MptForCausalLM.forward(input_ids=None, past_key_values=None, attention_mask=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set labels = input_ids Indices are selected in [-100, 0, ..., config.vocab_size] All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size]

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

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[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], CausalLMOutputWithCrossAttentions]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    transformer_outputs = self.transformer(
        input_ids,
        past_key_values=past_key_values,
        attention_mask=attention_mask,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    hidden_states = transformer_outputs[0]

    lm_logits = self.lm_head(hidden_states)

    loss = None
    if labels is not None:
        # Shift so that tokens < n predict n
        shift_logits = lm_logits[..., :-1, :]
        shift_labels = labels[..., 1:]
        batch_size, seq_length, vocab_size = shift_logits.shape
        # Flatten the tokens
        loss = ops.cross_entropy(
            shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
        )

    if not return_dict:
        output = (lm_logits,) + transformer_outputs[1:]
        return ((loss,) + output) if loss is not None else output

    return CausalLMOutputWithCrossAttentions(
        loss=loss,
        logits=lm_logits,
        past_key_values=transformer_outputs.past_key_values,
        hidden_states=transformer_outputs.hidden_states,
        attentions=transformer_outputs.attentions,
    )

mindnlp.transformers.models.mpt.modeling_mpt.MptForCausalLM.get_output_embeddings()

Returns the output embeddings for the MptForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the MptForCausalLM class.

RETURNS DESCRIPTION
embeddings

The output embeddings which are stored in the lm_head attribute of the MptForCausalLM instance.

This method retrieves and returns the output embeddings of the MptForCausalLM model. The output embeddings are stored in the lm_head attribute of the instance. The lm_head attribute represents the final layer of the language model, responsible for generating the output predictions.

Note that the output embeddings are specific to the MptForCausalLM model and are derived from the language model's internal representation. The embeddings capture the semantic meaning and contextual information of the input text, enabling downstream tasks such as text generation, completion, or classification.

Example
>>> model = MptForCausalLM()
>>> output_embeddings = model.get_output_embeddings()
Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def get_output_embeddings(self):
    """
    Returns the output embeddings for the MptForCausalLM model.

    Args:
        self: An instance of the MptForCausalLM class.

    Returns:
        embeddings: The output embeddings which are stored in the `lm_head` attribute of the MptForCausalLM instance.

    Raises:
        None.

    This method retrieves and returns the output embeddings of the MptForCausalLM model.
    The output embeddings are stored in the `lm_head` attribute of the instance.
    The `lm_head` attribute represents the final layer of the language model, responsible for generating the
    output predictions.

    Note that the output embeddings are specific to the MptForCausalLM model and are derived from the language
    model's internal representation. The embeddings capture the semantic meaning and contextual information of the
    input text, enabling downstream tasks such as text generation, completion, or classification.

    Example:
        ```python
        >>> model = MptForCausalLM()
        >>> output_embeddings = model.get_output_embeddings()
        ```
    """
    return self.lm_head

mindnlp.transformers.models.mpt.modeling_mpt.MptForCausalLM.prepare_inputs_for_generation(input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, use_cache=None, **kwargs)

Prepares inputs for generation in the MptForCausalLM class.

PARAMETER DESCRIPTION
self

The object instance.

input_ids

The input tensor containing the tokenized input sequence.

TYPE: Tensor

past_key_values

The tensor containing the past key values for auto-regressive generation. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The tensor specifying which tokens should be attended to. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The tensor containing the embeddings of the input sequence. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

use_cache

Specifies whether to use cache for faster generation. Default is None.

TYPE: Optional[bool] DEFAULT: None

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION
dict

A dictionary containing the prepared model inputs, including 'input_ids', 'inputs_embeds', 'past_key_values', 'use_cache', and 'attention_mask'.

TYPE: dict

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def prepare_inputs_for_generation(
    self,
    input_ids: mindspore.Tensor,
    past_key_values: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    **kwargs,
) -> dict:
    """
    Prepares inputs for generation in the MptForCausalLM class.

    Args:
        self: The object instance.
        input_ids (mindspore.Tensor): The input tensor containing the tokenized input sequence.
        past_key_values (Optional[mindspore.Tensor]): The tensor containing the past key values for
            auto-regressive generation. Default is None.
        attention_mask (Optional[mindspore.Tensor]): The tensor specifying which tokens should be attended to.
            Default is None.
        inputs_embeds (Optional[mindspore.Tensor]): The tensor containing the embeddings of the input sequence.
            Default is None.
        use_cache (Optional[bool]): Specifies whether to use cache for faster generation. Default is None.
        **kwargs: Additional keyword arguments.

    Returns:
        dict: A dictionary containing the prepared model inputs, including 'input_ids', 'inputs_embeds',
            'past_key_values', 'use_cache', and 'attention_mask'.

    Raises:
        None.
    """
    # only last tokens for input_ids if past is not None
    if past_key_values is not None:
        past_length = past_key_values[0][0].shape[2]

        # Some generation methods already pass only the last input ID
        if input_ids.shape[1] > past_length:
            remove_prefix_length = past_length
        else:
            # Default to old behavior: keep only final ID
            remove_prefix_length = input_ids.shape[1] - 1

        input_ids = input_ids[:, remove_prefix_length:]

    # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
    if inputs_embeds is not None and past_key_values is None:
        model_inputs = {"inputs_embeds": inputs_embeds}
    else:
        model_inputs = {"input_ids": input_ids}

    model_inputs.update(
        {
            "past_key_values": past_key_values,  # NITS should it be layer_past?
            "use_cache": use_cache,
            "attention_mask": attention_mask,
        }
    )
    return model_inputs

mindnlp.transformers.models.mpt.modeling_mpt.MptForCausalLM.set_output_embeddings(new_embeddings)

Method to set new output embeddings for the language model.

PARAMETER DESCRIPTION
self

The instance of the MptForCausalLM class.

TYPE: MptForCausalLM

new_embeddings

The new embeddings to be set as the output embeddings for the language model. It should be a Tensor object containing the embeddings to be used for the output layer.

TYPE: Tensor

RETURNS DESCRIPTION
None

This method updates the 'lm_head' attribute of the MptForCausalLM instance with the new embeddings provided.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def set_output_embeddings(self, new_embeddings: mindspore.Tensor):
    """
    Method to set new output embeddings for the language model.

    Args:
        self (MptForCausalLM): The instance of the MptForCausalLM class.
        new_embeddings (mindspore.Tensor): The new embeddings to be set as the output embeddings for the language model.
            It should be a Tensor object containing the embeddings to be used for the output layer.

    Returns:
        None:
            This method updates the 'lm_head' attribute of the MptForCausalLM instance with the new embeddings
            provided.

    Raises:
        None.
    """
    self.lm_head = new_embeddings

mindnlp.transformers.models.mpt.modeling_mpt.MptForQuestionAnswering

Bases: MptPreTrainedModel

MptForQuestionAnswering is a class representing a model for question answering. It inherits from MptPreTrainedModel and provides methods for forwarding a question answering model.

The class includes an initializer method that takes a 'config' parameter and initializes the transformer and qa_outputs attributes. It also provides a 'forward' method for forwarding the question answering model, which takes input_ids, attention_mask, inputs_embeds, start_positions, end_positions, output_attentions, output_hidden_states, and return_dict as optional parameters and returns a QuestionAnsweringModelOutput.

The 'forward' method computes the start and end positions for the labelled span, computes the token classification loss, and returns the total loss along with start_logits, end_logits, hidden_states, and attentions if return_dict is False. If return_dict is True, it returns a QuestionAnsweringModelOutput containing the loss, start_logits, end_logits, hidden_states, and attentions.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
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
class MptForQuestionAnswering(MptPreTrainedModel):

    """
    MptForQuestionAnswering is a class representing a model for question answering. It inherits from MptPreTrainedModel
    and provides methods for forwarding a question answering model.

    The class includes an initializer method that takes a 'config' parameter and initializes the transformer and
    qa_outputs attributes. It also provides a 'forward' method for forwarding the question answering model,
    which takes input_ids, attention_mask, inputs_embeds, start_positions, end_positions, output_attentions,
    output_hidden_states, and return_dict as optional parameters and returns a QuestionAnsweringModelOutput.

    The 'forward' method computes the start and end positions for the labelled span, computes the token classification
    loss, and returns the total loss along with start_logits, end_logits, hidden_states, and attentions if return_dict
    is False. If return_dict is True, it returns a QuestionAnsweringModelOutput containing the loss, start_logits,
    end_logits, hidden_states, and attentions.

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

        Args:
            self (MptForQuestionAnswering): The instance itself.
            config: A dictionary containing configuration parameters for the model.

        Returns:
            None.

        Raises:
            None
        """
        super().__init__(config)
        self.transformer = MptModel(config)
        self.qa_outputs = nn.Linear(config.hidden_size, 2)

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        start_positions: Optional[mindspore.Tensor] = None,
        end_positions: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, QuestionAnsweringModelOutput]:
        r"""
        Args:
            start_positions (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for position (index) of the start of the labelled span for computing the token classification loss.
                Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
                are not taken into account for computing the loss.
            end_positions (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for position (index) of the end of the labelled span for computing the token classification loss.
                Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
                are not taken into account for computing the loss.
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.transformer(
            input_ids,
            attention_mask=attention_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.qa_outputs(sequence_output)
        start_logits, end_logits = logits.split(1, axis=-1)
        start_logits = start_logits.squeeze(-1)
        end_logits = end_logits.squeeze(-1)

        total_loss = None
        if start_positions is not None and end_positions is not None:
            # If we are on multi-GPU, split add a dimension
            if len(start_positions.shape) > 1:
                start_positions = start_positions.squeeze(-1)
            if len(end_positions.shape) > 1:
                end_positions = end_positions.squeeze(-1)
            # sometimes the start/end positions are outside our model inputs, we ignore these terms
            ignored_index = start_logits.shape[1]
            start_positions = start_positions.clamp(0, ignored_index)
            end_positions = end_positions.clamp(0, ignored_index)

            start_loss =ops.cross_entropy(start_logits,start_positions, ignore_index=ignored_index)
            end_loss = ops.cross_entropy(end_logits, end_positions,ignore_index=ignored_index)
            total_loss = (start_loss + end_loss) / 2

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

        return QuestionAnsweringModelOutput(
            loss=total_loss,
            start_logits=start_logits,
            end_logits=end_logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

mindnlp.transformers.models.mpt.modeling_mpt.MptForQuestionAnswering.__init__(config)

Initializes an instance of MptForQuestionAnswering class.

PARAMETER DESCRIPTION
self

The instance itself.

TYPE: MptForQuestionAnswering

config

A dictionary containing configuration parameters for the model.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
def __init__(self, config):
    """
    Initializes an instance of MptForQuestionAnswering class.

    Args:
        self (MptForQuestionAnswering): The instance itself.
        config: A dictionary containing configuration parameters for the model.

    Returns:
        None.

    Raises:
        None
    """
    super().__init__(config)
    self.transformer = MptModel(config)
    self.qa_outputs = nn.Linear(config.hidden_size, 2)

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

mindnlp.transformers.models.mpt.modeling_mpt.MptForQuestionAnswering.forward(input_ids=None, attention_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
start_positions

Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

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

end_positions

Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

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

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    start_positions: Optional[mindspore.Tensor] = None,
    end_positions: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, QuestionAnsweringModelOutput]:
    r"""
    Args:
        start_positions (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.transformer(
        input_ids,
        attention_mask=attention_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.qa_outputs(sequence_output)
    start_logits, end_logits = logits.split(1, axis=-1)
    start_logits = start_logits.squeeze(-1)
    end_logits = end_logits.squeeze(-1)

    total_loss = None
    if start_positions is not None and end_positions is not None:
        # If we are on multi-GPU, split add a dimension
        if len(start_positions.shape) > 1:
            start_positions = start_positions.squeeze(-1)
        if len(end_positions.shape) > 1:
            end_positions = end_positions.squeeze(-1)
        # sometimes the start/end positions are outside our model inputs, we ignore these terms
        ignored_index = start_logits.shape[1]
        start_positions = start_positions.clamp(0, ignored_index)
        end_positions = end_positions.clamp(0, ignored_index)

        start_loss =ops.cross_entropy(start_logits,start_positions, ignore_index=ignored_index)
        end_loss = ops.cross_entropy(end_logits, end_positions,ignore_index=ignored_index)
        total_loss = (start_loss + end_loss) / 2

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

    return QuestionAnsweringModelOutput(
        loss=total_loss,
        start_logits=start_logits,
        end_logits=end_logits,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
    )

mindnlp.transformers.models.mpt.modeling_mpt.MptForSequenceClassification

Bases: MptPreTrainedModel

This class represents a sequence classification model based on the MptPreTrainedModel architecture.

The MptForSequenceClassification class is a subclass of MptPreTrainedModel and is designed for sequence classification tasks. It includes methods for initializing the model, forwarding the model, and generating sequence classification outputs.

ATTRIBUTE DESCRIPTION
num_labels

The number of labels for the sequence classification task.

TYPE: int

transformer

The transformer model used for sequence encoding.

TYPE: MptModel

score

The linear layer for generating logits from the hidden states.

TYPE: Linear

METHOD DESCRIPTION
__init__

Initializes the MptForSequenceClassification instance with a configuration object.

forward

Constructs the sequence classification model and returns the classification outputs.

The MptForSequenceClassification class inherits from the MptPreTrainedModel class and extends its functionality specifically for sequence classification tasks. It utilizes a transformer model for encoding the input sequences and a linear layer for generating logits from the hidden states. The class provides a method for forwarding the model and returning the classification outputs.

Note

This class assumes that the input sequences are tokenized and encoded as input_ids, and the labels are provided for computing the sequence classification/regression loss. The number of labels should be in the range of [0, config.num_labels - 1]. If config.num_labels == 1, a regression loss is computed using Mean-Square loss. If config.num_labels > 1, a classification loss is computed using Cross-Entropy.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
 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
1035
1036
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
class MptForSequenceClassification(MptPreTrainedModel):

    """
    This class represents a sequence classification model based on the MptPreTrainedModel architecture.

    The MptForSequenceClassification class is a subclass of MptPreTrainedModel and is designed for sequence 
    classification tasks. It includes methods for initializing the model, forwarding the model, and
    generating sequence classification outputs.

    Attributes:
        num_labels (int): The number of labels for the sequence classification task.
        transformer (MptModel): The transformer model used for sequence encoding.
        score (nn.Linear): The linear layer for generating logits from the hidden states.

    Methods:
        __init__: Initializes the MptForSequenceClassification instance with a configuration object.
        forward: Constructs the sequence classification model and returns the classification outputs.

    The MptForSequenceClassification class inherits from the MptPreTrainedModel class and extends its functionality 
    specifically for sequence classification tasks. It utilizes a transformer model for encoding the input sequences 
    and a linear layer for generating logits from the hidden states. The class provides a method for forwarding the 
    model and returning the classification outputs.

    Note:
        This class assumes that the input sequences are tokenized and encoded as input_ids, and the labels are 
        provided for computing the sequence classification/regression loss. The number of labels should be in the range 
        of [0, config.num_labels - 1]. If config.num_labels == 1, a regression loss is computed using Mean-Square loss. 
        If config.num_labels > 1, a classification loss is computed using Cross-Entropy.
    """
    def __init__(self, config: MptConfig):
        """
        Initializes an instance of MptForSequenceClassification.

        Args:
            self: The instance of the class.
            config (MptConfig): An instance of MptConfig containing configuration parameters.
                It specifies the configuration settings for the model.
                Must be of type MptConfig.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.transformer = MptModel(config)
        self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[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], SequenceClassifierOutputWithPast]:
        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

        transformer_outputs = self.transformer(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        hidden_states = transformer_outputs[0]
        logits = self.score(hidden_states)

        if input_ids is not None:
            batch_size = input_ids.shape[0]
        else:
            batch_size = inputs_embeds.shape[0]

        if self.config.pad_token_id is None and batch_size != 1:
            raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
        if self.config.pad_token_id is None:
            sequence_lengths = -1
        else:
            if input_ids is not None:
                # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
                sequence_lengths = ops.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
                sequence_lengths = sequence_lengths % input_ids.shape[-1]
            else:
                sequence_lengths = -1
                logger.warning(
                    f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
                    "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
                )

        pooled_logits = logits[ops.arange(batch_size), sequence_lengths]

        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.long64, 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 = ops.mse_loss(pooled_logits.squeeze(), labels.squeeze())
                else:
                    loss = ops.mse_loss(pooled_logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss = ops.cross_entropy(pooled_logits, labels)
            elif self.config.problem_type == "multi_label_classification":
                loss = ops.binary_cross_entropy_with_logits(pooled_logits, labels)
        if not return_dict:
            output = (pooled_logits,) + transformer_outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return SequenceClassifierOutputWithPast(
            loss=loss,
            logits=pooled_logits,
            past_key_values=transformer_outputs.past_key_values,
            hidden_states=transformer_outputs.hidden_states,
            attentions=transformer_outputs.attentions,
        )

mindnlp.transformers.models.mpt.modeling_mpt.MptForSequenceClassification.__init__(config)

Initializes an instance of MptForSequenceClassification.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An instance of MptConfig containing configuration parameters. It specifies the configuration settings for the model. Must be of type MptConfig.

TYPE: MptConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
def __init__(self, config: MptConfig):
    """
    Initializes an instance of MptForSequenceClassification.

    Args:
        self: The instance of the class.
        config (MptConfig): An instance of MptConfig containing configuration parameters.
            It specifies the configuration settings for the model.
            Must be of type MptConfig.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.transformer = MptModel(config)
    self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)

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

mindnlp.transformers.models.mpt.modeling_mpt.MptForSequenceClassification.forward(input_ids=None, past_key_values=None, attention_mask=None, inputs_embeds=None, labels=None, use_cache=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/mpt/modeling_mpt.py
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[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], SequenceClassifierOutputWithPast]:
    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

    transformer_outputs = self.transformer(
        input_ids,
        past_key_values=past_key_values,
        attention_mask=attention_mask,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    hidden_states = transformer_outputs[0]
    logits = self.score(hidden_states)

    if input_ids is not None:
        batch_size = input_ids.shape[0]
    else:
        batch_size = inputs_embeds.shape[0]

    if self.config.pad_token_id is None and batch_size != 1:
        raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
    if self.config.pad_token_id is None:
        sequence_lengths = -1
    else:
        if input_ids is not None:
            # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
            sequence_lengths = ops.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
            sequence_lengths = sequence_lengths % input_ids.shape[-1]
        else:
            sequence_lengths = -1
            logger.warning(
                f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
                "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
            )

    pooled_logits = logits[ops.arange(batch_size), sequence_lengths]

    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.long64, 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 = ops.mse_loss(pooled_logits.squeeze(), labels.squeeze())
            else:
                loss = ops.mse_loss(pooled_logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss = ops.cross_entropy(pooled_logits, labels)
        elif self.config.problem_type == "multi_label_classification":
            loss = ops.binary_cross_entropy_with_logits(pooled_logits, labels)
    if not return_dict:
        output = (pooled_logits,) + transformer_outputs[1:]
        return ((loss,) + output) if loss is not None else output

    return SequenceClassifierOutputWithPast(
        loss=loss,
        logits=pooled_logits,
        past_key_values=transformer_outputs.past_key_values,
        hidden_states=transformer_outputs.hidden_states,
        attentions=transformer_outputs.attentions,
    )

mindnlp.transformers.models.mpt.modeling_mpt.MptForTokenClassification

Bases: MptPreTrainedModel

MptForTokenClassification represents a model for token classification tasks, inheriting from MptPreTrainedModel. It includes methods for initializing the model and forwarding the forward pass for token classification.

The init method initializes the model parameters and components such as the transformer and classifier layers, with optional dropout specified in the config.

The forward method processes the input data through the transformer, applies dropout, computes logits using the classifier, calculates loss if labels are provided, and returns the output in the specified format.

PARAMETER DESCRIPTION
config

Configuration object containing model settings.

TYPE: MptConfig

input_ids

Input token IDs.

TYPE: Optional[Tensor]

past_key_values

Past key values for attention mechanisms.

TYPE: Optional[Tuple[Tuple[Tensor, Tensor], ...]]

attention_mask

Mask for attention scores.

TYPE: Optional[Tensor]

inputs_embeds

Embedded input tokens.

TYPE: Optional[Tensor]

labels

Target labels for classification/regression.

TYPE: Optional[Tensor]

use_cache

Flag for using cache in the transformer.

TYPE: Optional[bool]

output_attentions

Flag for outputting attentions.

TYPE: Optional[bool]

output_hidden_states

Flag for outputting hidden states.

TYPE: Optional[bool]

return_dict

Flag for returning output as a dictionary.

TYPE: Optional[bool]

RETURNS DESCRIPTION

Union[Tuple[mindspore.Tensor], TokenClassifierOutput]: Tuple containing the loss and output based on return format.

Note
  • Labels should be indices in [0, ..., config.num_labels - 1].
  • For single label regression, config.num_labels should be 1.
  • For multiple labels classification, config.num_labels > 1.
  • Cross-entropy loss is computed for classification tasks.

For detailed information on methods and attributes, please refer to the method implementations in the class.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
1201
1202
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
class MptForTokenClassification(MptPreTrainedModel):

    """
    MptForTokenClassification represents a model for token classification tasks, inheriting from MptPreTrainedModel.
    It includes methods for initializing the model and forwarding the forward pass for token classification.

    The __init__ method initializes the model parameters and components such as the transformer and classifier layers,
    with optional dropout specified in the config.

    The forward method processes the input data through the transformer, applies dropout, computes logits using the
    classifier, calculates loss if labels are provided, and returns the output in the specified format.

    Parameters:
        config (MptConfig): Configuration object containing model settings.
        input_ids (Optional[mindspore.Tensor]): Input token IDs.
        past_key_values (Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]]):
            Past key values for attention mechanisms.
        attention_mask (Optional[mindspore.Tensor]): Mask for attention scores.
        inputs_embeds (Optional[mindspore.Tensor]): Embedded input tokens.
        labels (Optional[mindspore.Tensor]): Target labels for classification/regression.
        use_cache (Optional[bool]): Flag for using cache in the transformer.
        output_attentions (Optional[bool]): Flag for outputting attentions.
        output_hidden_states (Optional[bool]): Flag for outputting hidden states.
        return_dict (Optional[bool]): Flag for returning output as a dictionary.

    Returns:
        Union[Tuple[mindspore.Tensor], TokenClassifierOutput]:
            Tuple containing the loss and output based on return format.

    Note:
        - Labels should be indices in [0, ..., config.num_labels - 1].
        - For single label regression, config.num_labels should be 1.
        - For multiple labels classification, config.num_labels > 1.
        - Cross-entropy loss is computed for classification tasks.

    For detailed information on methods and attributes, please refer to the method implementations in the class.
    """
    def __init__(self, config: MptConfig):
        """
        Initializes an instance of the MptForTokenClassification class.

        Args:
            self: The instance of the MptForTokenClassification class.
            config (MptConfig):
                An object of type MptConfig containing configuration parameters for the model.

                - num_labels (int): The number of labels for token classification.
                - classifier_dropout (float, optional): The dropout probability for the classifier layer.
                - hidden_dropout (float, optional): The dropout probability for hidden layers.

        Returns:
            None:
                This method initializes the MptForTokenClassification instance with the provided configuration.

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

        self.transformer = MptModel(config)
        if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
            classifier_dropout = config.classifier_dropout
        elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
            classifier_dropout = config.hidden_dropout
        else:
            classifier_dropout = 0.1
        self.dropout = nn.Dropout(p=classifier_dropout)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        **deprecated_arguments,
    ) -> Union[Tuple[mindspore.Tensor], TokenClassifierOutput]:
        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

        transformer_outputs = self.transformer(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        hidden_states = transformer_outputs[0]
        hidden_states = self.dropout(hidden_states)
        logits = self.classifier(hidden_states)

        loss = None
        if labels is not None:
            batch_size, seq_length = labels.shape
            loss = ops.cross_entropy(
                logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
            )

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

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

mindnlp.transformers.models.mpt.modeling_mpt.MptForTokenClassification.__init__(config)

Initializes an instance of the MptForTokenClassification class.

PARAMETER DESCRIPTION
self

The instance of the MptForTokenClassification class.

config

An object of type MptConfig containing configuration parameters for the model.

  • num_labels (int): The number of labels for token classification.
  • classifier_dropout (float, optional): The dropout probability for the classifier layer.
  • hidden_dropout (float, optional): The dropout probability for hidden layers.

TYPE: MptConfig

RETURNS DESCRIPTION
None

This method initializes the MptForTokenClassification instance with the provided configuration.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def __init__(self, config: MptConfig):
    """
    Initializes an instance of the MptForTokenClassification class.

    Args:
        self: The instance of the MptForTokenClassification class.
        config (MptConfig):
            An object of type MptConfig containing configuration parameters for the model.

            - num_labels (int): The number of labels for token classification.
            - classifier_dropout (float, optional): The dropout probability for the classifier layer.
            - hidden_dropout (float, optional): The dropout probability for hidden layers.

    Returns:
        None:
            This method initializes the MptForTokenClassification instance with the provided configuration.

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

    self.transformer = MptModel(config)
    if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
        classifier_dropout = config.classifier_dropout
    elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
        classifier_dropout = config.hidden_dropout
    else:
        classifier_dropout = 0.1
    self.dropout = nn.Dropout(p=classifier_dropout)
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.mpt.modeling_mpt.MptForTokenClassification.forward(input_ids=None, past_key_values=None, attention_mask=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, **deprecated_arguments)

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/mpt/modeling_mpt.py
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
1201
1202
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
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
    **deprecated_arguments,
) -> Union[Tuple[mindspore.Tensor], TokenClassifierOutput]:
    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

    transformer_outputs = self.transformer(
        input_ids,
        past_key_values=past_key_values,
        attention_mask=attention_mask,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    hidden_states = transformer_outputs[0]
    hidden_states = self.dropout(hidden_states)
    logits = self.classifier(hidden_states)

    loss = None
    if labels is not None:
        batch_size, seq_length = labels.shape
        loss = ops.cross_entropy(
            logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
        )

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

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

mindnlp.transformers.models.mpt.modeling_mpt.MptMLP

Bases: Module

Class representing a Multi-Layer Perceptron (MLP) for Mpt models.

This class defines the architecture of a Multi-Layer Perceptron for Mpt models. It consists of an up projection layer, activation function (GELU), down projection layer, hidden dropout layer, and a forward method to process hidden states and residuals.

Inherits from nn.Module.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
class MptMLP(nn.Module):

    """
    Class representing a Multi-Layer Perceptron (MLP) for Mpt models.

    This class defines the architecture of a Multi-Layer Perceptron for Mpt models.
    It consists of an up projection layer, activation function (GELU), down projection layer, hidden dropout layer,
    and a forward method to process hidden states and residuals.

    Inherits from nn.Module.
    """
    def __init__(self, config: MptConfig):
        """
        Initializes an instance of the MptMLP class.

        Args:
            self: The instance of the class.
            config (MptConfig): An object of type MptConfig containing configuration parameters.
                The config parameter is used to specify the hidden size for the MLP model.
                It is expected to have the following attributes:

                - hidden_size: An integer specifying the size of the hidden layer.
                - attn_config: An object containing attention configuration parameters.

                    - attn_pdrop: A float specifying the dropout probability for attention.

        Returns:
            None.

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

        self.up_proj = nn.Linear(hidden_size, 4 * hidden_size, bias=False)
        self.act = nn.GELU(approximate=False)
        self.down_proj = nn.Linear(4 * hidden_size, hidden_size, bias=False)
        self.hidden_dropout = config.attn_config.attn_pdrop

    def forward(self, hidden_states: mindspore.Tensor, residual: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs a multi-layer perception (MLP) module.

        Args:
            self (MptMLP): An instance of the MptMLP class.
            hidden_states (mindspore.Tensor): The input hidden states tensor of shape (batch_size, hidden_size).
            residual (mindspore.Tensor): The residual tensor of shape (batch_size, hidden_size).

        Returns:
            mindspore.Tensor: The output tensor of shape (batch_size, hidden_size).

        Raises:
            TypeError: If the input hidden_states or residual is not a mindspore.Tensor.
            ValueError: If the shapes of hidden_states and residual do not match.
        """
        hidden_states = self.act(self.up_proj(hidden_states))

        intermediate_output = self.down_proj(hidden_states)

        output = ops.dropout(intermediate_output, p=self.hidden_dropout, training=self.training)
        output = output + residual

        return output

mindnlp.transformers.models.mpt.modeling_mpt.MptMLP.__init__(config)

Initializes an instance of the MptMLP class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object of type MptConfig containing configuration parameters. The config parameter is used to specify the hidden size for the MLP model. It is expected to have the following attributes:

  • hidden_size: An integer specifying the size of the hidden layer.
  • attn_config: An object containing attention configuration parameters.

    • attn_pdrop: A float specifying the dropout probability for attention.

TYPE: MptConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def __init__(self, config: MptConfig):
    """
    Initializes an instance of the MptMLP class.

    Args:
        self: The instance of the class.
        config (MptConfig): An object of type MptConfig containing configuration parameters.
            The config parameter is used to specify the hidden size for the MLP model.
            It is expected to have the following attributes:

            - hidden_size: An integer specifying the size of the hidden layer.
            - attn_config: An object containing attention configuration parameters.

                - attn_pdrop: A float specifying the dropout probability for attention.

    Returns:
        None.

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

    self.up_proj = nn.Linear(hidden_size, 4 * hidden_size, bias=False)
    self.act = nn.GELU(approximate=False)
    self.down_proj = nn.Linear(4 * hidden_size, hidden_size, bias=False)
    self.hidden_dropout = config.attn_config.attn_pdrop

mindnlp.transformers.models.mpt.modeling_mpt.MptMLP.forward(hidden_states, residual)

Constructs a multi-layer perception (MLP) module.

PARAMETER DESCRIPTION
self

An instance of the MptMLP class.

TYPE: MptMLP

hidden_states

The input hidden states tensor of shape (batch_size, hidden_size).

TYPE: Tensor

residual

The residual tensor of shape (batch_size, hidden_size).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The output tensor of shape (batch_size, hidden_size).

RAISES DESCRIPTION
TypeError

If the input hidden_states or residual is not a mindspore.Tensor.

ValueError

If the shapes of hidden_states and residual do not match.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def forward(self, hidden_states: mindspore.Tensor, residual: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs a multi-layer perception (MLP) module.

    Args:
        self (MptMLP): An instance of the MptMLP class.
        hidden_states (mindspore.Tensor): The input hidden states tensor of shape (batch_size, hidden_size).
        residual (mindspore.Tensor): The residual tensor of shape (batch_size, hidden_size).

    Returns:
        mindspore.Tensor: The output tensor of shape (batch_size, hidden_size).

    Raises:
        TypeError: If the input hidden_states or residual is not a mindspore.Tensor.
        ValueError: If the shapes of hidden_states and residual do not match.
    """
    hidden_states = self.act(self.up_proj(hidden_states))

    intermediate_output = self.down_proj(hidden_states)

    output = ops.dropout(intermediate_output, p=self.hidden_dropout, training=self.training)
    output = output + residual

    return output

mindnlp.transformers.models.mpt.modeling_mpt.MptModel

Bases: MptPreTrainedModel

This class represents a modified pre-trained transformer model (MptModel) for natural language processing tasks. It inherits from MptPreTrainedModel and includes methods for initializing the model, handling input embeddings, forwarding the model with various optional parameters, and building the multi-head positional tensor alibi. The model consists of multiple MptBlocks organized in a sequence. It provides functionality for processing input data, managing past key values, applying attention masks, and computing hidden states. Additionally, the model supports gradient checkpointing for efficient training. The MptModel class encapsulates the core functionality required for performing transformer-based operations on text data.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
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
679
680
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
class MptModel(MptPreTrainedModel):

    """
    This class represents a modified pre-trained transformer model (MptModel) for natural language processing tasks.
    It inherits from MptPreTrainedModel and includes methods for initializing the model, handling input embeddings,
    forwarding the model with various optional parameters, and building the multi-head positional tensor alibi.
    The model consists of multiple MptBlocks organized in a sequence. It provides functionality for processing input
    data, managing past key values, applying attention masks, and computing hidden states. Additionally, the model supports
    gradient checkpointing for efficient training. The MptModel class encapsulates the core functionality required for
    performing transformer-based operations on text data.
    """
    def __init__(self, config: MptConfig):
        """
        Initializes an instance of MptModel.

        Args:
            self: The object instance itself.
            config (MptConfig):
                An instance of MptConfig containing the configuration parameters for the model.

                - Type: MptConfig
                - Purpose: Specifies the configuration parameters for the model.
                - Restrictions: Must be an instance of MptConfig.

        Returns:
            None.

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

        self.hidden_size = config.hidden_size
        self.num_heads = config.n_heads

        # Embedding + LN Embedding
        self.wte = nn.Embedding(config.vocab_size, self.hidden_size)

        # Transformer blocks
        self.blocks = nn.ModuleList([MptBlock(config) for _ in range(config.n_layers)])

        # Final Layer Norm
        self.norm_f = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_epsilon, elementwise_affine=False)
        # backward compatibility with weights on the Hub
        self.norm_f.bias = None

        self.gradient_checkpointing = False

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

    def get_input_embeddings(self):
        """
        This method is part of the MptModel class and is used to retrieve the input embeddings.

        Args:
            self: An instance of the MptModel class.

        Returns:
            None: This method returns None, as it simply retrieves the input embeddings without any additional processing.

        Raises:
            None.
        """
        return self.wte

    def build_mpt_alibi_tensor(self, num_heads, sequence_length, alibi_bias_max=8):
        """
        This method builds a multi-head attention (MPT) alibi tensor.

        Args:
            self (MptModel): The instance of the MptModel class.
            num_heads (int): The number of attention heads to be used in the tensor.
            sequence_length (int): The length of the input sequence.
            alibi_bias_max (int, optional): The maximum value for the alibi bias. Defaults to 8.

        Returns:
            None.

        Raises:
            ValueError: If num_heads or sequence_length is not a positive integer.
            TypeError: If num_heads, sequence_length, or alibi_bias_max is not of type int.
        """
        return build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max)

    def set_input_embeddings(self, new_embeddings: mindspore.Tensor):
        """
        Sets the input embeddings for the MptModel.

        Args:
            self (MptModel): The instance of the MptModel class.
            new_embeddings (mindspore.Tensor): The new embeddings to be set as input.

        Returns:
            None.

        Raises:
            None.
        """
        self.wte = new_embeddings

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[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, ...], BaseModelOutputWithPastAndCrossAttentions]:
        """
        Constructs the MptModel.

        Args:
            self: The MptModel instance.
            input_ids (Optional[mindspore.Tensor]):
                The input tensor of shape (batch_size, seq_length) containing the input IDs.
            past_key_values (Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]]):
                The past key values tensor of shape (batch_size, past_seq_length, hidden_size) containing
                the past key values.
            attention_mask (Optional[mindspore.Tensor]): The attention mask tensor of shape (batch_size, seq_length)
                containing the attention mask values.
            inputs_embeds (Optional[mindspore.Tensor]): The inputs embeddings tensor of shape
                (batch_size, seq_length, hidden_size) containing the input embeddings.
            use_cache (Optional[bool]): Flag indicating whether to use cache. Default is None.
            output_attentions (Optional[bool]): Flag indicating whether to output attentions. Default is None.
            output_hidden_states (Optional[bool]): Flag indicating whether to output hidden states. Default is None.
            return_dict (Optional[bool]): Flag indicating whether to return a dictionary. Default is None.

        Returns:
            Union[Tuple[mindspore.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
                A tuple containing the hidden states, presents, all hidden states, and all self attentions.
                The hidden states tensor has shape (batch_size, seq_length, hidden_size). The presents tensor has shape
                (batch_size, past_seq_length + seq_length, hidden_size). The all hidden states tensor is a tuple of
                hidden states tensors at each layer. The all self attentions tensor is a tuple of self attention tensors
                at each layer.

        Raises:
            ValueError: If both input_ids and inputs_embeds are specified simultaneously.
            ValueError: If neither input_ids nor inputs_embeds are specified.
            Warning: If use_cache is set to True and gradient checkpointing is enabled, as they are incompatible.

        """
        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
        )
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        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")
        elif input_ids is not None:
            batch_size, seq_length = input_ids.shape
        elif inputs_embeds is not None:
            batch_size, seq_length, _ = inputs_embeds.shape
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        if past_key_values is None:
            past_key_values = tuple([None] * len(self.blocks))

        if inputs_embeds is None:
            inputs_embeds = self.wte(input_ids)

        hidden_states = inputs_embeds

        presents = () if use_cache else None
        all_self_attentions = () if output_attentions else None
        all_hidden_states = () if output_hidden_states else None

        if self.gradient_checkpointing and self.training:
            if use_cache:
                logger.warning_once(
                    "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
                )
                use_cache = False

        # Compute alibi tensor: check build_alibi_tensor documentation
        seq_length_with_past = seq_length
        past_key_values_length = 0
        if past_key_values[0] is not None:
            past_key_values_length = past_key_values[0][0].shape[2]
            seq_length_with_past = seq_length_with_past + past_key_values_length
        if attention_mask is None:
            attention_mask = ops.ones((batch_size, seq_length_with_past))
        else:
            pass

        alibi = self.build_mpt_alibi_tensor(self.num_heads, self.config.max_seq_len)

        causal_mask = _prepare_4d_causal_attention_mask(
            attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
        )
        causal_mask = causal_mask.bool()

        for block, layer_past in zip(self.blocks, past_key_values):
            if output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_states,)

            if self.gradient_checkpointing and self.training:
                outputs = self._gradient_checkpointing_func(
                    block.__call__,
                    hidden_states,
                    alibi,
                    causal_mask,
                    layer_past,
                    use_cache,
                    output_attentions,
                )
            else:
                outputs = block(
                    hidden_states,
                    layer_past=layer_past,
                    attention_mask=causal_mask,
                    use_cache=use_cache,
                    output_attentions=output_attentions,
                    position_bias=alibi,
                )

            hidden_states = outputs[0]
            if use_cache is True:
                presents = presents + (outputs[1],)

            if output_attentions:
                all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)

        # Add last hidden state
        hidden_states = self.norm_f(hidden_states)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if not return_dict:
            return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)

        return BaseModelOutputWithPastAndCrossAttentions(
            last_hidden_state=hidden_states,
            past_key_values=presents,
            hidden_states=all_hidden_states,
            attentions=all_self_attentions,
        )

mindnlp.transformers.models.mpt.modeling_mpt.MptModel.__init__(config)

Initializes an instance of MptModel.

PARAMETER DESCRIPTION
self

The object instance itself.

config

An instance of MptConfig containing the configuration parameters for the model.

  • Type: MptConfig
  • Purpose: Specifies the configuration parameters for the model.
  • Restrictions: Must be an instance of MptConfig.

TYPE: MptConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
def __init__(self, config: MptConfig):
    """
    Initializes an instance of MptModel.

    Args:
        self: The object instance itself.
        config (MptConfig):
            An instance of MptConfig containing the configuration parameters for the model.

            - Type: MptConfig
            - Purpose: Specifies the configuration parameters for the model.
            - Restrictions: Must be an instance of MptConfig.

    Returns:
        None.

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

    self.hidden_size = config.hidden_size
    self.num_heads = config.n_heads

    # Embedding + LN Embedding
    self.wte = nn.Embedding(config.vocab_size, self.hidden_size)

    # Transformer blocks
    self.blocks = nn.ModuleList([MptBlock(config) for _ in range(config.n_layers)])

    # Final Layer Norm
    self.norm_f = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_epsilon, elementwise_affine=False)
    # backward compatibility with weights on the Hub
    self.norm_f.bias = None

    self.gradient_checkpointing = False

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

mindnlp.transformers.models.mpt.modeling_mpt.MptModel.build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max=8)

This method builds a multi-head attention (MPT) alibi tensor.

PARAMETER DESCRIPTION
self

The instance of the MptModel class.

TYPE: MptModel

num_heads

The number of attention heads to be used in the tensor.

TYPE: int

sequence_length

The length of the input sequence.

TYPE: int

alibi_bias_max

The maximum value for the alibi bias. Defaults to 8.

TYPE: int DEFAULT: 8

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If num_heads or sequence_length is not a positive integer.

TypeError

If num_heads, sequence_length, or alibi_bias_max is not of type int.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
def build_mpt_alibi_tensor(self, num_heads, sequence_length, alibi_bias_max=8):
    """
    This method builds a multi-head attention (MPT) alibi tensor.

    Args:
        self (MptModel): The instance of the MptModel class.
        num_heads (int): The number of attention heads to be used in the tensor.
        sequence_length (int): The length of the input sequence.
        alibi_bias_max (int, optional): The maximum value for the alibi bias. Defaults to 8.

    Returns:
        None.

    Raises:
        ValueError: If num_heads or sequence_length is not a positive integer.
        TypeError: If num_heads, sequence_length, or alibi_bias_max is not of type int.
    """
    return build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max)

mindnlp.transformers.models.mpt.modeling_mpt.MptModel.forward(input_ids=None, past_key_values=None, attention_mask=None, inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the MptModel.

PARAMETER DESCRIPTION
self

The MptModel instance.

input_ids

The input tensor of shape (batch_size, seq_length) containing the input IDs.

TYPE: Optional[Tensor] DEFAULT: None

past_key_values

The past key values tensor of shape (batch_size, past_seq_length, hidden_size) containing the past key values.

TYPE: Optional[Tuple[Tuple[Tensor, Tensor], ...]] DEFAULT: None

attention_mask

The attention mask tensor of shape (batch_size, seq_length) containing the attention mask values.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The inputs embeddings tensor of shape (batch_size, seq_length, hidden_size) containing the input embeddings.

TYPE: Optional[Tensor] DEFAULT: None

use_cache

Flag indicating whether to use cache. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_attentions

Flag indicating whether to output attentions. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Flag indicating whether to output hidden states. Default is None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Flag indicating whether to return a dictionary. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple[Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]

Union[Tuple[mindspore.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]: A tuple containing the hidden states, presents, all hidden states, and all self attentions. The hidden states tensor has shape (batch_size, seq_length, hidden_size). The presents tensor has shape (batch_size, past_seq_length + seq_length, hidden_size). The all hidden states tensor is a tuple of hidden states tensors at each layer. The all self attentions tensor is a tuple of self attention tensors at each layer.

RAISES DESCRIPTION
ValueError

If both input_ids and inputs_embeds are specified simultaneously.

ValueError

If neither input_ids nor inputs_embeds are specified.

Warning

If use_cache is set to True and gradient checkpointing is enabled, as they are incompatible.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
679
680
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
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[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, ...], BaseModelOutputWithPastAndCrossAttentions]:
    """
    Constructs the MptModel.

    Args:
        self: The MptModel instance.
        input_ids (Optional[mindspore.Tensor]):
            The input tensor of shape (batch_size, seq_length) containing the input IDs.
        past_key_values (Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]]):
            The past key values tensor of shape (batch_size, past_seq_length, hidden_size) containing
            the past key values.
        attention_mask (Optional[mindspore.Tensor]): The attention mask tensor of shape (batch_size, seq_length)
            containing the attention mask values.
        inputs_embeds (Optional[mindspore.Tensor]): The inputs embeddings tensor of shape
            (batch_size, seq_length, hidden_size) containing the input embeddings.
        use_cache (Optional[bool]): Flag indicating whether to use cache. Default is None.
        output_attentions (Optional[bool]): Flag indicating whether to output attentions. Default is None.
        output_hidden_states (Optional[bool]): Flag indicating whether to output hidden states. Default is None.
        return_dict (Optional[bool]): Flag indicating whether to return a dictionary. Default is None.

    Returns:
        Union[Tuple[mindspore.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
            A tuple containing the hidden states, presents, all hidden states, and all self attentions.
            The hidden states tensor has shape (batch_size, seq_length, hidden_size). The presents tensor has shape
            (batch_size, past_seq_length + seq_length, hidden_size). The all hidden states tensor is a tuple of
            hidden states tensors at each layer. The all self attentions tensor is a tuple of self attention tensors
            at each layer.

    Raises:
        ValueError: If both input_ids and inputs_embeds are specified simultaneously.
        ValueError: If neither input_ids nor inputs_embeds are specified.
        Warning: If use_cache is set to True and gradient checkpointing is enabled, as they are incompatible.

    """
    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
    )
    use_cache = use_cache if use_cache is not None else self.config.use_cache
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    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")
    elif input_ids is not None:
        batch_size, seq_length = input_ids.shape
    elif inputs_embeds is not None:
        batch_size, seq_length, _ = inputs_embeds.shape
    else:
        raise ValueError("You have to specify either input_ids or inputs_embeds")

    if past_key_values is None:
        past_key_values = tuple([None] * len(self.blocks))

    if inputs_embeds is None:
        inputs_embeds = self.wte(input_ids)

    hidden_states = inputs_embeds

    presents = () if use_cache else None
    all_self_attentions = () if output_attentions else None
    all_hidden_states = () if output_hidden_states else None

    if self.gradient_checkpointing and self.training:
        if use_cache:
            logger.warning_once(
                "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
            )
            use_cache = False

    # Compute alibi tensor: check build_alibi_tensor documentation
    seq_length_with_past = seq_length
    past_key_values_length = 0
    if past_key_values[0] is not None:
        past_key_values_length = past_key_values[0][0].shape[2]
        seq_length_with_past = seq_length_with_past + past_key_values_length
    if attention_mask is None:
        attention_mask = ops.ones((batch_size, seq_length_with_past))
    else:
        pass

    alibi = self.build_mpt_alibi_tensor(self.num_heads, self.config.max_seq_len)

    causal_mask = _prepare_4d_causal_attention_mask(
        attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
    )
    causal_mask = causal_mask.bool()

    for block, layer_past in zip(self.blocks, past_key_values):
        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if self.gradient_checkpointing and self.training:
            outputs = self._gradient_checkpointing_func(
                block.__call__,
                hidden_states,
                alibi,
                causal_mask,
                layer_past,
                use_cache,
                output_attentions,
            )
        else:
            outputs = block(
                hidden_states,
                layer_past=layer_past,
                attention_mask=causal_mask,
                use_cache=use_cache,
                output_attentions=output_attentions,
                position_bias=alibi,
            )

        hidden_states = outputs[0]
        if use_cache is True:
            presents = presents + (outputs[1],)

        if output_attentions:
            all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)

    # Add last hidden state
    hidden_states = self.norm_f(hidden_states)

    if output_hidden_states:
        all_hidden_states = all_hidden_states + (hidden_states,)

    if not return_dict:
        return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)

    return BaseModelOutputWithPastAndCrossAttentions(
        last_hidden_state=hidden_states,
        past_key_values=presents,
        hidden_states=all_hidden_states,
        attentions=all_self_attentions,
    )

mindnlp.transformers.models.mpt.modeling_mpt.MptModel.get_input_embeddings()

This method is part of the MptModel class and is used to retrieve the input embeddings.

PARAMETER DESCRIPTION
self

An instance of the MptModel class.

RETURNS DESCRIPTION
None

This method returns None, as it simply retrieves the input embeddings without any additional processing.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def get_input_embeddings(self):
    """
    This method is part of the MptModel class and is used to retrieve the input embeddings.

    Args:
        self: An instance of the MptModel class.

    Returns:
        None: This method returns None, as it simply retrieves the input embeddings without any additional processing.

    Raises:
        None.
    """
    return self.wte

mindnlp.transformers.models.mpt.modeling_mpt.MptModel.set_input_embeddings(new_embeddings)

Sets the input embeddings for the MptModel.

PARAMETER DESCRIPTION
self

The instance of the MptModel class.

TYPE: MptModel

new_embeddings

The new embeddings to be set as input.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def set_input_embeddings(self, new_embeddings: mindspore.Tensor):
    """
    Sets the input embeddings for the MptModel.

    Args:
        self (MptModel): The instance of the MptModel class.
        new_embeddings (mindspore.Tensor): The new embeddings to be set as input.

    Returns:
        None.

    Raises:
        None.
    """
    self.wte = new_embeddings

mindnlp.transformers.models.mpt.modeling_mpt.MptPreTrainedModel

Bases: PreTrainedModel

MptPreTrainedModel is a Python class representing a pre-trained model for Mpt (MindSpore Transformer) models. It provides methods for initializing weights of different types of neural network cells and converting the cache to the format expected by Mpt.

The class includes an init method for initializing the model, an _init_weights method for weight initialization of different cell types, and a static method _convert_to_mpt_cache for converting the cache format to be compatible with Mpt.

The _init_weights method initializes weights based on the type of neural network cell, such as nn.Linear, nn.Embedding, and nn.LayerNorm. The method sets the weights and biases of the cells according to specific initializations.

The _convert_to_mpt_cache static method takes a past_key_value tuple and converts it to the format expected by Mpt, reshaping the tensors to match the batch size, number of heads, head dimension, and sequence length.

Note

This class inherits from PreTrainedModel.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
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
class MptPreTrainedModel(PreTrainedModel):

    """
    MptPreTrainedModel is a Python class representing a pre-trained model for Mpt (MindSpore Transformer) models.
    It provides methods for initializing weights of different types of neural network cells and converting the cache
    to the format expected by Mpt.

    The class includes an __init__ method for initializing the model, an _init_weights method for weight initialization
    of different cell types, and a static method _convert_to_mpt_cache for converting the cache format to be compatible
    with Mpt.

    The _init_weights method initializes weights based on the type of neural network cell, such as nn.Linear,
    nn.Embedding, and nn.LayerNorm.
    The method sets the weights and biases of the cells according to specific initializations.

    The _convert_to_mpt_cache static method takes a past_key_value tuple and converts it to the format expected by Mpt,
    reshaping the tensors to match the batch size, number of heads, head dimension, and sequence length.

    Note:
        This class inherits from PreTrainedModel.
    """
    config_class = MptConfig
    base_model_prefix = "transformer"
    supports_gradient_checkpointing = True
    _no_split_modules = ["MptBlock"]
    _keys_to_ignore_on_load_missing = [r"lm_head.*."]

    def __init__(self, *inputs, **kwargs):
        """
        Initializes a new instance of the MptPreTrainedModel class.

        Args:
            self:
                The object itself.

                - Type: MptPreTrainedModel
                - Purpose: Represents the current instance of the MptPreTrainedModel class.
                - Restrictions: None

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(*inputs, **kwargs)

    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
            cell.weight.set_data(initializer(Normal(self.config.initializer_range),
                                                    cell.weight.shape, cell.weight.dtype))
            if cell.bias:
                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(mindspore.Tensor(weight, cell.weight.dtype))
        elif isinstance(cell, nn.LayerNorm):
            cell.weight.set_data(initializer('ones', cell.weight.shape, cell.weight.dtype))
            if cell.bias:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))

    @staticmethod
    def _convert_to_mpt_cache(
        past_key_value: Tuple[Tuple[mindspore.Tensor, mindspore.Tensor]],
    ) -> Tuple[Tuple[mindspore.Tensor, mindspore.Tensor]]:
        """
        Converts the cache to the format expected by Mpt, i.e. to tuple(tuple([batch_size * num_heads, ...]))
        """
        batch_size, num_heads, head_dim, seq_length = past_key_value[0][0].shape
        batch_size_times_num_heads = batch_size * num_heads
        # key:  [batch_size, num_heads, head_dim, seq_length] -> [batch_size * num_heads, head_dim, seq_length]
        # value: [batch_size, num_heads, seq_length, head_dim] -> [batch_size * num_heads, seq_length, head_dim]
        return tuple(
            (
                layer_past[0].reshape(batch_size_times_num_heads, head_dim, seq_length),
                layer_past[1].reshape(batch_size_times_num_heads, seq_length, head_dim),
            )
            for layer_past in past_key_value
        )

mindnlp.transformers.models.mpt.modeling_mpt.MptPreTrainedModel.__init__(*inputs, **kwargs)

Initializes a new instance of the MptPreTrainedModel class.

PARAMETER DESCRIPTION
self

The object itself.

  • Type: MptPreTrainedModel
  • Purpose: Represents the current instance of the MptPreTrainedModel class.
  • Restrictions: None

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
def __init__(self, *inputs, **kwargs):
    """
    Initializes a new instance of the MptPreTrainedModel class.

    Args:
        self:
            The object itself.

            - Type: MptPreTrainedModel
            - Purpose: Represents the current instance of the MptPreTrainedModel class.
            - Restrictions: None

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(*inputs, **kwargs)

mindnlp.transformers.models.mpt.modeling_mpt.build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max=8)

Link to paper: https://arxiv.org/abs/2108.12409 - Alibi tensor is not causal as the original paper mentions, it relies on a translation invariance of softmax for quick implementation. This implementation has been copied from the alibi implementation of MPT source code that led to slightly different results than the Bloom alibi: https://huggingface.co/mosaicml/mpt-7b/blob/main/attention.py#L292

Source code in mindnlp/transformers/models/mpt/modeling_mpt.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def build_mpt_alibi_tensor(num_heads, sequence_length, alibi_bias_max=8):
    r"""
    Link to paper: https://arxiv.org/abs/2108.12409 - Alibi tensor is not causal as the original paper mentions, it
    relies on a translation invariance of softmax for quick implementation. This implementation has been copied from
    the alibi implementation of MPT source code that led to slightly different results than the Bloom alibi:
    https://huggingface.co/mosaicml/mpt-7b/blob/main/attention.py#L292
    """
    alibi = ops.arange(1 - sequence_length, 1, dtype=mindspore.int32).view(1, 1, 1, sequence_length)
    num_heads_power_of_2 = 2 ** math.ceil(math.log2(num_heads))

    base = ops.arange(1, num_heads_power_of_2 + 1, dtype=mindspore.int64).float()
    base = base * (alibi_bias_max / num_heads_power_of_2)

    slopes = 1.0 / ops.pow(2, base)
    slopes = slopes.view(1, num_heads_power_of_2, 1, 1)

    if num_heads_power_of_2 != num_heads:
        slopes = ops.concat([slopes[:, 1::2, ...], slopes[:, ::2, ...]], axis=1)[:, :num_heads, ...]

    alibi = alibi * slopes
    return alibi.squeeze(0)