Skip to content

gemma

mindnlp.transformers.models.gemma.configuration_gemma

Gemma model configuration

mindnlp.transformers.models.gemma.configuration_gemma.GemmaConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [GemmaModel]. It is used to instantiate an Gemma 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 Gemma-7B.

e.g. google/gemma-7b

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

PARAMETER DESCRIPTION
vocab_size

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

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

hidden_size

Dimension of the hidden representations.

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

intermediate_size

Dimension of the MLP representations.

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

num_hidden_layers

Number of hidden layers in the Transformer decoder.

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

num_attention_heads

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

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

num_key_value_heads

This is the number of key_value heads that should be used to implement Grouped Query Attention. If num_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), if num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be forwarded by meanpooling all the original heads within that group. For more details checkout this paper. If it is not specified, will default to num_attention_heads.

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

head_dim

The attention head dimension.

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

hidden_act

The non-linear activation function (function or string) in the decoder.

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

max_position_embeddings

The maximum sequence length that this model might ever be used with.

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

initializer_range

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

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

rms_norm_eps

The epsilon used by the rms normalization layers.

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

use_cache

Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if config.is_decoder=True.

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

pad_token_id

Padding token id.

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

eos_token_id

End of stream token id.

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

bos_token_id

Beginning of stream token id.

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

tie_word_embeddings

Whether to tie weight embeddings

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

rope_theta

The base period of the RoPE embeddings.

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

attention_bias

Whether to use a bias in the query, key, value and output projection layers during self-attention.

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

attention_dropout

The dropout ratio for the attention probabilities.

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

Example
>>> from transformers import GemmaModel, GemmaConfig
...
>>> # Initializing a Gemma gemma-7b style configuration
>>> configuration = GemmaConfig()
...
>>> # Initializing a model from the gemma-7b style configuration
>>> model = GemmaModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/gemma/configuration_gemma.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 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
class GemmaConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`GemmaModel`]. It is used to instantiate an Gemma
    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 Gemma-7B.

    e.g. [google/gemma-7b](https://hf-mirror.com/google/gemma-7b)

    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 256000):
            Vocabulary size of the Gemma model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`GemmaModel`]
        hidden_size (`int`, *optional*, defaults to 3072):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 24576):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 28):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer decoder.
        num_key_value_heads (`int`, *optional*, defaults to 16):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be forwarded
            by meanpooling all the original heads within that group. For more details checkout [this
            paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
            `num_attention_heads`.
        head_dim (`int`, *optional*, defaults to 256):
            The attention head dimension.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 8192):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the rms normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        pad_token_id (`int`, *optional*, defaults to 0):
            Padding token id.
        eos_token_id (`int`, *optional*, defaults to 1):
            End of stream token id.
        bos_token_id (`int`, *optional*, defaults to 2):
            Beginning of stream token id.
        tie_word_embeddings (`bool`, *optional*, defaults to `True`):
            Whether to tie weight embeddings
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
            Whether to use a bias in the query, key, value and output projection layers during self-attention.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.

    Example:
        ```python
        >>> from transformers import GemmaModel, GemmaConfig
        ...
        >>> # Initializing a Gemma gemma-7b style configuration
        >>> configuration = GemmaConfig()
        ...
        >>> # Initializing a model from the gemma-7b style configuration
        >>> model = GemmaModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "gemma"
    keys_to_ignore_at_inference = ["past_key_values"]

    def __init__(
        self,
        vocab_size=256000,
        hidden_size=3072,
        intermediate_size=24576,
        num_hidden_layers=28,
        num_attention_heads=16,
        num_key_value_heads=16,
        head_dim=256,
        hidden_act="gelu",
        max_position_embeddings=8192,
        initializer_range=0.02,
        rms_norm_eps=1e-6,
        use_cache=True,
        pad_token_id=0,
        eos_token_id=1,
        bos_token_id=2,
        tie_word_embeddings=True,
        rope_theta=10000.0,
        attention_bias=False,
        attention_dropout=0.0,
        **kwargs,
    ):
        """
        Initializes a new instance of GemmaConfig.

        Args:
            self: The object itself.
            vocab_size (int, optional): The size of the vocabulary. Defaults to 256000.
            hidden_size (int, optional): The size of the hidden layers. Defaults to 3072.
            intermediate_size (int, optional): The size of the intermediate layers. Defaults to 24576.
            num_hidden_layers (int, optional): The number of hidden layers. Defaults to 28.
            num_attention_heads (int, optional): The number of attention heads. Defaults to 16.
            num_key_value_heads (int, optional): The number of key-value attention heads. Defaults to 16.
            head_dim (int, optional): The dimension of the attention heads. Defaults to 256.
            hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
            max_position_embeddings (int, optional): The maximum position embeddings. Defaults to 8192.
            initializer_range (float, optional): The range for weight initialization. Defaults to 0.02.
            rms_norm_eps (float, optional): The epsilon value for RMS normalization. Defaults to 1e-06.
            use_cache (bool, optional): Whether to use caching. Defaults to True.
            pad_token_id (int, optional): The ID for padding token. Defaults to 0.
            eos_token_id (int, optional): The ID for end-of-sequence token. Defaults to 1.
            bos_token_id (int, optional): The ID for beginning-of-sequence token. Defaults to 2.
            tie_word_embeddings (bool, optional): Whether to tie word embeddings. Defaults to True.
            rope_theta (float, optional): The theta value for ROPE. Defaults to 10000.0.
            attention_bias (bool, optional): Whether to use attention bias. Defaults to False.
            attention_dropout (float, optional): The dropout rate for attention. Defaults to 0.0.

        Returns:
            None.

        Raises:
            ValueError: If any of the input parameters is invalid.
        """
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.head_dim = head_dim
        self.num_key_value_heads = num_key_value_heads
        self.hidden_act = hidden_act
        self.initializer_range = initializer_range
        self.rms_norm_eps = rms_norm_eps
        self.use_cache = use_cache
        self.rope_theta = rope_theta
        self.attention_bias = attention_bias
        self.attention_dropout = attention_dropout

        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            tie_word_embeddings=tie_word_embeddings,
            **kwargs,
        )

mindnlp.transformers.models.gemma.configuration_gemma.GemmaConfig.__init__(vocab_size=256000, hidden_size=3072, intermediate_size=24576, num_hidden_layers=28, num_attention_heads=16, num_key_value_heads=16, head_dim=256, hidden_act='gelu', max_position_embeddings=8192, initializer_range=0.02, rms_norm_eps=1e-06, use_cache=True, pad_token_id=0, eos_token_id=1, bos_token_id=2, tie_word_embeddings=True, rope_theta=10000.0, attention_bias=False, attention_dropout=0.0, **kwargs)

Initializes a new instance of GemmaConfig.

PARAMETER DESCRIPTION
self

The object itself.

vocab_size

The size of the vocabulary. Defaults to 256000.

TYPE: int DEFAULT: 256000

hidden_size

The size of the hidden layers. Defaults to 3072.

TYPE: int DEFAULT: 3072

intermediate_size

The size of the intermediate layers. Defaults to 24576.

TYPE: int DEFAULT: 24576

num_hidden_layers

The number of hidden layers. Defaults to 28.

TYPE: int DEFAULT: 28

num_attention_heads

The number of attention heads. Defaults to 16.

TYPE: int DEFAULT: 16

num_key_value_heads

The number of key-value attention heads. Defaults to 16.

TYPE: int DEFAULT: 16

head_dim

The dimension of the attention heads. Defaults to 256.

TYPE: int DEFAULT: 256

hidden_act

The activation function for the hidden layers. Defaults to 'gelu'.

TYPE: str DEFAULT: 'gelu'

max_position_embeddings

The maximum position embeddings. Defaults to 8192.

TYPE: int DEFAULT: 8192

initializer_range

The range for weight initialization. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

rms_norm_eps

The epsilon value for RMS normalization. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

use_cache

Whether to use caching. Defaults to True.

TYPE: bool DEFAULT: True

pad_token_id

The ID for padding token. Defaults to 0.

TYPE: int DEFAULT: 0

eos_token_id

The ID for end-of-sequence token. Defaults to 1.

TYPE: int DEFAULT: 1

bos_token_id

The ID for beginning-of-sequence token. Defaults to 2.

TYPE: int DEFAULT: 2

tie_word_embeddings

Whether to tie word embeddings. Defaults to True.

TYPE: bool DEFAULT: True

rope_theta

The theta value for ROPE. Defaults to 10000.0.

TYPE: float DEFAULT: 10000.0

attention_bias

Whether to use attention bias. Defaults to False.

TYPE: bool DEFAULT: False

attention_dropout

The dropout rate for attention. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If any of the input parameters is invalid.

Source code in mindnlp/transformers/models/gemma/configuration_gemma.py
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
def __init__(
    self,
    vocab_size=256000,
    hidden_size=3072,
    intermediate_size=24576,
    num_hidden_layers=28,
    num_attention_heads=16,
    num_key_value_heads=16,
    head_dim=256,
    hidden_act="gelu",
    max_position_embeddings=8192,
    initializer_range=0.02,
    rms_norm_eps=1e-6,
    use_cache=True,
    pad_token_id=0,
    eos_token_id=1,
    bos_token_id=2,
    tie_word_embeddings=True,
    rope_theta=10000.0,
    attention_bias=False,
    attention_dropout=0.0,
    **kwargs,
):
    """
    Initializes a new instance of GemmaConfig.

    Args:
        self: The object itself.
        vocab_size (int, optional): The size of the vocabulary. Defaults to 256000.
        hidden_size (int, optional): The size of the hidden layers. Defaults to 3072.
        intermediate_size (int, optional): The size of the intermediate layers. Defaults to 24576.
        num_hidden_layers (int, optional): The number of hidden layers. Defaults to 28.
        num_attention_heads (int, optional): The number of attention heads. Defaults to 16.
        num_key_value_heads (int, optional): The number of key-value attention heads. Defaults to 16.
        head_dim (int, optional): The dimension of the attention heads. Defaults to 256.
        hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
        max_position_embeddings (int, optional): The maximum position embeddings. Defaults to 8192.
        initializer_range (float, optional): The range for weight initialization. Defaults to 0.02.
        rms_norm_eps (float, optional): The epsilon value for RMS normalization. Defaults to 1e-06.
        use_cache (bool, optional): Whether to use caching. Defaults to True.
        pad_token_id (int, optional): The ID for padding token. Defaults to 0.
        eos_token_id (int, optional): The ID for end-of-sequence token. Defaults to 1.
        bos_token_id (int, optional): The ID for beginning-of-sequence token. Defaults to 2.
        tie_word_embeddings (bool, optional): Whether to tie word embeddings. Defaults to True.
        rope_theta (float, optional): The theta value for ROPE. Defaults to 10000.0.
        attention_bias (bool, optional): Whether to use attention bias. Defaults to False.
        attention_dropout (float, optional): The dropout rate for attention. Defaults to 0.0.

    Returns:
        None.

    Raises:
        ValueError: If any of the input parameters is invalid.
    """
    self.vocab_size = vocab_size
    self.max_position_embeddings = max_position_embeddings
    self.hidden_size = hidden_size
    self.intermediate_size = intermediate_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.head_dim = head_dim
    self.num_key_value_heads = num_key_value_heads
    self.hidden_act = hidden_act
    self.initializer_range = initializer_range
    self.rms_norm_eps = rms_norm_eps
    self.use_cache = use_cache
    self.rope_theta = rope_theta
    self.attention_bias = attention_bias
    self.attention_dropout = attention_dropout

    super().__init__(
        pad_token_id=pad_token_id,
        bos_token_id=bos_token_id,
        eos_token_id=eos_token_id,
        tie_word_embeddings=tie_word_embeddings,
        **kwargs,
    )

mindnlp.transformers.models.gemma.modeling_gemma

MindSpore Gemma model.

mindnlp.transformers.models.gemma.modeling_gemma.GemmaAttention

Bases: Module

Multi-headed attention from 'Attention Is All You Need' paper

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
class GemmaAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""
    # Ignore copy
    def __init__(self, config: GemmaConfig, layer_idx: Optional[int] = None):
        """
        Initializes a new instance of the GemmaAttention class.

        Args:
            self: The object itself.
            config (GemmaConfig): The configuration object for the attention layer.
            layer_idx (Optional[int]): The index of the layer. Defaults to None.

        Returns:
            None.

        Raises:
            ValueError: If the `hidden_size` is not divisible by `num_heads`.

        Note:
            - If `layer_idx` is not provided, a warning message will be logged to indicate potential errors during the
            forward call if caching is used.
            - The GemmaAttention class performs attention calculations in the transformer model. It takes in a
            configuration object and initializes various attributes based on the provided configuration.
            - The attention_dropout attribute determines the dropout rate for attention weights.
            - The hidden_size attribute specifies the dimensionality of the hidden state.
            - The num_heads attribute specifies the number of attention heads.
            - The head_dim attribute specifies the dimensionality of each attention head.
            - The num_key_value_heads attribute specifies the number of key-value attention heads.
            - The num_key_value_groups attribute specifies the number of groups for key-value attention heads.
            - The max_position_embeddings attribute specifies the maximum number of position embeddings.
            - The rope_theta attribute specifies the base value for the rotary position encoding.
            - The is_causal attribute is set to True to indicate causal attention.
            - The q_proj attribute is a linear projection layer for the query values.
            - The k_proj attribute is a linear projection layer for the key values.
            - The v_proj attribute is a linear projection layer for the value values.
            - The o_proj attribute is a linear projection layer for the output values.
            - The rotary_emb attribute is a GemmaRotaryEmbedding object for rotary position encoding.
            - If the hidden_size is not divisible by num_heads, a ValueError will be raised.

        Example:
            ```python
            >>> config = GemmaConfig(hidden_size=768, num_attention_heads=12)
            >>> attention = GemmaAttention(config)
            ```
        """
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        if layer_idx is None:
            logger.warning_once(
                f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
                "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
                "when creating this class."
            )

        self.attention_dropout = config.attention_dropout
        self.hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads
        self.head_dim = config.head_dim
        self.num_key_value_heads = config.num_key_value_heads
        self.num_key_value_groups = self.num_heads // self.num_key_value_heads
        self.max_position_embeddings = config.max_position_embeddings
        self.rope_theta = config.rope_theta
        self.is_causal = True

        if self.hidden_size % self.num_heads != 0:
            raise ValueError(
                f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
                f" and `num_heads`: {self.num_heads})."
            )

        self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
        self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
        self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
        self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
        self.rotary_emb = GemmaRotaryEmbedding(
            self.head_dim,
            max_position_embeddings=self.max_position_embeddings,
            base=self.rope_theta,
        )

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        past_key_value: Optional[Cache] = None,
        output_attentions: bool = False,
        use_cache: bool = False,
        cache_position: Optional[mindspore.Tensor] = None,
        **kwargs,
    ) -> Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
        '''
        This method forwards attention output using the given hidden states and optional attention mask, position ids,
        past key value, and other parameters.

        Args:
            self: The object instance.
            hidden_states (mindspore.Tensor): The input hidden states of shape (batch_size, sequence_length, hidden_size).
            attention_mask (Optional[mindspore.Tensor]):
                An optional attention mask of shape (batch_size, sequence_length, sequence_length) to mask the
                attention scores. Default is None.
            position_ids (Optional[mindspore.Tensor]):
                An optional tensor of shape (batch_size, sequence_length) containing the position indices of the input tokens.
            past_key_value (Optional[Cache]):
                An optional cache of previous key and value states. Default is None.
            output_attentions (bool): A flag indicating whether to output the attention weights. Default is False.
            use_cache (bool): A flag indicating whether to use cache for previous key and value states. Default is False.
            cache_position (Optional[mindspore.Tensor]): An optional cache position tensor. Default is None.
            **kwargs: Additional keyword arguments.

        Returns:
            Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
                A tuple containing the attention output tensor of shape (batch_size, sequence_length, hidden_size),
                optional attention weights tensor, and optional tuple of key and value cache states.

        Raises:
            ValueError: If the shape of `attn_output` does not match the expected shape
                (batch_size, num_heads, sequence_length, head_dim).
        '''
        bsz, q_len, _ = hidden_states.shape

        query_states = self.q_proj(hidden_states)
        key_states = self.k_proj(hidden_states)
        value_states = self.v_proj(hidden_states)

        query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).swapaxes(1, 2)
        key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).swapaxes(1, 2)
        value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).swapaxes(1, 2)

        past_key_value = getattr(self, "past_key_value", past_key_value)
        cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)

        if past_key_value is not None:
            # sin and cos are specific to RoPE models; position_ids needed for the static cache
            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
            key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

        key_states = repeat_kv(key_states, self.num_key_value_groups)
        value_states = repeat_kv(value_states, self.num_key_value_groups)

        attn_weights = ops.matmul(query_states, key_states.swapaxes(2, 3)) / math.sqrt(self.head_dim)

        if attention_mask is not None:  # no matter the length, we just slice it
            if cache_position is not None:
                causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
            else:
                causal_mask = attention_mask
            attn_weights = attn_weights + causal_mask

        # upcast attention to fp32
        attn_weights = ops.softmax(attn_weights, axis=-1, dtype=mindspore.float32).to(query_states.dtype)
        attn_weights = ops.dropout(attn_weights, p=self.attention_dropout, training=self.training)
        attn_output = ops.matmul(attn_weights, value_states)

        if attn_output.shape != (bsz, self.num_heads, q_len, self.head_dim):
            raise ValueError(
                f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
                f" {attn_output.shape}"
            )

        attn_output = attn_output.swapaxes(1, 2)

        attn_output = attn_output.view(bsz, q_len, -1)
        attn_output = self.o_proj(attn_output)

        if not output_attentions:
            attn_weights = None

        return attn_output, attn_weights, past_key_value

mindnlp.transformers.models.gemma.modeling_gemma.GemmaAttention.__init__(config, layer_idx=None)

Initializes a new instance of the GemmaAttention class.

PARAMETER DESCRIPTION
self

The object itself.

config

The configuration object for the attention layer.

TYPE: GemmaConfig

layer_idx

The index of the layer. Defaults to None.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the hidden_size is not divisible by num_heads.

Note
  • If layer_idx is not provided, a warning message will be logged to indicate potential errors during the forward call if caching is used.
  • The GemmaAttention class performs attention calculations in the transformer model. It takes in a configuration object and initializes various attributes based on the provided configuration.
  • The attention_dropout attribute determines the dropout rate for attention weights.
  • The hidden_size attribute specifies the dimensionality of the hidden state.
  • The num_heads attribute specifies the number of attention heads.
  • The head_dim attribute specifies the dimensionality of each attention head.
  • The num_key_value_heads attribute specifies the number of key-value attention heads.
  • The num_key_value_groups attribute specifies the number of groups for key-value attention heads.
  • The max_position_embeddings attribute specifies the maximum number of position embeddings.
  • The rope_theta attribute specifies the base value for the rotary position encoding.
  • The is_causal attribute is set to True to indicate causal attention.
  • The q_proj attribute is a linear projection layer for the query values.
  • The k_proj attribute is a linear projection layer for the key values.
  • The v_proj attribute is a linear projection layer for the value values.
  • The o_proj attribute is a linear projection layer for the output values.
  • The rotary_emb attribute is a GemmaRotaryEmbedding object for rotary position encoding.
  • If the hidden_size is not divisible by num_heads, a ValueError will be raised.
Example
>>> config = GemmaConfig(hidden_size=768, num_attention_heads=12)
>>> attention = GemmaAttention(config)
Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
def __init__(self, config: GemmaConfig, layer_idx: Optional[int] = None):
    """
    Initializes a new instance of the GemmaAttention class.

    Args:
        self: The object itself.
        config (GemmaConfig): The configuration object for the attention layer.
        layer_idx (Optional[int]): The index of the layer. Defaults to None.

    Returns:
        None.

    Raises:
        ValueError: If the `hidden_size` is not divisible by `num_heads`.

    Note:
        - If `layer_idx` is not provided, a warning message will be logged to indicate potential errors during the
        forward call if caching is used.
        - The GemmaAttention class performs attention calculations in the transformer model. It takes in a
        configuration object and initializes various attributes based on the provided configuration.
        - The attention_dropout attribute determines the dropout rate for attention weights.
        - The hidden_size attribute specifies the dimensionality of the hidden state.
        - The num_heads attribute specifies the number of attention heads.
        - The head_dim attribute specifies the dimensionality of each attention head.
        - The num_key_value_heads attribute specifies the number of key-value attention heads.
        - The num_key_value_groups attribute specifies the number of groups for key-value attention heads.
        - The max_position_embeddings attribute specifies the maximum number of position embeddings.
        - The rope_theta attribute specifies the base value for the rotary position encoding.
        - The is_causal attribute is set to True to indicate causal attention.
        - The q_proj attribute is a linear projection layer for the query values.
        - The k_proj attribute is a linear projection layer for the key values.
        - The v_proj attribute is a linear projection layer for the value values.
        - The o_proj attribute is a linear projection layer for the output values.
        - The rotary_emb attribute is a GemmaRotaryEmbedding object for rotary position encoding.
        - If the hidden_size is not divisible by num_heads, a ValueError will be raised.

    Example:
        ```python
        >>> config = GemmaConfig(hidden_size=768, num_attention_heads=12)
        >>> attention = GemmaAttention(config)
        ```
    """
    super().__init__()
    self.config = config
    self.layer_idx = layer_idx
    if layer_idx is None:
        logger.warning_once(
            f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
            "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
            "when creating this class."
        )

    self.attention_dropout = config.attention_dropout
    self.hidden_size = config.hidden_size
    self.num_heads = config.num_attention_heads
    self.head_dim = config.head_dim
    self.num_key_value_heads = config.num_key_value_heads
    self.num_key_value_groups = self.num_heads // self.num_key_value_heads
    self.max_position_embeddings = config.max_position_embeddings
    self.rope_theta = config.rope_theta
    self.is_causal = True

    if self.hidden_size % self.num_heads != 0:
        raise ValueError(
            f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
            f" and `num_heads`: {self.num_heads})."
        )

    self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
    self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
    self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
    self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
    self.rotary_emb = GemmaRotaryEmbedding(
        self.head_dim,
        max_position_embeddings=self.max_position_embeddings,
        base=self.rope_theta,
    )

mindnlp.transformers.models.gemma.modeling_gemma.GemmaAttention.forward(hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cache_position=None, **kwargs)

This method forwards attention output using the given hidden states and optional attention mask, position ids, past key value, and other parameters.

PARAMETER DESCRIPTION
self

The object instance.

hidden_states

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

TYPE: Tensor

attention_mask

An optional attention mask of shape (batch_size, sequence_length, sequence_length) to mask the attention scores. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

An optional tensor of shape (batch_size, sequence_length) containing the position indices of the input tokens.

TYPE: Optional[Tensor] DEFAULT: None

past_key_value

An optional cache of previous key and value states. Default is None.

TYPE: Optional[Cache] DEFAULT: None

output_attentions

A flag indicating whether to output the attention weights. Default is False.

TYPE: bool DEFAULT: False

use_cache

A flag indicating whether to use cache for previous key and value states. Default is False.

TYPE: bool DEFAULT: False

cache_position

An optional cache position tensor. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION
Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor]]]

Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]: A tuple containing the attention output tensor of shape (batch_size, sequence_length, hidden_size), optional attention weights tensor, and optional tuple of key and value cache states.

RAISES DESCRIPTION
ValueError

If the shape of attn_output does not match the expected shape (batch_size, num_heads, sequence_length, head_dim).

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
def forward(
    self,
    hidden_states: mindspore.Tensor,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    past_key_value: Optional[Cache] = None,
    output_attentions: bool = False,
    use_cache: bool = False,
    cache_position: Optional[mindspore.Tensor] = None,
    **kwargs,
) -> Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
    '''
    This method forwards attention output using the given hidden states and optional attention mask, position ids,
    past key value, and other parameters.

    Args:
        self: The object instance.
        hidden_states (mindspore.Tensor): The input hidden states of shape (batch_size, sequence_length, hidden_size).
        attention_mask (Optional[mindspore.Tensor]):
            An optional attention mask of shape (batch_size, sequence_length, sequence_length) to mask the
            attention scores. Default is None.
        position_ids (Optional[mindspore.Tensor]):
            An optional tensor of shape (batch_size, sequence_length) containing the position indices of the input tokens.
        past_key_value (Optional[Cache]):
            An optional cache of previous key and value states. Default is None.
        output_attentions (bool): A flag indicating whether to output the attention weights. Default is False.
        use_cache (bool): A flag indicating whether to use cache for previous key and value states. Default is False.
        cache_position (Optional[mindspore.Tensor]): An optional cache position tensor. Default is None.
        **kwargs: Additional keyword arguments.

    Returns:
        Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
            A tuple containing the attention output tensor of shape (batch_size, sequence_length, hidden_size),
            optional attention weights tensor, and optional tuple of key and value cache states.

    Raises:
        ValueError: If the shape of `attn_output` does not match the expected shape
            (batch_size, num_heads, sequence_length, head_dim).
    '''
    bsz, q_len, _ = hidden_states.shape

    query_states = self.q_proj(hidden_states)
    key_states = self.k_proj(hidden_states)
    value_states = self.v_proj(hidden_states)

    query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).swapaxes(1, 2)
    key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).swapaxes(1, 2)
    value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).swapaxes(1, 2)

    past_key_value = getattr(self, "past_key_value", past_key_value)
    cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
    query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)

    if past_key_value is not None:
        # sin and cos are specific to RoPE models; position_ids needed for the static cache
        cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

    key_states = repeat_kv(key_states, self.num_key_value_groups)
    value_states = repeat_kv(value_states, self.num_key_value_groups)

    attn_weights = ops.matmul(query_states, key_states.swapaxes(2, 3)) / math.sqrt(self.head_dim)

    if attention_mask is not None:  # no matter the length, we just slice it
        if cache_position is not None:
            causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
        else:
            causal_mask = attention_mask
        attn_weights = attn_weights + causal_mask

    # upcast attention to fp32
    attn_weights = ops.softmax(attn_weights, axis=-1, dtype=mindspore.float32).to(query_states.dtype)
    attn_weights = ops.dropout(attn_weights, p=self.attention_dropout, training=self.training)
    attn_output = ops.matmul(attn_weights, value_states)

    if attn_output.shape != (bsz, self.num_heads, q_len, self.head_dim):
        raise ValueError(
            f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
            f" {attn_output.shape}"
        )

    attn_output = attn_output.swapaxes(1, 2)

    attn_output = attn_output.view(bsz, q_len, -1)
    attn_output = self.o_proj(attn_output)

    if not output_attentions:
        attn_weights = None

    return attn_output, attn_weights, past_key_value

mindnlp.transformers.models.gemma.modeling_gemma.GemmaDecoderLayer

Bases: Module

The GemmaDecoderLayer class represents a single layer of the Gemma decoder. It inherits from the nn.Module class and provides methods for forwarding the decoder layer.

ATTRIBUTE DESCRIPTION
hidden_size

The size of the hidden states in the layer.

TYPE: int

self_attn

The attention mechanism used in the layer.

TYPE: GemmaAttention

mlp

The multi-layer perceptron used in the layer.

TYPE: GemmaMLP

input_layernorm

The layer normalization applied to the input.

TYPE: GemmaRMSNorm

post_attention_layernorm

The layer normalization applied after the attention mechanism.

TYPE: GemmaRMSNorm

METHOD DESCRIPTION
forward

Constructs the decoder layer using the given input and optional arguments. Returns the resulting hidden states and optionally the attention weights and present key value.

PARAMETER DESCRIPTION
hidden_states

Input to the layer of shape (batch, seq_len, embed_dim).

TYPE: Tensor

attention_mask

Attention mask of size (batch_size, sequence_length) if flash attention is used or (batch_size, 1, query_sequence_length, key_sequence_length) if default attention is used.

TYPE: Tensor

output_attentions

Whether or not to return the attentions tensors of all attention layers.

TYPE: bool

use_cache

If set to True, past key value states are returned and can be used to speed up decoding.

TYPE: bool

past_key_value

Cached past key and value projection states.

TYPE: Tuple(Tensor)

cache_position

Position of the cache.

TYPE: Tensor

**kwargs

Additional keyword arguments.

RAISES DESCRIPTION
DeprecationWarning

If 'padding_mask' is passed, a warning is issued indicating that it is deprecated and will be removed in a future version.

RETURNS DESCRIPTION

Tuple[mindspore.Tensor, Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]]: The resulting hidden states and optionally the attention weights and present key value.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
class GemmaDecoderLayer(nn.Module):

    """
    The GemmaDecoderLayer class represents a single layer of the Gemma decoder.
    It inherits from the nn.Module class and provides methods for forwarding the decoder layer.

    Attributes:
        hidden_size (int): The size of the hidden states in the layer.
        self_attn (GemmaAttention): The attention mechanism used in the layer.
        mlp (GemmaMLP): The multi-layer perceptron used in the layer.
        input_layernorm (GemmaRMSNorm): The layer normalization applied to the input.
        post_attention_layernorm (GemmaRMSNorm): The layer normalization applied after the attention mechanism.

    Methods:
        forward:
            Constructs the decoder layer using the given input and optional arguments.
            Returns the resulting hidden states and optionally the attention weights and present key value.

    Args:
        hidden_states (mindspore.Tensor): Input to the layer of shape (batch, seq_len, embed_dim).
        attention_mask (mindspore.Tensor, optional): Attention mask of size (batch_size, sequence_length)
            if flash attention is used or (batch_size, 1, query_sequence_length, key_sequence_length) if default
            attention is used.
        output_attentions (bool, optional): Whether or not to return the attentions tensors of all attention layers.
        use_cache (bool, optional): If set to True, past key value states are returned and can be used to speed up decoding.
        past_key_value (Tuple(mindspore.Tensor), optional): Cached past key and value projection states.
        cache_position (mindspore.Tensor, optional): Position of the cache.
        **kwargs: Additional keyword arguments.

    Raises:
        DeprecationWarning: If 'padding_mask' is passed, a warning is issued indicating that it is deprecated and will
            be removed in a future version.

    Returns:
        Tuple[mindspore.Tensor, Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]]:
            The resulting hidden states and optionally the attention weights and present key value.
    """
    def __init__(self, config: GemmaConfig, layer_idx: int):
        """
        Initializes a new instance of the GemmaDecoderLayer class.

        Args:
            self: The object itself.
            config (GemmaConfig): The configuration object containing various settings.
            layer_idx (int): The index of the decoder layer.

        Returns:
            None.

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

        self.self_attn = GEMMA_ATTENTION_CLASSES["eager"](config=config, layer_idx=layer_idx)

        self.mlp = GemmaMLP(config)
        self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
        output_attentions: Optional[bool] = False,
        use_cache: Optional[bool] = False,
        cache_position: Optional[mindspore.Tensor] = None,
        **kwargs,
    ) -> Tuple[mindspore.Tensor, Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]]:
        """
        Args:
            hidden_states (`mindspore.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`mindspore.Tensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            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`).
            past_key_value (`Tuple(mindspore.Tensor)`, *optional*): cached past key and value projection states
        """
        if "padding_mask" in kwargs:
            warnings.warn(
                "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
            )

        residual = hidden_states

        hidden_states = self.input_layernorm(hidden_states)

        # Self Attention
        hidden_states, self_attn_weights, present_key_value = self.self_attn(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_value=past_key_value,
            output_attentions=output_attentions,
            use_cache=use_cache,
            cache_position=cache_position,
            **kwargs,
        )
        hidden_states = residual + hidden_states

        # Fully Connected
        residual = hidden_states
        hidden_states = self.post_attention_layernorm(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = residual + hidden_states

        outputs = (hidden_states,)

        if output_attentions:
            outputs += (self_attn_weights,)

        if use_cache:
            outputs += (present_key_value,)

        return outputs

mindnlp.transformers.models.gemma.modeling_gemma.GemmaDecoderLayer.__init__(config, layer_idx)

Initializes a new instance of the GemmaDecoderLayer class.

PARAMETER DESCRIPTION
self

The object itself.

config

The configuration object containing various settings.

TYPE: GemmaConfig

layer_idx

The index of the decoder layer.

TYPE: int

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
def __init__(self, config: GemmaConfig, layer_idx: int):
    """
    Initializes a new instance of the GemmaDecoderLayer class.

    Args:
        self: The object itself.
        config (GemmaConfig): The configuration object containing various settings.
        layer_idx (int): The index of the decoder layer.

    Returns:
        None.

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

    self.self_attn = GEMMA_ATTENTION_CLASSES["eager"](config=config, layer_idx=layer_idx)

    self.mlp = GemmaMLP(config)
    self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
    self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)

