Skip to content

bart

mindnlp.transformers.models.bart.configuration_bart.BartConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [BartModel]. It is used to instantiate a BART model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the BART facebook/bart-large architecture.

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

PARAMETER DESCRIPTION
vocab_size

Vocabulary size of the BART model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [BartModel] or [TFBartModel].

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

d_model

Dimensionality of the layers and the pooler layer.

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

encoder_layers

Number of encoder layers.

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

decoder_layers

Number of decoder layers.

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

encoder_attention_heads

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

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

decoder_attention_heads

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

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

decoder_ffn_dim

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

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

encoder_ffn_dim

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

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

activation_function

The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu", "silu" and "gelu_new" are supported.

TYPE: `str` or `function`, *optional*, defaults to `"gelu"` DEFAULT: 'gelu'

dropout

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

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

attention_dropout

The dropout ratio for the attention probabilities.

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

activation_dropout

The dropout ratio for activations inside the fully connected layer.

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

classifier_dropout

The dropout ratio for classifier.

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

max_position_embeddings

The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).

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

init_std

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

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

encoder_layerdrop

The LayerDrop probability for the encoder. See the LayerDrop paper for more details.

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

decoder_layerdrop

The LayerDrop probability for the decoder. See the LayerDrop paper for more details.

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

scale_embedding

Scale embeddings by diving by sqrt(d_model).

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

use_cache

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

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

num_labels

The number of labels to use in [BartForSequenceClassification].

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

forced_eos_token_id

The id of the token to force as the last generated token when max_length is reached. Usually set to eos_token_id.

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

Example
>>> from transformers import BartConfig, BartModel

>>> # Initializing a BART facebook/bart-large style configuration
>>> configuration = BartConfig()

>>> # Initializing a model (with random weights) from the facebook/bart-large style configuration
>>> model = BartModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/bart/configuration_bart.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class BartConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`BartModel`]. It is used to instantiate a BART
    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to that of the BART
    [facebook/bart-large](https://hf-mirror.com/facebook/bart-large) architecture.

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


    Args:
        vocab_size (`int`, *optional*, defaults to 50265):
            Vocabulary size of the BART model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`BartModel`] or [`TFBartModel`].
        d_model (`int`, *optional*, defaults to 1024):
            Dimensionality of the layers and the pooler layer.
        encoder_layers (`int`, *optional*, defaults to 12):
            Number of encoder layers.
        decoder_layers (`int`, *optional*, defaults to 12):
            Number of decoder layers.
        encoder_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        decoder_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer decoder.
        decoder_ffn_dim (`int`, *optional*, defaults to 4096):
            Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
        encoder_ffn_dim (`int`, *optional*, defaults to 4096):
            Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
        activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"silu"` and `"gelu_new"` are supported.
        dropout (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        activation_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for activations inside the fully connected layer.
        classifier_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for classifier.
        max_position_embeddings (`int`, *optional*, defaults to 1024):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        init_std (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        encoder_layerdrop (`float`, *optional*, defaults to 0.0):
            The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
            for more details.
        decoder_layerdrop (`float`, *optional*, defaults to 0.0):
            The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
            for more details.
        scale_embedding (`bool`, *optional*, defaults to `False`):
            Scale embeddings by diving by sqrt(d_model).
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).
        num_labels (`int`, *optional*, defaults to 3):
            The number of labels to use in [`BartForSequenceClassification`].
        forced_eos_token_id (`int`, *optional*, defaults to 2):
            The id of the token to force as the last generated token when `max_length` is reached. Usually set to
            `eos_token_id`.

    Example:
        ```python
        >>> from transformers import BartConfig, BartModel

        >>> # Initializing a BART facebook/bart-large style configuration
        >>> configuration = BartConfig()

        >>> # Initializing a model (with random weights) from the facebook/bart-large style configuration
        >>> model = BartModel(configuration)

        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "bart"
    keys_to_ignore_at_inference = ["past_key_values"]
    attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}

    def __init__(
        self,
        vocab_size=50265,
        max_position_embeddings=1024,
        encoder_layers=12,
        encoder_ffn_dim=4096,
        encoder_attention_heads=16,
        decoder_layers=12,
        decoder_ffn_dim=4096,
        decoder_attention_heads=16,
        encoder_layerdrop=0.0,
        decoder_layerdrop=0.0,
        activation_function="gelu",
        d_model=1024,
        dropout=0.1,
        attention_dropout=0.0,
        activation_dropout=0.0,
        init_std=0.02,
        classifier_dropout=0.0,
        scale_embedding=False,
        use_cache=True,
        num_labels=3,
        pad_token_id=1,
        bos_token_id=0,
        eos_token_id=2,
        is_encoder_decoder=True,
        decoder_start_token_id=2,
        forced_eos_token_id=2,
        **kwargs,
    ):
        """
        Initializes a new instance of BartConfig.

        Args:
            vocab_size (int, optional): The size of the vocabulary. Defaults to 50265.
            max_position_embeddings (int, optional): The maximum position index. Defaults to 1024.
            encoder_layers (int, optional): The number of encoder layers. Defaults to 12.
            encoder_ffn_dim (int, optional): The dimension of the encoder's feedforward network. Defaults to 4096.
            encoder_attention_heads (int, optional): The number of encoder attention heads. Defaults to 16.
            decoder_layers (int, optional): The number of decoder layers. Defaults to 12.
            decoder_ffn_dim (int, optional): The dimension of the decoder's feedforward network. Defaults to 4096.
            decoder_attention_heads (int, optional): The number of decoder attention heads. Defaults to 16.
            encoder_layerdrop (float, optional): The probability of dropping an encoder layer. Defaults to 0.0.
            decoder_layerdrop (float, optional): The probability of dropping a decoder layer. Defaults to 0.0.
            activation_function (str, optional): The activation function. Defaults to 'gelu'.
            d_model (int, optional): The model dimension. Defaults to 1024.
            dropout (float, optional): The dropout probability. Defaults to 0.1.
            attention_dropout (float, optional): The attention dropout probability. Defaults to 0.0.
            activation_dropout (float, optional): The activation dropout probability. Defaults to 0.0.
            init_std (float, optional): The standard deviation for weight initialization. Defaults to 0.02.
            classifier_dropout (float, optional): The classifier dropout probability. Defaults to 0.0.
            scale_embedding (bool, optional): Whether to scale embeddings. Defaults to False.
            use_cache (bool, optional): Whether to use cache. Defaults to True.
            num_labels (int, optional): The number of labels. Defaults to 3.
            pad_token_id (int, optional): The id of the padding token. Defaults to 1.
            bos_token_id (int, optional): The id of the beginning-of-sequence token. Defaults to 0.
            eos_token_id (int, optional): The id of the end-of-sequence token. Defaults to 2.
            is_encoder_decoder (bool, optional): Whether the model is an encoder-decoder. Defaults to True.
            decoder_start_token_id (int, optional): The id of the decoder start token. Defaults to 2.
            forced_eos_token_id (int, optional): The id of the forced end-of-sequence token. Defaults to 2.

        Returns:
            None.

        Raises:
            Warning: If the config does not include forced_bos_token_id in future versions.
        """
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.d_model = d_model
        self.encoder_ffn_dim = encoder_ffn_dim
        self.encoder_layers = encoder_layers
        self.encoder_attention_heads = encoder_attention_heads
        self.decoder_ffn_dim = decoder_ffn_dim
        self.decoder_layers = decoder_layers
        self.decoder_attention_heads = decoder_attention_heads
        self.dropout = dropout
        self.attention_dropout = attention_dropout
        self.activation_dropout = activation_dropout
        self.activation_function = activation_function
        self.init_std = init_std
        self.encoder_layerdrop = encoder_layerdrop
        self.decoder_layerdrop = decoder_layerdrop
        self.classifier_dropout = classifier_dropout
        self.use_cache = use_cache
        self.num_hidden_layers = encoder_layers
        self.scale_embedding = scale_embedding  # scale factor will be sqrt(d_model) if True

        super().__init__(
            num_labels=num_labels,
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            is_encoder_decoder=is_encoder_decoder,
            decoder_start_token_id=decoder_start_token_id,
            forced_eos_token_id=forced_eos_token_id,
            **kwargs,
        )

        # ensure backward compatibility for BART CNN models
        if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
            self.forced_bos_token_id = self.bos_token_id
            warnings.warn(
                f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
                "The config can simply be saved and uploaded again to be fixed."
            )

mindnlp.transformers.models.bart.configuration_bart.BartConfig.__init__(vocab_size=50265, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_dim=4096, encoder_attention_heads=16, decoder_layers=12, decoder_ffn_dim=4096, decoder_attention_heads=16, encoder_layerdrop=0.0, decoder_layerdrop=0.0, activation_function='gelu', d_model=1024, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, classifier_dropout=0.0, scale_embedding=False, use_cache=True, num_labels=3, pad_token_id=1, bos_token_id=0, eos_token_id=2, is_encoder_decoder=True, decoder_start_token_id=2, forced_eos_token_id=2, **kwargs)

Initializes a new instance of BartConfig.

PARAMETER DESCRIPTION
vocab_size

The size of the vocabulary. Defaults to 50265.

TYPE: int DEFAULT: 50265

max_position_embeddings

The maximum position index. Defaults to 1024.

TYPE: int DEFAULT: 1024

encoder_layers

The number of encoder layers. Defaults to 12.

TYPE: int DEFAULT: 12

encoder_ffn_dim

The dimension of the encoder's feedforward network. Defaults to 4096.

TYPE: int DEFAULT: 4096

encoder_attention_heads

The number of encoder attention heads. Defaults to 16.

TYPE: int DEFAULT: 16

decoder_layers

The number of decoder layers. Defaults to 12.

TYPE: int DEFAULT: 12

decoder_ffn_dim

The dimension of the decoder's feedforward network. Defaults to 4096.

TYPE: int DEFAULT: 4096

decoder_attention_heads

The number of decoder attention heads. Defaults to 16.

TYPE: int DEFAULT: 16

encoder_layerdrop

The probability of dropping an encoder layer. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

decoder_layerdrop

The probability of dropping a decoder layer. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

activation_function

The activation function. Defaults to 'gelu'.

TYPE: str DEFAULT: 'gelu'

d_model

The model dimension. Defaults to 1024.

TYPE: int DEFAULT: 1024

dropout

The dropout probability. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

attention_dropout

The attention dropout probability. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

activation_dropout

The activation dropout probability. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

init_std

The standard deviation for weight initialization. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

classifier_dropout

The classifier dropout probability. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

scale_embedding

Whether to scale embeddings. Defaults to False.

TYPE: bool DEFAULT: False

use_cache

Whether to use cache. Defaults to True.

TYPE: bool DEFAULT: True

num_labels

The number of labels. Defaults to 3.

TYPE: int DEFAULT: 3

pad_token_id

The id of the padding token. Defaults to 1.

TYPE: int DEFAULT: 1

bos_token_id

The id of the beginning-of-sequence token. Defaults to 0.

TYPE: int DEFAULT: 0

eos_token_id

The id of the end-of-sequence token. Defaults to 2.

TYPE: int DEFAULT: 2

is_encoder_decoder

Whether the model is an encoder-decoder. Defaults to True.

TYPE: bool DEFAULT: True

decoder_start_token_id

The id of the decoder start token. Defaults to 2.

TYPE: int DEFAULT: 2

forced_eos_token_id

The id of the forced end-of-sequence token. Defaults to 2.

TYPE: int DEFAULT: 2

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
Warning

If the config does not include forced_bos_token_id in future versions.

Source code in mindnlp/transformers/models/bart/configuration_bart.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def __init__(
    self,
    vocab_size=50265,
    max_position_embeddings=1024,
    encoder_layers=12,
    encoder_ffn_dim=4096,
    encoder_attention_heads=16,
    decoder_layers=12,
    decoder_ffn_dim=4096,
    decoder_attention_heads=16,
    encoder_layerdrop=0.0,
    decoder_layerdrop=0.0,
    activation_function="gelu",
    d_model=1024,
    dropout=0.1,
    attention_dropout=0.0,
    activation_dropout=0.0,
    init_std=0.02,
    classifier_dropout=0.0,
    scale_embedding=False,
    use_cache=True,
    num_labels=3,
    pad_token_id=1,
    bos_token_id=0,
    eos_token_id=2,
    is_encoder_decoder=True,
    decoder_start_token_id=2,
    forced_eos_token_id=2,
    **kwargs,
):
    """
    Initializes a new instance of BartConfig.

    Args:
        vocab_size (int, optional): The size of the vocabulary. Defaults to 50265.
        max_position_embeddings (int, optional): The maximum position index. Defaults to 1024.
        encoder_layers (int, optional): The number of encoder layers. Defaults to 12.
        encoder_ffn_dim (int, optional): The dimension of the encoder's feedforward network. Defaults to 4096.
        encoder_attention_heads (int, optional): The number of encoder attention heads. Defaults to 16.
        decoder_layers (int, optional): The number of decoder layers. Defaults to 12.
        decoder_ffn_dim (int, optional): The dimension of the decoder's feedforward network. Defaults to 4096.
        decoder_attention_heads (int, optional): The number of decoder attention heads. Defaults to 16.
        encoder_layerdrop (float, optional): The probability of dropping an encoder layer. Defaults to 0.0.
        decoder_layerdrop (float, optional): The probability of dropping a decoder layer. Defaults to 0.0.
        activation_function (str, optional): The activation function. Defaults to 'gelu'.
        d_model (int, optional): The model dimension. Defaults to 1024.
        dropout (float, optional): The dropout probability. Defaults to 0.1.
        attention_dropout (float, optional): The attention dropout probability. Defaults to 0.0.
        activation_dropout (float, optional): The activation dropout probability. Defaults to 0.0.
        init_std (float, optional): The standard deviation for weight initialization. Defaults to 0.02.
        classifier_dropout (float, optional): The classifier dropout probability. Defaults to 0.0.
        scale_embedding (bool, optional): Whether to scale embeddings. Defaults to False.
        use_cache (bool, optional): Whether to use cache. Defaults to True.
        num_labels (int, optional): The number of labels. Defaults to 3.
        pad_token_id (int, optional): The id of the padding token. Defaults to 1.
        bos_token_id (int, optional): The id of the beginning-of-sequence token. Defaults to 0.
        eos_token_id (int, optional): The id of the end-of-sequence token. Defaults to 2.
        is_encoder_decoder (bool, optional): Whether the model is an encoder-decoder. Defaults to True.
        decoder_start_token_id (int, optional): The id of the decoder start token. Defaults to 2.
        forced_eos_token_id (int, optional): The id of the forced end-of-sequence token. Defaults to 2.

    Returns:
        None.

    Raises:
        Warning: If the config does not include forced_bos_token_id in future versions.
    """
    self.vocab_size = vocab_size
    self.max_position_embeddings = max_position_embeddings
    self.d_model = d_model
    self.encoder_ffn_dim = encoder_ffn_dim
    self.encoder_layers = encoder_layers
    self.encoder_attention_heads = encoder_attention_heads
    self.decoder_ffn_dim = decoder_ffn_dim
    self.decoder_layers = decoder_layers
    self.decoder_attention_heads = decoder_attention_heads
    self.dropout = dropout
    self.attention_dropout = attention_dropout
    self.activation_dropout = activation_dropout
    self.activation_function = activation_function
    self.init_std = init_std
    self.encoder_layerdrop = encoder_layerdrop
    self.decoder_layerdrop = decoder_layerdrop
    self.classifier_dropout = classifier_dropout
    self.use_cache = use_cache
    self.num_hidden_layers = encoder_layers
    self.scale_embedding = scale_embedding  # scale factor will be sqrt(d_model) if True

    super().__init__(
        num_labels=num_labels,
        pad_token_id=pad_token_id,
        bos_token_id=bos_token_id,
        eos_token_id=eos_token_id,
        is_encoder_decoder=is_encoder_decoder,
        decoder_start_token_id=decoder_start_token_id,
        forced_eos_token_id=forced_eos_token_id,
        **kwargs,
    )

    # ensure backward compatibility for BART CNN models
    if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
        self.forced_bos_token_id = self.bos_token_id
        warnings.warn(
            f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
            "The config can simply be saved and uploaded again to be fixed."
        )

mindnlp.transformers.models.bart.modeling_bart.BART_PRETRAINED_MODEL_ARCHIVE_LIST = ['facebook/bart-large'] module-attribute

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM

Bases: BartPreTrainedModel

This class represents a Bart model for causal language modeling (LM). It is a subclass of BartPreTrainedModel.

BartForCausalLM is designed for generating text in an autoregressive manner, where the model predicts the next word in a sequence given the previous words. It consists of a decoder component that takes input_ids and attention_mask as inputs, and produces a sequence of predicted logits. The decoder can be configured with various options such as encoder_hidden_states, encoder_attention_mask, head_mask, cross_attn_head_mask, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, and return_dict.

The class provides methods for getting and setting the input and output embeddings, as well as getting and setting the decoder component. The forward method is the main method for generating text. It akes input_ids, attention_mask, and other optional arguments, and returns the predicted logits, along with other optional outputs such as loss, past_key_values, hidden_states, attentions, and cross_attentions.

The prepare_inputs_for_generation method is used to prepare inputs for text generation. It takes input_ids, past_key_values, attention_mask, use_cache, and other optional arguments, and returns a dictionary containing the prepared inputs.

The _reorder_cache method is a static method that is used to reorder the past_key_values cache during beam search.

Example
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
>>> model = BartForCausalLM.from_pretrained("facebook/bart-base", add_cross_attention=False)
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

