Skip to content

deberta_v2

mindnlp.transformers.models.deberta_v2.configuration_deberta_v2

DeBERTa-v2 model configuration

mindnlp.transformers.models.deberta_v2.configuration_deberta_v2.DebertaV2Config

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [DebertaV2Model]. It is used to instantiate a DeBERTa-v2 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 DeBERTa microsoft/deberta-v2-xlarge architecture.

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

PARAMETER DESCRIPTION
vocab_size

Vocabulary size of the DeBERTa-v2 model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [DebertaV2Model].

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

hidden_size

Dimensionality of the encoder layers and the pooler layer.

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

num_hidden_layers

Number of hidden layers in the Transformer encoder.

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

num_attention_heads

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

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

intermediate_size

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

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

hidden_act

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

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

hidden_dropout_prob

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

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

attention_probs_dropout_prob

The dropout ratio for the attention probabilities.

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

max_position_embeddings

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

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

type_vocab_size

The vocabulary size of the token_type_ids passed when calling [DebertaModel] or [TFDebertaModel].

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

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 layer normalization layers.

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

relative_attention

Whether use relative position encoding.

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

max_relative_positions

The range of relative positions [-max_position_embeddings, max_position_embeddings]. Use the same value as max_position_embeddings.

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

pad_token_id

The value used to pad input_ids.

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

position_biased_input

Whether add absolute position embedding to content embedding.

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

pos_att_type

The type of relative position attention, it can be a combination of ["p2c", "c2p"], e.g. ["p2c"], ["p2c", "c2p"], ["p2c", "c2p"].

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

layer_norm_eps

The epsilon used by the layer normalization layers.

TYPE: `float`, optional, defaults to 1e-12 DEFAULT: 1e-07

Example
>>> from transformers import DebertaV2Config, DebertaV2Model
...
>>> # Initializing a DeBERTa-v2 microsoft/deberta-v2-xlarge style configuration
>>> configuration = DebertaV2Config()
...
>>> # Initializing a model (with random weights) from the microsoft/deberta-v2-xlarge style configuration
>>> model = DebertaV2Model(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/deberta_v2/configuration_deberta_v2.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
class DebertaV2Config(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`DebertaV2Model`]. It is used to instantiate a
    DeBERTa-v2 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 DeBERTa
    [microsoft/deberta-v2-xlarge](https://huggingface.co/microsoft/deberta-v2-xlarge) architecture.

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

    Arguments:
        vocab_size (`int`, *optional*, defaults to 128100):
            Vocabulary size of the DeBERTa-v2 model. Defines the number of different tokens that can be represented by
            the `inputs_ids` passed when calling [`DebertaV2Model`].
        hidden_size (`int`, *optional*, defaults to 1536):
            Dimensionality of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 24):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 24):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (`int`, *optional*, defaults to 6144):
            Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
        hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"silu"`, `"gelu"`, `"tanh"`, `"gelu_fast"`, `"mish"`, `"linear"`, `"sigmoid"` and `"gelu_new"`
            are supported.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention probabilities.
        max_position_embeddings (`int`, *optional*, defaults to 512):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        type_vocab_size (`int`, *optional*, defaults to 0):
            The vocabulary size of the `token_type_ids` passed when calling [`DebertaModel`] or [`TFDebertaModel`].
        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-7):
            The epsilon used by the layer normalization layers.
        relative_attention (`bool`, *optional*, defaults to `True`):
            Whether use relative position encoding.
        max_relative_positions (`int`, *optional*, defaults to -1):
            The range of relative positions `[-max_position_embeddings, max_position_embeddings]`. Use the same value
            as `max_position_embeddings`.
        pad_token_id (`int`, *optional*, defaults to 0):
            The value used to pad input_ids.
        position_biased_input (`bool`, *optional*, defaults to `True`):
            Whether add absolute position embedding to content embedding.
        pos_att_type (`List[str]`, *optional*):
            The type of relative position attention, it can be a combination of `["p2c", "c2p"]`, e.g. `["p2c"]`,
            `["p2c", "c2p"]`, `["p2c", "c2p"]`.
        layer_norm_eps (`float`, optional, defaults to 1e-12):
            The epsilon used by the layer normalization layers.

    Example:
        ```python
        >>> from transformers import DebertaV2Config, DebertaV2Model
        ...
        >>> # Initializing a DeBERTa-v2 microsoft/deberta-v2-xlarge style configuration
        >>> configuration = DebertaV2Config()
        ...
        >>> # Initializing a model (with random weights) from the microsoft/deberta-v2-xlarge style configuration
        >>> model = DebertaV2Model(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """

    model_type = "deberta-v2"

    def __init__(
        self,
        vocab_size=128100,
        hidden_size=1536,
        num_hidden_layers=24,
        num_attention_heads=24,
        intermediate_size=6144,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=0,
        initializer_range=0.02,
        layer_norm_eps=1e-7,
        relative_attention=False,
        max_relative_positions=-1,
        pad_token_id=0,
        position_biased_input=True,
        pos_att_type=None,
        pooler_dropout=0,
        pooler_hidden_act="gelu",
        **kwargs,
    ):
        super().__init__(**kwargs)

        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.max_position_embeddings = max_position_embeddings
        self.type_vocab_size = type_vocab_size
        self.initializer_range = initializer_range
        self.relative_attention = relative_attention
        self.max_relative_positions = max_relative_positions
        self.pad_token_id = pad_token_id
        self.position_biased_input = position_biased_input

        # Backwards compatibility
        if isinstance(pos_att_type, str):
            pos_att_type = [x.strip() for x in pos_att_type.lower().split("|")]

        self.pos_att_type = pos_att_type
        self.vocab_size = vocab_size
        self.layer_norm_eps = layer_norm_eps

        self.pooler_hidden_size = kwargs.get("pooler_hidden_size", hidden_size)
        self.pooler_dropout = pooler_dropout
        self.pooler_hidden_act = pooler_hidden_act

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2

PyTorch DeBERTa-v2 model.

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.ContextPooler

Bases: Module

Represents a ContextPooler module used for pooling contextual embeddings in a neural network architecture.

This class inherits from nn.Module and provides methods for initializing the pooler, forwarding the pooled output based on hidden states, and retrieving the output dimension. The pooler consists of a dense layer and dropout mechanism for processing hidden states.

ATTRIBUTE DESCRIPTION
dense

A dense layer for transforming input hidden states to pooler hidden size.

TYPE: Linear

dropout

A dropout layer for stable dropout operations.

TYPE: StableDropout

config

Configuration object containing pooler settings.

METHOD DESCRIPTION
__init__

Initializes the ContextPooler with the given configuration.

forward

Constructs the pooled output by processing hidden states.

output_dim

Property that returns the output dimension based on the hidden size in the configuration.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
 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
class ContextPooler(nn.Module):

    """
    Represents a ContextPooler module used for pooling contextual embeddings in a neural network architecture.

    This class inherits from nn.Module and provides methods for initializing the pooler, forwarding the pooled output
    based on hidden states, and retrieving the output dimension.
    The pooler consists of a dense layer and dropout mechanism for processing hidden states.

    Attributes:
        dense (nn.Linear): A dense layer for transforming input hidden states to pooler hidden size.
        dropout (StableDropout): A dropout layer for stable dropout operations.
        config: Configuration object containing pooler settings.

    Methods:
        __init__: Initializes the ContextPooler with the given configuration.
        forward: Constructs the pooled output by processing hidden states.
        output_dim: Property that returns the output dimension based on the hidden size in the configuration.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the ContextPooler class.

        Args:
            self: The instance of the ContextPooler class.
            config:
                An object of type 'config' that contains the configuration parameters for the ContextPooler.

                - Type: 'config'
                - Purpose: Specifies the configuration parameters for the ContextPooler.
                - Restrictions: None.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size)
        self.dropout = StableDropout(config.pooler_dropout)
        self.config = config

    def forward(self, hidden_states):
        """
        Args:
            self (ContextPooler): The instance of the ContextPooler class.
            hidden_states (tensor): A tensor containing hidden states.
                It is expected to have a specific shape and format for processing.

        Returns:
            pooled_output (tensor): The output tensor after the pooling operation.
                It represents the pooled context information.

        Raises:
            ValueError: If the hidden_states tensor does not meet the expected shape or format requirements.
            RuntimeError: If an error occurs during the pooling operation.

        """
        # We "pool" the model by simply taking the hidden state corresponding
        # to the first token.

        context_token = hidden_states[:, 0]
        context_token = self.dropout(context_token)
        pooled_output = self.dense(context_token)
        pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output)
        return pooled_output

    @property
    def output_dim(self):
        """
        Method to retrieve the output dimension of the ContextPooler.

        Args:
            self (ContextPooler): An instance of the ContextPooler class.
                This parameter is required to access the configuration information.

        Returns:
            None: The method does not perform any computation but simply returns the output dimension.

        Raises:
            None.
        """
        return self.config.hidden_size

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.ContextPooler.output_dim property

Method to retrieve the output dimension of the ContextPooler.

PARAMETER DESCRIPTION
self

An instance of the ContextPooler class. This parameter is required to access the configuration information.

TYPE: ContextPooler

RETURNS DESCRIPTION
None

The method does not perform any computation but simply returns the output dimension.

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.ContextPooler.__init__(config)

Initializes a new instance of the ContextPooler class.

PARAMETER DESCRIPTION
self

The instance of the ContextPooler class.

config

An object of type 'config' that contains the configuration parameters for the ContextPooler.

  • Type: 'config'
  • Purpose: Specifies the configuration parameters for the ContextPooler.
  • Restrictions: None.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def __init__(self, config):
    """
    Initializes a new instance of the ContextPooler class.

    Args:
        self: The instance of the ContextPooler class.
        config:
            An object of type 'config' that contains the configuration parameters for the ContextPooler.

            - Type: 'config'
            - Purpose: Specifies the configuration parameters for the ContextPooler.
            - Restrictions: None.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size)
    self.dropout = StableDropout(config.pooler_dropout)
    self.config = config

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.ContextPooler.forward(hidden_states)

PARAMETER DESCRIPTION
self

The instance of the ContextPooler class.

TYPE: ContextPooler

hidden_states

A tensor containing hidden states. It is expected to have a specific shape and format for processing.

TYPE: tensor

RETURNS DESCRIPTION
pooled_output

The output tensor after the pooling operation. It represents the pooled context information.

TYPE: tensor

RAISES DESCRIPTION
ValueError

If the hidden_states tensor does not meet the expected shape or format requirements.

RuntimeError

If an error occurs during the pooling operation.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def forward(self, hidden_states):
    """
    Args:
        self (ContextPooler): The instance of the ContextPooler class.
        hidden_states (tensor): A tensor containing hidden states.
            It is expected to have a specific shape and format for processing.

    Returns:
        pooled_output (tensor): The output tensor after the pooling operation.
            It represents the pooled context information.

    Raises:
        ValueError: If the hidden_states tensor does not meet the expected shape or format requirements.
        RuntimeError: If an error occurs during the pooling operation.

    """
    # We "pool" the model by simply taking the hidden state corresponding
    # to the first token.

    context_token = hidden_states[:, 0]
    context_token = self.dropout(context_token)
    pooled_output = self.dense(context_token)
    pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output)
    return pooled_output

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Attention

Bases: Module

This class represents the DebertaAttention module, which is a component of the DeBERTa model. It inherits from the nn.Module class.

DebertaAttention applies self-attention mechanism on the input hidden states, allowing the model to focus on different parts of the input sequence. It consists of a DisentangledSelfAttention layer and a DebertaSelfOutput layer.

PARAMETER DESCRIPTION
config

A dictionary containing the configuration parameters for the DebertaAttention module.

TYPE: dict

METHOD DESCRIPTION
__init__

Initializes a new instance of DebertaAttention.

Args:

  • config (dict): A dictionary containing the configuration parameters for the DebertaAttention module.
forward

Applies the DebertaAttention mechanism on the input hidden states.

Args:

  • hidden_states (Tensor): The input hidden states of shape (batch_size, sequence_length, hidden_size).
  • attention_mask (Tensor): The attention mask of shape (batch_size, sequence_length, sequence_length) where 1 indicates tokens to attend to and 0 indicates tokens to ignore.
  • output_attentions (bool, optional): Whether to output the attention matrix. Defaults to False.
  • query_states (Tensor, optional): The query states of shape (batch_size, sequence_length, hidden_size). If not provided, defaults to using the input hidden states.
  • relative_pos (Tensor, optional): The relative positions of the tokens of shape (batch_size, sequence_length, sequence_length).
  • rel_embeddings (Tensor, optional): The relative embeddings of shape (batch_size, sequence_length, hidden_size).

Returns: Tensor or Tuple: The attention output tensor of shape (batch_size, sequence_length, hidden_size) or a tuple containing the attention output tensor and the attention matrix if output_attentions is True.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
class DebertaV2Attention(nn.Module):

    """
    This class represents the DebertaAttention module, which is a component of the DeBERTa model.
    It inherits from the nn.Module class.

    DebertaAttention applies self-attention mechanism on the input hidden states, allowing the model to
    focus on different parts of the input sequence. It consists of a DisentangledSelfAttention layer and a
    DebertaSelfOutput layer.

    Args:
        config (dict): A dictionary containing the configuration parameters for the DebertaAttention module.

    Methods:
        __init__(self, config):
            Initializes a new instance of DebertaAttention.

            Args:

            - config (dict): A dictionary containing the configuration parameters for the DebertaAttention module.

        forward:

            Applies the DebertaAttention mechanism on the input hidden states.

            Args:

            - hidden_states (Tensor): The input hidden states of shape (batch_size, sequence_length, hidden_size).
            - attention_mask (Tensor): The attention mask of shape (batch_size, sequence_length, sequence_length)
            where 1 indicates tokens to attend to and 0 indicates tokens to ignore.
            - output_attentions (bool, optional): Whether to output the attention matrix. Defaults to False.
            - query_states (Tensor, optional): The query states of shape (batch_size, sequence_length, hidden_size).
            If not provided, defaults to using the input hidden states.
            - relative_pos (Tensor, optional):
            The relative positions of the tokens of shape (batch_size, sequence_length, sequence_length).
            - rel_embeddings (Tensor, optional):
            The relative embeddings of shape (batch_size, sequence_length, hidden_size).

            Returns:
                Tensor or Tuple: The attention output tensor of shape (batch_size, sequence_length, hidden_size)
                or a tuple containing the attention output tensor and the attention matrix if output_attentions
                is True.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the DebertaAttention class.

        Args:
            self (DebertaAttention): The current instance of the DebertaAttention class.
            config (object): The configuration object containing the settings for the attention module.
                It should provide the necessary parameters for initializing the DisentangledSelfAttention and
                DebertaSelfOutput instances.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.self = DisentangledSelfAttention(config)
        self.output = DebertaV2SelfOutput(config)
        self.config = config

    def forward(
        self,
        hidden_states,
        attention_mask,
        output_attentions=False,
        query_states=None,
        relative_pos=None,
        rel_embeddings=None,
    ):
        """
        Constructs the DebertaAttention layer with the given parameters.

        Args:
            self: The DebertaAttention instance.
            hidden_states (torch.Tensor): The input hidden states with shape (batch_size, sequence_length, hidden_size).
            attention_mask (torch.Tensor): The attention mask with shape (batch_size, sequence_length).
            output_attentions (bool): Whether to output attention matrices.
            query_states (torch.Tensor): The query states with shape (batch_size, sequence_length, hidden_size).
                If not provided, defaults to hidden_states.
            relative_pos (torch.Tensor):
                The relative position encoding with shape (batch_size, sequence_length, sequence_length).
            rel_embeddings (torch.Tensor):
                The relative position embeddings with shape (num_relative_distances, hidden_size).

        Returns:
            None

        Raises:
            None
        """
        self_output = self.self(
            hidden_states,
            attention_mask,
            output_attentions,
            query_states=query_states,
            relative_pos=relative_pos,
            rel_embeddings=rel_embeddings,
        )
        if output_attentions:
            self_output, att_matrix = self_output
        if query_states is None:
            query_states = hidden_states
        attention_output = self.output(self_output, query_states)

        if output_attentions:
            return (attention_output, att_matrix)
        return attention_output

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Attention.__init__(config)

