跳转至

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

MindSpore 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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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):
        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.clip_qkv = config.attn_config.clip_qkv
        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,
    ):
        batch_size, seq_length = hidden_states.shape[:2]

        mixed_qkv = self.Wqkv(hidden_states)
        if self.clip_qkv:
            mixed_qkv = mixed_qkv.clamp(min=-self.clip_qkv, max=self.clip_qkv)

        query_states, key_states, value_states = ops.chunk(mixed_qkv, 3, dim=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], dim=2)
                value_states = ops.cat([past_key_value[1], value_states], dim=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, float(ops.finfo(query_states.dtype).min))

        # (batch_size, n_heads, seq_length, key_length)
        attn_weights = nn.functional.softmax(attention_scores.float(), dim=-1).to(value_states.dtype)
        attn_weights = nn.functional.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.MptForCausalLM

Bases: MptPreTrainedModel

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
class MptForCausalLM(MptPreTrainedModel):
    _tied_weights_keys = ["lm_head.weight"]

    def __init__(self, config: MptConfig):
        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):
        return self.lm_head

    def set_output_embeddings(self, new_embeddings: mindspore.Tensor):
        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:
        # 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"""
        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_fct = CrossEntropyLoss()
            loss = loss_fct(
                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`.
        """
        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.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)

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]

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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"""
    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_fct = CrossEntropyLoss()
        loss = loss_fct(
            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.MptForQuestionAnswering

Bases: MptPreTrainedModel

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
class MptForQuestionAnswering(MptPreTrainedModel):
    def __init__(self, config):
        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"""
        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 = ops.split(logits, 1, dim=-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)

            loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
            start_loss = loss_fct(start_logits, start_positions)
            end_loss = loss_fct(end_logits, end_positions)
            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.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)

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.

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
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
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"""
    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 = ops.split(logits, 1, dim=-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)

        loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
        start_loss = loss_fct(start_logits, start_positions)
        end_loss = loss_fct(end_logits, end_positions)
        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

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
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
class MptForSequenceClassification(MptPreTrainedModel):
    def __init__(self, config: MptConfig):
        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"""
        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_once(
                    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.int64, mindspore.int32):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                loss_fct = MSELoss()
                if self.num_labels == 1:
                    loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
                else:
                    loss = loss_fct(pooled_logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss_fct = CrossEntropyLoss()
                loss = loss_fct(pooled_logits, labels)
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = BCEWithLogitsLoss()
                loss = loss_fct(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.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)

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

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
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
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"""
    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_once(
                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.int64, mindspore.int32):
                self.config.problem_type = "single_label_classification"
            else:
                self.config.problem_type = "multi_label_classification"

        if self.config.problem_type == "regression":
            loss_fct = MSELoss()
            if self.num_labels == 1:
                loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
            else:
                loss = loss_fct(pooled_logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss_fct = CrossEntropyLoss()
            loss = loss_fct(pooled_logits, labels)
        elif self.config.problem_type == "multi_label_classification":
            loss_fct = BCEWithLogitsLoss()
            loss = loss_fct(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

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
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
class MptForTokenClassification(MptPreTrainedModel):
    def __init__(self, config: MptConfig):
        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(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"""
        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_fct = CrossEntropyLoss()
            loss = loss_fct(
                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.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)

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

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
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
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"""
    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_fct = CrossEntropyLoss()
        loss = loss_fct(
            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.MptPreTrainedModel

Bases: PreTrainedModel

Source code in mindnlp\transformers\models\mpt\modeling_mpt.py
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 MptPreTrainedModel(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_weights(self, module: nn.Module):
        """Initialize the weights."""
        if isinstance(module, nn.Linear):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
            if module.bias is not None:
                nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
            if module.padding_idx is not None:
                module.weight[module.padding_idx] = 0
        elif isinstance(module, LayerNorm):
            if module.bias is not None:
                nn.init.zeros_(module.bias)
            nn.init.ones_(module.weight)

    @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.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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, ...]], dim=1)[:, :num_heads, ...]

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