This example demonstrates how to use the BartForCausalLM class for text generation. The model takes input_ids as input and generates predicted logits as output.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
class BartForCausalLM(BartPreTrainedModel):

    """
    This class represents a Bart model for causal language modeling (LM). It is a subclass of BartPreTrainedModel.

    BartForCausalLM is designed for generating text in an autoregressive manner,
    where the model predicts the next word in a sequence given the previous words.
    It consists of a decoder component that takes input_ids and attention_mask as inputs,
    and produces a sequence of predicted logits.
    The decoder can be configured with various options such as encoder_hidden_states, encoder_attention_mask, head_mask,
    cross_attn_head_mask, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states,
    and return_dict.

    The class provides methods for getting and setting the input and output embeddings,
    as well as getting and setting the decoder component.
    The forward method is the main method for generating text. It akes input_ids, attention_mask, and other optional
    arguments, and returns the predicted logits, along with other optional outputs such as loss,
    past_key_values, hidden_states, attentions, and cross_attentions.

    The prepare_inputs_for_generation method is used to prepare inputs for text generation. It takes input_ids,
    past_key_values, attention_mask, use_cache, and other optional arguments, and returns a dictionary containing
    the prepared inputs.

    The _reorder_cache method is a static method that is used to reorder the past_key_values cache during beam search.

    Example:
        ```python
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
        >>> model = BartForCausalLM.from_pretrained("facebook/bart-base", add_cross_attention=False)
        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)
        ```

    This example demonstrates how to use the BartForCausalLM class for text generation.
    The model takes input_ids as input and generates predicted logits as output.
    """
    _tied_weights_keys = ["lm_head.weight"]

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

        Args:
            self: The instance of BartForCausalLM.
            config (dict): The configuration parameters for the model.
                Must contain the necessary settings for the model initialization.

        Returns:
            None.

        Raises:
            AttributeError: If the provided configuration is missing required attributes.
            TypeError: If the configuration is not in the expected format.
        """
        config = copy.deepcopy(config)
        config.is_decoder = True
        config.is_encoder_decoder = False
        super().__init__(config)
        self.model = BartDecoderWrapper(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_input_embeddings(self):
        """
        Method to retrieve the input embeddings from the decoder of a BartForCausalLM model.

        Args:
            self: BartForCausalLM - The instance of BartForCausalLM class.
                This parameter represents the current instance of the BartForCausalLM class.

        Returns:
            embed_tokens:
                This method returns the input embeddings from the decoder of the BartForCausalLM model.

        Raises:
            None.
        """
        return self.model.decoder.embed_tokens

    def set_input_embeddings(self, value):
        """
        Set the input embeddings for the BartForCausalLM model.

        Args:
            self (BartForCausalLM): The instance of the BartForCausalLM class.
            value (torch.Tensor): The input embeddings to be set for the model.
                This should be a torch.Tensor representing the new input embeddings.

        Returns:
            None.

        Raises:
            None.
        """
        self.model.decoder.embed_tokens = value

    def get_output_embeddings(self):
        """Return the output embeddings of the BartForCausalLM model.

        Args:
            self (BartForCausalLM): The instance of the BartForCausalLM class.

        Returns:
            None.

        Raises:
            None.

        """
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        """
        Sets the output embeddings of the `BartForCausalLM` model.

        Args:
            self: An instance of the `BartForCausalLM` class.
            new_embeddings (torch.nn.Module): The new embeddings to be set as the output embeddings.
                This should be an instance of `torch.nn.Module` subclass, which represents the new embeddings
                to be used as output in the `BartForCausalLM` model. It is expected to have the same size as the
                existing embeddings.

        Returns:
            None.

        Raises:
            None.

        Note:
            This method replaces the existing output embeddings in the `BartForCausalLM` model with the provided
            new embeddings. It is useful when fine-tuning the model's output layer or updating the embeddings with
            pre-trained weights.
        """
        self.lm_head = new_embeddings

    def set_decoder(self, decoder):
        """
        Sets the decoder for the BartForCausalLM model.

        Args:
            self (BartForCausalLM): The instance of the BartForCausalLM class.
            decoder (nn.Module): The decoder module to be set for the model.

        Returns:
            None.

        Raises:
            None.

        Description:
            This method allows the user to set the decoder module for the BartForCausalLM model.
            The decoder module is responsible for generating the output sequence during the model's forward pass.

            The `self` parameter refers to the instance of the BartForCausalLM class on which the method is called.

            The `decoder` parameter is of type `nn.Module` and represents the decoder module to be set for the model.
            The decoder module should be compatible with the BartForCausalLM model architecture.

            Note that setting the decoder module will overwrite any previously set decoder module for the model.

        Example:
            ```python
            >>> model = BartForCausalLM()
            >>> decoder = nn.Linear(768, 1024)
            >>> model.set_decoder(decoder)
            ```
        """
        self.model.decoder = decoder

    def get_decoder(self):
        """
        This method returns the decoder component of the model.

        Args:
            self: An instance of the BartForCausalLM class.

        Returns:
            None

        Raises:
            No specific exceptions are raised by this method.
        """
        return self.model.decoder

    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        encoder_hidden_states: Optional[mindspore.Tensor] = None,
        encoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[List[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, CausalLMOutputWithCrossAttentions]:
        r"""
        Args:
            input_ids (`mindspore.Tensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

                Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
                [`PreTrainedTokenizer.__call__`] for details.

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states  (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                if the model is configured as a decoder.
            encoder_attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
                in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
            head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            cross_attn_head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        Returns:
            Union[Tuple, CausalLMOutputWithCrossAttentions]

        Example:
            ```python
            >>> from transformers import AutoTokenizer, BartForCausalLM
            ...
            >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
            >>> model = BartForCausalLM.from_pretrained("facebook/bart-base", add_cross_attention=False)
            >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
            >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
            >>> outputs = model(**inputs)
            ...
            >>> logits = outputs.logits
            >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
            >>> list(logits.shape) == expected_shape
            True
            ```
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
        outputs = self.model.decoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
            head_mask=head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        logits = self.lm_head(outputs[0])

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

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

        return CausalLMOutputWithCrossAttentions(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            cross_attentions=outputs.cross_attentions,
        )

    def prepare_inputs_for_generation(
        self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
    ):
        """
        Prepare the inputs for generation in the BartForCausalLM class.

        This method takes 5 parameters: self, input_ids, past_key_values, attention_mask, use_cache.

        Args:
            self: The instance of the BartForCausalLM class.
            input_ids (torch.Tensor): Tensor containing the input ids for the generation.
            past_key_values (tuple): Tuple of past key values for the generation. Default is None.
            attention_mask (torch.Tensor): Tensor containing the attention mask for the input ids.
                If None, a new attention mask with all ones will be created. Default is None.
            use_cache (bool): Whether or not to use past key values cache. Default is None.

        Returns:
            dict:
                A dictionary containing the prepared inputs for generation.

                - input_ids (torch.Tensor): The modified input ids.
                - attention_mask (torch.Tensor): The attention mask.
                - past_key_values (tuple): The past key values.
                - use_cache (bool): The use_cache flag.

        Raises:
            None.

        """
        # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
        if attention_mask is None:
            attention_mask = ops.ones(*input_ids.shape, input_ids)

        if past_key_values:
            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:]
        # first step, decoder_cached_states are empty
        return {
            "input_ids": input_ids,  # encoder_outputs is defined. input_ids not needed
            "attention_mask": attention_mask,
            "past_key_values": past_key_values,
            "use_cache": use_cache,
        }

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache for the BartForCausalLM model based on the specified beam index.

        Args:
            past_key_values (tuple): A tuple containing the past key-value states for each layer of the model.
                Each element in the tuple represents the past key-value states for a layer.
            beam_idx (torch.Tensor): A 1D tensor containing the indices of the beams to reorder the past states.

        Returns:
            None: This method does not return any value but modifies the 'past_key_values' in place.

        Raises:
            IndexError: If the 'beam_idx' tensor contains indices that are out of range for the past states.
            TypeError: If the input types are not as expected, this method may raise a TypeError.
        """
        reordered_past = ()
        for layer_past in past_key_values:
            reordered_past += (
                tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),
            )
        return reordered_past

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.__init__(config)

Initializes an instance of BartForCausalLM.

PARAMETER DESCRIPTION
self

The instance of BartForCausalLM.

config

The configuration parameters for the model. Must contain the necessary settings for the model initialization.

TYPE: dict

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
AttributeError

If the provided configuration is missing required attributes.

TypeError

If the configuration is not in the expected format.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
def __init__(self, config):
    """
    Initializes an instance of BartForCausalLM.

    Args:
        self: The instance of BartForCausalLM.
        config (dict): The configuration parameters for the model.
            Must contain the necessary settings for the model initialization.

    Returns:
        None.

    Raises:
        AttributeError: If the provided configuration is missing required attributes.
        TypeError: If the configuration is not in the expected format.
    """
    config = copy.deepcopy(config)
    config.is_decoder = True
    config.is_encoder_decoder = False
    super().__init__(config)
    self.model = BartDecoderWrapper(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.bart.modeling_bart.BartForCausalLM.forward(input_ids=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, head_mask=None, cross_attn_head_mask=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
input_ids

Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

Indices can be obtained using [AutoTokenizer]. See [PreTrainedTokenizer.encode] and [PreTrainedTokenizer.__call__] for details.

What are input IDs?

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

attention_mask

Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

  • 1 for tokens that are not masked,
  • 0 for tokens that are masked.

What are attention masks?

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

encoder_hidden_states

Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder.

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

encoder_attention_mask

Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in [0, 1]:

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

head_mask

Mask to nullify selected heads of the attention modules. Mask values selected in [0, 1]:

  • 1 indicates the head is not masked,
  • 0 indicates the head is masked.

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

cross_attn_head_mask

Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]:

  • 1 indicates the head is not masked,
  • 0 indicates the head is masked.

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

past_key_values

Tuple of tuple(mindspore.Tensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The two additional tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don't have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length).

TYPE: `tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True` DEFAULT: None

labels

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

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

use_cache

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

  • 1 for tokens that are not masked,
  • 0 for tokens that are masked.

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

output_attentions

Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

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

output_hidden_states

Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

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

return_dict

Whether or not to return a [~utils.ModelOutput] instead of a plain tuple.

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

RETURNS DESCRIPTION
Union[Tuple, CausalLMOutputWithCrossAttentions]

Union[Tuple, CausalLMOutputWithCrossAttentions]

Example
>>> from transformers import AutoTokenizer, BartForCausalLM
...
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
>>> model = BartForCausalLM.from_pretrained("facebook/bart-base", add_cross_attention=False)
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
...
>>> logits = outputs.logits
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
>>> list(logits.shape) == expected_shape
True
Source code in mindnlp/transformers/models/bart/modeling_bart.py
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    encoder_hidden_states: Optional[mindspore.Tensor] = None,
    encoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[List[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, CausalLMOutputWithCrossAttentions]:
    r"""
    Args:
        input_ids (`mindspore.Tensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
            provide it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        encoder_hidden_states  (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
            if the model is configured as a decoder.
        encoder_attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
            in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
        head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        cross_attn_head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
            shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
            tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
            cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
            that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
            all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
            (see `past_key_values`).

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under
            returned tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
            for more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

    Returns:
        Union[Tuple, CausalLMOutputWithCrossAttentions]

    Example:
        ```python
        >>> from transformers import AutoTokenizer, BartForCausalLM
        ...
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
        >>> model = BartForCausalLM.from_pretrained("facebook/bart-base", add_cross_attention=False)
        >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)
        ...
        >>> logits = outputs.logits
        >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
        >>> list(logits.shape) == expected_shape
        True
        ```
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
    outputs = self.model.decoder(
        input_ids=input_ids,
        attention_mask=attention_mask,
        encoder_hidden_states=encoder_hidden_states,
        encoder_attention_mask=encoder_attention_mask,
        head_mask=head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        past_key_values=past_key_values,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    logits = self.lm_head(outputs[0])

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

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

    return CausalLMOutputWithCrossAttentions(
        loss=loss,
        logits=logits,
        past_key_values=outputs.past_key_values,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
        cross_attentions=outputs.cross_attentions,
    )

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.get_decoder()

This method returns the decoder component of the model.

PARAMETER DESCRIPTION
self

An instance of the BartForCausalLM class.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
def get_decoder(self):
    """
    This method returns the decoder component of the model.

    Args:
        self: An instance of the BartForCausalLM class.

    Returns:
        None

    Raises:
        No specific exceptions are raised by this method.
    """
    return self.model.decoder

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.get_input_embeddings()

Method to retrieve the input embeddings from the decoder of a BartForCausalLM model.

PARAMETER DESCRIPTION
self

BartForCausalLM - The instance of BartForCausalLM class. This parameter represents the current instance of the BartForCausalLM class.

RETURNS DESCRIPTION
embed_tokens

This method returns the input embeddings from the decoder of the BartForCausalLM model.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from the decoder of a BartForCausalLM model.

    Args:
        self: BartForCausalLM - The instance of BartForCausalLM class.
            This parameter represents the current instance of the BartForCausalLM class.

    Returns:
        embed_tokens:
            This method returns the input embeddings from the decoder of the BartForCausalLM model.

    Raises:
        None.
    """
    return self.model.decoder.embed_tokens

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.get_output_embeddings()

Return the output embeddings of the BartForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BartForCausalLM class.

TYPE: BartForCausalLM

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
def get_output_embeddings(self):
    """Return the output embeddings of the BartForCausalLM model.

    Args:
        self (BartForCausalLM): The instance of the BartForCausalLM class.

    Returns:
        None.

    Raises:
        None.

    """
    return self.lm_head

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.prepare_inputs_for_generation(input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs)

Prepare the inputs for generation in the BartForCausalLM class.

This method takes 5 parameters: self, input_ids, past_key_values, attention_mask, use_cache.

PARAMETER DESCRIPTION
self

The instance of the BartForCausalLM class.

input_ids

Tensor containing the input ids for the generation.

TYPE: Tensor

past_key_values

Tuple of past key values for the generation. Default is None.

TYPE: tuple DEFAULT: None

attention_mask

Tensor containing the attention mask for the input ids. If None, a new attention mask with all ones will be created. Default is None.

TYPE: Tensor DEFAULT: None

use_cache

Whether or not to use past key values cache. Default is None.

TYPE: bool DEFAULT: None

RETURNS DESCRIPTION
dict

A dictionary containing the prepared inputs for generation.

  • input_ids (torch.Tensor): The modified input ids.
  • attention_mask (torch.Tensor): The attention mask.
  • past_key_values (tuple): The past key values.
  • use_cache (bool): The use_cache flag.
Source code in mindnlp/transformers/models/bart/modeling_bart.py
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
def prepare_inputs_for_generation(
    self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
):
    """
    Prepare the inputs for generation in the BartForCausalLM class.

    This method takes 5 parameters: self, input_ids, past_key_values, attention_mask, use_cache.

    Args:
        self: The instance of the BartForCausalLM class.
        input_ids (torch.Tensor): Tensor containing the input ids for the generation.
        past_key_values (tuple): Tuple of past key values for the generation. Default is None.
        attention_mask (torch.Tensor): Tensor containing the attention mask for the input ids.
            If None, a new attention mask with all ones will be created. Default is None.
        use_cache (bool): Whether or not to use past key values cache. Default is None.

    Returns:
        dict:
            A dictionary containing the prepared inputs for generation.

            - input_ids (torch.Tensor): The modified input ids.
            - attention_mask (torch.Tensor): The attention mask.
            - past_key_values (tuple): The past key values.
            - use_cache (bool): The use_cache flag.

    Raises:
        None.

    """
    # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
    if attention_mask is None:
        attention_mask = ops.ones(*input_ids.shape, input_ids)

    if past_key_values:
        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:]
    # first step, decoder_cached_states are empty
    return {
        "input_ids": input_ids,  # encoder_outputs is defined. input_ids not needed
        "attention_mask": attention_mask,
        "past_key_values": past_key_values,
        "use_cache": use_cache,
    }

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.set_decoder(decoder)

Sets the decoder for the BartForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BartForCausalLM class.

TYPE: BartForCausalLM

decoder

The decoder module to be set for the model.

TYPE: Module

RETURNS DESCRIPTION

None.

Description

This method allows the user to set the decoder module for the BartForCausalLM model. The decoder module is responsible for generating the output sequence during the model's forward pass.

The self parameter refers to the instance of the BartForCausalLM class on which the method is called.

The decoder parameter is of type nn.Module and represents the decoder module to be set for the model. The decoder module should be compatible with the BartForCausalLM model architecture.

Note that setting the decoder module will overwrite any previously set decoder module for the model.

Example
>>> model = BartForCausalLM()
>>> decoder = nn.Linear(768, 1024)
>>> model.set_decoder(decoder)
Source code in mindnlp/transformers/models/bart/modeling_bart.py
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
def set_decoder(self, decoder):
    """
    Sets the decoder for the BartForCausalLM model.

    Args:
        self (BartForCausalLM): The instance of the BartForCausalLM class.
        decoder (nn.Module): The decoder module to be set for the model.

    Returns:
        None.

    Raises:
        None.

    Description:
        This method allows the user to set the decoder module for the BartForCausalLM model.
        The decoder module is responsible for generating the output sequence during the model's forward pass.

        The `self` parameter refers to the instance of the BartForCausalLM class on which the method is called.

        The `decoder` parameter is of type `nn.Module` and represents the decoder module to be set for the model.
        The decoder module should be compatible with the BartForCausalLM model architecture.

        Note that setting the decoder module will overwrite any previously set decoder module for the model.

    Example:
        ```python
        >>> model = BartForCausalLM()
        >>> decoder = nn.Linear(768, 1024)
        >>> model.set_decoder(decoder)
        ```
    """
    self.model.decoder = decoder

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.set_input_embeddings(value)

Set the input embeddings for the BartForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BartForCausalLM class.

TYPE: BartForCausalLM

value

The input embeddings to be set for the model. This should be a torch.Tensor representing the new input embeddings.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the BartForCausalLM model.

    Args:
        self (BartForCausalLM): The instance of the BartForCausalLM class.
        value (torch.Tensor): The input embeddings to be set for the model.
            This should be a torch.Tensor representing the new input embeddings.

    Returns:
        None.

    Raises:
        None.
    """
    self.model.decoder.embed_tokens = value

mindnlp.transformers.models.bart.modeling_bart.BartForCausalLM.set_output_embeddings(new_embeddings)

Sets the output embeddings of the BartForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the BartForCausalLM class.

new_embeddings

The new embeddings to be set as the output embeddings. This should be an instance of torch.nn.Module subclass, which represents the new embeddings to be used as output in the BartForCausalLM model. It is expected to have the same size as the existing embeddings.

TYPE: Module

RETURNS DESCRIPTION

None.

Note

This method replaces the existing output embeddings in the BartForCausalLM model with the provided new embeddings. It is useful when fine-tuning the model's output layer or updating the embeddings with pre-trained weights.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
def set_output_embeddings(self, new_embeddings):
    """
    Sets the output embeddings of the `BartForCausalLM` model.

    Args:
        self: An instance of the `BartForCausalLM` class.
        new_embeddings (torch.nn.Module): The new embeddings to be set as the output embeddings.
            This should be an instance of `torch.nn.Module` subclass, which represents the new embeddings
            to be used as output in the `BartForCausalLM` model. It is expected to have the same size as the
            existing embeddings.

    Returns:
        None.

    Raises:
        None.

    Note:
        This method replaces the existing output embeddings in the `BartForCausalLM` model with the provided
        new embeddings. It is useful when fine-tuning the model's output layer or updating the embeddings with
        pre-trained weights.
    """
    self.lm_head = new_embeddings

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration

Bases: BartPreTrainedModel

This class represents a BART model for conditional text generation. It inherits from BartPreTrainedModel and provides methods for model initialization, encoder and decoder retrieval, resizing token embeddings, output embeddings, model forwardion, preparing inputs for generation, preparing decoder input ids from labels, and reordering cache. The class includes methods for initializing the model, retrieving encoder and decoder, resizing token embeddings, forwarding the model, preparing inputs for text generation, and reordering cache for efficient generation. Additionally, it provides methods for setting and getting output embeddings and resizing final logits bias. The class also includes a method for preparing decoder input ids from labels for masked language modeling.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
class BartForConditionalGeneration(BartPreTrainedModel):

    """
    This class represents a BART model for conditional text generation.
    It inherits from BartPreTrainedModel and provides methods for model initialization, encoder and decoder retrieval,
    resizing token embeddings, output embeddings, model forwardion, preparing inputs for generation,
    preparing decoder input ids from labels, and reordering cache.
    The class includes methods for initializing the model, retrieving encoder and decoder, resizing token embeddings,
    forwarding the model, preparing inputs for text generation, and reordering cache for efficient generation.
    Additionally, it provides methods for setting and getting output embeddings and resizing final logits bias.
    The class also includes a method for preparing decoder input ids from labels for masked language modeling.
    """
    base_model_prefix = "model"
    _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
    # _keys_to_ignore_on_load_missing = ["final_logits_bias"]

    def __init__(self, config: BartConfig):
        """Initialize a BART model for conditional generation.

        Args:
            self (BartForConditionalGeneration): The object instance of the BartForConditionalGeneration class.
            config (BartConfig): The configuration object for the BART model.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.model = BartModel(config)
        self.final_logits_bias = ops.zeros(1, self.model.shared.num_embeddings)
        self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)

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

    def get_encoder(self):
        """
        Method to retrieve the encoder from the BartForConditionalGeneration model.

        Args:
            self: Instance of the BartForConditionalGeneration class.
                This parameter refers to the current instance of the class.

        Returns:
            encoder:
                Returns the encoder obtained from the model.

        Raises:
            None
        """
        return self.model.get_encoder()

    def get_decoder(self):
        """
        Method to retrieve the decoder module from the BartForConditionalGeneration model.

        Args:
            self: An instance of the BartForConditionalGeneration class.

        Returns:
            decoder: Returns the decoder module from the BartForConditionalGeneration model.

        Raises:
            None.
        """
        return self.model.get_decoder()

    def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
        """
        Resize the token embeddings for the BartForConditionalGeneration model.

        Args:
            self: The instance of the BartForConditionalGeneration class.
            new_num_tokens (int): The new number of tokens to resize the embeddings to.
                Specifies the desired number of tokens for the embeddings.
            pad_to_multiple_of (Optional[int]): The optional value to pad the resize to a multiple of.
                If provided, the new embeddings size will be padded to the nearest multiple of this value.

        Returns:
            nn.Embedding: The resized token embeddings as an instance of nn.Embedding.
                Represents the updated embeddings after resizing.

        Raises:
            None.
        """
        new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
        self._resize_final_logits_bias(new_embeddings.weight.shape[0])
        return new_embeddings

    def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
        '''
        Resize the final logits bias to accommodate a different number of tokens.

        Args:
            self (BartForConditionalGeneration): The instance of the BartForConditionalGeneration class.
            new_num_tokens (int):
                The new number of tokens to resize the final logits bias to. It should be a positive integer.

        Returns:
            None: The method modifies the final_logits_bias attribute of the BartForConditionalGeneration instance in place.

        Raises:
            ValueError: If new_num_tokens is not a positive integer.
        '''
        old_num_tokens = self.final_logits_bias.shape[-1]
        if new_num_tokens <= old_num_tokens:
            new_bias = self.final_logits_bias[:, :new_num_tokens]
        else:
            extra_bias = ops.zeros(1, new_num_tokens - old_num_tokens)
            new_bias = ops.cat([self.final_logits_bias, extra_bias], dim=1)
        self.final_logits_bias = new_bias

    def get_output_embeddings(self):
        """
        Method to retrieve the output embeddings from the BartForConditionalGeneration model.

        Args:
            self: An instance of the BartForConditionalGeneration class.
                This parameter is required to access the model's output embeddings.
                It should always be passed as the first argument when calling this method.

        Returns:
            lm_head: This method returns the lm_head attribute of the BartForConditionalGeneration instance.
                The lm_head attribute represents the output embeddings of the model.

        Raises:
            None.
        """
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        """
        Method:
            set_output_embeddings

        Description:
            Sets the output embeddings for the BartForConditionalGeneration model.

        Args:
            self (BartForConditionalGeneration): The instance of the BartForConditionalGeneration class.
            new_embeddings (Tensor): The new embeddings to be set as the output embeddings for the model.

        Returns:
            None.

        Raises:
            TypeError: If the new_embeddings parameter is not of type Tensor.
            ValueError: If the new_embeddings parameter is empty or invalid.
        """
        self.lm_head = new_embeddings

    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        decoder_input_ids: Optional[mindspore.Tensor] = None,
        decoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        decoder_head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        encoder_outputs: Optional[List[mindspore.Tensor]] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        decoder_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, Seq2SeqLMOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:
            Union[Tuple, Seq2SeqLMOutput]
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if labels is not None:
            if use_cache:
                logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
            use_cache = False
            if decoder_input_ids is None and decoder_inputs_embeds is None:
                decoder_input_ids = shift_tokens_right(
                    labels, self.config.pad_token_id, self.config.decoder_start_token_id
                )

        outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            decoder_input_ids=decoder_input_ids,
            encoder_outputs=encoder_outputs,
            decoder_attention_mask=decoder_attention_mask,
            head_mask=head_mask,
            decoder_head_mask=decoder_head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            decoder_inputs_embeds=decoder_inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        lm_logits = self.lm_head(outputs[0])
        lm_logits = lm_logits + self.final_logits_bias

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

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

        return Seq2SeqLMOutput(
            loss=masked_lm_loss,
            logits=lm_logits,
            past_key_values=outputs.past_key_values,
            decoder_hidden_states=outputs.decoder_hidden_states,
            decoder_attentions=outputs.decoder_attentions,
            cross_attentions=outputs.cross_attentions,
            encoder_last_hidden_state=outputs.encoder_last_hidden_state,
            encoder_hidden_states=outputs.encoder_hidden_states,
            encoder_attentions=outputs.encoder_attentions,
        )

    def prepare_inputs_for_generation(
        self,
        decoder_input_ids,
        past_key_values=None,
        attention_mask=None,
        decoder_attention_mask=None,
        head_mask=None,
        decoder_head_mask=None,
        cross_attn_head_mask=None,
        use_cache=None,
        encoder_outputs=None,
        **kwargs,
    ):
        """
        Prepare the inputs for generation in the BartForConditionalGeneration class.

        Args:
            self (BartForConditionalGeneration): The instance of the BartForConditionalGeneration class.
            decoder_input_ids (torch.Tensor): The input tensor representing the decoder input IDs.
            past_key_values (Tuple[torch.Tensor]): Optional. The past key values for generating the output. Default is None.
            attention_mask (torch.Tensor): Optional. The attention mask tensor for the encoder. Default is None.
            decoder_attention_mask (torch.Tensor): Optional. The attention mask tensor for the decoder. Default is None.
            head_mask (torch.Tensor): Optional. The mask tensor for the encoder's attention heads. Default is None.
            decoder_head_mask (torch.Tensor): Optional. The mask tensor for the decoder's attention heads. Default is None.
            cross_attn_head_mask (torch.Tensor): Optional. The mask tensor for the cross-attention heads. Default is None.
            use_cache (bool): Optional. Whether to use cache for faster decoding. Default is None.
            encoder_outputs (torch.Tensor): Optional. The tensor representing the encoder outputs. Default is None.

        Returns:
            dict: A dictionary containing the prepared inputs for generation.
                The dictionary has the following keys:

                - 'input_ids' (None): Represents the input IDs, which are set to None.
                - 'encoder_outputs' (torch.Tensor): Represents the encoder outputs.
                - 'past_key_values' (Tuple[torch.Tensor]): Represents the past key values for generating the output.
                - 'decoder_input_ids' (torch.Tensor): Represents the decoder input IDs after removing the prefix.
                - 'attention_mask' (torch.Tensor): Represents the attention mask tensor for the encoder.
                - 'decoder_attention_mask' (torch.Tensor): Represents the attention mask tensor for the decoder.
                - 'head_mask' (torch.Tensor): Represents the mask tensor for the encoder's attention heads.
                - 'decoder_head_mask' (torch.Tensor): Represents the mask tensor for the decoder's attention heads.
                - 'cross_attn_head_mask' (torch.Tensor): Represents the mask tensor for the cross-attention heads.
                - 'use_cache' (bool): Represents whether to use cache for faster decoding.

        Raises:
            None.
        """
        # cut decoder_input_ids if past_key_values is used
        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 decoder_input_ids.shape[1] > past_length:
                remove_prefix_length = past_length
            else:
                # Default to old behavior: keep only final ID
                remove_prefix_length = decoder_input_ids.shape[1] - 1

            decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]

        return {
            "input_ids": None,  # encoder_outputs is defined. input_ids not needed
            "encoder_outputs": encoder_outputs,
            "past_key_values": past_key_values,
            "decoder_input_ids": decoder_input_ids,
            "attention_mask": attention_mask,
            "decoder_attention_mask": decoder_attention_mask,
            "head_mask": head_mask,
            "decoder_head_mask": decoder_head_mask,
            "cross_attn_head_mask": cross_attn_head_mask,
            "use_cache": use_cache,  # change this to avoid caching (presumably for debugging)
        }

    def prepare_decoder_input_ids_from_labels(self, labels: mindspore.Tensor):
        """
        Prepare decoder input IDs from labels.

        This method takes in two parameters: self, labels.
        The 'self' parameter refers to the current instance of the 'BartForConditionalGeneration' class,
        while the 'labels' parameter is a tensor containing the input labels.

        Args:
            self (BartForConditionalGeneration): The current instance of the BartForConditionalGeneration class.
            labels (mindspore.Tensor): A tensor containing the input labels.

        Returns:
            None

        Raises:
            None
        """
        return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache for the BartForConditionalGeneration model based on the provided beam index.

        Args:
            past_key_values (tuple): A tuple containing the past key and value states for each layer of the model.
                The states are used to generate the next token probabilities.
            beam_idx (torch.Tensor): A tensor representing the indices of the beams to reorder the cache.

        Returns:
            None: This method does not return a value but modifies the past_key_values in place
                by reordering the cache based on the beam index.

        Raises:
            None.
        """
        reordered_past = ()
        for layer_past in past_key_values:
            # cached cross_attention states don't have to be reordered -> they are always the same
            reordered_past += (
                tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2])
                + layer_past[2:],
            )
        return reordered_past

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.__init__(config)

Initialize a BART model for conditional generation.

PARAMETER DESCRIPTION
self

The object instance of the BartForConditionalGeneration class.

TYPE: BartForConditionalGeneration

config

The configuration object for the BART model.

TYPE: BartConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
def __init__(self, config: BartConfig):
    """Initialize a BART model for conditional generation.

    Args:
        self (BartForConditionalGeneration): The object instance of the BartForConditionalGeneration class.
        config (BartConfig): The configuration object for the BART model.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.model = BartModel(config)
    self.final_logits_bias = ops.zeros(1, self.model.shared.num_embeddings)
    self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)

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

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.forward(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_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 masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].

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

RETURNS DESCRIPTION
Union[Tuple, Seq2SeqLMOutput]

Union[Tuple, Seq2SeqLMOutput]

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    decoder_input_ids: Optional[mindspore.Tensor] = None,
    decoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    decoder_head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    encoder_outputs: Optional[List[mindspore.Tensor]] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    decoder_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, Seq2SeqLMOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

    Returns:
        Union[Tuple, Seq2SeqLMOutput]
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    if labels is not None:
        if use_cache:
            logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
        use_cache = False
        if decoder_input_ids is None and decoder_inputs_embeds is None:
            decoder_input_ids = shift_tokens_right(
                labels, self.config.pad_token_id, self.config.decoder_start_token_id
            )

    outputs = self.model(
        input_ids,
        attention_mask=attention_mask,
        decoder_input_ids=decoder_input_ids,
        encoder_outputs=encoder_outputs,
        decoder_attention_mask=decoder_attention_mask,
        head_mask=head_mask,
        decoder_head_mask=decoder_head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        past_key_values=past_key_values,
        inputs_embeds=inputs_embeds,
        decoder_inputs_embeds=decoder_inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    lm_logits = self.lm_head(outputs[0])
    lm_logits = lm_logits + self.final_logits_bias

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

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

    return Seq2SeqLMOutput(
        loss=masked_lm_loss,
        logits=lm_logits,
        past_key_values=outputs.past_key_values,
        decoder_hidden_states=outputs.decoder_hidden_states,
        decoder_attentions=outputs.decoder_attentions,
        cross_attentions=outputs.cross_attentions,
        encoder_last_hidden_state=outputs.encoder_last_hidden_state,
        encoder_hidden_states=outputs.encoder_hidden_states,
        encoder_attentions=outputs.encoder_attentions,
    )

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.get_decoder()

Method to retrieve the decoder module from the BartForConditionalGeneration model.

PARAMETER DESCRIPTION
self

An instance of the BartForConditionalGeneration class.

RETURNS DESCRIPTION
decoder

Returns the decoder module from the BartForConditionalGeneration model.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def get_decoder(self):
    """
    Method to retrieve the decoder module from the BartForConditionalGeneration model.

    Args:
        self: An instance of the BartForConditionalGeneration class.

    Returns:
        decoder: Returns the decoder module from the BartForConditionalGeneration model.

    Raises:
        None.
    """
    return self.model.get_decoder()

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.get_encoder()

Method to retrieve the encoder from the BartForConditionalGeneration model.

PARAMETER DESCRIPTION
self

Instance of the BartForConditionalGeneration class. This parameter refers to the current instance of the class.

RETURNS DESCRIPTION
encoder

Returns the encoder obtained from the model.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
def get_encoder(self):
    """
    Method to retrieve the encoder from the BartForConditionalGeneration model.

    Args:
        self: Instance of the BartForConditionalGeneration class.
            This parameter refers to the current instance of the class.

    Returns:
        encoder:
            Returns the encoder obtained from the model.

    Raises:
        None
    """
    return self.model.get_encoder()

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.get_output_embeddings()

Method to retrieve the output embeddings from the BartForConditionalGeneration model.

PARAMETER DESCRIPTION
self

An instance of the BartForConditionalGeneration class. This parameter is required to access the model's output embeddings. It should always be passed as the first argument when calling this method.

RETURNS DESCRIPTION
lm_head

This method returns the lm_head attribute of the BartForConditionalGeneration instance. The lm_head attribute represents the output embeddings of the model.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
def get_output_embeddings(self):
    """
    Method to retrieve the output embeddings from the BartForConditionalGeneration model.

    Args:
        self: An instance of the BartForConditionalGeneration class.
            This parameter is required to access the model's output embeddings.
            It should always be passed as the first argument when calling this method.

    Returns:
        lm_head: This method returns the lm_head attribute of the BartForConditionalGeneration instance.
            The lm_head attribute represents the output embeddings of the model.

    Raises:
        None.
    """
    return self.lm_head

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.prepare_decoder_input_ids_from_labels(labels)

Prepare decoder input IDs from labels.

This method takes in two parameters: self, labels. The 'self' parameter refers to the current instance of the 'BartForConditionalGeneration' class, while the 'labels' parameter is a tensor containing the input labels.

PARAMETER DESCRIPTION
self

The current instance of the BartForConditionalGeneration class.

TYPE: BartForConditionalGeneration

labels

A tensor containing the input labels.

TYPE: Tensor

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
def prepare_decoder_input_ids_from_labels(self, labels: mindspore.Tensor):
    """
    Prepare decoder input IDs from labels.

    This method takes in two parameters: self, labels.
    The 'self' parameter refers to the current instance of the 'BartForConditionalGeneration' class,
    while the 'labels' parameter is a tensor containing the input labels.

    Args:
        self (BartForConditionalGeneration): The current instance of the BartForConditionalGeneration class.
        labels (mindspore.Tensor): A tensor containing the input labels.

    Returns:
        None

    Raises:
        None
    """
    return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.prepare_inputs_for_generation(decoder_input_ids, past_key_values=None, attention_mask=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, use_cache=None, encoder_outputs=None, **kwargs)

Prepare the inputs for generation in the BartForConditionalGeneration class.

PARAMETER DESCRIPTION
self

The instance of the BartForConditionalGeneration class.

TYPE: BartForConditionalGeneration

decoder_input_ids

The input tensor representing the decoder input IDs.

TYPE: Tensor

past_key_values

Optional. The past key values for generating the output. Default is None.

TYPE: Tuple[Tensor] DEFAULT: None

attention_mask

Optional. The attention mask tensor for the encoder. Default is None.

TYPE: Tensor DEFAULT: None

decoder_attention_mask

Optional. The attention mask tensor for the decoder. Default is None.

TYPE: Tensor DEFAULT: None

head_mask

Optional. The mask tensor for the encoder's attention heads. Default is None.

TYPE: Tensor DEFAULT: None

decoder_head_mask

Optional. The mask tensor for the decoder's attention heads. Default is None.

TYPE: Tensor DEFAULT: None

cross_attn_head_mask

Optional. The mask tensor for the cross-attention heads. Default is None.

TYPE: Tensor DEFAULT: None

use_cache

Optional. Whether to use cache for faster decoding. Default is None.

TYPE: bool DEFAULT: None

encoder_outputs

Optional. The tensor representing the encoder outputs. Default is None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
dict

A dictionary containing the prepared inputs for generation. The dictionary has the following keys:

  • 'input_ids' (None): Represents the input IDs, which are set to None.
  • 'encoder_outputs' (torch.Tensor): Represents the encoder outputs.
  • 'past_key_values' (Tuple[torch.Tensor]): Represents the past key values for generating the output.
  • 'decoder_input_ids' (torch.Tensor): Represents the decoder input IDs after removing the prefix.
  • 'attention_mask' (torch.Tensor): Represents the attention mask tensor for the encoder.
  • 'decoder_attention_mask' (torch.Tensor): Represents the attention mask tensor for the decoder.
  • 'head_mask' (torch.Tensor): Represents the mask tensor for the encoder's attention heads.
  • 'decoder_head_mask' (torch.Tensor): Represents the mask tensor for the decoder's attention heads.
  • 'cross_attn_head_mask' (torch.Tensor): Represents the mask tensor for the cross-attention heads.
  • 'use_cache' (bool): Represents whether to use cache for faster decoding.
Source code in mindnlp/transformers/models/bart/modeling_bart.py
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
def prepare_inputs_for_generation(
    self,
    decoder_input_ids,
    past_key_values=None,
    attention_mask=None,
    decoder_attention_mask=None,
    head_mask=None,
    decoder_head_mask=None,
    cross_attn_head_mask=None,
    use_cache=None,
    encoder_outputs=None,
    **kwargs,
):
    """
    Prepare the inputs for generation in the BartForConditionalGeneration class.

    Args:
        self (BartForConditionalGeneration): The instance of the BartForConditionalGeneration class.
        decoder_input_ids (torch.Tensor): The input tensor representing the decoder input IDs.
        past_key_values (Tuple[torch.Tensor]): Optional. The past key values for generating the output. Default is None.
        attention_mask (torch.Tensor): Optional. The attention mask tensor for the encoder. Default is None.
        decoder_attention_mask (torch.Tensor): Optional. The attention mask tensor for the decoder. Default is None.
        head_mask (torch.Tensor): Optional. The mask tensor for the encoder's attention heads. Default is None.
        decoder_head_mask (torch.Tensor): Optional. The mask tensor for the decoder's attention heads. Default is None.
        cross_attn_head_mask (torch.Tensor): Optional. The mask tensor for the cross-attention heads. Default is None.
        use_cache (bool): Optional. Whether to use cache for faster decoding. Default is None.
        encoder_outputs (torch.Tensor): Optional. The tensor representing the encoder outputs. Default is None.

    Returns:
        dict: A dictionary containing the prepared inputs for generation.
            The dictionary has the following keys:

            - 'input_ids' (None): Represents the input IDs, which are set to None.
            - 'encoder_outputs' (torch.Tensor): Represents the encoder outputs.
            - 'past_key_values' (Tuple[torch.Tensor]): Represents the past key values for generating the output.
            - 'decoder_input_ids' (torch.Tensor): Represents the decoder input IDs after removing the prefix.
            - 'attention_mask' (torch.Tensor): Represents the attention mask tensor for the encoder.
            - 'decoder_attention_mask' (torch.Tensor): Represents the attention mask tensor for the decoder.
            - 'head_mask' (torch.Tensor): Represents the mask tensor for the encoder's attention heads.
            - 'decoder_head_mask' (torch.Tensor): Represents the mask tensor for the decoder's attention heads.
            - 'cross_attn_head_mask' (torch.Tensor): Represents the mask tensor for the cross-attention heads.
            - 'use_cache' (bool): Represents whether to use cache for faster decoding.

    Raises:
        None.
    """
    # cut decoder_input_ids if past_key_values is used
    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 decoder_input_ids.shape[1] > past_length:
            remove_prefix_length = past_length
        else:
            # Default to old behavior: keep only final ID
            remove_prefix_length = decoder_input_ids.shape[1] - 1

        decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]

    return {
        "input_ids": None,  # encoder_outputs is defined. input_ids not needed
        "encoder_outputs": encoder_outputs,
        "past_key_values": past_key_values,
        "decoder_input_ids": decoder_input_ids,
        "attention_mask": attention_mask,
        "decoder_attention_mask": decoder_attention_mask,
        "head_mask": head_mask,
        "decoder_head_mask": decoder_head_mask,
        "cross_attn_head_mask": cross_attn_head_mask,
        "use_cache": use_cache,  # change this to avoid caching (presumably for debugging)
    }

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.resize_token_embeddings(new_num_tokens, pad_to_multiple_of=None)

Resize the token embeddings for the BartForConditionalGeneration model.

PARAMETER DESCRIPTION
self

The instance of the BartForConditionalGeneration class.

new_num_tokens

The new number of tokens to resize the embeddings to. Specifies the desired number of tokens for the embeddings.

TYPE: int

pad_to_multiple_of

The optional value to pad the resize to a multiple of. If provided, the new embeddings size will be padded to the nearest multiple of this value.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION
Embedding

nn.Embedding: The resized token embeddings as an instance of nn.Embedding. Represents the updated embeddings after resizing.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
    """
    Resize the token embeddings for the BartForConditionalGeneration model.

    Args:
        self: The instance of the BartForConditionalGeneration class.
        new_num_tokens (int): The new number of tokens to resize the embeddings to.
            Specifies the desired number of tokens for the embeddings.
        pad_to_multiple_of (Optional[int]): The optional value to pad the resize to a multiple of.
            If provided, the new embeddings size will be padded to the nearest multiple of this value.

    Returns:
        nn.Embedding: The resized token embeddings as an instance of nn.Embedding.
            Represents the updated embeddings after resizing.

    Raises:
        None.
    """
    new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
    self._resize_final_logits_bias(new_embeddings.weight.shape[0])
    return new_embeddings

mindnlp.transformers.models.bart.modeling_bart.BartForConditionalGeneration.set_output_embeddings(new_embeddings)

Method

set_output_embeddings

Description

Sets the output embeddings for the BartForConditionalGeneration model.

PARAMETER DESCRIPTION
self

The instance of the BartForConditionalGeneration class.

TYPE: BartForConditionalGeneration

new_embeddings

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

TYPE: Tensor

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the new_embeddings parameter is not of type Tensor.

ValueError

If the new_embeddings parameter is empty or invalid.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
def set_output_embeddings(self, new_embeddings):
    """
    Method:
        set_output_embeddings

    Description:
        Sets the output embeddings for the BartForConditionalGeneration model.

    Args:
        self (BartForConditionalGeneration): The instance of the BartForConditionalGeneration class.
        new_embeddings (Tensor): The new embeddings to be set as the output embeddings for the model.

    Returns:
        None.

    Raises:
        TypeError: If the new_embeddings parameter is not of type Tensor.
        ValueError: If the new_embeddings parameter is empty or invalid.
    """
    self.lm_head = new_embeddings

mindnlp.transformers.models.bart.modeling_bart.BartForQuestionAnswering

Bases: BartPreTrainedModel

This class represents a BART model for question answering tasks. It inherits from the BartPreTrainedModel class.

BARTForQuestionAnswering is a fine-tuned version of the BART model, specifically designed for question answering tasks. It takes in input sequences and returns the predicted start and end positions of the answer span within the input sequence.

The BARTForQuestionAnswering class contains the following methods:

  • init(self, config): Initializes the BARTForQuestionAnswering model with the provided configuration.
  • forward(self, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, head_mask, decoder_head_mask, cross_attn_head_mask, encoder_outputs, start_positions, end_positions, inputs_embeds, decoder_inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict): forwards the BART model for question answering and returns the predicted start and end positions of the answer span.

The forward method takes the following parameters:

  • input_ids (mindspore.Tensor): The input token IDs.
  • attention_mask (Optional[mindspore.Tensor]): The attention mask tensor.
  • decoder_input_ids (Optional[mindspore.Tensor]): The decoder input token IDs.
  • decoder_attention_mask (Optional[mindspore.Tensor]): The decoder attention mask tensor.
  • head_mask (Optional[mindspore.Tensor]): The attention head mask tensor.
  • decoder_head_mask (Optional[mindspore.Tensor]): The decoder attention head mask tensor.
  • cross_attn_head_mask (Optional[mindspore.Tensor]): The cross-attention head mask tensor.
  • encoder_outputs (Optional[List[mindspore.Tensor]]): The encoder outputs tensor.
  • start_positions (Optional[mindspore.Tensor]): The labels for the start positions of the answer span.
  • end_positions (Optional[mindspore.Tensor]): The labels for the end positions of the answer span.
  • inputs_embeds (Optional[mindspore.Tensor]): The embedded input tensor.
  • decoder_inputs_embeds (Optional[mindspore.Tensor]): The embedded decoder input tensor.
  • use_cache (Optional[bool]): Whether to use cache.
  • output_attentions (Optional[bool]): Whether to output attentions.
  • output_hidden_states (Optional[bool]): Whether to output hidden states.
  • return_dict (Optional[bool]): Whether to return a Seq2SeqQuestionAnsweringModelOutput object.

The forward method returns a Seq2SeqQuestionAnsweringModelOutput object that contains the following attributes:

  • loss (Optional[mindspore.Tensor]): The total loss.
  • start_logits (mindspore.Tensor): The predicted start logits.
  • end_logits (mindspore.Tensor): The predicted end logits.
  • past_key_values (Optional[mindspore.Tensor]): The past key values.
  • decoder_hidden_states (Optional[mindspore.Tensor]): The decoder hidden states.
  • decoder_attentions (Optional[mindspore.Tensor]): The decoder attentions.
  • cross_attentions (Optional[mindspore.Tensor]): The cross attentions.
  • encoder_last_hidden_state (Optional[mindspore.Tensor]): The encoder last hidden state.
  • encoder_hidden_states (Optional[mindspore.Tensor]): The encoder hidden states.
  • encoder_attentions (Optional[mindspore.Tensor]): The encoder attentions.
Source code in mindnlp/transformers/models/bart/modeling_bart.py
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
class BartForQuestionAnswering(BartPreTrainedModel):

    """
    This class represents a BART model for question answering tasks. It inherits from the BartPreTrainedModel class.

    BARTForQuestionAnswering is a fine-tuned version of the BART model, specifically designed for question answering tasks.
    It takes in input sequences and returns the predicted start and end positions of the answer span within the input sequence.

    The BARTForQuestionAnswering class contains the following methods:

    - __init__(self, config): Initializes the BARTForQuestionAnswering model with the provided configuration.
    - forward(self, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, head_mask, decoder_head_mask,
    cross_attn_head_mask, encoder_outputs, start_positions, end_positions, inputs_embeds,
    decoder_inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict):
    forwards the BART model for question answering and returns the predicted start and end positions of the answer span.

    The forward method takes the following parameters:

    - input_ids (mindspore.Tensor): The input token IDs.
    - attention_mask (Optional[mindspore.Tensor]): The attention mask tensor.
    - decoder_input_ids (Optional[mindspore.Tensor]): The decoder input token IDs.
    - decoder_attention_mask (Optional[mindspore.Tensor]): The decoder attention mask tensor.
    - head_mask (Optional[mindspore.Tensor]): The attention head mask tensor.
    - decoder_head_mask (Optional[mindspore.Tensor]): The decoder attention head mask tensor.
    - cross_attn_head_mask (Optional[mindspore.Tensor]): The cross-attention head mask tensor.
    - encoder_outputs (Optional[List[mindspore.Tensor]]): The encoder outputs tensor.
    - start_positions (Optional[mindspore.Tensor]): The labels for the start positions of the answer span.
    - end_positions (Optional[mindspore.Tensor]): The labels for the end positions of the answer span.
    - inputs_embeds (Optional[mindspore.Tensor]): The embedded input tensor.
    - decoder_inputs_embeds (Optional[mindspore.Tensor]): The embedded decoder input tensor.
    - use_cache (Optional[bool]): Whether to use cache.
    - output_attentions (Optional[bool]): Whether to output attentions.
    - output_hidden_states (Optional[bool]): Whether to output hidden states.
    - return_dict (Optional[bool]): Whether to return a Seq2SeqQuestionAnsweringModelOutput object.

    The forward method returns a Seq2SeqQuestionAnsweringModelOutput object that contains the following attributes:

    - loss (Optional[mindspore.Tensor]): The total loss.
    - start_logits (mindspore.Tensor): The predicted start logits.
    - end_logits (mindspore.Tensor): The predicted end logits.
    - past_key_values (Optional[mindspore.Tensor]): The past key values.
    - decoder_hidden_states (Optional[mindspore.Tensor]): The decoder hidden states.
    - decoder_attentions (Optional[mindspore.Tensor]): The decoder attentions.
    - cross_attentions (Optional[mindspore.Tensor]): The cross attentions.
    - encoder_last_hidden_state (Optional[mindspore.Tensor]): The encoder last hidden state.
    - encoder_hidden_states (Optional[mindspore.Tensor]): The encoder hidden states.
    - encoder_attentions (Optional[mindspore.Tensor]): The encoder attentions.
    """
    _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]

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

        Args:
            self: The object instance.
            config: An instance of the 'BartConfig' class containing the model configuration.

        Returns:
            None.

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

        config.num_labels = 2
        self.num_labels = config.num_labels

        self.model = BartModel(config)
        self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        decoder_input_ids: Optional[mindspore.Tensor] = None,
        decoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        decoder_head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        encoder_outputs: Optional[List[mindspore.Tensor]] = None,
        start_positions: Optional[mindspore.Tensor] = None,
        end_positions: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        decoder_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, Seq2SeqQuestionAnsweringModelOutput]:
        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
        if start_positions is not None and end_positions is not None:
            use_cache = False

        outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            decoder_input_ids=decoder_input_ids,
            decoder_attention_mask=decoder_attention_mask,
            head_mask=head_mask,
            decoder_head_mask=decoder_head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            encoder_outputs=encoder_outputs,
            inputs_embeds=inputs_embeds,
            decoder_inputs_embeds=decoder_inputs_embeds,
            use_cache=use_cache,
            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 = F.cross_entropy(start_logits, start_positions, ignore_index=ignored_index)
            end_loss = F.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[1:]
            return ((total_loss,) + output) if total_loss is not None else output

        return Seq2SeqQuestionAnsweringModelOutput(
            loss=total_loss,
            start_logits=start_logits,
            end_logits=end_logits,
            past_key_values=outputs.past_key_values,
            decoder_hidden_states=outputs.decoder_hidden_states,
            decoder_attentions=outputs.decoder_attentions,
            cross_attentions=outputs.cross_attentions,
            encoder_last_hidden_state=outputs.encoder_last_hidden_state,
            encoder_hidden_states=outputs.encoder_hidden_states,
            encoder_attentions=outputs.encoder_attentions,
        )

mindnlp.transformers.models.bart.modeling_bart.BartForQuestionAnswering.__init__(config)

Initializes an instance of the 'BartForQuestionAnswering' class.

PARAMETER DESCRIPTION
self

The object instance.

config

An instance of the 'BartConfig' class containing the model configuration.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
def __init__(self, config):
    """
    Initializes an instance of the 'BartForQuestionAnswering' class.

    Args:
        self: The object instance.
        config: An instance of the 'BartConfig' class containing the model configuration.

    Returns:
        None.

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

    config.num_labels = 2
    self.num_labels = config.num_labels

    self.model = BartModel(config)
    self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.bart.modeling_bart.BartForQuestionAnswering.forward(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, start_positions=None, end_positions=None, inputs_embeds=None, decoder_inputs_embeds=None, use_cache=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/bart/modeling_bart.py
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    decoder_input_ids: Optional[mindspore.Tensor] = None,
    decoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    decoder_head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    encoder_outputs: Optional[List[mindspore.Tensor]] = None,
    start_positions: Optional[mindspore.Tensor] = None,
    end_positions: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    decoder_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, Seq2SeqQuestionAnsweringModelOutput]:
    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
    if start_positions is not None and end_positions is not None:
        use_cache = False

    outputs = self.model(
        input_ids,
        attention_mask=attention_mask,
        decoder_input_ids=decoder_input_ids,
        decoder_attention_mask=decoder_attention_mask,
        head_mask=head_mask,
        decoder_head_mask=decoder_head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        encoder_outputs=encoder_outputs,
        inputs_embeds=inputs_embeds,
        decoder_inputs_embeds=decoder_inputs_embeds,
        use_cache=use_cache,
        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 = F.cross_entropy(start_logits, start_positions, ignore_index=ignored_index)
        end_loss = F.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[1:]
        return ((total_loss,) + output) if total_loss is not None else output

    return Seq2SeqQuestionAnsweringModelOutput(
        loss=total_loss,
        start_logits=start_logits,
        end_logits=end_logits,
        past_key_values=outputs.past_key_values,
        decoder_hidden_states=outputs.decoder_hidden_states,
        decoder_attentions=outputs.decoder_attentions,
        cross_attentions=outputs.cross_attentions,
        encoder_last_hidden_state=outputs.encoder_last_hidden_state,
        encoder_hidden_states=outputs.encoder_hidden_states,
        encoder_attentions=outputs.encoder_attentions,
    )

mindnlp.transformers.models.bart.modeling_bart.BartForSequenceClassification

Bases: BartPreTrainedModel

The BartForSequenceClassification class represents a BART model fine-tuned for sequence classification tasks. It inherits from the BartPreTrainedModel class and includes methods for model initialization and sequence classification.

This class includes an __init__ method for initializing the BART model and a forward method for forwarding the sequence classification outputs. The forward method accepts various input and output parameters, including input and output tensors, attention masks, labels, and cache usage. It processes the input data through the BART model, computes the classification logits, and calculates the loss based on the specified problem type.

The class also includes additional methods for handling sequence classification tasks and managing model outputs. The BartForSequenceClassification class provides a comprehensive solution for utilizing BART models for sequence classification applications.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
class BartForSequenceClassification(BartPreTrainedModel):

    """
    The `BartForSequenceClassification` class represents a BART model fine-tuned for sequence classification tasks.
    It inherits from the `BartPreTrainedModel` class and includes methods for model initialization and sequence classification.

    This class includes an `__init__` method for initializing the BART model and a `forward` method for
    forwarding the sequence classification outputs.
    The `forward` method accepts various input and output parameters, including input and output tensors,
    attention masks, labels, and cache usage.
    It processes the input data through the BART model, computes the classification logits, and calculates the loss
    based on the specified problem type.

    The class also includes additional methods for handling sequence classification tasks and managing model outputs.
    The `BartForSequenceClassification` class provides a comprehensive solution for utilizing
    BART models for sequence classification applications.
    """
    _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]

    def __init__(self, config: BartConfig, **kwargs):
        """
        Initializes a new instance of BartForSequenceClassification.

        Args:
            self: The instance of the class.
            config (BartConfig): The configuration for the BART model.
                It contains the model architecture and hyperparameters.

        Returns:
            None.

        Raises:
            TypeError: If the provided config is not an instance of BartConfig.
        """
        super().__init__(config, **kwargs)
        self.model = BartModel(config)
        self.classification_head = BartClassificationHead(
            config.d_model,
            config.d_model,
            config.num_labels,
            config.classifier_dropout,
        )

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

    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        decoder_input_ids: Optional[mindspore.Tensor] = None,
        decoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        decoder_head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        encoder_outputs: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        decoder_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, Seq2SeqSequenceClassifierOutput]:
        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 classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
        if labels is not None:
            use_cache = False

        if input_ids is None and inputs_embeds is not None:
            raise NotImplementedError(
                f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
            )

        outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            decoder_input_ids=decoder_input_ids,
            decoder_attention_mask=decoder_attention_mask,
            head_mask=head_mask,
            decoder_head_mask=decoder_head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            encoder_outputs=encoder_outputs,
            inputs_embeds=inputs_embeds,
            decoder_inputs_embeds=decoder_inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        hidden_states = outputs[0]  # last hidden state

        eos_mask = input_ids.eq(self.config.eos_token_id)

        # if len(ops.unique_consecutive(eos_mask.sum(1))) > 1:
        #     raise ValueError("All examples must have the same number of <eos> tokens.")

        sentence_representation = hidden_states[eos_mask].view(hidden_states.shape[0], -1, hidden_states.shape[-1])[
            :, -1, :
        ]
        logits = self.classification_head(sentence_representation)

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

            if self.config.problem_type == "regression":
                if self.config.num_labels == 1:
                    loss = F.mse_loss(logits.squeeze(), labels.squeeze())
                else:
                    loss = F.mse_loss(logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss = F.cross_entropy(logits.view(-1, self.config.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss = F.binary_cross_entropy_with_logits(logits, labels)
        if not return_dict:
            output = (logits,) + outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return Seq2SeqSequenceClassifierOutput(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            decoder_hidden_states=outputs.decoder_hidden_states,
            decoder_attentions=outputs.decoder_attentions,
            cross_attentions=outputs.cross_attentions,
            encoder_last_hidden_state=outputs.encoder_last_hidden_state,
            encoder_hidden_states=outputs.encoder_hidden_states,
            encoder_attentions=outputs.encoder_attentions,
        )

mindnlp.transformers.models.bart.modeling_bart.BartForSequenceClassification.__init__(config, **kwargs)

Initializes a new instance of BartForSequenceClassification.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration for the BART model. It contains the model architecture and hyperparameters.

TYPE: BartConfig

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the provided config is not an instance of BartConfig.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
def __init__(self, config: BartConfig, **kwargs):
    """
    Initializes a new instance of BartForSequenceClassification.

    Args:
        self: The instance of the class.
        config (BartConfig): The configuration for the BART model.
            It contains the model architecture and hyperparameters.

    Returns:
        None.

    Raises:
        TypeError: If the provided config is not an instance of BartConfig.
    """
    super().__init__(config, **kwargs)
    self.model = BartModel(config)
    self.classification_head = BartClassificationHead(
        config.d_model,
        config.d_model,
        config.num_labels,
        config.classifier_dropout,
    )

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

mindnlp.transformers.models.bart.modeling_bart.BartForSequenceClassification.forward(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, inputs_embeds=None, decoder_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 classification loss is computed (Cross-Entropy).

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

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    decoder_input_ids: Optional[mindspore.Tensor] = None,
    decoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    decoder_head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    encoder_outputs: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    decoder_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, Seq2SeqSequenceClassifierOutput]:
    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 classification loss is computed (Cross-Entropy).
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    if labels is not None:
        use_cache = False

    if input_ids is None and inputs_embeds is not None:
        raise NotImplementedError(
            f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
        )

    outputs = self.model(
        input_ids,
        attention_mask=attention_mask,
        decoder_input_ids=decoder_input_ids,
        decoder_attention_mask=decoder_attention_mask,
        head_mask=head_mask,
        decoder_head_mask=decoder_head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        encoder_outputs=encoder_outputs,
        inputs_embeds=inputs_embeds,
        decoder_inputs_embeds=decoder_inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    hidden_states = outputs[0]  # last hidden state

    eos_mask = input_ids.eq(self.config.eos_token_id)

    # if len(ops.unique_consecutive(eos_mask.sum(1))) > 1:
    #     raise ValueError("All examples must have the same number of <eos> tokens.")

    sentence_representation = hidden_states[eos_mask].view(hidden_states.shape[0], -1, hidden_states.shape[-1])[
        :, -1, :
    ]
    logits = self.classification_head(sentence_representation)

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

        if self.config.problem_type == "regression":
            if self.config.num_labels == 1:
                loss = F.mse_loss(logits.squeeze(), labels.squeeze())
            else:
                loss = F.mse_loss(logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss = F.cross_entropy(logits.view(-1, self.config.num_labels), labels.view(-1))
        elif self.config.problem_type == "multi_label_classification":
            loss = F.binary_cross_entropy_with_logits(logits, labels)
    if not return_dict:
        output = (logits,) + outputs[1:]
        return ((loss,) + output) if loss is not None else output

    return Seq2SeqSequenceClassifierOutput(
        loss=loss,
        logits=logits,
        past_key_values=outputs.past_key_values,
        decoder_hidden_states=outputs.decoder_hidden_states,
        decoder_attentions=outputs.decoder_attentions,
        cross_attentions=outputs.cross_attentions,
        encoder_last_hidden_state=outputs.encoder_last_hidden_state,
        encoder_hidden_states=outputs.encoder_hidden_states,
        encoder_attentions=outputs.encoder_attentions,
    )

mindnlp.transformers.models.bart.modeling_bart.BartModel

Bases: BartPreTrainedModel

BartModel is a class that represents the BART (Bidirectional and Auto-Regressive Transformers) model for sequence-to-sequence tasks. It inherits from BartPreTrainedModel and encapsulates the architecture and functionality of the BART model.

ATTRIBUTE DESCRIPTION
shared

Shared embedding layer for both encoder and decoder parts of the model.

TYPE: Embedding

encoder

Encoder component of the BART model.

TYPE: BartEncoder

decoder

Decoder component of the BART model.

TYPE: BartDecoder

METHOD DESCRIPTION
__init__

Initializes the BART model with the provided configuration.

_tie_weights

Ties the weights of word embeddings if specified in the configuration.

get_input_embeddings

Retrieves the shared input embeddings.

set_input_embeddings

Sets the shared input embeddings to the provided value.

get_encoder

Retrieves the encoder component of the model.

get_decoder

Retrieves the decoder component of the model.

forward

forwards the BART model for sequence-to-sequence tasks with the specified inputs and configurations.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
class BartModel(BartPreTrainedModel):

    """
    BartModel is a class that represents the BART (Bidirectional and Auto-Regressive Transformers) model
    for sequence-to-sequence tasks.
    It inherits from BartPreTrainedModel and encapsulates the architecture and functionality of the BART model.

    Attributes:
        shared (nn.Embedding): Shared embedding layer for both encoder and decoder parts of the model.
        encoder (BartEncoder): Encoder component of the BART model.
        decoder (BartDecoder): Decoder component of the BART model.

    Methods:
        __init__: Initializes the BART model with the provided configuration.
        _tie_weights: Ties the weights of word embeddings if specified in the configuration.
        get_input_embeddings: Retrieves the shared input embeddings.
        set_input_embeddings: Sets the shared input embeddings to the provided value.
        get_encoder: Retrieves the encoder component of the model.
        get_decoder: Retrieves the decoder component of the model.
        forward: forwards the BART model for sequence-to-sequence tasks with the specified inputs and configurations.
    """
    _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]

    def __init__(self, config: BartConfig):
        """
        Initialize the BartModel class with the provided configuration.

        Args:
            self: The instance of the BartModel class.
            config (BartConfig): The configuration object for the BartModel.
                It specifies the model's settings and hyperparameters.

                - config.pad_token_id (int): The index of the padding token in the vocabulary.
                - config.vocab_size (int): The size of the model's vocabulary.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type BartConfig.
            ValueError: If the provided pad_token_id is not a valid index in the vocabulary.
            ValueError: If the provided vocab_size is not a valid vocabulary size.
        """
        super().__init__(config)

        padding_idx, vocab_size = config.pad_token_id, config.vocab_size
        self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)

        self.encoder = BartEncoder(config, self.shared)
        self.decoder = BartDecoder(config, self.shared)

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

    def _tie_weights(self):
        """
        Ties the weights of the word embeddings in the encoder and decoder of the BartModel.

        Args:
            self (BartModel): An instance of the BartModel class.

        Returns:
            None

        Raises:
            None

        Description:
            This method is used to tie the weights of the word embeddings in the encoder and decoder of the BartModel.
            The tying of weights means that the same weight parameters are shared between the encoder and
            decoder embeddings.

            The method first checks if the 'tie_word_embeddings' flag in the model configuration is set to True.
            If it is, the method calls the '_tie_or_clone_weights' function to tie the weights of the
            'embed_tokens' in the encoder with the 'shared' weights.
            It then repeats the process for the 'embed_tokens' in the decoder.

            Note that tying the weights can help reduce the number of parameters in the model and improve efficiency,
            especially in scenarios where the encoder and decoder share the same vocabulary.

        Example:
            ```python
            >>> model = BartModel()
            >>> model._tie_weights()
            ```
        """
        if self.config.tie_word_embeddings:
            self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
            self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)

    def get_input_embeddings(self):
        """
        Method to get the input embeddings for the BartModel.

        Args:
            self:
                The instance of the BartModel class.

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

        Returns:
            None.

        Raises:
            None.
        """
        return self.shared

    def set_input_embeddings(self, value):
        """
        Set input embeddings for the BartModel.

        Args:
            self (BartModel): The instance of the BartModel class.
            value (torch.Tensor): The input embeddings to be set. It should be a torch.Tensor.

        Returns:
            None.

        Raises:
            None.
        """
        self.shared = value
        self.encoder.embed_tokens = self.shared
        self.decoder.embed_tokens = self.shared

    def get_encoder(self):
        """
        Get the encoder associated with the BartModel.

        Args:
            self: BartModel instance. The current instance of BartModel.

        Returns:
            encoder: The encoder associated with the BartModel instance.

        Raises:
            None.
        """
        return self.encoder

    def get_decoder(self):
        """
        Method get_decoder in class BartModel.

        Args:
            self: BartModel instance.
                Represents the current instance of the BartModel class.

        Returns:
            decoder:
                This method returns the decoder associated with the BartModel instance.

        Raises:
            None.
        """
        return self.decoder

    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        decoder_input_ids: Optional[mindspore.Tensor] = None,
        decoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        decoder_head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        encoder_outputs: Optional[List[mindspore.Tensor]] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        decoder_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, Seq2SeqModelOutput]:
        """
        forwards the BartModel.

        Args:
            self (BartModel): An instance of the BartModel class.
            input_ids (mindspore.Tensor, optional): The input sequence tensor. Default: None.
            attention_mask (Optional[mindspore.Tensor], optional): The attention mask tensor. Default: None.
            decoder_input_ids (Optional[mindspore.Tensor], optional): The decoder input sequence tensor. Default: None.
            decoder_attention_mask (Optional[mindspore.Tensor], optional): The decoder attention mask tensor. Default: None.
            head_mask (Optional[mindspore.Tensor], optional): The head mask tensor. Default: None.
            decoder_head_mask (Optional[mindspore.Tensor], optional): The decoder head mask tensor. Default: None.
            cross_attn_head_mask (Optional[mindspore.Tensor], optional): The cross attention head mask tensor. Default: None.
            encoder_outputs (Optional[List[mindspore.Tensor]], optional): The encoder outputs tensor. Default: None.
            past_key_values (Optional[List[mindspore.Tensor]], optional): The past key values tensor. Default: None.
            inputs_embeds (Optional[mindspore.Tensor], optional): The input embeddings tensor. Default: None.
            decoder_inputs_embeds (Optional[mindspore.Tensor], optional): The decoder input embeddings tensor. Default: None.
            use_cache (Optional[bool], optional): Whether to use cache. Default: None.
            output_attentions (Optional[bool], optional): Whether to output attentions. Default: None.
            output_hidden_states (Optional[bool], optional): Whether to output hidden states. Default: None.
            return_dict (Optional[bool], optional): Whether to return a dictionary. Default: None.

        Returns:
            Union[Tuple, Seq2SeqModelOutput]: A tuple or a Seq2SeqModelOutput object containing the last hidden state,
                past key values, decoder hidden states, decoder attentions, cross attentions, encoder last
                hidden state, encoder hidden states, and encoder attentions.

        Raises:
            ValueError: If no `decoder_input_ids` or `decoder_inputs_embeds` are passed and `input_ids` is `None`.
        """
        # different to other models, Bart automatically creates decoder_input_ids from
        # input_ids if no decoder_input_ids are provided
        if decoder_input_ids is None and decoder_inputs_embeds is None:
            if input_ids is None:
                raise ValueError(
                    "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
                    "passed, `input_ids` cannot be `None`. Please pass either "
                    "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
                )

            decoder_input_ids = shift_tokens_right(
                input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
            )

        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 encoder_outputs is None:
            encoder_outputs = self.encoder(
                input_ids=input_ids,
                attention_mask=attention_mask,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
            )
        # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
        elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
            encoder_outputs = BaseModelOutput(
                last_hidden_state=encoder_outputs[0],
                hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
                attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
            )

        # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
        decoder_outputs = self.decoder(
            input_ids=decoder_input_ids,
            attention_mask=decoder_attention_mask,
            encoder_hidden_states=encoder_outputs[0],
            encoder_attention_mask=attention_mask,
            head_mask=decoder_head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            past_key_values=past_key_values,
            inputs_embeds=decoder_inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        if not return_dict:
            return decoder_outputs + encoder_outputs

        return Seq2SeqModelOutput(
            last_hidden_state=decoder_outputs.last_hidden_state,
            past_key_values=decoder_outputs.past_key_values,
            decoder_hidden_states=decoder_outputs.hidden_states,
            decoder_attentions=decoder_outputs.attentions,
            cross_attentions=decoder_outputs.cross_attentions,
            encoder_last_hidden_state=encoder_outputs.last_hidden_state,
            encoder_hidden_states=encoder_outputs.hidden_states,
            encoder_attentions=encoder_outputs.attentions,
        )

mindnlp.transformers.models.bart.modeling_bart.BartModel.__init__(config)

Initialize the BartModel class with the provided configuration.

PARAMETER DESCRIPTION
self

The instance of the BartModel class.

config

The configuration object for the BartModel. It specifies the model's settings and hyperparameters.

  • config.pad_token_id (int): The index of the padding token in the vocabulary.
  • config.vocab_size (int): The size of the model's vocabulary.

TYPE: BartConfig

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type BartConfig.

ValueError

If the provided pad_token_id is not a valid index in the vocabulary.

ValueError

If the provided vocab_size is not a valid vocabulary size.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
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
def __init__(self, config: BartConfig):
    """
    Initialize the BartModel class with the provided configuration.

    Args:
        self: The instance of the BartModel class.
        config (BartConfig): The configuration object for the BartModel.
            It specifies the model's settings and hyperparameters.

            - config.pad_token_id (int): The index of the padding token in the vocabulary.
            - config.vocab_size (int): The size of the model's vocabulary.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type BartConfig.
        ValueError: If the provided pad_token_id is not a valid index in the vocabulary.
        ValueError: If the provided vocab_size is not a valid vocabulary size.
    """
    super().__init__(config)

    padding_idx, vocab_size = config.pad_token_id, config.vocab_size
    self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)

    self.encoder = BartEncoder(config, self.shared)
    self.decoder = BartDecoder(config, self.shared)

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

mindnlp.transformers.models.bart.modeling_bart.BartModel.forward(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

forwards the BartModel.

PARAMETER DESCRIPTION
self

An instance of the BartModel class.

TYPE: BartModel

input_ids

The input sequence tensor. Default: None.

TYPE: Tensor DEFAULT: None

attention_mask

The attention mask tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

decoder_input_ids

The decoder input sequence tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

decoder_attention_mask

The decoder attention mask tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The head mask tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

decoder_head_mask

The decoder head mask tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

cross_attn_head_mask

The cross attention head mask tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

encoder_outputs

The encoder outputs tensor. Default: None.

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

past_key_values

The past key values tensor. Default: None.

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

inputs_embeds

The input embeddings tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

decoder_inputs_embeds

The decoder input embeddings tensor. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

use_cache

Whether to use cache. Default: None.

TYPE: Optional[bool] DEFAULT: None

output_attentions

Whether to output attentions. Default: None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output hidden states. Default: None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary. Default: None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, Seq2SeqModelOutput]

Union[Tuple, Seq2SeqModelOutput]: A tuple or a Seq2SeqModelOutput object containing the last hidden state, past key values, decoder hidden states, decoder attentions, cross attentions, encoder last hidden state, encoder hidden states, and encoder attentions.

RAISES DESCRIPTION
ValueError

If no decoder_input_ids or decoder_inputs_embeds are passed and input_ids is None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    decoder_input_ids: Optional[mindspore.Tensor] = None,
    decoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    decoder_head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    encoder_outputs: Optional[List[mindspore.Tensor]] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    decoder_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, Seq2SeqModelOutput]:
    """
    forwards the BartModel.

    Args:
        self (BartModel): An instance of the BartModel class.
        input_ids (mindspore.Tensor, optional): The input sequence tensor. Default: None.
        attention_mask (Optional[mindspore.Tensor], optional): The attention mask tensor. Default: None.
        decoder_input_ids (Optional[mindspore.Tensor], optional): The decoder input sequence tensor. Default: None.
        decoder_attention_mask (Optional[mindspore.Tensor], optional): The decoder attention mask tensor. Default: None.
        head_mask (Optional[mindspore.Tensor], optional): The head mask tensor. Default: None.
        decoder_head_mask (Optional[mindspore.Tensor], optional): The decoder head mask tensor. Default: None.
        cross_attn_head_mask (Optional[mindspore.Tensor], optional): The cross attention head mask tensor. Default: None.
        encoder_outputs (Optional[List[mindspore.Tensor]], optional): The encoder outputs tensor. Default: None.
        past_key_values (Optional[List[mindspore.Tensor]], optional): The past key values tensor. Default: None.
        inputs_embeds (Optional[mindspore.Tensor], optional): The input embeddings tensor. Default: None.
        decoder_inputs_embeds (Optional[mindspore.Tensor], optional): The decoder input embeddings tensor. Default: None.
        use_cache (Optional[bool], optional): Whether to use cache. Default: None.
        output_attentions (Optional[bool], optional): Whether to output attentions. Default: None.
        output_hidden_states (Optional[bool], optional): Whether to output hidden states. Default: None.
        return_dict (Optional[bool], optional): Whether to return a dictionary. Default: None.

    Returns:
        Union[Tuple, Seq2SeqModelOutput]: A tuple or a Seq2SeqModelOutput object containing the last hidden state,
            past key values, decoder hidden states, decoder attentions, cross attentions, encoder last
            hidden state, encoder hidden states, and encoder attentions.

    Raises:
        ValueError: If no `decoder_input_ids` or `decoder_inputs_embeds` are passed and `input_ids` is `None`.
    """
    # different to other models, Bart automatically creates decoder_input_ids from
    # input_ids if no decoder_input_ids are provided
    if decoder_input_ids is None and decoder_inputs_embeds is None:
        if input_ids is None:
            raise ValueError(
                "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
                "passed, `input_ids` cannot be `None`. Please pass either "
                "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
            )

        decoder_input_ids = shift_tokens_right(
            input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
        )

    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 encoder_outputs is None:
        encoder_outputs = self.encoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
    # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
    elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
        encoder_outputs = BaseModelOutput(
            last_hidden_state=encoder_outputs[0],
            hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
            attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
        )

    # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
    decoder_outputs = self.decoder(
        input_ids=decoder_input_ids,
        attention_mask=decoder_attention_mask,
        encoder_hidden_states=encoder_outputs[0],
        encoder_attention_mask=attention_mask,
        head_mask=decoder_head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        past_key_values=past_key_values,
        inputs_embeds=decoder_inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    if not return_dict:
        return decoder_outputs + encoder_outputs

    return Seq2SeqModelOutput(
        last_hidden_state=decoder_outputs.last_hidden_state,
        past_key_values=decoder_outputs.past_key_values,
        decoder_hidden_states=decoder_outputs.hidden_states,
        decoder_attentions=decoder_outputs.attentions,
        cross_attentions=decoder_outputs.cross_attentions,
        encoder_last_hidden_state=encoder_outputs.last_hidden_state,
        encoder_hidden_states=encoder_outputs.hidden_states,
        encoder_attentions=encoder_outputs.attentions,
    )

mindnlp.transformers.models.bart.modeling_bart.BartModel.get_decoder()

Method get_decoder in class BartModel.

PARAMETER DESCRIPTION
self

BartModel instance. Represents the current instance of the BartModel class.

RETURNS DESCRIPTION
decoder

This method returns the decoder associated with the BartModel instance.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
def get_decoder(self):
    """
    Method get_decoder in class BartModel.

    Args:
        self: BartModel instance.
            Represents the current instance of the BartModel class.

    Returns:
        decoder:
            This method returns the decoder associated with the BartModel instance.

    Raises:
        None.
    """
    return self.decoder

mindnlp.transformers.models.bart.modeling_bart.BartModel.get_encoder()

Get the encoder associated with the BartModel.

PARAMETER DESCRIPTION
self

BartModel instance. The current instance of BartModel.

RETURNS DESCRIPTION
encoder

The encoder associated with the BartModel instance.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
def get_encoder(self):
    """
    Get the encoder associated with the BartModel.

    Args:
        self: BartModel instance. The current instance of BartModel.

    Returns:
        encoder: The encoder associated with the BartModel instance.

    Raises:
        None.
    """
    return self.encoder

mindnlp.transformers.models.bart.modeling_bart.BartModel.get_input_embeddings()

Method to get the input embeddings for the BartModel.

PARAMETER DESCRIPTION
self

The instance of the BartModel class.

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

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
def get_input_embeddings(self):
    """
    Method to get the input embeddings for the BartModel.

    Args:
        self:
            The instance of the BartModel class.

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

    Returns:
        None.

    Raises:
        None.
    """
    return self.shared

mindnlp.transformers.models.bart.modeling_bart.BartModel.set_input_embeddings(value)

Set input embeddings for the BartModel.

PARAMETER DESCRIPTION
self

The instance of the BartModel class.

TYPE: BartModel

value

The input embeddings to be set. It should be a torch.Tensor.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/modeling_bart.py
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
def set_input_embeddings(self, value):
    """
    Set input embeddings for the BartModel.

    Args:
        self (BartModel): The instance of the BartModel class.
        value (torch.Tensor): The input embeddings to be set. It should be a torch.Tensor.

    Returns:
        None.

    Raises:
        None.
    """
    self.shared = value
    self.encoder.embed_tokens = self.shared
    self.decoder.embed_tokens = self.shared

mindnlp.transformers.models.bart.modeling_bart.BartPreTrainedModel

Bases: PreTrainedModel

BartPreTrainedModel class represents a pre-trained BART (Bidirectional and Auto-Regressive Transformers) model for natural language processing tasks. This class inherits from PreTrainedModel and includes methods for initializing weights and generating dummy inputs for the model.

ATTRIBUTE DESCRIPTION
config

The configuration instance for the BART model.

METHOD DESCRIPTION
_init_weights

Initializes the weights for the BART model based on the specified cell type, using the provided configuration standard deviation.

dummy_inputs

Generates dummy input data for the BART model, including input_ids and attention_mask.

Example
>>> # Initialize a BART pre-trained model
>>> model = BartPreTrainedModel(config)
...
>>> # Initialize the weights for the model
>>> model._init_weights(cell)
...
>>> # Generate dummy inputs for the model
>>> inputs = model.dummy_inputs()
Source code in mindnlp/transformers/models/bart/modeling_bart.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
class BartPreTrainedModel(PreTrainedModel):

    """
    BartPreTrainedModel class represents a pre-trained BART (Bidirectional and Auto-Regressive Transformers) model
    for natural language processing tasks.
    This class inherits from PreTrainedModel and includes methods for initializing weights and generating
    dummy inputs for the model.

    Attributes:
        config: The configuration instance for the BART model.

    Methods:
        _init_weights(self, cell):
            Initializes the weights for the BART model based on the specified cell type,
            using the provided configuration standard deviation.
        dummy_inputs(self): Generates dummy input data for the BART model, including input_ids and attention_mask.

    Example:
        ```python
        >>> # Initialize a BART pre-trained model
        >>> model = BartPreTrainedModel(config)
        ...
        >>> # Initialize the weights for the model
        >>> model._init_weights(cell)
        ...
        >>> # Generate dummy inputs for the model
        >>> inputs = model.dummy_inputs()
        ```
    """
    config_class = BartConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = False
    _keys_to_ignore_on_load_unexpected = ["encoder.version", "decoder.version"]
    _no_split_modules = [r"BartEncoderLayer", r"BartDecoderLayer"]

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

            cell.weight.set_data(Tensor(weight, cell.weight.dtype))

    @property
    def dummy_inputs(self):
        """
        Method: dummy_inputs

        Description:
            This method generates dummy inputs for a BartPreTrainedModel.

        Args:
            self: BartPreTrainedModel
                The instance of BartPreTrainedModel class.

        Returns:
            dict:
                A dictionary containing dummy inputs for the model with the following keys:

                - 'attention_mask': A Tensor representing the attention mask for the input_ids.
                - 'input_ids': A Tensor representing the input token IDs.

        Raises:
        This method does not raise any exceptions.
        """
        pad_token = self.config.pad_token_id
        input_ids = mindspore.Tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]])
        dummy_inputs = {
            "attention_mask": input_ids.ne(pad_token),
            "input_ids": input_ids,
        }
        return dummy_inputs