Initializes a new instance of the DebertaAttention class.

PARAMETER DESCRIPTION
self

The current instance of the DebertaAttention class.

TYPE: DebertaAttention

config

The configuration object containing the settings for the attention module. It should provide the necessary parameters for initializing the DisentangledSelfAttention and DebertaSelfOutput instances.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def __init__(self, config):
    """
    Initializes a new instance of the DebertaAttention class.

    Args:
        self (DebertaAttention): The current instance of the DebertaAttention class.
        config (object): The configuration object containing the settings for the attention module.
            It should provide the necessary parameters for initializing the DisentangledSelfAttention and
            DebertaSelfOutput instances.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.self = DisentangledSelfAttention(config)
    self.output = DebertaV2SelfOutput(config)
    self.config = config

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Attention.forward(hidden_states, attention_mask, output_attentions=False, query_states=None, relative_pos=None, rel_embeddings=None)

Constructs the DebertaAttention layer with the given parameters.

PARAMETER DESCRIPTION
self

The DebertaAttention instance.

hidden_states

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

TYPE: Tensor

attention_mask

The attention mask with shape (batch_size, sequence_length).

TYPE: Tensor

output_attentions

Whether to output attention matrices.

TYPE: bool DEFAULT: False

query_states

The query states with shape (batch_size, sequence_length, hidden_size). If not provided, defaults to hidden_states.

TYPE: Tensor DEFAULT: None

relative_pos

The relative position encoding with shape (batch_size, sequence_length, sequence_length).

TYPE: Tensor DEFAULT: None

rel_embeddings

The relative position embeddings with shape (num_relative_distances, hidden_size).

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
def forward(
    self,
    hidden_states,
    attention_mask,
    output_attentions=False,
    query_states=None,
    relative_pos=None,
    rel_embeddings=None,
):
    """
    Constructs the DebertaAttention layer with the given parameters.

    Args:
        self: The DebertaAttention instance.
        hidden_states (torch.Tensor): The input hidden states with shape (batch_size, sequence_length, hidden_size).
        attention_mask (torch.Tensor): The attention mask with shape (batch_size, sequence_length).
        output_attentions (bool): Whether to output attention matrices.
        query_states (torch.Tensor): The query states with shape (batch_size, sequence_length, hidden_size).
            If not provided, defaults to hidden_states.
        relative_pos (torch.Tensor):
            The relative position encoding with shape (batch_size, sequence_length, sequence_length).
        rel_embeddings (torch.Tensor):
            The relative position embeddings with shape (num_relative_distances, hidden_size).

    Returns:
        None

    Raises:
        None
    """
    self_output = self.self(
        hidden_states,
        attention_mask,
        output_attentions,
        query_states=query_states,
        relative_pos=relative_pos,
        rel_embeddings=rel_embeddings,
    )
    if output_attentions:
        self_output, att_matrix = self_output
    if query_states is None:
        query_states = hidden_states
    attention_output = self.output(self_output, query_states)

    if output_attentions:
        return (attention_output, att_matrix)
    return attention_output

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Embeddings

Bases: Module

Construct the embeddings from word, position and token_type embeddings.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
class DebertaV2Embeddings(nn.Module):
    """Construct the embeddings from word, position and token_type embeddings."""
    def __init__(self, config):
        """
        Initializes the DebertaEmbeddings class.

        Args:
            self (object): Instance of the DebertaEmbeddings class.
            config (object): 
                An object containing configuration parameters for the Deberta model.

                - Type: Custom class object.
                - Purpose: Specifies the model configuration including vocab size, hidden size, max position embeddings, 
                type vocab size, etc.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        pad_token_id = getattr(config, "pad_token_id", 0)
        self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
        self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id)

        self.position_biased_input = getattr(config, "position_biased_input", True)
        if not self.position_biased_input:
            self.position_embeddings = None
        else:
            self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size)

        if config.type_vocab_size > 0:
            self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size)

        if self.embedding_size != config.hidden_size:
            self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False)
        self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.dropout = StableDropout(config.hidden_dropout_prob)
        self.config = config

        # position_ids (1, len position emb) is contiguous in memory and exported when serialized
        self.position_ids = ops.arange(config.max_position_embeddings).broadcast_to((1, -1))

    def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None):
        """
        Constructs the embeddings for the Deberta model.

        Args:
            self (DebertaEmbeddings): An instance of the DebertaEmbeddings class.
            input_ids (Tensor, optional):
                A tensor of shape (batch_size, sequence_length) representing the input token IDs. Default is None.
            token_type_ids (Tensor, optional):
                A tensor of shape (batch_size, sequence_length) representing the token type IDs. Default is None.
            position_ids (Tensor, optional):
                A tensor of shape (batch_size, sequence_length) representing the position IDs. Default is None.
            mask (Tensor, optional):
                A tensor of shape (batch_size, sequence_length) representing the attention mask. Default is None.
            inputs_embeds (Tensor, optional):
                A tensor of shape (batch_size, sequence_length, embedding_size) representing the input embeddings.
                Default is None.

        Returns:
            Tensor: A tensor of shape (batch_size, sequence_length, embedding_size) representing the forwarded embeddings.

        Raises:
            None.
        """
        if input_ids is not None:
            input_shape = input_ids.shape
        else:
            input_shape = inputs_embeds.shape[:-1]

        seq_length = input_shape[1]

        if position_ids is None:
            position_ids = self.position_ids[:, :seq_length]

        if token_type_ids is None:
            token_type_ids = ops.zeros(input_shape, dtype=mindspore.int64)

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

        if self.position_embeddings is not None:
            position_embeddings = self.position_embeddings(position_ids.to(dtype=mindspore.int64))
        else:
            position_embeddings = ops.zeros_like(inputs_embeds)

        embeddings = inputs_embeds
        if self.position_biased_input:
            embeddings += position_embeddings
        if self.config.type_vocab_size > 0:
            token_type_embeddings = self.token_type_embeddings(token_type_ids)
            embeddings += token_type_embeddings

        if self.embedding_size != self.config.hidden_size:
            embeddings = self.embed_proj(embeddings)

        embeddings = self.LayerNorm(embeddings)

        if mask is not None:
            if mask.ndim != embeddings.ndim:
                if mask.ndim == 4:
                    mask = mask.squeeze(1).squeeze(1)
                mask = mask.unsqueeze(2)
            mask = mask.to(embeddings.dtype)

            embeddings = embeddings * mask

        embeddings = self.dropout(embeddings)
        return embeddings

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Embeddings.__init__(config)

Initializes the DebertaEmbeddings class.

PARAMETER DESCRIPTION
self

Instance of the DebertaEmbeddings class.

TYPE: object

config

An object containing configuration parameters for the Deberta model.

  • Type: Custom class object.
  • Purpose: Specifies the model configuration including vocab size, hidden size, max position embeddings, type vocab size, etc.
  • Restrictions: Must be a valid configuration object.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
def __init__(self, config):
    """
    Initializes the DebertaEmbeddings class.

    Args:
        self (object): Instance of the DebertaEmbeddings class.
        config (object): 
            An object containing configuration parameters for the Deberta model.

            - Type: Custom class object.
            - Purpose: Specifies the model configuration including vocab size, hidden size, max position embeddings, 
            type vocab size, etc.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    pad_token_id = getattr(config, "pad_token_id", 0)
    self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
    self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id)

    self.position_biased_input = getattr(config, "position_biased_input", True)
    if not self.position_biased_input:
        self.position_embeddings = None
    else:
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size)

    if config.type_vocab_size > 0:
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size)

    if self.embedding_size != config.hidden_size:
        self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False)
    self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.dropout = StableDropout(config.hidden_dropout_prob)
    self.config = config

    # position_ids (1, len position emb) is contiguous in memory and exported when serialized
    self.position_ids = ops.arange(config.max_position_embeddings).broadcast_to((1, -1))

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Embeddings.forward(input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None)

Constructs the embeddings for the Deberta model.

PARAMETER DESCRIPTION
self

An instance of the DebertaEmbeddings class.

TYPE: DebertaEmbeddings

input_ids

A tensor of shape (batch_size, sequence_length) representing the input token IDs. Default is None.

TYPE: Tensor DEFAULT: None

token_type_ids

A tensor of shape (batch_size, sequence_length) representing the token type IDs. Default is None.

TYPE: Tensor DEFAULT: None

position_ids

A tensor of shape (batch_size, sequence_length) representing the position IDs. Default is None.

TYPE: Tensor DEFAULT: None

mask

A tensor of shape (batch_size, sequence_length) representing the attention mask. Default is None.

TYPE: Tensor DEFAULT: None

inputs_embeds

A tensor of shape (batch_size, sequence_length, embedding_size) representing the input embeddings. Default is None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
Tensor

A tensor of shape (batch_size, sequence_length, embedding_size) representing the forwarded embeddings.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None):
    """
    Constructs the embeddings for the Deberta model.

    Args:
        self (DebertaEmbeddings): An instance of the DebertaEmbeddings class.
        input_ids (Tensor, optional):
            A tensor of shape (batch_size, sequence_length) representing the input token IDs. Default is None.
        token_type_ids (Tensor, optional):
            A tensor of shape (batch_size, sequence_length) representing the token type IDs. Default is None.
        position_ids (Tensor, optional):
            A tensor of shape (batch_size, sequence_length) representing the position IDs. Default is None.
        mask (Tensor, optional):
            A tensor of shape (batch_size, sequence_length) representing the attention mask. Default is None.
        inputs_embeds (Tensor, optional):
            A tensor of shape (batch_size, sequence_length, embedding_size) representing the input embeddings.
            Default is None.

    Returns:
        Tensor: A tensor of shape (batch_size, sequence_length, embedding_size) representing the forwarded embeddings.

    Raises:
        None.
    """
    if input_ids is not None:
        input_shape = input_ids.shape
    else:
        input_shape = inputs_embeds.shape[:-1]

    seq_length = input_shape[1]

    if position_ids is None:
        position_ids = self.position_ids[:, :seq_length]

    if token_type_ids is None:
        token_type_ids = ops.zeros(input_shape, dtype=mindspore.int64)

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

    if self.position_embeddings is not None:
        position_embeddings = self.position_embeddings(position_ids.to(dtype=mindspore.int64))
    else:
        position_embeddings = ops.zeros_like(inputs_embeds)

    embeddings = inputs_embeds
    if self.position_biased_input:
        embeddings += position_embeddings
    if self.config.type_vocab_size > 0:
        token_type_embeddings = self.token_type_embeddings(token_type_ids)
        embeddings += token_type_embeddings

    if self.embedding_size != self.config.hidden_size:
        embeddings = self.embed_proj(embeddings)

    embeddings = self.LayerNorm(embeddings)

    if mask is not None:
        if mask.ndim != embeddings.ndim:
            if mask.ndim == 4:
                mask = mask.squeeze(1).squeeze(1)
            mask = mask.unsqueeze(2)
        mask = mask.to(embeddings.dtype)

        embeddings = embeddings * mask

    embeddings = self.dropout(embeddings)
    return embeddings

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Encoder

Bases: Module

Modified BertEncoder with relative position bias support

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
 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
class DebertaV2Encoder(nn.Module):
    """Modified BertEncoder with relative position bias support"""

    def __init__(self, config):
        super().__init__()

        self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)])
        self.relative_attention = getattr(config, "relative_attention", False)

        if self.relative_attention:
            self.max_relative_positions = getattr(config, "max_relative_positions", -1)
            if self.max_relative_positions < 1:
                self.max_relative_positions = config.max_position_embeddings

            self.position_buckets = getattr(config, "position_buckets", -1)
            pos_ebd_size = self.max_relative_positions * 2

            if self.position_buckets > 0:
                pos_ebd_size = self.position_buckets * 2

            self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size)

        self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")]

        if "layer_norm" in self.norm_rel_ebd:
            self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)

        self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None
        self.gradient_checkpointing = False

    def get_rel_embedding(self):
        rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None
        if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd):
            rel_embeddings = self.LayerNorm(rel_embeddings)
        return rel_embeddings

    def get_attention_mask(self, attention_mask):
        if attention_mask.dim() <= 2:
            extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
            attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1)
        elif attention_mask.dim() == 3:
            attention_mask = attention_mask.unsqueeze(1)

        return attention_mask

    def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None):
        if self.relative_attention and relative_pos is None:
            q = query_states.shape[-2] if query_states is not None else hidden_states.shape[-2]
            relative_pos = build_relative_position(
                q,
                hidden_states.shape[-2],
                bucket_size=self.position_buckets,
                max_position=self.max_relative_positions,
            )
        return relative_pos

    def forward(
        self,
        hidden_states,
        attention_mask,
        output_hidden_states=True,
        output_attentions=False,
        query_states=None,
        relative_pos=None,
        return_dict=True,
    ):
        if attention_mask.dim() <= 2:
            input_mask = attention_mask
        else:
            input_mask = attention_mask.sum(-2) > 0
        attention_mask = self.get_attention_mask(attention_mask)
        relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos)

        all_hidden_states = () if output_hidden_states else None
        all_attentions = () if output_attentions else None

        if isinstance(hidden_states, Sequence):
            next_kv = hidden_states[0]
        else:
            next_kv = hidden_states
        rel_embeddings = self.get_rel_embedding()
        output_states = next_kv
        for i, layer_module in enumerate(self.layer):
            if output_hidden_states:
                all_hidden_states = all_hidden_states + (output_states,)

            if self.gradient_checkpointing and self.training:
                output_states = self._gradient_checkpointing_func(
                    layer_module.__call__,
                    next_kv,
                    attention_mask,
                    query_states,
                    relative_pos,
                    rel_embeddings,
                    output_attentions,
                )
            else:
                output_states = layer_module(
                    next_kv,
                    attention_mask,
                    query_states=query_states,
                    relative_pos=relative_pos,
                    rel_embeddings=rel_embeddings,
                    output_attentions=output_attentions,
                )

            if output_attentions:
                output_states, att_m = output_states

            if i == 0 and self.conv is not None:
                output_states = self.conv(hidden_states, output_states, input_mask)

            if query_states is not None:
                query_states = output_states
                if isinstance(hidden_states, Sequence):
                    next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None
            else:
                next_kv = output_states

            if output_attentions:
                all_attentions = all_attentions + (att_m,)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (output_states,)

        if not return_dict:
            return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None)
        return BaseModelOutput(
            last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions
        )

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2ForQuestionAnswering

Bases: DebertaV2PreTrainedModel

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
class DebertaV2ForQuestionAnswering(DebertaV2PreTrainedModel):

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

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

        Returns:
            None.

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

        self.deberta = DebertaV2Model(config)
        self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        start_positions: Optional[mindspore.Tensor] = None,
        end_positions: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, QuestionAnsweringModelOutput]:
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.deberta(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        sequence_output = outputs[0]

        logits = self.qa_outputs(sequence_output)
        start_logits, end_logits = logits.split(1, axis=-1)
        start_logits = start_logits.squeeze(-1)
        end_logits = end_logits.squeeze(-1)

        total_loss = None
        if start_positions is not None and end_positions is not None:
            # If we are on multi-GPU, split add a dimension
            if len(start_positions.shape) > 1:
                start_positions = start_positions.squeeze(-1)
            if len(end_positions.shape) > 1:
                end_positions = end_positions.squeeze(-1)
            # sometimes the start/end positions are outside our model inputs, we ignore these terms
            ignored_index = start_logits.shape[1]
            start_positions = start_positions.clamp(0, ignored_index)
            end_positions = end_positions.clamp(0, ignored_index)

            start_loss = ops.cross_entropy(start_logits, start_positions, ignore_index=ignored_index)
            end_loss = ops.cross_entropy(end_logits, end_positions, ignore_index=ignored_index)
            total_loss = (start_loss + end_loss) / 2

        if not return_dict:
            output = (start_logits, end_logits) + outputs[1:]
            return ((total_loss,) + output) if total_loss is not None else output

        return QuestionAnsweringModelOutput(
            loss=total_loss,
            start_logits=start_logits,
            end_logits=end_logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2ForQuestionAnswering.__init__(config)

Initializes a new instance of the DebertaForQuestionAnswering class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An instance of the configuration class containing the model configuration.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
def __init__(self, config):
    """
    Initializes a new instance of the DebertaForQuestionAnswering class.

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

    Returns:
        None.

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

    self.deberta = DebertaV2Model(config)
    self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2ForTokenClassification

