Skip to content

phi

mindnlp.transformers.models.phi.configuration_phi

Phi model configuration

mindnlp.transformers.models.phi.configuration_phi.PhiConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [PhiModel]. It is used to instantiate an Phi model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Phi microsoft/phi-1.

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

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

hidden_size

Dimension of the hidden representations.

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

intermediate_size

Dimension of the MLP representations.

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

num_hidden_layers

Number of hidden layers in the Transformer decoder.

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

num_attention_heads

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

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

num_key_value_heads

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

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

resid_pdrop

Dropout probability for mlp outputs.

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

embd_pdrop

The dropout ratio for the embeddings.

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

attention_dropout

The dropout ratio after computing the attention scores.

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

hidden_act

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

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

max_position_embeddings

The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048 tokens.

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

initializer_range

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

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

layer_norm_eps

The epsilon used by the rms normalization layers.

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

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. Whether to tie weight embeddings or not.

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

tie_word_embeddings

Whether to tie weight embeddings

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

rope_theta

The base period of the RoPE embeddings.

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

rope_scaling

Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format is {"type": strategy name, "factor": scaling factor}. When using this flag, don't update max_position_embeddings to the expected new maximum. See the following thread for more information on how these scaling strategies behave: https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an experimental feature, subject to breaking API changes in future versions.

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

partial_rotary_factor

Percentage of the query and keys which will have rotary embedding.

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

qk_layernorm

Whether or not to normalize the Queries and Keys after projecting the hidden states.

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

bos_token_id

Denotes beginning of sequences token id.

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

eos_token_id

Denotes end of sequences token id.

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

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

    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 51200):
            Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`PhiModel`].
        hidden_size (`int`, *optional*, defaults to 2048):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 8192):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 24):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer in the Transformer decoder.
        num_key_value_heads (`int`, *optional*):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be forwarded
            by meanpooling all the original heads within that group. For more details checkout [this
            paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
            `num_attention_heads`.
        resid_pdrop (`float`, *optional*, defaults to 0.0):
            Dropout probability for mlp outputs.
        embd_pdrop (`int`, *optional*, defaults to 0.0):
            The dropout ratio for the embeddings.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio after computing the attention scores.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 2048):
            The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
            tokens.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the rms normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether to tie weight embeddings
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        rope_scaling (`Dict`, *optional*):
            Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
            strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
            is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
            `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
            these scaling strategies behave:
            https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
            is an experimental feature, subject to breaking API changes in future versions.
        partial_rotary_factor (`float`, *optional*, defaults to 0.5):
            Percentage of the query and keys which will have rotary embedding.
        qk_layernorm (`bool`, *optional*, defaults to `False`):
            Whether or not to normalize the Queries and Keys after projecting the hidden states.
        bos_token_id (`int`, *optional*, defaults to 1):
            Denotes beginning of sequences token id.
        eos_token_id (`int`, *optional*, defaults to 2):
            Denotes end of sequences token id.

    Example:
        ```python
        >>> from transformers import PhiModel, PhiConfig
        ...
        >>> # Initializing a Phi-1 style configuration
        >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
        ...
        >>> # Initializing a model from the configuration
        >>> model = PhiModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "phi"
    keys_to_ignore_at_inference = ["past_key_values"]

    def __init__(
        self,
        vocab_size=51200,
        hidden_size=2048,
        intermediate_size=8192,
        num_hidden_layers=24,
        num_attention_heads=32,
        num_key_value_heads=None,
        resid_pdrop=0.0,
        embd_pdrop=0.0,
        attention_dropout=0.0,
        hidden_act="gelu_new",
        max_position_embeddings=2048,
        initializer_range=0.02,
        layer_norm_eps=1e-5,
        use_cache=True,
        tie_word_embeddings=False,
        rope_theta=10000.0,
        rope_scaling=None,
        partial_rotary_factor=0.5,
        qk_layernorm=False,
        bos_token_id=1,
        eos_token_id=2,
        **kwargs,
    ):
        """
        Initializes an instance of the PhiConfig class.

        Args:
            self: The instance of the PhiConfig class.
            vocab_size (int): The size of the vocabulary. Default is 51200.
            hidden_size (int): The size of the hidden layer. Default is 2048.
            intermediate_size (int): The size of the intermediate layer. Default is 8192.
            num_hidden_layers (int): The number of hidden layers. Default is 24.
            num_attention_heads (int): The number of attention heads. Default is 32.
            num_key_value_heads (int): The number of key-value heads. Default is the same as num_attention_heads.
            resid_pdrop (float): The dropout probability for residual connections. Default is 0.0.
            embd_pdrop (float): The dropout probability for embedding layer. Default is 0.0.
            attention_dropout (float): The dropout probability for attention layers. Default is 0.0.
            hidden_act (str): The activation function for the hidden layer. Default is 'gelu_new'.
            max_position_embeddings (int): The maximum position embeddings. Default is 2048.
            initializer_range (float): The range of the initializer. Default is 0.02.
            layer_norm_eps (float): The epsilon value for layer normalization. Default is 1e-05.
            use_cache (bool): Whether to use cache for transformer layers. Default is True.
            tie_word_embeddings (bool): Whether to tie word embeddings. Default is False.
            rope_theta (float): The theta value for rope positional encoding. Default is 10000.0.
            rope_scaling (None or float): The scaling factor for rope positional encoding. Default is None.
            partial_rotary_factor (float): The factor for partial rotary positional encoding. Default is 0.5.
            qk_layernorm (bool): Whether to apply layer normalization on query-key vectors. Default is False.
            bos_token_id (int): The ID of the beginning-of-sequence token. Default is 1.
            eos_token_id (int): The ID of the end-of-sequence token. Default is 2.

        Returns:
            None

        Raises:
            None
        """
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads

        if num_key_value_heads is None:
            num_key_value_heads = num_attention_heads

        self.num_key_value_heads = num_key_value_heads
        self.resid_pdrop = resid_pdrop
        self.embd_pdrop = embd_pdrop
        self.attention_dropout = attention_dropout
        self.hidden_act = hidden_act
        self.max_position_embeddings = max_position_embeddings
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.use_cache = use_cache
        self.rope_theta = rope_theta
        self.rope_scaling = rope_scaling
        self.partial_rotary_factor = partial_rotary_factor
        self.qk_layernorm = qk_layernorm
        self._rope_scaling_validation()

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

    # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
    def _rope_scaling_validation(self):
        """
        Validate the `rope_scaling` configuration.
        """
        if self.rope_scaling is None:
            return

        if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
            raise ValueError(
                "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
                f"got {self.rope_scaling}"
            )
        rope_scaling_type = self.rope_scaling.get("type", None)
        rope_scaling_factor = self.rope_scaling.get("factor", None)
        if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
            raise ValueError(
                f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
            )
        if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
            raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")

mindnlp.transformers.models.phi.configuration_phi.PhiConfig.__init__(vocab_size=51200, hidden_size=2048, intermediate_size=8192, num_hidden_layers=24, num_attention_heads=32, num_key_value_heads=None, resid_pdrop=0.0, embd_pdrop=0.0, attention_dropout=0.0, hidden_act='gelu_new', max_position_embeddings=2048, initializer_range=0.02, layer_norm_eps=1e-05, use_cache=True, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, partial_rotary_factor=0.5, qk_layernorm=False, bos_token_id=1, eos_token_id=2, **kwargs)

Initializes an instance of the PhiConfig class.

PARAMETER DESCRIPTION
self

The instance of the PhiConfig class.

vocab_size

The size of the vocabulary. Default is 51200.

TYPE: int DEFAULT: 51200

hidden_size

The size of the hidden layer. Default is 2048.

TYPE: int DEFAULT: 2048

intermediate_size

The size of the intermediate layer. Default is 8192.

TYPE: int DEFAULT: 8192

num_hidden_layers

The number of hidden layers. Default is 24.

TYPE: int DEFAULT: 24

num_attention_heads

The number of attention heads. Default is 32.

TYPE: int DEFAULT: 32

num_key_value_heads

The number of key-value heads. Default is the same as num_attention_heads.

TYPE: int DEFAULT: None

resid_pdrop

The dropout probability for residual connections. Default is 0.0.

TYPE: float DEFAULT: 0.0

embd_pdrop

The dropout probability for embedding layer. Default is 0.0.

TYPE: float DEFAULT: 0.0

attention_dropout

The dropout probability for attention layers. Default is 0.0.

TYPE: float DEFAULT: 0.0

hidden_act

The activation function for the hidden layer. Default is 'gelu_new'.

TYPE: str DEFAULT: 'gelu_new'

max_position_embeddings

The maximum position embeddings. Default is 2048.

TYPE: int DEFAULT: 2048

initializer_range

The range of the initializer. Default is 0.02.

TYPE: float DEFAULT: 0.02

layer_norm_eps

The epsilon value for layer normalization. Default is 1e-05.

TYPE: float DEFAULT: 1e-05

use_cache

Whether to use cache for transformer layers. Default is True.

TYPE: bool DEFAULT: True

tie_word_embeddings

Whether to tie word embeddings. Default is False.

TYPE: bool DEFAULT: False

rope_theta

The theta value for rope positional encoding. Default is 10000.0.

TYPE: float DEFAULT: 10000.0

rope_scaling

The scaling factor for rope positional encoding. Default is None.

TYPE: None or float DEFAULT: None

partial_rotary_factor

The factor for partial rotary positional encoding. Default is 0.5.

TYPE: float DEFAULT: 0.5

qk_layernorm

Whether to apply layer normalization on query-key vectors. Default is False.

TYPE: bool DEFAULT: False

bos_token_id

The ID of the beginning-of-sequence token. Default is 1.

TYPE: int DEFAULT: 1

eos_token_id

The ID of the end-of-sequence token. Default is 2.

TYPE: int DEFAULT: 2

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/phi/configuration_phi.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def __init__(
    self,
    vocab_size=51200,
    hidden_size=2048,
    intermediate_size=8192,
    num_hidden_layers=24,
    num_attention_heads=32,
    num_key_value_heads=None,
    resid_pdrop=0.0,
    embd_pdrop=0.0,
    attention_dropout=0.0,
    hidden_act="gelu_new",
    max_position_embeddings=2048,
    initializer_range=0.02,
    layer_norm_eps=1e-5,
    use_cache=True,
    tie_word_embeddings=False,
    rope_theta=10000.0,
    rope_scaling=None,
    partial_rotary_factor=0.5,
    qk_layernorm=False,
    bos_token_id=1,
    eos_token_id=2,
    **kwargs,
):
    """
    Initializes an instance of the PhiConfig class.

    Args:
        self: The instance of the PhiConfig class.
        vocab_size (int): The size of the vocabulary. Default is 51200.
        hidden_size (int): The size of the hidden layer. Default is 2048.
        intermediate_size (int): The size of the intermediate layer. Default is 8192.
        num_hidden_layers (int): The number of hidden layers. Default is 24.
        num_attention_heads (int): The number of attention heads. Default is 32.
        num_key_value_heads (int): The number of key-value heads. Default is the same as num_attention_heads.
        resid_pdrop (float): The dropout probability for residual connections. Default is 0.0.
        embd_pdrop (float): The dropout probability for embedding layer. Default is 0.0.
        attention_dropout (float): The dropout probability for attention layers. Default is 0.0.
        hidden_act (str): The activation function for the hidden layer. Default is 'gelu_new'.
        max_position_embeddings (int): The maximum position embeddings. Default is 2048.
        initializer_range (float): The range of the initializer. Default is 0.02.
        layer_norm_eps (float): The epsilon value for layer normalization. Default is 1e-05.
        use_cache (bool): Whether to use cache for transformer layers. Default is True.
        tie_word_embeddings (bool): Whether to tie word embeddings. Default is False.
        rope_theta (float): The theta value for rope positional encoding. Default is 10000.0.
        rope_scaling (None or float): The scaling factor for rope positional encoding. Default is None.
        partial_rotary_factor (float): The factor for partial rotary positional encoding. Default is 0.5.
        qk_layernorm (bool): Whether to apply layer normalization on query-key vectors. Default is False.
        bos_token_id (int): The ID of the beginning-of-sequence token. Default is 1.
        eos_token_id (int): The ID of the end-of-sequence token. Default is 2.

    Returns:
        None

    Raises:
        None
    """
    self.vocab_size = vocab_size
    self.hidden_size = hidden_size
    self.intermediate_size = intermediate_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads

    if num_key_value_heads is None:
        num_key_value_heads = num_attention_heads

    self.num_key_value_heads = num_key_value_heads
    self.resid_pdrop = resid_pdrop
    self.embd_pdrop = embd_pdrop
    self.attention_dropout = attention_dropout
    self.hidden_act = hidden_act
    self.max_position_embeddings = max_position_embeddings
    self.initializer_range = initializer_range
    self.layer_norm_eps = layer_norm_eps
    self.use_cache = use_cache
    self.rope_theta = rope_theta
    self.rope_scaling = rope_scaling
    self.partial_rotary_factor = partial_rotary_factor
    self.qk_layernorm = qk_layernorm
    self._rope_scaling_validation()

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