mindnlp.transformers.models.gemma.modeling_gemma.GemmaDecoderLayer.forward(hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, cache_position=None, **kwargs)

PARAMETER DESCRIPTION
hidden_states

input to the layer of shape (batch, seq_len, embed_dim)

TYPE: `mindspore.Tensor`

attention_mask

attention mask of size (batch_size, sequence_length) if flash attention is used or (batch_size, 1, query_sequence_length, key_sequence_length) if default attention is used.

TYPE: `mindspore.Tensor`, *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: False

use_cache

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

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

past_key_value

cached past key and value projection states

TYPE: `Tuple(mindspore.Tensor)`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def forward(
    self,
    hidden_states: mindspore.Tensor,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
    output_attentions: Optional[bool] = False,
    use_cache: Optional[bool] = False,
    cache_position: Optional[mindspore.Tensor] = None,
    **kwargs,
) -> Tuple[mindspore.Tensor, Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]]:
    """
    Args:
        hidden_states (`mindspore.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
        attention_mask (`mindspore.Tensor`, *optional*):
            attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
            query_sequence_length, key_sequence_length)` if default attention is used.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under
            returned tensors for more detail.
        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`).
        past_key_value (`Tuple(mindspore.Tensor)`, *optional*): cached past key and value projection states
    """
    if "padding_mask" in kwargs:
        warnings.warn(
            "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
        )

    residual = hidden_states

    hidden_states = self.input_layernorm(hidden_states)

    # Self Attention
    hidden_states, self_attn_weights, present_key_value = self.self_attn(
        hidden_states=hidden_states,
        attention_mask=attention_mask,
        position_ids=position_ids,
        past_key_value=past_key_value,
        output_attentions=output_attentions,
        use_cache=use_cache,
        cache_position=cache_position,
        **kwargs,
    )
    hidden_states = residual + hidden_states

    # Fully Connected
    residual = hidden_states
    hidden_states = self.post_attention_layernorm(hidden_states)
    hidden_states = self.mlp(hidden_states)
    hidden_states = residual + hidden_states

    outputs = (hidden_states,)

    if output_attentions:
        outputs += (self_attn_weights,)

    if use_cache:
        outputs += (present_key_value,)

    return outputs

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM

Bases: GemmaPreTrainedModel

This class represents a model for Causal Language Modeling using the Gemma architecture. It provides methods for setting and getting input and output embeddings, setting the decoder, and generating text based on input sequences. The class also includes methods for preparing inputs for text generation and reordering past key values.

The class inherits from GemmaPreTrainedModel and includes the following methods:

  • init: Initializes the model with the given configuration.
  • get_input_embeddings): Returns the input embeddings.
  • set_input_embeddings: Sets the input embeddings to the given value.
  • get_output_embeddings: Returns the output embeddings.
  • set_output_embeddings: Sets the output embeddings to the new embeddings.
  • set_decoder: Sets the decoder model.
  • get_decoder: Returns the decoder model.
  • forward: Constructs the model for text generation.
  • prepare_inputs_for_generation: Prepares inputs for text generation.
  • _reorder_cache(past_key_values, beam_idx): Reorders the cache based on the beam index.