mindnlp.transformers.models.bart.modeling_bart.BartPreTrainedModel.dummy_inputs property

Description

This method generates dummy inputs for a BartPreTrainedModel.

PARAMETER DESCRIPTION
self

BartPreTrainedModel The instance of BartPreTrainedModel class.

RETURNS DESCRIPTION
dict

A dictionary containing dummy inputs for the model with the following keys:

  • 'attention_mask': A Tensor representing the attention mask for the input_ids.
  • 'input_ids': A Tensor representing the input token IDs.

This method does not raise any exceptions.

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer

Bases: PreTrainedTokenizer

Constructs a BART tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beginning of the sentence (without space) or not:

Example
>>> from transformers import BartTokenizer
...
>>> tokenizer = BartTokenizer.from_pretrained("facebook/bart-base")
>>> tokenizer("Hello world")["input_ids"]
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")["input_ids"]
[0, 20920, 232, 2]

You can get around that behavior by passing add_prefix_space=True when instantiating this tokenizer or when you call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

When used with is_split_into_words=True, this tokenizer will add a space before each word (even the first one).

This tokenizer inherits from [PreTrainedTokenizer] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

PARAMETER DESCRIPTION
vocab_file

Path to the vocabulary file.

TYPE: `str`

merges_file

Path to the merges file.