mindnlp.transformers.models.phi.modeling_phi

MindSpore Phi model.

mindnlp.transformers.models.phi.modeling_phi.PhiAttention

Bases: Module

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

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
class PhiAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""
    def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
        """
        Initializes an instance of the PhiAttention class.

        Args:
            self: The instance of the class.
            config (PhiConfig): An instance of the PhiConfig class containing configuration parameters.
            layer_idx (Optional[int]): The index of the layer. Defaults to None.

        Returns:
            None

        Raises:
            ValueError: If the hidden_size is not divisible by num_heads.
            TypeError: If config is not an instance of PhiConfig.
            TypeError: If layer_idx is not an integer or None.
            Warning: If layer_idx is None, it is not recommended and may lead to errors during forward call
                if caching is used.

        Note:
            This method initializes the PhiAttention class with the given configuration and layer index.
            It sets the various properties and performs necessary checks.

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

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

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

        self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
        self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
        self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
        self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)

        self.qk_layernorm = config.qk_layernorm
        if self.qk_layernorm:
            self.q_layernorm = nn.LayerNorm(
                [config.hidden_size // self.num_heads], eps=config.layer_norm_eps, elementwise_affine=True
            )
            self.k_layernorm = nn.LayerNorm(
                [config.hidden_size // self.num_heads], eps=config.layer_norm_eps, elementwise_affine=True
            )

        self._init_rope()

    def _init_rope(self):
        """
        Initializes the RoPE (Rotary Position Embedding) for PhiAttention.

        Args:
            self: The instance of the PhiAttention class.

        Returns:
            None: This method modifies the rotary_emb attribute of the instance.

        Raises:
            ValueError: If the RoPE scaling type is unknown.

        The method initializes the RoPE based on the configuration provided. If the rope_scaling is not specified,
        the method initializes a PhiRotaryEmbedding object with the given partial_rotary_factor and
        max_position_embeddings.

        If rope_scaling is specified, the method checks the scaling_type. If the scaling_type is 'linear',
        it initializes a PhiLinearScalingRotaryEmbedding object with the given partial_rotary_factor,
        max_position_embeddings, scaling_factor, and base. If the scaling_type is 'dynamic',
        it initializes a PhiDynamicNTKScalingRotaryEmbedding object with the given partial_rotary_factor,
        max_position_embeddings, scaling_factor, and base.

        Note:
            RoPE stands for Rotary Position Embedding and is used to incorporate positional information in the
            attention mechanism.

        """
        if self.config.rope_scaling is None:
            self.rotary_emb = PhiRotaryEmbedding(
                int(self.partial_rotary_factor * self.head_dim),
                max_position_embeddings=self.max_position_embeddings,
                base=self.rope_theta,
            )
        else:
            scaling_type = self.config.rope_scaling["type"]
            scaling_factor = self.config.rope_scaling["factor"]
            if scaling_type == "linear":
                self.rotary_emb = PhiLinearScalingRotaryEmbedding(
                    int(self.partial_rotary_factor * self.head_dim),
                    max_position_embeddings=self.max_position_embeddings,
                    scaling_factor=scaling_factor,
                    base=self.rope_theta,
                )
            elif scaling_type == "dynamic":
                self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
                    int(self.partial_rotary_factor * self.head_dim),
                    max_position_embeddings=self.max_position_embeddings,
                    scaling_factor=scaling_factor,
                    base=self.rope_theta,
                )
            else:
                raise ValueError(f"Unknown RoPE scaling type {scaling_type}")

    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,
    ) -> Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
        '''
        This method, named 'forward', is defined in the class 'PhiAttention'.

        Args:
            self: The instance of the class.
            hidden_states (mindspore.Tensor): The input hidden states with shape
                (batch_size, sequence_length, hidden_size).
            attention_mask (Optional[mindspore.Tensor]): An optional tensor with shape
                (batch_size, 1, sequence_length, sequence_length) to mask the attention scores.
            position_ids (Optional[mindspore.Tensor]): An optional tensor representing the position indices of
                input tokens with shape (batch_size, sequence_length).
            past_key_value (Optional[Cache]): An optional cache structure for storing previous key and value states
                during auto-regressive decoding.
            output_attentions (bool): A boolean flag indicating whether to return the attention weights.
            use_cache (bool): A boolean flag indicating whether to use caching for key and value states.

        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),
                optional attention weights tensor, and optional updated cache structure.

        Raises:
            ValueError: If the cache structure has changed since version v4.36 and the layer index is not initialized
                when using the cache for auto-regressive decoding.
            ValueError: If the shape of attention weights does not match
                (batch_size, num_heads, sequence_length, sequence_length).
            ValueError: If the shape of attention mask does not match (batch_size, 1, sequence_length, sequence_length).
            ValueError: If the shape of attn_output does not match (batch_size, num_heads, sequence_length, hidden_size).
        '''
        bsz, q_len, _ = hidden_states.shape
        query_states = self.q_proj(hidden_states)
        key_states = self.k_proj(hidden_states)
        value_states = self.v_proj(hidden_states)
        if self.qk_layernorm:
            query_states = self.q_layernorm(query_states)
            key_states = self.k_layernorm(key_states)

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

        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)

        # Partial rotary embedding
        query_rot, query_pass = (
            query_states[..., : self.rotary_emb.dim],
            query_states[..., self.rotary_emb.dim :],
        )
        key_rot, key_pass = (
            key_states[..., : self.rotary_emb.dim],
            key_states[..., self.rotary_emb.dim :],
        )
        # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
        query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)

        # [batch_size, seq_length, num_heads, head_dim]
        query_states = ops.cat((query_rot, query_pass), axis=-1)
        key_states = ops.cat((key_rot, key_pass), axis=-1)

        if past_key_value is not None:
            cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
            key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

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

        # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
        attn_weights = ops.matmul(
            query_states.to(mindspore.float32), key_states.to(mindspore.float32).swapaxes(2, 3)
        ) / math.sqrt(self.head_dim)
        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(value_states.dtype)
        attn_weights = ops.dropout(attn_weights, p=self.attention_dropout, training=self.training)

        attn_output = ops.matmul(attn_weights, value_states)

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

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

        attn_output = self.dense(attn_output)

        if not output_attentions:
            attn_weights = None

        return attn_output, attn_weights, past_key_value

mindnlp.transformers.models.phi.modeling_phi.PhiAttention.__init__(config, layer_idx=None)

Initializes an instance of the PhiAttention class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An instance of the PhiConfig class containing configuration parameters.

TYPE: PhiConfig

layer_idx

The index of the layer. Defaults to None.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the hidden_size is not divisible by num_heads.

TypeError

If config is not an instance of PhiConfig.

TypeError

If layer_idx is not an integer or None.

Warning

If layer_idx is None, it is not recommended and may lead to errors during forward call if caching is used.

Note

This method initializes the PhiAttention class with the given configuration and layer index. It sets the various properties and performs necessary checks.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
    """
    Initializes an instance of the PhiAttention class.

    Args:
        self: The instance of the class.
        config (PhiConfig): An instance of the PhiConfig class containing configuration parameters.
        layer_idx (Optional[int]): The index of the layer. Defaults to None.

    Returns:
        None

    Raises:
        ValueError: If the hidden_size is not divisible by num_heads.
        TypeError: If config is not an instance of PhiConfig.
        TypeError: If layer_idx is not an integer or None.
        Warning: If layer_idx is None, it is not recommended and may lead to errors during forward call
            if caching is used.

    Note:
        This method initializes the PhiAttention class with the given configuration and layer index.
        It sets the various properties and performs necessary checks.

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

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

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

    self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
    self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
    self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
    self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)

    self.qk_layernorm = config.qk_layernorm
    if self.qk_layernorm:
        self.q_layernorm = nn.LayerNorm(
            [config.hidden_size // self.num_heads], eps=config.layer_norm_eps, elementwise_affine=True
        )
        self.k_layernorm = nn.LayerNorm(
            [config.hidden_size // self.num_heads], eps=config.layer_norm_eps, elementwise_affine=True
        )

    self._init_rope()

mindnlp.transformers.models.phi.modeling_phi.PhiAttention.forward(hidden_states, attention_mask=None, position_ids=None, past_key_value=None, output_attentions=False, use_cache=False)

This method, named 'forward', is defined in the class 'PhiAttention'.

PARAMETER DESCRIPTION
self

The instance of the class.

hidden_states

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

TYPE: Tensor

attention_mask

An optional tensor with shape (batch_size, 1, sequence_length, sequence_length) to mask the attention scores.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

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

TYPE: Optional[Tensor] DEFAULT: None

past_key_value

An optional cache structure for storing previous key and value states during auto-regressive decoding.

TYPE: Optional[Cache] DEFAULT: None

output_attentions

A boolean flag indicating whether to return the attention weights.

TYPE: bool DEFAULT: False

use_cache

A boolean flag indicating whether to use caching for key and value states.

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), optional attention weights tensor, and optional updated cache structure.

RAISES DESCRIPTION
ValueError

If the cache structure has changed since version v4.36 and the layer index is not initialized when using the cache for auto-regressive decoding.

ValueError

If the shape of attention weights does not match (batch_size, num_heads, sequence_length, sequence_length).

ValueError

If the shape of attention mask does not match (batch_size, 1, sequence_length, sequence_length).

ValueError

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

Source code in mindnlp/transformers/models/phi/modeling_phi.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
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,
) -> Tuple[mindspore.Tensor, Optional[mindspore.Tensor], Optional[Tuple[mindspore.Tensor]]]:
    '''
    This method, named 'forward', is defined in the class 'PhiAttention'.

    Args:
        self: The instance of the class.
        hidden_states (mindspore.Tensor): The input hidden states with shape
            (batch_size, sequence_length, hidden_size).
        attention_mask (Optional[mindspore.Tensor]): An optional tensor with shape
            (batch_size, 1, sequence_length, sequence_length) to mask the attention scores.
        position_ids (Optional[mindspore.Tensor]): An optional tensor representing the position indices of
            input tokens with shape (batch_size, sequence_length).
        past_key_value (Optional[Cache]): An optional cache structure for storing previous key and value states
            during auto-regressive decoding.
        output_attentions (bool): A boolean flag indicating whether to return the attention weights.
        use_cache (bool): A boolean flag indicating whether to use caching for key and value states.

    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),
            optional attention weights tensor, and optional updated cache structure.

    Raises:
        ValueError: If the cache structure has changed since version v4.36 and the layer index is not initialized
            when using the cache for auto-regressive decoding.
        ValueError: If the shape of attention weights does not match
            (batch_size, num_heads, sequence_length, sequence_length).
        ValueError: If the shape of attention mask does not match (batch_size, 1, sequence_length, sequence_length).
        ValueError: If the shape of attn_output does not match (batch_size, num_heads, sequence_length, hidden_size).
    '''
    bsz, q_len, _ = hidden_states.shape
    query_states = self.q_proj(hidden_states)
    key_states = self.k_proj(hidden_states)
    value_states = self.v_proj(hidden_states)
    if self.qk_layernorm:
        query_states = self.q_layernorm(query_states)
        key_states = self.k_layernorm(key_states)

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

    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)

    # Partial rotary embedding
    query_rot, query_pass = (
        query_states[..., : self.rotary_emb.dim],
        query_states[..., self.rotary_emb.dim :],
    )
    key_rot, key_pass = (
        key_states[..., : self.rotary_emb.dim],
        key_states[..., self.rotary_emb.dim :],
    )
    # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
    query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)

    # [batch_size, seq_length, num_heads, head_dim]
    query_states = ops.cat((query_rot, query_pass), axis=-1)
    key_states = ops.cat((key_rot, key_pass), axis=-1)

    if past_key_value is not None:
        cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
        key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

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

    # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
    attn_weights = ops.matmul(
        query_states.to(mindspore.float32), key_states.to(mindspore.float32).swapaxes(2, 3)
    ) / math.sqrt(self.head_dim)
    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(value_states.dtype)
    attn_weights = ops.dropout(attn_weights, p=self.attention_dropout, training=self.training)

    attn_output = ops.matmul(attn_weights, value_states)

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

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

    attn_output = self.dense(attn_output)

    if not output_attentions:
        attn_weights = None

    return attn_output, attn_weights, past_key_value