Example
>>> from transformers import AutoTokenizer, GemmaForCausalLM
...
>>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
...
>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
...
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> "What is your favorite condiment?"
Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
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
class GemmaForCausalLM(GemmaPreTrainedModel):

    """
    This class represents a model for Causal Language Modeling using the Gemma architecture.
    It provides methods for setting and getting input and output embeddings, setting the decoder, and generating text
    based on input sequences. The class also includes methods for preparing inputs for text generation
    and reordering past key values.

    The class inherits from GemmaPreTrainedModel and includes the following methods:

    - __init__: Initializes the model with the given configuration.
    - get_input_embeddings): Returns the input embeddings.
    - set_input_embeddings: Sets the input embeddings to the given value.
    - get_output_embeddings: Returns the output embeddings.
    - set_output_embeddings: Sets the output embeddings to the new embeddings.
    - set_decoder: Sets the decoder model.
    - get_decoder: Returns the decoder model.
    - forward: Constructs the model for
    text generation.
    - prepare_inputs_for_generation: Prepares inputs for text generation.
    - _reorder_cache(past_key_values, beam_idx): Reorders the cache based on the beam index.

    Example:
        ```python
        >>> from transformers import AutoTokenizer, GemmaForCausalLM
        ...
        >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
        ...
        >>> prompt = "What is your favorite condiment?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")
        ...
        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        >>> "What is your favorite condiment?"
        ```
    """
    _tied_weights_keys = ["lm_head.weight"]

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

        Args:
            self: The object itself.
            config: An instance of the configuration class that holds the model configuration settings.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.model = GemmaModel(config)
        self.vocab_size = config.vocab_size
        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):
        """
        Retrieves the input embeddings from the GemmaForCausalLM model.

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

        Returns:
            None.

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

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

        Args:
            self (GemmaForCausalLM): The instance of the GemmaForCausalLM class.
            value: The input embeddings to be set for the model.

        Returns:
            None.

        Raises:
            None.

        Description:
            This method sets the input embeddings for the GemmaForCausalLM model. The input embeddings are used to map
            input tokens to their corresponding embedding vectors. The `value` parameter should be an object containing
            the desired input embeddings. The input embeddings are assigned to the `embed_tokens` attribute of the model.

        Example:
            ```python
            >>> model = GemmaForCausalLM()
            >>> embeddings = Embeddings()
            >>> model.set_input_embeddings(embeddings)
            ```
        """
        self.model.embed_tokens = value

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

        Args:
            self (GemmaForCausalLM): The instance of GemmaForCausalLM class.
                Represents the model object for which the output embeddings are to be retrieved.

        Returns:
            None: This method returns None as it directly provides access to the 'lm_head' attribute
                containing the output embeddings.

        Raises:
            None
        """
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        """
        Sets the output embeddings for the GemmaForCausalLM model.

        Args:
            self (GemmaForCausalLM): The GemmaForCausalLM instance.
            new_embeddings (torch.Tensor): The new embeddings to be set as the model's output embeddings.

        Returns:
            None.

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

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

        Args:
            self (GemmaForCausalLM): The instance of the GemmaForCausalLM class.
            decoder: The decoder object to be set for the model. It should be compatible with the GemmaForCausalLM model.

        Returns:
            None.

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

    def get_decoder(self):
        """
        Returns the decoder model used for causal language modeling in the GemmaForCausalLM class.

        Args:
            self: An instance of the GemmaForCausalLM class.

        Returns:
            The decoder model:
                which is an instance of the model used for causal language modeling.

        Raises:
            None.
        """
        return self.model

    # Ignore copy
    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: 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,
        cache_position: Optional[mindspore.Tensor] = None,
    ) -> Union[Tuple, CausalLMOutputWithPast]:
        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, CausalLMOutputWithPast]

        Example:
            ```python
            >>> from transformers import AutoTokenizer, GemmaForCausalLM
            ...
            >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
            >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
            ...
            >>> prompt = "What is your favorite condiment?"
            >>> inputs = tokenizer(prompt, return_tensors="pt")
            ...
            >>> # Generate
            >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
            >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
            "What is your favorite condiment?"
            ```
        """
        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(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            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,
            cache_position=cache_position,
        )

        hidden_states = outputs[0]
        logits = self.lm_head(hidden_states)

        loss = None
        if labels is not None:
            # Shift so that tokens < n predict n
            shift_logits = logits[..., :-1, :]
            shift_labels = labels[..., 1:]
            # Flatten the tokens
            shift_logits = shift_logits.view(-1, self.config.vocab_size)
            shift_labels = shift_labels.view(-1)
            # Enable model parallelism
            loss = ops.cross_entropy(shift_logits, shift_labels)

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

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

    def prepare_inputs_for_generation(
        self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
    ):
        """
        Prepare inputs for generation.

        Args:
            self (object): The instance of the GemmaForCausalLM class.
            input_ids (tensor): The input tensor containing token indices for the input sequence.
            past_key_values (Cache or tuple or None): The past key values used in the generation process.
                If past_key_values is a Cache object, it contains the cached key value states.
                If past_key_values is a tuple, it represents the cached key value states as a tuple of tensors.
                If past_key_values is None, no cached key value states are used.
            attention_mask (tensor or None): The attention mask tensor used to mask the input sequence.
                If provided, it should have the same shape as input_ids.
                If None, no attention mask is applied.
            inputs_embeds (tensor or None): The tensor containing the embedded input embeddings.
                If provided, it should have the same shape as input_ids.
                If None, input_ids is used for token embeddings.

        Returns:
            dict or None: A dictionary containing the model inputs including input_ids, position_ids, cache_position,
                past_key_values, use_cache, and attention_mask. Returns None if no inputs are provided.

        Raises:
            TypeError: If input_ids, attention_mask, or inputs_embeds have invalid types.
            ValueError: If input_ids and attention_mask have incompatible shapes.
            ValueError: If cache_position is not None and is not a valid cache position tensor.
            ValueError: If past_key_values is not of type Cache or tuple.
        """
        past_length = 0
        if past_key_values is not None:
            if isinstance(past_key_values, Cache):
                cache_length = past_key_values.get_seq_length()
                past_length = past_key_values.seen_tokens
                max_cache_length = past_key_values.get_max_length()
            else:
                cache_length = past_length = past_key_values[0][0].shape[2]
                max_cache_length = None

            # Keep only the unprocessed tokens:
            # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
            # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
            # input)
            if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
                input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
            # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
            # input_ids based on the past_length.
            elif past_length < input_ids.shape[1]:
                input_ids = input_ids[:, past_length:]
            # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.

            # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
            if (
                max_cache_length is not None
                and attention_mask is not None
                and cache_length + input_ids.shape[1] > max_cache_length
            ):
                attention_mask = attention_mask[:, -max_cache_length:]

        position_ids = kwargs.get("position_ids", None)
        if attention_mask is not None and position_ids is None:
            # create position_ids on the fly for batch generation
            position_ids = attention_mask.long().cumsum(-1) - 1
            position_ids = position_ids.masked_fill(attention_mask == 0, 1)
            if past_key_values:
                position_ids = position_ids[:, -input_ids.shape[1] :]

        if getattr(self.model.layers[0].self_attn, "past_key_value", None) is not None:
            # generation with static cache
            cache_position = kwargs.get("cache_position", None)
            if cache_position is None:
                past_length = 0
            else:
                past_length = cache_position[-1] + 1
            input_ids = input_ids[:, past_length:]
            position_ids = position_ids[:, past_length:]

        # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
        # same goes for position ids. Could also help with continued generation.
        cache_position = ops.arange(past_length, past_length + position_ids.shape[-1])

        # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
        if inputs_embeds is not None and past_key_values is None:
            model_inputs = {"inputs_embeds": inputs_embeds}
        else:
            # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
            # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
            # TODO: use `next_tokens` directly instead.
            model_inputs = {"input_ids": input_ids}

        model_inputs.update(
            {
                "position_ids": position_ids,
                "cache_position": cache_position,
                "past_key_values": past_key_values,
                "use_cache": kwargs.get("use_cache"),
                "attention_mask": attention_mask,
            }
        )
        return model_inputs

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache for the given beam index.

        Args:
            past_key_values (tuple): A tuple containing the past key-value states for each layer of the model.
                Each layer's past key-value state is a tuple of tensors with shape (batch_size, sequence_length, hidden_size).
            beam_idx (torch.Tensor): A tensor of shape (batch_size,) representing the beam index to reorder the cache for.

        Returns:
            None: This method does not return any value. The cache is reordered in-place.

        Raises:
            None.
        """
        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.gemma.modeling_gemma.GemmaForCausalLM.__init__(config)

Initializes an instance of the GemmaForCausalLM class.

PARAMETER DESCRIPTION
self

The object itself.

config

An instance of the configuration class that holds the model configuration settings.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
def __init__(self, config):
    """
    Initializes an instance of the GemmaForCausalLM class.

    Args:
        self: The object itself.
        config: An instance of the configuration class that holds the model configuration settings.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.model = GemmaModel(config)
    self.vocab_size = config.vocab_size
    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.gemma.modeling_gemma.GemmaForCausalLM.forward(input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, cache_position=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, CausalLMOutputWithPast]

Union[Tuple, CausalLMOutputWithPast]

Example
>>> from transformers import AutoTokenizer, GemmaForCausalLM
...
>>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
...
>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
...
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is your favorite condiment?"
Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: 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,
    cache_position: Optional[mindspore.Tensor] = None,
) -> Union[Tuple, CausalLMOutputWithPast]:
    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, CausalLMOutputWithPast]

    Example:
        ```python
        >>> from transformers import AutoTokenizer, GemmaForCausalLM
        ...
        >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
        ...
        >>> prompt = "What is your favorite condiment?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")
        ...
        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "What is your favorite condiment?"
        ```
    """
    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(
        input_ids=input_ids,
        attention_mask=attention_mask,
        position_ids=position_ids,
        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,
        cache_position=cache_position,
    )

    hidden_states = outputs[0]
    logits = self.lm_head(hidden_states)

    loss = None
    if labels is not None:
        # Shift so that tokens < n predict n
        shift_logits = logits[..., :-1, :]
        shift_labels = labels[..., 1:]
        # Flatten the tokens
        shift_logits = shift_logits.view(-1, self.config.vocab_size)
        shift_labels = shift_labels.view(-1)
        # Enable model parallelism
        loss = ops.cross_entropy(shift_logits, shift_labels)

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

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.get_decoder()

Returns the decoder model used for causal language modeling in the GemmaForCausalLM class.

PARAMETER DESCRIPTION
self

An instance of the GemmaForCausalLM class.

RETURNS DESCRIPTION

The decoder model: which is an instance of the model used for causal language modeling.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
def get_decoder(self):
    """
    Returns the decoder model used for causal language modeling in the GemmaForCausalLM class.

    Args:
        self: An instance of the GemmaForCausalLM class.

    Returns:
        The decoder model:
            which is an instance of the model used for causal language modeling.

    Raises:
        None.
    """
    return self.model

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.get_input_embeddings()

Retrieves the input embeddings from the GemmaForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the GemmaForCausalLM class.

TYPE: GemmaForCausalLM

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
def get_input_embeddings(self):
    """
    Retrieves the input embeddings from the GemmaForCausalLM model.

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

    Returns:
        None.

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.get_output_embeddings()

Method to retrieve the output embeddings from a GemmaForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of GemmaForCausalLM class. Represents the model object for which the output embeddings are to be retrieved.

TYPE: GemmaForCausalLM

RETURNS DESCRIPTION
None

This method returns None as it directly provides access to the 'lm_head' attribute containing the output embeddings.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
def get_output_embeddings(self):
    """
    Method to retrieve the output embeddings from a GemmaForCausalLM model.

    Args:
        self (GemmaForCausalLM): The instance of GemmaForCausalLM class.
            Represents the model object for which the output embeddings are to be retrieved.

    Returns:
        None: This method returns None as it directly provides access to the 'lm_head' attribute
            containing the output embeddings.

    Raises:
        None
    """
    return self.lm_head

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.prepare_inputs_for_generation(input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs)

Prepare inputs for generation.

PARAMETER DESCRIPTION
self

The instance of the GemmaForCausalLM class.

TYPE: object

input_ids

The input tensor containing token indices for the input sequence.

TYPE: tensor

past_key_values

The past key values used in the generation process. If past_key_values is a Cache object, it contains the cached key value states. If past_key_values is a tuple, it represents the cached key value states as a tuple of tensors. If past_key_values is None, no cached key value states are used.

TYPE: Cache or tuple or None DEFAULT: None

attention_mask

The attention mask tensor used to mask the input sequence. If provided, it should have the same shape as input_ids. If None, no attention mask is applied.

TYPE: tensor or None DEFAULT: None

inputs_embeds

The tensor containing the embedded input embeddings. If provided, it should have the same shape as input_ids. If None, input_ids is used for token embeddings.

TYPE: tensor or None DEFAULT: None

RETURNS DESCRIPTION

dict or None: A dictionary containing the model inputs including input_ids, position_ids, cache_position, past_key_values, use_cache, and attention_mask. Returns None if no inputs are provided.

RAISES DESCRIPTION
TypeError

If input_ids, attention_mask, or inputs_embeds have invalid types.

ValueError

If input_ids and attention_mask have incompatible shapes.

ValueError

If cache_position is not None and is not a valid cache position tensor.

ValueError

If past_key_values is not of type Cache or tuple.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
def prepare_inputs_for_generation(
    self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
):
    """
    Prepare inputs for generation.

    Args:
        self (object): The instance of the GemmaForCausalLM class.
        input_ids (tensor): The input tensor containing token indices for the input sequence.
        past_key_values (Cache or tuple or None): The past key values used in the generation process.
            If past_key_values is a Cache object, it contains the cached key value states.
            If past_key_values is a tuple, it represents the cached key value states as a tuple of tensors.
            If past_key_values is None, no cached key value states are used.
        attention_mask (tensor or None): The attention mask tensor used to mask the input sequence.
            If provided, it should have the same shape as input_ids.
            If None, no attention mask is applied.
        inputs_embeds (tensor or None): The tensor containing the embedded input embeddings.
            If provided, it should have the same shape as input_ids.
            If None, input_ids is used for token embeddings.

    Returns:
        dict or None: A dictionary containing the model inputs including input_ids, position_ids, cache_position,
            past_key_values, use_cache, and attention_mask. Returns None if no inputs are provided.

    Raises:
        TypeError: If input_ids, attention_mask, or inputs_embeds have invalid types.
        ValueError: If input_ids and attention_mask have incompatible shapes.
        ValueError: If cache_position is not None and is not a valid cache position tensor.
        ValueError: If past_key_values is not of type Cache or tuple.
    """
    past_length = 0
    if past_key_values is not None:
        if isinstance(past_key_values, Cache):
            cache_length = past_key_values.get_seq_length()
            past_length = past_key_values.seen_tokens
            max_cache_length = past_key_values.get_max_length()
        else:
            cache_length = past_length = past_key_values[0][0].shape[2]
            max_cache_length = None

        # Keep only the unprocessed tokens:
        # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
        # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
        # input)
        if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
            input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
        # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
        # input_ids based on the past_length.
        elif past_length < input_ids.shape[1]:
            input_ids = input_ids[:, past_length:]
        # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.

        # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
        if (
            max_cache_length is not None
            and attention_mask is not None
            and cache_length + input_ids.shape[1] > max_cache_length
        ):
            attention_mask = attention_mask[:, -max_cache_length:]

    position_ids = kwargs.get("position_ids", None)
    if attention_mask is not None and position_ids is None:
        # create position_ids on the fly for batch generation
        position_ids = attention_mask.long().cumsum(-1) - 1
        position_ids = position_ids.masked_fill(attention_mask == 0, 1)
        if past_key_values:
            position_ids = position_ids[:, -input_ids.shape[1] :]

    if getattr(self.model.layers[0].self_attn, "past_key_value", None) is not None:
        # generation with static cache
        cache_position = kwargs.get("cache_position", None)
        if cache_position is None:
            past_length = 0
        else:
            past_length = cache_position[-1] + 1
        input_ids = input_ids[:, past_length:]
        position_ids = position_ids[:, past_length:]

    # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
    # same goes for position ids. Could also help with continued generation.
    cache_position = ops.arange(past_length, past_length + position_ids.shape[-1])

    # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
    if inputs_embeds is not None and past_key_values is None:
        model_inputs = {"inputs_embeds": inputs_embeds}
    else:
        # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
        # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
        # TODO: use `next_tokens` directly instead.
        model_inputs = {"input_ids": input_ids}

    model_inputs.update(
        {
            "position_ids": position_ids,
            "cache_position": cache_position,
            "past_key_values": past_key_values,
            "use_cache": kwargs.get("use_cache"),
            "attention_mask": attention_mask,
        }
    )
    return model_inputs

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.set_decoder(decoder)

Sets the decoder for the GemmaForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the GemmaForCausalLM class.

TYPE: GemmaForCausalLM

decoder

The decoder object to be set for the model. It should be compatible with the GemmaForCausalLM model.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
def set_decoder(self, decoder):
    """
    Sets the decoder for the GemmaForCausalLM model.

    Args:
        self (GemmaForCausalLM): The instance of the GemmaForCausalLM class.
        decoder: The decoder object to be set for the model. It should be compatible with the GemmaForCausalLM model.

    Returns:
        None.

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.set_input_embeddings(value)

Set the input embeddings for the GemmaForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the GemmaForCausalLM class.

TYPE: GemmaForCausalLM

value

The input embeddings to be set for the model.

RETURNS DESCRIPTION

None.

Description

This method sets the input embeddings for the GemmaForCausalLM model. The input embeddings are used to map input tokens to their corresponding embedding vectors. The value parameter should be an object containing the desired input embeddings. The input embeddings are assigned to the embed_tokens attribute of the model.