TYPE: `str`

errors

Paradigm to follow when decoding bytes to UTF-8. See bytes.decode for more information.

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

bos_token

The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the cls_token.

TYPE: `str`, *optional*, defaults to `"<s>"` DEFAULT: '<s>'

eos_token

The end of sequence token.

When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the sep_token.

TYPE: `str`, *optional*, defaults to `"</s>"` DEFAULT: '</s>'

sep_token

The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.

TYPE: `str`, *optional*, defaults to `"</s>"` DEFAULT: '</s>'

cls_token

The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.

TYPE: `str`, *optional*, defaults to `"<s>"` DEFAULT: '<s>'

unk_token

The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.

TYPE: `str`, *optional*, defaults to `"<unk>"` DEFAULT: '<unk>'

pad_token

The token used for padding, for example when batching sequences of different lengths.

TYPE: `str`, *optional*, defaults to `"<pad>"` DEFAULT: '<pad>'

mask_token

The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict.

TYPE: `str`, *optional*, defaults to `"<mask>"` DEFAULT: '<mask>'

add_prefix_space

Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (BART tokenizer detect beginning of words by the preceding space).

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

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
class BartTokenizer(PreTrainedTokenizer):
    """
    Constructs a BART tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.

    This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
    be encoded differently whether it is at the beginning of the sentence (without space) or not:

    Example:
        ```python
        >>> from transformers import BartTokenizer
        ...
        >>> tokenizer = BartTokenizer.from_pretrained("facebook/bart-base")
        >>> tokenizer("Hello world")["input_ids"]
        [0, 31414, 232, 2]
        >>> tokenizer(" Hello world")["input_ids"]
        [0, 20920, 232, 2]
        ```

    You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
    call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

    <Tip>

    When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).

    </Tip>

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_token`.

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        unk_token (`str`, *optional*, defaults to `"<unk>"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        mask_token (`str`, *optional*, defaults to `"<mask>"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word. (BART tokenizer detect beginning of words by the preceding space).
    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        merges_file,
        errors="replace",
        bos_token="<s>",
        eos_token="</s>",
        sep_token="</s>",
        cls_token="<s>",
        unk_token="<unk>",
        pad_token="<pad>",
        mask_token="<mask>",
        add_prefix_space=False,
        **kwargs,
    ):
        """
        This method initializes an instance of the BartTokenizer class.

        Args:
            self: The instance of the class.
            vocab_file (str): The path to the vocabulary file containing token mappings.
            merges_file (str): The path to the merges file for byte pair encoding.
            errors (str): Controls error handling during tokenization (default is 'replace').
            bos_token (str): Beginning of sentence token (default is '<s>').
            eos_token (str): End of sentence token (default is '</s>').
            sep_token (str): Separation token (default is '</s>').
            cls_token (str): Classification token (default is '<s>').
            unk_token (str): Token for unknown tokens (default is '<unk>').
            pad_token (str): Token for padding sequences (default is '<pad>').
            mask_token (str): Token for masking sequences (default is '<mask>').
            add_prefix_space (bool): Whether to add space to the beginning of the token (default is False).

        Returns:
            None.

        Raises:
            FileNotFoundError: If the vocab_file or merges_file is not found.
            UnicodeDecodeError: If an error occurs during decoding the files.
            ValueError: If an error occurs during tokenization.
        """
        bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
        eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
        sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
        cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
        unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
        pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token

        # Mask token behave like a normal word, i.e. include the space before it
        mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token

        with open(vocab_file, encoding="utf-8") as vocab_handle:
            self.encoder = json.load(vocab_handle)
        self.decoder = {v: k for k, v in self.encoder.items()}
        self.errors = errors  # how to handle errors in decoding
        self.byte_encoder = bytes_to_unicode()
        self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
        with open(merges_file, encoding="utf-8") as merges_handle:
            bpe_merges = merges_handle.read().split("\n")[1:-1]
        bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
        self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
        self.cache = {}
        self.add_prefix_space = add_prefix_space

        # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
        self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")

        super().__init__(
            errors=errors,
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            sep_token=sep_token,
            cls_token=cls_token,
            pad_token=pad_token,
            mask_token=mask_token,
            add_prefix_space=add_prefix_space,
            **kwargs,
        )

    @property
    def vocab_size(self):
        """
        Method to retrieve the vocabulary size of the BartTokenizer instance.

        Args:
            self (BartTokenizer): The BartTokenizer instance itself.
                This parameter is required as the method operates on the current instance.

        Returns:
            None:
                This method returns the vocabulary size, which is the length of the encoder in the BartTokenizer instance.

        Raises:
            None.
        """
        return len(self.encoder)

    def get_vocab(self):
        """Return the vocabulary of the BartTokenizer.

        Args:
            self (BartTokenizer): An instance of the BartTokenizer class.

        Returns:
            dict: A dictionary representing the vocabulary of the tokenizer. The keys are the tokens in the vocabulary,
                and the values are their corresponding integer encodings.

        Raises:
            None.

        """
        return dict(self.encoder, **self.added_tokens_encoder)

    def bpe(self, token):
        """
        This method 'bpe' is defined within the class 'BartTokenizer' and performs Byte Pair Encoding (BPE) on a given token.

        Args:
            self:
                Represents the instance of the class 'BartTokenizer'.

                - Type: BartTokenizer
                - Purpose: Allows access to class attributes and methods.
                - Restrictions: None

            token:
                The input token to be processed using Byte Pair Encoding.

                - Type: str
                - Purpose: Represents the token to be encoded.
                - Restrictions: Must be a valid string input.

        Returns:
            token:
                The method returns the processed token after applying Byte Pair Encoding.

                - Type: str
                - Purpose: Represents the token after encoding.

        Raises:
            None
        """
        if token in self.cache:
            return self.cache[token]
        word = tuple(token)
        pairs = get_pairs(word)

        if not pairs:
            return token

        while True:
            bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
            if bigram not in self.bpe_ranks:
                break
            first, second = bigram
            new_word = []
            i = 0
            while i < len(word):
                try:
                    j = word.index(first, i)
                except ValueError:
                    new_word.extend(word[i:])
                    break
                else:
                    new_word.extend(word[i:j])
                    i = j

                if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
                    new_word.append(first + second)
                    i += 2
                else:
                    new_word.append(word[i])
                    i += 1
            new_word = tuple(new_word)
            word = new_word
            if len(word) == 1:
                break
            pairs = get_pairs(word)
        word = " ".join(word)
        self.cache[token] = word
        return word

    def _tokenize(self, text):
        """Tokenize a string."""
        bpe_tokens = []
        for token in re.findall(self.pat, text):
            token = "".join(
                self.byte_encoder[b] for b in token.encode("utf-8")
            )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
            bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
        return bpe_tokens

    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.encoder.get(token, self.encoder.get(self.unk_token))

    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        return self.decoder.get(index)

    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        text = "".join(tokens)
        text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
        return text

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary files for the BartTokenizer.

        Args:
            self (BartTokenizer): The instance of the BartTokenizer class.
            save_directory (str): The directory where the vocabulary files will be saved.
            filename_prefix (Optional[str]): An optional prefix to be added to the filenames. Default is None.

        Returns:
            Tuple[str]: A tuple containing the paths of the saved vocabulary files.

        Raises:
            FileNotFoundError: If the specified save_directory does not exist.
            IOError: If there is an issue writing the vocabulary files.
            ValueError: If the provided filename_prefix is not a string.
        """
        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )
        merge_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
        )

        with open(vocab_file, "w", encoding="utf-8") as f:
            f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

        index = 0
        with open(merge_file, "w", encoding="utf-8") as writer:
            writer.write("#version: 0.2\n")
            for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
                if index != token_index:
                    logger.warning(
                        f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                        " Please check that the tokenizer is not corrupted!"
                    )
                    index = token_index
                writer.write(" ".join(bpe_tokens) + "\n")
                index += 1

        return vocab_file, merge_file

    def build_inputs_with_special_tokens(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A BART sequence has the following format:

        - single sequence: `<s> X </s>`
        - pair of sequences: `<s> A </s></s> B </s>`

        Args:
            token_ids_0 (`List[int]`):
                List of IDs to which the special tokens will be added.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """
        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
        cls = [self.cls_token_id]
        sep = [self.sep_token_id]
        return cls + token_ids_0 + sep + sep + token_ids_1 + sep

    def get_special_tokens_mask(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
    ) -> List[int]:
        """
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        """
        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
            )

        if token_ids_1 is None:
            return [1] + ([0] * len(token_ids_0)) + [1]
        return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
        make use of token type ids, therefore a list of zeros is returned.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of zeros.
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]

        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

    def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
        """
        Prepares the input text for tokenization in the BartTokenizer class.

        Args:
            self: The instance of the BartTokenizer class.
            text (str): The input text to be prepared for tokenization.
            is_split_into_words (bool):
                Flag indicating whether the text is already split into words. Default is False.

                - If True, the text is assumed to be split into words and no further processing is done.
                - If False, the text is assumed to be a continuous string and additional processing may be applied.
            **kwargs:
                Additional keyword arguments.

                add_prefix_space (bool):

                Flag indicating whether a space should be added to the beginning of the text.

                - If True, and if the text is not empty and does not start with a space,
                a space is added before the text.
                - If False, no space is added. Default is the value of self.add_prefix_space.

        Returns:
            str: The prepared text for tokenization.

        Raises:
            None.

        Note:
            The 'is_split_into_words' and 'add_prefix_space' parameters are mutually exclusive.
            If 'is_split_into_words' is set to True, the 'add_prefix_space' parameter is ignored.

        Example:
            ```python
            >>> tokenizer = BartTokenizer()
            >>> prepared_text = tokenizer.prepare_for_tokenization("Hello, world!")
            ```
        """
        add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
        if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
            text = " " + text
        return (text, kwargs)

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size property

Method to retrieve the vocabulary size of the BartTokenizer instance.

PARAMETER DESCRIPTION
self

The BartTokenizer instance itself. This parameter is required as the method operates on the current instance.

TYPE: BartTokenizer

RETURNS DESCRIPTION
None

This method returns the vocabulary size, which is the length of the encoder in the BartTokenizer instance.

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.__init__(vocab_file, merges_file, errors='replace', bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_token='<s>', unk_token='<unk>', pad_token='<pad>', mask_token='<mask>', add_prefix_space=False, **kwargs)

This method initializes an instance of the BartTokenizer class.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

The path to the vocabulary file containing token mappings.

TYPE: str

merges_file

The path to the merges file for byte pair encoding.

TYPE: str

errors

Controls error handling during tokenization (default is 'replace').

TYPE: str DEFAULT: 'replace'

bos_token

Beginning of sentence token (default is '').

TYPE: str DEFAULT: '<s>'

eos_token

End of sentence token (default is '').

TYPE: str DEFAULT: '</s>'

sep_token

Separation token (default is '').

TYPE: str DEFAULT: '</s>'

cls_token

Classification token (default is '').

TYPE: str DEFAULT: '<s>'

unk_token

Token for unknown tokens (default is '').

TYPE: str DEFAULT: '<unk>'

pad_token

Token for padding sequences (default is '').

TYPE: str DEFAULT: '<pad>'

mask_token

Token for masking sequences (default is '').

TYPE: str DEFAULT: '<mask>'

add_prefix_space

Whether to add space to the beginning of the token (default is False).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
FileNotFoundError

If the vocab_file or merges_file is not found.

UnicodeDecodeError

If an error occurs during decoding the files.

ValueError

If an error occurs during tokenization.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def __init__(
    self,
    vocab_file,
    merges_file,
    errors="replace",
    bos_token="<s>",
    eos_token="</s>",
    sep_token="</s>",
    cls_token="<s>",
    unk_token="<unk>",
    pad_token="<pad>",
    mask_token="<mask>",
    add_prefix_space=False,
    **kwargs,
):
    """
    This method initializes an instance of the BartTokenizer class.

    Args:
        self: The instance of the class.
        vocab_file (str): The path to the vocabulary file containing token mappings.
        merges_file (str): The path to the merges file for byte pair encoding.
        errors (str): Controls error handling during tokenization (default is 'replace').
        bos_token (str): Beginning of sentence token (default is '<s>').
        eos_token (str): End of sentence token (default is '</s>').
        sep_token (str): Separation token (default is '</s>').
        cls_token (str): Classification token (default is '<s>').
        unk_token (str): Token for unknown tokens (default is '<unk>').
        pad_token (str): Token for padding sequences (default is '<pad>').
        mask_token (str): Token for masking sequences (default is '<mask>').
        add_prefix_space (bool): Whether to add space to the beginning of the token (default is False).

    Returns:
        None.

    Raises:
        FileNotFoundError: If the vocab_file or merges_file is not found.
        UnicodeDecodeError: If an error occurs during decoding the files.
        ValueError: If an error occurs during tokenization.
    """
    bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
    eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
    sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
    cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
    unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
    pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token

    # Mask token behave like a normal word, i.e. include the space before it
    mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token

    with open(vocab_file, encoding="utf-8") as vocab_handle:
        self.encoder = json.load(vocab_handle)
    self.decoder = {v: k for k, v in self.encoder.items()}
    self.errors = errors  # how to handle errors in decoding
    self.byte_encoder = bytes_to_unicode()
    self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
    with open(merges_file, encoding="utf-8") as merges_handle:
        bpe_merges = merges_handle.read().split("\n")[1:-1]
    bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
    self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
    self.cache = {}
    self.add_prefix_space = add_prefix_space

    # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
    self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")

    super().__init__(
        errors=errors,
        bos_token=bos_token,
        eos_token=eos_token,
        unk_token=unk_token,
        sep_token=sep_token,
        cls_token=cls_token,
        pad_token=pad_token,
        mask_token=mask_token,
        add_prefix_space=add_prefix_space,
        **kwargs,
    )

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.bpe(token)

This method 'bpe' is defined within the class 'BartTokenizer' and performs Byte Pair Encoding (BPE) on a given token.

PARAMETER DESCRIPTION
self

Represents the instance of the class 'BartTokenizer'.

  • Type: BartTokenizer
  • Purpose: Allows access to class attributes and methods.
  • Restrictions: None

token

The input token to be processed using Byte Pair Encoding.

  • Type: str
  • Purpose: Represents the token to be encoded.
  • Restrictions: Must be a valid string input.

RETURNS DESCRIPTION
token

The method returns the processed token after applying Byte Pair Encoding.

  • Type: str
  • Purpose: Represents the token after encoding.
Source code in mindnlp/transformers/models/bart/tokenization_bart.py
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
def bpe(self, token):
    """
    This method 'bpe' is defined within the class 'BartTokenizer' and performs Byte Pair Encoding (BPE) on a given token.

    Args:
        self:
            Represents the instance of the class 'BartTokenizer'.

            - Type: BartTokenizer
            - Purpose: Allows access to class attributes and methods.
            - Restrictions: None

        token:
            The input token to be processed using Byte Pair Encoding.

            - Type: str
            - Purpose: Represents the token to be encoded.
            - Restrictions: Must be a valid string input.

    Returns:
        token:
            The method returns the processed token after applying Byte Pair Encoding.

            - Type: str
            - Purpose: Represents the token after encoding.

    Raises:
        None
    """
    if token in self.cache:
        return self.cache[token]
    word = tuple(token)
    pairs = get_pairs(word)

    if not pairs:
        return token

    while True:
        bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
        if bigram not in self.bpe_ranks:
            break
        first, second = bigram
        new_word = []
        i = 0
        while i < len(word):
            try:
                j = word.index(first, i)
            except ValueError:
                new_word.extend(word[i:])
                break
            else:
                new_word.extend(word[i:j])
                i = j

            if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
                new_word.append(first + second)
                i += 2
            else:
                new_word.append(word[i])
                i += 1
        new_word = tuple(new_word)
        word = new_word
        if len(word) == 1:
            break
        pairs = get_pairs(word)
    word = " ".join(word)
    self.cache[token] = word
    return word

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BART sequence has the following format:

  • single sequence: <s> X </s>
  • pair of sequences: <s> A </s></s> B </s>
PARAMETER DESCRIPTION
token_ids_0

List of IDs to which the special tokens will be added.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

TYPE: `List[int]`, *optional* DEFAULT: None

RETURNS DESCRIPTION
List[int]

List[int]: List of input IDs with the appropriate special tokens.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def build_inputs_with_special_tokens(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    adding special tokens. A BART sequence has the following format:

    - single sequence: `<s> X </s>`
    - pair of sequences: `<s> A </s></s> B </s>`

    Args:
        token_ids_0 (`List[int]`):
            List of IDs to which the special tokens will be added.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """
    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + sep + token_ids_1 + sep

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.convert_tokens_to_string(tokens)

Converts a sequence of tokens (string) in a single string.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
384
385
386
387
388
def convert_tokens_to_string(self, tokens):
    """Converts a sequence of tokens (string) in a single string."""
    text = "".join(tokens)
    text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
    return text

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not make use of token type ids, therefore a list of zeros is returned.

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

TYPE: `List[int]`, *optional* DEFAULT: None

RETURNS DESCRIPTION
List[int]

List[int]: List of zeros.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def create_token_type_ids_from_sequences(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
    make use of token type ids, therefore a list of zeros is returned.

    Args:
        token_ids_0 (`List[int]`):
            List of IDs.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.

    Returns:
        `List[int]`: List of zeros.
    """
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]

    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.get_special_tokens_mask(token_ids_0, token_ids_1=None, already_has_special_tokens=False)

Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model method.

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

TYPE: `List[int]`, *optional* DEFAULT: None

already_has_special_tokens

Whether or not the token list is already formatted with special tokens for the model.

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

RETURNS DESCRIPTION
List[int]

List[int]: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
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
def get_special_tokens_mask(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
    """
    Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
    special tokens using the tokenizer `prepare_for_model` method.

    Args:
        token_ids_0 (`List[int]`):
            List of IDs.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.
        already_has_special_tokens (`bool`, *optional*, defaults to `False`):
            Whether or not the token list is already formatted with special tokens for the model.

    Returns:
        `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
    """
    if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
        )

    if token_ids_1 is None:
        return [1] + ([0] * len(token_ids_0)) + [1]
    return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.get_vocab()

Return the vocabulary of the BartTokenizer.

PARAMETER DESCRIPTION
self

An instance of the BartTokenizer class.

TYPE: BartTokenizer

RETURNS DESCRIPTION
dict

A dictionary representing the vocabulary of the tokenizer. The keys are the tokens in the vocabulary, and the values are their corresponding integer encodings.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def get_vocab(self):
    """Return the vocabulary of the BartTokenizer.

    Args:
        self (BartTokenizer): An instance of the BartTokenizer class.

    Returns:
        dict: A dictionary representing the vocabulary of the tokenizer. The keys are the tokens in the vocabulary,
            and the values are their corresponding integer encodings.

    Raises:
        None.

    """
    return dict(self.encoder, **self.added_tokens_encoder)

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.prepare_for_tokenization(text, is_split_into_words=False, **kwargs)

Prepares the input text for tokenization in the BartTokenizer class.

PARAMETER DESCRIPTION
self

The instance of the BartTokenizer class.

text

The input text to be prepared for tokenization.

TYPE: str

is_split_into_words

Flag indicating whether the text is already split into words. Default is False.

  • If True, the text is assumed to be split into words and no further processing is done.
  • If False, the text is assumed to be a continuous string and additional processing may be applied.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments.

add_prefix_space (bool):

Flag indicating whether a space should be added to the beginning of the text.

  • If True, and if the text is not empty and does not start with a space, a space is added before the text.
  • If False, no space is added. Default is the value of self.add_prefix_space.

DEFAULT: {}

RETURNS DESCRIPTION
str

The prepared text for tokenization.

Note

The 'is_split_into_words' and 'add_prefix_space' parameters are mutually exclusive. If 'is_split_into_words' is set to True, the 'add_prefix_space' parameter is ignored.

Example
>>> tokenizer = BartTokenizer()
>>> prepared_text = tokenizer.prepare_for_tokenization("Hello, world!")
Source code in mindnlp/transformers/models/bart/tokenization_bart.py
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
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
    """
    Prepares the input text for tokenization in the BartTokenizer class.

    Args:
        self: The instance of the BartTokenizer class.
        text (str): The input text to be prepared for tokenization.
        is_split_into_words (bool):
            Flag indicating whether the text is already split into words. Default is False.

            - If True, the text is assumed to be split into words and no further processing is done.
            - If False, the text is assumed to be a continuous string and additional processing may be applied.
        **kwargs:
            Additional keyword arguments.

            add_prefix_space (bool):

            Flag indicating whether a space should be added to the beginning of the text.

            - If True, and if the text is not empty and does not start with a space,
            a space is added before the text.
            - If False, no space is added. Default is the value of self.add_prefix_space.

    Returns:
        str: The prepared text for tokenization.

    Raises:
        None.

    Note:
        The 'is_split_into_words' and 'add_prefix_space' parameters are mutually exclusive.
        If 'is_split_into_words' is set to True, the 'add_prefix_space' parameter is ignored.

    Example:
        ```python
        >>> tokenizer = BartTokenizer()
        >>> prepared_text = tokenizer.prepare_for_tokenization("Hello, world!")
        ```
    """
    add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
    if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
        text = " " + text
    return (text, kwargs)

mindnlp.transformers.models.bart.tokenization_bart.BartTokenizer.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary files for the BartTokenizer.

PARAMETER DESCRIPTION
self

The instance of the BartTokenizer class.

TYPE: BartTokenizer

save_directory

The directory where the vocabulary files will be saved.

TYPE: str

filename_prefix

An optional prefix to be added to the filenames. Default is None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the paths of the saved vocabulary files.

RAISES DESCRIPTION
FileNotFoundError

If the specified save_directory does not exist.

IOError

If there is an issue writing the vocabulary files.

ValueError

If the provided filename_prefix is not a string.

Source code in mindnlp/transformers/models/bart/tokenization_bart.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary files for the BartTokenizer.

    Args:
        self (BartTokenizer): The instance of the BartTokenizer class.
        save_directory (str): The directory where the vocabulary files will be saved.
        filename_prefix (Optional[str]): An optional prefix to be added to the filenames. Default is None.

    Returns:
        Tuple[str]: A tuple containing the paths of the saved vocabulary files.

    Raises:
        FileNotFoundError: If the specified save_directory does not exist.
        IOError: If there is an issue writing the vocabulary files.
        ValueError: If the provided filename_prefix is not a string.
    """
    if not os.path.isdir(save_directory):
        logger.error(f"Vocabulary path ({save_directory}) should be a directory")
        return
    vocab_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
    )
    merge_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
    )

    with open(vocab_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

    index = 0
    with open(merge_file, "w", encoding="utf-8") as writer:
        writer.write("#version: 0.2\n")
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
            if index != token_index:
                logger.warning(
                    f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                    " Please check that the tokenizer is not corrupted!"
                )
                index = token_index
            writer.write(" ".join(bpe_tokens) + "\n")
            index += 1

    return vocab_file, merge_file

mindnlp.transformers.models.bart.tokenization_bart_fast.BartTokenizerFast

Bases: PreTrainedTokenizerFast

Construct a "fast" BART tokenizer (backed by HuggingFace's tokenizers library), derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beginning of the sentence (without space) or not:

Example
>>> from transformers import BartTokenizerFast
...
>>> tokenizer = BartTokenizerFast.from_pretrained("facebook/bart-base")
>>> tokenizer("Hello world")["input_ids"]
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")["input_ids"]
[0, 20920, 232, 2]

You can get around that behavior by passing add_prefix_space=True when instantiating this tokenizer or when you call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

When used with is_split_into_words=True, this tokenizer needs to be instantiated with add_prefix_space=True.

This tokenizer inherits from [PreTrainedTokenizerFast] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

PARAMETER DESCRIPTION
vocab_file

Path to the vocabulary file.

TYPE: `str` DEFAULT: None

merges_file

Path to the merges file.

TYPE: `str` DEFAULT: None

errors

Paradigm to follow when decoding bytes to UTF-8. See bytes.decode for more information.

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

bos_token

The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the cls_token.

TYPE: `str`, *optional*, defaults to `"<s>"` DEFAULT: '<s>'

eos_token

The end of sequence token.

When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the sep_token.

TYPE: `str`, *optional*, defaults to `"</s>"` DEFAULT: '</s>'

sep_token

The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.

TYPE: `str`, *optional*, defaults to `"</s>"` DEFAULT: '</s>'

cls_token

The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.

TYPE: `str`, *optional*, defaults to `"<s>"` DEFAULT: '<s>'

unk_token

The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.

TYPE: `str`, *optional*, defaults to `"<unk>"` DEFAULT: '<unk>'

pad_token

The token used for padding, for example when batching sequences of different lengths.

TYPE: `str`, *optional*, defaults to `"<pad>"` DEFAULT: '<pad>'

mask_token

The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict.

TYPE: `str`, *optional*, defaults to `"<mask>"` DEFAULT: '<mask>'

add_prefix_space

Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (BART tokenizer detect beginning of words by the preceding space).

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

trim_offsets

Whether the post processing step should trim offsets to avoid including whitespaces.

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

Source code in mindnlp/transformers/models/bart/tokenization_bart_fast.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
class BartTokenizerFast(PreTrainedTokenizerFast):
    r"""
    Construct a "fast" BART tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer,
    using byte-level Byte-Pair-Encoding.

    This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
    be encoded differently whether it is at the beginning of the sentence (without space) or not:

    Example:
        ```python
        >>> from transformers import BartTokenizerFast
        ...
        >>> tokenizer = BartTokenizerFast.from_pretrained("facebook/bart-base")
        >>> tokenizer("Hello world")["input_ids"]
        [0, 31414, 232, 2]
        >>> tokenizer(" Hello world")["input_ids"]
        [0, 20920, 232, 2]
        ```

    You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
    call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

    <Tip>

    When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.

    </Tip>

    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
    refer to this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_token`.

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        unk_token (`str`, *optional*, defaults to `"<unk>"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        mask_token (`str`, *optional*, defaults to `"<mask>"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word. (BART tokenizer detect beginning of words by the preceding space).
        trim_offsets (`bool`, *optional*, defaults to `True`):
            Whether the post processing step should trim offsets to avoid including whitespaces.
    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]
    slow_tokenizer_class = BartTokenizer

    def __init__(
        self,
        vocab_file=None,
        merges_file=None,
        tokenizer_file=None,
        errors="replace",
        bos_token="<s>",
        eos_token="</s>",
        sep_token="</s>",
        cls_token="<s>",
        unk_token="<unk>",
        pad_token="<pad>",
        mask_token="<mask>",
        add_prefix_space=False,
        trim_offsets=True,
        **kwargs,
    ):
        """
        This method initializes an instance of the BartTokenizerFast class.

        Args:
            self: The instance of the BartTokenizerFast class.
            vocab_file (str, optional): The path to the vocabulary file. Defaults to None.
            merges_file (str, optional): The path to the merges file. Defaults to None.
            tokenizer_file (str, optional): The path to the tokenizer file. Defaults to None.
            errors (str, optional): The error handling scheme. Defaults to 'replace'.
            bos_token (str, optional): The beginning of sentence token. Defaults to '<s>'.
            eos_token (str, optional): The end of sentence token. Defaults to '</s>'.
            sep_token (str, optional): The separator token. Defaults to '</s>'.
            cls_token (str, optional): The classification token. Defaults to '<s>'.
            unk_token (str, optional): The unknown token. Defaults to '<unk>'.
            pad_token (str, optional): The padding token. Defaults to '<pad>'.
            mask_token (str, optional): The mask token. Defaults to '<mask>'.
            add_prefix_space (bool, optional): Whether to add prefix space. Defaults to False.
            trim_offsets (bool, optional): Whether to trim offsets. Defaults to True.
            **kwargs: Additional keyword arguments.

        Returns:
            None.

        Raises:
            None
        """
        # we have to specify that this tokens is special otherwise adding it will reset the normalized flag to `False` in `add_special_tokens`
        mask_token = (
            AddedToken(mask_token, lstrip=True, normalized=True, special=True)
            if isinstance(mask_token, str)
            else mask_token
        )
        super().__init__(
            vocab_file,
            merges_file,
            tokenizer_file=tokenizer_file,
            errors=errors,
            bos_token=bos_token,
            eos_token=eos_token,
            sep_token=sep_token,
            cls_token=cls_token,
            unk_token=unk_token,
            pad_token=pad_token,
            mask_token=mask_token,
            add_prefix_space=add_prefix_space,
            trim_offsets=trim_offsets,
            **kwargs,
        )

        pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
        if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
            pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
            pre_tok_state["add_prefix_space"] = add_prefix_space
            self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)

        self.add_prefix_space = add_prefix_space

        # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
        tokenizer_component = "post_processor"
        tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
        if tokenizer_component_instance:
            state = json.loads(tokenizer_component_instance.__getstate__())

            # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
            if "sep" in state:
                state["sep"] = tuple(state["sep"])
            if "cls" in state:
                state["cls"] = tuple(state["cls"])

            changes_to_apply = False

            if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
                state["add_prefix_space"] = add_prefix_space
                changes_to_apply = True

            if state.get("trim_offsets", trim_offsets) != trim_offsets:
                state["trim_offsets"] = trim_offsets
                changes_to_apply = True

            if changes_to_apply:
                component_class = getattr(processors, state.pop("type"))
                new_value = component_class(**state)
                setattr(self.backend_tokenizer, tokenizer_component, new_value)

    @property
    def mask_token(self) -> str:
        """
        `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
        having been set.

        BART tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
        comprise the space before the *<mask>*.
        """
        if self._mask_token is None:
            if self.verbose:
                logger.error("Using mask_token, but it is not set yet.")
            return None
        return str(self._mask_token)

    @mask_token.setter
    def mask_token(self, value):
        """
        Overriding the default behavior of the mask token to have it eat the space before it.

        This is needed to preserve backward compatibility with all the previously used models based on Bart.
        """
        # Mask token behave like a normal word, i.e. include the space before it
        # So we set lstrip to True
        value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
        self._mask_token = value

    def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
        """
        This method '_batch_encode_plus' is defined in the class 'BartTokenizerFast' and is responsible for batch encoding input sequences.

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

        Returns:
            BatchEncoding: A dictionary-like object containing the encoded inputs.

        Raises:
            ValueError: Raised if the parameter 'is_split_into_words' is set to True but 'add_prefix_space' is False.
                In such cases, it indicates that the tokenizer needs to be instantiated with
                'add_prefix_space=True' to work with pretokenized inputs.
        """
        is_split_into_words = kwargs.get("is_split_into_words", False)

        if is_split_into_words and not self.add_prefix_space:
            raise ValueError(
                f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
                "to use it with pretokenized inputs."
            )

        return super()._batch_encode_plus(*args, **kwargs)

    def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
        """
        This method encodes inputs into a batch encoding using the BartTokenizerFast class.

        Args:
            self (BartTokenizerFast): The instance of the BartTokenizerFast class.

            *args: Variable length argument list.

            **kwargs: Arbitrary keyword arguments.
                is_split_into_words (bool, optional): Indicates whether the input is split into words. Defaults to False.

        Returns:
            BatchEncoding: A batch encoding containing the encoded inputs.

        Raises:
            ValueError: If is_split_into_words is True and add_prefix_space is False, a ValueError is raised indicating that
                the BartTokenizerFast instance needs to be instantiated with add_prefix_space=True to use it with pretokenized inputs.
        """
        is_split_into_words = kwargs.get("is_split_into_words", False)

        if is_split_into_words and not self.add_prefix_space:
            raise ValueError(
                f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
                "to use it with pretokenized inputs."
            )

        return super()._encode_plus(*args, **kwargs)

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        '''
        Save the vocabulary files for the tokenizer.

        Args:
            self (BartTokenizerFast): The instance of the BartTokenizerFast class.
            save_directory (str): The directory where the vocabulary files will be saved.
            filename_prefix (Optional[str]): The prefix to be added to the filename of the saved vocabulary files. Default is None.

        Returns:
            Tuple[str]: A tuple containing the filenames of the saved vocabulary files.

        Raises:
            None: Any exceptions raised by the underlying tokenizer model.save method.
        '''
        files = self._tokenizer.model.save(save_directory, name=filename_prefix)
        return tuple(files)

    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        """
        This method builds inputs with special tokens for the BartTokenizerFast class.

        Args:
            self: The instance of the BartTokenizerFast class.
            token_ids_0: A list of token IDs representing the first sequence.
            token_ids_1: A list of token IDs representing the second sequence. This parameter is optional and defaults to None.

        Returns:
            None: The method modifies the input token lists in place.

        Raises:
            None.
        """
        output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
        if token_ids_1 is None:
            return output

        return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
        make use of token type ids, therefore a list of zeros is returned.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of zeros.
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]

        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