mindnlp.transformers.models.phi.modeling_phi.PhiDecoderLayer

Bases: Module

PhiDecoderLayer represents a single layer of the Phi decoder model.

This class inherits from nn.Module and contains methods for initializing the layer and forwarding the layer's computations.

The init method initializes the PhiDecoderLayer with the provided configuration and layer index. It sets up the self-attention mechanism, multi-layer perceptron, layer normalization, and residual dropout.

The forward method takes hidden_states as input and applies layer normalization. It then computes the self-attention outputs, optionally returning attention weights and caching key-value states. The method also computes the feed-forward hidden states and returns the final layer outputs, optionally including attention weights and key-value states in the output tuple.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
class PhiDecoderLayer(nn.Module):

    """
    PhiDecoderLayer represents a single layer of the Phi decoder model.

    This class inherits from nn.Module and contains methods for initializing the layer and forwarding the
    layer's computations.

    The __init__ method initializes the PhiDecoderLayer with the provided configuration and layer index.
    It sets up the self-attention mechanism, multi-layer perceptron, layer normalization, and residual dropout.

    The forward method takes hidden_states as input and applies layer normalization. It then computes the
    self-attention outputs, optionally returning attention weights and caching key-value states. The method also
    computes the feed-forward hidden states and returns the final layer outputs, optionally including attention weights
    and key-value states in the output tuple.
    """
    def __init__(self, config: PhiConfig, layer_idx: int):
        """
        This method initializes a PhiDecoderLayer object.

        Args:
            self (PhiDecoderLayer): The current instance of PhiDecoderLayer.
            config (PhiConfig): An object containing configuration settings for the PhiDecoderLayer.
            layer_idx (int): An integer representing the index of the layer within the PhiDecoderLayer.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type PhiConfig.
            ValueError: If the layer_idx parameter is not an integer.
        """
        super().__init__()
        self.self_attn = PHI_ATTENTION_CLASSES["eager"](config, layer_idx=layer_idx)
        self.mlp = PhiMLP(config)
        self.input_layernorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.resid_dropout = nn.Dropout(p=config.resid_pdrop)

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        attention_mask: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = False,
        use_cache: Optional[bool] = False,
        past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
    ) -> Tuple[mindspore.Tensor, Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]]:
        """
        Args:
            hidden_states (`mindspore.Tensor`):
                input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`mindspore.Tensor`, *optional*): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            position_ids (`mindspore.Tensor` of shape `({0})`, *optional*):
                Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
                `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(mindspore.Tensor)`, *optional*): cached past key and value projection states
        """
        residual = hidden_states

        hidden_states = self.input_layernorm(hidden_states)

        # Self Attention
        attn_outputs, self_attn_weights, present_key_value = self.self_attn(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_value=past_key_value,
            output_attentions=output_attentions,
            use_cache=use_cache,
        )
        attn_outputs = self.resid_dropout(attn_outputs)

        feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
        hidden_states = attn_outputs + feed_forward_hidden_states + residual
        outputs = (hidden_states,)

        if output_attentions:
            outputs += (self_attn_weights,)

        if use_cache:
            outputs += (present_key_value,)

        return outputs

mindnlp.transformers.models.phi.modeling_phi.PhiDecoderLayer.__init__(config, layer_idx)

This method initializes a PhiDecoderLayer object.

PARAMETER DESCRIPTION
self

The current instance of PhiDecoderLayer.

TYPE: PhiDecoderLayer

config

An object containing configuration settings for the PhiDecoderLayer.

TYPE: PhiConfig

layer_idx

An integer representing the index of the layer within the PhiDecoderLayer.

TYPE: int

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type PhiConfig.

ValueError

If the layer_idx parameter is not an integer.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
def __init__(self, config: PhiConfig, layer_idx: int):
    """
    This method initializes a PhiDecoderLayer object.

    Args:
        self (PhiDecoderLayer): The current instance of PhiDecoderLayer.
        config (PhiConfig): An object containing configuration settings for the PhiDecoderLayer.
        layer_idx (int): An integer representing the index of the layer within the PhiDecoderLayer.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type PhiConfig.
        ValueError: If the layer_idx parameter is not an integer.
    """
    super().__init__()
    self.self_attn = PHI_ATTENTION_CLASSES["eager"](config, layer_idx=layer_idx)
    self.mlp = PhiMLP(config)
    self.input_layernorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.resid_dropout = nn.Dropout(p=config.resid_pdrop)

mindnlp.transformers.models.phi.modeling_phi.PhiDecoderLayer.forward(hidden_states, attention_mask=None, position_ids=None, output_attentions=False, use_cache=False, past_key_value=None)

PARAMETER DESCRIPTION
hidden_states

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

TYPE: `mindspore.Tensor`

attention_mask

attention mask of size (batch, 1, tgt_len, src_len) where padding elements are indicated by very large negative values.

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

position_ids

Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1]. What are position IDs?

TYPE: `mindspore.Tensor` of shape `({0})`, *optional* DEFAULT: None

output_attentions

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

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

use_cache

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

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

past_key_value

cached past key and value projection states

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

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
def forward(
    self,
    hidden_states: mindspore.Tensor,
    attention_mask: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = False,
    use_cache: Optional[bool] = False,
    past_key_value: Optional[Tuple[mindspore.Tensor]] = None,
) -> Tuple[mindspore.Tensor, Optional[Tuple[mindspore.Tensor, mindspore.Tensor]]]:
    """
    Args:
        hidden_states (`mindspore.Tensor`):
            input to the layer of shape `(batch, seq_len, embed_dim)`
        attention_mask (`mindspore.Tensor`, *optional*): attention mask of size
            `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
        position_ids (`mindspore.Tensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
            `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under
            returned tensors for more detail.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
            (see `past_key_values`).
        past_key_value (`Tuple(mindspore.Tensor)`, *optional*): cached past key and value projection states
    """
    residual = hidden_states

    hidden_states = self.input_layernorm(hidden_states)

    # Self Attention
    attn_outputs, self_attn_weights, present_key_value = self.self_attn(
        hidden_states=hidden_states,
        attention_mask=attention_mask,
        position_ids=position_ids,
        past_key_value=past_key_value,
        output_attentions=output_attentions,
        use_cache=use_cache,
    )
    attn_outputs = self.resid_dropout(attn_outputs)

    feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
    hidden_states = attn_outputs + feed_forward_hidden_states + residual
    outputs = (hidden_states,)

    if output_attentions:
        outputs += (self_attn_weights,)

    if use_cache:
        outputs += (present_key_value,)

    return outputs

mindnlp.transformers.models.phi.modeling_phi.PhiDynamicNTKScalingRotaryEmbedding

Bases: PhiRotaryEmbedding

PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
    """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
    def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
        """
        Initializes an instance of PhiDynamicNTKScalingRotaryEmbedding.

        Args:
            self: The instance of the class.
            dim (int): The dimensionality of the embedding.
            max_position_embeddings (int): The maximum number of position embeddings.
            base (int): The base value used in calculations.
            scaling_factor (float): The scaling factor applied to the embeddings.

        Returns:
            None.

        Raises:
            None.
        """
        self.scaling_factor = scaling_factor
        super().__init__(dim, max_position_embeddings, base)

    def _set_cos_sin_cache(self, seq_len, dtype):
        '''
        _set_cos_sin_cache method in the PhiDynamicNTKScalingRotaryEmbedding class.

        This method is used to set the cosine and sine cache for the rotary position embeddings based on the
        given sequence length and data type.

        Args:
            self (PhiDynamicNTKScalingRotaryEmbedding): The instance of the PhiDynamicNTKScalingRotaryEmbedding class.
            seq_len (int): The length of the sequence for which the cosine and sine cache is to be set.
            dtype: The data type for the cache values.

        Returns:
            None.

        Raises:
            ValueError: If the sequence length is less than or equal to 0.
            TypeError: If the input data type is not compatible with the operations performed within the method.
        '''
        self.max_seq_len_cached = seq_len

        if seq_len > self.max_position_embeddings:
            base = self.base * (
                (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
            ) ** (self.dim / (self.dim - 2))
            inv_freq = 1.0 / (base ** (ops.arange(0, self.dim, 2).float() / self.dim))
            self.inv_freq = inv_freq

        t = ops.arange(self.max_seq_len_cached, dtype=self.inv_freq.dtype)

        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)

mindnlp.transformers.models.phi.modeling_phi.PhiDynamicNTKScalingRotaryEmbedding.__init__(dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0)

Initializes an instance of PhiDynamicNTKScalingRotaryEmbedding.

PARAMETER DESCRIPTION
self

The instance of the class.

dim

The dimensionality of the embedding.

TYPE: int

max_position_embeddings

The maximum number of position embeddings.

TYPE: int DEFAULT: 2048

base

The base value used in calculations.

TYPE: int DEFAULT: 10000

scaling_factor

The scaling factor applied to the embeddings.

TYPE: float DEFAULT: 1.0

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
    """
    Initializes an instance of PhiDynamicNTKScalingRotaryEmbedding.

    Args:
        self: The instance of the class.
        dim (int): The dimensionality of the embedding.
        max_position_embeddings (int): The maximum number of position embeddings.
        base (int): The base value used in calculations.
        scaling_factor (float): The scaling factor applied to the embeddings.

    Returns:
        None.

    Raises:
        None.
    """
    self.scaling_factor = scaling_factor
    super().__init__(dim, max_position_embeddings, base)

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM

Bases: PhiPreTrainedModel

The PhiForCausalLM class represents a Phi model for causal language modeling. It inherits from PhiPreTrainedModel and provides methods for initializing the model, getting and setting input and output embeddings, setting the decoder, forwarding the model, preparing inputs for generation, and reordering cache. The PhiForCausalLM class also includes detailed type annotations and example usage.

The class includes the following methods:

  • __init__: Initializes the PhiForCausalLM model with the provided configuration.
  • get_input_embeddings: Returns the input embeddings of the model.
  • set_input_embeddings: Sets the input embeddings of the model to the provided value.
  • get_output_embeddings: Returns the output embeddings of the model.
  • set_output_embeddings: Sets the output embeddings of the model to the provided new_embeddings.
  • set_decoder: Sets the decoder of the model to the provided decoder.
  • get_decoder: Returns the decoder of the model.
  • forward: Constructs the model for causal language modeling with the specified inputs and returns the outputs.
  • prepare_inputs_for_generation: Prepares the inputs for generation based on the provided input_ids, past_key_values, attention_mask, and inputs_embeds.
  • _reorder_cache: Reorders the past_key_values based on the specified beam index.

The class docstring includes detailed descriptions of the methods, their arguments, and return values, as well as an example usage demonstrating how to use the PhiForCausalLM class for generating text using the model.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
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
class PhiForCausalLM(PhiPreTrainedModel):

    """
    The `PhiForCausalLM` class represents a Phi model for causal language modeling. It inherits from `PhiPreTrainedModel`
    and provides methods for initializing the model, getting and setting input and output embeddings, setting the
    decoder, forwarding the model, preparing inputs for generation, and reordering cache.
    The `PhiForCausalLM` class also includes detailed type annotations and example usage.

    The class includes the following methods:

    - `__init__`: Initializes the PhiForCausalLM model with the provided configuration.
    - `get_input_embeddings`: Returns the input embeddings of the model.
    - `set_input_embeddings`: Sets the input embeddings of the model to the provided value.
    - `get_output_embeddings`: Returns the output embeddings of the model.
    - `set_output_embeddings`: Sets the output embeddings of the model to the provided new_embeddings.
    - `set_decoder`: Sets the decoder of the model to the provided decoder.
    - `get_decoder`: Returns the decoder of the model.
    - `forward`: Constructs the model for causal language modeling with the specified inputs and returns the outputs.
    - `prepare_inputs_for_generation`: Prepares the inputs for generation based on the provided input_ids,
    past_key_values, attention_mask, and inputs_embeds.
    - `_reorder_cache`: Reorders the past_key_values based on the specified beam index.

    The class docstring includes detailed descriptions of the methods, their arguments, and return values, as well as
    an example usage demonstrating how to use the `PhiForCausalLM` class for generating text using the model.

    """
    _tied_weights_keys = ["lm_head.weight"]

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
    def __init__(self, config):
        """
        Initializes an instance of the 'PhiForCausalLM' class.

        Args:
            self: The instance of the class.
            config (object):
                The configuration object containing the necessary parameters for the Phi model.

                - config.vocab_size (int): The size of the vocabulary.
                - config.hidden_size (int): The size of the hidden state of the model.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.model = PhiModel(config)
        self.vocab_size = config.vocab_size
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
        # Initialize weights and apply final processing
        self.post_init()

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
    def get_input_embeddings(self):
        """
        Method to retrieve the input embeddings from the PhiForCausalLM model.

        Args:
            self (PhiForCausalLM): An instance of the PhiForCausalLM class.
                Represents the current object instance.

        Returns:
            embed_tokens: This method returns the input embeddings as obtained from the model's embed_tokens attribute.

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

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
    def set_input_embeddings(self, value):
        """
        This method sets the input embeddings for the PhiForCausalLM model.

        Args:
            self (PhiForCausalLM): The instance of the PhiForCausalLM class.
            value (Tensor): The input embeddings to be set for the model.
                It should be a tensor of appropriate shape and type.

        Returns:
            None.

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

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
    def get_output_embeddings(self):
        """
        Returns the output embeddings for the PhiForCausalLM model.

        Args:
            self: An instance of the PhiForCausalLM class.

        Returns:
            None: The method returns the output embeddings for the PhiForCausalLM model.
                These embeddings are used to map the output tokens to a continuous representation.

        Raises:
            None.
        """
        return self.lm_head

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
    def set_output_embeddings(self, new_embeddings):
        """
        Sets the output embeddings for the PhiForCausalLM model.

        Args:
            self (PhiForCausalLM): The instance of the PhiForCausalLM class.
            new_embeddings: The new embeddings to be set as the model's output embeddings.
                It should be a tensor of shape (vocab_size, hidden_size) where 'vocab_size'
                represents the size of the vocabulary and 'hidden_size' represents the size
                of the hidden layer. The new embeddings should be compatible with the model's
                existing architecture.

        Returns:
            None.

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

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
    def set_decoder(self, decoder):
        """
        Args:
            self (PhiForCausalLM): The instance of the PhiForCausalLM class.
            decoder: The decoder object to be set for the model. It should be an instance of the decoder class.

        Returns:
            None.

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

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
    def get_decoder(self):
        """
        Returns the decoder model used for PhiForCausalLM.

        Args:
            self: An instance of the PhiForCausalLM class.

        Returns:
            None.

        Raises:
            None.

        This method retrieves the decoder model that is used for PhiForCausalLM. The decoder model is an essential component
        of the PhiForCausalLM class and is responsible for generating output based on the input data. The decoder model
        contains the learned weights and biases that enable the PhiForCausalLM class to perform its tasks effectively.
        The returned decoder model is of type 'None' as it is used internally within the PhiForCausalLM class and is not
        intended to be directly accessed or modified by the user.
        """
        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]

        Example:
            ```python
            >>> from transformers import AutoTokenizer, PhiForCausalLM
            ...
            >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
            >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
            ...
            >>> prompt = "This is an example script ."
            >>> inputs = tokenizer(prompt, return_tensors="pt")
            ...
            >>> # Generate
            >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
            >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
            'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
            ```
        """
        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)
            # Enable model parallelism
            loss = ops.cross_entropy(shift_logits, shift_labels)

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

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

    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
    def prepare_inputs_for_generation(
        self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
    ):
        """
        Prepares inputs for generating output sequences using PhiForCausalLM model.

        Args:
            self (PhiForCausalLM): An instance of PhiForCausalLM class.
            input_ids (torch.Tensor): A tensor of shape (batch_size, sequence_length) containing input sequence tokens.
            past_key_values (Cache or tuple or None): A cache object or tuple of two tensors containing previously
                computed key and value pairs for the attention mechanism. If None, no caching is performed.
            attention_mask (torch.Tensor or None): An optional tensor of shape (batch_size, sequence_length)
                containing a mask to avoid performing attention on padding tokens.
            inputs_embeds (torch.Tensor or None): An optional tensor of shape (batch_size, sequence_length, hidden_size)
                containing precomputed embeddings for the input sequence.

        Returns:
            model_inputs (dict):
                A dictionary containing the following keys:

                - 'input_ids': The input sequence tokens tensor.
                - 'position_ids': The tensor of positional encoding for the input sequence.
                - 'past_key_values': The cache object or tuple of two tensors containing previously computed key and
                value pairs for the attention mechanism.
                - 'use_cache': A boolean indicating whether to use caching.
                - 'attention_mask': The tensor containing the attention mask for the input sequence.

        Raises:
            None.
        """
        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
    # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache of past key values based on the given beam index.

        Args:
            past_key_values (tuple): A tuple containing past key values for each layer. Each element in the tuple is
                a tensor representing the past key values.
            beam_idx (Tensor): A tensor containing the indices of the beams to reorder the cache based on.

        Returns:
            None: The method modifies the cache in place.

        Raises:
            ValueError: If the input past_key_values or beam_idx are not in the expected format.
            IndexError: If the beam index is out of bounds.
        """
        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.phi.modeling_phi.PhiForCausalLM.__init__(config)

Initializes an instance of the 'PhiForCausalLM' class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object containing the necessary parameters for the Phi model.

  • config.vocab_size (int): The size of the vocabulary.
  • config.hidden_size (int): The size of the hidden state of the model.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
def __init__(self, config):
    """
    Initializes an instance of the 'PhiForCausalLM' class.

    Args:
        self: The instance of the class.
        config (object):
            The configuration object containing the necessary parameters for the Phi model.

            - config.vocab_size (int): The size of the vocabulary.
            - config.hidden_size (int): The size of the hidden state of the model.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.model = PhiModel(config)
    self.vocab_size = config.vocab_size
    self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.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]

Example
>>> from transformers import AutoTokenizer, PhiForCausalLM
...
>>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
...
>>> prompt = "This is an example script ."
>>> inputs = tokenizer(prompt, return_tensors="pt")
...
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
Source code in mindnlp/transformers/models/phi/modeling_phi.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
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]

    Example:
        ```python
        >>> from transformers import AutoTokenizer, PhiForCausalLM
        ...
        >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
        ...
        >>> prompt = "This is an example script ."
        >>> inputs = tokenizer(prompt, return_tensors="pt")
        ...
        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
        ```
    """
    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)
        # Enable model parallelism
        loss = ops.cross_entropy(shift_logits, shift_labels)

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

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

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.get_decoder()

Returns the decoder model used for PhiForCausalLM.

PARAMETER DESCRIPTION
self

An instance of the PhiForCausalLM class.

RETURNS DESCRIPTION

None.

This method retrieves the decoder model that is used for PhiForCausalLM. The decoder model is an essential component of the PhiForCausalLM class and is responsible for generating output based on the input data. The decoder model contains the learned weights and biases that enable the PhiForCausalLM class to perform its tasks effectively. The returned decoder model is of type 'None' as it is used internally within the PhiForCausalLM class and is not intended to be directly accessed or modified by the user.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
def get_decoder(self):
    """
    Returns the decoder model used for PhiForCausalLM.

    Args:
        self: An instance of the PhiForCausalLM class.

    Returns:
        None.

    Raises:
        None.

    This method retrieves the decoder model that is used for PhiForCausalLM. The decoder model is an essential component
    of the PhiForCausalLM class and is responsible for generating output based on the input data. The decoder model
    contains the learned weights and biases that enable the PhiForCausalLM class to perform its tasks effectively.
    The returned decoder model is of type 'None' as it is used internally within the PhiForCausalLM class and is not
    intended to be directly accessed or modified by the user.
    """
    return self.model

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.get_input_embeddings()

Method to retrieve the input embeddings from the PhiForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the PhiForCausalLM class. Represents the current object instance.

TYPE: PhiForCausalLM

RETURNS DESCRIPTION
embed_tokens

This method returns the input embeddings as obtained from the model's embed_tokens attribute.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from the PhiForCausalLM model.

    Args:
        self (PhiForCausalLM): An instance of the PhiForCausalLM class.
            Represents the current object instance.

    Returns:
        embed_tokens: This method returns the input embeddings as obtained from the model's embed_tokens attribute.

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

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.get_output_embeddings()

Returns the output embeddings for the PhiForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the PhiForCausalLM class.

RETURNS DESCRIPTION
None

The method returns the output embeddings for the PhiForCausalLM model. These embeddings are used to map the output tokens to a continuous representation.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
def get_output_embeddings(self):
    """
    Returns the output embeddings for the PhiForCausalLM model.

    Args:
        self: An instance of the PhiForCausalLM class.

    Returns:
        None: The method returns the output embeddings for the PhiForCausalLM model.
            These embeddings are used to map the output tokens to a continuous representation.

    Raises:
        None.
    """
    return self.lm_head

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.prepare_inputs_for_generation(input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs)

Prepares inputs for generating output sequences using PhiForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of PhiForCausalLM class.

TYPE: PhiForCausalLM

input_ids

A tensor of shape (batch_size, sequence_length) containing input sequence tokens.

TYPE: Tensor

past_key_values

A cache object or tuple of two tensors containing previously computed key and value pairs for the attention mechanism. If None, no caching is performed.

TYPE: Cache or tuple or None DEFAULT: None

attention_mask

An optional tensor of shape (batch_size, sequence_length) containing a mask to avoid performing attention on padding tokens.