Bases: DebertaV2PreTrainedModel

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
class DebertaV2ForTokenClassification(DebertaV2PreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.num_labels = config.num_labels

        self.deberta = DebertaV2Model(config)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        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,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, TokenClassifierOutput]:
        r"""
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.deberta(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        sequence_output = outputs[0]

        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_output)

        loss = None
        if labels is not None:
            loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

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

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

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2ForTokenClassification.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the token classification loss. Indices should be in [0, ..., config.num_labels - 1].

TYPE: `torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    token_type_ids: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, TokenClassifierOutput]:
    r"""
    Args:
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.deberta(
        input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    sequence_output = outputs[0]

    sequence_output = self.dropout(sequence_output)
    logits = self.classifier(sequence_output)

    loss = None
    if labels is not None:
        loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

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

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

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Intermediate

Bases: Module

DebertaIntermediate represents an intermediate layer in the DeBERTa neural network architecture for natural language processing tasks. This class inherits from nn.Module and contains methods for initializing the layer and performing computations on hidden states. The layer consists of a dense transformation followed by an activation function specified in the configuration.

ATTRIBUTE DESCRIPTION
dense

A dense layer with hidden size and intermediate size specified in the configuration.

TYPE: Linear

intermediate_act_fn

The activation function applied to the hidden states.

TYPE: function

METHOD DESCRIPTION
__init__

Initializes the DebertaIntermediate layer with the provided configuration.

forward

mindspore.Tensor) -> mindspore.Tensor: Applies the dense transformation and activation function to the input hidden states.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
class DebertaV2Intermediate(nn.Module):

    """
    DebertaIntermediate represents an intermediate layer in the DeBERTa neural network architecture for natural language processing tasks. 
    This class inherits from nn.Module and contains methods for initializing the layer and performing computations on hidden states. 
    The layer consists of a dense transformation followed by an activation function specified in the configuration. 

    Attributes:
        dense (nn.Linear): A dense layer with hidden size and intermediate size specified in the configuration.
        intermediate_act_fn (function): The activation function applied to the hidden states.

    Methods:
        __init__(config): Initializes the DebertaIntermediate layer with the provided configuration.
        forward(hidden_states: mindspore.Tensor) -> mindspore.Tensor:
            Applies the dense transformation and activation function to the input hidden states.

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

        Args:
            self: The object itself.
            config (object): An object containing the configuration parameters for the DebertaIntermediate class.
                It should have the following properties:

                - hidden_size (int): The size of the hidden layer in the intermediate module.
                - intermediate_size (int): The size of the intermediate layer.
                - hidden_act (str or object): The activation function for the hidden layer.

                    - If it is a string, it should be one of the supported activation functions.
                    - If it is an object, it should be a callable that takes a single argument.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        if isinstance(config.hidden_act, str):
            self.intermediate_act_fn = ACT2FN[config.hidden_act]
        else:
            self.intermediate_act_fn = config.hidden_act

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs the intermediate layer of the Deberta model.

        Args:
            self (DebertaIntermediate): The instance of the DebertaIntermediate class.
            hidden_states (mindspore.Tensor): The input hidden states tensor.

        Returns:
            mindspore.Tensor: The tensor representing the output hidden states.

        Raises:
            None.

        This method takes in the hidden states tensor and applies a series of transformations to it in order to
        forward the intermediate layer of the Deberta model. The hidden states tensor is first passed through
        a dense layer, followed by an activation function specified by 'intermediate_act_fn'.
        The resulting tensor represents the intermediate hidden states and is returned as the output of this method.

        Note:
            The 'intermediate_act_fn' attribute should be set prior to calling this method to specify the desired
            activation function.

        Example:
            ```python
            >>> intermediate_layer = DebertaIntermediate()
            >>> hidden_states = mindspore.Tensor([0.1, 0.2, 0.3])
            >>> output = intermediate_layer.forward(hidden_states)
            ```
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Intermediate.__init__(config)

Initializes a new instance of the DebertaIntermediate class.

PARAMETER DESCRIPTION
self

The object itself.

config

An object containing the configuration parameters for the DebertaIntermediate class. It should have the following properties:

  • hidden_size (int): The size of the hidden layer in the intermediate module.
  • intermediate_size (int): The size of the intermediate layer.
  • hidden_act (str or object): The activation function for the hidden layer.

    • If it is a string, it should be one of the supported activation functions.
    • If it is an object, it should be a callable that takes a single argument.

TYPE: object

RETURNS DESCRIPTION

None.

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

    Args:
        self: The object itself.
        config (object): An object containing the configuration parameters for the DebertaIntermediate class.
            It should have the following properties:

            - hidden_size (int): The size of the hidden layer in the intermediate module.
            - intermediate_size (int): The size of the intermediate layer.
            - hidden_act (str or object): The activation function for the hidden layer.

                - If it is a string, it should be one of the supported activation functions.
                - If it is an object, it should be a callable that takes a single argument.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
    if isinstance(config.hidden_act, str):
        self.intermediate_act_fn = ACT2FN[config.hidden_act]
    else:
        self.intermediate_act_fn = config.hidden_act

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Intermediate.forward(hidden_states)

Constructs the intermediate layer of the Deberta model.

PARAMETER DESCRIPTION
self

The instance of the DebertaIntermediate class.

TYPE: DebertaIntermediate

hidden_states

The input hidden states tensor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The tensor representing the output hidden states.

This method takes in the hidden states tensor and applies a series of transformations to it in order to forward the intermediate layer of the Deberta model. The hidden states tensor is first passed through a dense layer, followed by an activation function specified by 'intermediate_act_fn'. The resulting tensor represents the intermediate hidden states and is returned as the output of this method.

Note

The 'intermediate_act_fn' attribute should be set prior to calling this method to specify the desired activation function.

Example
>>> intermediate_layer = DebertaIntermediate()
>>> hidden_states = mindspore.Tensor([0.1, 0.2, 0.3])
>>> output = intermediate_layer.forward(hidden_states)
Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs the intermediate layer of the Deberta model.

    Args:
        self (DebertaIntermediate): The instance of the DebertaIntermediate class.
        hidden_states (mindspore.Tensor): The input hidden states tensor.

    Returns:
        mindspore.Tensor: The tensor representing the output hidden states.

    Raises:
        None.

    This method takes in the hidden states tensor and applies a series of transformations to it in order to
    forward the intermediate layer of the Deberta model. The hidden states tensor is first passed through
    a dense layer, followed by an activation function specified by 'intermediate_act_fn'.
    The resulting tensor represents the intermediate hidden states and is returned as the output of this method.

    Note:
        The 'intermediate_act_fn' attribute should be set prior to calling this method to specify the desired
        activation function.

    Example:
        ```python
        >>> intermediate_layer = DebertaIntermediate()
        >>> hidden_states = mindspore.Tensor([0.1, 0.2, 0.3])
        >>> output = intermediate_layer.forward(hidden_states)
        ```
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.intermediate_act_fn(hidden_states)
    return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2LMPredictionHead

Bases: Module

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
class DebertaV2LMPredictionHead(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.transform = DebertaV2PredictionHeadTransform(config)

        self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
        # The output weights are the same as the input embeddings, but there is
        # an output-only bias for each token.
        self.decoder = nn.Linear(self.embedding_size, config.vocab_size, bias=False)

        self.bias = Parameter(ops.zeros(config.vocab_size))

        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        """
        This method forwards the prediction head for DebertaLM model.

        Args:
            self (DebertaLMPredictionHead): An instance of the DebertaLMPredictionHead class.
            hidden_states (tensor): The hidden states to be processed for prediction.

        Returns:
            None: The processed hidden states after passing through the transformation and decoder layers.

        Raises:
            None.
        """
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2LMPredictionHead.forward(hidden_states)

This method forwards the prediction head for DebertaLM model.

PARAMETER DESCRIPTION
self

An instance of the DebertaLMPredictionHead class.

TYPE: DebertaLMPredictionHead

hidden_states

The hidden states to be processed for prediction.

TYPE: tensor

RETURNS DESCRIPTION
None

The processed hidden states after passing through the transformation and decoder layers.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
def forward(self, hidden_states):
    """
    This method forwards the prediction head for DebertaLM model.

    Args:
        self (DebertaLMPredictionHead): An instance of the DebertaLMPredictionHead class.
        hidden_states (tensor): The hidden states to be processed for prediction.

    Returns:
        None: The processed hidden states after passing through the transformation and decoder layers.

    Raises:
        None.
    """
    hidden_states = self.transform(hidden_states)
    hidden_states = self.decoder(hidden_states)
    return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Layer

Bases: Module

Represents a single layer in the DeBERTa model, containing modules for attention, intermediate processing, and output computation.

This class inherits from nn.Module and is responsible for processing input hidden states through attention mechanisms, intermediate processing, and final output computation. It provides a 'forward' method to perform these operations and return the final layer output.

ATTRIBUTE DESCRIPTION
attention

Module for performing attention mechanism computation.

TYPE: DebertaAttention

intermediate

Module for intermediate processing of attention output.

TYPE: DebertaIntermediate

output

Module for computing final output based on intermediate processed data.

TYPE: DebertaOutput

METHOD DESCRIPTION
forward

Process the input hidden states through attention, intermediate, and output modules to compute the final layer output.

Args:

  • hidden_states (Tensor): Input hidden states to be processed.
  • attention_mask (Tensor): Mask for attention calculation.
  • query_states (Tensor, optional): Query states for attention mechanism. Default is None.
  • relative_pos (Tensor, optional): Relative position information for attention computation. Default is None.
  • rel_embeddings (Tensor, optional): Relative embeddings for attention computation. Default is None.
  • output_attentions (bool, optional): Flag indicating whether to output attention matrices. Default is False.

Returns:

  • layer_output (Tensor): Final computed output of the layer.
  • att_matrix (Tensor, optional): Attention matrix if 'output_attentions' is True. Otherwise, None.
Note

If 'output_attentions' is set to True, the 'forward' method will return both the final layer output and the attention matrix.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
class DebertaV2Layer(nn.Module):

    """
    Represents a single layer in the DeBERTa model, containing modules for attention, intermediate processing,
    and output computation.

    This class inherits from nn.Module and is responsible for processing input hidden states through attention mechanisms,
    intermediate processing, and final output computation. It provides a 'forward' method to perform these operations
    and return the final layer output.

    Attributes:
        attention (DebertaAttention): Module for performing attention mechanism computation.
        intermediate (DebertaIntermediate): Module for intermediate processing of attention output.
        output (DebertaOutput): Module for computing final output based on intermediate processed data.

    Methods:
        forward(hidden_states, attention_mask, query_states=None, relative_pos=None, rel_embeddings=None, output_attentions=False):
            Process the input hidden states through attention, intermediate, and output modules to compute the final layer output.

            Args:

            - hidden_states (Tensor): Input hidden states to be processed.
            - attention_mask (Tensor): Mask for attention calculation.
            - query_states (Tensor, optional): Query states for attention mechanism. Default is None.
            - relative_pos (Tensor, optional): Relative position information for attention computation. Default is None.
            - rel_embeddings (Tensor, optional): Relative embeddings for attention computation. Default is None.
            - output_attentions (bool, optional): Flag indicating whether to output attention matrices. Default is False.

            Returns:

            - layer_output (Tensor): Final computed output of the layer.
            - att_matrix (Tensor, optional): Attention matrix if 'output_attentions' is True. Otherwise, None.

    Note:
        If 'output_attentions' is set to True,
        the 'forward' method will return both the final layer output and the attention matrix.
    """
    def __init__(self, config):
        """
        Initialize a DebertaLayer instance.

        Args:
            self (object): The instance of the DebertaLayer class.
            config (object): An object containing configuration settings for the DebertaLayer.
                It is used to customize the behavior of the layer during initialization.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.attention = DebertaV2Attention(config)
        self.intermediate = DebertaV2Intermediate(config)
        self.output = DebertaV2Output(config)

    def forward(
        self,
        hidden_states,
        attention_mask,
        query_states=None,
        relative_pos=None,
        rel_embeddings=None,
        output_attentions=False,
    ):
        """
        Constructs the DebertaLayer by performing attention, intermediate, and output operations.

        Args:
            self (object): The class instance.
            hidden_states (torch.Tensor): The input hidden states tensor.
            attention_mask (torch.Tensor): The attention mask tensor to mask out padded tokens.
            query_states (torch.Tensor, optional): The tensor representing query states for attention computation. 
                Defaults to None.
            relative_pos (torch.Tensor, optional): The tensor representing relative positions for attention computation. 
                Defaults to None.
            rel_embeddings (torch.Tensor, optional): The tensor containing relative embeddings for attention computation. 
                Defaults to None.
            output_attentions (bool): Flag indicating whether to output attention matrices. Defaults to False.

        Returns:
            None.

        Raises:
            ValueError: If the dimensions of the input tensors are incompatible.
            TypeError: If the input parameters are not of the expected types.
        """
        attention_output = self.attention(
            hidden_states,
            attention_mask,
            output_attentions=output_attentions,
            query_states=query_states,
            relative_pos=relative_pos,
            rel_embeddings=rel_embeddings,
        )
        if output_attentions:
            attention_output, att_matrix = attention_output
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        if output_attentions:
            return (layer_output, att_matrix)
        return layer_output

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Layer.__init__(config)

Initialize a DebertaLayer instance.

PARAMETER DESCRIPTION
self

The instance of the DebertaLayer class.

TYPE: object

config