mindnlp.transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token: str property writable

str: Mask token, to use when training a model with masked-language modeling. Log an error if used while not having been set.

BART tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily comprise the space before the .

mindnlp.transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.__init__(vocab_file=None, merges_file=None, tokenizer_file=None, errors='replace', bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_token='<s>', unk_token='<unk>', pad_token='<pad>', mask_token='<mask>', add_prefix_space=False, trim_offsets=True, **kwargs)

This method initializes an instance of the BartTokenizerFast class.

PARAMETER DESCRIPTION
self

The instance of the BartTokenizerFast class.

vocab_file

The path to the vocabulary file. Defaults to None.

TYPE: str DEFAULT: None

merges_file

The path to the merges file. Defaults to None.

TYPE: str DEFAULT: None

tokenizer_file

The path to the tokenizer file. Defaults to None.

TYPE: str DEFAULT: None

errors

The error handling scheme. Defaults to 'replace'.

TYPE: str DEFAULT: 'replace'

bos_token

The beginning of sentence token. Defaults to ''.

TYPE: str DEFAULT: '<s>'

eos_token

The end of sentence token. Defaults to ''.

TYPE: str DEFAULT: '</s>'

sep_token

The separator token. Defaults to ''.

TYPE: str DEFAULT: '</s>'

