Skip to content

jetmoe

mindnlp.transformers.models.jetmoe.configuration_jetmoe

JetMoE model configuration

mindnlp.transformers.models.jetmoe.configuration_jetmoe.JetMoEConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [JetMoEModel]. It is used to instantiate an JetMoE model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a configuration of the JetMoE-4B.

jetmoe/jetmoe-8b

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 JetMoE model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [JetMoEModel]

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

hidden_size

Dimension of the hidden representations.

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

num_hidden_layers

Defines the number of blocks.

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

num_attention_heads

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

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

num_key_value_heads

Number of attention heads for each key and value in the Transformer encoder.

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

kv_channels

Defines the number of channels for the key and value tensors.

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

ffn_hidden_size

Defines the hidden size of the feed-forward layer.

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

max_position_embeddings

The maximum sequence length that this model might ever be used with. JetMoE's sliding window attention allows sequence of up to 4096*32 tokens.

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

activation_function

Defines the activation function for MLP experts.

TYPE: `string`, *optional*, defaults to `"silu"` DEFAULT: 'silu'

glu

Whether to use Gated Linear Units in the MLP experts.

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

moe_num_experts

Defines the number of experts in the mixture of experts.

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

moe_top_k

Defines the number of experts to use for each token.

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

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

bos_token_id

The id of the "beginning-of-sequence" token.

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

eos_token_id

The id of the "end-of-sequence" token.

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

tie_word_embeddings

Whether the model's input and output word embeddings should be tied.

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

bias

Whether to use bias in the feed-forward and attention layer.

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

rms_norm_eps

The epsilon used by the rms normalization layers.

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

initializer_range

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

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

Example
>>> from transformers import JetMoEModel, JetMoEConfig
...
>>> # Initializing a JetMoE 4B style configuration
>>> configuration = JetMoEConfig()
...
>>> # Initializing a model from the JetMoE 4B style configuration
>>> model = JetMoEModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/jetmoe/configuration_jetmoe.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 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
class JetMoEConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`JetMoEModel`]. It is used to instantiate an
    JetMoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
    with the defaults will yield a configuration of the JetMoE-4B.

    [jetmoe/jetmoe-8b](https://huggingface.co/jetmoe/jetmoe-8b)

    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 32000):
            Vocabulary size of the JetMoE model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`JetMoEModel`]
        hidden_size (`int`, *optional*, defaults to 2048):
            Dimension of the hidden representations.
        num_hidden_layers (`int`, *optional*, defaults to 12): Defines the number of blocks.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer in the Transformer encoder.
        num_key_value_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each key and value in the Transformer encoder.
        kv_channels (`int`, *optional*, defaults to 128): Defines the number of channels for the key and value tensors.
        ffn_hidden_size (`int`, *optional*, defaults to 5632): Defines the hidden size of the feed-forward layer.
        max_position_embeddings (`int`, *optional*, defaults to 4096):
            The maximum sequence length that this model might ever be used with. JetMoE's sliding window attention
            allows sequence of up to 4096*32 tokens.
        activation_function (`string`, *optional*, defaults to `"silu"`): Defines the activation function for MLP experts.
        glu (`bool`, *optional*, defaults to `True`): Whether to use Gated Linear Units in the MLP experts.
        moe_num_experts (`int`, *optional*, defaults to 8): Defines the number of experts in the mixture of experts.
        moe_top_k (`int, *optional*, defaults to 2): Defines the number of experts to use for each token.
        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`.
        bos_token_id (`int`, *optional*, defaults to 1):
            The id of the "beginning-of-sequence" token.
        eos_token_id (`int`, *optional*, defaults to 2):
            The id of the "end-of-sequence" token.
        tie_word_embeddings (`bool`, *optional*, defaults to `True`):
            Whether the model's input and output word embeddings should be tied.
        bias (`bool`, *optional*, defaults to `True`): Whether to use bias in the feed-forward and attention layer.
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        rms_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the rms normalization layers.
        initializer_range (`float`, *optional*, defaults to 0.01):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

    Example:
        ```python
        >>> from transformers import JetMoEModel, JetMoEConfig
        ...
        >>> # Initializing a JetMoE 4B style configuration
        >>> configuration = JetMoEConfig()
        ...
        >>> # Initializing a model from the JetMoE 4B style configuration
        >>> model = JetMoEModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "jetmoe"
    keys_to_ignore_at_inference = ["past_key_values"]

    def __init__(
        self,
        vocab_size=32000,
        hidden_size=2048,
        num_hidden_layers=12,
        num_attention_heads=32,
        num_key_value_heads=16,
        kv_channels=128,
        ffn_hidden_size=5632,
        max_position_embeddings=4096,
        activation_function="silu",
        glu=True,
        moe_num_experts=8,
        moe_top_k=2,
        use_cache=True,
        bos_token_id=1,
        eos_token_id=2,
        tie_word_embeddings=True,
        bias=True,
        rope_theta=10000.0,
        rms_norm_eps=1e-6,
        initializer_range=0.01,
        **kwargs,
    ):
        """
        __init__

        Initializes a new instance of JetMoEConfig.

        Args:
            self: The instance of the class.
            vocab_size (int, optional): The size of the vocabulary. Defaults to 32000.
            hidden_size (int, optional): The size of the hidden layers. Defaults to 2048.
            num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
            num_attention_heads (int, optional): The number of attention heads. Defaults to 32.
            num_key_value_heads (int, optional): The number of key-value heads. Defaults to 16.
            kv_channels (int, optional): The number of channels for key and value computation. Defaults to 128.
            ffn_hidden_size (int, optional): The size of the feed-forward network hidden layers. Defaults to 5632.
            max_position_embeddings (int, optional): The maximum position for positional embeddings. Defaults to 4096.
            activation_function (str, optional): The activation function to be used. Defaults to 'silu'.
            glu (bool, optional): Whether to use Gated Linear Unit (GLU). Defaults to True.
            moe_num_experts (int, optional): The number of experts for Mixture of Experts (MoE). Defaults to 8.
            moe_top_k (int, optional): The top K experts to be used in MoE. Defaults to 2.
            use_cache (bool, optional): Whether to use cache for decoding. Defaults to True.
            bos_token_id (int, optional): The ID of the beginning of sequence token. Defaults to 1.
            eos_token_id (int, optional): The ID of the end of sequence token. Defaults to 2.
            tie_word_embeddings (bool, optional): Whether to tie word embeddings. Defaults to True.
            bias (bool, optional): Whether to use bias. Defaults to True.
            rope_theta (float, optional): The theta value for Relative Positional Embeddings (RoPE). Defaults to 10000.0.
            rms_norm_eps (float, optional): The epsilon value for RMSNorm. Defaults to 1e-06.
            initializer_range (float, optional): The range for weight initialization. Defaults to 0.01.

        Returns:
            None.

        Raises:
            None.
        """
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.num_key_value_heads = num_key_value_heads
        self.kv_channels = kv_channels
        self.ffn_hidden_size = ffn_hidden_size
        self.max_position_embeddings = max_position_embeddings
        self.activation_function = activation_function
        self.glu = glu
        self.moe_num_experts = moe_num_experts
        self.moe_top_k = moe_top_k
        self.use_cache = use_cache
        self.initializer_range = initializer_range

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        self.bias = bias
        self.rope_theta = rope_theta
        self.rms_norm_eps = rms_norm_eps

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

mindnlp.transformers.models.jetmoe.configuration_jetmoe.JetMoEConfig.__init__(vocab_size=32000, hidden_size=2048, num_hidden_layers=12, num_attention_heads=32, num_key_value_heads=16, kv_channels=128, ffn_hidden_size=5632, max_position_embeddings=4096, activation_function='silu', glu=True, moe_num_experts=8, moe_top_k=2, use_cache=True, bos_token_id=1, eos_token_id=2, tie_word_embeddings=True, bias=True, rope_theta=10000.0, rms_norm_eps=1e-06, initializer_range=0.01, **kwargs)

init

Initializes a new instance of JetMoEConfig.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_size

The size of the vocabulary. Defaults to 32000.

TYPE: int DEFAULT: 32000

hidden_size

The size of the hidden layers. Defaults to 2048.

TYPE: int DEFAULT: 2048

num_hidden_layers

The number of hidden layers. Defaults to 12.

TYPE: int DEFAULT: 12

num_attention_heads

The number of attention heads. Defaults to 32.

TYPE: int DEFAULT: 32

num_key_value_heads

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

TYPE: int DEFAULT: 16

kv_channels

The number of channels for key and value computation. Defaults to 128.

TYPE: int DEFAULT: 128

ffn_hidden_size

The size of the feed-forward network hidden layers. Defaults to 5632.

TYPE: int DEFAULT: 5632

max_position_embeddings

The maximum position for positional embeddings. Defaults to 4096.

TYPE: int DEFAULT: 4096

activation_function

The activation function to be used. Defaults to 'silu'.

TYPE: str DEFAULT: 'silu'

glu

Whether to use Gated Linear Unit (GLU). Defaults to True.

TYPE: bool DEFAULT: True

moe_num_experts

The number of experts for Mixture of Experts (MoE). Defaults to 8.

TYPE: int DEFAULT: 8

moe_top_k

The top K experts to be used in MoE. Defaults to 2.

TYPE: int DEFAULT: 2

use_cache

Whether to use cache for decoding. Defaults to True.

TYPE: bool DEFAULT: True

bos_token_id

The ID of the beginning of sequence token. Defaults to 1.

TYPE: int DEFAULT: 1

eos_token_id

The ID of the end 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

bias

Whether to use bias. Defaults to True.

TYPE: bool DEFAULT: True

rope_theta

The theta value for Relative Positional Embeddings (RoPE). Defaults to 10000.0.

TYPE: float DEFAULT: 10000.0

rms_norm_eps

The epsilon value for RMSNorm. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

initializer_range

The range for weight initialization. Defaults to 0.01.

TYPE: float DEFAULT: 0.01

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/jetmoe/configuration_jetmoe.py
 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
def __init__(
    self,
    vocab_size=32000,
    hidden_size=2048,
    num_hidden_layers=12,
    num_attention_heads=32,
    num_key_value_heads=16,
    kv_channels=128,
    ffn_hidden_size=5632,
    max_position_embeddings=4096,
    activation_function="silu",
    glu=True,
    moe_num_experts=8,
    moe_top_k=2,
    use_cache=True,
    bos_token_id=1,
    eos_token_id=2,
    tie_word_embeddings=True,
    bias=True,
    rope_theta=10000.0,
    rms_norm_eps=1e-6,
    initializer_range=0.01,
    **kwargs,
):
    """
    __init__

    Initializes a new instance of JetMoEConfig.

    Args:
        self: The instance of the class.
        vocab_size (int, optional): The size of the vocabulary. Defaults to 32000.
        hidden_size (int, optional): The size of the hidden layers. Defaults to 2048.
        num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
        num_attention_heads (int, optional): The number of attention heads. Defaults to 32.
        num_key_value_heads (int, optional): The number of key-value heads. Defaults to 16.
        kv_channels (int, optional): The number of channels for key and value computation. Defaults to 128.
        ffn_hidden_size (int, optional): The size of the feed-forward network hidden layers. Defaults to 5632.
        max_position_embeddings (int, optional): The maximum position for positional embeddings. Defaults to 4096.
        activation_function (str, optional): The activation function to be used. Defaults to 'silu'.
        glu (bool, optional): Whether to use Gated Linear Unit (GLU). Defaults to True.
        moe_num_experts (int, optional): The number of experts for Mixture of Experts (MoE). Defaults to 8.
        moe_top_k (int, optional): The top K experts to be used in MoE. Defaults to 2.
        use_cache (bool, optional): Whether to use cache for decoding. Defaults to True.
        bos_token_id (int, optional): The ID of the beginning of sequence token. Defaults to 1.
        eos_token_id (int, optional): The ID of the end of sequence token. Defaults to 2.
        tie_word_embeddings (bool, optional): Whether to tie word embeddings. Defaults to True.
        bias (bool, optional): Whether to use bias. Defaults to True.
        rope_theta (float, optional): The theta value for Relative Positional Embeddings (RoPE). Defaults to 10000.0.
        rms_norm_eps (float, optional): The epsilon value for RMSNorm. Defaults to 1e-06.
        initializer_range (float, optional): The range for weight initialization. Defaults to 0.01.

    Returns:
        None.

    Raises:
        None.
    """
    self.vocab_size = vocab_size
    self.hidden_size = hidden_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.num_key_value_heads = num_key_value_heads
    self.kv_channels = kv_channels
    self.ffn_hidden_size = ffn_hidden_size
    self.max_position_embeddings = max_position_embeddings
    self.activation_function = activation_function
    self.glu = glu
    self.moe_num_experts = moe_num_experts
    self.moe_top_k = moe_top_k
    self.use_cache = use_cache
    self.initializer_range = initializer_range

    self.bos_token_id = bos_token_id
    self.eos_token_id = eos_token_id

    self.bias = bias
    self.rope_theta = rope_theta
    self.rms_norm_eps = rms_norm_eps

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe

MindSpore JetMoE model.

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEAttention

Bases: Module

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

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
class JetMoEAttention(nn.Module):
    """
    Multi-headed attention from 'Attention Is All You Need' paper.
    """
    def __init__(self, config: JetMoEConfig, layer_idx: Optional[int] = None):
        """
        Initialize the JetMoEAttention module.

        Args:
            config: Configuration object with model hyperparameters.
        """
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.is_causal = True
        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.top_k = config.moe_top_k

        self.kv_projection_size = config.kv_channels * config.num_key_value_heads
        self.num_key_value_heads = config.num_key_value_heads
        self.num_heads = config.num_attention_heads
        assert self.num_heads == self.num_key_value_heads * config.moe_top_k
        self.hidden_size_per_attention_head = config.kv_channels

        self.experts = MoE(
            input_size=config.hidden_size,
            hidden_size=self.kv_projection_size,
            num_experts=config.moe_num_experts,
            top_k=config.moe_top_k,
            glu=False,
        )

        self.kv_proj = nn.Linear(config.hidden_size, self.kv_projection_size * 2, bias=False)

        self.rotary_emb = JetMoERotaryEmbedding(
            config.kv_channels,
            max_position_embeddings=config.max_position_embeddings,
            base=config.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,
        **kwargs,
    ) -> Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
        """
        Constructs the JetMoEAttention.

        Args:
            self (JetMoEAttention): The object itself.
            hidden_states (mindspore.Tensor): The input hidden states with shape
                (batch_size, sequence_length, hidden_size).
            attention_mask (Optional[mindspore.Tensor], optional): The attention mask tensor with shape
                (batch_size, 1, sequence_length, key_value_sequence_length). Defaults to None.
            position_ids (Optional[mindspore.Tensor], optional): The position ids tensor with shape
                (batch_size, sequence_length). Defaults to None.
            past_key_value (Optional[Cache], optional): The past key-value cache. Defaults to None.
            output_attentions (bool, optional): Whether to return the attention weights. Defaults to False.
            use_cache (bool, optional): Whether to use cache for the key-value pairs. Defaults to False.

        Returns:
            Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
                A tuple containing the attention output tensor with shape (batch_size, sequence_length, hidden_size),
                the attention weights tensor (if output_attentions is True), and the updated past key-value cache.

        Raises:
            ValueError: If the attention weights or mask have invalid shapes.
            ValueError: If the cache structure has changed and the layer index is not initialized for auto-regressive decoding.
        """
        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.`"
            )
        bsz, q_len, _ = hidden_states.shape

        query_states, aux_loss = self.experts.map(hidden_states)
        key_states, value_states = self.kv_proj(hidden_states).chunk(2, axis=-1)

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

        kv_seq_len = key_states.shape[2]
        if past_key_value is not None:
            if self.layer_idx is None:
                raise ValueError(
                    f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
                    "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
                    "with a layer index."
                )
            kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
        cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
        query_states, key_states = apply_rotary_pos_emb(
            query_states, key_states, cos, sin, position_ids, unsqueeze_dim=1
        )

        if past_key_value is not None:
            cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
            key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

        # repeat k/v heads if n_kv_heads < n_heads
        key_states = key_states.repeat(1, self.top_k, 1, 1)
        value_states = value_states.repeat(1, self.top_k, 1, 1)

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

        if attn_weights.shape != (bsz, self.num_heads, q_len, kv_seq_len):
            raise ValueError(
                f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
                f" {attn_weights.shape}"
            )

        if attention_mask is not None:
            if attention_mask.shape != (bsz, 1, q_len, kv_seq_len):
                raise ValueError(
                    f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.shape}"
                )

            attn_weights = attn_weights + attention_mask

        # upcast attention to fp32
        attn_weights = ops.softmax(attn_weights, axis=-1, dtype=mindspore.float32).to(query_states.dtype)

        attn_output = ops.matmul(attn_weights, value_states)

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

        attn_output = attn_output.swapaxes(1, 2)
        attn_output = attn_output.reshape(bsz, q_len, self.top_k, self.kv_projection_size)

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

        if not output_attentions:
            attn_weights = None

        return attn_output, attn_weights, past_key_value, aux_loss

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEAttention.__init__(config, layer_idx=None)