An object containing configuration settings for the DebertaLayer. It is used to customize the behavior of the layer during initialization.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
def __init__(self, config):
    """
    Initialize a DebertaLayer instance.

    Args:
        self (object): The instance of the DebertaLayer class.
        config (object): An object containing configuration settings for the DebertaLayer.
            It is used to customize the behavior of the layer during initialization.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.attention = DebertaV2Attention(config)
    self.intermediate = DebertaV2Intermediate(config)
    self.output = DebertaV2Output(config)

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Layer.forward(hidden_states, attention_mask, query_states=None, relative_pos=None, rel_embeddings=None, output_attentions=False)

Constructs the DebertaLayer by performing attention, intermediate, and output operations.

PARAMETER DESCRIPTION
self

The class instance.

TYPE: object

hidden_states

The input hidden states tensor.

TYPE: Tensor

attention_mask

The attention mask tensor to mask out padded tokens.

TYPE: Tensor

query_states

The tensor representing query states for attention computation. Defaults to None.

TYPE: Tensor DEFAULT: None

relative_pos

The tensor representing relative positions for attention computation. Defaults to None.

TYPE: Tensor DEFAULT: None

rel_embeddings

The tensor containing relative embeddings for attention computation. Defaults to None.

TYPE: Tensor DEFAULT: None

output_attentions

Flag indicating whether to output attention matrices. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the dimensions of the input tensors are incompatible.

TypeError

If the input parameters are not of the expected types.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
def forward(
    self,
    hidden_states,
    attention_mask,
    query_states=None,
    relative_pos=None,
    rel_embeddings=None,
    output_attentions=False,
):
    """
    Constructs the DebertaLayer by performing attention, intermediate, and output operations.

    Args:
        self (object): The class instance.
        hidden_states (torch.Tensor): The input hidden states tensor.
        attention_mask (torch.Tensor): The attention mask tensor to mask out padded tokens.
        query_states (torch.Tensor, optional): The tensor representing query states for attention computation. 
            Defaults to None.
        relative_pos (torch.Tensor, optional): The tensor representing relative positions for attention computation. 
            Defaults to None.
        rel_embeddings (torch.Tensor, optional): The tensor containing relative embeddings for attention computation. 
            Defaults to None.
        output_attentions (bool): Flag indicating whether to output attention matrices. Defaults to False.

    Returns:
        None.

    Raises:
        ValueError: If the dimensions of the input tensors are incompatible.
        TypeError: If the input parameters are not of the expected types.
    """
    attention_output = self.attention(
        hidden_states,
        attention_mask,
        output_attentions=output_attentions,
        query_states=query_states,
        relative_pos=relative_pos,
        rel_embeddings=rel_embeddings,
    )
    if output_attentions:
        attention_output, att_matrix = attention_output
    intermediate_output = self.intermediate(attention_output)
    layer_output = self.output(intermediate_output, attention_output)
    if output_attentions:
        return (layer_output, att_matrix)
    return layer_output

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Model

Bases: DebertaV2PreTrainedModel

DebertaModel class represents a DeBERTa model for natural language processing tasks. This class inherits functionalities from DebertaPreTrainedModel and implements methods for initializing the model, getting and setting input embeddings, and forwarding the model output.

ATTRIBUTE DESCRIPTION
embeddings

The embeddings module of the DeBERTa model.

TYPE: DebertaEmbeddings

encoder

The encoder module of the DeBERTa model.

TYPE: DebertaEncoder

z_steps

Number of Z steps used in the model.

TYPE: int

config

Configuration object for the model.

METHOD DESCRIPTION
__init__

Initializes the DebertaModel with the provided configuration.

get_input_embeddings

Retrieves the word embeddings from the input embeddings.

set_input_embeddings

Sets new word embeddings for the input embeddings.

_prune_heads

Prunes heads of the model based on the provided dictionary.

forward

Constructs the model output based on the input parameters.

RAISES DESCRIPTION
NotImplementedError

If the prune function is called as it is not implemented in the DeBERTa model.

ValueError

If both input_ids and inputs_embeds are specified simultaneously, or if neither input_ids nor inputs_embeds are provided.

RETURNS DESCRIPTION

Tuple or BaseModelOutput: Depending on the configuration settings, returns either a tuple or a BaseModelOutput object containing the model output.

Note

This class is designed for use in natural language processing tasks and leverages the DeBERTa architecture for efficient modeling.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
class DebertaV2Model(DebertaV2PreTrainedModel):

    """
    DebertaModel class represents a DeBERTa model for natural language processing tasks. 
    This class inherits functionalities from DebertaPreTrainedModel and implements methods for initializing the model,
    getting and setting input embeddings, and forwarding the model output.

    Attributes:
        embeddings (DebertaEmbeddings): The embeddings module of the DeBERTa model.
        encoder (DebertaEncoder): The encoder module of the DeBERTa model.
        z_steps (int): Number of Z steps used in the model.
        config: Configuration object for the model.

    Methods:
        __init__: Initializes the DebertaModel with the provided configuration.
        get_input_embeddings: Retrieves the word embeddings from the input embeddings.
        set_input_embeddings: Sets new word embeddings for the input embeddings.
        _prune_heads: Prunes heads of the model based on the provided dictionary.
        forward: Constructs the model output based on the input parameters.

    Raises:
        NotImplementedError: If the prune function is called as it is not implemented in the DeBERTa model.
        ValueError: If both input_ids and inputs_embeds are specified simultaneously,
            or if neither input_ids nor inputs_embeds are provided.

    Returns:
        Tuple or BaseModelOutput: Depending on the configuration settings, returns either a tuple or a
            BaseModelOutput object containing the model output.

    Note:
        This class is designed for use in natural language processing tasks and leverages the DeBERTa architecture
        for efficient modeling.

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

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

        Returns:
            None.

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

        self.embeddings = DebertaV2Embeddings(config)
        self.encoder = DebertaV2Encoder(config)
        self.z_steps = 0
        self.config = config
        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        """
        Retrieve the input embeddings from the DebertaModel.

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

        Returns:
            None.

        Raises:
            None.
        """
        return self.embeddings.word_embeddings

    def set_input_embeddings(self, new_embeddings):
        """
        Method to set the input embeddings for a DebertaModel instance.

        Args:
            self (DebertaModel): The instance of the DebertaModel class.
            new_embeddings (object): New input embeddings to be set for the model. 
                It should be of the appropriate type compatible with the model's word_embeddings attribute.

        Returns:
            None.

        Raises:
            TypeError: If the new_embeddings parameter is not of the expected type.
            ValueError: If the new_embeddings parameter is invalid or incompatible with the model.
        """
        self.embeddings.word_embeddings = new_embeddings

    def _prune_heads(self, heads_to_prune):
        """
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        """
        raise NotImplementedError("The prune function is not implemented in DeBERTa model.")

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, BaseModelOutput]:
        """
        This method forwards a DebertaModel based on the provided input parameters.

        Args:
            self (object): The instance of the DebertaModel class.
            input_ids (Optional[mindspore.Tensor]): The input tensor containing token indices. Default is None.
            attention_mask (Optional[mindspore.Tensor]):
                The attention mask tensor to specify which tokens should be attended to. Default is None.
            token_type_ids (Optional[mindspore.Tensor]): The tensor specifying the type of each token. Default is None.
            position_ids (Optional[mindspore.Tensor]): The tensor containing position indices of tokens. Default is None.
            inputs_embeds (Optional[mindspore.Tensor]):
                The tensor containing precomputed embeddings for input tokens. Default is None.
            output_attentions (Optional[bool]): Flag to indicate whether to output attentions. Default is None.
            output_hidden_states (Optional[bool]): Flag to indicate whether to output hidden states. Default is None.
            return_dict (Optional[bool]): Flag to indicate whether to return output as a dictionary. Default is None.

        Returns:
            Union[Tuple, BaseModelOutput]:
                The output value, which can either be a tuple or a BaseModelOutput object, containing
                the forwarded DebertaModel.

        Raises:
            ValueError: Raised if both input_ids and inputs_embeds are specified simultaneously.
            ValueError: Raised if neither input_ids nor inputs_embeds are specified.
        """
        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

        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:
            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
            input_shape = input_ids.shape
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.shape[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        if attention_mask is None:
            attention_mask = ops.ones(input_shape)
        if token_type_ids is None:
            token_type_ids = ops.zeros(input_shape, dtype=mindspore.int64)

        embedding_output = self.embeddings(
            input_ids=input_ids,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            mask=attention_mask,
            inputs_embeds=inputs_embeds,
        )

        encoder_outputs = self.encoder(
            embedding_output,
            attention_mask,
            output_hidden_states=True,
            output_attentions=output_attentions,
            return_dict=return_dict,
        )
        encoded_layers = encoder_outputs[1]

        if self.z_steps > 1:
            hidden_states = encoded_layers[-2]
            layers = [self.encoder.layer[-1] for _ in range(self.z_steps)]
            query_states = encoded_layers[-1]
            rel_embeddings = self.encoder.get_rel_embedding()
            attention_mask = self.encoder.get_attention_mask(attention_mask)
            rel_pos = self.encoder.get_rel_pos(embedding_output)
            for layer in layers[1:]:
                query_states = layer(
                    hidden_states,
                    attention_mask,
                    output_attentions=False,
                    query_states=query_states,
                    relative_pos=rel_pos,
                    rel_embeddings=rel_embeddings,
                )
                encoded_layers.append(query_states)

        sequence_output = encoded_layers[-1]

        if not return_dict:
            return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :]

        return BaseModelOutput(
            last_hidden_state=sequence_output,
            hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
            attentions=encoder_outputs.attentions,
        )

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Model.__init__(config)

Initializes a new instance of the DebertaModel class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object containing the model configuration parameters.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
def __init__(self, config):
    """
    Initializes a new instance of the DebertaModel class.

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

    Returns:
        None.

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

    self.embeddings = DebertaV2Embeddings(config)
    self.encoder = DebertaV2Encoder(config)
    self.z_steps = 0
    self.config = config
    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Model.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)

This method forwards a DebertaModel based on the provided input parameters.

PARAMETER DESCRIPTION
self

The instance of the DebertaModel class.

TYPE: object

input_ids

The input tensor containing token indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask tensor to specify which tokens should be attended to. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The tensor specifying the type of each token. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The tensor containing position indices of tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The tensor containing precomputed embeddings for input tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Flag to indicate whether to output attentions. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Flag to indicate whether to output hidden states. Default is None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Flag to indicate whether to return output as a dictionary. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutput]

Union[Tuple, BaseModelOutput]: The output value, which can either be a tuple or a BaseModelOutput object, containing the forwarded DebertaModel.

RAISES DESCRIPTION
ValueError

Raised if both input_ids and inputs_embeds are specified simultaneously.

ValueError

Raised if neither input_ids nor inputs_embeds are specified.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    token_type_ids: Optional[mindspore.Tensor] = None,
    position_ids: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutput]:
    """
    This method forwards a DebertaModel based on the provided input parameters.

    Args:
        self (object): The instance of the DebertaModel class.
        input_ids (Optional[mindspore.Tensor]): The input tensor containing token indices. Default is None.
        attention_mask (Optional[mindspore.Tensor]):
            The attention mask tensor to specify which tokens should be attended to. Default is None.
        token_type_ids (Optional[mindspore.Tensor]): The tensor specifying the type of each token. Default is None.
        position_ids (Optional[mindspore.Tensor]): The tensor containing position indices of tokens. Default is None.
        inputs_embeds (Optional[mindspore.Tensor]):
            The tensor containing precomputed embeddings for input tokens. Default is None.
        output_attentions (Optional[bool]): Flag to indicate whether to output attentions. Default is None.
        output_hidden_states (Optional[bool]): Flag to indicate whether to output hidden states. Default is None.
        return_dict (Optional[bool]): Flag to indicate whether to return output as a dictionary. Default is None.

    Returns:
        Union[Tuple, BaseModelOutput]:
            The output value, which can either be a tuple or a BaseModelOutput object, containing
            the forwarded DebertaModel.

    Raises:
        ValueError: Raised if both input_ids and inputs_embeds are specified simultaneously.
        ValueError: Raised if neither input_ids nor inputs_embeds are specified.
    """
    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

    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:
        self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
        input_shape = input_ids.shape
    elif inputs_embeds is not None:
        input_shape = inputs_embeds.shape[:-1]
    else:
        raise ValueError("You have to specify either input_ids or inputs_embeds")

    if attention_mask is None:
        attention_mask = ops.ones(input_shape)
    if token_type_ids is None:
        token_type_ids = ops.zeros(input_shape, dtype=mindspore.int64)

    embedding_output = self.embeddings(
        input_ids=input_ids,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        mask=attention_mask,
        inputs_embeds=inputs_embeds,
    )

    encoder_outputs = self.encoder(
        embedding_output,
        attention_mask,
        output_hidden_states=True,
        output_attentions=output_attentions,
        return_dict=return_dict,
    )
    encoded_layers = encoder_outputs[1]

    if self.z_steps > 1:
        hidden_states = encoded_layers[-2]
        layers = [self.encoder.layer[-1] for _ in range(self.z_steps)]
        query_states = encoded_layers[-1]
        rel_embeddings = self.encoder.get_rel_embedding()
        attention_mask = self.encoder.get_attention_mask(attention_mask)
        rel_pos = self.encoder.get_rel_pos(embedding_output)
        for layer in layers[1:]:
            query_states = layer(
                hidden_states,
                attention_mask,
                output_attentions=False,
                query_states=query_states,
                relative_pos=rel_pos,
                rel_embeddings=rel_embeddings,
            )
            encoded_layers.append(query_states)

    sequence_output = encoded_layers[-1]

    if not return_dict:
        return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :]

    return BaseModelOutput(
        last_hidden_state=sequence_output,
        hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
        attentions=encoder_outputs.attentions,
    )

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Model.get_input_embeddings()

Retrieve the input embeddings from the DebertaModel.

PARAMETER DESCRIPTION
self

An instance of the DebertaModel class.

TYPE: DebertaModel

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
def get_input_embeddings(self):
    """
    Retrieve the input embeddings from the DebertaModel.

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

    Returns:
        None.

    Raises:
        None.
    """
    return self.embeddings.word_embeddings

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Model.set_input_embeddings(new_embeddings)

Method to set the input embeddings for a DebertaModel instance.

PARAMETER DESCRIPTION
self

The instance of the DebertaModel class.

TYPE: DebertaModel

new_embeddings

New input embeddings to be set for the model. It should be of the appropriate type compatible with the model's word_embeddings attribute.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the new_embeddings parameter is not of the expected type.

ValueError

If the new_embeddings parameter is invalid or incompatible with the model.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
def set_input_embeddings(self, new_embeddings):
    """
    Method to set the input embeddings for a DebertaModel instance.

    Args:
        self (DebertaModel): The instance of the DebertaModel class.
        new_embeddings (object): New input embeddings to be set for the model. 
            It should be of the appropriate type compatible with the model's word_embeddings attribute.

    Returns:
        None.

    Raises:
        TypeError: If the new_embeddings parameter is not of the expected type.
        ValueError: If the new_embeddings parameter is invalid or incompatible with the model.
    """
    self.embeddings.word_embeddings = new_embeddings

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Output

Bases: Module

This class represents the output layer of the Deberta model. It inherits from the nn.Module class and is responsible for applying the final transformations to the hidden states.

ATTRIBUTE DESCRIPTION
dense

A dense layer that transforms the hidden states to an intermediate size.

TYPE: Linear

LayerNorm

A layer normalization module that normalizes the hidden states.

TYPE: DebertaLayerNorm

dropout

A dropout layer that applies dropout to the hidden states.

TYPE: StableDropout

config

The configuration object for the Deberta model.

METHOD DESCRIPTION
__init__

Initializes the DebertaOutput instance.

Args:

  • config: The configuration object for the Deberta model.
forward

Applies the final transformations to the hidden states.

Args:

  • hidden_states: The input hidden states.
  • input_tensor: The original input tensor.

Returns: The transformed hidden states after applying the intermediate dense layer, dropout, and layer normalization.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
class DebertaV2Output(nn.Module):

    """
    This class represents the output layer of the Deberta model.
    It inherits from the nn.Module class and is responsible for applying the final transformations to the hidden states.

    Attributes:
        dense (nn.Linear): A dense layer that transforms the hidden states to an intermediate size.
        LayerNorm (DebertaLayerNorm): A layer normalization module that normalizes the hidden states.
        dropout (StableDropout): A dropout layer that applies dropout to the hidden states.
        config: The configuration object for the Deberta model.

    Methods:
        __init__(self, config):
            Initializes the DebertaOutput instance.

            Args:

            - config: The configuration object for the Deberta model.

        forward(self, hidden_states, input_tensor):
            Applies the final transformations to the hidden states.

            Args:

            - hidden_states: The input hidden states.
            - input_tensor: The original input tensor.

            Returns:
                The transformed hidden states after applying the intermediate dense layer, dropout,
                and layer normalization.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the DebertaOutput class.

        Args:
            self: The instance of the DebertaOutput class.
            config:
                An instance of the configuration class containing the parameters for the DebertaOutput layer.

                - Type: object
                - Purpose: Specifies the configuration settings for the DebertaOutput layer.
                - Restrictions: Must be a valid instance of the configuration class.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.dropout = StableDropout(config.hidden_dropout_prob)
        self.config = config

    def forward(self, hidden_states, input_tensor):
        """
        Constructs the output of the Deberta model by performing a series of operations.

        Args:
            self (DebertaOutput): The instance of the DebertaOutput class.
            hidden_states (Tensor): The input hidden states. This tensor represents the intermediate outputs of the model.
            input_tensor (Tensor): The input tensor to be added to the hidden states.

        Returns:
            None

        Raises:
            None
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Output.__init__(config)

Initializes a new instance of the DebertaOutput class.

PARAMETER DESCRIPTION
self

The instance of the DebertaOutput class.

config

An instance of the configuration class containing the parameters for the DebertaOutput layer.

  • Type: object
  • Purpose: Specifies the configuration settings for the DebertaOutput layer.
  • Restrictions: Must be a valid instance of the configuration class.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def __init__(self, config):
    """
    Initializes a new instance of the DebertaOutput class.

    Args:
        self: The instance of the DebertaOutput class.
        config:
            An instance of the configuration class containing the parameters for the DebertaOutput layer.

            - Type: object
            - Purpose: Specifies the configuration settings for the DebertaOutput layer.
            - Restrictions: Must be a valid instance of the configuration class.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
    self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.dropout = StableDropout(config.hidden_dropout_prob)
    self.config = config

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2Output.forward(hidden_states, input_tensor)