cls_token

The classification token. Defaults to ''.

TYPE: str DEFAULT: '<s>'

unk_token

The unknown token. Defaults to ''.

TYPE: str DEFAULT: '<unk>'

pad_token

The padding token. Defaults to ''.

TYPE: str DEFAULT: '<pad>'

mask_token

The mask token. Defaults to ''.

TYPE: str DEFAULT: '<mask>'

add_prefix_space

Whether to add prefix space. Defaults to False.

TYPE: bool DEFAULT: False

trim_offsets

Whether to trim offsets. Defaults to True.

TYPE: bool DEFAULT: True

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/bart/tokenization_bart_fast.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(
    self,
    vocab_file=None,
    merges_file=None,
    tokenizer_file=None,
    errors="replace",
    bos_token="<s>",
    eos_token="</s>",
    sep_token="</s>",
    cls_token="<s>",
    unk_token="<unk>",
    pad_token="<pad>",
    mask_token="<mask>",
    add_prefix_space=False,
    trim_offsets=True,
    **kwargs,
):
    """
    This method initializes an instance of the BartTokenizerFast class.

    Args:
        self: The instance of the BartTokenizerFast class.
        vocab_file (str, optional): The path to the vocabulary file. Defaults to None.
        merges_file (str, optional): The path to the merges file. Defaults to None.
        tokenizer_file (str, optional): The path to the tokenizer file. Defaults to None.
        errors (str, optional): The error handling scheme. Defaults to 'replace'.
        bos_token (str, optional): The beginning of sentence token. Defaults to '<s>'.
        eos_token (str, optional): The end of sentence token. Defaults to '</s>'.
        sep_token (str, optional): The separator token. Defaults to '</s>'.
        cls_token (str, optional): The classification token. Defaults to '<s>'.
        unk_token (str, optional): The unknown token. Defaults to '<unk>'.
        pad_token (str, optional): The padding token. Defaults to '<pad>'.
        mask_token (str, optional): The mask token. Defaults to '<mask>'.
        add_prefix_space (bool, optional): Whether to add prefix space. Defaults to False.
        trim_offsets (bool, optional): Whether to trim offsets. Defaults to True.
        **kwargs: Additional keyword arguments.

    Returns:
        None.

    Raises:
        None
    """
    # we have to specify that this tokens is special otherwise adding it will reset the normalized flag to `False` in `add_special_tokens`
    mask_token = (
        AddedToken(mask_token, lstrip=True, normalized=True, special=True)
        if isinstance(mask_token, str)
        else mask_token
    )
    super().__init__(
        vocab_file,
        merges_file,
        tokenizer_file=tokenizer_file,
        errors=errors,
        bos_token=bos_token,
        eos_token=eos_token,
        sep_token=sep_token,
        cls_token=cls_token,
        unk_token=unk_token,
        pad_token=pad_token,
        mask_token=mask_token,
        add_prefix_space=add_prefix_space,
        trim_offsets=trim_offsets,
        **kwargs,
    )

    pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
    if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
        pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
        pre_tok_state["add_prefix_space"] = add_prefix_space
        self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)

    self.add_prefix_space = add_prefix_space

    # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
    tokenizer_component = "post_processor"
    tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
    if tokenizer_component_instance:
        state = json.loads(tokenizer_component_instance.__getstate__())

        # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
        if "sep" in state:
            state["sep"] = tuple(state["sep"])
        if "cls" in state:
            state["cls"] = tuple(state["cls"])

        changes_to_apply = False

        if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
            state["add_prefix_space"] = add_prefix_space
            changes_to_apply = True

        if state.get("trim_offsets", trim_offsets) != trim_offsets:
            state["trim_offsets"] = trim_offsets
            changes_to_apply = True

        if changes_to_apply:
            component_class = getattr(processors, state.pop("type"))
            new_value = component_class(**state)
            setattr(self.backend_tokenizer, tokenizer_component, new_value)