Example
>>> model = GemmaForCausalLM()
>>> embeddings = Embeddings()
>>> model.set_input_embeddings(embeddings)
Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the GemmaForCausalLM model.

    Args:
        self (GemmaForCausalLM): The instance of the GemmaForCausalLM class.
        value: The input embeddings to be set for the model.

    Returns:
        None.

    Raises:
        None.

    Description:
        This method sets the input embeddings for the GemmaForCausalLM model. The input embeddings are used to map
        input tokens to their corresponding embedding vectors. The `value` parameter should be an object containing
        the desired input embeddings. The input embeddings are assigned to the `embed_tokens` attribute of the model.

    Example:
        ```python
        >>> model = GemmaForCausalLM()
        >>> embeddings = Embeddings()
        >>> model.set_input_embeddings(embeddings)
        ```
    """
    self.model.embed_tokens = value

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForCausalLM.set_output_embeddings(new_embeddings)

Sets the output embeddings for the GemmaForCausalLM model.

PARAMETER DESCRIPTION
self

The GemmaForCausalLM instance.

TYPE: GemmaForCausalLM

new_embeddings

The new embeddings to be set as the model's output embeddings.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
def set_output_embeddings(self, new_embeddings):
    """
    Sets the output embeddings for the GemmaForCausalLM model.

    Args:
        self (GemmaForCausalLM): The GemmaForCausalLM instance.
        new_embeddings (torch.Tensor): The new embeddings to be set as the model's output embeddings.

    Returns:
        None.

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForSequenceClassification

Bases: GemmaPreTrainedModel

A Python class that represents a Gemma model for sequence classification tasks. This class inherits from the GemmaPreTrainedModel class.

This class provides methods for initializing the model, getting and setting input embeddings, and forwarding the model for sequence classification. It also includes methods for computing the loss and returning the model outputs.

ATTRIBUTE DESCRIPTION
num_labels

The number of labels for the sequence classification task.

TYPE: int

model

The underlying Gemma model.

TYPE: GemmaModel

score

The dense layer for computing the logits.

TYPE: Linear

METHOD DESCRIPTION
__init__

Initializes the GemmaForSequenceClassification instance with the given configuration.

get_input_embeddings

Returns the input embeddings of the model.

set_input_embeddings

Sets the input embeddings of the model.

forward

Constructs the model for sequence classification and returns the model outputs.

Example
>>> # Initialize the GemmaForSequenceClassification instance
>>> model = GemmaForSequenceClassification(config)
...
>>> # Get the input embeddings
>>> embeddings = model.get_input_embeddings()
...
>>> # Set new input embeddings
>>> model.set_input_embeddings(embeddings)
...
>>> # Construct the model for sequence classification
>>> outputs = model.forward(input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)
...
>>> # Get the logits and past key values
>>> logits = outputs.logits
>>> past_key_values = outputs.past_key_values
...
>>> # Compute the loss
>>> loss = outputs.loss
...
>>> # Return the model outputs
>>> return_dict = True
>>> output = model.forward(input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)
Note

This class assumes that the GemmaPreTrainedModel class is already defined and imported.

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

    """
    A Python class that represents a Gemma model for sequence classification tasks.
    This class inherits from the GemmaPreTrainedModel class.

    This class provides methods for initializing the model, getting and setting input embeddings, and forwarding
    the model for sequence classification. It also includes methods for computing the loss and returning the model outputs.

    Attributes:
        num_labels (int): The number of labels for the sequence classification task.
        model (GemmaModel): The underlying Gemma model.
        score (nn.Linear): The dense layer for computing the logits.

    Methods:
        __init__: Initializes the GemmaForSequenceClassification instance with the given configuration.
        get_input_embeddings: Returns the input embeddings of the model.
        set_input_embeddings: Sets the input embeddings of the model.
        forward: Constructs the model for sequence classification and returns the model outputs.

    Example:
        ```python
        >>> # Initialize the GemmaForSequenceClassification instance
        >>> model = GemmaForSequenceClassification(config)
        ...
        >>> # Get the input embeddings
        >>> embeddings = model.get_input_embeddings()
        ...
        >>> # Set new input embeddings
        >>> model.set_input_embeddings(embeddings)
        ...
        >>> # Construct the model for sequence classification
        >>> outputs = model.forward(input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)
        ...
        >>> # Get the logits and past key values
        >>> logits = outputs.logits
        >>> past_key_values = outputs.past_key_values
        ...
        >>> # Compute the loss
        >>> loss = outputs.loss
        ...
        >>> # Return the model outputs
        >>> return_dict = True
        >>> output = model.forward(input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)
        ```

    Note:
        This class assumes that the GemmaPreTrainedModel class is already defined and imported.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the GemmaForSequenceClassification class.

        Args:
            self: The object itself.
            config (class): A configuration class that contains the necessary parameters for initializing the model.
                This includes the number of labels for classification.

        Returns:
            None.

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

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

    def get_input_embeddings(self):
        """
        This method retrieves the input embeddings from the GemmaForSequenceClassification model.

        Args:
            self: The instance of the GemmaForSequenceClassification class.

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

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

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

        Args:
            self (GemmaForSequenceClassification): The instance of the GemmaForSequenceClassification class.
            value (object): The input embeddings to be set for the model. This should be an object that represents the
                embeddings, such as a tensor or a list of tensors.

        Returns:
            None.

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

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

        transformer_outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            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,
        )
        hidden_states = transformer_outputs[0]
        logits = self.score(hidden_states)

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

        if self.config.pad_token_id is None and batch_size != 1:
            raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
        if self.config.pad_token_id is None:
            sequence_lengths = -1
        else:
            if input_ids is not None:
                # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
                sequence_lengths = ops.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
                sequence_lengths = sequence_lengths % input_ids.shape[-1]
            else:
                sequence_lengths = -1

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

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

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

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForSequenceClassification.__init__(config)

Initializes a new instance of the GemmaForSequenceClassification class.

PARAMETER DESCRIPTION
self

The object itself.

config

A configuration class that contains the necessary parameters for initializing the model. This includes the number of labels for classification.

TYPE: class

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
def __init__(self, config):
    """
    Initializes a new instance of the GemmaForSequenceClassification class.

    Args:
        self: The object itself.
        config (class): A configuration class that contains the necessary parameters for initializing the model.
            This includes the number of labels for classification.

    Returns:
        None.

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

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForSequenceClassification.forward(input_ids=None, attention_mask=None, position_ids=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
labels

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

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

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: 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, SequenceClassifierOutputWithPast]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    transformer_outputs = self.model(
        input_ids,
        attention_mask=attention_mask,
        position_ids=position_ids,
        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,
    )
    hidden_states = transformer_outputs[0]
    logits = self.score(hidden_states)

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

    if self.config.pad_token_id is None and batch_size != 1:
        raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
    if self.config.pad_token_id is None:
        sequence_lengths = -1
    else:
        if input_ids is not None:
            # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
            sequence_lengths = ops.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
            sequence_lengths = sequence_lengths % input_ids.shape[-1]
        else:
            sequence_lengths = -1

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

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

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

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForSequenceClassification.get_input_embeddings()

This method retrieves the input embeddings from the GemmaForSequenceClassification model.

PARAMETER DESCRIPTION
self

The instance of the GemmaForSequenceClassification class.

RETURNS DESCRIPTION
embed_tokens

This method returns the input embeddings from the model.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
def get_input_embeddings(self):
    """
    This method retrieves the input embeddings from the GemmaForSequenceClassification model.

    Args:
        self: The instance of the GemmaForSequenceClassification class.

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

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaForSequenceClassification.set_input_embeddings(value)

Sets the input embeddings for the GemmaForSequenceClassification model.

PARAMETER DESCRIPTION
self

The instance of the GemmaForSequenceClassification class.

TYPE: GemmaForSequenceClassification

value