Initialize the JetMoEAttention module.

PARAMETER DESCRIPTION
config

Configuration object with model hyperparameters.

TYPE: JetMoEConfig

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
def __init__(self, config: JetMoEConfig, layer_idx: Optional[int] = None):
    """
    Initialize the JetMoEAttention module.

    Args:
        config: Configuration object with model hyperparameters.
    """
    super().__init__()
    self.config = config
    self.layer_idx = layer_idx
    self.is_causal = True
    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.top_k = config.moe_top_k

    self.kv_projection_size = config.kv_channels * config.num_key_value_heads
    self.num_key_value_heads = config.num_key_value_heads
    self.num_heads = config.num_attention_heads
    assert self.num_heads == self.num_key_value_heads * config.moe_top_k
    self.hidden_size_per_attention_head = config.kv_channels

    self.experts = MoE(
        input_size=config.hidden_size,
        hidden_size=self.kv_projection_size,
        num_experts=config.moe_num_experts,
        top_k=config.moe_top_k,
        glu=False,
    )

    self.kv_proj = nn.Linear(config.hidden_size, self.kv_projection_size * 2, bias=False)

    self.rotary_emb = JetMoERotaryEmbedding(
        config.kv_channels,
        max_position_embeddings=config.max_position_embeddings,
        base=config.rope_theta,
    )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEAttention.forward(hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False, **kwargs)

Constructs the JetMoEAttention.

PARAMETER DESCRIPTION
self

The object itself.

TYPE: JetMoEAttention

hidden_states

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

TYPE: Tensor

attention_mask

The attention mask tensor with shape (batch_size, 1, sequence_length, key_value_sequence_length). Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The position ids tensor with shape (batch_size, sequence_length). Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

past_key_value

The past key-value cache. Defaults to None.

TYPE: Optional[Cache] DEFAULT: None

output_attentions

Whether to return the attention weights. Defaults to False.

TYPE: bool DEFAULT: False

use_cache

Whether to use cache for the key-value pairs. Defaults to False.

TYPE: bool DEFAULT: False

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 with shape (batch_size, sequence_length, hidden_size), the attention weights tensor (if output_attentions is True), and the updated past key-value cache.

RAISES DESCRIPTION
ValueError

If the attention weights or mask have invalid shapes.

ValueError