Constructs the output of the Deberta model by performing a series of operations.

PARAMETER DESCRIPTION
self

The instance of the DebertaOutput class.

TYPE: DebertaOutput

hidden_states

The input hidden states. This tensor represents the intermediate outputs of the model.

TYPE: Tensor

input_tensor

The input tensor to be added to the hidden states.

TYPE: Tensor

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def forward(self, hidden_states, input_tensor):
    """
    Constructs the output of the Deberta model by performing a series of operations.

    Args:
        self (DebertaOutput): The instance of the DebertaOutput class.
        hidden_states (Tensor): The input hidden states. This tensor represents the intermediate outputs of the model.
        input_tensor (Tensor): The input tensor to be added to the hidden states.

    Returns:
        None

    Raises:
        None
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.dropout(hidden_states)
    hidden_states = self.LayerNorm(hidden_states + input_tensor)
    return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2PreTrainedModel

Bases: PreTrainedModel

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

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
class DebertaV2PreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = DebertaV2Config
    base_model_prefix = "deberta"
    _keys_to_ignore_on_load_unexpected = ["position_embeddings"]
    supports_gradient_checkpointing = True

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

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

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2PredictionHeadTransform

Bases: Module

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
class DebertaV2PredictionHeadTransform(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.embedding_size = getattr(config, "embedding_size", config.hidden_size)

        self.dense = nn.Linear(config.hidden_size, self.embedding_size)
        if isinstance(config.hidden_act, str):
            self.transform_act_fn = ACT2FN[config.hidden_act]
        else:
            self.transform_act_fn = config.hidden_act
        self.LayerNorm = nn.LayerNorm([self.embedding_size], eps=config.layer_norm_eps)

    def forward(self, hidden_states):
        """
        This method 'forward' is defined within the class 'DebertaPredictionHeadTransform' and is responsible for
        processing the hidden states.

        Args:
            self: An instance of the 'DebertaPredictionHeadTransform' class.
            hidden_states: A tensor representing the hidden states to be processed.
                It is of type 'Tensor' and is expected to contain the information to be transformed.

        Returns:
            hidden_states: A tensor containing the transformed hidden states after processing.
                It is of type 'Tensor' and represents the result of the transformation operation.

        Raises:
            This method does not explicitly raise any exceptions.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.transform_act_fn(hidden_states)
        hidden_states = self.LayerNorm(hidden_states)
        return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2PredictionHeadTransform.forward(hidden_states)

This method 'forward' is defined within the class 'DebertaPredictionHeadTransform' and is responsible for processing the hidden states.

PARAMETER DESCRIPTION
self

An instance of the 'DebertaPredictionHeadTransform' class.

hidden_states

A tensor representing the hidden states to be processed. It is of type 'Tensor' and is expected to contain the information to be transformed.

RETURNS DESCRIPTION
hidden_states

A tensor containing the transformed hidden states after processing. It is of type 'Tensor' and represents the result of the transformation operation.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
def forward(self, hidden_states):
    """
    This method 'forward' is defined within the class 'DebertaPredictionHeadTransform' and is responsible for
    processing the hidden states.

    Args:
        self: An instance of the 'DebertaPredictionHeadTransform' class.
        hidden_states: A tensor representing the hidden states to be processed.
            It is of type 'Tensor' and is expected to contain the information to be transformed.

    Returns:
        hidden_states: A tensor containing the transformed hidden states after processing.
            It is of type 'Tensor' and represents the result of the transformation operation.

    Raises:
        This method does not explicitly raise any exceptions.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.transform_act_fn(hidden_states)
    hidden_states = self.LayerNorm(hidden_states)
    return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2SelfOutput

Bases: Module

Represents the output layer for the DeBERTa model, responsible for transforming hidden states and applying normalization and dropout.

This class inherits from nn.Module and contains methods to initialize the output layer components, including dense transformation, layer normalization, and dropout. The 'forward' method takes hidden states and input tensor, applies transformations, and returns the final hidden states after normalization and dropout.

ATTRIBUTE DESCRIPTION
dense

A fully connected layer for transforming hidden states.

TYPE: Linear

LayerNorm

Layer normalization applied to the hidden states.

TYPE: DebertaLayerNorm

dropout

Dropout regularization to prevent overfitting.

TYPE: StableDropout

METHOD DESCRIPTION
__init__

Initializes the output layer components with the given configuration.

forward

Applies transformations to hidden states and input tensor to produce final hidden states.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
class DebertaV2SelfOutput(nn.Module):

    """
    Represents the output layer for the DeBERTa model, responsible for transforming hidden states and
    applying normalization and dropout.

    This class inherits from nn.Module and contains methods to initialize the output layer components,
    including dense transformation, layer normalization, and dropout.
    The 'forward' method takes hidden states and input tensor, applies transformations,
    and returns the final hidden states after normalization and dropout.

    Attributes:
        dense (nn.Linear): A fully connected layer for transforming hidden states.
        LayerNorm (DebertaLayerNorm): Layer normalization applied to the hidden states.
        dropout (StableDropout): Dropout regularization to prevent overfitting.

    Methods:
        __init__: Initializes the output layer components with the given configuration.
        forward: Applies transformations to hidden states and input tensor to produce final hidden states.

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

        Args:
            self (DebertaSelfOutput): The current instance of the class.
            config: The configuration object containing the settings for the Deberta model.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.dropout = StableDropout(config.hidden_dropout_prob)

    def forward(self, hidden_states, input_tensor):
        """
        Method 'forward' in the class 'DebertaSelfOutput'.

        This method forwards the hidden states by applying a series of operations on the input hidden states and the input tensor.

        Args:
            self:
                Instance of the DebertaSelfOutput class.

                - Type: DebertaSelfOutput
                - Purpose: Represents the current instance of the class.

            hidden_states:
                Hidden states that need to be processed.

                - Type: tensor
                - Purpose: Represents the input hidden states that will undergo transformation.

            input_tensor:
                Input tensor to be added to the processed hidden states.

                - Type: tensor
                - Purpose: Represents the input tensor to be added to the processed hidden states.

        Returns:
            None.

        Raises:
            None
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2SelfOutput.__init__(config)

Initializes an instance of the DebertaSelfOutput class.

PARAMETER DESCRIPTION
self

The current instance of the class.

TYPE: DebertaSelfOutput

config

The configuration object containing the settings for the Deberta model.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def __init__(self, config):
    """
    Initializes an instance of the DebertaSelfOutput class.

    Args:
        self (DebertaSelfOutput): The current instance of the class.
        config: The configuration object containing the settings for the Deberta model.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_size)
    self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.dropout = StableDropout(config.hidden_dropout_prob)

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DebertaV2SelfOutput.forward(hidden_states, input_tensor)

Method 'forward' in the class 'DebertaSelfOutput'.

This method forwards the hidden states by applying a series of operations on the input hidden states and the input tensor.

PARAMETER DESCRIPTION
self

Instance of the DebertaSelfOutput class.

  • Type: DebertaSelfOutput
  • Purpose: Represents the current instance of the class.

hidden_states

Hidden states that need to be processed.

  • Type: tensor
  • Purpose: Represents the input hidden states that will undergo transformation.

input_tensor

Input tensor to be added to the processed hidden states.

  • Type: tensor
  • Purpose: Represents the input tensor to be added to the processed hidden states.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