The input embeddings to be set for the model. This should be an object that represents the embeddings, such as a tensor or a list of tensors.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
def set_input_embeddings(self, value):
    """
    Sets the input embeddings for the GemmaForSequenceClassification model.

    Args:
        self (GemmaForSequenceClassification): The instance of the GemmaForSequenceClassification class.
        value (object): The input embeddings to be set for the model. This should be an object that represents the
            embeddings, such as a tensor or a list of tensors.

    Returns:
        None.

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaMLP

Bases: Module

GemmaMLP is a class representing a multi-layer perceptron (MLP) model for neural network operations. It inherits from nn.Module and implements functionality for forwarding the MLP.

ATTRIBUTE DESCRIPTION
config

A configuration object containing parameters for the MLP.

hidden_size

The size of the hidden layers in the MLP.

intermediate_size

The size of the intermediate layers in the MLP.

gate_proj

A dense layer for projecting input to the intermediate size with no bias.

up_proj

A dense layer for projecting input to the intermediate size with no bias.

down_proj

A dense layer for projecting from intermediate size to hidden size with no bias.

act_fn

The activation function to be used in the hidden layers.

METHOD DESCRIPTION
forward

Constructs the multi-layer perceptron using the given input x by applying the specified operations.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
class GemmaMLP(nn.Module):

    """
    GemmaMLP is a class representing a multi-layer perceptron (MLP) model for neural network operations.
    It inherits from nn.Module and implements functionality for forwarding the MLP.

    Attributes:
        config: A configuration object containing parameters for the MLP.
        hidden_size: The size of the hidden layers in the MLP.
        intermediate_size: The size of the intermediate layers in the MLP.
        gate_proj: A dense layer for projecting input to the intermediate size with no bias.
        up_proj: A dense layer for projecting input to the intermediate size with no bias.
        down_proj: A dense layer for projecting from intermediate size to hidden size with no bias.
        act_fn: The activation function to be used in the hidden layers.

    Methods:
        forward(x): Constructs the multi-layer perceptron using the given input x by applying the specified operations.
    """
    def __init__(self, config):
        """
        Initializes a GemmaMLP instance with the provided configuration.

        Args:
            self (GemmaMLP): The GemmaMLP instance to be initialized.
            config (Config):
                An object containing configuration parameters for the GemmaMLP model.

                - hidden_size (int): The size of the hidden layers in the model.
                - intermediate_size (int): The size of the intermediate layers in the model.

        Returns:
            None.

        Raises:
            TypeError: If config is not provided or is not of type Config.
            ValueError: If hidden_size or intermediate_size are not valid integer values.
            RuntimeError: If there is an issue initializing the gate_proj, up_proj, down_proj, or act_fn attributes.
        """
        super().__init__()
        self.config = config
        self.hidden_size = config.hidden_size
        self.intermediate_size = config.intermediate_size
        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
        self.act_fn = ACT2FN[config.hidden_act]

    def forward(self, x):
        """
        Constructs a multi-layer perceptron using the GemmaMLP class.

        Args:
            self (object): The instance of the GemmaMLP class.
            x (object): Input tensor or data to be processed by the MLP.

        Returns:
            None: The method modifies the internal state of the GemmaMLP instance.

        Raises:
            TypeError: If any of the input parameters are of incorrect types.
            ValueError: If there are issues during the execution of the method.
        """
        return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))

mindnlp.transformers.models.gemma.modeling_gemma.GemmaMLP.__init__(config)

Initializes a GemmaMLP instance with the provided configuration.

PARAMETER DESCRIPTION
self

The GemmaMLP instance to be initialized.

TYPE: GemmaMLP

config

An object containing configuration parameters for the GemmaMLP model.

  • hidden_size (int): The size of the hidden layers in the model.
  • intermediate_size (int): The size of the intermediate layers in the model.

TYPE: Config

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If config is not provided or is not of type Config.

ValueError

If hidden_size or intermediate_size are not valid integer values.

RuntimeError

If there is an issue initializing the gate_proj, up_proj, down_proj, or act_fn attributes.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
def __init__(self, config):
    """
    Initializes a GemmaMLP instance with the provided configuration.

    Args:
        self (GemmaMLP): The GemmaMLP instance to be initialized.
        config (Config):
            An object containing configuration parameters for the GemmaMLP model.

            - hidden_size (int): The size of the hidden layers in the model.
            - intermediate_size (int): The size of the intermediate layers in the model.

    Returns:
        None.

    Raises:
        TypeError: If config is not provided or is not of type Config.
        ValueError: If hidden_size or intermediate_size are not valid integer values.
        RuntimeError: If there is an issue initializing the gate_proj, up_proj, down_proj, or act_fn attributes.
    """
    super().__init__()
    self.config = config
    self.hidden_size = config.hidden_size
    self.intermediate_size = config.intermediate_size
    self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
    self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
    self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
    self.act_fn = ACT2FN[config.hidden_act]

mindnlp.transformers.models.gemma.modeling_gemma.GemmaMLP.forward(x)

Constructs a multi-layer perceptron using the GemmaMLP class.

PARAMETER DESCRIPTION
self

The instance of the GemmaMLP class.

TYPE: object

x

Input tensor or data to be processed by the MLP.

TYPE: object

RETURNS DESCRIPTION
None

The method modifies the internal state of the GemmaMLP instance.

RAISES DESCRIPTION
TypeError

If any of the input parameters are of incorrect types.

ValueError

If there are issues during the execution of the method.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def forward(self, x):
    """
    Constructs a multi-layer perceptron using the GemmaMLP class.

    Args:
        self (object): The instance of the GemmaMLP class.
        x (object): Input tensor or data to be processed by the MLP.

    Returns:
        None: The method modifies the internal state of the GemmaMLP instance.

    Raises:
        TypeError: If any of the input parameters are of incorrect types.
        ValueError: If there are issues during the execution of the method.
    """
    return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))

mindnlp.transformers.models.gemma.modeling_gemma.GemmaModel

Bases: GemmaPreTrainedModel

Transformer decoder consisting of config.num_hidden_layers layers. Each layer is a [GemmaDecoderLayer]

PARAMETER DESCRIPTION
config

GemmaConfig

TYPE: GemmaConfig

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
class GemmaModel(GemmaPreTrainedModel):
    """
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GemmaDecoderLayer`]

    Args:
        config: GemmaConfig
    """
    def __init__(self, config: GemmaConfig):
        """
        Initializes a GemmaModel instance.

        Args:
            self: The instance of the GemmaModel class.
            config (GemmaConfig): An instance of GemmaConfig containing the configuration parameters for the GemmaModel.
                This includes information such as the vocabulary size, hidden size, number of hidden layers, pad token id,
                maximum position embeddings, and RMS normalization epsilon.

                - config.pad_token_id (int): The padding token ID.
                - config.vocab_size (int): The size of the vocabulary.
                - config.hidden_size (int): The size of the hidden layers.
                - config.num_hidden_layers (int): The number of hidden layers.
                - config.max_position_embeddings (int): The maximum number of position embeddings.
                - config.rms_norm_eps (float): The epsilon value for RMS normalization.

        Returns:
            None: The method initializes various attributes of the GemmaModel instance, such as padding_idx, vocab_size,
                embed_tokens, layers, norm, gradient_checkpointing, causal_mask, and invokes the post_init method.

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

        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
        self.layers = nn.ModuleList(
            [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.gradient_checkpointing = False

        # register a causal mask to separate causal and padding mask creation. Merging happends in the attention class
        causal_mask = ops.full((config.max_position_embeddings, config.max_position_embeddings), fill_value=1)
        self.causal_mask = ops.triu(causal_mask, diagonal=1)
        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        """
        Get the input embeddings for the GemmaModel.

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

        Returns:
            None.

        Raises:
            None.
        """
        return self.embed_tokens

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

        Args:
            self (GemmaModel): The instance of the GemmaModel class.
            value: The input embeddings to set for the model. This should be a tensor of shape (vocab_size, embedding_dim).

        Returns:
            None.

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

    # Ignore copy
    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        cache_position: Optional[mindspore.Tensor] = None,
    ) -> Union[Tuple, BaseModelOutputWithPast]:
        """
        Constructs GemmaModel.

        This method forwards the GemmaModel and performs the forward pass of the model.
        It takes various input parameters and returns the output hidden states, cache values, and attention values.

        Args:
            self (GemmaModel): The instance of the GemmaModel class.
            input_ids (mindspore.Tensor, optional):
                The input tensor containing the tokenized input sequence. Default is None.
            attention_mask (mindspore.Tensor, optional):
                The attention mask tensor to avoid attending to padding tokens. Default is None.
            position_ids (mindspore.Tensor, optional):
                The position indices tensor to specify the position of each token. Default is None.
            past_key_values (List[mindspore.Tensor], optional):
                The list of tensors containing the cached key-value pairs of the previous attention mechanism.
                Default is None.
            inputs_embeds (mindspore.Tensor, optional): The input embedding tensor. Default is None.
            use_cache (bool, optional): Whether to use cache mechanism. Default is None.
            output_attentions (bool, optional): Whether to output the attention values. Default is None.
            output_hidden_states (bool, optional): Whether to output the hidden states. Default is None.
            return_dict (bool, optional): Whether to return the output as a dictionary. Default is None.
            cache_position (mindspore.Tensor, optional): The tensor representing the position of each token in the cache. Default is None.

        Returns:
            Union[Tuple, BaseModelOutputWithPast]: The output of the model.
                It can be a tuple containing hidden states, cache values, hidden states from all layers,
                and attention values from all layers; or an instance of BaseModelOutputWithPast containing the
                last hidden state, cache values, hidden states from all layers, and attention values from all layers.

        Raises:
            ValueError: If both input_ids and inputs_embeds are specified or neither of them is specified.
            Warning: If use_cache is set to True while using gradient checkpointing, it will be set to False as it is not compatible.
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if (input_ids is None) ^ (inputs_embeds is not None):
            raise ValueError(
                "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
            )

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

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

        past_seen_tokens = 0
        if use_cache:  # kept for BC (cache positions)
            if not isinstance(past_key_values, StaticCache):
                past_key_values = DynamicCache.from_legacy_cache(past_key_values)
            past_seen_tokens = past_key_values.get_seq_length()

        if cache_position is None:
            cache_position = ops.arange(
                past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1]
            )

        if position_ids is None:
            position_ids = cache_position.unsqueeze(0)

        causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)

        # embed positions
        hidden_states = inputs_embeds

        # normalized
        hidden_states = hidden_states * (self.config.hidden_size**0.5)

        # decoder layers
        all_hidden_states = () if output_hidden_states else None
        all_self_attns = () if output_attentions else None
        next_decoder_cache = None

        for decoder_layer in self.layers:
            if output_hidden_states:
                all_hidden_states += (hidden_states,)

            layer_outputs = decoder_layer(
                hidden_states,
                attention_mask=causal_mask,
                position_ids=position_ids,
                past_key_value=past_key_values,
                output_attentions=output_attentions,
                use_cache=use_cache,
                cache_position=cache_position,
            )

            hidden_states = layer_outputs[0]

            if use_cache:
                next_decoder_cache = layer_outputs[2 if output_attentions else 1]

            if output_attentions:
                all_self_attns += (layer_outputs[1],)

        hidden_states = self.norm(hidden_states)

        # add hidden states from the last decoder layer
        if output_hidden_states:
            all_hidden_states += (hidden_states,)

        next_cache = None
        if use_cache:
            next_cache = (
                next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
            )
        if not return_dict:
            return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
        return BaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=next_cache,
            hidden_states=all_hidden_states,
            attentions=all_self_attns,
        )

    # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
    # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
    # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
    # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
    def _update_causal_mask(self, attention_mask, input_tensor):
        '''
        Updates the causal mask used for self-attention in the GemmaModel class.

        Args:
            self (GemmaModel): The instance of the GemmaModel class.
            attention_mask (Tensor, optional): The attention mask tensor. Default is None.
            input_tensor (Tensor): The input tensor used to determine the shape of the causal mask.

        Returns:
            None

        Raises:
            None
        '''
        batch_size, seq_length = input_tensor.shape[:2]
        dtype = input_tensor.dtype

        # support going beyond cached `max_position_embedding`
        if seq_length > self.causal_mask.shape[-1]:
            causal_mask = ops.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
            self.causal_mask = ops.triu(causal_mask, diagonal=1)

        # We use the current dtype to avoid any overflows
        causal_mask = self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype) * finfo(dtype, 'min')

        causal_mask = causal_mask.to(dtype=dtype)
        if attention_mask is not None and attention_mask.dim() == 2:
            mask_length = attention_mask.shape[-1]
            padding_mask = causal_mask[..., :mask_length].eq(0.0).astype(mindspore.int32) * attention_mask[:, None, None, :].eq(0.0).astype(mindspore.int32)
            causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(
                padding_mask.astype(mindspore.bool_), finfo(dtype, 'min')
            )

        return causal_mask

mindnlp.transformers.models.gemma.modeling_gemma.GemmaModel.__init__(config)

Initializes a GemmaModel instance.

PARAMETER DESCRIPTION
self

The instance of the GemmaModel class.

config

An instance of GemmaConfig containing the configuration parameters for the GemmaModel. This includes information such as the vocabulary size, hidden size, number of hidden layers, pad token id, maximum position embeddings, and RMS normalization epsilon.

  • config.pad_token_id (int): The padding token ID.
  • config.vocab_size (int): The size of the vocabulary.
  • config.hidden_size (int): The size of the hidden layers.
  • config.num_hidden_layers (int): The number of hidden layers.
  • config.max_position_embeddings (int): The maximum number of position embeddings.
  • config.rms_norm_eps (float): The epsilon value for RMS normalization.

TYPE: GemmaConfig

RETURNS DESCRIPTION
None

The method initializes various attributes of the GemmaModel instance, such as padding_idx, vocab_size, embed_tokens, layers, norm, gradient_checkpointing, causal_mask, and invokes the post_init method.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
def __init__(self, config: GemmaConfig):
    """
    Initializes a GemmaModel instance.

    Args:
        self: The instance of the GemmaModel class.
        config (GemmaConfig): An instance of GemmaConfig containing the configuration parameters for the GemmaModel.
            This includes information such as the vocabulary size, hidden size, number of hidden layers, pad token id,
            maximum position embeddings, and RMS normalization epsilon.

            - config.pad_token_id (int): The padding token ID.
            - config.vocab_size (int): The size of the vocabulary.
            - config.hidden_size (int): The size of the hidden layers.
            - config.num_hidden_layers (int): The number of hidden layers.
            - config.max_position_embeddings (int): The maximum number of position embeddings.
            - config.rms_norm_eps (float): The epsilon value for RMS normalization.

    Returns:
        None: The method initializes various attributes of the GemmaModel instance, such as padding_idx, vocab_size,
            embed_tokens, layers, norm, gradient_checkpointing, causal_mask, and invokes the post_init method.

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

    self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
    self.layers = nn.ModuleList(
        [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
    )
    self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
    self.gradient_checkpointing = False

    # register a causal mask to separate causal and padding mask creation. Merging happends in the attention class
    causal_mask = ops.full((config.max_position_embeddings, config.max_position_embeddings), fill_value=1)
    self.causal_mask = ops.triu(causal_mask, diagonal=1)
    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.gemma.modeling_gemma.GemmaModel.forward(input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, cache_position=None)

Constructs GemmaModel.

This method forwards the GemmaModel and performs the forward pass of the model. It takes various input parameters and returns the output hidden states, cache values, and attention values.

PARAMETER DESCRIPTION
self

The instance of the GemmaModel class.

TYPE: GemmaModel

input_ids

The input tensor containing the tokenized input sequence. Default is None.

TYPE: Tensor DEFAULT: None

attention_mask

The attention mask tensor to avoid attending to padding tokens. Default is None.

TYPE: Tensor DEFAULT: None

position_ids

The position indices tensor to specify the position of each token. Default is None.

TYPE: Tensor DEFAULT: None

past_key_values

The list of tensors containing the cached key-value pairs of the previous attention mechanism. Default is None.

TYPE: List[Tensor] DEFAULT: None

inputs_embeds

The input embedding tensor. Default is None.

TYPE: Tensor DEFAULT: None

use_cache

Whether to use cache mechanism. Default is None.

TYPE: bool DEFAULT: None

output_attentions

Whether to output the attention values. Default is None.

TYPE: bool DEFAULT: None

output_hidden_states

Whether to output the hidden states. Default is None.

TYPE: bool DEFAULT: None

return_dict

Whether to return the output as a dictionary. Default is None.

TYPE: bool DEFAULT: None

cache_position

The tensor representing the position of each token in the cache. Default is None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutputWithPast]

Union[Tuple, BaseModelOutputWithPast]: The output of the model. It can be a tuple containing hidden states, cache values, hidden states from all layers, and attention values from all layers; or an instance of BaseModelOutputWithPast containing the last hidden state, cache values, hidden states from all layers, and attention values from all layers.

RAISES DESCRIPTION
ValueError

If both input_ids and inputs_embeds are specified or neither of them is specified.

Warning

If use_cache is set to True while using gradient checkpointing, it will be set to False as it is not compatible.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
    cache_position: Optional[mindspore.Tensor] = None,
) -> Union[Tuple, BaseModelOutputWithPast]:
    """
    Constructs GemmaModel.

    This method forwards the GemmaModel and performs the forward pass of the model.
    It takes various input parameters and returns the output hidden states, cache values, and attention values.

    Args:
        self (GemmaModel): The instance of the GemmaModel class.
        input_ids (mindspore.Tensor, optional):
            The input tensor containing the tokenized input sequence. Default is None.
        attention_mask (mindspore.Tensor, optional):
            The attention mask tensor to avoid attending to padding tokens. Default is None.
        position_ids (mindspore.Tensor, optional):
            The position indices tensor to specify the position of each token. Default is None.
        past_key_values (List[mindspore.Tensor], optional):
            The list of tensors containing the cached key-value pairs of the previous attention mechanism.
            Default is None.
        inputs_embeds (mindspore.Tensor, optional): The input embedding tensor. Default is None.
        use_cache (bool, optional): Whether to use cache mechanism. Default is None.
        output_attentions (bool, optional): Whether to output the attention values. Default is None.
        output_hidden_states (bool, optional): Whether to output the hidden states. Default is None.
        return_dict (bool, optional): Whether to return the output as a dictionary. Default is None.
        cache_position (mindspore.Tensor, optional): The tensor representing the position of each token in the cache. Default is None.

    Returns:
        Union[Tuple, BaseModelOutputWithPast]: The output of the model.
            It can be a tuple containing hidden states, cache values, hidden states from all layers,
            and attention values from all layers; or an instance of BaseModelOutputWithPast containing the
            last hidden state, cache values, hidden states from all layers, and attention values from all layers.

    Raises:
        ValueError: If both input_ids and inputs_embeds are specified or neither of them is specified.
        Warning: If use_cache is set to True while using gradient checkpointing, it will be set to False as it is not compatible.
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    use_cache = use_cache if use_cache is not None else self.config.use_cache
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    if (input_ids is None) ^ (inputs_embeds is not None):
        raise ValueError(
            "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
        )

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

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

    past_seen_tokens = 0
    if use_cache:  # kept for BC (cache positions)
        if not isinstance(past_key_values, StaticCache):
            past_key_values = DynamicCache.from_legacy_cache(past_key_values)
        past_seen_tokens = past_key_values.get_seq_length()

    if cache_position is None:
        cache_position = ops.arange(
            past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1]
        )

    if position_ids is None:
        position_ids = cache_position.unsqueeze(0)

    causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)

    # embed positions
    hidden_states = inputs_embeds

    # normalized
    hidden_states = hidden_states * (self.config.hidden_size**0.5)

    # decoder layers
    all_hidden_states = () if output_hidden_states else None
    all_self_attns = () if output_attentions else None
    next_decoder_cache = None

    for decoder_layer in self.layers:
        if output_hidden_states:
            all_hidden_states += (hidden_states,)

        layer_outputs = decoder_layer(
            hidden_states,
            attention_mask=causal_mask,
            position_ids=position_ids,
            past_key_value=past_key_values,
            output_attentions=output_attentions,
            use_cache=use_cache,
            cache_position=cache_position,
        )

        hidden_states = layer_outputs[0]

        if use_cache:
            next_decoder_cache = layer_outputs[2 if output_attentions else 1]

        if output_attentions:
            all_self_attns += (layer_outputs[1],)

    hidden_states = self.norm(hidden_states)

    # add hidden states from the last decoder layer
    if output_hidden_states:
        all_hidden_states += (hidden_states,)

    next_cache = None
    if use_cache:
        next_cache = (
            next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
        )
    if not return_dict:
        return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
    return BaseModelOutputWithPast(
        last_hidden_state=hidden_states,
        past_key_values=next_cache,
        hidden_states=all_hidden_states,
        attentions=all_self_attns,
    )

mindnlp.transformers.models.gemma.modeling_gemma.GemmaModel.get_input_embeddings()

Get the input embeddings for the GemmaModel.

PARAMETER DESCRIPTION
self

An instance of the GemmaModel class.

TYPE: GemmaModel

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def get_input_embeddings(self):
    """
    Get the input embeddings for the GemmaModel.

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

    Returns:
        None.

    Raises:
        None.
    """
    return self.embed_tokens

mindnlp.transformers.models.gemma.modeling_gemma.GemmaModel.set_input_embeddings(value)

Set the input embeddings for the GemmaModel.

PARAMETER DESCRIPTION
self

The instance of the GemmaModel class.

TYPE: GemmaModel

value

The input embeddings to set for the model. This should be a tensor of shape (vocab_size, embedding_dim).

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the GemmaModel.

    Args:
        self (GemmaModel): The instance of the GemmaModel class.
        value: The input embeddings to set for the model. This should be a tensor of shape (vocab_size, embedding_dim).

    Returns:
        None.

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

mindnlp.transformers.models.gemma.modeling_gemma.GemmaPreTrainedModel

Bases: PreTrainedModel

The GemmaPreTrainedModel class is a subclass of PreTrainedModel that represents a pre-trained model for natural language processing tasks. It provides methods for initializing weights, setting up cache, and resetting cache.

METHOD DESCRIPTION
`_init_weights`

Initializes the weights of the given cell, which can be either a dense layer or an embedding layer.

`_setup_cache`

Sets up the cache for the model using the specified cache class, maximum batch size, and maximum cache length.

`_reset_cache`

Resets the cache for the model.

Example
>>> model = GemmaPreTrainedModel()
>>> model._init_weights(cell)
>>> model._setup_cache(cache_cls, max_batch_size, max_cache_len)
>>> model._reset_cache()
Note

The GemmaPreTrainedModel class inherits from PreTrainedModel. Refer to the documentation of PreTrainedModel for more information.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
class GemmaPreTrainedModel(PreTrainedModel):

    """
    The `GemmaPreTrainedModel` class is a subclass of `PreTrainedModel` that represents a pre-trained model for
    natural language processing tasks. It provides methods for initializing weights, setting up cache, and
    resetting cache.

    Methods:
        `_init_weights`: Initializes the weights of the given `cell`, which can be either a dense layer or an embedding layer.
        `_setup_cache`: Sets up the cache for the model using the specified cache class, maximum batch size,
            and maximum cache length.
        `_reset_cache`: Resets the cache for the model.

    Example:
        ```python
        >>> model = GemmaPreTrainedModel()
        >>> model._init_weights(cell)
        >>> model._setup_cache(cache_cls, max_batch_size, max_cache_len)
        >>> model._reset_cache()
        ```

    Note:
        The `GemmaPreTrainedModel` class inherits from `PreTrainedModel`. Refer to the documentation of `PreTrainedModel`
        for more information.
    """
    config_class = GemmaConfig
    base_model_prefix = "model"
    _keep_in_fp32_modules = ["inv_freq", "rotary_emb", "cos_cached", "sin_cached"]
    _no_split_modules = ["GemmaDecoderLayer"]
    _skip_keys_device_placement = ["past_key_values", "causal_mask"]
    _supports_cache_class = True

    def _init_weights(self, cell):
        """Initialize the weights"""
        if isinstance(cell, nn.Linear):
            cell.weight.set_data(initializer(Normal(self.config.initializer_range),
                                                    cell.weight.shape, cell.weight.dtype))
            if cell.bias:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.Embedding):
            weight = np.random.normal(0.0, self.config.initializer_range, cell.weight.shape)
            if cell.padding_idx:
                weight[cell.padding_idx] = 0

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

    def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
        """
        This method initializes the cache for the GemmaPreTrainedModel.

        Args:
            self (object): The instance of the GemmaPreTrainedModel class.
            cache_cls (class): The class representing the cache implementation.
            max_batch_size (int): The maximum batch size for caching.
            max_cache_len (int, Optional): The maximum length of the cache. Defaults to None.

        Returns:
            None.

        Raises:
            ValueError: If the attention implementation is 'flash_attention_2' and the cache_cls is StaticCache,
                as these are not compatible. It advises to use 'sdpa' as an alternative and to open an issue at
                https://github.com/huggingface/transformers.
            ValueError: If the max_cache_len exceeds the length of the model's causal mask.
                This ensures that the cache length does not exceed the model's capabilities.
        """
        if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
            raise ValueError(
                "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
                "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
            )

        if max_cache_len > self.model.causal_mask.shape[-1]:
            causal_mask = ops.full((max_cache_len, max_cache_len), fill_value=1)
            self.causal_mask = ops.triu(causal_mask, diagonal=1)

        for layer in self.model.layers:
            weights = layer.self_attn.o_proj.weight
            layer.self_attn.past_key_value = cache_cls(
                self.config, max_batch_size, max_cache_len, dtype=weights.dtype
            )

    def _reset_cache(self):
        """
        Resets the cache for the GemmaPreTrainedModel.

        Args:
            self: GemmaPreTrainedModel instance. The instance of the GemmaPreTrainedModel for which the cache is to be reset.

        Returns:
            None.

        Raises:
            None.
        """
        for layer in self.model.layers:
            layer.self_attn.past_key_value = None

mindnlp.transformers.models.gemma.modeling_gemma.GemmaRMSNorm

Bases: Module

This class represents a custom implementation of Root Mean Square Normalization (RMSNorm) called GemmaRMSNorm, which is designed for neural network operations. It inherits from the nn.Module class. The GemmaRMSNorm class initializes with parameters for dimension and epsilon value, and includes methods for calculating the normalized output based on the input data and weight parameters. The _norm method calculates the normalized output based on the input data and epsilon value. The forward method applies the normalization and weight parameters to the input data to generate the final output.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
class GemmaRMSNorm(nn.Module):

    """
    This class represents a custom implementation of Root Mean Square Normalization (RMSNorm) called GemmaRMSNorm,
    which is designed for neural network operations.
    It inherits from the nn.Module class. The GemmaRMSNorm class initializes with parameters for dimension and epsilon
    value, and includes methods for calculating the normalized output based on the input data and weight parameters.
    The _norm method calculates the normalized output based on the input data and epsilon value.
    The forward method applies the normalization and weight parameters to the input data to generate the final output.
    """
    def __init__(self, dim: int, eps: float = 1e-6):
        """
        Initializes a GemmaRMSNorm instance.

        Args:
            self: The object instance itself.
            dim (int): The dimension of the GemmaRMSNorm.
            eps (float, optional): The epsilon value for numerical stability. Defaults to 1e-06.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.eps = eps
        self.weight = Parameter(ops.zeros(dim))

    def _norm(self, x):
        """
        Calculates the normalized value of a given input tensor 'x' using the root mean square (RMS) normalization method.

        Args:
            self (GemmaRMSNorm): An instance of the GemmaRMSNorm class.
            x (Tensor):
                The input tensor to be normalized.

                - Shape: (batch_size, ..., features)
                - dtype: torch.float32 or torch.float64

        Returns:
            None

        Raises:
            ValueError: If the input tensor 'x' is not a valid tensor.
            RuntimeError: If an error occurs during the calculation.

        Notes:
            - The RMS normalization method divides each element of the input tensor 'x' by the root mean square of the tensor.
            - The root mean square of 'x' is calculated as follows:

                - square each element of 'x'
                - calculate the mean across the last dimension of the tensor (features)
                - take the square root of the mean

            - The resulting normalized tensor has the same shape as the input tensor 'x'.
            - The 'keep_dims' argument in the mean operation ensures that the mean is calculated along the last
            dimension and the resulting tensor has the same number of dimensions as the input tensor.

        Example:
            ```python
            >>> norm = GemmaRMSNorm()
            >>> x = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
            >>> norm._norm(x)
            >>> # x is now normalized using the RMS normalization method.
            ```
        """
        return x * ops.rsqrt(x.pow(2).mean(-1, keep_dims=True) + self.eps)

    def forward(self, x):
        """
        Constructs a normalized tensor using the GemmaRMSNorm algorithm.

        Args:
            self (GemmaRMSNorm): An instance of the GemmaRMSNorm class.
            x (Tensor): The input tensor to be normalized. It should have a numeric data type.

        Returns:
            None: This method does not return any value.
                The normalized tensor is stored internally within the GemmaRMSNorm instance.

        Raises:
            TypeError: If the input tensor `x` is not of numeric data type.
        """
        output = self._norm(x.float()).astype(x.dtype)
        return output * (1 + self.weight)

mindnlp.transformers.models.gemma.modeling_gemma.GemmaRMSNorm.__init__(dim, eps=1e-06)

Initializes a GemmaRMSNorm instance.

PARAMETER DESCRIPTION
self

The object instance itself.

dim

The dimension of the GemmaRMSNorm.

TYPE: int

eps

The epsilon value for numerical stability. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(self, dim: int, eps: float = 1e-6):
    """
    Initializes a GemmaRMSNorm instance.

    Args:
        self: The object instance itself.
        dim (int): The dimension of the GemmaRMSNorm.
        eps (float, optional): The epsilon value for numerical stability. Defaults to 1e-06.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.eps = eps
    self.weight = Parameter(ops.zeros(dim))

mindnlp.transformers.models.gemma.modeling_gemma.GemmaRMSNorm.forward(x)

Constructs a normalized tensor using the GemmaRMSNorm algorithm.

PARAMETER DESCRIPTION
self

An instance of the GemmaRMSNorm class.

TYPE: GemmaRMSNorm

x

The input tensor to be normalized. It should have a numeric data type.

TYPE: Tensor

RETURNS DESCRIPTION
None

This method does not return any value. The normalized tensor is stored internally within the GemmaRMSNorm instance.

RAISES DESCRIPTION
TypeError

If the input tensor x is not of numeric data type.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def forward(self, x):
    """
    Constructs a normalized tensor using the GemmaRMSNorm algorithm.

    Args:
        self (GemmaRMSNorm): An instance of the GemmaRMSNorm class.
        x (Tensor): The input tensor to be normalized. It should have a numeric data type.

    Returns:
        None: This method does not return any value.
            The normalized tensor is stored internally within the GemmaRMSNorm instance.

    Raises:
        TypeError: If the input tensor `x` is not of numeric data type.
    """
    output = self._norm(x.float()).astype(x.dtype)
    return output * (1 + self.weight)

mindnlp.transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding

Bases: Module

This class represents a GemmaRotaryEmbedding module, which is a custom embedding layer used in neural networks. It inherits from the nn.Module class.

The GemmaRotaryEmbedding module is designed to forward rotary embeddings for input data sequences. It creates embeddings based on the positions in the input sequence, using a sinusoidal function. The embeddings are computed as the cosine and sine of the frequency values derived from the positions.

ATTRIBUTE DESCRIPTION
dim

The dimension of the embeddings.

TYPE: int

max_position_embeddings

The maximum number of positions in the input sequence. Defaults to 2048.

TYPE: int

base

The base value used in the frequency calculation. Defaults to 10000.

TYPE: int

inv_freq

An array storing the precomputed inverse frequencies. Defaults to None.

TYPE: ndarray or None

METHOD DESCRIPTION
__init__

Initializes the GemmaRotaryEmbedding module with the given parameters.

Args:

  • dim (int): The dimension of the embeddings.
  • max_position_embeddings (int, optional): The maximum number of positions in the input sequence. Defaults to 2048.
  • base (int, optional): The base value used in the frequency calculation. Defaults to 10000.
forward

Constructs the rotary embeddings based on the input data and position IDs.

Args:

  • x (Tensor): The input data tensor.
  • position_ids (Tensor): The tensor containing the position IDs corresponding to each element in the input sequence.
  • seq_len (int, optional): The length of the input sequence. Defaults to None.

Returns:

  • Tensor: The forwarded rotary embeddings as the cosine and sine of the frequency values, casted to the same data type as the input tensor.
Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
class GemmaRotaryEmbedding(nn.Module):

    """
    This class represents a GemmaRotaryEmbedding module, which is a custom embedding layer used in neural networks.
    It inherits from the nn.Module class.

    The GemmaRotaryEmbedding module is designed to forward rotary embeddings for input data sequences.
    It creates embeddings based on the positions in the input sequence, using a sinusoidal function.
    The embeddings are computed as the cosine and sine of the frequency values derived from the positions.

    Attributes:
        dim (int): The dimension of the embeddings.
        max_position_embeddings (int): The maximum number of positions in the input sequence. Defaults to 2048.
        base (int): The base value used in the frequency calculation. Defaults to 10000.
        inv_freq (ndarray or None): An array storing the precomputed inverse frequencies. Defaults to None.

    Methods:
        __init__(self, dim, max_position_embeddings=2048, base=10000):
            Initializes the GemmaRotaryEmbedding module with the given parameters.

            Args:

            - dim (int): The dimension of the embeddings.
            - max_position_embeddings (int, optional): The maximum number of positions in the input sequence.
            Defaults to 2048.
            - base (int, optional): The base value used in the frequency calculation. Defaults to 10000.

        forward(self, x, position_ids, seq_len=None):
            Constructs the rotary embeddings based on the input data and position IDs.

            Args:

            - x (Tensor): The input data tensor.
            - position_ids (Tensor): The tensor containing the position IDs corresponding to each element in the
            input sequence.
            - seq_len (int, optional): The length of the input sequence. Defaults to None.

            Returns:

            - Tensor: The forwarded rotary embeddings as the cosine and sine of the frequency values,
            casted to the same data type as the input tensor.
    """
    def __init__(self, dim, max_position_embeddings=2048, base=10000):
        """
        Initialize GemmaRotaryEmbedding object with specified parameters.

        Args:
            self (object): The instance of the class.
            dim (int): The dimension of the embedding.
            max_position_embeddings (int, optional): Maximum number of positions for the embeddings. Default is 2048.
            base (int, optional): Base value used for calculations. Default is 10000.

        Returns:
            None.

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

        self.dim = dim
        self.max_position_embeddings = max_position_embeddings
        self.base = base
        self.inv_freq = None

    def forward(self, x, position_ids, seq_len=None):
        """
        Constructs GemmaRotaryEmbedding for positional encoding.

        Args:
            self (GemmaRotaryEmbedding): The instance of the GemmaRotaryEmbedding class.
            x (Tensor): The input tensor.
            position_ids (Tensor): The tensor containing positional IDs.
            seq_len (int): The length of the input sequence.

        Returns:
            The concatenated cosine and sine embeddings of the positional encoding.

        Raises:
            ValueError: If self.inv_freq is not initialized.
            TypeError: If the input tensors x and position_ids are not of the correct data type.
            IndexError: If the dimensions of the input tensors are incompatible for matrix multiplication.
        """
        # x: [bs, num_attention_heads, seq_len, head_size]
        if self.inv_freq is None:
            self.inv_freq = 1.0 / (
                self.base ** (ops.arange(0, self.dim, 2, dtype=mindspore.int64).float() / self.dim)
            )

        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
        position_ids_expanded = position_ids[:, None, :].float()
        freqs = (inv_freq_expanded @ position_ids_expanded).swapaxes(1, 2)
        emb = ops.cat((freqs, freqs), axis=-1)
        return emb.cos().to(dtype=x.dtype), emb.sin().to(dtype=x.dtype)

mindnlp.transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding.__init__(dim, max_position_embeddings=2048, base=10000)

Initialize GemmaRotaryEmbedding object with specified parameters.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

dim

The dimension of the embedding.

TYPE: int

max_position_embeddings

Maximum number of positions for the embeddings. Default is 2048.

TYPE: int DEFAULT: 2048

base

Base value used for calculations. Default is 10000.

TYPE: int DEFAULT: 10000

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def __init__(self, dim, max_position_embeddings=2048, base=10000):
    """
    Initialize GemmaRotaryEmbedding object with specified parameters.

    Args:
        self (object): The instance of the class.
        dim (int): The dimension of the embedding.
        max_position_embeddings (int, optional): Maximum number of positions for the embeddings. Default is 2048.
        base (int, optional): Base value used for calculations. Default is 10000.

    Returns:
        None.

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

    self.dim = dim
    self.max_position_embeddings = max_position_embeddings
    self.base = base
    self.inv_freq = None

mindnlp.transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding.forward(x, position_ids, seq_len=None)

Constructs GemmaRotaryEmbedding for positional encoding.

PARAMETER DESCRIPTION
self

The instance of the GemmaRotaryEmbedding class.

TYPE: GemmaRotaryEmbedding

x

The input tensor.

TYPE: Tensor

position_ids

The tensor containing positional IDs.

TYPE: Tensor

seq_len

The length of the input sequence.

TYPE: int DEFAULT: None

RETURNS DESCRIPTION

The concatenated cosine and sine embeddings of the positional encoding.

RAISES DESCRIPTION
ValueError

If self.inv_freq is not initialized.

TypeError

If the input tensors x and position_ids are not of the correct data type.

IndexError

If the dimensions of the input tensors are incompatible for matrix multiplication.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def forward(self, x, position_ids, seq_len=None):
    """
    Constructs GemmaRotaryEmbedding for positional encoding.

    Args:
        self (GemmaRotaryEmbedding): The instance of the GemmaRotaryEmbedding class.
        x (Tensor): The input tensor.
        position_ids (Tensor): The tensor containing positional IDs.
        seq_len (int): The length of the input sequence.

    Returns:
        The concatenated cosine and sine embeddings of the positional encoding.

    Raises:
        ValueError: If self.inv_freq is not initialized.
        TypeError: If the input tensors x and position_ids are not of the correct data type.
        IndexError: If the dimensions of the input tensors are incompatible for matrix multiplication.
    """
    # x: [bs, num_attention_heads, seq_len, head_size]
    if self.inv_freq is None:
        self.inv_freq = 1.0 / (
            self.base ** (ops.arange(0, self.dim, 2, dtype=mindspore.int64).float() / self.dim)
        )

    inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
    position_ids_expanded = position_ids[:, None, :].float()
    freqs = (inv_freq_expanded @ position_ids_expanded).swapaxes(1, 2)
    emb = ops.cat((freqs, freqs), axis=-1)
    return emb.cos().to(dtype=x.dtype), emb.sin().to(dtype=x.dtype)

mindnlp.transformers.models.gemma.modeling_gemma.apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1)

Applies Rotary Position Embedding to the query and key tensors.

PARAMETER DESCRIPTION
q

The query tensor.

TYPE: `mindspore.Tensor`

k

The key tensor.

TYPE: `mindspore.Tensor`

cos

The cosine part of the rotary embedding.

TYPE: `mindspore.Tensor`

sin

The sine part of the rotary embedding.

TYPE: `mindspore.Tensor`

position_ids

Deprecated and unused.

TYPE: `mindspore.Tensor`, *optional* DEFAULT: None

unsqueeze_dim

The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.

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

RETURNS DESCRIPTION

tuple(mindspore.Tensor) comprising of the query and key tensors rotated using the Rotary Position Embedding.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
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
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
    """Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`mindspore.Tensor`): The query tensor.
        k (`mindspore.Tensor`): The key tensor.
        cos (`mindspore.Tensor`): The cosine part of the rotary embedding.
        sin (`mindspore.Tensor`): The sine part of the rotary embedding.
        position_ids (`mindspore.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.

    Returns:
        `tuple(mindspore.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    """
    cos = cos.unsqueeze(unsqueeze_dim)
    sin = sin.unsqueeze(unsqueeze_dim)
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed, k_embed

mindnlp.transformers.models.gemma.modeling_gemma.repeat_kv(hidden_states, n_rep)

This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
364
365
366
367
368
369
370
371
372
373
def repeat_kv(hidden_states: mindspore.Tensor, n_rep: int) -> mindspore.Tensor:
    """
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    """
    batch, num_key_value_heads, slen, head_dim = hidden_states.shape
    if n_rep == 1:
        return hidden_states
    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)

mindnlp.transformers.models.gemma.modeling_gemma.rotate_half(x)

Rotates half the hidden dims of the input.

Source code in mindnlp/transformers/models/gemma/modeling_gemma.py
260
261
262
263
264
265
def rotate_half(x):
    """Rotates half the hidden dims of the input."""
    # x1 = x[..., : x.shape[-1] // 2]
    # x2 = x[..., x.shape[-1] // 2 :]
    x1, x2 = x.tensor_split(2, axis=-1)
    return ops.cat((-x2, x1), axis=-1)

mindnlp.transformers.models.gemma.tokenization_gemma

Tokenization classes for Gemma.

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer

Bases: PreTrainedTokenizer

Construct a Gemma tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is no padding token in the original model.

PARAMETER DESCRIPTION
vocab_file

Path to the vocabulary file.

TYPE: `str`

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` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"` DEFAULT: '<unk>'