If the cache structure has changed and the layer index is not initialized for auto-regressive decoding.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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,
    **kwargs,
) -> Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
    """
    Constructs the JetMoEAttention.

    Args:
        self (JetMoEAttention): The object itself.
        hidden_states (mindspore.Tensor): The input hidden states with shape
            (batch_size, sequence_length, hidden_size).
        attention_mask (Optional[mindspore.Tensor], optional): The attention mask tensor with shape
            (batch_size, 1, sequence_length, key_value_sequence_length). Defaults to None.
        position_ids (Optional[mindspore.Tensor], optional): The position ids tensor with shape
            (batch_size, sequence_length). Defaults to None.
        past_key_value (Optional[Cache], optional): The past key-value cache. Defaults to None.
        output_attentions (bool, optional): Whether to return the attention weights. Defaults to False.
        use_cache (bool, optional): Whether to use cache for the key-value pairs. Defaults to False.

    Returns:
        Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
            A tuple containing the attention output tensor with shape (batch_size, sequence_length, hidden_size),
            the attention weights tensor (if output_attentions is True), and the updated past key-value cache.

    Raises:
        ValueError: If the attention weights or mask have invalid shapes.
        ValueError: If the cache structure has changed and the layer index is not initialized for auto-regressive decoding.
    """
    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.`"
        )
    bsz, q_len, _ = hidden_states.shape

    query_states, aux_loss = self.experts.map(hidden_states)
    key_states, value_states = self.kv_proj(hidden_states).chunk(2, axis=-1)

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

    kv_seq_len = key_states.shape[2]
    if past_key_value is not None:
        if self.layer_idx is None:
            raise ValueError(
                f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
                "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
                "with a layer index."
            )
        kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
    cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
    query_states, key_states = apply_rotary_pos_emb(
        query_states, key_states, cos, sin, position_ids, unsqueeze_dim=1
    )

    if past_key_value is not None:
        cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

    # repeat k/v heads if n_kv_heads < n_heads
    key_states = key_states.repeat(1, self.top_k, 1, 1)
    value_states = value_states.repeat(1, self.top_k, 1, 1)

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

    if attn_weights.shape != (bsz, self.num_heads, q_len, kv_seq_len):
        raise ValueError(
            f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
            f" {attn_weights.shape}"
        )

    if attention_mask is not None:
        if attention_mask.shape != (bsz, 1, q_len, kv_seq_len):
            raise ValueError(
                f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.shape}"
            )

        attn_weights = attn_weights + attention_mask

    # upcast attention to fp32
    attn_weights = ops.softmax(attn_weights, axis=-1, dtype=mindspore.float32).to(query_states.dtype)

    attn_output = ops.matmul(attn_weights, value_states)

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

    attn_output = attn_output.swapaxes(1, 2)
    attn_output = attn_output.reshape(bsz, q_len, self.top_k, self.kv_projection_size)

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

    if not output_attentions:
        attn_weights = None

    return attn_output, attn_weights, past_key_value, aux_loss

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEBaseModelOutputWithPast dataclass

Bases: BaseModelOutputWithPast

Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).

PARAMETER DESCRIPTION
last_hidden_state

Sequence of hidden-states at the output of the last layer of the model.

If past_key_values is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output.

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

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
@dataclass
class JetMoEBaseModelOutputWithPast(BaseModelOutputWithPast):
    """
    Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).

    Args:
        last_hidden_state (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.

            If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
            hidden_size)` is output.
        past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True`
            is passed or when `config.use_cache=True`):
            Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
            `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
            input) to speed up sequential decoding.
        hidden_states (`tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed
            or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed
            or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    """
    last_hidden_state: mindspore.Tensor = None
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor]]] = None
    hidden_states: Optional[Tuple[mindspore.Tensor]] = None
    attentions: Optional[Tuple[mindspore.Tensor]] = None
    aux_loss: Optional[mindspore.Tensor] = None

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEBlock

Bases: Module

The 'JetMoEBlock' class represents a module that implements a JetMoE block for a neural network model. This block consists of components such as self-attention mechanism, layer normalization, and a multi-layer perceptron (MLP) with Mixture of Experts (MoE) architecture. The block is designed to be used within a larger neural network model for various natural language processing tasks.

The class provides methods for initialization and forward pass computation. During initialization, it sets up the necessary components including input layer normalization, self-attention mechanism, post-attention layer normalization, and the MLP with MoE architecture based on the provided configuration.

The 'forward' method performs the forward pass computation of the JetMoEBlock module. It takes input hidden states, optional position IDs, past key-value states, attention mask, and other optional arguments. The method computes the self-attention output, updates the hidden states, applies the MLP operation, and returns the final outputs. Optional outputs such as attention weights and cached states can also be returned based on the method arguments.

Overall, the 'JetMoEBlock' class encapsulates the functionality of a JetMoE block within a neural network model, providing the necessary components for attention-based computations and expert-based transformations.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
class JetMoEBlock(nn.Module):

    """
    The 'JetMoEBlock' class represents a module that implements a JetMoE block for a neural network model.
    This block consists of components such as self-attention mechanism, layer normalization,
    and a multi-layer perceptron (MLP) with Mixture of Experts (MoE) architecture.
    The block is designed to be used within a larger neural network model for various natural language processing tasks.

    The class provides methods for initialization and forward pass computation.
    During initialization, it sets up the necessary components including input layer normalization,
    self-attention mechanism, post-attention layer normalization, and the MLP with MoE architecture based on the
    provided configuration.

    The 'forward' method performs the forward pass computation of the JetMoEBlock module.
    It takes input hidden states, optional position IDs, past key-value states, attention mask,
    and other optional arguments.
    The method computes the self-attention output, updates the hidden states, applies the MLP operation,
    and returns the final outputs.
    Optional outputs such as attention weights and cached states can also be returned based on the method arguments.

    Overall, the 'JetMoEBlock' class encapsulates the functionality of a JetMoE block within a neural network model,
    providing the necessary components for attention-based computations and expert-based transformations.
    """
    def __init__(self, config: JetMoEConfig, layer_idx: Optional[int] = None):
        """
        Initialize the JetMoEBlock module.

        Args:
            config: Configuration object with model hyperparameters.
        """
        super().__init__()
        self.input_layernorm = JetMoERMSNorm(config.hidden_size)
        self.self_attention = JETMOE_ATTENTION_CLASSES["eager"](config, layer_idx)
        self.post_attention_layernorm = JetMoERMSNorm(config.hidden_size)

        self.mlp = MoE(
            input_size=config.hidden_size,
            hidden_size=config.ffn_hidden_size,
            num_experts=config.moe_num_experts,
            activation=ACT2FN[config.activation_function],
            top_k=config.moe_top_k,
            bias=config.bias,
            glu=config.glu,
        )

    def forward(
        self,
        hidden_states: Optional[mindspore.Tensor],
        position_ids: Optional[mindspore.Tensor] = None,
        past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = False,
        use_cache: Optional[bool] = False,
        **kwargs,
    ) -> Union[Tuple[mindspore.Tensor], Optional[Tuple[mindspore.Tensor, Tuple[mindspore.Tensor, ...]]]]:
        """
        Forward pass of the JetMoEBlock module.

        Args:
            hidden_states (Optional[mindspore.Tensor]): Input hidden states.
            layer_past (Optional[Tuple[mindspore.Tensor]]): Past layer state.
            attention_mask (Optional[mindspore.Tensor]): Attention mask.
            head_mask (Optional[mindspore.Tensor]): Head mask.
            use_cache (Optional[bool]): Whether to use cached states.
            output_attentions (Optional[bool]): Whether to output attention weights.

        Returns:
            Union[Tuple[mindspore.Tensor], Optional[Tuple[mindspore.Tensor, Tuple[mindspore.Tensor, ...]]]]:
                Tuple containing outputs or optional attention weights.
        """
        # Self Attention
        attn_output, self_attn_weights, present_key_value, att_aux_loss = self.self_attention(
            hidden_states=self.input_layernorm(hidden_states),
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_value=past_key_value,
            output_attentions=output_attentions,
            use_cache=use_cache,
        )

        hidden_states = hidden_states + attn_output
        x_mlp, mlp_aux_loss = self.mlp(self.post_attention_layernorm(hidden_states))
        hidden_states = hidden_states + x_mlp

        outputs = (hidden_states,)

        if output_attentions:
            outputs += (self_attn_weights,)

        if use_cache:
            outputs += (present_key_value,)

        outputs += (att_aux_loss + mlp_aux_loss,)

        return outputs

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEBlock.__init__(config, layer_idx=None)

Initialize the JetMoEBlock module.

PARAMETER DESCRIPTION
config

Configuration object with model hyperparameters.

TYPE: JetMoEConfig

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def __init__(self, config: JetMoEConfig, layer_idx: Optional[int] = None):
    """
    Initialize the JetMoEBlock module.

    Args:
        config: Configuration object with model hyperparameters.
    """
    super().__init__()
    self.input_layernorm = JetMoERMSNorm(config.hidden_size)
    self.self_attention = JETMOE_ATTENTION_CLASSES["eager"](config, layer_idx)
    self.post_attention_layernorm = JetMoERMSNorm(config.hidden_size)

    self.mlp = MoE(
        input_size=config.hidden_size,
        hidden_size=config.ffn_hidden_size,
        num_experts=config.moe_num_experts,
        activation=ACT2FN[config.activation_function],
        top_k=config.moe_top_k,
        bias=config.bias,
        glu=config.glu,
    )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEBlock.forward(hidden_states, position_ids=None, past_key_value=None, attention_mask=None, output_attentions=False, use_cache=False, **kwargs)

Forward pass of the JetMoEBlock module.

PARAMETER DESCRIPTION
hidden_states

Input hidden states.

TYPE: Optional[Tensor]

layer_past

Past layer state.

TYPE: Optional[Tuple[Tensor]]

attention_mask

Attention mask.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

Head mask.

TYPE: Optional[Tensor]

use_cache

Whether to use cached states.

TYPE: Optional[bool] DEFAULT: False

output_attentions

Whether to output attention weights.

TYPE: Optional[bool] DEFAULT: False

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

Union[Tuple[mindspore.Tensor], Optional[Tuple[mindspore.Tensor, Tuple[mindspore.Tensor, ...]]]]: Tuple containing outputs or optional attention weights.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def forward(
    self,
    hidden_states: Optional[mindspore.Tensor],
    position_ids: Optional[mindspore.Tensor] = None,
    past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = False,
    use_cache: Optional[bool] = False,
    **kwargs,
) -> Union[Tuple[mindspore.Tensor], Optional[Tuple[mindspore.Tensor, Tuple[mindspore.Tensor, ...]]]]:
    """
    Forward pass of the JetMoEBlock module.

    Args:
        hidden_states (Optional[mindspore.Tensor]): Input hidden states.
        layer_past (Optional[Tuple[mindspore.Tensor]]): Past layer state.
        attention_mask (Optional[mindspore.Tensor]): Attention mask.
        head_mask (Optional[mindspore.Tensor]): Head mask.
        use_cache (Optional[bool]): Whether to use cached states.
        output_attentions (Optional[bool]): Whether to output attention weights.

    Returns:
        Union[Tuple[mindspore.Tensor], Optional[Tuple[mindspore.Tensor, Tuple[mindspore.Tensor, ...]]]]:
            Tuple containing outputs or optional attention weights.
    """
    # Self Attention
    attn_output, self_attn_weights, present_key_value, att_aux_loss = self.self_attention(
        hidden_states=self.input_layernorm(hidden_states),
        attention_mask=attention_mask,
        position_ids=position_ids,
        past_key_value=past_key_value,
        output_attentions=output_attentions,
        use_cache=use_cache,
    )

    hidden_states = hidden_states + attn_output
    x_mlp, mlp_aux_loss = self.mlp(self.post_attention_layernorm(hidden_states))
    hidden_states = hidden_states + x_mlp

    outputs = (hidden_states,)

    if output_attentions:
        outputs += (self_attn_weights,)

    if use_cache:
        outputs += (present_key_value,)

    outputs += (att_aux_loss + mlp_aux_loss,)

    return outputs

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoECausalLMOutputWithPast dataclass

Bases: CausalLMOutputWithPast

Base class for causal language model (or autoregressive) outputs.

PARAMETER DESCRIPTION
loss

Language modeling loss (for next-token prediction).

TYPE: `mindspore.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided DEFAULT: None

logits

Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

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

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
 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
@dataclass
class JetMoECausalLMOutputWithPast(CausalLMOutputWithPast):
    """
    Base class for causal language model (or autoregressive) outputs.

    Args:
        loss (`mindspore.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`mindspore.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed
            or when `config.use_cache=True`):
            Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed
            or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed
            or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    """
    loss: Optional[mindspore.Tensor] = None
    logits: mindspore.Tensor = None
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor]]] = None
    hidden_states: Optional[Tuple[mindspore.Tensor]] = None
    attentions: Optional[Tuple[mindspore.Tensor]] = None
    aux_loss: Optional[mindspore.Tensor] = None

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM

Bases: JetMoEPreTrainedModel

The JetMoEForCausalLM class represents a JetMoE model for causal language modeling. It inherits from the JetMoEPreTrainedModel.

This class includes methods for initializing the model, getting and setting input and output embeddings, setting and getting the decoder, forwarding the model, preparing inputs for generation, and reordering cache. The forward method handles the generation of outputs based on input and model configuration, while the prepare_inputs_for_generation method prepares inputs for the generation process. Additionally, the _reorder_cache method is a static method for reordering past key values based on beam index.

The class also includes attributes for model configuration, vocabulary size, auxiliary loss coefficient, LM head, and tie_word_embeddings.

The class provides flexibility for customizing and utilizing the JetMoE model for causal language modeling tasks.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
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
class JetMoEForCausalLM(JetMoEPreTrainedModel):

    '''
    The JetMoEForCausalLM class represents a JetMoE model for causal language modeling. 
    It inherits from the JetMoEPreTrainedModel.

    This class includes methods for initializing the model, getting and setting input and output embeddings, 
    setting and getting the decoder, forwarding the model, preparing inputs for generation, and reordering cache. 
    The forward method handles the generation of outputs based on input and model configuration, 
    while the prepare_inputs_for_generation method prepares inputs for the generation process.
    Additionally, the _reorder_cache method is a static method for reordering past key values based on beam index.

    The class also includes attributes for model configuration, vocabulary size, auxiliary loss coefficient, LM head, 
    and tie_word_embeddings.

    The class provides flexibility for customizing and utilizing the JetMoE model for causal language modeling tasks.
    '''
    _tied_weights_keys = ["lm_head.weight"]

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

        Args:
            self: Instance of the JetMoEForCausalLM class.
            config:
                An object containing configuration parameters for the model.

                - Type: Any
                - Purpose: Contains settings and hyperparameters for the model.
                - Restrictions: None

        Returns:
            None

        Raises:
            None.
        """
        super().__init__(config)
        self.model = JetMoEModel(config)
        self.vocab_size = config.vocab_size
        self.aux_loss_coef = getattr(config, "aux_loss_coef", 0.01)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
        self.tie_word_embeddings = config.tie_word_embeddings

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

    def get_input_embeddings(self):
        """
        Method to retrieve the input embeddings from the model.

        Args:
            self:
                The instance of the JetMoEForCausalLM class.

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

        Returns:
            embed_tokens:
                The input embeddings from the model.

                - Type: None
                - Purpose: Represents the embedding tokens used as input for the model.

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

    def set_input_embeddings(self, value):
        """
        This method sets the input embeddings for the JetMoEForCausalLM model.

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

        Returns:
            None.

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

    def get_output_embeddings(self):
        """
        Returns the output embeddings of the JetMoE model for causal language modeling.

        Args:
            self: An instance of the JetMoEForCausalLM class.

        Returns:
            The output embeddings of the JetMoE model for causal language modeling.

        Raises:
            None.

        Note:
            This method is a part of the JetMoEForCausalLM class and can be used to retrieve
            the output embeddings of the model.
            The output embeddings represent the contextualized representations of
            the input tokens generated by the model.
        """
        return self.lm_head

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

        Args:
            self (JetMoEForCausalLM): The instance of the JetMoEForCausalLM model.
            new_embeddings (Tensor): The new output embeddings to be set for the model.
                Should be a tensor of shape (vocab_size, hidden_size).

        Returns:
            None.

        Raises:
            TypeError: If the new_embeddings parameter is not a valid tensor.
            ValueError: If the new_embeddings tensor shape does not match the expected (vocab_size, hidden_size) shape.
        """
        self.lm_head = new_embeddings

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

        Args:
            self (JetMoEForCausalLM): An instance of the JetMoEForCausalLM class.
            decoder: The decoder to be set for the model.

        Returns:
            None.

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

    def get_decoder(self):
        """
        Method to retrieve the decoder model for the JetMoEForCausalLM class.

        Args:
            self: JetMoEForCausalLM instance.
                The instance of the JetMoEForCausalLM class.

        Returns:
            None:
                The decoder model associated with the JetMoEForCausalLM instance.

        Raises:
            None.
        """
        return self.model

    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, 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]
        """
        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,
        )

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

        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)
            # Ensure tensors are on the same device
            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

        if labels is not None and self.model.training:
            loss += self.aux_loss_coef * outputs.aux_loss

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

    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 (JetMoEForCausalLM): The instance of the JetMoEForCausalLM class.
            input_ids (torch.Tensor): The input tensor with token IDs.
            past_key_values (Union[Cache, Tuple[torch.Tensor]]):
                The past key values for caching.

                - If Cache instance is provided, information about cache length, past length,
                and max cache length are extracted.
                - If Tuple is provided, the past length is determined as the shape of the first
                dimension of the first element.
            attention_mask (torch.Tensor): The attention mask tensor to mask certain tokens.
            inputs_embeds (torch.Tensor): The embeddings tensor for input tokens.

        Returns:
            model_inputs (Dict[str, Any]): A dictionary containing model inputs for generation.
              It includes 'inputs_embeds' if inputs_embeds is provided, otherwise 'input_ids'.
              Additionally, 'position_ids', 'past_key_values', 'use_cache', and 'attention_mask' are included.

        Raises:
            TypeError: If past_key_values is not of type Cache or Tuple.
            IndexError: If attention_mask shape is inconsistent with input_ids shape.
            ValueError: If cache_length + input_ids length exceeds max_cache_length.
            AttributeError: If position_ids calculation encounters errors.
            RuntimeError: If there are issues with masked_fill operation.
        """
        # Omit tokens covered by past_key_values
        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 `inputs_embeds` are passed, we only want to use them in the 1st generation step
        if inputs_embeds is not None and past_key_values is None:
            model_inputs = {"inputs_embeds": inputs_embeds}
        else:
            model_inputs = {"input_ids": input_ids}

        model_inputs.update(
            {
                "position_ids": position_ids,
                "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 JetMoEForCausalLM model based on the specified beam index.

        Args:
            past_key_values (tuple): A tuple containing the past key values for the model's cache.
            beam_idx (int): The index of the beam to use for reordering the cache.
                It represents the position of the beam in the cache.

        Returns:
            None: This method modifies the cache 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.jetmoe.modeling_jetmoe.JetMoEForCausalLM.__init__(config)

Initializes an instance of JetMoEForCausalLM.

PARAMETER DESCRIPTION
self

Instance of the JetMoEForCausalLM class.

config

An object containing configuration parameters for the model.

  • Type: Any
  • Purpose: Contains settings and hyperparameters for the model.
  • Restrictions: None

RETURNS DESCRIPTION

None

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

    Args:
        self: Instance of the JetMoEForCausalLM class.
        config:
            An object containing configuration parameters for the model.

            - Type: Any
            - Purpose: Contains settings and hyperparameters for the model.
            - Restrictions: None

    Returns:
        None

    Raises:
        None.
    """
    super().__init__(config)
    self.model = JetMoEModel(config)
    self.vocab_size = config.vocab_size
    self.aux_loss_coef = getattr(config, "aux_loss_coef", 0.01)
    self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
    self.tie_word_embeddings = config.tie_word_embeddings

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.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 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]

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
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, 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]
    """
    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,
    )

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

    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)
        # Ensure tensors are on the same device
        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

    if labels is not None and self.model.training:
        loss += self.aux_loss_coef * outputs.aux_loss

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.get_decoder()

Method to retrieve the decoder model for the JetMoEForCausalLM class.

PARAMETER DESCRIPTION
self

JetMoEForCausalLM instance. The instance of the JetMoEForCausalLM class.

RETURNS DESCRIPTION
None

The decoder model associated with the JetMoEForCausalLM instance.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
def get_decoder(self):
    """
    Method to retrieve the decoder model for the JetMoEForCausalLM class.

    Args:
        self: JetMoEForCausalLM instance.
            The instance of the JetMoEForCausalLM class.

    Returns:
        None:
            The decoder model associated with the JetMoEForCausalLM instance.

    Raises:
        None.
    """
    return self.model

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.get_input_embeddings()

Method to retrieve the input embeddings from the model.

PARAMETER DESCRIPTION
self

The instance of the JetMoEForCausalLM class.

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

RETURNS DESCRIPTION
embed_tokens

The input embeddings from the model.

  • Type: None
  • Purpose: Represents the embedding tokens used as input for the model.
Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from the model.

    Args:
        self:
            The instance of the JetMoEForCausalLM class.

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

    Returns:
        embed_tokens:
            The input embeddings from the model.

            - Type: None
            - Purpose: Represents the embedding tokens used as input for the model.

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.get_output_embeddings()

Returns the output embeddings of the JetMoE model for causal language modeling.

PARAMETER DESCRIPTION
self

An instance of the JetMoEForCausalLM class.

RETURNS DESCRIPTION

The output embeddings of the JetMoE model for causal language modeling.

Note

This method is a part of the JetMoEForCausalLM class and can be used to retrieve the output embeddings of the model. The output embeddings represent the contextualized representations of the input tokens generated by the model.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
def get_output_embeddings(self):
    """
    Returns the output embeddings of the JetMoE model for causal language modeling.

    Args:
        self: An instance of the JetMoEForCausalLM class.

    Returns:
        The output embeddings of the JetMoE model for causal language modeling.

    Raises:
        None.

    Note:
        This method is a part of the JetMoEForCausalLM class and can be used to retrieve
        the output embeddings of the model.
        The output embeddings represent the contextualized representations of
        the input tokens generated by the model.
    """
    return self.lm_head

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.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 JetMoEForCausalLM class.

TYPE: JetMoEForCausalLM

input_ids

The input tensor with token IDs.

TYPE: Tensor

past_key_values

The past key values for caching.

  • If Cache instance is provided, information about cache length, past length, and max cache length are extracted.
  • If Tuple is provided, the past length is determined as the shape of the first dimension of the first element.

TYPE: Union[Cache, Tuple[Tensor]] DEFAULT: None

attention_mask

The attention mask tensor to mask certain tokens.