mindnlp.transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

This method builds inputs with special tokens for the BartTokenizerFast class.

PARAMETER DESCRIPTION
self

The instance of the BartTokenizerFast class.

token_ids_0

A list of token IDs representing the first sequence.

token_ids_1

A list of token IDs representing the second sequence. This parameter is optional and defaults to None.

DEFAULT: None

RETURNS DESCRIPTION
None

The method modifies the input token lists in place.

Source code in mindnlp/transformers/models/bart/tokenization_bart_fast.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    """
    This method builds inputs with special tokens for the BartTokenizerFast class.

    Args:
        self: The instance of the BartTokenizerFast class.
        token_ids_0: A list of token IDs representing the first sequence.
        token_ids_1: A list of token IDs representing the second sequence. This parameter is optional and defaults to None.

    Returns:
        None: The method modifies the input token lists in place.

    Raises:
        None.
    """
    output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
    if token_ids_1 is None:
        return output

    return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]

mindnlp.transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not make use of token type ids, therefore a list of zeros is returned.

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

TYPE: `List[int]`, *optional* DEFAULT: None

RETURNS DESCRIPTION
List[int]

List[int]: List of zeros.

Source code in mindnlp/transformers/models/bart/tokenization_bart_fast.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def create_token_type_ids_from_sequences(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Create a mask from the two sequences passed to be used in a sequence-pair classification task. BART does not
    make use of token type ids, therefore a list of zeros is returned.

    Args:
        token_ids_0 (`List[int]`):
            List of IDs.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.

    Returns:
        `List[int]`: List of zeros.
    """
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]

    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

mindnlp.transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary files for the tokenizer.

PARAMETER DESCRIPTION
self

The instance of the BartTokenizerFast class.

TYPE: BartTokenizerFast

save_directory

The directory where the vocabulary files will be saved.

TYPE: str

filename_prefix

The prefix to be added to the filename of the saved vocabulary files. Default is None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the filenames of the saved vocabulary files.

RAISES DESCRIPTION
None

Any exceptions raised by the underlying tokenizer model.save method.

Source code in mindnlp/transformers/models/bart/tokenization_bart_fast.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    '''
    Save the vocabulary files for the tokenizer.

    Args:
        self (BartTokenizerFast): The instance of the BartTokenizerFast class.
        save_directory (str): The directory where the vocabulary files will be saved.
        filename_prefix (Optional[str]): The prefix to be added to the filename of the saved vocabulary files. Default is None.

    Returns:
        Tuple[str]: A tuple containing the filenames of the saved vocabulary files.

    Raises:
        None: Any exceptions raised by the underlying tokenizer model.save method.
    '''
    files = self._tokenizer.model.save(save_directory, name=filename_prefix)
    return tuple(files)