bos_token

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

TYPE: `str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"` DEFAULT: '<bos>'

eos_token

The end of sequence token.

TYPE: `str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"` DEFAULT: '<eos>'

pad_token

A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation.

TYPE: `str` or `tokenizers.AddedToken`, *optional*, defaults to `"<pad>"` DEFAULT: '<pad>'

sp_model_kwargs

Will be passed to the SentencePieceProcessor.__init__() method. The Python wrapper for SentencePiece can be used, among other things, to set:

  • enable_sampling: Enable subword regularization.
  • nbest_size: Sampling parameters for unigram. Invalid for BPE-Dropout.

    • nbest_size = {0,1}: No sampling is performed.
    • nbest_size > 1: samples from the nbest_size results.
    • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
    • alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.

TYPE: `Dict[str, Any]`, `Optional`, *optional* DEFAULT: None

add_bos_token

Whether or not to add an bos_token at the start of sequences.

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

add_eos_token

Whether or not to add an eos_token at the end of sequences.

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

clean_up_tokenization_spaces

Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces.

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

use_default_system_prompt

Whether or not the default system prompt for Gemma should be used.

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

spaces_between_special_tokens

Whether or not to add spaces between special tokens.

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

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
 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
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
class GemmaTokenizer(PreTrainedTokenizer):
    """
    Construct a Gemma tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
    no padding token in the original model.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        unk_token (`str` or `tokenizers.AddedToken`, *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.
        bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
        eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"`):
            The end of sequence token.
        pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<pad>"`):
            A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
            attention mechanisms or loss computation.
        sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

            - `enable_sampling`: Enable subword regularization.
            - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

                - `nbest_size = {0,1}`: No sampling is performed.
                - `nbest_size > 1`: samples from the nbest_size results.
                - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.
                - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
                BPE-dropout.

        add_bos_token (`bool`, *optional*, defaults to `True`):
            Whether or not to add an `bos_token` at the start of sequences.
        add_eos_token (`bool`, *optional*, defaults to `False`):
            Whether or not to add an `eos_token` at the end of sequences.
        clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
            Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
            extra spaces.
        use_default_system_prompt (`bool`, *optional*, defaults to `False`):
            Whether or not the default system prompt for Gemma should be used.
        spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
            Whether or not to add spaces between special tokens.
    """
    vocab_files_names = VOCAB_FILES_NAMES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        unk_token="<unk>",
        bos_token="<bos>",
        eos_token="<eos>",
        pad_token="<pad>",
        sp_model_kwargs: Optional[Dict[str, Any]] = None,
        add_bos_token=True,
        add_eos_token=False,
        clean_up_tokenization_spaces=False,
        use_default_system_prompt=False,
        spaces_between_special_tokens=False,
        **kwargs,
    ):
        """
        This method initializes an instance of GemmaTokenizer.

        Args:
            self: The instance of the class.
            vocab_file (str): The path to the vocabulary file.
            unk_token (str): The unknown token. Default is '<unk>'.
            bos_token (str): The beginning of sequence token. Default is '<bos>'.
            eos_token (str): The end of sequence token. Default is '<eos>'.
            pad_token (str): The padding token. Default is '<pad>'.
            sp_model_kwargs (Optional[Dict[str, Any]]): Optional keyword arguments for SentencePiece model configuration.
                Default is None.
            add_bos_token (bool): Whether to add the beginning of sequence token. Default is True.
            add_eos_token (bool): Whether to add the end of sequence token. Default is False.
            clean_up_tokenization_spaces (bool): Whether to clean up tokenization spaces. Default is False.
            use_default_system_prompt (bool): Whether to use the default system prompt. Default is False.
            spaces_between_special_tokens (bool): Whether to add spaces between special tokens. Default is False.

        Returns:
            None.

        Raises:
            ValueError: If the provided vocab_file is invalid or does not exist.
            OSError: If an I/O or OS error occurs while loading the vocab_file.
            TypeError: If the provided sp_model_kwargs is not a dictionary.
            RuntimeError: If an error occurs during the initialization process.
        """
        self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
        bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
        eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
        unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
        pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token

        self.vocab_file = vocab_file
        self.add_bos_token = add_bos_token
        self.add_eos_token = add_eos_token
        self.use_default_system_prompt = use_default_system_prompt

        self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
        self.sp_model.Load(vocab_file)

        super().__init__(
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            pad_token=pad_token,
            add_bos_token=add_bos_token,
            add_eos_token=add_eos_token,
            sp_model_kwargs=self.sp_model_kwargs,
            clean_up_tokenization_spaces=clean_up_tokenization_spaces,
            use_default_system_prompt=use_default_system_prompt,
            spaces_between_special_tokens=spaces_between_special_tokens,
            **kwargs,
        )

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.__getstate__
    def __getstate__(self):
        """
        Get the state of the GemmaTokenizer object for serialization.

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

        Returns:
            None.

        Raises:
            None.
        """
        state = self.__dict__.copy()
        state["sp_model"] = None
        state["sp_model_proto"] = self.sp_model.serialized_model_proto()
        return state

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.__setstate__
    def __setstate__(self, d):
        """
        This method '__setstate__' in the class 'GemmaTokenizer' is used to set the internal state of the tokenizer
        object based on the provided dictionary 'd'.

        Args:
            self (GemmaTokenizer): The instance of the GemmaTokenizer class on which this method is called.
                It represents the tokenizer object itself.
            d (dict): A dictionary containing the state information to be set on the tokenizer object.
                This dictionary should include the necessary information for reforwarding the object's state.

        Returns:
            None: This method does not return any value explicitly.
                It updates the state of the GemmaTokenizer object in-place.

        Raises:
            None:
                However, potential exceptions could be raised during the execution of the code within the method, such as:

                - TypeError: If the provided 'd' parameter is not a valid dictionary.
                - ValueError: If the 'sp_model_kwargs' or 'sp_model_proto' keys are missing in the 'd' dictionary.
                - Other exceptions related to the initialization or loading of the SentencePieceProcessor object may occur.
        """
        self.__dict__ = d
        self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto)

    @property
    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.vocab_size
    def vocab_size(self):
        """Returns vocab size"""
        return self.sp_model.get_piece_size()

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.get_vocab
    def get_vocab(self):
        """Returns vocab as a dict"""
        vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
        vocab.update(self.added_tokens_encoder)
        return vocab

    def _tokenize(self, text, **kwargs):
        """
        Returns a tokenized string. The Gemma tokenizer never adds a prefix space.
        """
        return self.sp_model.encode(text, out_type=str)

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer._convert_token_to_id
    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.sp_model.piece_to_id(token)

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer._convert_id_to_token
    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        token = self.sp_model.IdToPiece(index)
        return token

    def _decode(
        self,
        token_ids: List[int],
        skip_special_tokens: bool = False,
        spaces_between_special_tokens: bool = False,
        **kwargs,
    ) -> str:
        """
        Decodes a list of token IDs into a string representation.

        Args:
            self (GemmaTokenizer): An instance of the GemmaTokenizer class.
            token_ids (List[int]): A list of token IDs to be decoded.
            skip_special_tokens (bool, optional): Whether to skip special tokens during decoding. Defaults to False.
            spaces_between_special_tokens (bool, optional):
                Whether to include spaces between special tokens in the decoded string. Defaults to False.
            **kwargs: Additional keyword arguments.

        Returns:
            str: The decoded string representation of the token IDs.

        Raises:
            None.

        Note:
            - The method decodes the token IDs by iterating through the list and converting each ID into its corresponding text.
            - If skip_special_tokens is set to True, special tokens are ignored and not included in the decoded string.
            - If spaces_between_special_tokens is set to True, spaces are added between special tokens in the decoded string.
            - The decoding process utilizes the GemmaTokenizer's sp_model and _added_tokens_decoder attributes.

        Example:
            ```python
            >>> tokenizer = GemmaTokenizer()
            >>> token_ids = [101, 2054, 2003, 1037, 2154, 2008, 1037, 2307, 1012, 102]
            >>> tokenizer._decode(token_ids)
            '[CLS] This is a sample text. [SEP]'
            ```
        """
        sub_texts = []
        current_sub_text = []
        for ids in token_ids:
            if skip_special_tokens and ids in self.all_special_ids:
                continue
            if ids in self._added_tokens_decoder:
                if current_sub_text:
                    sub_texts.append(self.sp_model.decode(current_sub_text))
                sub_texts.append(self._added_tokens_decoder[ids].content)
                current_sub_text = []
            else:
                current_sub_text.append(ids)
        if current_sub_text:
            sub_texts.append(self.sp_model.decode(current_sub_text))

        if spaces_between_special_tokens:
            sub_texts = " ".join(sub_texts)
        else:
            sub_texts = "".join(sub_texts)

        return sub_texts

    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        current_sub_tokens = []
        out_string = ""
        for token in tokens:
            # make sure that special tokens are not decoded using sentencepiece model
            if token in self._added_tokens_encoder:
                out_string += self.sp_model.decode(current_sub_tokens) + token
                current_sub_tokens = []
            else:
                current_sub_tokens.append(token)
        out_string += self.sp_model.decode(current_sub_tokens)
        return out_string

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.save_vocabulary
    def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary and special tokens file to a directory.

        Args:
            save_directory (`str`):
                The directory in which to save the vocabulary.

        Returns:
            `Tuple(str)`: Paths to the files saved.
        """
        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        out_vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )

        if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
            copyfile(self.vocab_file, out_vocab_file)
        elif not os.path.isfile(self.vocab_file):
            with open(out_vocab_file, "wb") as fi:
                content_spiece_model = self.sp_model.serialized_model_proto()
                fi.write(content_spiece_model)

        return (out_vocab_file,)

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        ''' 
        build_inputs_with_special_tokens method in GemmaTokenizer class.

        This method takes three parameters:

        Args:
            self: GemmaTokenizer object.
            token_ids_0: list of integers. The token IDs for the first sequence.
            token_ids_1: (optional) list of integers. The token IDs for the second sequence.

        Returns:
            list of integers:
                The concatenated token IDs with special tokens added at the beginning and end of each sequence.

        Raises:
            None.
        '''
        bos_token_id = [self.bos_token_id] if self.add_bos_token else []
        eos_token_id = [self.eos_token_id] if self.add_eos_token else []

        output = bos_token_id + token_ids_0 + eos_token_id

        if token_ids_1 is not None:
            output = output + bos_token_id + token_ids_1 + eos_token_id

        return output

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.get_special_tokens_mask
    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
            )

        bos_token_id = [1] if self.add_bos_token else []
        eos_token_id = [1] if self.add_eos_token else []

        if token_ids_1 is None:
            return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
        return (
            bos_token_id
            + ([0] * len(token_ids_0))
            + eos_token_id
            + bos_token_id
            + ([0] * len(token_ids_1))
            + eos_token_id
        )

    # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.create_token_type_ids_from_sequences
    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
        sequence pair mask has the following format:

        ```
        0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
        | first sequence    | second sequence |
        ```

        if token_ids_1 is None, only returns the first portion of the mask (0s).

        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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        """
        bos_token_id = [self.bos_token_id] if self.add_bos_token else []
        eos_token_id = [self.eos_token_id] if self.add_eos_token else []

        output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)

        if token_ids_1 is not None:
            output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)

        return output

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.vocab_size property