def forward(self, hidden_states, input_tensor):
    """
    Method 'forward' in the class 'DebertaSelfOutput'.

    This method forwards the hidden states by applying a series of operations on the input hidden states and the input tensor.

    Args:
        self:
            Instance of the DebertaSelfOutput class.

            - Type: DebertaSelfOutput
            - Purpose: Represents the current instance of the class.

        hidden_states:
            Hidden states that need to be processed.

            - Type: tensor
            - Purpose: Represents the input hidden states that will undergo transformation.

        input_tensor:
            Input tensor to be added to the processed hidden states.

            - Type: tensor
            - Purpose: Represents the input tensor to be added to the processed hidden states.

    Returns:
        None.

    Raises:
        None
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.dropout(hidden_states)
    hidden_states = self.LayerNorm(hidden_states + input_tensor)
    return hidden_states

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DisentangledSelfAttention

Bases: Module

Disentangled self-attention module

PARAMETER DESCRIPTION
config

A model config class instance with the configuration to build a new model. The schema is similar to BertConfig, for more details, please refer [DebertaV2Config]

TYPE: `DebertaV2Config`

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
class DisentangledSelfAttention(nn.Module):
    """
    Disentangled self-attention module

    Parameters:
        config (`DebertaV2Config`):
            A model config class instance with the configuration to build a new model. The schema is similar to
            *BertConfig*, for more details, please refer [`DebertaV2Config`]

    """

    def __init__(self, config):
        super().__init__()
        if config.hidden_size % config.num_attention_heads != 0:
            raise ValueError(
                f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
                f"heads ({config.num_attention_heads})"
            )
        self.num_attention_heads = config.num_attention_heads
        _attention_head_size = config.hidden_size // config.num_attention_heads
        self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size)
        self.all_head_size = self.num_attention_heads * self.attention_head_size
        self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
        self.key_proj =  nn.Linear(config.hidden_size, self.all_head_size, bias=True)
        self.value_proj =  nn.Linear(config.hidden_size, self.all_head_size, bias=True)

        self.share_att_key = getattr(config, "share_att_key", False)
        self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else []
        self.relative_attention = getattr(config, "relative_attention", False)

        if self.relative_attention:
            self.position_buckets = getattr(config, "position_buckets", -1)
            self.max_relative_positions = getattr(config, "max_relative_positions", -1)
            if self.max_relative_positions < 1:
                self.max_relative_positions = config.max_position_embeddings
            self.pos_ebd_size = self.max_relative_positions
            if self.position_buckets > 0:
                self.pos_ebd_size = self.position_buckets

            self.pos_dropout = StableDropout(config.hidden_dropout_prob)

            if not self.share_att_key:
                if "c2p" in self.pos_att_type:
                    self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
                if "p2c" in self.pos_att_type:
                    self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size)

        self.dropout = StableDropout(config.attention_probs_dropout_prob)
        self.softmax = XSoftmax(-1)
    def swapaxes_for_scores(self, x, attention_heads):
        new_x_shape = x.shape[:-1] + (attention_heads, -1)
        x = x.view(new_x_shape)
        return x.permute(0, 2, 1, 3).view(-1, x.shape[1], x.shape[-1])

    def forward(
        self,
        hidden_states,
        attention_mask,
        output_attentions=False,
        query_states=None,
        relative_pos=None,
        rel_embeddings=None,
    ):
        """
        Call the module

        Args:
            hidden_states (`torch.FloatTensor`):
                Input states to the module usually the output from previous layer, it will be the Q,K and V in
                *Attention(Q,K,V)*

            attention_mask (`torch.BoolTensor`):
                An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum
                sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j*
                th token.

            output_attentions (`bool`, optional):
                Whether return the attention matrix.

            query_states (`torch.FloatTensor`, optional):
                The *Q* state in *Attention(Q,K,V)*.

            relative_pos (`torch.LongTensor`):
                The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with
                values ranging in [*-max_relative_positions*, *max_relative_positions*].

            rel_embeddings (`torch.FloatTensor`):
                The embedding of relative distances. It's a tensor of shape [\\(2 \\times
                \\text{max_relative_positions}\\), *hidden_size*].


        """
        if query_states is None:
            query_states = hidden_states
        query_layer = self.swapaxes_for_scores(self.query_proj(query_states), self.num_attention_heads)
        key_layer = self.swapaxes_for_scores(self.key_proj(hidden_states), self.num_attention_heads)
        value_layer = self.swapaxes_for_scores(self.value_proj(hidden_states), self.num_attention_heads)

        rel_att = None
        # Take the dot product between "query" and "key" to get the raw attention scores.
        scale_factor = 1
        if "c2p" in self.pos_att_type:
            scale_factor += 1
        if "p2c" in self.pos_att_type:
            scale_factor += 1
        scale = ops.sqrt(mindspore.tensor(query_layer.shape[-1], dtype=mindspore.float32) * scale_factor)
        attention_scores = ops.bmm(query_layer, key_layer.swapaxes(-1, -2) / scale.to(dtype=query_layer.dtype))
        if self.relative_attention:
            rel_embeddings = self.pos_dropout(rel_embeddings)
            rel_att = self.disentangled_attention_bias(
                query_layer, key_layer, relative_pos, rel_embeddings, scale_factor
            )

        if rel_att is not None:
            attention_scores = attention_scores + rel_att
        attention_scores = attention_scores.view(
            -1, self.num_attention_heads, attention_scores.shape[-2], attention_scores.shape[-1]
        )

        # bsz x height x length x dimension
        attention_probs = self.softmax(attention_scores, attention_mask)
        attention_probs = self.dropout(attention_probs)
        context_layer = ops.bmm(
            attention_probs.view(-1, attention_probs.shape[-2], attention_probs.shape[-1]), value_layer
        )
        context_layer = (
            context_layer.view(-1, self.num_attention_heads, context_layer.shape[-2], context_layer.shape[-1])
            .permute(0, 2, 1, 3)
        )
        new_context_layer_shape = context_layer.shape[:-2] + (-1,)
        context_layer = context_layer.view(new_context_layer_shape)
        if output_attentions:
            return (context_layer, attention_probs)
        else:
            return context_layer

    def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor):
        if relative_pos is None:
            q = query_layer.shape[-2]
            relative_pos = build_relative_position(
                q,
                key_layer.shape[-2],
                bucket_size=self.position_buckets,
                max_position=self.max_relative_positions,
            )
        if relative_pos.dim() == 2:
            relative_pos = relative_pos.unsqueeze(0).unsqueeze(0)
        elif relative_pos.dim() == 3:
            relative_pos = relative_pos.unsqueeze(1)
        # bsz x height x query x key
        elif relative_pos.dim() != 4:
            raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")

        att_span = self.pos_ebd_size
        relative_pos = relative_pos.to(dtype=mindspore.int64)

        rel_embeddings = rel_embeddings[0 : att_span * 2, :].unsqueeze(0)
        if self.share_att_key:
            pos_query_layer = self.swapaxes_for_scores(
                self.query_proj(rel_embeddings), self.num_attention_heads
            ).repeat(query_layer.shape[0] // self.num_attention_heads, 1, 1)
            pos_key_layer = self.swapaxes_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat(
                query_layer.shape[0] // self.num_attention_heads, 1, 1
            )
        else:
            if "c2p" in self.pos_att_type:
                pos_key_layer = self.swapaxes_for_scores(
                    self.pos_key_proj(rel_embeddings), self.num_attention_heads
                ).repeat(query_layer.shape[0] // self.num_attention_heads, 1, 1)  # .split(self.all_head_size, dim=-1)
            if "p2c" in self.pos_att_type:
                pos_query_layer = self.swapaxes_for_scores(
                    self.pos_query_proj(rel_embeddings), self.num_attention_heads
                ).repeat(query_layer.shape[0] // self.num_attention_heads, 1, 1)  # .split(self.all_head_size, dim=-1)

        score = 0
        # content->position
        if "c2p" in self.pos_att_type:
            scale = ops.sqrt(mindspore.tensor(pos_key_layer.shape[-1], dtype=mindspore.float32) * scale_factor)
            c2p_att = ops.bmm(query_layer, pos_key_layer.swapaxes(-1, -2))
            c2p_pos = ops.clamp(relative_pos + att_span, 0, att_span * 2 - 1)
            c2p_att = ops.gather_elements(
                c2p_att,
                dim=-1,
                index=c2p_pos.squeeze(0).broadcast_to((query_layer.shape[0], query_layer.shape[1], relative_pos.shape[-1])),
            )
            score += c2p_att / scale.to(dtype=c2p_att.dtype)

        # position->content
        if "p2c" in self.pos_att_type:
            scale = ops.sqrt(mindspore.tensor(pos_query_layer.shape[-1], dtype=mindspore.float32) * scale_factor)
            if key_layer.shape[-2] != query_layer.shape[-2]:
                r_pos = build_relative_position(
                    key_layer.shape[-2],
                    key_layer.shape[-2],
                    bucket_size=self.position_buckets,
                    max_position=self.max_relative_positions,
                )
                r_pos = r_pos.unsqueeze(0)
            else:
                r_pos = relative_pos

            p2c_pos = ops.clamp(-r_pos + att_span, 0, att_span * 2 - 1)
            p2c_att = ops.bmm(key_layer, pos_query_layer.swapaxes(-1, -2))
            p2c_att = ops.gather_elements(
                p2c_att,
                dim=-1,
                index=p2c_pos.squeeze(0).broadcast_to((query_layer.shape[0], key_layer.shape[-2], key_layer.shape[-2])),
            ).swapaxes(-1, -2)
            score += p2c_att / scale.to(dtype=p2c_att.dtype)

        return score

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DisentangledSelfAttention.forward(hidden_states, attention_mask, output_attentions=False, query_states=None, relative_pos=None, rel_embeddings=None)

Call the module

PARAMETER DESCRIPTION
hidden_states

Input states to the module usually the output from previous layer, it will be the Q,K and V in Attention(Q,K,V)

TYPE: `torch.FloatTensor`

attention_mask

An attention mask matrix of shape [B, N, N] where B is the batch size, N is the maximum sequence length in which element [i,j] = 1 means the i th token in the input can attend to the j th token.

TYPE: `torch.BoolTensor`

output_attentions

Whether return the attention matrix.

TYPE: `bool` DEFAULT: False

query_states

The Q state in Attention(Q,K,V).

TYPE: `torch.FloatTensor` DEFAULT: None

relative_pos

The relative position encoding between the tokens in the sequence. It's of shape [B, N, N] with values ranging in [-max_relative_positions, max_relative_positions].

TYPE: `torch.LongTensor` DEFAULT: None

rel_embeddings

The embedding of relative distances. It's a tensor of shape [\(2 \times \text{max_relative_positions}\), hidden_size].

TYPE: `torch.FloatTensor` DEFAULT: None

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
def forward(
    self,
    hidden_states,
    attention_mask,
    output_attentions=False,
    query_states=None,
    relative_pos=None,
    rel_embeddings=None,
):
    """
    Call the module

    Args:
        hidden_states (`torch.FloatTensor`):
            Input states to the module usually the output from previous layer, it will be the Q,K and V in
            *Attention(Q,K,V)*

        attention_mask (`torch.BoolTensor`):
            An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum
            sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j*
            th token.

        output_attentions (`bool`, optional):
            Whether return the attention matrix.

        query_states (`torch.FloatTensor`, optional):
            The *Q* state in *Attention(Q,K,V)*.

        relative_pos (`torch.LongTensor`):
            The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with
            values ranging in [*-max_relative_positions*, *max_relative_positions*].

        rel_embeddings (`torch.FloatTensor`):
            The embedding of relative distances. It's a tensor of shape [\\(2 \\times
            \\text{max_relative_positions}\\), *hidden_size*].


    """
    if query_states is None:
        query_states = hidden_states
    query_layer = self.swapaxes_for_scores(self.query_proj(query_states), self.num_attention_heads)
    key_layer = self.swapaxes_for_scores(self.key_proj(hidden_states), self.num_attention_heads)
    value_layer = self.swapaxes_for_scores(self.value_proj(hidden_states), self.num_attention_heads)

    rel_att = None
    # Take the dot product between "query" and "key" to get the raw attention scores.
    scale_factor = 1
    if "c2p" in self.pos_att_type:
        scale_factor += 1
    if "p2c" in self.pos_att_type:
        scale_factor += 1
    scale = ops.sqrt(mindspore.tensor(query_layer.shape[-1], dtype=mindspore.float32) * scale_factor)
    attention_scores = ops.bmm(query_layer, key_layer.swapaxes(-1, -2) / scale.to(dtype=query_layer.dtype))
    if self.relative_attention:
        rel_embeddings = self.pos_dropout(rel_embeddings)
        rel_att = self.disentangled_attention_bias(
            query_layer, key_layer, relative_pos, rel_embeddings, scale_factor
        )

    if rel_att is not None:
        attention_scores = attention_scores + rel_att
    attention_scores = attention_scores.view(
        -1, self.num_attention_heads, attention_scores.shape[-2], attention_scores.shape[-1]
    )

    # bsz x height x length x dimension
    attention_probs = self.softmax(attention_scores, attention_mask)
    attention_probs = self.dropout(attention_probs)
    context_layer = ops.bmm(
        attention_probs.view(-1, attention_probs.shape[-2], attention_probs.shape[-1]), value_layer
    )
    context_layer = (
        context_layer.view(-1, self.num_attention_heads, context_layer.shape[-2], context_layer.shape[-1])
        .permute(0, 2, 1, 3)
    )
    new_context_layer_shape = context_layer.shape[:-2] + (-1,)
    context_layer = context_layer.view(new_context_layer_shape)
    if output_attentions:
        return (context_layer, attention_probs)
    else:
        return context_layer

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DropoutContext

Represents a context for managing dropout operations within a neural network.

This class defines a context for managing dropout operations, including setting the dropout rate, mask, scaling factor, and reusing masks across iterations. It is designed to be used within a neural network framework to control dropout behavior during training.

ATTRIBUTE DESCRIPTION
dropout

The dropout rate to be applied.

TYPE: float

mask

The mask array used for applying dropout.

TYPE: ndarray or None

scale

The scaling factor applied to the output.

TYPE: float

reuse_mask

Flag indicating whether to reuse the mask across iterations.

TYPE: bool

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
class DropoutContext:

    """
    Represents a context for managing dropout operations within a neural network.

    This class defines a context for managing dropout operations, including setting the dropout rate, mask,
    scaling factor, and reusing masks across iterations.
    It is designed to be used within a neural network framework to control dropout behavior during training.

    Attributes:
        dropout (float): The dropout rate to be applied.
        mask (ndarray or None): The mask array used for applying dropout.
        scale (float): The scaling factor applied to the output.
        reuse_mask (bool): Flag indicating whether to reuse the mask across iterations.

    """
    def __init__(self):
        """
        Initialize a DropoutContext object.

        Args:
            self: The instance of the DropoutContext class.

        Returns:
            None.

        Raises:
            None.
        """
        self.dropout = 0
        self.mask = None
        self.scale = 1
        self.reuse_mask = True

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.DropoutContext.__init__()

Initialize a DropoutContext object.

PARAMETER DESCRIPTION
self

The instance of the DropoutContext class.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def __init__(self):
    """
    Initialize a DropoutContext object.

    Args:
        self: The instance of the DropoutContext class.

    Returns:
        None.

    Raises:
        None.
    """
    self.dropout = 0
    self.mask = None
    self.scale = 1
    self.reuse_mask = True

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.StableDropout

Bases: Module

Optimized dropout module for stabilizing the training

PARAMETER DESCRIPTION
drop_prob

the dropout probabilities

TYPE: float

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
class StableDropout(nn.Module):
    """
    Optimized dropout module for stabilizing the training

    Args:
        drop_prob (float): the dropout probabilities
    """
    def __init__(self, drop_prob):
        """Initialize the StableDropout object.

        This method is called when a new instance of the StableDropout class is created.
        It initializes the object with the given drop probability and sets the count and context_stack attributes
        to their initial values.

        Args:
            self (StableDropout): The instance of the StableDropout class.
            drop_prob (float): The probability of dropping a value during dropout. Must be between 0 and 1 (inclusive).

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.drop_prob = drop_prob
        self.count = 0
        self.context_stack = None

    def forward(self, x):
        """
        Call the module

        Args:
            x (`mindspore.tensor`): The input tensor to apply dropout
        """
        if self.training and self.drop_prob > 0:
            return XDropout(self.get_context())(x)
        return x

    def clear_context(self):
        """
        Clears the context of the StableDropout class.

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

        Returns:
            None.

        Raises:
            None.
        """
        self.count = 0
        self.context_stack = None

    def init_context(self, reuse_mask=True, scale=1):
        """
        Initializes the context stack for the StableDropout class.

        Args:
            self: The instance of the StableDropout class.
            reuse_mask (bool, optional): Indicates whether the dropout mask should be reused or not. Defaults to True.
            scale (int, optional): The scaling factor applied to the dropout mask. Defaults to 1.

        Returns:
            None.

        Raises:
            None.
        """
        if self.context_stack is None:
            self.context_stack = []
        self.count = 0
        for c in self.context_stack:
            c.reuse_mask = reuse_mask
            c.scale = scale

    def get_context(self):
        """
        Args:
            self (StableDropout): The instance of the StableDropout class invoking the method.
                This parameter is required for accessing the instance attributes and methods.

        Returns:
            None.

        Raises:
            None.
        """
        if self.context_stack is not None:
            if self.count >= len(self.context_stack):
                self.context_stack.append(DropoutContext())
            ctx = self.context_stack[self.count]
            ctx.dropout = self.drop_prob
            self.count += 1
            return ctx
        return self.drop_prob

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.StableDropout.__init__(drop_prob)

Initialize the StableDropout object.

This method is called when a new instance of the StableDropout class is created. It initializes the object with the given drop probability and sets the count and context_stack attributes to their initial values.

PARAMETER DESCRIPTION
self

The instance of the StableDropout class.

TYPE: StableDropout

drop_prob

The probability of dropping a value during dropout. Must be between 0 and 1 (inclusive).

TYPE: float

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def __init__(self, drop_prob):
    """Initialize the StableDropout object.

    This method is called when a new instance of the StableDropout class is created.
    It initializes the object with the given drop probability and sets the count and context_stack attributes
    to their initial values.

    Args:
        self (StableDropout): The instance of the StableDropout class.
        drop_prob (float): The probability of dropping a value during dropout. Must be between 0 and 1 (inclusive).

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.drop_prob = drop_prob
    self.count = 0
    self.context_stack = None

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.StableDropout.clear_context()

Clears the context of the StableDropout class.

PARAMETER DESCRIPTION
self

An instance of the StableDropout class.

TYPE: StableDropout

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def clear_context(self):
    """
    Clears the context of the StableDropout class.

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

    Returns:
        None.

    Raises:
        None.
    """
    self.count = 0
    self.context_stack = None

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.StableDropout.forward(x)

Call the module

PARAMETER DESCRIPTION
x

The input tensor to apply dropout

TYPE: `mindspore.tensor`

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
381
382
383
384
385
386
387
388
389
390
def forward(self, x):
    """
    Call the module

    Args:
        x (`mindspore.tensor`): The input tensor to apply dropout
    """
    if self.training and self.drop_prob > 0:
        return XDropout(self.get_context())(x)
    return x

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.StableDropout.get_context()

PARAMETER DESCRIPTION
self

The instance of the StableDropout class invoking the method. This parameter is required for accessing the instance attributes and methods.

TYPE: StableDropout

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def get_context(self):
    """
    Args:
        self (StableDropout): The instance of the StableDropout class invoking the method.
            This parameter is required for accessing the instance attributes and methods.

    Returns:
        None.

    Raises:
        None.
    """
    if self.context_stack is not None:
        if self.count >= len(self.context_stack):
            self.context_stack.append(DropoutContext())
        ctx = self.context_stack[self.count]
        ctx.dropout = self.drop_prob
        self.count += 1
        return ctx
    return self.drop_prob

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.StableDropout.init_context(reuse_mask=True, scale=1)

Initializes the context stack for the StableDropout class.

PARAMETER DESCRIPTION
self

The instance of the StableDropout class.

reuse_mask

Indicates whether the dropout mask should be reused or not. Defaults to True.

TYPE: bool DEFAULT: True

scale

The scaling factor applied to the dropout mask. Defaults to 1.

TYPE: int DEFAULT: 1

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def init_context(self, reuse_mask=True, scale=1):
    """
    Initializes the context stack for the StableDropout class.

    Args:
        self: The instance of the StableDropout class.
        reuse_mask (bool, optional): Indicates whether the dropout mask should be reused or not. Defaults to True.
        scale (int, optional): The scaling factor applied to the dropout mask. Defaults to 1.

    Returns:
        None.

    Raises:
        None.
    """
    if self.context_stack is None:
        self.context_stack = []
    self.count = 0
    for c in self.context_stack:
        c.reuse_mask = reuse_mask
        c.scale = scale

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XDropout

Bases: Module

Optimized dropout function to save computation and memory by using mask operation instead of multiplication.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
class XDropout(nn.Module):
    """Optimized dropout function to save computation and memory by using mask operation instead of multiplication."""
    def __init__(self, local_ctx):
        """
        Initialize a new instance of the XDropout class.

        Args:
            self (object): The instance of the XDropout class.
            local_ctx (object): The local context for the XDropout instance.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.local_ctx = local_ctx
        self.scale = 0
        self.mask = None

    def forward(self, inputs):
        """
        Constructs a masked and scaled version of the input tensor using the XDropout method.

        Args:
            self (XDropout): An instance of the XDropout class.
            inputs (torch.Tensor): The input tensor to be masked and scaled.

        Returns:
            None.

        Raises:
            None.
        """
        mask, dropout = get_mask(inputs, self.local_ctx)
        self.scale = 1.0 / (1 - dropout)
        self.mask = mask
        if dropout > 0:
            return inputs.masked_fill(mask, 0) * self.scale
        return inputs

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XDropout.__init__(local_ctx)