TYPE: Tensor or None DEFAULT: None

inputs_embeds

An optional tensor of shape (batch_size, sequence_length, hidden_size) containing precomputed embeddings for the input sequence.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
model_inputs

A dictionary containing the following keys:

  • 'input_ids': The input sequence tokens tensor.
  • 'position_ids': The tensor of positional encoding for the input sequence.
  • 'past_key_values': The cache object or tuple of two tensors containing previously computed key and value pairs for the attention mechanism.
  • 'use_cache': A boolean indicating whether to use caching.
  • 'attention_mask': The tensor containing the attention mask for the input sequence.

TYPE: dict

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
def prepare_inputs_for_generation(
    self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
):
    """
    Prepares inputs for generating output sequences using PhiForCausalLM model.

    Args:
        self (PhiForCausalLM): An instance of PhiForCausalLM class.
        input_ids (torch.Tensor): A tensor of shape (batch_size, sequence_length) containing input sequence tokens.
        past_key_values (Cache or tuple or None): A cache object or tuple of two tensors containing previously
            computed key and value pairs for the attention mechanism. If None, no caching is performed.
        attention_mask (torch.Tensor or None): An optional tensor of shape (batch_size, sequence_length)
            containing a mask to avoid performing attention on padding tokens.
        inputs_embeds (torch.Tensor or None): An optional tensor of shape (batch_size, sequence_length, hidden_size)
            containing precomputed embeddings for the input sequence.

    Returns:
        model_inputs (dict):
            A dictionary containing the following keys:

            - 'input_ids': The input sequence tokens tensor.
            - 'position_ids': The tensor of positional encoding for the input sequence.
            - 'past_key_values': The cache object or tuple of two tensors containing previously computed key and
            value pairs for the attention mechanism.
            - 'use_cache': A boolean indicating whether to use caching.
            - 'attention_mask': The tensor containing the attention mask for the input sequence.

    Raises:
        None.
    """
    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.phi.modeling_phi.PhiForCausalLM.set_decoder(decoder)

PARAMETER DESCRIPTION
self

The instance of the PhiForCausalLM class.

TYPE: PhiForCausalLM

decoder

The decoder object to be set for the model. It should be an instance of the decoder class.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
def set_decoder(self, decoder):
    """
    Args:
        self (PhiForCausalLM): The instance of the PhiForCausalLM class.
        decoder: The decoder object to be set for the model. It should be an instance of the decoder class.

    Returns:
        None.

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

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.set_input_embeddings(value)

This method sets the input embeddings for the PhiForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the PhiForCausalLM class.

TYPE: PhiForCausalLM

value

The input embeddings to be set for the model. It should be a tensor of appropriate shape and type.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
def set_input_embeddings(self, value):
    """
    This method sets the input embeddings for the PhiForCausalLM model.

    Args:
        self (PhiForCausalLM): The instance of the PhiForCausalLM class.
        value (Tensor): The input embeddings to be set for the model.
            It should be a tensor of appropriate shape and type.

    Returns:
        None.

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

mindnlp.transformers.models.phi.modeling_phi.PhiForCausalLM.set_output_embeddings(new_embeddings)

Sets the output embeddings for the PhiForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the PhiForCausalLM class.

TYPE: PhiForCausalLM

new_embeddings