Returns vocab size

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.__getstate__()

Get the state of the GemmaTokenizer object for serialization.

PARAMETER DESCRIPTION
self

The current instance of the GemmaTokenizer class.

TYPE: GemmaTokenizer

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def __getstate__(self):
    """
    Get the state of the GemmaTokenizer object for serialization.

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

    Returns:
        None.

    Raises:
        None.
    """
    state = self.__dict__.copy()
    state["sp_model"] = None
    state["sp_model_proto"] = self.sp_model.serialized_model_proto()
    return state

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.__init__(vocab_file, unk_token='<unk>', bos_token='<bos>', eos_token='<eos>', pad_token='<pad>', sp_model_kwargs=None, add_bos_token=True, add_eos_token=False, clean_up_tokenization_spaces=False, use_default_system_prompt=False, spaces_between_special_tokens=False, **kwargs)

This method initializes an instance of GemmaTokenizer.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

The path to the vocabulary file.

TYPE: str

unk_token

The unknown token. Default is ''.

TYPE: str DEFAULT: '<unk>'

bos_token

The beginning of sequence token. Default is ''.

TYPE: str DEFAULT: '<bos>'

eos_token

The end of sequence token. Default is ''.

TYPE: str DEFAULT: '<eos>'

pad_token

The padding token. Default is ''.

TYPE: str DEFAULT: '<pad>'

sp_model_kwargs

Optional keyword arguments for SentencePiece model configuration. Default is None.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

add_bos_token

Whether to add the beginning of sequence token. Default is True.

TYPE: bool DEFAULT: True

add_eos_token

Whether to add the end of sequence token. Default is False.

TYPE: bool DEFAULT: False

clean_up_tokenization_spaces

Whether to clean up tokenization spaces. Default is False.

TYPE: bool DEFAULT: False

use_default_system_prompt

Whether to use the default system prompt. Default is False.

TYPE: bool DEFAULT: False

spaces_between_special_tokens

Whether to add spaces between special tokens. Default is False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the provided vocab_file is invalid or does not exist.

OSError

If an I/O or OS error occurs while loading the vocab_file.

TypeError

If the provided sp_model_kwargs is not a dictionary.

RuntimeError

If an error occurs during the initialization process.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
 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
def __init__(
    self,
    vocab_file,
    unk_token="<unk>",
    bos_token="<bos>",
    eos_token="<eos>",
    pad_token="<pad>",
    sp_model_kwargs: Optional[Dict[str, Any]] = None,
    add_bos_token=True,
    add_eos_token=False,
    clean_up_tokenization_spaces=False,
    use_default_system_prompt=False,
    spaces_between_special_tokens=False,
    **kwargs,
):
    """
    This method initializes an instance of GemmaTokenizer.

    Args:
        self: The instance of the class.
        vocab_file (str): The path to the vocabulary file.
        unk_token (str): The unknown token. Default is '<unk>'.
        bos_token (str): The beginning of sequence token. Default is '<bos>'.
        eos_token (str): The end of sequence token. Default is '<eos>'.
        pad_token (str): The padding token. Default is '<pad>'.
        sp_model_kwargs (Optional[Dict[str, Any]]): Optional keyword arguments for SentencePiece model configuration.
            Default is None.
        add_bos_token (bool): Whether to add the beginning of sequence token. Default is True.
        add_eos_token (bool): Whether to add the end of sequence token. Default is False.
        clean_up_tokenization_spaces (bool): Whether to clean up tokenization spaces. Default is False.
        use_default_system_prompt (bool): Whether to use the default system prompt. Default is False.
        spaces_between_special_tokens (bool): Whether to add spaces between special tokens. Default is False.

    Returns:
        None.

    Raises:
        ValueError: If the provided vocab_file is invalid or does not exist.
        OSError: If an I/O or OS error occurs while loading the vocab_file.
        TypeError: If the provided sp_model_kwargs is not a dictionary.
        RuntimeError: If an error occurs during the initialization process.
    """
    self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
    bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
    eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
    unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
    pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token

    self.vocab_file = vocab_file
    self.add_bos_token = add_bos_token
    self.add_eos_token = add_eos_token
    self.use_default_system_prompt = use_default_system_prompt

    self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
    self.sp_model.Load(vocab_file)

    super().__init__(
        bos_token=bos_token,
        eos_token=eos_token,
        unk_token=unk_token,
        pad_token=pad_token,
        add_bos_token=add_bos_token,
        add_eos_token=add_eos_token,
        sp_model_kwargs=self.sp_model_kwargs,
        clean_up_tokenization_spaces=clean_up_tokenization_spaces,
        use_default_system_prompt=use_default_system_prompt,
        spaces_between_special_tokens=spaces_between_special_tokens,
        **kwargs,
    )

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.__setstate__(d)

This method 'setstate' in the class 'GemmaTokenizer' is used to set the internal state of the tokenizer object based on the provided dictionary 'd'.

PARAMETER DESCRIPTION
self

The instance of the GemmaTokenizer class on which this method is called. It represents the tokenizer object itself.

TYPE: GemmaTokenizer

d

A dictionary containing the state information to be set on the tokenizer object. This dictionary should include the necessary information for reforwarding the object's state.

TYPE: dict

RETURNS DESCRIPTION
None

This method does not return any value explicitly. It updates the state of the GemmaTokenizer object in-place.

RAISES DESCRIPTION
None

However, potential exceptions could be raised during the execution of the code within the method, such as:

  • TypeError: If the provided 'd' parameter is not a valid dictionary.
  • ValueError: If the 'sp_model_kwargs' or 'sp_model_proto' keys are missing in the 'd' dictionary.
  • Other exceptions related to the initialization or loading of the SentencePieceProcessor object may occur.
Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
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
def __setstate__(self, d):
    """
    This method '__setstate__' in the class 'GemmaTokenizer' is used to set the internal state of the tokenizer
    object based on the provided dictionary 'd'.

    Args:
        self (GemmaTokenizer): The instance of the GemmaTokenizer class on which this method is called.
            It represents the tokenizer object itself.
        d (dict): A dictionary containing the state information to be set on the tokenizer object.
            This dictionary should include the necessary information for reforwarding the object's state.

    Returns:
        None: This method does not return any value explicitly.
            It updates the state of the GemmaTokenizer object in-place.

    Raises:
        None:
            However, potential exceptions could be raised during the execution of the code within the method, such as:

            - TypeError: If the provided 'd' parameter is not a valid dictionary.
            - ValueError: If the 'sp_model_kwargs' or 'sp_model_proto' keys are missing in the 'd' dictionary.
            - Other exceptions related to the initialization or loading of the SentencePieceProcessor object may occur.
    """
    self.__dict__ = d
    self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto)

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

build_inputs_with_special_tokens method in GemmaTokenizer class.

This method takes three parameters:

PARAMETER DESCRIPTION
self

GemmaTokenizer object.

token_ids_0

list of integers. The token IDs for the first sequence.

token_ids_1

(optional) list of integers. The token IDs for the second sequence.

DEFAULT: None

RETURNS DESCRIPTION

list of integers: The concatenated token IDs with special tokens added at the beginning and end of each sequence.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
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
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    ''' 
    build_inputs_with_special_tokens method in GemmaTokenizer class.

    This method takes three parameters:

    Args:
        self: GemmaTokenizer object.
        token_ids_0: list of integers. The token IDs for the first sequence.
        token_ids_1: (optional) list of integers. The token IDs for the second sequence.

    Returns:
        list of integers:
            The concatenated token IDs with special tokens added at the beginning and end of each sequence.

    Raises:
        None.
    '''
    bos_token_id = [self.bos_token_id] if self.add_bos_token else []
    eos_token_id = [self.eos_token_id] if self.add_eos_token else []

    output = bos_token_id + token_ids_0 + eos_token_id

    if token_ids_1 is not None:
        output = output + bos_token_id + token_ids_1 + eos_token_id

    return output

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.convert_tokens_to_string(tokens)

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

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
292
293
294
295
296
297
298
299
300
301
302
303
304
def convert_tokens_to_string(self, tokens):
    """Converts a sequence of tokens (string) in a single string."""
    current_sub_tokens = []
    out_string = ""
    for token in tokens:
        # make sure that special tokens are not decoded using sentencepiece model
        if token in self._added_tokens_encoder:
            out_string += self.sp_model.decode(current_sub_tokens) + token
            current_sub_tokens = []
        else:
            current_sub_tokens.append(token)
    out_string += self.sp_model.decode(current_sub_tokens)
    return out_string

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT sequence pair mask has the following format:

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

if token_ids_1 is None, only returns the first portion of the mask (0s).

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 token type IDs according to the given sequence(s).

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
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 create_token_type_ids_from_sequences(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
    sequence pair mask has the following format:

    ```
    0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
    | first sequence    | second sequence |
    ```

    if token_ids_1 is None, only returns the first portion of the mask (0s).

    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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
    """
    bos_token_id = [self.bos_token_id] if self.add_bos_token else []
    eos_token_id = [self.eos_token_id] if self.add_eos_token else []

    output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)

    if token_ids_1 is not None:
        output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)

    return output

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.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/gemma/tokenization_gemma.py
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
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
        )

    bos_token_id = [1] if self.add_bos_token else []
    eos_token_id = [1] if self.add_eos_token else []

    if token_ids_1 is None:
        return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
    return (
        bos_token_id
        + ([0] * len(token_ids_0))
        + eos_token_id
        + bos_token_id
        + ([0] * len(token_ids_1))
        + eos_token_id
    )

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.get_vocab()

Returns vocab as a dict

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
209
210
211
212
213
def get_vocab(self):
    """Returns vocab as a dict"""
    vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
    vocab.update(self.added_tokens_encoder)
    return vocab

mindnlp.transformers.models.gemma.tokenization_gemma.GemmaTokenizer.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary and special tokens file to a directory.

PARAMETER DESCRIPTION
save_directory

The directory in which to save the vocabulary.

TYPE: `str`

RETURNS DESCRIPTION
Tuple[str]

Tuple(str): Paths to the files saved.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma.py
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
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary and special tokens file to a directory.

    Args:
        save_directory (`str`):
            The directory in which to save the vocabulary.

    Returns:
        `Tuple(str)`: Paths to the files saved.
    """
    if not os.path.isdir(save_directory):
        logger.error(f"Vocabulary path ({save_directory}) should be a directory")
        return
    out_vocab_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
    )

    if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
        copyfile(self.vocab_file, out_vocab_file)
    elif not os.path.isfile(self.vocab_file):
        with open(out_vocab_file, "wb") as fi:
            content_spiece_model = self.sp_model.serialized_model_proto()
            fi.write(content_spiece_model)

    return (out_vocab_file,)

mindnlp.transformers.models.gemma.tokenization_gemma_fast

Gemma Tokenizer

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast

Bases: PreTrainedTokenizerFast

Construct a Gemma tokenizer fast. Based on byte-level Byte-Pair-Encoding.

This uses notably ByteFallback and no prefix space. Normalization is applied to replace " " with "▁"

Example
>>> from transformers import GemmaTokenizerFast
...
>>> tokenizer = GemmaTokenizerFast.from_pretrained("hf-internal-testing/dummy-gemma")
>>> tokenizer.encode("Hello this is a test")
[2, 4521, 736, 603, 476, 2121]