TYPE: Tensor DEFAULT: None

inputs_embeds

The embeddings tensor for input tokens.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
model_inputs

A dictionary containing model inputs for generation. It includes 'inputs_embeds' if inputs_embeds is provided, otherwise 'input_ids'. Additionally, 'position_ids', 'past_key_values', 'use_cache', and 'attention_mask' are included.

TYPE: Dict[str, Any]

RAISES DESCRIPTION
TypeError

If past_key_values is not of type Cache or Tuple.

IndexError

If attention_mask shape is inconsistent with input_ids shape.

ValueError

If cache_length + input_ids length exceeds max_cache_length.

AttributeError

If position_ids calculation encounters errors.

RuntimeError

If there are issues with masked_fill operation.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
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 (JetMoEForCausalLM): The instance of the JetMoEForCausalLM class.
        input_ids (torch.Tensor): The input tensor with token IDs.
        past_key_values (Union[Cache, Tuple[torch.Tensor]]):
            The past key values for caching.

            - If Cache instance is provided, information about cache length, past length,
            and max cache length are extracted.
            - If Tuple is provided, the past length is determined as the shape of the first
            dimension of the first element.
        attention_mask (torch.Tensor): The attention mask tensor to mask certain tokens.
        inputs_embeds (torch.Tensor): The embeddings tensor for input tokens.

    Returns:
        model_inputs (Dict[str, Any]): A dictionary containing model inputs for generation.
          It includes 'inputs_embeds' if inputs_embeds is provided, otherwise 'input_ids'.
          Additionally, 'position_ids', 'past_key_values', 'use_cache', and 'attention_mask' are included.

    Raises:
        TypeError: If past_key_values is not of type Cache or Tuple.
        IndexError: If attention_mask shape is inconsistent with input_ids shape.
        ValueError: If cache_length + input_ids length exceeds max_cache_length.
        AttributeError: If position_ids calculation encounters errors.
        RuntimeError: If there are issues with masked_fill operation.
    """
    # Omit tokens covered by past_key_values
    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 `inputs_embeds` are passed, we only want to use them in the 1st generation step
    if inputs_embeds is not None and past_key_values is None:
        model_inputs = {"inputs_embeds": inputs_embeds}
    else:
        model_inputs = {"input_ids": input_ids}

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.set_decoder(decoder)

Sets the decoder for the JetMoEForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the JetMoEForCausalLM class.

TYPE: JetMoEForCausalLM

decoder

The decoder to be set for the model.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def set_decoder(self, decoder):
    """
    Sets the decoder for the JetMoEForCausalLM model.

    Args:
        self (JetMoEForCausalLM): An instance of the JetMoEForCausalLM class.
        decoder: The decoder to be set for the model.

    Returns:
        None.

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.set_input_embeddings(value)

This method sets the input embeddings for the JetMoEForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the JetMoEForCausalLM class.

TYPE: JetMoEForCausalLM