The new embeddings to be set as the model's output embeddings. It should be a tensor of shape (vocab_size, hidden_size) where 'vocab_size' represents the size of the vocabulary and 'hidden_size' represents the size of the hidden layer. The new embeddings should be compatible with the model's existing architecture.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
def set_output_embeddings(self, new_embeddings):
    """
    Sets the output embeddings for the PhiForCausalLM model.

    Args:
        self (PhiForCausalLM): The instance of the PhiForCausalLM class.
        new_embeddings: The new embeddings to be set as the model's output embeddings.
            It should be a tensor of shape (vocab_size, hidden_size) where 'vocab_size'
            represents the size of the vocabulary and 'hidden_size' represents the size
            of the hidden layer. The new embeddings should be compatible with the model's
            existing architecture.

    Returns:
        None.

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

mindnlp.transformers.models.phi.modeling_phi.PhiForSequenceClassification

Bases: PhiPreTrainedModel

PhiForSequenceClassification

This class is a sequence classification model that uses the PHI algorithm for natural language processing tasks. It inherits from the PhiPreTrainedModel class.

ATTRIBUTE DESCRIPTION
config

The model configuration class instance.

TYPE: PhiConfig

num_labels

The number of labels for the classification task.

TYPE: int

model

The PHI model for token embeddings.

TYPE: PhiModel

score

The dense layer for scoring hidden states.

TYPE: Linear

METHOD DESCRIPTION
__init__

Initializes a new PhiForSequenceClassification instance.

get_input_embeddings

Retrieves the input embeddings from the model.

set_input_embeddings

Sets the input embeddings for the model.

forward

Constructs the model for sequence classification.

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

    """PhiForSequenceClassification

    This class is a sequence classification model that uses the PHI algorithm for natural language processing tasks.
    It inherits from the PhiPreTrainedModel class.

    Attributes:
        config (PhiConfig): The model configuration class instance.
        num_labels (int): The number of labels for the classification task.
        model (PhiModel): The PHI model for token embeddings.
        score (nn.Linear): The dense layer for scoring hidden states.

    Methods:
        __init__: Initializes a new PhiForSequenceClassification instance.
        get_input_embeddings: Retrieves the input embeddings from the model.
        set_input_embeddings: Sets the input embeddings for the model.
        forward: Constructs the model for sequence classification.

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

        Args:
            self: The instance of the class.
            config:
                An object containing configuration parameters for the model.

                - Type: object
                - Purpose: Configuration object specifying the model's settings.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

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

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

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

        Raises:
            None: This method does not raise any exceptions.
        """
        return self.model.embed_tokens

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

        Args:
            self (PhiForSequenceClassification): The instance of the PhiForSequenceClassification class.
            value (Tensor): The new input embeddings tensor to be set for the model.

        Returns:
            None.

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

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

        model_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 = model_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,) + model_outputs[1:]
            return ((loss,) + output) if loss is not None else output

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

mindnlp.transformers.models.phi.modeling_phi.PhiForSequenceClassification.__init__(config)

Initializes a new instance of the PhiForSequenceClassification class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing configuration parameters for the model.

  • Type: object
  • Purpose: Configuration object specifying the model's settings.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

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

    Args:
        self: The instance of the class.
        config:
            An object containing configuration parameters for the model.

            - Type: object
            - Purpose: Configuration object specifying the model's settings.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.model = PhiModel(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.phi.modeling_phi.PhiForSequenceClassification.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/phi/modeling_phi.py
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
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

    model_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 = model_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,) + model_outputs[1:]
        return ((loss,) + output) if loss is not None else output

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

mindnlp.transformers.models.phi.modeling_phi.PhiForSequenceClassification.get_input_embeddings()

Retrieves the input embeddings from the PhiForSequenceClassification model.

PARAMETER DESCRIPTION
self

The instance of the PhiForSequenceClassification class.

TYPE: PhiForSequenceClassification

RETURNS DESCRIPTION
None

This method does not return any value.

RAISES DESCRIPTION
None

This method does not raise any exceptions.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
def get_input_embeddings(self):
    """
    Retrieves the input embeddings from the PhiForSequenceClassification model.

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

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

    Raises:
        None: This method does not raise any exceptions.
    """
    return self.model.embed_tokens

mindnlp.transformers.models.phi.modeling_phi.PhiForSequenceClassification.set_input_embeddings(value)

Sets the input embeddings for the PhiForSequenceClassification model.

PARAMETER DESCRIPTION
self

The instance of the PhiForSequenceClassification class.

TYPE: PhiForSequenceClassification

value

The new input embeddings tensor to be set for the model.

TYPE: Tensor

RETURNS DESCRIPTION

None.

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

    Args:
        self (PhiForSequenceClassification): The instance of the PhiForSequenceClassification class.
        value (Tensor): The new input embeddings tensor to be set for the model.

    Returns:
        None.

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

mindnlp.transformers.models.phi.modeling_phi.PhiForTokenClassification

Bases: PhiPreTrainedModel

This class represents a PhiForTokenClassification model, which is used for token classification tasks such as Named Entity Recognition (NER) or Part-of-Speech (POS) tagging. It is a subclass of the PhiPreTrainedModel.

The PhiForTokenClassification class initializes with a PhiConfig object, which contains the configuration parameters for the model. It sets the number of labels for the classification task and creates an instance of the PhiModel based on the provided configuration.

The class also handles the initialization of the classifier dropout, which can be set either through the 'classifier_dropout' parameter in the config or the 'hidden_dropout' parameter. If neither is provided, a default dropout rate of 0.1 is used.

The 'forward' method is used to perform the forward pass of the model. It takes several input tensors such as 'input_ids', 'past_key_values', 'attention_mask', 'inputs_embeds', and 'labels'. It also supports various optional arguments such as 'use_cache', 'output_attentions', 'output_hidden_states', and 'return_dict'.

The 'labels' tensor is optional and represents the ground truth labels for computing the sequence classification/regression loss. The indices in 'labels' should be in the range of [0, config.num_labels - 1]. If 'config.num_labels == 1', a regression loss (Mean-Square loss) is computed. If 'config.num_labels > 1', a classification loss (Cross-Entropy) is computed.

The 'forward' method returns either a tuple of logits and other model outputs or a TokenClassifierOutput object depending on the 'return_dict' parameter. If 'labels' are provided, the method also computes the loss using the logits and the ground truth labels.

Please note that the class inherits additional functionality and attributes from the PhiPreTrainedModel superclass.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
class PhiForTokenClassification(PhiPreTrainedModel):

    """
    This class represents a PhiForTokenClassification model, which is used for token classification tasks such as
    Named Entity Recognition (NER) or Part-of-Speech (POS) tagging. It is a subclass of the PhiPreTrainedModel.

    The PhiForTokenClassification class initializes with a PhiConfig object, which contains the configuration parameters
    for the model. It sets the number of labels for the classification task and creates an instance of the PhiModel
    based on the provided configuration.

    The class also handles the initialization of the classifier dropout, which can be set either through the
    'classifier_dropout' parameter in the config or the 'hidden_dropout' parameter. If neither is provided, a default
    dropout rate of 0.1 is used.

    The 'forward' method is used to perform the forward pass of the model. It takes several input tensors such as
    'input_ids', 'past_key_values', 'attention_mask', 'inputs_embeds', and 'labels'. It also supports various optional
    arguments such as 'use_cache', 'output_attentions', 'output_hidden_states', and 'return_dict'.

    The 'labels' tensor is optional and represents the ground truth labels for computing the sequence
    classification/regression loss. The indices in 'labels' should be in the range of [0, config.num_labels - 1].
    If 'config.num_labels == 1', a regression loss (Mean-Square loss) is computed. If 'config.num_labels > 1',
    a classification loss (Cross-Entropy) is computed.

    The 'forward' method returns either a tuple of logits and other model outputs or a TokenClassifierOutput object
    depending on the 'return_dict' parameter. If 'labels' are provided, the method also computes the loss using the
    logits and the ground truth labels.

    Please note that the class inherits additional functionality and attributes from the PhiPreTrainedModel superclass.

    """
    def __init__(self, config: PhiConfig):
        """
        Initializes a new instance of the PhiForTokenClassification class.

        Args:
            self: The object itself.
            config (PhiConfig): The configuration object for PhiForTokenClassification.
                This object contains various parameters for configuring the model.
                The config parameter is required and cannot be None.

        Returns:
            None

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

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

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        **deprecated_arguments,
    ) -> Union[Tuple[mindspore.Tensor], TokenClassifierOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
                config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
                `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        model_outputs = self.model(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

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

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

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

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

mindnlp.transformers.models.phi.modeling_phi.PhiForTokenClassification.__init__(config)

Initializes a new instance of the PhiForTokenClassification class.

PARAMETER DESCRIPTION
self

The object itself.

config

The configuration object for PhiForTokenClassification. This object contains various parameters for configuring the model. The config parameter is required and cannot be None.

TYPE: PhiConfig

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
def __init__(self, config: PhiConfig):
    """
    Initializes a new instance of the PhiForTokenClassification class.

    Args:
        self: The object itself.
        config (PhiConfig): The configuration object for PhiForTokenClassification.
            This object contains various parameters for configuring the model.
            The config parameter is required and cannot be None.

    Returns:
        None

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

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

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

mindnlp.transformers.models.phi.modeling_phi.PhiForTokenClassification.forward(input_ids=None, past_key_values=None, attention_mask=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, **deprecated_arguments)

PARAMETER DESCRIPTION
labels

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

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

Source code in mindnlp/transformers/models/phi/modeling_phi.py
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[mindspore.Tensor, mindspore.Tensor], ...]] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
    **deprecated_arguments,
) -> Union[Tuple[mindspore.Tensor], TokenClassifierOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    model_outputs = self.model(
        input_ids,
        past_key_values=past_key_values,
        attention_mask=attention_mask,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

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

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

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

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

mindnlp.transformers.models.phi.modeling_phi.PhiLinearScalingRotaryEmbedding

Bases: PhiRotaryEmbedding

PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev

Source code in mindnlp/transformers/models/phi/modeling_phi.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
    """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
    def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
        """
        Initializes the PhiLinearScalingRotaryEmbedding object.

        Args:
            self: The object itself.
            dim (int): The dimension of the embedding.
            max_position_embeddings (int, optional): The maximum number of position embeddings. Defaults to 2048.
            base (int, optional): The base value for calculations. Defaults to 10000.
            scaling_factor (float, optional): The scaling factor applied to the embeddings. Defaults to 1.0.

        Returns:
            None.

        Raises:
            None.
        """
        self.scaling_factor = scaling_factor
        super().__init__(dim, max_position_embeddings, base)

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

        Args:
            self: The PhiLinearScalingRotaryEmbedding instance.
            seq_len (int): The maximum sequence length to cache.
            dtype: The data type of the cache.

        Returns:
            None.

        Raises:
            None.

        This method sets the cosine and sine cache for the PhiLinearScalingRotaryEmbedding layer.
        It creates an array of range values from 0 to the maximum sequence length and divides it by the scaling factor.
        It then creates an array of frequencies by taking the outer product of the range values and the inverse
        frequency values. The cosine and sine of the frequencies are then computed and stored in the cache. The
        maximum sequence length cached is stored in the instance variable max_seq_len_cached."""
        self.max_seq_len_cached = seq_len
        t = ops.arange(self.max_seq_len_cached, dtype=self.inv_freq.dtype)
        t = t / self.scaling_factor

        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)

mindnlp.transformers.models.phi.modeling_phi.PhiLinearScalingRotaryEmbedding.__init__(dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0)

Initializes the PhiLinearScalingRotaryEmbedding object.

PARAMETER DESCRIPTION
self

The object itself.

dim

The dimension of the embedding.

TYPE: int

max_position_embeddings

The maximum number of position embeddings. Defaults to 2048.

TYPE: int DEFAULT: 2048

base

The base value for calculations. Defaults to 10000.

TYPE: int DEFAULT: 10000

scaling_factor

The scaling factor applied to the embeddings. Defaults to 1.0.

TYPE: float DEFAULT: 1.0

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=1.0):
    """
    Initializes the PhiLinearScalingRotaryEmbedding object.

    Args:
        self: The object itself.
        dim (int): The dimension of the embedding.
        max_position_embeddings (int, optional): The maximum number of position embeddings. Defaults to 2048.
        base (int, optional): The base value for calculations. Defaults to 10000.
        scaling_factor (float, optional): The scaling factor applied to the embeddings. Defaults to 1.0.

    Returns:
        None.

    Raises:
        None.
    """
    self.scaling_factor = scaling_factor
    super().__init__(dim, max_position_embeddings, base)

mindnlp.transformers.models.phi.modeling_phi.PhiMLP

Bases: Module

PhiMLP represents a Multi-Layer Perceptron (MLP) neural network with configurable hidden layer sizes and activation functions.

This class inherits from nn.Module and implements the forward pass of the MLP by defining the layers and activation functions.

ATTRIBUTE DESCRIPTION
config

A configuration object that specifies the MLP architecture parameters.

TYPE: object

activation_fn

The activation function used in the hidden layers of the MLP.

TYPE: function

fc1

The first fully connected layer of the MLP.

TYPE: Linear

fc2

The second fully connected layer of the MLP.

TYPE: Linear

METHOD DESCRIPTION
__init__

Initializes the PhiMLP instance with the provided configuration.

forward

Constructs the forward pass of the MLP using the provided input tensor.

RETURNS DESCRIPTION

mindspore.Tensor: The output tensor of the forward pass through the MLP.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
class PhiMLP(nn.Module):

    """
    PhiMLP represents a Multi-Layer Perceptron (MLP) neural network with configurable hidden layer sizes and
    activation functions.

    This class inherits from nn.Module and implements the forward pass of the MLP by defining the layers and
    activation functions.

    Attributes:
        config (object): A configuration object that specifies the MLP architecture parameters.
        activation_fn (function): The activation function used in the hidden layers of the MLP.
        fc1 (nn.Linear): The first fully connected layer of the MLP.
        fc2 (nn.Linear): The second fully connected layer of the MLP.

    Methods:
        __init__:
            Initializes the PhiMLP instance with the provided configuration.

        forward:
            Constructs the forward pass of the MLP using the provided input tensor.

    Returns:
        mindspore.Tensor: The output tensor of the forward pass through the MLP.
    """
    def __init__(self, config):
        """
        Initializes an instance of the PhiMLP class.

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

                - Type: Custom object
                - Purpose: Stores various configuration parameters for the model.
                - Restrictions: None

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.config = config
        self.activation_fn = ACT2FN[config.hidden_act]
        self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
        self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs the forward pass of the PhiMLP model.

        Args:
            self (PhiMLP): The instance of the PhiMLP class.
            hidden_states (mindspore.Tensor): The input hidden states tensor to be processed.
                The shape of the hidden_states tensor should be compatible with the model's architecture.

        Returns:
            mindspore.Tensor: The tensor resulting from the forward pass through the PhiMLP model.

        Raises:
            TypeError: If the input hidden_states is not of type mindspore.Tensor.
            ValueError: If the shape of the hidden_states tensor is incompatible with the model's architecture.
        """
        hidden_states = self.fc1(hidden_states)
        hidden_states = self.activation_fn(hidden_states)
        hidden_states = self.fc2(hidden_states)
        return hidden_states

mindnlp.transformers.models.phi.modeling_phi.PhiMLP.__init__(config)

Initializes an instance of the PhiMLP class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing configuration parameters for the PhiMLP model.

  • Type: Custom object
  • Purpose: Stores various configuration parameters for the model.
  • Restrictions: None

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def __init__(self, config):
    """
    Initializes an instance of the PhiMLP class.

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

            - Type: Custom object
            - Purpose: Stores various configuration parameters for the model.
            - Restrictions: None

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.config = config
    self.activation_fn = ACT2FN[config.hidden_act]
    self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
    self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)

mindnlp.transformers.models.phi.modeling_phi.PhiMLP.forward(hidden_states)

Constructs the forward pass of the PhiMLP model.

PARAMETER DESCRIPTION
self

The instance of the PhiMLP class.

TYPE: PhiMLP

hidden_states

The input hidden states tensor to be processed. The shape of the hidden_states tensor should be compatible with the model's architecture.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The tensor resulting from the forward pass through the PhiMLP model.

RAISES DESCRIPTION
TypeError

If the input hidden_states is not of type mindspore.Tensor.

ValueError

If the shape of the hidden_states tensor is incompatible with the model's architecture.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs the forward pass of the PhiMLP model.

    Args:
        self (PhiMLP): The instance of the PhiMLP class.
        hidden_states (mindspore.Tensor): The input hidden states tensor to be processed.
            The shape of the hidden_states tensor should be compatible with the model's architecture.

    Returns:
        mindspore.Tensor: The tensor resulting from the forward pass through the PhiMLP model.

    Raises:
        TypeError: If the input hidden_states is not of type mindspore.Tensor.
        ValueError: If the shape of the hidden_states tensor is incompatible with the model's architecture.
    """
    hidden_states = self.fc1(hidden_states)
    hidden_states = self.activation_fn(hidden_states)
    hidden_states = self.fc2(hidden_states)
    return hidden_states

mindnlp.transformers.models.phi.modeling_phi.PhiModel

Bases: PhiPreTrainedModel

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

PARAMETER DESCRIPTION
config

PhiConfig

TYPE: PhiConfig

Source code in mindnlp/transformers/models/phi/modeling_phi.py
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
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
class PhiModel(PhiPreTrainedModel):
    """
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]

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

        Args:
            self: The instance of the PhiModel class.
            config (PhiConfig):
                The configuration object containing the model's hyperparameters and settings.

                `config` is of type PhiConfig.
                It specifies the configuration for the PhiModel.
                This object is used to set various attributes of the PhiModel instance.
                The attributes set are:

                - `padding_idx`: The index to use for padding in the input sequence.
                It is initialized with the value of `config.pad_token_id`.
                - `vocab_size`: The size of the vocabulary, i.e., the total number of unique tokens.
                It is initialized with the value of `config.vocab_size`.
                - `embed_tokens`: The embedding layer for the input tokens.
                It is an instance of `nn.Embedding` and is initialized with the values:

                    - `config.vocab_size`: The size of the vocabulary.
                    - `config.hidden_size`: The dimensionality of the hidden state.
                    - `self.padding_idx`: The index used for padding.

                - `embed_dropout`: The dropout layer applied to the input embeddings.
                It is an instance of `nn.Dropout` and is initialized with the dropout probability `config.embd_pdrop`.
                - `layers`: A list of PhiDecoderLayer instances representing the decoder layers of the model.
                It is initialized as a `nn.ModuleList` containing `config.num_hidden_layers` PhiDecoderLayer instances.
                Each PhiDecoderLayer instance is created using the `PhiDecoderLayer` forwardor with `config` and `layer_idx`.
                - `final_layernorm`: The layer normalization applied to the final hidden state.
                It is an instance of `nn.LayerNorm` and is initialized with the following attributes:

                    - `[config.hidden_size]`: The normalized shape of the input tensor.
                    - `epsilon=config.layer_norm_eps`: The epsilon value added to the denominator for numerical stability.

                - `gradient_checkpointing`: A boolean flag indicating whether gradient checkpointing is enabled.
                It is initialized as `False`.

        Raises:
            None.

        Returns:
            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.embed_dropout = nn.Dropout(p=config.embd_pdrop)
        self.layers = nn.ModuleList(
            [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.final_layernorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)

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

    def get_input_embeddings(self):
        """
        Returns the input embeddings for the PhiModel.

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

        Returns:
            None.

        Raises:
            None.
        """
        return self.embed_tokens

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

        Args:
            self (PhiModel): The instance of the PhiModel class.
            value: The input embeddings to be set for the PhiModel.
                It should be a tensor or an object that can be assigned to self.embed_tokens.

        Returns:
            None.

        Raises:
            TypeError: If the provided value is not compatible with the expected input embeddings format.
            ValueError: If the provided value is empty or invalid.
        """
        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 PhiModel using the specified input parameters and returns the output as a tuple or
        a BaseModelOutputWithPast object.

        Args:
            self: The instance of the class.
            input_ids (mindspore.Tensor, optional): The input tensor containing the token ids for the model input.
                Defaults to None.
            attention_mask (mindspore.Tensor, optional): An optional tensor providing the attention mask for the input.
                Defaults to None.
            position_ids (mindspore.Tensor, optional): An optional tensor representing the position ids for the input.
                Defaults to None.
            past_key_values (List[mindspore.Tensor], optional): An optional list of tensors containing the past key values.
                Defaults to None.
            inputs_embeds (mindspore.Tensor, optional): An optional tensor representing the embedded inputs.
                Defaults to None.
            use_cache (bool, optional): An optional boolean flag indicating whether to use caching. Defaults to None.
            output_attentions (bool, optional): An optional boolean flag indicating whether to output attentions.
                Defaults to None.
            output_hidden_states (bool, optional): An optional boolean flag indicating whether to output hidden states.
                Defaults to None.
            return_dict (bool, optional): An optional boolean flag indicating whether to return a dictionary.
                Defaults to None.

        Returns:
            Union[Tuple, BaseModelOutputWithPast]: The output is either a tuple containing the hidden states,
                next_cache, all_hidden_states, and all_self_attns or a BaseModelOutputWithPast object containing
                the last hidden state, past key values, hidden states, and attentions.

        Raises:
            ValueError: Raised if both input_ids and inputs_embeds are specified simultaneously or if neither input_ids
                nor inputs_embeds are specified.
            Warning: If `use_cache=True` is incompatible with gradient checkpointing, a warning is raised to indicate
                that `use_cache` will be set to False.
        """
        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 input_ids and inputs_embeds at the same time")
        if input_ids is not None:
            batch_size, seq_length = input_ids.shape[:2]
        elif inputs_embeds is not None:
            batch_size, seq_length = inputs_embeds.shape[:2]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        past_key_values_length = 0

        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

        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)

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

        inputs_embeds = self.embed_dropout(inputs_embeds)

        # Attention mask.
        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

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

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

        hidden_states = self.final_layernorm(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 BaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=next_cache,
            hidden_states=all_hidden_states,
            attentions=all_self_attns,
        )

mindnlp.transformers.models.phi.modeling_phi.PhiModel.__init__(config)

Initializes an instance of the PhiModel class.

PARAMETER DESCRIPTION
self

The instance of the PhiModel class.

config

The configuration object containing the model's hyperparameters and settings.

config is of type PhiConfig. It specifies the configuration for the PhiModel. This object is used to set various attributes of the PhiModel instance. The attributes set are:

  • padding_idx: The index to use for padding in the input sequence. It is initialized with the value of config.pad_token_id.
  • vocab_size: The size of the vocabulary, i.e., the total number of unique tokens. It is initialized with the value of config.vocab_size.
  • embed_tokens: The embedding layer for the input tokens. It is an instance of nn.Embedding and is initialized with the values:

    • config.vocab_size: The size of the vocabulary.
    • config.hidden_size: The dimensionality of the hidden state.
    • self.padding_idx: The index used for padding.
  • embed_dropout: The dropout layer applied to the input embeddings. It is an instance of nn.Dropout and is initialized with the dropout probability config.embd_pdrop.

  • layers: A list of PhiDecoderLayer instances representing the decoder layers of the model. It is initialized as a nn.ModuleList containing config.num_hidden_layers PhiDecoderLayer instances. Each PhiDecoderLayer instance is created using the PhiDecoderLayer forwardor with config and layer_idx.
  • final_layernorm: The layer normalization applied to the final hidden state. It is an instance of nn.LayerNorm and is initialized with the following attributes:

    • [config.hidden_size]: The normalized shape of the input tensor.
    • epsilon=config.layer_norm_eps: The epsilon value added to the denominator for numerical stability.
  • gradient_checkpointing: A boolean flag indicating whether gradient checkpointing is enabled. It is initialized as False.

TYPE: PhiConfig

RETURNS DESCRIPTION

None.

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

    Args:
        self: The instance of the PhiModel class.
        config (PhiConfig):
            The configuration object containing the model's hyperparameters and settings.

            `config` is of type PhiConfig.
            It specifies the configuration for the PhiModel.
            This object is used to set various attributes of the PhiModel instance.
            The attributes set are:

            - `padding_idx`: The index to use for padding in the input sequence.
            It is initialized with the value of `config.pad_token_id`.
            - `vocab_size`: The size of the vocabulary, i.e., the total number of unique tokens.
            It is initialized with the value of `config.vocab_size`.
            - `embed_tokens`: The embedding layer for the input tokens.
            It is an instance of `nn.Embedding` and is initialized with the values:

                - `config.vocab_size`: The size of the vocabulary.
                - `config.hidden_size`: The dimensionality of the hidden state.
                - `self.padding_idx`: The index used for padding.

            - `embed_dropout`: The dropout layer applied to the input embeddings.
            It is an instance of `nn.Dropout` and is initialized with the dropout probability `config.embd_pdrop`.
            - `layers`: A list of PhiDecoderLayer instances representing the decoder layers of the model.
            It is initialized as a `nn.ModuleList` containing `config.num_hidden_layers` PhiDecoderLayer instances.
            Each PhiDecoderLayer instance is created using the `PhiDecoderLayer` forwardor with `config` and `layer_idx`.
            - `final_layernorm`: The layer normalization applied to the final hidden state.
            It is an instance of `nn.LayerNorm` and is initialized with the following attributes:

                - `[config.hidden_size]`: The normalized shape of the input tensor.
                - `epsilon=config.layer_norm_eps`: The epsilon value added to the denominator for numerical stability.

            - `gradient_checkpointing`: A boolean flag indicating whether gradient checkpointing is enabled.
            It is initialized as `False`.

    Raises:
        None.

    Returns:
        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.embed_dropout = nn.Dropout(p=config.embd_pdrop)
    self.layers = nn.ModuleList(
        [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
    )
    self.final_layernorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)

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

mindnlp.transformers.models.phi.modeling_phi.PhiModel.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 PhiModel using the specified input parameters and returns the output as a tuple or a BaseModelOutputWithPast object.

PARAMETER DESCRIPTION
self

The instance of the class.

input_ids

The input tensor containing the token ids for the model input. Defaults to None.

TYPE: Tensor DEFAULT: None

attention_mask

An optional tensor providing the attention mask for the input. Defaults to None.

TYPE: Tensor DEFAULT: None

position_ids

An optional tensor representing the position ids for the input. Defaults to None.

TYPE: Tensor DEFAULT: None

past_key_values

An optional list of tensors containing the past key values. Defaults to None.

TYPE: List[Tensor] DEFAULT: None

inputs_embeds

An optional tensor representing the embedded inputs. Defaults to None.

TYPE: Tensor DEFAULT: None

use_cache

An optional boolean flag indicating whether to use caching. Defaults to None.

TYPE: bool DEFAULT: None

output_attentions

An optional boolean flag indicating whether to output attentions. Defaults to None.

TYPE: bool DEFAULT: None

output_hidden_states

An optional boolean flag indicating whether to output hidden states. Defaults to None.

TYPE: bool DEFAULT: None

return_dict

An optional boolean flag indicating whether to return a dictionary. Defaults to None.

TYPE: bool DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutputWithPast]

Union[Tuple, BaseModelOutputWithPast]: The output is either a tuple containing the hidden states, next_cache, all_hidden_states, and all_self_attns or a BaseModelOutputWithPast object containing the last hidden state, past key values, hidden states, and attentions.

RAISES DESCRIPTION
ValueError

Raised if both input_ids and inputs_embeds are specified simultaneously or if neither input_ids nor inputs_embeds are specified.

Warning

If use_cache=True is incompatible with gradient checkpointing, a warning is raised to indicate that use_cache will be set to False.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
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
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 PhiModel using the specified input parameters and returns the output as a tuple or
    a BaseModelOutputWithPast object.

    Args:
        self: The instance of the class.
        input_ids (mindspore.Tensor, optional): The input tensor containing the token ids for the model input.
            Defaults to None.
        attention_mask (mindspore.Tensor, optional): An optional tensor providing the attention mask for the input.
            Defaults to None.
        position_ids (mindspore.Tensor, optional): An optional tensor representing the position ids for the input.
            Defaults to None.
        past_key_values (List[mindspore.Tensor], optional): An optional list of tensors containing the past key values.
            Defaults to None.
        inputs_embeds (mindspore.Tensor, optional): An optional tensor representing the embedded inputs.
            Defaults to None.
        use_cache (bool, optional): An optional boolean flag indicating whether to use caching. Defaults to None.
        output_attentions (bool, optional): An optional boolean flag indicating whether to output attentions.
            Defaults to None.
        output_hidden_states (bool, optional): An optional boolean flag indicating whether to output hidden states.
            Defaults to None.
        return_dict (bool, optional): An optional boolean flag indicating whether to return a dictionary.
            Defaults to None.

    Returns:
        Union[Tuple, BaseModelOutputWithPast]: The output is either a tuple containing the hidden states,
            next_cache, all_hidden_states, and all_self_attns or a BaseModelOutputWithPast object containing
            the last hidden state, past key values, hidden states, and attentions.

    Raises:
        ValueError: Raised if both input_ids and inputs_embeds are specified simultaneously or if neither input_ids
            nor inputs_embeds are specified.
        Warning: If `use_cache=True` is incompatible with gradient checkpointing, a warning is raised to indicate
            that `use_cache` will be set to False.
    """
    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 input_ids and inputs_embeds at the same time")
    if input_ids is not None:
        batch_size, seq_length = input_ids.shape[:2]
    elif inputs_embeds is not None:
        batch_size, seq_length = inputs_embeds.shape[:2]
    else:
        raise ValueError("You have to specify either input_ids or inputs_embeds")

    past_key_values_length = 0

    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

    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)

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

    inputs_embeds = self.embed_dropout(inputs_embeds)

    # Attention mask.
    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

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

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

    hidden_states = self.final_layernorm(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 BaseModelOutputWithPast(
        last_hidden_state=hidden_states,
        past_key_values=next_cache,
        hidden_states=all_hidden_states,
        attentions=all_self_attns,
    )

mindnlp.transformers.models.phi.modeling_phi.PhiModel.get_input_embeddings()

Returns the input embeddings for the PhiModel.

PARAMETER DESCRIPTION
self

The instance of the PhiModel class.

TYPE: PhiModel

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
913
914
915
916
917
918
919
920
921
922
923
924
925
926
def get_input_embeddings(self):
    """
    Returns the input embeddings for the PhiModel.

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

    Returns:
        None.

    Raises:
        None.
    """
    return self.embed_tokens

mindnlp.transformers.models.phi.modeling_phi.PhiModel.set_input_embeddings(value)

Set the input embeddings for the PhiModel.

PARAMETER DESCRIPTION
self

The instance of the PhiModel class.

TYPE: PhiModel

value

The input embeddings to be set for the PhiModel. It should be a tensor or an object that can be assigned to self.embed_tokens.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the provided value is not compatible with the expected input embeddings format.

ValueError

If the provided value is empty or invalid.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the PhiModel.

    Args:
        self (PhiModel): The instance of the PhiModel class.
        value: The input embeddings to be set for the PhiModel.
            It should be a tensor or an object that can be assigned to self.embed_tokens.

    Returns:
        None.

    Raises:
        TypeError: If the provided value is not compatible with the expected input embeddings format.
        ValueError: If the provided value is empty or invalid.
    """
    self.embed_tokens = value

mindnlp.transformers.models.phi.modeling_phi.PhiPreTrainedModel

Bases: PreTrainedModel

This class represents a PhiPreTrainedModel, which is a subclass of PreTrainedModel. It is designed for pre-training models using the Phi framework.

The class includes a method called _init_weights which initializes the weights of the model's cells. The method takes a cell object as an argument and sets the weights and biases for the cell based on the configuration settings.

If the cell is an instance of nn.Linear, the method sets the weight data using the initializer function with a normal distribution and the specified standard deviation. It also sets the bias data to zeros if the cell has a bias.

If the cell is an instance of nn.Embedding, the method generates random weight values from a normal distribution with a mean of 0 and the specified standard deviation. If the cell has a padding index, the weight value at that index is set to 0. The weight data is then set for the cell.

Note

This docstring does not include signatures or any other code. Please refer to the actual code implementation for more details.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
class PhiPreTrainedModel(PreTrainedModel):

    """
    This class represents a PhiPreTrainedModel, which is a subclass of PreTrainedModel.
    It is designed for pre-training models using the Phi framework.

    The class includes a method called _init_weights which initializes the weights of the model's cells.
    The method takes a cell object as an argument and sets the weights and biases for the cell based on the
    configuration settings.

    If the cell is an instance of nn.Linear, the method sets the weight data using the initializer function with a
    normal distribution and the specified standard deviation. It also sets the bias data to zeros if the cell has a bias.

    If the cell is an instance of nn.Embedding, the method generates random weight values from a normal distribution
    with a mean of 0 and the specified standard deviation. If the cell has a padding index, the weight value at that
    index is set to 0. The weight data is then set for the cell.

    Note:
        This docstring does not include signatures or any other code. Please refer to the actual code implementation
        for more details.
    """
    config_class = PhiConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = False
    _no_split_modules = ["PhiDecoderLayer"]
    _supports_cache_class = True

    def _init_weights(self, cell):
        """
        Initializes the weights and biases of a neural network cell based on the specified configuration.

        Args:
            self (PhiPreTrainedModel): The instance of the PhiPreTrainedModel class.
            cell (nn.Module): The neural network cell for which the weights and biases are initialized.

        Returns:
            None.

        Raises:
            ValueError: If the cell type is neither nn.Linear nor nn.Embedding.
            TypeError: If the cell type is not recognized or if there are issues with setting the data for
                weights and biases.
            IndexError: If there are issues with indexing while setting the weight values.
        """
        std = self.config.initializer_range
        if isinstance(cell, nn.Linear):
            cell.weight.set_data(initializer(Normal(std), cell.weight.shape, cell.weight.dtype))
            if cell.bias:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.Embedding):
            weight = np.random.normal(0.0, std, cell.weight.shape)
            if cell.padding_idx:
                weight[cell.padding_idx] = 0

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

mindnlp.transformers.models.phi.modeling_phi.PhiRotaryEmbedding

Bases: Module

The PhiRotaryEmbedding class represents a rotational positional embedding for neural network models. It inherits from nn.Module and provides functionality for forwarding rotational embeddings based on input sequences and sequence lengths.

ATTRIBUTE DESCRIPTION
dim

The dimension of the rotational positional embedding.

TYPE: int

max_position_embeddings

The maximum position embeddings allowed.

TYPE: int

base

The base value used in the rotational embedding calculation.

TYPE: int

inv_freq

The inverse frequency used in the rotational embedding calculation.

TYPE: Tensor

max_seq_len_cached

The maximum sequence length for which the cosine and sine cache is precomputed.

TYPE: int

cos_cached

Precomputed cosine values for positional embeddings.

TYPE: Tensor

sin_cached

Precomputed sine values for positional embeddings.

TYPE: Tensor

METHOD DESCRIPTION
_set_cos_sin_cache

Precomputes and caches cosine and sine values for positional embeddings based on the specified sequence length and data type.

forward

Constructs the rotational positional embedding for the input sequence based on the specified sequence length or the maximum cached sequence length.

Note

This docstring is based on the provided code snippet and may need additional details or context to fully describe the class and its functionality.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class PhiRotaryEmbedding(nn.Module):

    """
    The PhiRotaryEmbedding class represents a rotational positional embedding for neural network models.
    It inherits from nn.Module and provides functionality for forwarding rotational embeddings based on
    input sequences and sequence lengths.

    Attributes:
        dim (int): The dimension of the rotational positional embedding.
        max_position_embeddings (int): The maximum position embeddings allowed.
        base (int): The base value used in the rotational embedding calculation.
        inv_freq (Tensor): The inverse frequency used in the rotational embedding calculation.
        max_seq_len_cached (int): The maximum sequence length for which the cosine and sine cache is precomputed.
        cos_cached (Tensor): Precomputed cosine values for positional embeddings.
        sin_cached (Tensor): Precomputed sine values for positional embeddings.

    Methods:
        _set_cos_sin_cache:
            Precomputes and caches cosine and sine values for positional embeddings based on the specified sequence
            length and data type.

        forward:
            Constructs the rotational positional embedding for the input sequence based on the specified sequence
            length or the maximum cached sequence length.

    Note:
        This docstring is based on the provided code snippet and may need additional details or context to fully
        describe the class and its functionality.
    """
    def __init__(self, dim, max_position_embeddings=2048, base=10000):
        """
        Initializes an instance of the PhiRotaryEmbedding class.

        Args:
            self: The instance of the class.
            dim (int): The dimensionality of the embeddings.
            max_position_embeddings (int, optional): The maximum number of position embeddings to generate. 
                Default is 2048.
            base (int, optional): The base value used in the calculation. Default is 10000.

        Returns:
            None.

        Raises:
            ValueError: If dim is not a positive integer.
            ValueError: If max_position_embeddings is not a positive integer.
            ValueError: If base is not a positive 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).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 PhiRotaryEmbedding.

        This method sets the cosine and sine cache for PhiRotaryEmbedding based on the given sequence 
        length and data type.

        Args:
            self (PhiRotaryEmbedding): The PhiRotaryEmbedding instance.
            seq_len (int): The length of the sequence.
            dtype (torch.dtype): The desired data type for the cache.

        Returns:
            None.

        Raises:
            None.
        """
        self.max_seq_len_cached = seq_len
        t = ops.arange(self.max_seq_len_cached, dtype=self.inv_freq.dtype)

        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):
        """
        Constructs a PhiRotaryEmbedding.

        Args:
            self (PhiRotaryEmbedding): The instance of the PhiRotaryEmbedding class.
            x: The input tensor.
            seq_len (int, optional): The length of the sequence. Defaults to None.

        Returns:
            None.

        Raises:
            ValueError: If `seq_len` is greater than `max_seq_len_cached`.

        This method forwards a PhiRotaryEmbedding by calculating and returning the cosine and sine cached values 
        based on the input tensor `x` and the provided sequence length `seq_len`. If `seq_len` is not specified, 
        the method returns the cosine and sine cached values for the entire sequence. 
        The returned values are converted to the same data type as `x`.

        If the specified `seq_len` is greater than the `max_seq_len_cached` value, the method internally updates the 
        cached values by calling the `_set_cos_sin_cache` method. This method should be called before accessing the 
        cached values to ensure they are up to date.

        Note that this method does not modify the instance's state and only returns the calculated cached values.
        """
        # 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.phi.modeling_phi.PhiRotaryEmbedding.__init__(dim, max_position_embeddings=2048, base=10000)

Initializes an instance of the PhiRotaryEmbedding class.

PARAMETER DESCRIPTION
self

The instance of the class.

dim

The dimensionality of the embeddings.

TYPE: int

max_position_embeddings

The maximum number of position embeddings to generate. Default is 2048.

TYPE: int DEFAULT: 2048

base

The base value used in the calculation. Default is 10000.

TYPE: int DEFAULT: 10000

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If dim is not a positive integer.

ValueError

If max_position_embeddings is not a positive integer.

ValueError

If base is not a positive integer.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
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
def __init__(self, dim, max_position_embeddings=2048, base=10000):
    """
    Initializes an instance of the PhiRotaryEmbedding class.

    Args:
        self: The instance of the class.
        dim (int): The dimensionality of the embeddings.
        max_position_embeddings (int, optional): The maximum number of position embeddings to generate. 
            Default is 2048.
        base (int, optional): The base value used in the calculation. Default is 10000.

    Returns:
        None.

    Raises:
        ValueError: If dim is not a positive integer.
        ValueError: If max_position_embeddings is not a positive integer.
        ValueError: If base is not a positive 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).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.phi.modeling_phi.PhiRotaryEmbedding.forward(x, seq_len=None)

Constructs a PhiRotaryEmbedding.

PARAMETER DESCRIPTION
self

The instance of the PhiRotaryEmbedding class.

TYPE: PhiRotaryEmbedding

x

The input tensor.

seq_len

The length of the sequence. Defaults to None.

TYPE: int DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If seq_len is greater than max_seq_len_cached.

This method forwards a PhiRotaryEmbedding by calculating and returning the cosine and sine cached values based on the input tensor x and the provided sequence length seq_len. If seq_len is not specified, the method returns the cosine and sine cached values for the entire sequence. The returned values are converted to the same data type as x.

If the specified seq_len is greater than the max_seq_len_cached value, the method internally updates the cached values by calling the _set_cos_sin_cache method. This method should be called before accessing the cached values to ensure they are up to date.

Note that this method does not modify the instance's state and only returns the calculated cached values.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def forward(self, x, seq_len=None):
    """
    Constructs a PhiRotaryEmbedding.

    Args:
        self (PhiRotaryEmbedding): The instance of the PhiRotaryEmbedding class.
        x: The input tensor.
        seq_len (int, optional): The length of the sequence. Defaults to None.

    Returns:
        None.

    Raises:
        ValueError: If `seq_len` is greater than `max_seq_len_cached`.

    This method forwards a PhiRotaryEmbedding by calculating and returning the cosine and sine cached values 
    based on the input tensor `x` and the provided sequence length `seq_len`. If `seq_len` is not specified, 
    the method returns the cosine and sine cached values for the entire sequence. 
    The returned values are converted to the same data type as `x`.

    If the specified `seq_len` is greater than the `max_seq_len_cached` value, the method internally updates the 
    cached values by calling the `_set_cos_sin_cache` method. This method should be called before accessing the 
    cached values to ensure they are up to date.

    Note that this method does not modify the instance's state and only returns the calculated cached values.
    """
    # 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.phi.modeling_phi.apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1)

Applies Rotary Position Embedding to the query and key tensors.

PARAMETER DESCRIPTION
q

The query tensor.

TYPE: `mindspore.Tensor`

k

The key tensor.

TYPE: `mindspore.Tensor`

cos

The cosine part of the rotary embedding.

TYPE: `mindspore.Tensor`

sin

The sine part of the rotary embedding.

TYPE: `mindspore.Tensor`

position_ids

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

RETURNS DESCRIPTION

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

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

    Args:
        q (`mindspore.Tensor`): The query tensor.
        k (`mindspore.Tensor`): The key tensor.
        cos (`mindspore.Tensor`): The cosine part of the rotary embedding.
        sin (`mindspore.Tensor`): The sine part of the rotary embedding.
        position_ids (`mindspore.Tensor`):
            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.phi.modeling_phi.repeat_kv(hidden_states, n_rep)

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

Source code in mindnlp/transformers/models/phi/modeling_phi.py
434
435
436
437
438
439
440
441
442
443
def repeat_kv(hidden_states: mindspore.Tensor, n_rep: int) -> mindspore.Tensor:
    """
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    """
    batch, num_key_value_heads, slen, head_dim = hidden_states.shape
    if n_rep == 1:
        return hidden_states
    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)

mindnlp.transformers.models.phi.modeling_phi.rotate_half(x)

Rotates half the hidden dims of the input.

Source code in mindnlp/transformers/models/phi/modeling_phi.py
324
325
326
327
def rotate_half(x):
    """Rotates half the hidden dims of the input."""
    x1, x2 = x.tensor_split(2, -1)
    return ops.cat((-x2, x1), axis=-1)