If you want to change the bos_token or the eos_token, make sure to specify them when initializing the model, or call tokenizer.update_post_processor() to make sure that the post-processing is correctly done (otherwise the values of the first token and final token of an encoded sequence will not be correct). For more details, checkout [post-processors] (https://hf-mirror.com/docs/tokenizers/api/post-processors) documentation.

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

SentencePiece file (generally has a .model extension) that contains the vocabulary necessary to instantiate a tokenizer.

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

tokenizer_file

tokenizers file (generally has a .json extension) that contains everything needed to load the tokenizer.

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

clean_up_tokenization_spaces

Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces.

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

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` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"` DEFAULT: '<unk>'

bos_token

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

TYPE: `str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"` DEFAULT: '<bos>'

eos_token

The end of sequence token.

TYPE: `str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"` DEFAULT: '<eos>'

pad_token

The padding token

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

add_bos_token

Whether or not to add an bos_token at the start of sequences.

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

add_eos_token

Whether or not to add an eos_token at the end of sequences.

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

Source code in mindnlp/transformers/models/gemma/tokenization_gemma_fast.py
 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
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
class GemmaTokenizerFast(PreTrainedTokenizerFast):
    """
    Construct a Gemma tokenizer fast. Based on byte-level Byte-Pair-Encoding.

    This uses notably ByteFallback and no prefix space. Normalization is applied to replace  `" "` with `"▁"`

    Example:
        ```python
        >>> from transformers import GemmaTokenizerFast
        ...
        >>> tokenizer = GemmaTokenizerFast.from_pretrained("hf-internal-testing/dummy-gemma")
        >>> tokenizer.encode("Hello this is a test")
        [2, 4521, 736, 603, 476, 2121]
        ```

    If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
    call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
    values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
    [post-processors] (https://hf-mirror.com/docs/tokenizers/api/post-processors) documentation.

    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`, *optional*):
            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        tokenizer_file (`str`, *optional*):
            [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
            contains everything needed to load the tokenizer.
        clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
            Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
            extra spaces.
        unk_token (`str` or `tokenizers.AddedToken`, *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.
        bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
        eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"`):
            The end of sequence token.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The padding token
        add_bos_token (`bool`, *optional*, defaults to `True`):
            Whether or not to add an `bos_token` at the start of sequences.
        add_eos_token (`bool`, *optional*, defaults to `False`):
            Whether or not to add an `eos_token` at the end of sequences.
    """
    vocab_files_names = VOCAB_FILES_NAMES
    slow_tokenizer_class = GemmaTokenizer
    padding_side = "left"
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file=None,
        tokenizer_file=None,
        clean_up_tokenization_spaces=False,
        unk_token="<unk>",
        bos_token="<bos>",
        eos_token="<eos>",
        pad_token="<pad>",
        add_bos_token=True,
        add_eos_token=False,
        **kwargs,
    ):
        """
        Initialize GemmaTokenizerFast object.

        Args:
            self (object): The GemmaTokenizerFast object itself.
            vocab_file (str, optional): Path to the vocabulary file. Default is None.
            tokenizer_file (str, optional): Path to the tokenizer file. Default is None.
            clean_up_tokenization_spaces (bool, optional): Whether to clean up tokenization spaces. Default is False.
            unk_token (str, optional): Unknown token to be used. Default is '<unk>'.
            bos_token (str, optional): Beginning of sentence token. Default is '<bos>'.
            eos_token (str, optional): End of sentence token. Default is '<eos>'.
            pad_token (str, optional): Padding token. Default is '<pad>'.
            add_bos_token (bool, optional): Whether to add the beginning of sentence token. Default is True.
            add_eos_token (bool, optional): Whether to add the end of sentence token. Default is False.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(
            vocab_file=vocab_file,
            tokenizer_file=tokenizer_file,
            clean_up_tokenization_spaces=clean_up_tokenization_spaces,
            unk_token=unk_token,
            bos_token=bos_token,
            eos_token=eos_token,
            pad_token=pad_token,
            add_bos_token=add_bos_token,
            add_eos_token=add_eos_token,
            **kwargs,
        )
        self._add_bos_token = add_bos_token
        self._add_eos_token = add_eos_token
        self.update_post_processor()
        self.vocab_file = vocab_file

    @property
    def can_save_slow_tokenizer(self) -> bool:
        """
        Checks if the slow tokenizer can be saved.

        Args:
            self: An instance of the GemmaTokenizerFast class.

        Returns:
            bool:
                A boolean value indicating whether the slow tokenizer can be saved.
                Returns True if the vocab_file exists, otherwise False.

        Raises:
            None.
        """
        return os.path.isfile(self.vocab_file) if self.vocab_file else False

    # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.update_post_processor
    def update_post_processor(self):
        """
        Updates the underlying post processor with the current `bos_token` and `eos_token`.
        """
        bos = self.bos_token
        bos_token_id = self.bos_token_id
        if bos is None and self.add_bos_token:
            raise ValueError("add_bos_token = True but bos_token = None")

        eos = self.eos_token
        eos_token_id = self.eos_token_id
        if eos is None and self.add_eos_token:
            raise ValueError("add_eos_token = True but eos_token = None")

        single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
        pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"

        special_tokens = []
        if self.add_bos_token:
            special_tokens.append((bos, bos_token_id))
        if self.add_eos_token:
            special_tokens.append((eos, eos_token_id))
        self._tokenizer.post_processor = processors.TemplateProcessing(
            single=single, pair=pair, special_tokens=special_tokens
        )

    @property
    def add_eos_token(self):
        """
        Adds an end-of-sentence (EOS) token to the GemmaTokenizerFast object.

        Args:
            self: An instance of the GemmaTokenizerFast class.

        Returns:
            None.

        Raises:
            None.

        This method adds an EOS token to the GemmaTokenizerFast object.
        The EOS token is used to mark the end of a sentence or text sequence.
        It is commonly used in natural language processing tasks such as language modeling and text generation.
        By adding an EOS token, the GemmaTokenizerFast object can handle text sequences more effectively,
        allowing for better analysis and processing.
        """
        return self._add_eos_token

    @property
    def add_bos_token(self):
        """
        This method adds the beginning of sentence (BOS) token to the tokenizer.

        Args:
            self (GemmaTokenizerFast): The instance of GemmaTokenizerFast class.

        Returns:
            None.

        Raises:
            None.
        """
        return self._add_bos_token

    @add_eos_token.setter
    def add_eos_token(self, value):
        """Sets the value of the add_eos_token property in the GemmaTokenizerFast class.

        Args:
            self (GemmaTokenizerFast): The instance of GemmaTokenizerFast.
            value (bool): The value to set for the add_eos_token property.
                It determines whether to add an end-of-sequence token to the tokenized output.

        Returns:
            None.

        Raises:
            None.
        """
        self._add_eos_token = value
        self.update_post_processor()

    @add_bos_token.setter
    def add_bos_token(self, value):
        """
        Method: add_bos_token

        Description:
        Setter method for adding a beginning of sentence (BOS) token to the GemmaTokenizerFast.

        Args:
            self: (GemmaTokenizerFast) The instance of GemmaTokenizerFast.
            value: (bool) A boolean value indicating whether to add the BOS token.
                True enables adding the BOS token, while False disables it.

        Returns:
            None.

        Raises:
            None.
        """
        self._add_bos_token = value
        self.update_post_processor()

    # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.save_vocabulary
    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary of the GemmaTokenizerFast instance to the specified directory with an optional filename prefix.

        Args:
            self (GemmaTokenizerFast): The instance of the GemmaTokenizerFast class.
            save_directory (str): The directory path where the vocabulary will be saved.
            filename_prefix (Optional[str], optional): An optional prefix to be added to the filename. Defaults to None.

        Returns:
            Tuple[str]: A tuple containing the path to the saved vocabulary file.

        Raises:
            ValueError:
                If the fast tokenizer does not have the necessary information to save the vocabulary for a slow
                tokenizer.
            OSError: If the save_directory provided is not a valid directory path.
            IOError: If an error occurs during the file copying process.
        """
        if not self.can_save_slow_tokenizer:
            raise ValueError(
                "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
                "tokenizer."
            )

        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        out_vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )

        if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
            copyfile(self.vocab_file, out_vocab_file)

        return (out_vocab_file,)

    # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.build_inputs_with_special_tokens
    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        """
        Build inputs with special tokens for the GemmaTokenizerFast.

        Args:
            self (GemmaTokenizerFast): An instance of the GemmaTokenizerFast class.
            token_ids_0 (list): A list of token IDs representing the first sequence.
            token_ids_1 (list, optional): A list of token IDs representing the second sequence.
                Defaults to None.

        Returns:
            list: A list of token IDs representing the input sequences with added special tokens.

        Raises:
            None.

        This method takes two sequences of token IDs and adds special tokens, such as
        beginning of sequence (bos) and end of sequence (eos) tokens. The special tokens
        are added based on the configuration of the tokenizer.

        The token_ids_0 parameter is a list of token IDs representing the first sequence.
        This parameter is required.

        The token_ids_1 parameter is an optional list of token IDs representing the second
        sequence. If provided, the method concatenates the first and second sequences with
        the special tokens in between.

        The method returns a list of token IDs representing the input sequences with the
        special tokens added.

        Example:
            ```python
            >>> tokenizer = GemmaTokenizerFast()
            >>> token_ids_0 = [101, 202, 303]
            >>> token_ids_1 = [404, 505]
            >>> inputs = tokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1)
            >>> print(inputs)
            Output:
            [101, 202, 303, 102, 404, 505, 102]
            ```
        """
        bos_token_id = [self.bos_token_id] if self.add_bos_token else []
        eos_token_id = [self.eos_token_id] if self.add_eos_token else []

        output = bos_token_id + token_ids_0 + eos_token_id

        if token_ids_1 is not None:
            output = output + bos_token_id + token_ids_1 + eos_token_id

        return output

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.add_bos_token property writable

This method adds the beginning of sentence (BOS) token to the tokenizer.

PARAMETER DESCRIPTION
self

The instance of GemmaTokenizerFast class.

TYPE: GemmaTokenizerFast

RETURNS DESCRIPTION

None.

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.add_eos_token property writable

Adds an end-of-sentence (EOS) token to the GemmaTokenizerFast object.

PARAMETER DESCRIPTION
self

An instance of the GemmaTokenizerFast class.

RETURNS DESCRIPTION

None.

This method adds an EOS token to the GemmaTokenizerFast object. The EOS token is used to mark the end of a sentence or text sequence. It is commonly used in natural language processing tasks such as language modeling and text generation. By adding an EOS token, the GemmaTokenizerFast object can handle text sequences more effectively, allowing for better analysis and processing.

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.can_save_slow_tokenizer: bool property

Checks if the slow tokenizer can be saved.

PARAMETER DESCRIPTION
self

An instance of the GemmaTokenizerFast class.

RETURNS DESCRIPTION
bool

A boolean value indicating whether the slow tokenizer can be saved. Returns True if the vocab_file exists, otherwise False.

TYPE: bool

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.__init__(vocab_file=None, tokenizer_file=None, clean_up_tokenization_spaces=False, unk_token='<unk>', bos_token='<bos>', eos_token='<eos>', pad_token='<pad>', add_bos_token=True, add_eos_token=False, **kwargs)

Initialize GemmaTokenizerFast object.

PARAMETER DESCRIPTION
self

The GemmaTokenizerFast object itself.

TYPE: object

vocab_file

Path to the vocabulary file. Default is None.

TYPE: str DEFAULT: None

tokenizer_file

Path to the tokenizer file. Default is None.

TYPE: str DEFAULT: None

clean_up_tokenization_spaces

Whether to clean up tokenization spaces. Default is False.

TYPE: bool DEFAULT: False

unk_token

Unknown token to be used. Default is ''.

TYPE: str DEFAULT: '<unk>'

bos_token

Beginning of sentence token. Default is ''.

TYPE: str DEFAULT: '<bos>'

eos_token

End of sentence token. Default is ''.

TYPE: str DEFAULT: '<eos>'

pad_token

Padding token. Default is ''.

TYPE: str DEFAULT: '<pad>'

add_bos_token

Whether to add the beginning of sentence token. Default is True.

TYPE: bool DEFAULT: True

add_eos_token

Whether to add the end of sentence token. Default is False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma_fast.py
 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
def __init__(
    self,
    vocab_file=None,
    tokenizer_file=None,
    clean_up_tokenization_spaces=False,
    unk_token="<unk>",
    bos_token="<bos>",
    eos_token="<eos>",
    pad_token="<pad>",
    add_bos_token=True,
    add_eos_token=False,
    **kwargs,
):
    """
    Initialize GemmaTokenizerFast object.

    Args:
        self (object): The GemmaTokenizerFast object itself.
        vocab_file (str, optional): Path to the vocabulary file. Default is None.
        tokenizer_file (str, optional): Path to the tokenizer file. Default is None.
        clean_up_tokenization_spaces (bool, optional): Whether to clean up tokenization spaces. Default is False.
        unk_token (str, optional): Unknown token to be used. Default is '<unk>'.
        bos_token (str, optional): Beginning of sentence token. Default is '<bos>'.
        eos_token (str, optional): End of sentence token. Default is '<eos>'.
        pad_token (str, optional): Padding token. Default is '<pad>'.
        add_bos_token (bool, optional): Whether to add the beginning of sentence token. Default is True.
        add_eos_token (bool, optional): Whether to add the end of sentence token. Default is False.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(
        vocab_file=vocab_file,
        tokenizer_file=tokenizer_file,
        clean_up_tokenization_spaces=clean_up_tokenization_spaces,
        unk_token=unk_token,
        bos_token=bos_token,
        eos_token=eos_token,
        pad_token=pad_token,
        add_bos_token=add_bos_token,
        add_eos_token=add_eos_token,
        **kwargs,
    )
    self._add_bos_token = add_bos_token
    self._add_eos_token = add_eos_token
    self.update_post_processor()
    self.vocab_file = vocab_file

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

Build inputs with special tokens for the GemmaTokenizerFast.

PARAMETER DESCRIPTION
self

An instance of the GemmaTokenizerFast class.

TYPE: GemmaTokenizerFast

token_ids_0

A list of token IDs representing the first sequence.

TYPE: list

token_ids_1

A list of token IDs representing the second sequence. Defaults to None.

TYPE: list DEFAULT: None

RETURNS DESCRIPTION
list

A list of token IDs representing the input sequences with added special tokens.

This method takes two sequences of token IDs and adds special tokens, such as beginning of sequence (bos) and end of sequence (eos) tokens. The special tokens are added based on the configuration of the tokenizer.

The token_ids_0 parameter is a list of token IDs representing the first sequence. This parameter is required.

The token_ids_1 parameter is an optional list of token IDs representing the second sequence. If provided, the method concatenates the first and second sequences with the special tokens in between.

The method returns a list of token IDs representing the input sequences with the special tokens added.

Example
>>> tokenizer = GemmaTokenizerFast()
>>> token_ids_0 = [101, 202, 303]
>>> token_ids_1 = [404, 505]
>>> inputs = tokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1)
>>> print(inputs)
Output:
[101, 202, 303, 102, 404, 505, 102]
Source code in mindnlp/transformers/models/gemma/tokenization_gemma_fast.py
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
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    """
    Build inputs with special tokens for the GemmaTokenizerFast.

    Args:
        self (GemmaTokenizerFast): An instance of the GemmaTokenizerFast class.
        token_ids_0 (list): A list of token IDs representing the first sequence.
        token_ids_1 (list, optional): A list of token IDs representing the second sequence.
            Defaults to None.

    Returns:
        list: A list of token IDs representing the input sequences with added special tokens.

    Raises:
        None.

    This method takes two sequences of token IDs and adds special tokens, such as
    beginning of sequence (bos) and end of sequence (eos) tokens. The special tokens
    are added based on the configuration of the tokenizer.

    The token_ids_0 parameter is a list of token IDs representing the first sequence.
    This parameter is required.

    The token_ids_1 parameter is an optional list of token IDs representing the second
    sequence. If provided, the method concatenates the first and second sequences with
    the special tokens in between.

    The method returns a list of token IDs representing the input sequences with the
    special tokens added.

    Example:
        ```python
        >>> tokenizer = GemmaTokenizerFast()
        >>> token_ids_0 = [101, 202, 303]
        >>> token_ids_1 = [404, 505]
        >>> inputs = tokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1)
        >>> print(inputs)
        Output:
        [101, 202, 303, 102, 404, 505, 102]
        ```
    """
    bos_token_id = [self.bos_token_id] if self.add_bos_token else []
    eos_token_id = [self.eos_token_id] if self.add_eos_token else []

    output = bos_token_id + token_ids_0 + eos_token_id

    if token_ids_1 is not None:
        output = output + bos_token_id + token_ids_1 + eos_token_id

    return output

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary of the GemmaTokenizerFast instance to the specified directory with an optional filename prefix.

PARAMETER DESCRIPTION
self

The instance of the GemmaTokenizerFast class.

TYPE: GemmaTokenizerFast

save_directory

The directory path where the vocabulary will be saved.

TYPE: str

filename_prefix

An optional prefix to be added to the filename. Defaults to None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the path to the saved vocabulary file.

RAISES DESCRIPTION
ValueError

If the fast tokenizer does not have the necessary information to save the vocabulary for a slow tokenizer.

OSError

If the save_directory provided is not a valid directory path.

IOError

If an error occurs during the file copying process.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma_fast.py
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
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary of the GemmaTokenizerFast instance to the specified directory with an optional filename prefix.

    Args:
        self (GemmaTokenizerFast): The instance of the GemmaTokenizerFast class.
        save_directory (str): The directory path where the vocabulary will be saved.
        filename_prefix (Optional[str], optional): An optional prefix to be added to the filename. Defaults to None.

    Returns:
        Tuple[str]: A tuple containing the path to the saved vocabulary file.

    Raises:
        ValueError:
            If the fast tokenizer does not have the necessary information to save the vocabulary for a slow
            tokenizer.
        OSError: If the save_directory provided is not a valid directory path.
        IOError: If an error occurs during the file copying process.
    """
    if not self.can_save_slow_tokenizer:
        raise ValueError(
            "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
            "tokenizer."
        )

    if not os.path.isdir(save_directory):
        logger.error(f"Vocabulary path ({save_directory}) should be a directory")
        return
    out_vocab_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
    )

    if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
        copyfile(self.vocab_file, out_vocab_file)

    return (out_vocab_file,)

mindnlp.transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast.update_post_processor()

Updates the underlying post processor with the current bos_token and eos_token.

Source code in mindnlp/transformers/models/gemma/tokenization_gemma_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
def update_post_processor(self):
    """
    Updates the underlying post processor with the current `bos_token` and `eos_token`.
    """
    bos = self.bos_token
    bos_token_id = self.bos_token_id
    if bos is None and self.add_bos_token:
        raise ValueError("add_bos_token = True but bos_token = None")

    eos = self.eos_token
    eos_token_id = self.eos_token_id
    if eos is None and self.add_eos_token:
        raise ValueError("add_eos_token = True but eos_token = None")

    single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
    pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"

    special_tokens = []
    if self.add_bos_token:
        special_tokens.append((bos, bos_token_id))
    if self.add_eos_token:
        special_tokens.append((eos, eos_token_id))
    self._tokenizer.post_processor = processors.TemplateProcessing(
        single=single, pair=pair, special_tokens=special_tokens
    )