value

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

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
def set_input_embeddings(self, value):
    """
    This method sets the input embeddings for the JetMoEForCausalLM model.

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

    Returns:
        None.

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForCausalLM.set_output_embeddings(new_embeddings)

Set the output embeddings for the JetMoEForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the JetMoEForCausalLM model.

TYPE: JetMoEForCausalLM

new_embeddings

The new output embeddings to be set for the model. Should be a tensor of shape (vocab_size, hidden_size).

TYPE: Tensor

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the new_embeddings parameter is not a valid tensor.

ValueError

If the new_embeddings tensor shape does not match the expected (vocab_size, hidden_size) shape.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
def set_output_embeddings(self, new_embeddings):
    """
    Set the output embeddings for the JetMoEForCausalLM model.

    Args:
        self (JetMoEForCausalLM): The instance of the JetMoEForCausalLM model.
        new_embeddings (Tensor): The new output embeddings to be set for the model.
            Should be a tensor of shape (vocab_size, hidden_size).

    Returns:
        None.

    Raises:
        TypeError: If the new_embeddings parameter is not a valid tensor.
        ValueError: If the new_embeddings tensor shape does not match the expected (vocab_size, hidden_size) shape.
    """
    self.lm_head = new_embeddings

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForSequenceClassification

Bases: JetMoEPreTrainedModel

JetMoEForSequenceClassification is a class that represents a sequence classification model based on the JetMoE architecture. It is designed to handle tasks such as sentiment analysis, text classification, and natural language inference.

This class inherits from the JetMoEPreTrainedModel class, which provides a set of pre-trained parameters and methods for fine-tuning the model on specific downstream tasks.

The JetMoEForSequenceClassification class provides the following methods:

  • init: Initializes the JetMoEForSequenceClassification instance with the given configuration.
  • get_input_embeddings: Returns the input embeddings used by the model.
  • set_input_embeddings: Sets the input embeddings of the model to the given value.
  • forward: Constructs the sequence classification model and computes the output logits. It takes several optional arguments such as input_ids, attention_mask, and labels, and returns a tuple containing the loss, logits, and other outputs.

The JetMoEForSequenceClassification class follows the configuration provided to initialize the model, including the number of labels for the classification task. It utilizes the JetMoEModel for the main transformer architecture and applies a score layer to compute the logits. The forward method handles the computation of the model's output based on the given inputs and labels, including handling different problem types (regression, single-label classification, or multi-label classification) and computing the loss.

Note

This docstring does not include the method signatures or any other code for clarity and readability.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
class JetMoEForSequenceClassification(JetMoEPreTrainedModel):

    """
    JetMoEForSequenceClassification is a class that represents a sequence classification model based on the JetMoE
    architecture. It is designed to handle tasks such as sentiment analysis, text classification,
    and natural language inference.

    This class inherits from the JetMoEPreTrainedModel class, which provides a set of pre-trained parameters
    and methods for fine-tuning the model on specific downstream tasks.

    The JetMoEForSequenceClassification class provides the following methods:

    - __init__: Initializes the JetMoEForSequenceClassification instance with the given configuration.
    - get_input_embeddings: Returns the input embeddings used by the model.
    - set_input_embeddings: Sets the input embeddings of the model to the given value.
    - forward: Constructs the sequence classification model and computes the output logits.
    It takes several optional arguments such as input_ids, attention_mask, and labels,
    and returns a tuple containing the loss, logits, and other outputs.

    The JetMoEForSequenceClassification class follows the configuration provided to initialize the model,
    including the number of labels for the classification task. It utilizes the JetMoEModel for the main
    transformer architecture and applies a score layer to compute the logits.
    The forward method handles the computation of the model's output based on the given inputs and labels,
    including handling different problem types (regression, single-label classification, or multi-label classification)
    and computing the loss.

    Note:
        This docstring does not include the method signatures or any other code for clarity and readability.
    """
    def __init__(self, config):
        """
        Initializes a JetMoEForSequenceClassification instance.

        Args:
            self: The object instance itself.
            config (object): An object containing configuration settings for the model.
                It should include the following attributes:

                - num_labels (int): The number of labels for classification.
                - hidden_size (int): The size of the hidden layers in the model.
                This parameter is used to configure the model and its components.

        Returns:
            None.

        Raises:
            NotImplementedError: If the method 'post_init()' is not implemented.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.model = JetMoEModel(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 JetMoEForSequenceClassification model.

        Args:
            self: An instance of the JetMoEForSequenceClassification class.

        Returns:
            None: This method returns the input embeddings which are of type 'None'.

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

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

        Args:
            self (JetMoEForSequenceClassification): The instance of the JetMoEForSequenceClassification class.
            value: The input embeddings to be set for the model.
                This should be an object that provides the embedding functionality.

        Returns:
            None.

        Raises:
            None.

        This method allows you to set the input embeddings for the JetMoEForSequenceClassification model.
        The input embeddings should be provided as an object that provides the embedding functionality.
        By setting the input embeddings, you can customize the way the model represents the input data.

        Note:
            The 'embed_tokens' attribute of the 'model' instance is updated with the provided 'value' to
            set the input embeddings.
        """
        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.jetmoe.modeling_jetmoe.JetMoEForSequenceClassification.__init__(config)

Initializes a JetMoEForSequenceClassification instance.

PARAMETER DESCRIPTION
self

The object instance itself.

config

An object containing configuration settings for the model. It should include the following attributes:

  • num_labels (int): The number of labels for classification.
  • hidden_size (int): The size of the hidden layers in the model. This parameter is used to configure the model and its components.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
NotImplementedError

If the method 'post_init()' is not implemented.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
def __init__(self, config):
    """
    Initializes a JetMoEForSequenceClassification instance.

    Args:
        self: The object instance itself.
        config (object): An object containing configuration settings for the model.
            It should include the following attributes:

            - num_labels (int): The number of labels for classification.
            - hidden_size (int): The size of the hidden layers in the model.
            This parameter is used to configure the model and its components.

    Returns:
        None.

    Raises:
        NotImplementedError: If the method 'post_init()' is not implemented.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.model = JetMoEModel(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.jetmoe.modeling_jetmoe.JetMoEForSequenceClassification.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/jetmoe/modeling_jetmoe.py
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
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.jetmoe.modeling_jetmoe.JetMoEForSequenceClassification.get_input_embeddings()

This method retrieves the input embeddings from the JetMoEForSequenceClassification model.

PARAMETER DESCRIPTION
self

An instance of the JetMoEForSequenceClassification class.

RETURNS DESCRIPTION
None

This method returns the input embeddings which are of type 'None'.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
def get_input_embeddings(self):
    """
    This method retrieves the input embeddings from the JetMoEForSequenceClassification model.

    Args:
        self: An instance of the JetMoEForSequenceClassification class.

    Returns:
        None: This method returns the input embeddings which are of type 'None'.

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEForSequenceClassification.set_input_embeddings(value)

Sets the input embeddings for the JetMoEForSequenceClassification model.

PARAMETER DESCRIPTION
self

The instance of the JetMoEForSequenceClassification class.

TYPE: JetMoEForSequenceClassification

value

The input embeddings to be set for the model. This should be an object that provides the embedding functionality.

RETURNS DESCRIPTION

None.

This method allows you to set the input embeddings for the JetMoEForSequenceClassification model. The input embeddings should be provided as an object that provides the embedding functionality. By setting the input embeddings, you can customize the way the model represents the input data.

Note

The 'embed_tokens' attribute of the 'model' instance is updated with the provided 'value' to set the input embeddings.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
def set_input_embeddings(self, value):
    """
    Sets the input embeddings for the JetMoEForSequenceClassification model.

    Args:
        self (JetMoEForSequenceClassification): The instance of the JetMoEForSequenceClassification class.
        value: The input embeddings to be set for the model.
            This should be an object that provides the embedding functionality.

    Returns:
        None.

    Raises:
        None.

    This method allows you to set the input embeddings for the JetMoEForSequenceClassification model.
    The input embeddings should be provided as an object that provides the embedding functionality.
    By setting the input embeddings, you can customize the way the model represents the input data.

    Note:
        The 'embed_tokens' attribute of the 'model' instance is updated with the provided 'value' to
        set the input embeddings.
    """
    self.model.embed_tokens = value

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEModel

Bases: JetMoEPreTrainedModel

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

PARAMETER DESCRIPTION
config

JetMoEConfig

TYPE: JetMoEConfig

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
class JetMoEModel(JetMoEPreTrainedModel):
    """
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JetMoEBlock`]

    Args:
        config: JetMoEConfig
    """
    def __init__(self, config: JetMoEConfig):
        """
        Initializes a new instance of the JetMoEModel class.

        Args:
            self: The object itself.
            config (JetMoEConfig):
                The configuration object that contains various settings for the model.

                - 'config' must be an instance of JetMoEConfig.
                - It specifies the configuration parameters for the model.

        Returns:
            None

        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([JetMoEBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
        self._attn_implementation = config._attn_implementation
        self.norm = JetMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)

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

    def get_input_embeddings(self):
        """
        Method to retrieve the input embeddings from the JetMoEModel.

        Args:
            self : JetMoEModel
                The instance of the JetMoEModel class.

        Returns:
            None
                Returns the input embeddings represented by embed_tokens.

        Raises:
            None
        """
        return self.embed_tokens

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

        Args:
            self (JetMoEModel): The instance of the JetMoEModel class.
            value (Any): The input embeddings to be set for the model.
                Should be a tensor or an object that can be assigned to self.embed_tokens.

        Returns:
            None: This method does not return any value.

        Raises:
            None
        """
        self.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,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, BaseModelOutputWithPast]:
        """
        This method forwards the JetMoEModel by processing input data and generating the model output.

        Args:
            self: The instance of the JetMoEModel class.
            input_ids (mindspore.Tensor): The input tensor containing token IDs. Default is None.
            attention_mask (Optional[mindspore.Tensor]): Optional tensor representing the attention mask.
                Default is None.
            position_ids (Optional[mindspore.Tensor]): Optional tensor containing position IDs. Default is None.
            past_key_values (Optional[List[mindspore.Tensor]]): Optional list of tensors representing past key values.
                Default is None.
            inputs_embeds (Optional[mindspore.Tensor]): Optional tensor containing input embeddings. Default is None.
            use_cache (Optional[bool]): Optional flag indicating whether to use cache. Default is None.
            output_attentions (Optional[bool]): Optional flag indicating whether to output attentions
                Default is None.
            output_hidden_states (Optional[bool]): Optional flag indicating whether to output hidden states.
                Default is None.
            return_dict (Optional[bool]): Optional flag indicating whether to return a dictionary. Default is None.

        Returns:
            Union[Tuple, BaseModelOutputWithPast]:
                The return value is a tuple or an instance of BaseModelOutputWithPast, which contains the model output.

        Raises:
            ValueError: Raised if both input_ids and inputs_embeds are specified, or if neither is specified,
                or if incompatible combinations are provided.
            Warning: Raised if `use_cache=True` is incompatible with gradient checkpointing.
            ValueError: Raised if attempting to perform batched generation with certain settings
                that may lead to unexpected behavior.
        """
        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

        # retrieve input_ids and inputs_embeds
        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
        elif input_ids is not None:
            batch_size, seq_length = input_ids.shape
        elif inputs_embeds is not None:
            batch_size, seq_length, _ = inputs_embeds.shape
        else:
            raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")

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

        past_key_values_length = 0

        if use_cache:
            use_legacy_cache = not isinstance(past_key_values, Cache)
            if use_legacy_cache:
                past_key_values = DynamicCache.from_legacy_cache(past_key_values)
            past_key_values_length = past_key_values.get_usable_length(seq_length)

        if position_ids is None:
            position_ids = ops.arange(
                past_key_values_length, seq_length + past_key_values_length, dtype=mindspore.int64
            )
            position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
        else:
            position_ids = position_ids.view(-1, seq_length).long()

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

        if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
            is_padding_right = attention_mask[:, -1].sum().item() != batch_size
            if is_padding_right:
                raise ValueError(
                    "You are attempting to perform batched generation with padding_side='right'"
                    " this may lead to unexpected behaviour for Flash Attention version of JetMoE. Make sure to "
                    " call `tokenizer.padding_side  = 'left'` before tokenizing the input. "
                )

        # 4d mask is passed through the layers
        attention_mask = _prepare_4d_causal_attention_mask(
            attention_mask,
            (batch_size, seq_length),
            inputs_embeds,
            past_key_values_length,
        )

        hidden_states = inputs_embeds

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

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

            # hidden_states: Optional[mindspore.Tensor],
            # position_ids: Optional[mindspore.Tensor] = None,
            # past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
            # attention_mask: Optional[mindspore.Tensor] = None,
            # output_attentions: Optional[bool] = False,
            # use_cache: Optional[bool] = False,

            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(
                    # decoder_layer.__call__,
                    decoder_layer,
                    hidden_states,
                    position_ids,
                    past_key_values,
                    attention_mask,
                    output_attentions,
                    use_cache,
                    use_reentrant=False,
                )
            else:
                layer_outputs = decoder_layer(
                    hidden_states,
                    attention_mask=attention_mask,
                    position_ids=position_ids,
                    past_key_value=past_key_values,
                    output_attentions=output_attentions,
                    use_cache=use_cache,
                )

            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],)

            aux_loss += 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 use_legacy_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 JetMoEBaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=next_cache,
            hidden_states=all_hidden_states,
            attentions=all_self_attns,
            aux_loss=aux_loss,
        )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEModel.__init__(config)

Initializes a new instance of the JetMoEModel class.

PARAMETER DESCRIPTION
self

The object itself.

config

The configuration object that contains various settings for the model.

  • 'config' must be an instance of JetMoEConfig.
  • It specifies the configuration parameters for the model.

TYPE: JetMoEConfig

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
def __init__(self, config: JetMoEConfig):
    """
    Initializes a new instance of the JetMoEModel class.

    Args:
        self: The object itself.
        config (JetMoEConfig):
            The configuration object that contains various settings for the model.

            - 'config' must be an instance of JetMoEConfig.
            - It specifies the configuration parameters for the model.

    Returns:
        None

    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([JetMoEBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
    self._attn_implementation = config._attn_implementation
    self.norm = JetMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)

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

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEModel.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)

This method forwards the JetMoEModel by processing input data and generating the model output.

PARAMETER DESCRIPTION
self

The instance of the JetMoEModel class.

input_ids

The input tensor containing token IDs. Default is None.

TYPE: Tensor DEFAULT: None

attention_mask

Optional tensor representing the attention mask. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

Optional tensor containing position IDs. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

past_key_values

Optional list of tensors representing past key values. Default is None.

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

inputs_embeds

Optional tensor containing input embeddings. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

use_cache

Optional flag indicating whether to use cache. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_attentions

Optional flag indicating whether to output attentions Default is None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Optional flag indicating whether to output hidden states. Default is None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Optional flag indicating whether to return a dictionary. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutputWithPast]

Union[Tuple, BaseModelOutputWithPast]: The return value is a tuple or an instance of BaseModelOutputWithPast, which contains the model output.

RAISES DESCRIPTION
ValueError

Raised if both input_ids and inputs_embeds are specified, or if neither is specified, or if incompatible combinations are provided.

Warning

Raised if use_cache=True is incompatible with gradient checkpointing.

ValueError

Raised if attempting to perform batched generation with certain settings that may lead to unexpected behavior.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
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,
) -> Union[Tuple, BaseModelOutputWithPast]:
    """
    This method forwards the JetMoEModel by processing input data and generating the model output.

    Args:
        self: The instance of the JetMoEModel class.
        input_ids (mindspore.Tensor): The input tensor containing token IDs. Default is None.
        attention_mask (Optional[mindspore.Tensor]): Optional tensor representing the attention mask.
            Default is None.
        position_ids (Optional[mindspore.Tensor]): Optional tensor containing position IDs. Default is None.
        past_key_values (Optional[List[mindspore.Tensor]]): Optional list of tensors representing past key values.
            Default is None.
        inputs_embeds (Optional[mindspore.Tensor]): Optional tensor containing input embeddings. Default is None.
        use_cache (Optional[bool]): Optional flag indicating whether to use cache. Default is None.
        output_attentions (Optional[bool]): Optional flag indicating whether to output attentions
            Default is None.
        output_hidden_states (Optional[bool]): Optional flag indicating whether to output hidden states.
            Default is None.
        return_dict (Optional[bool]): Optional flag indicating whether to return a dictionary. Default is None.

    Returns:
        Union[Tuple, BaseModelOutputWithPast]:
            The return value is a tuple or an instance of BaseModelOutputWithPast, which contains the model output.

    Raises:
        ValueError: Raised if both input_ids and inputs_embeds are specified, or if neither is specified,
            or if incompatible combinations are provided.
        Warning: Raised if `use_cache=True` is incompatible with gradient checkpointing.
        ValueError: Raised if attempting to perform batched generation with certain settings
            that may lead to unexpected behavior.
    """
    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

    # retrieve input_ids and inputs_embeds
    if input_ids is not None and inputs_embeds is not None:
        raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
    elif input_ids is not None:
        batch_size, seq_length = input_ids.shape
    elif inputs_embeds is not None:
        batch_size, seq_length, _ = inputs_embeds.shape
    else:
        raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")

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

    past_key_values_length = 0

    if use_cache:
        use_legacy_cache = not isinstance(past_key_values, Cache)
        if use_legacy_cache:
            past_key_values = DynamicCache.from_legacy_cache(past_key_values)
        past_key_values_length = past_key_values.get_usable_length(seq_length)

    if position_ids is None:
        position_ids = ops.arange(
            past_key_values_length, seq_length + past_key_values_length, dtype=mindspore.int64
        )
        position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
    else:
        position_ids = position_ids.view(-1, seq_length).long()

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

    if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
        is_padding_right = attention_mask[:, -1].sum().item() != batch_size
        if is_padding_right:
            raise ValueError(
                "You are attempting to perform batched generation with padding_side='right'"
                " this may lead to unexpected behaviour for Flash Attention version of JetMoE. Make sure to "
                " call `tokenizer.padding_side  = 'left'` before tokenizing the input. "
            )

    # 4d mask is passed through the layers
    attention_mask = _prepare_4d_causal_attention_mask(
        attention_mask,
        (batch_size, seq_length),
        inputs_embeds,
        past_key_values_length,
    )

    hidden_states = inputs_embeds

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

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

        # hidden_states: Optional[mindspore.Tensor],
        # position_ids: Optional[mindspore.Tensor] = None,
        # past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
        # attention_mask: Optional[mindspore.Tensor] = None,
        # output_attentions: Optional[bool] = False,
        # use_cache: Optional[bool] = False,

        if self.gradient_checkpointing and self.training:
            layer_outputs = self._gradient_checkpointing_func(
                # decoder_layer.__call__,
                decoder_layer,
                hidden_states,
                position_ids,
                past_key_values,
                attention_mask,
                output_attentions,
                use_cache,
                use_reentrant=False,
            )
        else:
            layer_outputs = decoder_layer(
                hidden_states,
                attention_mask=attention_mask,
                position_ids=position_ids,
                past_key_value=past_key_values,
                output_attentions=output_attentions,
                use_cache=use_cache,
            )

        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],)

        aux_loss += 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 use_legacy_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 JetMoEBaseModelOutputWithPast(
        last_hidden_state=hidden_states,
        past_key_values=next_cache,
        hidden_states=all_hidden_states,
        attentions=all_self_attns,
        aux_loss=aux_loss,
    )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEModel.get_input_embeddings()

Method to retrieve the input embeddings from the JetMoEModel.

PARAMETER DESCRIPTION
self

JetMoEModel The instance of the JetMoEModel class.

RETURNS DESCRIPTION

None Returns the input embeddings represented by embed_tokens.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from the JetMoEModel.

    Args:
        self : JetMoEModel
            The instance of the JetMoEModel class.

    Returns:
        None
            Returns the input embeddings represented by embed_tokens.

    Raises:
        None
    """
    return self.embed_tokens

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEModel.set_input_embeddings(value)

Set the input embeddings for the JetMoEModel.

PARAMETER DESCRIPTION
self

The instance of the JetMoEModel class.

TYPE: JetMoEModel

value

The input embeddings to be set for the model. Should be a tensor or an object that can be assigned to self.embed_tokens.

TYPE: Any

RETURNS DESCRIPTION
None

This method does not return any value.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the JetMoEModel.

    Args:
        self (JetMoEModel): The instance of the JetMoEModel class.
        value (Any): The input embeddings to be set for the model.
            Should be a tensor or an object that can be assigned to self.embed_tokens.

    Returns:
        None: This method does not return any value.

    Raises:
        None
    """
    self.embed_tokens = value

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEPreTrainedModel

Bases: PreTrainedModel

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

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
class JetMoEPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = JetMoEConfig
    base_model_prefix = "transformer"
    supports_gradient_checkpointing = False
    _no_split_modules = ["JetMoEBlock"]
    _skip_keys_device_placement = "past_key_values"
    _supports_cache_class = True

    def __init__(self, *inputs, **kwargs):
        """
        Initialize the JetMoEPreTrainedModel.

        Args:
            *inputs: Variable length input arguments.
            **kwargs: Keyword arguments.
        """
        super().__init__(*inputs, **kwargs)

        self.gradient_checkpointing = False

    def _init_weights(self, module):
        """Initialize the weights."""
        if isinstance(module, (nn.Linear,)):
            # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            module.weight.initialize(Normal(self.config.initializer_range))
            if module.bias is not None:
                module.bias.initialize('zeros')
        elif isinstance(module, nn.Embedding):
            module.weight.initialize(Normal(self.config.initializer_range))
            if module.padding_idx is not None:
                module.weight[module.padding_idx] = 0
        elif isinstance(module, nn.LayerNorm):
            module.bias.initialize('zeros')
            module.weight.initialize('ones')
        elif isinstance(module, ParallelExperts):
            module.weight.initialize(Normal(self.config.initializer_range))

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoEPreTrainedModel.__init__(*inputs, **kwargs)

Initialize the JetMoEPreTrainedModel.

PARAMETER DESCRIPTION
*inputs

Variable length input arguments.

DEFAULT: ()

**kwargs

Keyword arguments.

DEFAULT: {}

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
696
697
698
699
700
701
702
703
704
705
706
def __init__(self, *inputs, **kwargs):
    """
    Initialize the JetMoEPreTrainedModel.

    Args:
        *inputs: Variable length input arguments.
        **kwargs: Keyword arguments.
    """
    super().__init__(*inputs, **kwargs)

    self.gradient_checkpointing = False

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoERMSNorm

Bases: Module

The 'JetMoERMSNorm' class is a custom implementation of the root mean square normalization (RMSNorm) module, specifically designed for the JetMoE model. It inherits from the 'nn.Module' class, which is a base class for all neural network modules in MindSpore.

This class provides a trainable normalization layer that performs RMS normalization on the input hidden states. The normalization is applied along the last dimension of the input tensor, reducing the variance across that dimension.

The forwardor 'init' initializes the 'JetMoERMSNorm' module. It takes two parameters: 'hidden_size' specifies the size of the hidden states, and 'eps' (default value 1e-06) is the epsilon value used for numerical stability in the normalization calculation.

The 'forward' method is the main functionality of the 'JetMoERMSNorm' module. It performs the RMS normalization on the input 'hidden_states' tensor. The method first converts the input tensor to 'mindspore.float32' to ensure consistent data type for the calculations. It then computes the variance along the last dimension of the tensor using the 'pow' and 'mean' operations. Afterward, the input tensor is multiplied element-wise by the reciprocal square root of the variance plus epsilon, using the 'rsqrt' and 'ops' operations. Finally, the normalized tensor is multiplied element-wise by the weight tensor and converted back to the original input data type.

Note that the 'JetMoERMSNorm' module is intended to be used as a part of the JetMoE model and can be applied to the hidden states of the model's components.

Please refer to the MindSpore documentation for more information on the 'nn.Module' class and the 'mindspore.float32' data type.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
class JetMoERMSNorm(nn.Module):

    """
    The 'JetMoERMSNorm' class is a custom implementation of the root mean square normalization (RMSNorm) module,
    specifically designed for the JetMoE model. It inherits from the 'nn.Module' class, which is a base class for
    all neural network modules in MindSpore.

    This class provides a trainable normalization layer that performs RMS normalization on the input hidden states.
    The normalization is applied along the last dimension of the input tensor, reducing the variance across
    that dimension.

    The forwardor '__init__' initializes the 'JetMoERMSNorm' module.
    It takes two parameters: 'hidden_size' specifies the size of the hidden states, and 'eps' (default value 1e-06)
    is the epsilon value used for numerical stability in the normalization calculation.

    The 'forward' method is the main functionality of the 'JetMoERMSNorm' module. It performs the RMS normalization
    on the input 'hidden_states' tensor. The method first converts the input tensor to 'mindspore.float32' to ensure
    consistent data type for the calculations. It then computes the variance along the last dimension of the tensor
    using the 'pow' and 'mean' operations. Afterward, the input tensor is multiplied element-wise by the reciprocal
    square root of the variance plus epsilon, using the 'rsqrt' and 'ops' operations. Finally, the normalized tensor
    is multiplied element-wise by the weight tensor and converted back to the original input data type.

    Note that the 'JetMoERMSNorm' module is intended to be used as a part of the JetMoE model and can be applied to the
    hidden states of the model's components.

    Please refer to the MindSpore documentation for more information on the 'nn.Module' class and the 'mindspore.float32'
    data type.
    """
    def __init__(self, hidden_size, eps=1e-6):
        """
        JetMoERMSNorm module
        """
        super().__init__()
        self.weight = Parameter(initializer('ones', (hidden_size,)))
        self.variance_epsilon = eps

    def forward(self, hidden_states):
        """
        Constructs the JetMoERMSNorm.

        This method takes in a tensor of hidden states and performs normalization using the RMSNorm technique.
        The normalized tensor is then multiplied by a weight parameter.

        Args:
            self (JetMoERMSNorm): An instance of the JetMoERMSNorm class.
            hidden_states (Tensor): A tensor containing the hidden states.
                The dtype of the tensor should be compatible with the operations performed within the method.

        Returns:
            None: This method does not return any value.
                The normalization is performed in-place on the hidden_states tensor.

        Raises:
            None.
        """
        input_dtype = hidden_states.dtype
        hidden_states = hidden_states.to(mindspore.float32)
        variance = hidden_states.pow(2).mean(-1, keep_dims=True)
        hidden_states = hidden_states * ops.rsqrt(variance + self.variance_epsilon)
        return self.weight * hidden_states.to(input_dtype)

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoERMSNorm.__init__(hidden_size, eps=1e-06)

JetMoERMSNorm module

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
228
229
230
231
232
233
234
def __init__(self, hidden_size, eps=1e-6):
    """
    JetMoERMSNorm module
    """
    super().__init__()
    self.weight = Parameter(initializer('ones', (hidden_size,)))
    self.variance_epsilon = eps

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoERMSNorm.forward(hidden_states)

Constructs the JetMoERMSNorm.

This method takes in a tensor of hidden states and performs normalization using the RMSNorm technique. The normalized tensor is then multiplied by a weight parameter.

PARAMETER DESCRIPTION
self

An instance of the JetMoERMSNorm class.

TYPE: JetMoERMSNorm

hidden_states

A tensor containing the hidden states. The dtype of the tensor should be compatible with the operations performed within the method.

TYPE: Tensor

RETURNS DESCRIPTION
None

This method does not return any value. The normalization is performed in-place on the hidden_states tensor.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def forward(self, hidden_states):
    """
    Constructs the JetMoERMSNorm.

    This method takes in a tensor of hidden states and performs normalization using the RMSNorm technique.
    The normalized tensor is then multiplied by a weight parameter.

    Args:
        self (JetMoERMSNorm): An instance of the JetMoERMSNorm class.
        hidden_states (Tensor): A tensor containing the hidden states.
            The dtype of the tensor should be compatible with the operations performed within the method.

    Returns:
        None: This method does not return any value.
            The normalization is performed in-place on the hidden_states tensor.

    Raises:
        None.
    """
    input_dtype = hidden_states.dtype
    hidden_states = hidden_states.to(mindspore.float32)
    variance = hidden_states.pow(2).mean(-1, keep_dims=True)
    hidden_states = hidden_states * ops.rsqrt(variance + self.variance_epsilon)
    return self.weight * hidden_states.to(input_dtype)

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoERotaryEmbedding

Bases: Module

The JetMoERotaryEmbedding class represents a rotary position embedding module that can be used in neural network models. It inherits from the nn.Module class and provides functionality for generating rotary position embeddings based on the input sequence length.

ATTRIBUTE DESCRIPTION
dim

The dimension of the position embeddings.

TYPE: int

max_position_embeddings

The maximum position embeddings allowed.

TYPE: int

base

The base value used in the calculation of position embeddings.

TYPE: int

inv_freq

The inverse frequency values used in the calculation of position embeddings.

TYPE: Tensor

max_seq_len_cached

The maximum sequence length for which cosine and sine embeddings are cached.

TYPE: int

cos_cached

Cached cosine embeddings for the given sequence length.

TYPE: Tensor

sin_cached

Cached sine embeddings for the given sequence length.

TYPE: Tensor

METHOD DESCRIPTION
_set_cos_sin_cache

Sets the cosine and sine embeddings cache for a given sequence length and data type.

forward

Constructs the cosine and sine embeddings for the input sequence, updating the cache if necessary.

Note

This class is designed to be used as part of neural network models, particularly in scenarios where rotary position embeddings are required.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.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
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
class JetMoERotaryEmbedding(nn.Module):

    """
    The JetMoERotaryEmbedding class represents a rotary position embedding module that can be used in
    neural network models. It inherits from the nn.Module class and provides functionality for generating rotary
    position embeddings based on the input sequence length.

    Attributes:
        dim (int): The dimension of the position embeddings.
        max_position_embeddings (int): The maximum position embeddings allowed.
        base (int): The base value used in the calculation of position embeddings.
        inv_freq (Tensor): The inverse frequency values used in the calculation of position embeddings.
        max_seq_len_cached (int): The maximum sequence length for which cosine and sine embeddings are cached.
        cos_cached (Tensor): Cached cosine embeddings for the given sequence length.
        sin_cached (Tensor): Cached sine embeddings for the given sequence length.

    Methods:
        _set_cos_sin_cache: Sets the cosine and sine embeddings cache for a given sequence length and data type.
        forward: Constructs the cosine and sine embeddings for the input sequence, updating the cache if necessary.

    Note:
        This class is designed to be used as part of neural network models,
        particularly in scenarios where rotary position embeddings are required.
    """
    def __init__(self, dim, max_position_embeddings=2048, base=10000):
        """
        Initializes the JetMoERotaryEmbedding object with the specified parameters.

        Args:
            self: The object itself.
            dim (int): The dimensionality of the embeddings.
            max_position_embeddings (int, optional): The maximum number of position embeddings. Defaults to 2048.
            base (int, optional): The base value used in the calculation. Defaults to 10000.

        Returns:
            None.

        Raises:
            ValueError: If the dimensionality 'dim' is not a positive integer.
            ValueError: If 'max_position_embeddings' is not a positive integer.
            ValueError: If 'base' is not a positive integer.
            TypeError: If the data type of 'dim', 'max_position_embeddings', or 'base' is not an integer.
        """
        super().__init__()

        self.dim = dim
        self.max_position_embeddings = max_position_embeddings
        self.base = base
        inv_freq = 1.0 / (self.base ** (ops.arange(0, self.dim, 2, dtype=mindspore.int64).float() / self.dim))
        self.inv_freq = inv_freq

        # Build here to make `torch.jit.trace` work.
        self._set_cos_sin_cache(
            seq_len=max_position_embeddings, dtype=get_default_dtype()
        )

    def _set_cos_sin_cache(self, seq_len, dtype):
        """
        Sets the cosine and sine cache for the JetMoERotaryEmbedding class.

        Args:
            self (JetMoERotaryEmbedding): The instance of the JetMoERotaryEmbedding class.
            seq_len (int): The length of the sequence for which the cosine and sine cache is being set.
            dtype (dtype): The data type for the cache, e.g., float32, float64, etc.

        Returns:
            None.

        Raises:
            TypeError: If seq_len is not an integer or dtype is not a valid data type.
            ValueError: If seq_len is less than 1.
        """
        self.max_seq_len_cached = seq_len
        t = ops.arange(self.max_seq_len_cached, dtype=mindspore.int64).type_as(self.inv_freq)

        freqs = ops.outer(t, self.inv_freq)
        # Different from paper, but it uses a different permutation in order to obtain the same calculation
        emb = ops.cat((freqs, freqs), axis=-1)
        self.cos_cached = emb.cos().to(dtype)
        self.sin_cached = emb.sin().to(dtype)

    def forward(self, x, seq_len=None):
        """
        Construct the JetMoERotaryEmbedding.

        Args:
            self (JetMoERotaryEmbedding): The instance of the JetMoERotaryEmbedding class.
            x:
                The input tensor.

                - Type: Any
                - Purpose: The input tensor for which the cos and sin cached values need to be forwarded.

                It is expected to be a tensor.
            seq_len:
                The length of the sequence for which the cached values need to be forwarded.

                - Type: int
                - Purpose: Determines the length of the sequence for which the cos and sin cached values
                need to be forwarded.
                - Restrictions: Should be a positive integer.

        Returns:
            None.

        Raises:
            ValueError: If seq_len is not a positive integer.
        """
        # x: [bs, num_attention_heads, seq_len, head_size]
        if seq_len > self.max_seq_len_cached:
            self._set_cos_sin_cache(seq_len=seq_len, dtype=x.dtype)

        return (
            self.cos_cached[:seq_len].to(dtype=x.dtype),
            self.sin_cached[:seq_len].to(dtype=x.dtype),
        )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoERotaryEmbedding.__init__(dim, max_position_embeddings=2048, base=10000)

Initializes the JetMoERotaryEmbedding object with the specified parameters.

PARAMETER DESCRIPTION
self

The object itself.

dim

The dimensionality of the embeddings.

TYPE: int

max_position_embeddings

The maximum number of position embeddings. Defaults to 2048.

TYPE: int DEFAULT: 2048

base

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

TYPE: int DEFAULT: 10000

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the dimensionality 'dim' is not a positive integer.

ValueError

If 'max_position_embeddings' is not a positive integer.

ValueError

If 'base' is not a positive integer.

TypeError

If the data type of 'dim', 'max_position_embeddings', or 'base' is not an integer.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
def __init__(self, dim, max_position_embeddings=2048, base=10000):
    """
    Initializes the JetMoERotaryEmbedding object with the specified parameters.

    Args:
        self: The object itself.
        dim (int): The dimensionality of the embeddings.
        max_position_embeddings (int, optional): The maximum number of position embeddings. Defaults to 2048.
        base (int, optional): The base value used in the calculation. Defaults to 10000.

    Returns:
        None.

    Raises:
        ValueError: If the dimensionality 'dim' is not a positive integer.
        ValueError: If 'max_position_embeddings' is not a positive integer.
        ValueError: If 'base' is not a positive integer.
        TypeError: If the data type of 'dim', 'max_position_embeddings', or 'base' is not an integer.
    """
    super().__init__()

    self.dim = dim
    self.max_position_embeddings = max_position_embeddings
    self.base = base
    inv_freq = 1.0 / (self.base ** (ops.arange(0, self.dim, 2, dtype=mindspore.int64).float() / self.dim))
    self.inv_freq = inv_freq

    # Build here to make `torch.jit.trace` work.
    self._set_cos_sin_cache(
        seq_len=max_position_embeddings, dtype=get_default_dtype()
    )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoERotaryEmbedding.forward(x, seq_len=None)

Construct the JetMoERotaryEmbedding.

PARAMETER DESCRIPTION
self

The instance of the JetMoERotaryEmbedding class.

TYPE: JetMoERotaryEmbedding

x

The input tensor.

  • Type: Any
  • Purpose: The input tensor for which the cos and sin cached values need to be forwarded.

It is expected to be a tensor.

seq_len

The length of the sequence for which the cached values need to be forwarded.

  • Type: int
  • Purpose: Determines the length of the sequence for which the cos and sin cached values need to be forwarded.
  • Restrictions: Should be a positive integer.

DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If seq_len is not a positive integer.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
def forward(self, x, seq_len=None):
    """
    Construct the JetMoERotaryEmbedding.

    Args:
        self (JetMoERotaryEmbedding): The instance of the JetMoERotaryEmbedding class.
        x:
            The input tensor.

            - Type: Any
            - Purpose: The input tensor for which the cos and sin cached values need to be forwarded.

            It is expected to be a tensor.
        seq_len:
            The length of the sequence for which the cached values need to be forwarded.

            - Type: int
            - Purpose: Determines the length of the sequence for which the cos and sin cached values
            need to be forwarded.
            - Restrictions: Should be a positive integer.

    Returns:
        None.

    Raises:
        ValueError: If seq_len is not a positive integer.
    """
    # x: [bs, num_attention_heads, seq_len, head_size]
    if seq_len > self.max_seq_len_cached:
        self._set_cos_sin_cache(seq_len=seq_len, dtype=x.dtype)

    return (
        self.cos_cached[:seq_len].to(dtype=x.dtype),
        self.sin_cached[:seq_len].to(dtype=x.dtype),
    )

mindnlp.transformers.models.jetmoe.modeling_jetmoe.JetMoESequenceClassifierOutputWithPast dataclass

Bases: SequenceClassifierOutputWithPast

Base class for outputs of sentence classification models.

PARAMETER DESCRIPTION
loss

Classification (or regression if config.num_labels==1) loss.

TYPE: `mindspore.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided DEFAULT: None

logits

Classification (or regression if config.num_labels==1) scores (before SoftMax).

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

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
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
@dataclass
class JetMoESequenceClassifierOutputWithPast(SequenceClassifierOutputWithPast):
    """
    Base class for outputs of sentence classification models.

    Args:
        loss (`mindspore.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Classification (or regression if config.num_labels==1) loss.
        logits (`mindspore.Tensor` of shape `(batch_size, config.num_labels)`):
            Classification (or regression if config.num_labels==1) scores (before SoftMax).
        past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed
            or when `config.use_cache=True`):
            Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed
            or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed
            or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    """
    loss: Optional[mindspore.Tensor] = None
    logits: mindspore.Tensor = None
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor]]] = None
    hidden_states: Optional[Tuple[mindspore.Tensor]] = None
    attentions: Optional[Tuple[mindspore.Tensor]] = None
    aux_loss: Optional[mindspore.Tensor] = None

mindnlp.transformers.models.jetmoe.modeling_jetmoe.apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=2)

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

The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache.

TYPE: `mindspore.Tensor`

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: 2

RETURNS DESCRIPTION

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

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=2):
    """
    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`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        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[position_ids].unsqueeze(unsqueeze_dim)
    sin = sin[position_ids].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.jetmoe.modeling_jetmoe.rotate_half(x)

Rotates half the hidden dims of the input.

Source code in mindnlp/transformers/models/jetmoe/modeling_jetmoe.py
382
383
384
385
386
387
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, -1)
    return ops.cat((-x2, x1), axis=-1)