Initialize a new instance of the XDropout class.

PARAMETER DESCRIPTION
self

The instance of the XDropout class.

TYPE: object

local_ctx

The local context for the XDropout instance.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def __init__(self, local_ctx):
    """
    Initialize a new instance of the XDropout class.

    Args:
        self (object): The instance of the XDropout class.
        local_ctx (object): The local context for the XDropout instance.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.local_ctx = local_ctx
    self.scale = 0
    self.mask = None

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XDropout.forward(inputs)

Constructs a masked and scaled version of the input tensor using the XDropout method.

PARAMETER DESCRIPTION
self

An instance of the XDropout class.

TYPE: XDropout

inputs

The input tensor to be masked and scaled.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def forward(self, inputs):
    """
    Constructs a masked and scaled version of the input tensor using the XDropout method.

    Args:
        self (XDropout): An instance of the XDropout class.
        inputs (torch.Tensor): The input tensor to be masked and scaled.

    Returns:
        None.

    Raises:
        None.
    """
    mask, dropout = get_mask(inputs, self.local_ctx)
    self.scale = 1.0 / (1 - dropout)
    self.mask = mask
    if dropout > 0:
        return inputs.masked_fill(mask, 0) * self.scale
    return inputs

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XSoftmax

Bases: Module

Masked Softmax which is optimized for saving memory

PARAMETER DESCRIPTION
input

The input tensor that will apply softmax.

TYPE: `mindspore.tensor`

mask

The mask matrix where 0 indicate that element will be ignored in the softmax calculation.

TYPE: `torch.IntTensor`

dim

The dimension that will apply softmax

TYPE: int DEFAULT: -1

Example
>>> import torch
>>> from transformers.models.deberta.modeling_deberta import XSoftmax
...
>>> # Make a tensor
>>> x = torch.randn([4, 20, 100])
...
>>> # Create a mask
>>> mask = (x > 0).int()
...
>>> # Specify the dimension to apply softmax
>>> dim = -1
...
>>> y = XSoftmax.apply(x, mask, dim)
Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class XSoftmax(nn.Module):
    """
    Masked Softmax which is optimized for saving memory

    Args:
        input (`mindspore.tensor`): The input tensor that will apply softmax.
        mask (`torch.IntTensor`):
            The mask matrix where 0 indicate that element will be ignored in the softmax calculation.
        dim (int): The dimension that will apply softmax

    Example:
        ```python
        >>> import torch
        >>> from transformers.models.deberta.modeling_deberta import XSoftmax
        ...
        >>> # Make a tensor
        >>> x = torch.randn([4, 20, 100])
        ...
        >>> # Create a mask
        >>> mask = (x > 0).int()
        ...
        >>> # Specify the dimension to apply softmax
        >>> dim = -1
        ...
        >>> y = XSoftmax.apply(x, mask, dim)
        ```
    """
    def __init__(self, dim=-1):
        """
        Initializes an instance of the XSoftmax class.

        Args:
            self: The instance of the XSoftmax class.
            dim (int): The dimension along which the softmax operation is performed. Default is -1.
                The value of dim must be a non-negative integer or -1. If -1, the operation is performed
                along the last dimension of the input tensor.

        Returns:
            None.

        Raises:
            None.

        """
        super().__init__()
        self.dim = dim

    def forward(self, input, mask):
        """
        Constructs a softmax operation with masking for a given input tensor.

        Args:
            self (XSoftmax): An instance of the XSoftmax class.
            input (Tensor): The input tensor on which the softmax operation is performed.
            mask (Tensor): A tensor representing the mask used for masking certain elements in the input tensor.

        Returns:
            None: The method modifies the input tensor in-place and does not return any value.

        Raises:
            TypeError: If the input tensor or the mask tensor is not of the expected type.
            ValueError: If the dimensions of the input tensor and the mask tensor do not match.
            RuntimeError: If an error occurs during the softmax operation or masking process.
        """
        rmask = ~(mask.to(mindspore.bool_))

        output = input.masked_fill(rmask, mindspore.tensor(finfo(input.dtype, 'min')))
        output = ops.softmax(output, self.dim)
        output = output.masked_fill(rmask, 0)
        return output

    def brop(self, input, mask, output, grad_output):
        """
        This method, 'brop', is a member of the 'XSoftmax' class and performs a specific operation on the given input,
        mask, output, and grad_output parameters.

        Args:
            self: An instance of the 'XSoftmax' class.
            input: The input parameter of type <input_type>. It represents the input value used in the operation.
            mask: The mask parameter of type <mask_type>. It represents a mask used in the operation.
                <Additional details about the purpose and restrictions of the mask parameter.>
            output: The output parameter of type <output_type>. It represents the output value of the operation.
            grad_output: The grad_output parameter of type <grad_output_type>. It represents the gradient of the output value.

        Returns:
            dx: A value of type <dx_type>. It represents the final result of the operation.
                <Additional details about the purpose and format of the dx value.>
            None

        Raises:
            <Exception1>: <Description of when and why this exception may be raised.>
            <Exception2>: <Description of when and why this exception may be raised.>
            <Additional exceptions>: <may be raised during the execution of the method.>
        """
        dx = ops.mul(output, ops.sub(grad_output, ops.sum(ops.mul(output, grad_output), self.dim, keepdim=True)))
        return dx, None

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XSoftmax.__init__(dim=-1)

Initializes an instance of the XSoftmax class.

PARAMETER DESCRIPTION
self

The instance of the XSoftmax class.

dim

The dimension along which the softmax operation is performed. Default is -1. The value of dim must be a non-negative integer or -1. If -1, the operation is performed along the last dimension of the input tensor.

TYPE: int DEFAULT: -1

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def __init__(self, dim=-1):
    """
    Initializes an instance of the XSoftmax class.

    Args:
        self: The instance of the XSoftmax class.
        dim (int): The dimension along which the softmax operation is performed. Default is -1.
            The value of dim must be a non-negative integer or -1. If -1, the operation is performed
            along the last dimension of the input tensor.

    Returns:
        None.

    Raises:
        None.

    """
    super().__init__()
    self.dim = dim

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XSoftmax.brop(input, mask, output, grad_output)

This method, 'brop', is a member of the 'XSoftmax' class and performs a specific operation on the given input, mask, output, and grad_output parameters.

PARAMETER DESCRIPTION
self

An instance of the 'XSoftmax' class.

input

The input parameter of type . It represents the input value used in the operation.

mask

The mask parameter of type . It represents a mask used in the operation.

output

The output parameter of type . It represents the output value of the operation.

grad_output

The grad_output parameter of type . It represents the gradient of the output value.

RETURNS DESCRIPTION
dx

A value of type . It represents the final result of the operation.

None

RAISES DESCRIPTION
<Exception1>

<Exception2>

<Additional exceptions>

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def brop(self, input, mask, output, grad_output):
    """
    This method, 'brop', is a member of the 'XSoftmax' class and performs a specific operation on the given input,
    mask, output, and grad_output parameters.

    Args:
        self: An instance of the 'XSoftmax' class.
        input: The input parameter of type <input_type>. It represents the input value used in the operation.
        mask: The mask parameter of type <mask_type>. It represents a mask used in the operation.
            <Additional details about the purpose and restrictions of the mask parameter.>
        output: The output parameter of type <output_type>. It represents the output value of the operation.
        grad_output: The grad_output parameter of type <grad_output_type>. It represents the gradient of the output value.

    Returns:
        dx: A value of type <dx_type>. It represents the final result of the operation.
            <Additional details about the purpose and format of the dx value.>
        None

    Raises:
        <Exception1>: <Description of when and why this exception may be raised.>
        <Exception2>: <Description of when and why this exception may be raised.>
        <Additional exceptions>: <may be raised during the execution of the method.>
    """
    dx = ops.mul(output, ops.sub(grad_output, ops.sum(ops.mul(output, grad_output), self.dim, keepdim=True)))
    return dx, None

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.XSoftmax.forward(input, mask)

Constructs a softmax operation with masking for a given input tensor.

PARAMETER DESCRIPTION
self

An instance of the XSoftmax class.

TYPE: XSoftmax

input

The input tensor on which the softmax operation is performed.

TYPE: Tensor

mask

A tensor representing the mask used for masking certain elements in the input tensor.

TYPE: Tensor

RETURNS DESCRIPTION
None

The method modifies the input tensor in-place and does not return any value.

RAISES DESCRIPTION
TypeError

If the input tensor or the mask tensor is not of the expected type.

ValueError

If the dimensions of the input tensor and the mask tensor do not match.

RuntimeError

If an error occurs during the softmax operation or masking process.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def forward(self, input, mask):
    """
    Constructs a softmax operation with masking for a given input tensor.

    Args:
        self (XSoftmax): An instance of the XSoftmax class.
        input (Tensor): The input tensor on which the softmax operation is performed.
        mask (Tensor): A tensor representing the mask used for masking certain elements in the input tensor.

    Returns:
        None: The method modifies the input tensor in-place and does not return any value.

    Raises:
        TypeError: If the input tensor or the mask tensor is not of the expected type.
        ValueError: If the dimensions of the input tensor and the mask tensor do not match.
        RuntimeError: If an error occurs during the softmax operation or masking process.
    """
    rmask = ~(mask.to(mindspore.bool_))

    output = input.masked_fill(rmask, mindspore.tensor(finfo(input.dtype, 'min')))
    output = ops.softmax(output, self.dim)
    output = output.masked_fill(rmask, 0)
    return output

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1)

Build relative position according to the query and key

We assume the absolute position of query \(P_q\) is range from (0, query_size) and the absolute position of key \(P_k\) is range from (0, key_size), The relative positions from query to key is \(R_{q \rightarrow k} = P_q - P_k\)

PARAMETER DESCRIPTION
query_size

the length of query

TYPE: int

key_size

the length of key

TYPE: int

bucket_size

the size of position bucket

TYPE: int DEFAULT: -1

max_position

the maximum allowed absolute position

TYPE: int DEFAULT: -1

device

the device on which tensors will be created.

TYPE: `torch.device`

Return

torch.LongTensor: A tensor with shape [1, query_size, key_size]

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
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
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1):
    """
    Build relative position according to the query and key

    We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key
    \\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q -
    P_k\\)

    Args:
        query_size (int): the length of query
        key_size (int): the length of key
        bucket_size (int): the size of position bucket
        max_position (int): the maximum allowed absolute position
        device (`torch.device`): the device on which tensors will be created.

    Return:
        `torch.LongTensor`: A tensor with shape [1, query_size, key_size]
    """

    q_ids = ops.arange(0, query_size)
    k_ids = ops.arange(0, key_size)
    rel_pos_ids = q_ids[:, None] - k_ids[None, :]
    if bucket_size > 0 and max_position > 0:
        rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
    rel_pos_ids = rel_pos_ids.to(dtype=mindspore.int64)
    rel_pos_ids = rel_pos_ids[:query_size, :]
    rel_pos_ids = rel_pos_ids.unsqueeze(0)
    return rel_pos_ids

mindnlp.transformers.models.deberta_v2.modeling_deberta_v2.get_mask(input, local_context)

PARAMETER DESCRIPTION
input

The input tensor for which the dropout mask is generated.

TYPE: Tensor

local_context

The local context containing information about dropout parameters.

  • If a DropoutContext object is provided, the dropout mask will be generated based on its parameters.
  • If a float value is provided, it will be used as the dropout rate.

TYPE: DropoutContext or float

RETURNS DESCRIPTION
None

The function returns the generated dropout mask, or None if no mask is generated.

RAISES DESCRIPTION
ValueError

If the local_context is not of type DropoutContext.

Source code in mindnlp/transformers/models/deberta_v2/modeling_deberta_v2.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def get_mask(input, local_context):
    """
    Args:
        input (Tensor): The input tensor for which the dropout mask is generated.
        local_context (DropoutContext or float):
            The local context containing information about dropout parameters.

            - If a DropoutContext object is provided, the dropout mask will be generated based on its parameters.
            - If a float value is provided, it will be used as the dropout rate.

    Returns:
        None: The function returns the generated dropout mask, or None if no mask is generated.

    Raises:
        ValueError: If the local_context is not of type DropoutContext.
    """
    if not isinstance(local_context, DropoutContext):
        dropout = local_context
        mask = None
    else:
        dropout = local_context.dropout
        dropout *= local_context.scale
        mask = local_context.mask if local_context.reuse_mask else None

    if dropout > 0 and mask is None:
        mask = (1 - ops.zeros_like(input).bernoulli(1 - dropout)).to(mindspore.bool_)

    if isinstance(local_context, DropoutContext):
        if local_context.mask is None:
            local_context.mask = mask

    return mask, dropout

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2

Tokenization class for model DeBERTa.

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.DebertaV2Tokenizer

Bases: PreTrainedTokenizer

Constructs a DeBERTa-v2 tokenizer. Based on SentencePiece.

PARAMETER DESCRIPTION
vocab_file

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

TYPE: `str`

do_lower_case

Whether or not to lowercase the input when tokenizing.

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

bos_token

The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token. When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the cls_token.

TYPE: `string`, *optional*, defaults to `"[CLS]"` DEFAULT: '[CLS]'

eos_token

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

TYPE: `string`, *optional*, defaults to `"[SEP]"` DEFAULT: '[SEP]'

unk_token

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

TYPE: `str`, *optional*, defaults to `"[UNK]"` DEFAULT: '[UNK]'

sep_token

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

TYPE: `str`, *optional*, defaults to `"[SEP]"` DEFAULT: '[SEP]'

pad_token

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

TYPE: `str`, *optional*, defaults to `"[PAD]"` DEFAULT: '[PAD]'

cls_token

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

TYPE: `str`, *optional*, defaults to `"[CLS]"` DEFAULT: '[CLS]'

mask_token

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

TYPE: `str`, *optional*, defaults to `"[MASK]"` DEFAULT: '[MASK]'

sp_model_kwargs

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

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

  • nbest_size = {0,1}: No sampling is performed.

  • nbest_size > 1: samples from the nbest_size results.
  • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.

  • alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
class DebertaV2Tokenizer(PreTrainedTokenizer):
    r"""
    Constructs a DeBERTa-v2 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).

    Args:
        vocab_file (`str`):
            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        do_lower_case (`bool`, *optional*, defaults to `False`):
            Whether or not to lowercase the input when tokenizing.
        bos_token (`string`, *optional*, defaults to `"[CLS]"`):
            The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.
        eos_token (`string`, *optional*, defaults to `"[SEP]"`):
            The end of sequence token. When building a sequence using special tokens, this is not the token that is
            used for the end of sequence. The token used is the `sep_token`.
        unk_token (`str`, *optional*, defaults to `"[UNK]"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        sep_token (`str`, *optional*, defaults to `"[SEP]"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        pad_token (`str`, *optional*, defaults to `"[PAD]"`):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (`str`, *optional*, defaults to `"[CLS]"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        mask_token (`str`, *optional*, defaults to `"[MASK]"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

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

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.
    """

    vocab_files_names = VOCAB_FILES_NAMES

    def __init__(
        self,
        vocab_file,
        do_lower_case=False,
        split_by_punct=False,
        bos_token="[CLS]",
        eos_token="[SEP]",
        unk_token="[UNK]",
        sep_token="[SEP]",
        pad_token="[PAD]",
        cls_token="[CLS]",
        mask_token="[MASK]",
        sp_model_kwargs: Optional[Dict[str, Any]] = None,
        **kwargs,
    ) -> None:
        self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs

        if not os.path.isfile(vocab_file):
            raise ValueError(
                f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
                " model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
            )
        self.do_lower_case = do_lower_case
        self.split_by_punct = split_by_punct
        self.vocab_file = vocab_file
        self._tokenizer = SPMTokenizer(
            vocab_file, None, split_by_punct=split_by_punct, sp_model_kwargs=self.sp_model_kwargs
        )
        unk_token = AddedToken(unk_token, normalized=True, special=True) if isinstance(unk_token, str) else unk_token
        super().__init__(
            do_lower_case=do_lower_case,
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            split_by_punct=split_by_punct,
            sp_model_kwargs=self.sp_model_kwargs,
            **kwargs,
        )
        self._tokenizer.special_tokens = self.all_special_tokens

    @property
    def vocab_size(self):
        return len(self.vocab)

    @property
    def vocab(self):
        return self._tokenizer.vocab

    def get_vocab(self):
        vocab = self.vocab.copy()
        vocab.update(self.get_added_vocab())
        return vocab

    def _tokenize(self, text: str) -> List[str]:
        """Take as input a string and return a list of strings (tokens) for words/sub-words"""
        if self.do_lower_case:
            text = text.lower()
        return self._tokenizer.tokenize(text)

    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self._tokenizer.spm.PieceToId(token)

    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        return self._tokenizer.spm.IdToPiece(index) if index < self.vocab_size else self.unk_token

    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        return self._tokenizer.decode(tokens)

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

        - single sequence: [CLS] X [SEP]
        - pair of sequences: [CLS] A [SEP] B [SEP]

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

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """

        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
        cls = [self.cls_token_id]
        sep = [self.sep_token_id]
        return cls + token_ids_0 + sep + token_ids_1 + sep

    def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
        """
        Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

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

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

        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
            )

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

    def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
        sequence pair mask has the following format:

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

        If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

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

        Returns:
            `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]
        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

    def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
        add_prefix_space = kwargs.pop("add_prefix_space", False)
        if is_split_into_words or add_prefix_space:
            text = " " + text
        return (text, kwargs)

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        return self._tokenizer.save_pretrained(save_directory, filename_prefix=filename_prefix)

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.DebertaV2Tokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

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

  • single sequence: [CLS] X [SEP]
  • pair of sequences: [CLS] A [SEP] B [SEP]
PARAMETER DESCRIPTION
token_ids_0

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

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    """
    Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    adding special tokens. A DeBERTa sequence has the following format:

    - single sequence: [CLS] X [SEP]
    - pair of sequences: [CLS] A [SEP] B [SEP]

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

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """

    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + token_ids_1 + sep

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.DebertaV2Tokenizer.convert_tokens_to_string(tokens)

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
154
155
156
def convert_tokens_to_string(self, tokens):
    """Converts a sequence of tokens (string) in a single string."""
    return self._tokenizer.decode(tokens)

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.DebertaV2Tokenizer.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa sequence pair mask has the following format:

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

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

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION

List[int]: List of token type IDs according to the given sequence(s).

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
    """
    Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
    sequence pair mask has the following format:

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

    If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

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

    Returns:
        `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
    """
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]
    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.DebertaV2Tokenizer.get_special_tokens_mask(token_ids_0, token_ids_1=None, already_has_special_tokens=False)

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

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

already_has_special_tokens

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

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

RETURNS DESCRIPTION

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
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
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
    """
    Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
    special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

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

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

    if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
        )

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

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.SPMTokenizer

Constructs a tokenizer based on SentencePiece.

PARAMETER DESCRIPTION
vocab_file

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

TYPE: `str`

sp_model_kwargs

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

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

  • nbest_size = {0,1}: No sampling is performed.

  • nbest_size > 1: samples from the nbest_size results.
  • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.

  • alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
class SPMTokenizer:
    r"""
    Constructs a tokenizer based on [SentencePiece](https://github.com/google/sentencepiece).

    Args:
        vocab_file (`str`):
            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

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

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.
    """

    def __init__(
        self, vocab_file, special_tokens, split_by_punct=False, sp_model_kwargs: Optional[Dict[str, Any]] = None
    ):
        self.split_by_punct = split_by_punct
        self.vocab_file = vocab_file
        self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
        spm = sp.SentencePieceProcessor(**self.sp_model_kwargs)
        if not os.path.exists(vocab_file):
            raise FileNotFoundError(f"{vocab_file} does not exist!")
        spm.load(vocab_file)
        bpe_vocab_size = spm.GetPieceSize()
        # Token map
        # <unk> 0+1
        # <s> 1+1
        # </s> 2+1
        self.vocab = {spm.IdToPiece(i): i for i in range(bpe_vocab_size)}
        self.ids_to_tokens = [spm.IdToPiece(i) for i in range(bpe_vocab_size)]
        # self.vocab['[PAD]'] = 0
        # self.vocab['[CLS]'] = 1
        # self.vocab['[SEP]'] = 2
        # self.vocab['[UNK]'] = 3

        self.spm = spm
        self.special_tokens = special_tokens

    def __getstate__(self):
        state = self.__dict__.copy()
        state["spm"] = None
        return state

    def __setstate__(self, d):
        self.__dict__ = d

        # for backward compatibility
        if not hasattr(self, "sp_model_kwargs"):
            self.sp_model_kwargs = {}

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

    def tokenize(self, text):
        return self._encode_as_pieces(text)

    def convert_ids_to_tokens(self, ids):
        tokens = []
        for i in ids:
            tokens.append(self.ids_to_tokens[i])
        return tokens

    def decode(self, tokens, start=-1, end=-1, raw_text=None):
        if raw_text is None:
            current_sub_tokens = []
            out_string = ""
            prev_is_special = False
            for token in tokens:
                # make sure that special tokens are not decoded using sentencepiece model
                if token in self.special_tokens:
                    if not prev_is_special:
                        out_string += " "
                    out_string += self.spm.decode_pieces(current_sub_tokens) + token
                    prev_is_special = True
                    current_sub_tokens = []
                else:
                    current_sub_tokens.append(token)
                    prev_is_special = False
            out_string += self.spm.decode_pieces(current_sub_tokens)
            return out_string.strip()
        else:
            words = self.split_to_words(raw_text)
            word_tokens = [self.tokenize(w) for w in words]
            token2words = [0] * len(tokens)
            tid = 0
            for i, w in enumerate(word_tokens):
                for k, t in enumerate(w):
                    token2words[tid] = i
                    tid += 1
            word_start = token2words[start]
            word_end = token2words[end] if end < len(tokens) else len(words)
            text = "".join(words[word_start:word_end])
            return text

    # TODO add a deprecation cycle as this can have different behaviour from our API
    def add_special_token(self, token):
        if token not in self.special_tokens:
            self.special_tokens.append(token)
            if token not in self.vocab:
                self.vocab[token] = len(self.vocab) - 1
                self.ids_to_tokens.append(token)
        return self.id(token)

    def part_of_whole_word(self, token, is_bos=False):
        logger.warning_once(
            "The `DebertaTokenizer.part_of_whole_word` method is deprecated and will be removed in `transformers==4.35`"
        )
        if is_bos:
            return True
        if (
            len(token) == 1
            and (_is_whitespace(list(token)[0]) or _is_control(list(token)[0]) or _is_punctuation(list(token)[0]))
        ) or token in self.special_tokens:
            return False

        word_start = b"\xe2\x96\x81".decode("utf-8")
        return not token.startswith(word_start)

    def pad(self):
        return "[PAD]"

    def bos(self):
        return "[CLS]"

    def eos(self):
        return "[SEP]"

    def unk(self):
        return "[UNK]"

    def mask(self):
        return "[MASK]"

    def sym(self, id):
        return self.ids_to_tokens[id]

    def id(self, sym):
        logger.warning_once(
            "The `DebertaTokenizer.id` method is deprecated and will be removed in `transformers==4.35`"
        )
        return self.vocab[sym] if sym in self.vocab else 1

    def _encode_as_pieces(self, text):
        text = convert_to_unicode(text)
        if self.split_by_punct:
            words = self._run_split_on_punc(text)
            pieces = [self.spm.encode(w, out_type=str) for w in words]
            return [p for w in pieces for p in w]
        else:
            return self.spm.encode(text, out_type=str)

    def split_to_words(self, text):
        pieces = self._encode_as_pieces(text)
        word_start = b"\xe2\x96\x81".decode("utf-8")
        words = []
        offset = 0
        prev_end = 0
        for i, p in enumerate(pieces):
            if p.startswith(word_start):
                if offset > prev_end:
                    words.append(text[prev_end:offset])
                prev_end = offset
                w = p.replace(word_start, "")
            else:
                w = p
            try:
                s = text.index(w, offset)
                pn = ""
                k = i + 1
                while k < len(pieces):
                    pn = pieces[k].replace(word_start, "")
                    if len(pn) > 0:
                        break
                    k += 1

                if len(pn) > 0 and pn in text[offset:s]:
                    offset = offset + 1
                else:
                    offset = s + len(w)
            except Exception:
                offset = offset + 1

        if prev_end < offset:
            words.append(text[prev_end:offset])

        return words

    def _run_split_on_punc(self, text):
        """Splits punctuation on a piece of text."""
        chars = list(text)
        i = 0
        start_new_word = True
        output = []
        while i < len(chars):
            char = chars[i]
            if _is_punctuation(char):
                output.append([char])
                start_new_word = True
            else:
                if start_new_word:
                    output.append([])
                start_new_word = False
                output[-1].append(char)
            i += 1

        return ["".join(x) for x in output]

    def save_pretrained(self, path: str, filename_prefix: str = None):
        filename = VOCAB_FILES_NAMES[list(VOCAB_FILES_NAMES.keys())[0]]
        if filename_prefix is not None:
            filename = filename_prefix + "-" + filename
        full_path = os.path.join(path, filename)
        with open(full_path, "wb") as fs:
            fs.write(self.spm.serialized_model_proto())
        return (full_path,)

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2.convert_to_unicode(text)

Converts text to Unicode (if it's not already), assuming utf-8 input.

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2.py
513
514
515
516
517
518
519
520
def convert_to_unicode(text):
    """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
    if isinstance(text, str):
        return text
    elif isinstance(text, bytes):
        return text.decode("utf-8", "ignore")
    else:
        raise ValueError(f"Unsupported string type: {type(text)}")

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2_fast

Fast Tokenization class for model DeBERTa.

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2_fast.DebertaV2TokenizerFast

Bases: PreTrainedTokenizerFast

Constructs a DeBERTa-v2 fast tokenizer. Based on SentencePiece.

PARAMETER DESCRIPTION
vocab_file

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

TYPE: `str` DEFAULT: None

do_lower_case

Whether or not to lowercase the input when tokenizing.

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

bos_token

The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token. When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the cls_token.

TYPE: `string`, *optional*, defaults to `"[CLS]"` DEFAULT: '[CLS]'

eos_token

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

TYPE: `string`, *optional*, defaults to `"[SEP]"` DEFAULT: '[SEP]'

unk_token

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

TYPE: `str`, *optional*, defaults to `"[UNK]"` DEFAULT: '[UNK]'

sep_token

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

TYPE: `str`, *optional*, defaults to `"[SEP]"` DEFAULT: '[SEP]'

pad_token

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

TYPE: `str`, *optional*, defaults to `"[PAD]"` DEFAULT: '[PAD]'

cls_token

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

TYPE: `str`, *optional*, defaults to `"[CLS]"` DEFAULT: '[CLS]'

mask_token

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

TYPE: `str`, *optional*, defaults to `"[MASK]"` DEFAULT: '[MASK]'

sp_model_kwargs

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

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

  • nbest_size = {0,1}: No sampling is performed.

  • nbest_size > 1: samples from the nbest_size results.
  • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.

  • alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout.

TYPE: `dict`, *optional*

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2_fast.py
 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
class DebertaV2TokenizerFast(PreTrainedTokenizerFast):
    r"""
    Constructs a DeBERTa-v2 fast tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).

    Args:
        vocab_file (`str`):
            [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
            contains the vocabulary necessary to instantiate a tokenizer.
        do_lower_case (`bool`, *optional*, defaults to `False`):
            Whether or not to lowercase the input when tokenizing.
        bos_token (`string`, *optional*, defaults to `"[CLS]"`):
            The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.
        eos_token (`string`, *optional*, defaults to `"[SEP]"`):
            The end of sequence token. When building a sequence using special tokens, this is not the token that is
            used for the end of sequence. The token used is the `sep_token`.
        unk_token (`str`, *optional*, defaults to `"[UNK]"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        sep_token (`str`, *optional*, defaults to `"[SEP]"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        pad_token (`str`, *optional*, defaults to `"[PAD]"`):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (`str`, *optional*, defaults to `"[CLS]"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        mask_token (`str`, *optional*, defaults to `"[MASK]"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

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

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.
    """

    vocab_files_names = VOCAB_FILES_NAMES
    slow_tokenizer_class = DebertaV2Tokenizer

    def __init__(
        self,
        vocab_file=None,
        tokenizer_file=None,
        do_lower_case=False,
        split_by_punct=False,
        bos_token="[CLS]",
        eos_token="[SEP]",
        unk_token="[UNK]",
        sep_token="[SEP]",
        pad_token="[PAD]",
        cls_token="[CLS]",
        mask_token="[MASK]",
        **kwargs,
    ) -> None:
        super().__init__(
            vocab_file,
            tokenizer_file=tokenizer_file,
            do_lower_case=do_lower_case,
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            split_by_punct=split_by_punct,
            **kwargs,
        )

        self.do_lower_case = do_lower_case
        self.split_by_punct = split_by_punct
        self.vocab_file = vocab_file

    @property
    def can_save_slow_tokenizer(self) -> bool:
        return os.path.isfile(self.vocab_file) if self.vocab_file else False

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

        - single sequence: [CLS] X [SEP]
        - pair of sequences: [CLS] A [SEP] B [SEP]

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

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """

        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
        cls = [self.cls_token_id]
        sep = [self.sep_token_id]
        return cls + token_ids_0 + sep + token_ids_1 + sep

    def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
        """
        Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

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

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

        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
            )

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

    def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
        sequence pair mask has the following format:

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

        If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

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

        Returns:
            `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]
        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        if not self.can_save_slow_tokenizer:
            raise ValueError(
                "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
                "tokenizer."
            )

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

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

        return (out_vocab_file,)

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2_fast.DebertaV2TokenizerFast.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

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

  • single sequence: [CLS] X [SEP]
  • pair of sequences: [CLS] A [SEP] B [SEP]
PARAMETER DESCRIPTION
token_ids_0

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

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2_fast.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    """
    Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    adding special tokens. A DeBERTa sequence has the following format:

    - single sequence: [CLS] X [SEP]
    - pair of sequences: [CLS] A [SEP] B [SEP]

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

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """

    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + token_ids_1 + sep

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2_fast.DebertaV2TokenizerFast.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa sequence pair mask has the following format:

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

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

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION

List[int]: List of token type IDs according to the given sequence(s).

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2_fast.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
def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
    """
    Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
    sequence pair mask has the following format:

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

    If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

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

    Returns:
        `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
    """
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]
    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

mindnlp.transformers.models.deberta_v2.tokenization_deberta_v2_fast.DebertaV2TokenizerFast.get_special_tokens_mask(token_ids_0, token_ids_1=None, already_has_special_tokens=False)

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

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

already_has_special_tokens

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

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

RETURNS DESCRIPTION

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

Source code in mindnlp/transformers/models/deberta_v2/tokenization_deberta_v2_fast.py
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
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
    """
    Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
    special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.

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

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

    if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
        )

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