Skip to content

convbert

mindnlp.transformers.models.convbert.convbert

ConvBERT model.

mindnlp.transformers.models.convbert.convbert.ConvBertAttention

Bases: Module

ConvBertAttention

Source code in mindnlp/transformers/models/convbert/convbert.py
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
class ConvBertAttention(nn.Module):
    """
    ConvBertAttention
    """
    def __init__(self, config):
        """
        Initializes an instance of the ConvBertAttention class.

        Args:
            self (ConvBertAttention): The instance of the ConvBertAttention class.
            config: The configuration parameters for the ConvBertAttention class.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.self = ConvBertSelfAttention(config)
        self.output = ConvBertSelfOutput(config)
        self.pruned_heads = set()

    def prune_heads(self, heads):
        """prune heads"""
        if len(heads) == 0:
            return
        heads, index = find_pruneable_heads_and_indices(
            heads,
            self.self.num_attention_heads,
            self.self.attention_head_size,
            self.pruned_heads,
        )

        # Prune linear layers
        self.self.query = prune_linear_layer(self.self.query, index)
        self.self.key = prune_linear_layer(self.self.key, index)
        self.self.value = prune_linear_layer(self.self.value, index)
        self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)

        # Update hyper params and store pruned heads
        self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
        self.self.all_head_size = (
            self.self.attention_head_size * self.self.num_attention_heads
        )
        self.pruned_heads = self.pruned_heads.union(heads)

    def forward(
        self,
        hidden_states: ms.Tensor,
        attention_mask: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        encoder_hidden_states: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[ms.Tensor, Optional[ms.Tensor]]:
        """
        This method forwards the output of ConvBertAttention.

        Args:
            self: The instance of ConvBertAttention.
            hidden_states (ms.Tensor): The input hidden states for the attention layer.
            attention_mask (Optional[ms.Tensor]): Optional tensor specifying which elements in the input sequence should be attended to.
            head_mask (Optional[ms.Tensor]): Optional tensor specifying the mask to be applied to the attention heads.
            encoder_hidden_states (Optional[ms.Tensor]): Optional tensor representing the hidden states of the encoder.
            output_attentions (Optional[bool]): Optional flag indicating whether to output the attention weights. Default is False.

        Returns:
            Tuple[ms.Tensor, Optional[ms.Tensor]]:
                A tuple containing the attention output tensor and optionally the attention weights.

        Raises:
            None.
        """
        self_outputs = self.self(
            hidden_states,
            attention_mask,
            head_mask,
            encoder_hidden_states,
            output_attentions,
        )
        attention_output = self.output(self_outputs[0], hidden_states)
        # add attentions if we output them
        outputs = (attention_output,) + self_outputs[1:]
        return outputs

mindnlp.transformers.models.convbert.convbert.ConvBertAttention.__init__(config)

Initializes an instance of the ConvBertAttention class.

PARAMETER DESCRIPTION
self

The instance of the ConvBertAttention class.

TYPE: ConvBertAttention

config

The configuration parameters for the ConvBertAttention class.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/convbert/convbert.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def __init__(self, config):
    """
    Initializes an instance of the ConvBertAttention class.

    Args:
        self (ConvBertAttention): The instance of the ConvBertAttention class.
        config: The configuration parameters for the ConvBertAttention class.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.self = ConvBertSelfAttention(config)
    self.output = ConvBertSelfOutput(config)
    self.pruned_heads = set()

mindnlp.transformers.models.convbert.convbert.ConvBertAttention.forward(hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, output_attentions=False)

This method forwards the output of ConvBertAttention.

PARAMETER DESCRIPTION
self

The instance of ConvBertAttention.

hidden_states

The input hidden states for the attention layer.

TYPE: Tensor

attention_mask

Optional tensor specifying which elements in the input sequence should be attended to.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

Optional tensor specifying the mask to be applied to the attention heads.

TYPE: Optional[Tensor] DEFAULT: None

encoder_hidden_states

Optional tensor representing the hidden states of the encoder.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

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

TYPE: Optional[bool] DEFAULT: False

RETURNS DESCRIPTION
Tuple[Tensor, Optional[Tensor]]

Tuple[ms.Tensor, Optional[ms.Tensor]]: A tuple containing the attention output tensor and optionally the attention weights.

Source code in mindnlp/transformers/models/convbert/convbert.py
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
def forward(
    self,
    hidden_states: ms.Tensor,
    attention_mask: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    encoder_hidden_states: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = False,
) -> Tuple[ms.Tensor, Optional[ms.Tensor]]:
    """
    This method forwards the output of ConvBertAttention.

    Args:
        self: The instance of ConvBertAttention.
        hidden_states (ms.Tensor): The input hidden states for the attention layer.
        attention_mask (Optional[ms.Tensor]): Optional tensor specifying which elements in the input sequence should be attended to.
        head_mask (Optional[ms.Tensor]): Optional tensor specifying the mask to be applied to the attention heads.
        encoder_hidden_states (Optional[ms.Tensor]): Optional tensor representing the hidden states of the encoder.
        output_attentions (Optional[bool]): Optional flag indicating whether to output the attention weights. Default is False.

    Returns:
        Tuple[ms.Tensor, Optional[ms.Tensor]]:
            A tuple containing the attention output tensor and optionally the attention weights.

    Raises:
        None.
    """
    self_outputs = self.self(
        hidden_states,
        attention_mask,
        head_mask,
        encoder_hidden_states,
        output_attentions,
    )
    attention_output = self.output(self_outputs[0], hidden_states)
    # add attentions if we output them
    outputs = (attention_output,) + self_outputs[1:]
    return outputs

mindnlp.transformers.models.convbert.convbert.ConvBertAttention.prune_heads(heads)

prune heads

Source code in mindnlp/transformers/models/convbert/convbert.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def prune_heads(self, heads):
    """prune heads"""
    if len(heads) == 0:
        return
    heads, index = find_pruneable_heads_and_indices(
        heads,
        self.self.num_attention_heads,
        self.self.attention_head_size,
        self.pruned_heads,
    )

    # Prune linear layers
    self.self.query = prune_linear_layer(self.self.query, index)
    self.self.key = prune_linear_layer(self.self.key, index)
    self.self.value = prune_linear_layer(self.self.value, index)
    self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)

    # Update hyper params and store pruned heads
    self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
    self.self.all_head_size = (
        self.self.attention_head_size * self.self.num_attention_heads
    )
    self.pruned_heads = self.pruned_heads.union(heads)

mindnlp.transformers.models.convbert.convbert.ConvBertClassificationHead

Bases: Module

Head for sentence-level classification tasks.

Source code in mindnlp/transformers/models/convbert/convbert.py
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
class ConvBertClassificationHead(nn.Module):
    """Head for sentence-level classification tasks."""
    def __init__(self, config):
        """
        Initializes an instance of the ConvBertClassificationHead class.

        Args:
            self (ConvBertClassificationHead): The instance of the class.
            config: The configuration object that contains the necessary parameters for initialization.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        classifier_dropout = (
            config.classifier_dropout
            if config.classifier_dropout is not None
            else config.hidden_dropout_prob
        )
        self.dropout = nn.Dropout(p=classifier_dropout)
        self.out_proj = nn.Linear(config.hidden_size, config.num_labels)

        self.config = config

    def forward(self, hidden_states: ms.Tensor, **kwargs) -> ms.Tensor:
        """
        This method forwards a classification head for ConvBert model.

        Args:
            self: The instance of the ConvBertClassificationHead class.
            hidden_states (ms.Tensor):
                The input tensor containing the hidden states from the ConvBert model.
                It is expected to have a shape of [batch_size, sequence_length, hidden_size].

        Returns:
            ms.Tensor: A tensor representing the output of the classification head. It has a shape of [batch_size, num_labels].

        Raises:
            None
        """
        x = hidden_states[:, 0, :]  # take <s> token (equiv. to [CLS])
        x = self.dropout(x)
        x = self.dense(x)
        x = ACT2FN[self.config.hidden_act](x)
        x = self.dropout(x)
        x = self.out_proj(x)
        return x

mindnlp.transformers.models.convbert.convbert.ConvBertClassificationHead.__init__(config)

Initializes an instance of the ConvBertClassificationHead class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: ConvBertClassificationHead

config

The configuration object that contains the necessary parameters for initialization.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/convbert/convbert.py
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
def __init__(self, config):
    """
    Initializes an instance of the ConvBertClassificationHead class.

    Args:
        self (ConvBertClassificationHead): The instance of the class.
        config: The configuration object that contains the necessary parameters for initialization.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_size)
    classifier_dropout = (
        config.classifier_dropout
        if config.classifier_dropout is not None
        else config.hidden_dropout_prob
    )
    self.dropout = nn.Dropout(p=classifier_dropout)
    self.out_proj = nn.Linear(config.hidden_size, config.num_labels)

    self.config = config

mindnlp.transformers.models.convbert.convbert.ConvBertClassificationHead.forward(hidden_states, **kwargs)

This method forwards a classification head for ConvBert model.

PARAMETER DESCRIPTION
self

The instance of the ConvBertClassificationHead class.

hidden_states

The input tensor containing the hidden states from the ConvBert model. It is expected to have a shape of [batch_size, sequence_length, hidden_size].

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: A tensor representing the output of the classification head. It has a shape of [batch_size, num_labels].

Source code in mindnlp/transformers/models/convbert/convbert.py
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
def forward(self, hidden_states: ms.Tensor, **kwargs) -> ms.Tensor:
    """
    This method forwards a classification head for ConvBert model.

    Args:
        self: The instance of the ConvBertClassificationHead class.
        hidden_states (ms.Tensor):
            The input tensor containing the hidden states from the ConvBert model.
            It is expected to have a shape of [batch_size, sequence_length, hidden_size].

    Returns:
        ms.Tensor: A tensor representing the output of the classification head. It has a shape of [batch_size, num_labels].

    Raises:
        None
    """
    x = hidden_states[:, 0, :]  # take <s> token (equiv. to [CLS])
    x = self.dropout(x)
    x = self.dense(x)
    x = ACT2FN[self.config.hidden_act](x)
    x = self.dropout(x)
    x = self.out_proj(x)
    return x

mindnlp.transformers.models.convbert.convbert.ConvBertEmbeddings

Bases: Module

Construct the embeddings from word, position and token_type embeddings.

Source code in mindnlp/transformers/models/convbert/convbert.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 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
class ConvBertEmbeddings(nn.Module):
    """Construct the embeddings from word, position and token_type embeddings."""
    def __init__(self, config):
        """
        Initializes the ConvBertEmbeddings object.

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

                - vocab_size (int): The size of the vocabulary.
                - embedding_size (int): The size of the word embeddings.
                - pad_token_id (int): The index of the padding token in the vocabulary.
                - max_position_embeddings (int): The maximum number of positions in the input sequence.
                - type_vocab_size (int): The size of the token type vocabulary.
                - layer_norm_eps (float): The epsilon value for layer normalization.
                - hidden_dropout_prob (float): The dropout probability for the embeddings.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.word_embeddings = nn.Embedding(
            config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id
        )
        self.position_embeddings = nn.Embedding(
            config.max_position_embeddings, config.embedding_size
        )
        self.token_type_embeddings = nn.Embedding(
            config.type_vocab_size, config.embedding_size
        )

        # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
        # any TensorFlow checkpoint file
        self.LayerNorm = nn.LayerNorm(
            config.embedding_size, eps=config.layer_norm_eps
        )
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        # 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)
        )

        self.token_type_ids = ops.zeros(self.position_ids.shape, dtype=ms.int64)

    def forward(
        self,
        input_ids: Optional[ms.Tensor] = None,
        token_type_ids: Optional[ms.Tensor] = None,
        position_ids: Optional[ms.Tensor] = None,
        inputs_embeds: Optional[ms.Tensor] = None,
    ) -> ms.Tensor:
        """
        Constructs the embeddings for ConvBert model.

        Args:
            self (ConvBertEmbeddings): The instance of the ConvBertEmbeddings class.
            input_ids (Optional[ms.Tensor]): The input tensor containing the token indices. Default is None.
            token_type_ids (Optional[ms.Tensor]): The input tensor containing the token type indices. Default is None.
            position_ids (Optional[ms.Tensor]): The input tensor containing the position indices. Default is None.
            inputs_embeds (Optional[ms.Tensor]): The input tensor containing the embedded representation of the input. Default is None.

        Returns:
            ms.Tensor: The forwarded embeddings tensor.

        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]

        # Setting the token_type_ids to the registered buffer in forwardor where it is all zeros, which usually occurs
        # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
        # issue #5664
        if token_type_ids is None:
            if hasattr(self, "token_type_ids"):
                buffered_token_type_ids = self.token_type_ids[:, :seq_length]
                buffered_token_type_ids_expanded = buffered_token_type_ids.broadcast_to(
                    input_shape[0], seq_length
                )
                token_type_ids = buffered_token_type_ids_expanded
            else:
                token_type_ids = ops.zeros(input_shape, dtype=ms.int64)

        if inputs_embeds is None:
            inputs_embeds = self.word_embeddings(input_ids)
        position_embeddings = self.position_embeddings(position_ids)
        token_type_embeddings = self.token_type_embeddings(token_type_ids)

        embeddings = inputs_embeds + position_embeddings + token_type_embeddings
        embeddings = self.LayerNorm(embeddings)
        embeddings = self.dropout(embeddings)
        return embeddings

mindnlp.transformers.models.convbert.convbert.ConvBertEmbeddings.__init__(config)

Initializes the ConvBertEmbeddings object.

PARAMETER DESCRIPTION
self

The current instance of the ConvBertEmbeddings class.

TYPE: ConvBertEmbeddings

config

An object containing the configuration parameters for the ConvBert model.

  • vocab_size (int): The size of the vocabulary.
  • embedding_size (int): The size of the word embeddings.
  • pad_token_id (int): The index of the padding token in the vocabulary.
  • max_position_embeddings (int): The maximum number of positions in the input sequence.
  • type_vocab_size (int): The size of the token type vocabulary.
  • layer_norm_eps (float): The epsilon value for layer normalization.
  • hidden_dropout_prob (float): The dropout probability for the embeddings.

RETURNS DESCRIPTION

None

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

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

            - vocab_size (int): The size of the vocabulary.
            - embedding_size (int): The size of the word embeddings.
            - pad_token_id (int): The index of the padding token in the vocabulary.
            - max_position_embeddings (int): The maximum number of positions in the input sequence.
            - type_vocab_size (int): The size of the token type vocabulary.
            - layer_norm_eps (float): The epsilon value for layer normalization.
            - hidden_dropout_prob (float): The dropout probability for the embeddings.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.word_embeddings = nn.Embedding(
        config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id
    )
    self.position_embeddings = nn.Embedding(
        config.max_position_embeddings, config.embedding_size
    )
    self.token_type_embeddings = nn.Embedding(
        config.type_vocab_size, config.embedding_size
    )

    # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
    # any TensorFlow checkpoint file
    self.LayerNorm = nn.LayerNorm(
        config.embedding_size, eps=config.layer_norm_eps
    )
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    # 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)
    )

    self.token_type_ids = ops.zeros(self.position_ids.shape, dtype=ms.int64)

mindnlp.transformers.models.convbert.convbert.ConvBertEmbeddings.forward(input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None)

Constructs the embeddings for ConvBert model.

PARAMETER DESCRIPTION
self

The instance of the ConvBertEmbeddings class.

TYPE: ConvBertEmbeddings

input_ids

The input tensor containing the token indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The input tensor containing the token type indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The input tensor containing the position indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The input tensor containing the embedded representation of the input. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

RETURNS DESCRIPTION
Tensor

ms.Tensor: The forwarded embeddings tensor.

Source code in mindnlp/transformers/models/convbert/convbert.py
 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
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
) -> ms.Tensor:
    """
    Constructs the embeddings for ConvBert model.

    Args:
        self (ConvBertEmbeddings): The instance of the ConvBertEmbeddings class.
        input_ids (Optional[ms.Tensor]): The input tensor containing the token indices. Default is None.
        token_type_ids (Optional[ms.Tensor]): The input tensor containing the token type indices. Default is None.
        position_ids (Optional[ms.Tensor]): The input tensor containing the position indices. Default is None.
        inputs_embeds (Optional[ms.Tensor]): The input tensor containing the embedded representation of the input. Default is None.

    Returns:
        ms.Tensor: The forwarded embeddings tensor.

    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]

    # Setting the token_type_ids to the registered buffer in forwardor where it is all zeros, which usually occurs
    # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
    # issue #5664
    if token_type_ids is None:
        if hasattr(self, "token_type_ids"):
            buffered_token_type_ids = self.token_type_ids[:, :seq_length]
            buffered_token_type_ids_expanded = buffered_token_type_ids.broadcast_to(
                input_shape[0], seq_length
            )
            token_type_ids = buffered_token_type_ids_expanded
        else:
            token_type_ids = ops.zeros(input_shape, dtype=ms.int64)

    if inputs_embeds is None:
        inputs_embeds = self.word_embeddings(input_ids)
    position_embeddings = self.position_embeddings(position_ids)
    token_type_embeddings = self.token_type_embeddings(token_type_ids)

    embeddings = inputs_embeds + position_embeddings + token_type_embeddings
    embeddings = self.LayerNorm(embeddings)
    embeddings = self.dropout(embeddings)
    return embeddings

mindnlp.transformers.models.convbert.convbert.ConvBertEncoder

Bases: Module

ConvBertEncoder

Source code in mindnlp/transformers/models/convbert/convbert.py
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
class ConvBertEncoder(nn.Module):
    """
    ConvBertEncoder
    """
    def __init__(self, config):
        """
        __init__(self, config)

        Initializes a ConvBertEncoder instance.

        Args:
            self (object): The instance of the ConvBertEncoder class.
            config (object): An object containing configuration parameters for the ConvBertEncoder.
                The config object should have attributes related to the encoder's configuration,
                such as the number of hidden layers, and other relevant settings.
                It should be an instance of a compatible configuration class.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.config = config
        self.layer = nn.ModuleList(
            [ConvBertLayer(config) for _ in range(config.num_hidden_layers)]
        )
        self.gradient_checkpointing = False

    def forward(
        self,
        hidden_states: ms.Tensor,
        attention_mask: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        encoder_hidden_states: Optional[ms.Tensor] = None,
        encoder_attention_mask: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = False,
        output_hidden_states: Optional[bool] = False,
        return_dict: Optional[bool] = True,
    ) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
        """
        This method forwards the ConvBertEncoder by processing the input hidden states through a series of layers.

        Args:
            self: The instance of the ConvBertEncoder class.
            hidden_states (ms.Tensor): The input hidden states to be processed by the encoder.
            attention_mask (Optional[ms.Tensor]): An optional tensor specifying the attention mask for the input.
            head_mask (Optional[ms.Tensor]): An optional tensor providing mask for heads in the multi-head attention mechanism.
            encoder_hidden_states (Optional[ms.Tensor]): An optional tensor representing hidden states from an encoder.
            encoder_attention_mask (Optional[ms.Tensor]): An optional tensor specifying the attention mask for the encoder hidden states.
            output_attentions (Optional[bool]): A flag indicating whether to output attention tensors.
            output_hidden_states (Optional[bool]): A flag indicating whether to output hidden states at each layer.
            return_dict (Optional[bool]): A flag indicating whether to return the output as a dictionary.

        Returns:
            Union[Tuple, BaseModelOutputWithCrossAttentions]: The output of the method which can be a tuple of relevant
            values or a BaseModelOutputWithCrossAttentions object containing the processed hidden states, attentions,
            and cross-attentions.

        Raises:
            None.
        """
        all_hidden_states = () if output_hidden_states else None
        all_self_attentions = () if output_attentions else None
        all_cross_attentions = (
            () if output_attentions and self.config.add_cross_attention else None
        )
        for i, layer_cell in enumerate(self.layer):
            if output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_states,)

            layer_head_mask = head_mask[i] if head_mask is not None else None

            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(
                    layer_cell.__call__,
                    hidden_states,
                    attention_mask,
                    layer_head_mask,
                    encoder_hidden_states,
                    encoder_attention_mask,
                    output_attentions,
                )
            else:
                layer_outputs = layer_cell(
                    hidden_states,
                    attention_mask,
                    layer_head_mask,
                    encoder_hidden_states,
                    encoder_attention_mask,
                    output_attentions,
                )
            hidden_states = layer_outputs[0]
            if output_attentions:
                all_self_attentions = all_self_attentions + (layer_outputs[1],)
                if self.config.add_cross_attention:
                    all_cross_attentions = all_cross_attentions + (layer_outputs[2],)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        if not return_dict:
            return tuple(
                v
                for v in [
                    hidden_states,
                    all_hidden_states,
                    all_self_attentions,
                    all_cross_attentions,
                ]
                if v is not None
            )
        return BaseModelOutputWithCrossAttentions(
            last_hidden_state=hidden_states,
            hidden_states=all_hidden_states,
            attentions=all_self_attentions,
            cross_attentions=all_cross_attentions,
        )

mindnlp.transformers.models.convbert.convbert.ConvBertEncoder.__init__(config)

init(self, config)

Initializes a ConvBertEncoder instance.

PARAMETER DESCRIPTION
self

The instance of the ConvBertEncoder class.

TYPE: object

config

An object containing configuration parameters for the ConvBertEncoder. The config object should have attributes related to the encoder's configuration, such as the number of hidden layers, and other relevant settings. It should be an instance of a compatible configuration class.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
def __init__(self, config):
    """
    __init__(self, config)

    Initializes a ConvBertEncoder instance.

    Args:
        self (object): The instance of the ConvBertEncoder class.
        config (object): An object containing configuration parameters for the ConvBertEncoder.
            The config object should have attributes related to the encoder's configuration,
            such as the number of hidden layers, and other relevant settings.
            It should be an instance of a compatible configuration class.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.config = config
    self.layer = nn.ModuleList(
        [ConvBertLayer(config) for _ in range(config.num_hidden_layers)]
    )
    self.gradient_checkpointing = False

mindnlp.transformers.models.convbert.convbert.ConvBertEncoder.forward(hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True)

This method forwards the ConvBertEncoder by processing the input hidden states through a series of layers.

PARAMETER DESCRIPTION
self

The instance of the ConvBertEncoder class.

hidden_states

The input hidden states to be processed by the encoder.

TYPE: Tensor

attention_mask

An optional tensor specifying the attention mask for the input.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

An optional tensor providing mask for heads in the multi-head attention mechanism.

TYPE: Optional[Tensor] DEFAULT: None

encoder_hidden_states

An optional tensor representing hidden states from an encoder.

TYPE: Optional[Tensor] DEFAULT: None

encoder_attention_mask

An optional tensor specifying the attention mask for the encoder hidden states.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

A flag indicating whether to output attention tensors.

TYPE: Optional[bool] DEFAULT: False

output_hidden_states

A flag indicating whether to output hidden states at each layer.

TYPE: Optional[bool] DEFAULT: False

return_dict

A flag indicating whether to return the output as a dictionary.

TYPE: Optional[bool] DEFAULT: True

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutputWithCrossAttentions]

Union[Tuple, BaseModelOutputWithCrossAttentions]: The output of the method which can be a tuple of relevant

Union[Tuple, BaseModelOutputWithCrossAttentions]

values or a BaseModelOutputWithCrossAttentions object containing the processed hidden states, attentions,

Union[Tuple, BaseModelOutputWithCrossAttentions]

and cross-attentions.

Source code in mindnlp/transformers/models/convbert/convbert.py
 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
def forward(
    self,
    hidden_states: ms.Tensor,
    attention_mask: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    encoder_hidden_states: Optional[ms.Tensor] = None,
    encoder_attention_mask: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = False,
    output_hidden_states: Optional[bool] = False,
    return_dict: Optional[bool] = True,
) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
    """
    This method forwards the ConvBertEncoder by processing the input hidden states through a series of layers.

    Args:
        self: The instance of the ConvBertEncoder class.
        hidden_states (ms.Tensor): The input hidden states to be processed by the encoder.
        attention_mask (Optional[ms.Tensor]): An optional tensor specifying the attention mask for the input.
        head_mask (Optional[ms.Tensor]): An optional tensor providing mask for heads in the multi-head attention mechanism.
        encoder_hidden_states (Optional[ms.Tensor]): An optional tensor representing hidden states from an encoder.
        encoder_attention_mask (Optional[ms.Tensor]): An optional tensor specifying the attention mask for the encoder hidden states.
        output_attentions (Optional[bool]): A flag indicating whether to output attention tensors.
        output_hidden_states (Optional[bool]): A flag indicating whether to output hidden states at each layer.
        return_dict (Optional[bool]): A flag indicating whether to return the output as a dictionary.

    Returns:
        Union[Tuple, BaseModelOutputWithCrossAttentions]: The output of the method which can be a tuple of relevant
        values or a BaseModelOutputWithCrossAttentions object containing the processed hidden states, attentions,
        and cross-attentions.

    Raises:
        None.
    """
    all_hidden_states = () if output_hidden_states else None
    all_self_attentions = () if output_attentions else None
    all_cross_attentions = (
        () if output_attentions and self.config.add_cross_attention else None
    )
    for i, layer_cell in enumerate(self.layer):
        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

        layer_head_mask = head_mask[i] if head_mask is not None else None

        if self.gradient_checkpointing and self.training:
            layer_outputs = self._gradient_checkpointing_func(
                layer_cell.__call__,
                hidden_states,
                attention_mask,
                layer_head_mask,
                encoder_hidden_states,
                encoder_attention_mask,
                output_attentions,
            )
        else:
            layer_outputs = layer_cell(
                hidden_states,
                attention_mask,
                layer_head_mask,
                encoder_hidden_states,
                encoder_attention_mask,
                output_attentions,
            )
        hidden_states = layer_outputs[0]
        if output_attentions:
            all_self_attentions = all_self_attentions + (layer_outputs[1],)
            if self.config.add_cross_attention:
                all_cross_attentions = all_cross_attentions + (layer_outputs[2],)

    if output_hidden_states:
        all_hidden_states = all_hidden_states + (hidden_states,)

    if not return_dict:
        return tuple(
            v
            for v in [
                hidden_states,
                all_hidden_states,
                all_self_attentions,
                all_cross_attentions,
            ]
            if v is not None
        )
    return BaseModelOutputWithCrossAttentions(
        last_hidden_state=hidden_states,
        hidden_states=all_hidden_states,
        attentions=all_self_attentions,
        cross_attentions=all_cross_attentions,
    )

mindnlp.transformers.models.convbert.convbert.ConvBertForMaskedLM

Bases: ConvBertPreTrainedModel

ConvBertForMaskedLM

Source code in mindnlp/transformers/models/convbert/convbert.py
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
class ConvBertForMaskedLM(ConvBertPreTrainedModel):
    """
    ConvBertForMaskedLM
    """
    _tied_weights_keys = ["generator.lm_head.weight"]

    def __init__(self, config):
        """Initialize a ConvBertForMaskedLM object.

        Args:
            self (ConvBertForMaskedLM): An instance of the ConvBertForMaskedLM class.
            config (object): The configuration object that contains the model's hyperparameters and settings.

        Returns:
            None

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

        self.convbert = ConvBertModel(config)
        self.generator_predictions = ConvBertGeneratorPredictions(config)

        self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
        # Initialize weights and apply final processing
        self.post_init()

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

        Args:
            self: The instance of the ConvBertForMaskedLM class.

        Returns:
            None: This method returns the generator_lm_head attribute from the ConvBertForMaskedLM model,
                which contains the output embeddings.

        Raises:
            None.
        """
        return self.generator_lm_head

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

        Args:
            self (ConvBertForMaskedLM): The instance of the ConvBertForMaskedLM class.
            new_embeddings: The new embeddings to be set for the output.
                This should be of the same type and shape as the current embeddings.

        Returns:
            None.

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

    def forward(
        self,
        input_ids: Optional[ms.Tensor] = None,
        attention_mask: Optional[ms.Tensor] = None,
        token_type_ids: Optional[ms.Tensor] = None,
        position_ids: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        inputs_embeds: Optional[ms.Tensor] = None,
        labels: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, MaskedLMOutput]:
        r"""
        Args:
            labels (`ms.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
                config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
                loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
        """
        return_dict = (
            return_dict if return_dict is not None else self.config.use_return_dict
        )

        generator_hidden_states = self.convbert(
            input_ids,
            attention_mask,
            token_type_ids,
            position_ids,
            head_mask,
            inputs_embeds,
            output_attentions,
            output_hidden_states,
            return_dict,
        )
        generator_sequence_output = generator_hidden_states[0]

        prediction_scores = self.generator_predictions(generator_sequence_output)
        prediction_scores = self.generator_lm_head(prediction_scores)

        loss = None
        # Masked language modeling softmax layer
        if labels is not None:
            labels = labels.to(ms.int32)
            loss = ops.cross_entropy(
                prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
            )

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

        return MaskedLMOutput(
            loss=loss,
            logits=prediction_scores,
            hidden_states=generator_hidden_states.hidden_states,
            attentions=generator_hidden_states.attentions,
        )

mindnlp.transformers.models.convbert.convbert.ConvBertForMaskedLM.__init__(config)

Initialize a ConvBertForMaskedLM object.

PARAMETER DESCRIPTION
self

An instance of the ConvBertForMaskedLM class.

TYPE: ConvBertForMaskedLM

config

The configuration object that contains the model's hyperparameters and settings.

TYPE: object

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/convbert/convbert.py
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
def __init__(self, config):
    """Initialize a ConvBertForMaskedLM object.

    Args:
        self (ConvBertForMaskedLM): An instance of the ConvBertForMaskedLM class.
        config (object): The configuration object that contains the model's hyperparameters and settings.

    Returns:
        None

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

    self.convbert = ConvBertModel(config)
    self.generator_predictions = ConvBertGeneratorPredictions(config)

    self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.convbert.convbert.ConvBertForMaskedLM.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

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

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

Source code in mindnlp/transformers/models/convbert/convbert.py
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
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    attention_mask: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
    labels: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, MaskedLMOutput]:
    r"""
    Args:
        labels (`ms.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
    """
    return_dict = (
        return_dict if return_dict is not None else self.config.use_return_dict
    )

    generator_hidden_states = self.convbert(
        input_ids,
        attention_mask,
        token_type_ids,
        position_ids,
        head_mask,
        inputs_embeds,
        output_attentions,
        output_hidden_states,
        return_dict,
    )
    generator_sequence_output = generator_hidden_states[0]

    prediction_scores = self.generator_predictions(generator_sequence_output)
    prediction_scores = self.generator_lm_head(prediction_scores)

    loss = None
    # Masked language modeling softmax layer
    if labels is not None:
        labels = labels.to(ms.int32)
        loss = ops.cross_entropy(
            prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
        )

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

    return MaskedLMOutput(
        loss=loss,
        logits=prediction_scores,
        hidden_states=generator_hidden_states.hidden_states,
        attentions=generator_hidden_states.attentions,
    )

mindnlp.transformers.models.convbert.convbert.ConvBertForMaskedLM.get_output_embeddings()

Method to retrieve the output embeddings from the ConvBertForMaskedLM model.

PARAMETER DESCRIPTION
self

The instance of the ConvBertForMaskedLM class.

RETURNS DESCRIPTION
None

This method returns the generator_lm_head attribute from the ConvBertForMaskedLM model, which contains the output embeddings.

Source code in mindnlp/transformers/models/convbert/convbert.py
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
def get_output_embeddings(self):
    """
    Method to retrieve the output embeddings from the ConvBertForMaskedLM model.

    Args:
        self: The instance of the ConvBertForMaskedLM class.

    Returns:
        None: This method returns the generator_lm_head attribute from the ConvBertForMaskedLM model,
            which contains the output embeddings.

    Raises:
        None.
    """
    return self.generator_lm_head

mindnlp.transformers.models.convbert.convbert.ConvBertForMaskedLM.set_output_embeddings(new_embeddings)

Sets the output embeddings for the ConvBertForMaskedLM model.

PARAMETER DESCRIPTION
self

The instance of the ConvBertForMaskedLM class.

TYPE: ConvBertForMaskedLM

new_embeddings

The new embeddings to be set for the output. This should be of the same type and shape as the current embeddings.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
def set_output_embeddings(self, new_embeddings):
    """
    Sets the output embeddings for the ConvBertForMaskedLM model.

    Args:
        self (ConvBertForMaskedLM): The instance of the ConvBertForMaskedLM class.
        new_embeddings: The new embeddings to be set for the output.
            This should be of the same type and shape as the current embeddings.

    Returns:
        None.

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

mindnlp.transformers.models.convbert.convbert.ConvBertForMultipleChoice

Bases: ConvBertPreTrainedModel

ConvBertForMultipleChoice

Source code in mindnlp/transformers/models/convbert/convbert.py
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
class ConvBertForMultipleChoice(ConvBertPreTrainedModel):
    """
    ConvBertForMultipleChoice
    """
    def __init__(self, config):
        """
        Initialize the ConvBertForMultipleChoice class.

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

        Returns:
            None.

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

        self.convbert = ConvBertModel(config)
        self.sequence_summary = SequenceSummary(config)
        self.classifier = nn.Linear(config.hidden_size, 1)

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

    def forward(
        self,
        input_ids: Optional[ms.Tensor] = None,
        attention_mask: Optional[ms.Tensor] = None,
        token_type_ids: Optional[ms.Tensor] = None,
        position_ids: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        inputs_embeds: Optional[ms.Tensor] = None,
        labels: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, MultipleChoiceModelOutput]:
        r"""
        Args:
            labels (`ms.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
                num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
                `input_ids` above)
        """
        return_dict = (
            return_dict if return_dict is not None else self.config.use_return_dict
        )
        num_choices = (
            input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
        )

        input_ids = (
            input_ids.view(-1, input_ids.shape[-1]) if input_ids is not None else None
        )
        attention_mask = (
            attention_mask.view(-1, attention_mask.shape[-1])
            if attention_mask is not None
            else None
        )
        token_type_ids = (
            token_type_ids.view(-1, token_type_ids.shape[-1])
            if token_type_ids is not None
            else None
        )
        position_ids = (
            position_ids.view(-1, position_ids.shape[-1])
            if position_ids is not None
            else None
        )
        inputs_embeds = (
            inputs_embeds.view(-1, inputs_embeds.shape[-2], inputs_embeds.shape[-1])
            if inputs_embeds is not None
            else None
        )

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

        sequence_output = outputs[0]

        pooled_output = self.sequence_summary(sequence_output)
        logits = self.classifier(pooled_output)
        reshaped_logits = logits.view(-1, num_choices)

        loss = None
        if labels is not None:
            labels = labels.to(ms.int32)
            loss = ops.cross_entropy(reshaped_logits, labels)

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

        return MultipleChoiceModelOutput(
            loss=loss,
            logits=reshaped_logits,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

mindnlp.transformers.models.convbert.convbert.ConvBertForMultipleChoice.__init__(config)

Initialize the ConvBertForMultipleChoice class.

PARAMETER DESCRIPTION
self

The instance of the ConvBertForMultipleChoice class.

TYPE: object

config

The configuration object containing various parameters for the model initialization.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
def __init__(self, config):
    """
    Initialize the ConvBertForMultipleChoice class.

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

    Returns:
        None.

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

    self.convbert = ConvBertModel(config)
    self.sequence_summary = SequenceSummary(config)
    self.classifier = nn.Linear(config.hidden_size, 1)

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

mindnlp.transformers.models.convbert.convbert.ConvBertForMultipleChoice.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices-1] where num_choices is the size of the second dimension of the input tensors. (See input_ids above)

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

Source code in mindnlp/transformers/models/convbert/convbert.py
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    attention_mask: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
    labels: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, MultipleChoiceModelOutput]:
    r"""
    Args:
        labels (`ms.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)
    """
    return_dict = (
        return_dict if return_dict is not None else self.config.use_return_dict
    )
    num_choices = (
        input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
    )

    input_ids = (
        input_ids.view(-1, input_ids.shape[-1]) if input_ids is not None else None
    )
    attention_mask = (
        attention_mask.view(-1, attention_mask.shape[-1])
        if attention_mask is not None
        else None
    )
    token_type_ids = (
        token_type_ids.view(-1, token_type_ids.shape[-1])
        if token_type_ids is not None
        else None
    )
    position_ids = (
        position_ids.view(-1, position_ids.shape[-1])
        if position_ids is not None
        else None
    )
    inputs_embeds = (
        inputs_embeds.view(-1, inputs_embeds.shape[-2], inputs_embeds.shape[-1])
        if inputs_embeds is not None
        else None
    )

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

    sequence_output = outputs[0]

    pooled_output = self.sequence_summary(sequence_output)
    logits = self.classifier(pooled_output)
    reshaped_logits = logits.view(-1, num_choices)

    loss = None
    if labels is not None:
        labels = labels.to(ms.int32)
        loss = ops.cross_entropy(reshaped_logits, labels)

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

    return MultipleChoiceModelOutput(
        loss=loss,
        logits=reshaped_logits,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
    )

mindnlp.transformers.models.convbert.convbert.ConvBertForQuestionAnswering

Bases: ConvBertPreTrainedModel

ConvBertForQuestionAnswering

Source code in mindnlp/transformers/models/convbert/convbert.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
class ConvBertForQuestionAnswering(ConvBertPreTrainedModel):
    """
    ConvBertForQuestionAnswering
    """
    def __init__(self, config):
        """
        Initializes an instance of ConvBertForQuestionAnswering.

        Args:
            self (object): The instance of the class.
            config (object):
                Configuration object containing the model's settings.

                - num_labels (int): The number of labels for the model.

        Returns:
            None.

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

        self.num_labels = config.num_labels
        self.convbert = ConvBertModel(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[ms.Tensor] = None,
        attention_mask: Optional[ms.Tensor] = None,
        token_type_ids: Optional[ms.Tensor] = None,
        position_ids: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        inputs_embeds: Optional[ms.Tensor] = None,
        start_positions: Optional[ms.Tensor] = None,
        end_positions: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, QuestionAnsweringModelOutput]:
        """
        Constructs the ConvBertForQuestionAnswering model.

        Args:
            self: An instance of the ConvBertForQuestionAnswering class.
            input_ids (Optional[ms.Tensor]): The input token IDs. Default is None.
            attention_mask (Optional[ms.Tensor]): The attention mask. Default is None.
            token_type_ids (Optional[ms.Tensor]): The token type IDs. Default is None.
            position_ids (Optional[ms.Tensor]): The position IDs. Default is None.
            head_mask (Optional[ms.Tensor]): The head mask. Default is None.
            inputs_embeds (Optional[ms.Tensor]): The input embeddings. Default is None.
            start_positions (Optional[ms.Tensor]): The start positions for question answering. Default is None.
            end_positions (Optional[ms.Tensor]): The end positions for question answering. Default is None.
            output_attentions (Optional[bool]): Whether to output attentions. Default is None.
            output_hidden_states (Optional[bool]): Whether to output hidden states. Default is None.
            return_dict (Optional[bool]): Whether to return a dictionary output. Default is None.

        Returns:
            Union[Tuple, QuestionAnsweringModelOutput]:
                The model output.

                - If return_dict is False, returns a tuple containing the start logits, end logits, and additional outputs.
                - If return_dict is True, returns a QuestionAnsweringModelOutput object containing the loss,
                start logits, end logits, hidden states, and attentions.

        Raises:
            None.
        """
        return_dict = (
            return_dict if return_dict is not None else self.config.use_return_dict
        )

        outputs = self.convbert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            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).to(ms.int32)
            end_positions = end_positions.clamp(0, ignored_index).to(ms.int32)

            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.convbert.convbert.ConvBertForQuestionAnswering.__init__(config)

Initializes an instance of ConvBertForQuestionAnswering.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

config

Configuration object containing the model's settings.

  • num_labels (int): The number of labels for the model.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
def __init__(self, config):
    """
    Initializes an instance of ConvBertForQuestionAnswering.

    Args:
        self (object): The instance of the class.
        config (object):
            Configuration object containing the model's settings.

            - num_labels (int): The number of labels for the model.

    Returns:
        None.

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

    self.num_labels = config.num_labels
    self.convbert = ConvBertModel(config)
    self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.convbert.convbert.ConvBertForQuestionAnswering.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the ConvBertForQuestionAnswering model.

PARAMETER DESCRIPTION
self

An instance of the ConvBertForQuestionAnswering class.

input_ids

The input token IDs. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The token type IDs. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The position IDs. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The head mask. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The input embeddings. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

start_positions

The start positions for question answering. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

end_positions

The end positions for question answering. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output attentions. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output hidden states. Default is None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary output. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, QuestionAnsweringModelOutput]

Union[Tuple, QuestionAnsweringModelOutput]: The model output.

  • If return_dict is False, returns a tuple containing the start logits, end logits, and additional outputs.
  • If return_dict is True, returns a QuestionAnsweringModelOutput object containing the loss, start logits, end logits, hidden states, and attentions.
Source code in mindnlp/transformers/models/convbert/convbert.py
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    attention_mask: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
    start_positions: Optional[ms.Tensor] = None,
    end_positions: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, QuestionAnsweringModelOutput]:
    """
    Constructs the ConvBertForQuestionAnswering model.

    Args:
        self: An instance of the ConvBertForQuestionAnswering class.
        input_ids (Optional[ms.Tensor]): The input token IDs. Default is None.
        attention_mask (Optional[ms.Tensor]): The attention mask. Default is None.
        token_type_ids (Optional[ms.Tensor]): The token type IDs. Default is None.
        position_ids (Optional[ms.Tensor]): The position IDs. Default is None.
        head_mask (Optional[ms.Tensor]): The head mask. Default is None.
        inputs_embeds (Optional[ms.Tensor]): The input embeddings. Default is None.
        start_positions (Optional[ms.Tensor]): The start positions for question answering. Default is None.
        end_positions (Optional[ms.Tensor]): The end positions for question answering. Default is None.
        output_attentions (Optional[bool]): Whether to output attentions. Default is None.
        output_hidden_states (Optional[bool]): Whether to output hidden states. Default is None.
        return_dict (Optional[bool]): Whether to return a dictionary output. Default is None.

    Returns:
        Union[Tuple, QuestionAnsweringModelOutput]:
            The model output.

            - If return_dict is False, returns a tuple containing the start logits, end logits, and additional outputs.
            - If return_dict is True, returns a QuestionAnsweringModelOutput object containing the loss,
            start logits, end logits, hidden states, and attentions.

    Raises:
        None.
    """
    return_dict = (
        return_dict if return_dict is not None else self.config.use_return_dict
    )

    outputs = self.convbert(
        input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        head_mask=head_mask,
        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).to(ms.int32)
        end_positions = end_positions.clamp(0, ignored_index).to(ms.int32)

        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.convbert.convbert.ConvBertForSequenceClassification

Bases: ConvBertPreTrainedModel

ConvBertForSequenceClassification

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

        Args:
            self (ConvBertForSequenceClassification): The current instance of the ConvBertForSequenceClassification class.
            config (ConvBertConfig):
                The configuration object for ConvBertForSequenceClassification.

                - num_labels (int): The number of labels for classification.
                - ... (other configuration parameters)

        Returns:
            None

        Raises:
            None
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.config = config
        self.convbert = ConvBertModel(config)
        self.classifier = ConvBertClassificationHead(config)

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

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

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

        sequence_output = outputs[0]
        logits = self.classifier(sequence_output)

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

            if self.config.problem_type == "regression":
                if self.num_labels == 1:
                    loss = ops.mse_loss(logits.squeeze(), labels.squeeze())
                else:
                    loss = ops.mse_loss(logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss = ops.binary_cross_entropy_with_logits(logits, labels)

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

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

mindnlp.transformers.models.convbert.convbert.ConvBertForSequenceClassification.__init__(config)

Initializes a new instance of ConvBertForSequenceClassification.

PARAMETER DESCRIPTION
self

The current instance of the ConvBertForSequenceClassification class.

TYPE: ConvBertForSequenceClassification

config

The configuration object for ConvBertForSequenceClassification.

  • num_labels (int): The number of labels for classification.
  • ... (other configuration parameters)

TYPE: ConvBertConfig

RETURNS DESCRIPTION

None

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

    Args:
        self (ConvBertForSequenceClassification): The current instance of the ConvBertForSequenceClassification class.
        config (ConvBertConfig):
            The configuration object for ConvBertForSequenceClassification.

            - num_labels (int): The number of labels for classification.
            - ... (other configuration parameters)

    Returns:
        None

    Raises:
        None
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.config = config
    self.convbert = ConvBertModel(config)
    self.classifier = ConvBertClassificationHead(config)

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

mindnlp.transformers.models.convbert.convbert.ConvBertForSequenceClassification.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

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

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

Source code in mindnlp/transformers/models/convbert/convbert.py
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
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    attention_mask: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
    labels: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, SequenceClassifierOutput]:
    r"""
    Args:
        labels (`ms.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
    """
    return_dict = (
        return_dict if return_dict is not None else self.config.use_return_dict
    )

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

    sequence_output = outputs[0]
    logits = self.classifier(sequence_output)

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

        if self.config.problem_type == "regression":
            if self.num_labels == 1:
                loss = ops.mse_loss(logits.squeeze(), labels.squeeze())
            else:
                loss = ops.mse_loss(logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
        elif self.config.problem_type == "multi_label_classification":
            loss = ops.binary_cross_entropy_with_logits(logits, labels)

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

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

mindnlp.transformers.models.convbert.convbert.ConvBertForTokenClassification

Bases: ConvBertPreTrainedModel

ConvBertForTokenClassification

Source code in mindnlp/transformers/models/convbert/convbert.py
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
class ConvBertForTokenClassification(ConvBertPreTrainedModel):
    """
    ConvBertForTokenClassification
    """
    def __init__(self, config):
        """
        Initializes an instance of the ConvBertForTokenClassification class.

        Args:
            self (ConvBertForTokenClassification): The object itself.
            config: The configuration object containing various settings for the ConvBert model.

        Returns:
            None.

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

        self.convbert = ConvBertModel(config)
        classifier_dropout = (
            config.classifier_dropout
            if config.classifier_dropout is not None
            else config.hidden_dropout_prob
        )
        self.dropout = nn.Dropout(p=classifier_dropout)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

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

    def forward(
        self,
        input_ids: Optional[ms.Tensor] = None,
        attention_mask: Optional[ms.Tensor] = None,
        token_type_ids: Optional[ms.Tensor] = None,
        position_ids: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        inputs_embeds: Optional[ms.Tensor] = None,
        labels: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, TokenClassifierOutput]:
        r"""
        Args:
            labels (`ms.Tensor` 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.convbert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            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:
            labels = labels.to(ms.int32)
            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.convbert.convbert.ConvBertForTokenClassification.__init__(config)

Initializes an instance of the ConvBertForTokenClassification class.

PARAMETER DESCRIPTION
self

The object itself.

TYPE: ConvBertForTokenClassification

config

The configuration object containing various settings for the ConvBert model.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
def __init__(self, config):
    """
    Initializes an instance of the ConvBertForTokenClassification class.

    Args:
        self (ConvBertForTokenClassification): The object itself.
        config: The configuration object containing various settings for the ConvBert model.

    Returns:
        None.

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

    self.convbert = ConvBertModel(config)
    classifier_dropout = (
        config.classifier_dropout
        if config.classifier_dropout is not None
        else config.hidden_dropout_prob
    )
    self.dropout = nn.Dropout(p=classifier_dropout)
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.convbert.convbert.ConvBertForTokenClassification.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=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: `ms.Tensor` of shape `(batch_size, sequence_length)`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/convbert/convbert.py
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    attention_mask: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
    labels: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, TokenClassifierOutput]:
    r"""
    Args:
        labels (`ms.Tensor` 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.convbert(
        input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        head_mask=head_mask,
        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:
        labels = labels.to(ms.int32)
        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.convbert.convbert.ConvBertGeneratorPredictions

Bases: Module

Prediction cell for the generator, made up of two dense layers.

Source code in mindnlp/transformers/models/convbert/convbert.py
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
class ConvBertGeneratorPredictions(nn.Module):
    """Prediction cell for the generator, made up of two dense layers."""
    def __init__(self, config):
        """
        Initializes an instance of the ConvBertGeneratorPredictions class.

        Args:
            self (ConvBertGeneratorPredictions): The current instance of the ConvBertGeneratorPredictions class.
            config: A configuration object containing various settings for the ConvBertGeneratorPredictions.

        Returns:
            None

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

        self.activation = get_activation("gelu")
        self.LayerNorm = nn.LayerNorm(
            config.embedding_size, eps=config.layer_norm_eps
        )
        self.dense = nn.Linear(config.hidden_size, config.embedding_size)

    def forward(self, generator_hidden_states: ms.Tensor) -> ms.Tensor:
        """
        Constructs the generator predictions based on the given generator hidden states.

        Args:
            self: An instance of the ConvBertGeneratorPredictions class.
            generator_hidden_states (ms.Tensor): The hidden states generated by the generator.
                It should be a tensor of shape (batch_size, sequence_length, hidden_size).
                The hidden_size is the dimensionality of the hidden states.

        Returns:
            ms.Tensor: The forwarded generator predictions.
                It is a tensor of shape (batch_size, sequence_length, hidden_size).
                The hidden_size is the same as the input hidden states.

        Raises:
            None.
        """
        hidden_states = self.dense(generator_hidden_states)
        hidden_states = self.activation(hidden_states)
        hidden_states = self.LayerNorm(hidden_states)

        return hidden_states

mindnlp.transformers.models.convbert.convbert.ConvBertGeneratorPredictions.__init__(config)

Initializes an instance of the ConvBertGeneratorPredictions class.

PARAMETER DESCRIPTION
self

The current instance of the ConvBertGeneratorPredictions class.

TYPE: ConvBertGeneratorPredictions

config

A configuration object containing various settings for the ConvBertGeneratorPredictions.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/convbert/convbert.py
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
def __init__(self, config):
    """
    Initializes an instance of the ConvBertGeneratorPredictions class.

    Args:
        self (ConvBertGeneratorPredictions): The current instance of the ConvBertGeneratorPredictions class.
        config: A configuration object containing various settings for the ConvBertGeneratorPredictions.

    Returns:
        None

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

    self.activation = get_activation("gelu")
    self.LayerNorm = nn.LayerNorm(
        config.embedding_size, eps=config.layer_norm_eps
    )
    self.dense = nn.Linear(config.hidden_size, config.embedding_size)

mindnlp.transformers.models.convbert.convbert.ConvBertGeneratorPredictions.forward(generator_hidden_states)

Constructs the generator predictions based on the given generator hidden states.

PARAMETER DESCRIPTION
self

An instance of the ConvBertGeneratorPredictions class.

generator_hidden_states

The hidden states generated by the generator. It should be a tensor of shape (batch_size, sequence_length, hidden_size). The hidden_size is the dimensionality of the hidden states.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: The forwarded generator predictions. It is a tensor of shape (batch_size, sequence_length, hidden_size). The hidden_size is the same as the input hidden states.

Source code in mindnlp/transformers/models/convbert/convbert.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
def forward(self, generator_hidden_states: ms.Tensor) -> ms.Tensor:
    """
    Constructs the generator predictions based on the given generator hidden states.

    Args:
        self: An instance of the ConvBertGeneratorPredictions class.
        generator_hidden_states (ms.Tensor): The hidden states generated by the generator.
            It should be a tensor of shape (batch_size, sequence_length, hidden_size).
            The hidden_size is the dimensionality of the hidden states.

    Returns:
        ms.Tensor: The forwarded generator predictions.
            It is a tensor of shape (batch_size, sequence_length, hidden_size).
            The hidden_size is the same as the input hidden states.

    Raises:
        None.
    """
    hidden_states = self.dense(generator_hidden_states)
    hidden_states = self.activation(hidden_states)
    hidden_states = self.LayerNorm(hidden_states)

    return hidden_states

mindnlp.transformers.models.convbert.convbert.ConvBertIntermediate

Bases: Module

ConvBertIntermediate

Source code in mindnlp/transformers/models/convbert/convbert.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
class ConvBertIntermediate(nn.Module):
    """
    ConvBertIntermediate
    """
    def __init__(self, config):
        """
        Initializes an instance of the ConvBertIntermediate class with the provided configuration.

        Args:
            self (ConvBertIntermediate): The current instance of the ConvBertIntermediate class.
            config (object):
                An object containing configuration parameters for the intermediate layer.

                - num_groups (int): The number of groups for the intermediate layer.
                Must be an integer greater than or equal to 1.
                - hidden_size (int): The size of the hidden layer.
                Must be an integer specifying the size of the hidden layer.
                - intermediate_size (int): The size of the intermediate layer.
                Must be an integer specifying the size of the intermediate layer.
                - hidden_act (str or function): The activation function for the hidden layer.
                Must be a string representing a predefined activation function or a custom activation function.

        Returns:
            None.

        Raises:
            ValueError: If the num_groups parameter is not an integer greater than or equal to 1.
            ValueError: If the hidden_size parameter is not an integer.
            ValueError: If the intermediate_size parameter is not an integer.
            ValueError: If the hidden_act parameter is not a valid string or function.
        """
        super().__init__()
        if config.num_groups == 1:
            self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        else:
            self.dense = GroupedLinearLayer(
                input_size=config.hidden_size,
                output_size=config.intermediate_size,
                num_groups=config.num_groups,
            )
        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: ms.Tensor) -> ms.Tensor:
        '''
        This method forwards the intermediate layer in the ConvBert model.

        Args:
            self (ConvBertIntermediate): The instance of the ConvBertIntermediate class.
            hidden_states (ms.Tensor): The input tensor containing the hidden states.

        Returns:
            ms.Tensor: Returns the tensor representing the forwarded intermediate layer.

        Raises:
            None
        '''
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        return hidden_states

mindnlp.transformers.models.convbert.convbert.ConvBertIntermediate.__init__(config)

Initializes an instance of the ConvBertIntermediate class with the provided configuration.

PARAMETER DESCRIPTION
self

The current instance of the ConvBertIntermediate class.

TYPE: ConvBertIntermediate

config

An object containing configuration parameters for the intermediate layer.

  • num_groups (int): The number of groups for the intermediate layer. Must be an integer greater than or equal to 1.
  • hidden_size (int): The size of the hidden layer. Must be an integer specifying the size of the hidden layer.
  • intermediate_size (int): The size of the intermediate layer. Must be an integer specifying the size of the intermediate layer.
  • hidden_act (str or function): The activation function for the hidden layer. Must be a string representing a predefined activation function or a custom activation function.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the num_groups parameter is not an integer greater than or equal to 1.

ValueError

If the hidden_size parameter is not an integer.

ValueError

If the intermediate_size parameter is not an integer.

ValueError

If the hidden_act parameter is not a valid string or function.

Source code in mindnlp/transformers/models/convbert/convbert.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
def __init__(self, config):
    """
    Initializes an instance of the ConvBertIntermediate class with the provided configuration.

    Args:
        self (ConvBertIntermediate): The current instance of the ConvBertIntermediate class.
        config (object):
            An object containing configuration parameters for the intermediate layer.

            - num_groups (int): The number of groups for the intermediate layer.
            Must be an integer greater than or equal to 1.
            - hidden_size (int): The size of the hidden layer.
            Must be an integer specifying the size of the hidden layer.
            - intermediate_size (int): The size of the intermediate layer.
            Must be an integer specifying the size of the intermediate layer.
            - hidden_act (str or function): The activation function for the hidden layer.
            Must be a string representing a predefined activation function or a custom activation function.

    Returns:
        None.

    Raises:
        ValueError: If the num_groups parameter is not an integer greater than or equal to 1.
        ValueError: If the hidden_size parameter is not an integer.
        ValueError: If the intermediate_size parameter is not an integer.
        ValueError: If the hidden_act parameter is not a valid string or function.
    """
    super().__init__()
    if config.num_groups == 1:
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
    else:
        self.dense = GroupedLinearLayer(
            input_size=config.hidden_size,
            output_size=config.intermediate_size,
            num_groups=config.num_groups,
        )
    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.convbert.convbert.ConvBertIntermediate.forward(hidden_states)

This method forwards the intermediate layer in the ConvBert model.

PARAMETER DESCRIPTION
self

The instance of the ConvBertIntermediate class.

TYPE: ConvBertIntermediate

hidden_states

The input tensor containing the hidden states.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: Returns the tensor representing the forwarded intermediate layer.

Source code in mindnlp/transformers/models/convbert/convbert.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
    '''
    This method forwards the intermediate layer in the ConvBert model.

    Args:
        self (ConvBertIntermediate): The instance of the ConvBertIntermediate class.
        hidden_states (ms.Tensor): The input tensor containing the hidden states.

    Returns:
        ms.Tensor: Returns the tensor representing the forwarded intermediate layer.

    Raises:
        None
    '''
    hidden_states = self.dense(hidden_states)
    hidden_states = self.intermediate_act_fn(hidden_states)
    return hidden_states

mindnlp.transformers.models.convbert.convbert.ConvBertLayer

Bases: Module

ConvBertLayer

Source code in mindnlp/transformers/models/convbert/convbert.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
class ConvBertLayer(nn.Module):
    """
    ConvBertLayer
    """
    def __init__(self, config):
        """
        Initializes a new instance of the ConvBertLayer class.

        Args:
            self: The current object instance.
            config: An object of type 'config' containing the configuration settings for the ConvBertLayer.

        Returns:
            None.

        Raises:
            TypeError: Raised if the 'add_cross_attention' flag is set to True but the ConvBertLayer is not used as a decoder model.
        """
        super().__init__()
        self.chunk_size_feed_forward = config.chunk_size_feed_forward
        self.seq_len_dim = 1
        self.attention = ConvBertAttention(config)
        self.is_decoder = config.is_decoder
        self.add_cross_attention = config.add_cross_attention
        if self.add_cross_attention:
            if not self.is_decoder:
                raise TypeError(
                    f"{self} should be used as a decoder model if cross attention is added"
                )
            self.crossattention = ConvBertAttention(config)
        self.intermediate = ConvBertIntermediate(config)
        self.output = ConvBertOutput(config)

    def forward(
        self,
        hidden_states: ms.Tensor,
        attention_mask: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        encoder_hidden_states: Optional[ms.Tensor] = None,
        encoder_attention_mask: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[ms.Tensor, Optional[ms.Tensor]]:
        """
        Constructs a ConvBertLayer.

        This method applies the ConvBertLayer transformation to the input hidden states and returns the
        transformed output. It also supports cross-attention if `encoder_hidden_states` are provided.

        Args:
            self (ConvBertLayer): An instance of the ConvBertLayer class.
            hidden_states (ms.Tensor): The input hidden states of shape (batch_size, seq_len, hidden_size).
            attention_mask (Optional[ms.Tensor]):
                The attention mask of shape (batch_size, seq_len) or (batch_size, seq_len, seq_len). Defaults to None.
            head_mask (Optional[ms.Tensor]):
                The head mask of shape (num_heads,) or (num_layers, num_heads). Defaults to None.
            encoder_hidden_states (Optional[ms.Tensor]):
                The hidden states of the encoder if cross-attention is enabled. Defaults to None.
            encoder_attention_mask (Optional[ms.Tensor]):
                The attention mask of the encoder if cross-attention is enabled. Defaults to None.
            output_attentions (Optional[bool]): Whether to output attentions. Defaults to False.

        Returns:
            Tuple[ms.Tensor, Optional[ms.Tensor]]: A tuple containing the transformed output tensor and
                optional attention tensors.

        Raises:
            AttributeError:
                If `encoder_hidden_states` are passed, `self` has to be instantiated with cross-attention layers
                by setting `config.add_cross_attention=True`.
        """
        self_attention_outputs = self.attention(
            hidden_states,
            attention_mask,
            head_mask,
            output_attentions=output_attentions,
        )
        attention_output = self_attention_outputs[0]
        # add self attentions if we output attention weights
        outputs = self_attention_outputs[1:]

        if self.is_decoder and encoder_hidden_states is not None:
            if not hasattr(self, "crossattention"):
                raise AttributeError(
                    f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
                    " by setting `config.add_cross_attention=True`"
                )
            cross_attention_outputs = self.crossattention(
                attention_output,
                encoder_attention_mask,
                head_mask,
                encoder_hidden_states,
                output_attentions,
            )
            attention_output = cross_attention_outputs[0]
            # add cross attentions if we output attention weights
            outputs = outputs + cross_attention_outputs[1:]

        layer_output = apply_chunking_to_forward(
            self.feed_forward_chunk,
            self.chunk_size_feed_forward,
            self.seq_len_dim,
            attention_output,
        )
        outputs = (layer_output,) + outputs
        return outputs

    def feed_forward_chunk(self, attention_output):
        """feed forward chunk"""
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        return layer_output

mindnlp.transformers.models.convbert.convbert.ConvBertLayer.__init__(config)

Initializes a new instance of the ConvBertLayer class.

PARAMETER DESCRIPTION
self

The current object instance.

config

An object of type 'config' containing the configuration settings for the ConvBertLayer.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

Raised if the 'add_cross_attention' flag is set to True but the ConvBertLayer is not used as a decoder model.

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

    Args:
        self: The current object instance.
        config: An object of type 'config' containing the configuration settings for the ConvBertLayer.

    Returns:
        None.

    Raises:
        TypeError: Raised if the 'add_cross_attention' flag is set to True but the ConvBertLayer is not used as a decoder model.
    """
    super().__init__()
    self.chunk_size_feed_forward = config.chunk_size_feed_forward
    self.seq_len_dim = 1
    self.attention = ConvBertAttention(config)
    self.is_decoder = config.is_decoder
    self.add_cross_attention = config.add_cross_attention
    if self.add_cross_attention:
        if not self.is_decoder:
            raise TypeError(
                f"{self} should be used as a decoder model if cross attention is added"
            )
        self.crossattention = ConvBertAttention(config)
    self.intermediate = ConvBertIntermediate(config)
    self.output = ConvBertOutput(config)

mindnlp.transformers.models.convbert.convbert.ConvBertLayer.feed_forward_chunk(attention_output)

feed forward chunk

Source code in mindnlp/transformers/models/convbert/convbert.py
911
912
913
914
915
def feed_forward_chunk(self, attention_output):
    """feed forward chunk"""
    intermediate_output = self.intermediate(attention_output)
    layer_output = self.output(intermediate_output, attention_output)
    return layer_output

mindnlp.transformers.models.convbert.convbert.ConvBertLayer.forward(hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=False)

Constructs a ConvBertLayer.

This method applies the ConvBertLayer transformation to the input hidden states and returns the transformed output. It also supports cross-attention if encoder_hidden_states are provided.

PARAMETER DESCRIPTION
self

An instance of the ConvBertLayer class.

TYPE: ConvBertLayer

hidden_states

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

TYPE: Tensor

attention_mask

The attention mask of shape (batch_size, seq_len) or (batch_size, seq_len, seq_len). Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The head mask of shape (num_heads,) or (num_layers, num_heads). Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

encoder_hidden_states

The hidden states of the encoder if cross-attention is enabled. Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

encoder_attention_mask

The attention mask of the encoder if cross-attention is enabled. Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output attentions. Defaults to False.

TYPE: Optional[bool] DEFAULT: False

RETURNS DESCRIPTION
Tuple[Tensor, Optional[Tensor]]

Tuple[ms.Tensor, Optional[ms.Tensor]]: A tuple containing the transformed output tensor and optional attention tensors.

RAISES DESCRIPTION
AttributeError

If encoder_hidden_states are passed, self has to be instantiated with cross-attention layers by setting config.add_cross_attention=True.

Source code in mindnlp/transformers/models/convbert/convbert.py
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
def forward(
    self,
    hidden_states: ms.Tensor,
    attention_mask: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    encoder_hidden_states: Optional[ms.Tensor] = None,
    encoder_attention_mask: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = False,
) -> Tuple[ms.Tensor, Optional[ms.Tensor]]:
    """
    Constructs a ConvBertLayer.

    This method applies the ConvBertLayer transformation to the input hidden states and returns the
    transformed output. It also supports cross-attention if `encoder_hidden_states` are provided.

    Args:
        self (ConvBertLayer): An instance of the ConvBertLayer class.
        hidden_states (ms.Tensor): The input hidden states of shape (batch_size, seq_len, hidden_size).
        attention_mask (Optional[ms.Tensor]):
            The attention mask of shape (batch_size, seq_len) or (batch_size, seq_len, seq_len). Defaults to None.
        head_mask (Optional[ms.Tensor]):
            The head mask of shape (num_heads,) or (num_layers, num_heads). Defaults to None.
        encoder_hidden_states (Optional[ms.Tensor]):
            The hidden states of the encoder if cross-attention is enabled. Defaults to None.
        encoder_attention_mask (Optional[ms.Tensor]):
            The attention mask of the encoder if cross-attention is enabled. Defaults to None.
        output_attentions (Optional[bool]): Whether to output attentions. Defaults to False.

    Returns:
        Tuple[ms.Tensor, Optional[ms.Tensor]]: A tuple containing the transformed output tensor and
            optional attention tensors.

    Raises:
        AttributeError:
            If `encoder_hidden_states` are passed, `self` has to be instantiated with cross-attention layers
            by setting `config.add_cross_attention=True`.
    """
    self_attention_outputs = self.attention(
        hidden_states,
        attention_mask,
        head_mask,
        output_attentions=output_attentions,
    )
    attention_output = self_attention_outputs[0]
    # add self attentions if we output attention weights
    outputs = self_attention_outputs[1:]

    if self.is_decoder and encoder_hidden_states is not None:
        if not hasattr(self, "crossattention"):
            raise AttributeError(
                f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
                " by setting `config.add_cross_attention=True`"
            )
        cross_attention_outputs = self.crossattention(
            attention_output,
            encoder_attention_mask,
            head_mask,
            encoder_hidden_states,
            output_attentions,
        )
        attention_output = cross_attention_outputs[0]
        # add cross attentions if we output attention weights
        outputs = outputs + cross_attention_outputs[1:]

    layer_output = apply_chunking_to_forward(
        self.feed_forward_chunk,
        self.chunk_size_feed_forward,
        self.seq_len_dim,
        attention_output,
    )
    outputs = (layer_output,) + outputs
    return outputs

mindnlp.transformers.models.convbert.convbert.ConvBertModel

Bases: ConvBertPreTrainedModel

ConvBertModel

Source code in mindnlp/transformers/models/convbert/convbert.py
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
class ConvBertModel(ConvBertPreTrainedModel):
    """
    ConvBertModel
    """
    def __init__(self, config):
        """
        Initializes the ConvBertModel class.

        Args:
            self (object): The instance of the ConvBertModel class.
            config (object): An object containing configuration parameters for the model.
                This object should include settings such as embedding size, hidden size, etc.
                It is used to configure the model's parameters and behavior.

        Returns:
            None.

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

        if config.embedding_size != config.hidden_size:
            self.embeddings_project = nn.Linear(
                config.embedding_size, config.hidden_size
            )

        self.encoder = ConvBertEncoder(config)
        self.config = config
        # Initialize weights and apply final processing
        self.post_init()

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

        Args:
            self (ConvBertModel): The object instance of the ConvBertModel class.

        Returns:
            word_embeddings: The method returns the word embeddings from the input embeddings.

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

    def set_input_embeddings(self, new_embeddings):
        """
        Set the input embeddings for the ConvBertModel.

        Args:
            self (ConvBertModel): The instance of the ConvBertModel class.
            new_embeddings (Tensor): The new embeddings to be set for input.

        Returns:
            None.

        Raises:
            None.
        """
        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
        """
        for layer, heads in heads_to_prune.items():
            self.encoder.layer[layer].attention.prune_heads(heads)

    def forward(
        self,
        input_ids: Optional[ms.Tensor] = None,
        attention_mask: Optional[ms.Tensor] = None,
        token_type_ids: Optional[ms.Tensor] = None,
        position_ids: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        inputs_embeds: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
        '''
        Construct method in ConvBertModel class.

        Args:
            self (ConvBertModel): The instance of the ConvBertModel class.
            input_ids (Optional[ms.Tensor]): Input tensor containing the indices of input sequence tokens in the vocabulary.
            attention_mask (Optional[ms.Tensor]): Mask tensor showing which elements of the input sequence should be attended to.
            token_type_ids (Optional[ms.Tensor]): Tensor containing the type embeddings of the input tokens.
            position_ids (Optional[ms.Tensor]): Tensor containing the position embeddings of the input tokens.
            head_mask (Optional[ms.Tensor]): Tensor to mask heads of the attention mechanism.
            inputs_embeds (Optional[ms.Tensor]): Input embeddings for the sequence.
            output_attentions (Optional[bool]): Whether to return attentions tensors.
            output_hidden_states (Optional[bool]): Whether to return hidden states.
            return_dict (Optional[bool]): Whether to return a dictionary of outputs in addition to the traditional tuple output.

        Returns:
            Union[Tuple, BaseModelOutputWithCrossAttentions]:
                A tuple or BaseModelOutputWithCrossAttentions object, containing the hidden states, attentions,
                and/or other model outputs.

        Raises:
            ValueError: If both input_ids and inputs_embeds are specified simultaneously.
            ValueError: 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")

        batch_size, seq_length = input_shape

        if attention_mask is None:
            attention_mask = ops.ones(input_shape)
        if token_type_ids is None:
            if hasattr(self.embeddings, "token_type_ids"):
                buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
                buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
                    batch_size, seq_length
                )
                token_type_ids = buffered_token_type_ids_expanded
            else:
                token_type_ids = ops.zeros(input_shape, dtype=ms.int64)

        extended_attention_mask = self.get_extended_attention_mask(
            attention_mask, input_shape
        )
        head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)

        hidden_states = self.embeddings(
            input_ids=input_ids,
            position_ids=position_ids,
            token_type_ids=token_type_ids,
            inputs_embeds=inputs_embeds,
        )

        if hasattr(self, "embeddings_project"):
            hidden_states = self.embeddings_project(hidden_states)

        hidden_states = self.encoder(
            hidden_states,
            attention_mask=extended_attention_mask,
            head_mask=head_mask,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        return hidden_states

mindnlp.transformers.models.convbert.convbert.ConvBertModel.__init__(config)

Initializes the ConvBertModel class.

PARAMETER DESCRIPTION
self

The instance of the ConvBertModel class.

TYPE: object

config

An object containing configuration parameters for the model. This object should include settings such as embedding size, hidden size, etc. It is used to configure the model's parameters and behavior.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def __init__(self, config):
    """
    Initializes the ConvBertModel class.

    Args:
        self (object): The instance of the ConvBertModel class.
        config (object): An object containing configuration parameters for the model.
            This object should include settings such as embedding size, hidden size, etc.
            It is used to configure the model's parameters and behavior.

    Returns:
        None.

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

    if config.embedding_size != config.hidden_size:
        self.embeddings_project = nn.Linear(
            config.embedding_size, config.hidden_size
        )

    self.encoder = ConvBertEncoder(config)
    self.config = config
    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.convbert.convbert.ConvBertModel.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Construct method in ConvBertModel class.

PARAMETER DESCRIPTION
self

The instance of the ConvBertModel class.

TYPE: ConvBertModel

input_ids

Input tensor containing the indices of input sequence tokens in the vocabulary.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

Mask tensor showing which elements of the input sequence should be attended to.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

Tensor containing the type embeddings of the input tokens.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

Tensor containing the position embeddings of the input tokens.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

Tensor to mask heads of the attention mechanism.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

Input embeddings for the sequence.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to return attentions tensors.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to return hidden states.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary of outputs in addition to the traditional tuple output.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutputWithCrossAttentions]

Union[Tuple, BaseModelOutputWithCrossAttentions]: A tuple or BaseModelOutputWithCrossAttentions object, containing the hidden states, attentions, and/or other model outputs.

RAISES DESCRIPTION
ValueError

If both input_ids and inputs_embeds are specified simultaneously.

ValueError

If neither input_ids nor inputs_embeds are specified.

Source code in mindnlp/transformers/models/convbert/convbert.py
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
def forward(
    self,
    input_ids: Optional[ms.Tensor] = None,
    attention_mask: Optional[ms.Tensor] = None,
    token_type_ids: Optional[ms.Tensor] = None,
    position_ids: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    inputs_embeds: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
    '''
    Construct method in ConvBertModel class.

    Args:
        self (ConvBertModel): The instance of the ConvBertModel class.
        input_ids (Optional[ms.Tensor]): Input tensor containing the indices of input sequence tokens in the vocabulary.
        attention_mask (Optional[ms.Tensor]): Mask tensor showing which elements of the input sequence should be attended to.
        token_type_ids (Optional[ms.Tensor]): Tensor containing the type embeddings of the input tokens.
        position_ids (Optional[ms.Tensor]): Tensor containing the position embeddings of the input tokens.
        head_mask (Optional[ms.Tensor]): Tensor to mask heads of the attention mechanism.
        inputs_embeds (Optional[ms.Tensor]): Input embeddings for the sequence.
        output_attentions (Optional[bool]): Whether to return attentions tensors.
        output_hidden_states (Optional[bool]): Whether to return hidden states.
        return_dict (Optional[bool]): Whether to return a dictionary of outputs in addition to the traditional tuple output.

    Returns:
        Union[Tuple, BaseModelOutputWithCrossAttentions]:
            A tuple or BaseModelOutputWithCrossAttentions object, containing the hidden states, attentions,
            and/or other model outputs.

    Raises:
        ValueError: If both input_ids and inputs_embeds are specified simultaneously.
        ValueError: 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")

    batch_size, seq_length = input_shape

    if attention_mask is None:
        attention_mask = ops.ones(input_shape)
    if token_type_ids is None:
        if hasattr(self.embeddings, "token_type_ids"):
            buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
            buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
                batch_size, seq_length
            )
            token_type_ids = buffered_token_type_ids_expanded
        else:
            token_type_ids = ops.zeros(input_shape, dtype=ms.int64)

    extended_attention_mask = self.get_extended_attention_mask(
        attention_mask, input_shape
    )
    head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)

    hidden_states = self.embeddings(
        input_ids=input_ids,
        position_ids=position_ids,
        token_type_ids=token_type_ids,
        inputs_embeds=inputs_embeds,
    )

    if hasattr(self, "embeddings_project"):
        hidden_states = self.embeddings_project(hidden_states)

    hidden_states = self.encoder(
        hidden_states,
        attention_mask=extended_attention_mask,
        head_mask=head_mask,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    return hidden_states

mindnlp.transformers.models.convbert.convbert.ConvBertModel.get_input_embeddings()

Retrieve the input embeddings from the ConvBertModel.

PARAMETER DESCRIPTION
self

The object instance of the ConvBertModel class.

TYPE: ConvBertModel

RETURNS DESCRIPTION
word_embeddings

The method returns the word embeddings from the input embeddings.

Source code in mindnlp/transformers/models/convbert/convbert.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
def get_input_embeddings(self):
    """
    Retrieve the input embeddings from the ConvBertModel.

    Args:
        self (ConvBertModel): The object instance of the ConvBertModel class.

    Returns:
        word_embeddings: The method returns the word embeddings from the input embeddings.

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

mindnlp.transformers.models.convbert.convbert.ConvBertModel.set_input_embeddings(new_embeddings)

Set the input embeddings for the ConvBertModel.

PARAMETER DESCRIPTION
self

The instance of the ConvBertModel class.

TYPE: ConvBertModel

new_embeddings

The new embeddings to be set for input.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
def set_input_embeddings(self, new_embeddings):
    """
    Set the input embeddings for the ConvBertModel.

    Args:
        self (ConvBertModel): The instance of the ConvBertModel class.
        new_embeddings (Tensor): The new embeddings to be set for input.

    Returns:
        None.

    Raises:
        None.
    """
    self.embeddings.word_embeddings = new_embeddings

mindnlp.transformers.models.convbert.convbert.ConvBertOutput

Bases: Module

ConvBertOutput

Source code in mindnlp/transformers/models/convbert/convbert.py
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
class ConvBertOutput(nn.Module):
    """
    ConvBertOutput
    """
    def __init__(self, config):
        """
        Initializes a new instance of the ConvBertOutput class.

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

                - num_groups (int): The number of groups. If equal to 1, a Dense layer is used.
                Otherwise, a GroupedLinearLayer is used. (Restrictions: Must be a positive integer)
                - intermediate_size (int): The size of the intermediate layer.
                - hidden_size (int): The size of the hidden layer.
                - layer_norm_eps (float): The epsilon value for layer normalization.
                - hidden_dropout_prob (float): The dropout probability for the hidden layer.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        if config.num_groups == 1:
            self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        else:
            self.dense = GroupedLinearLayer(
                input_size=config.intermediate_size,
                output_size=config.hidden_size,
                num_groups=config.num_groups,
            )
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def forward(self, hidden_states: ms.Tensor, input_tensor: ms.Tensor) -> ms.Tensor:
        """
        Constructs the output tensor for the ConvBertOutput class.

        Args:
            self (ConvBertOutput): The instance of the ConvBertOutput class.
            hidden_states (ms.Tensor): The input tensor representing the hidden states.
            input_tensor (ms.Tensor): The input tensor.

        Returns:
            ms.Tensor: The output tensor representing the forwarded hidden states.

        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.convbert.convbert.ConvBertOutput.__init__(config)

Initializes a new instance of the ConvBertOutput class.

PARAMETER DESCRIPTION
self

The object instance.

config

An object of type 'config' containing the configuration parameters for the ConvBertOutput class.

  • num_groups (int): The number of groups. If equal to 1, a Dense layer is used. Otherwise, a GroupedLinearLayer is used. (Restrictions: Must be a positive integer)
  • intermediate_size (int): The size of the intermediate layer.
  • hidden_size (int): The size of the hidden layer.
  • layer_norm_eps (float): The epsilon value for layer normalization.
  • hidden_dropout_prob (float): The dropout probability for the hidden layer.

RETURNS DESCRIPTION

None.

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

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

            - num_groups (int): The number of groups. If equal to 1, a Dense layer is used.
            Otherwise, a GroupedLinearLayer is used. (Restrictions: Must be a positive integer)
            - intermediate_size (int): The size of the intermediate layer.
            - hidden_size (int): The size of the hidden layer.
            - layer_norm_eps (float): The epsilon value for layer normalization.
            - hidden_dropout_prob (float): The dropout probability for the hidden layer.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    if config.num_groups == 1:
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
    else:
        self.dense = GroupedLinearLayer(
            input_size=config.intermediate_size,
            output_size=config.hidden_size,
            num_groups=config.num_groups,
        )
    self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.convbert.convbert.ConvBertOutput.forward(hidden_states, input_tensor)

Constructs the output tensor for the ConvBertOutput class.

PARAMETER DESCRIPTION
self

The instance of the ConvBertOutput class.

TYPE: ConvBertOutput

hidden_states

The input tensor representing the hidden states.

TYPE: Tensor

input_tensor

The input tensor.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: The output tensor representing the forwarded hidden states.

Source code in mindnlp/transformers/models/convbert/convbert.py
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
def forward(self, hidden_states: ms.Tensor, input_tensor: ms.Tensor) -> ms.Tensor:
    """
    Constructs the output tensor for the ConvBertOutput class.

    Args:
        self (ConvBertOutput): The instance of the ConvBertOutput class.
        hidden_states (ms.Tensor): The input tensor representing the hidden states.
        input_tensor (ms.Tensor): The input tensor.

    Returns:
        ms.Tensor: The output tensor representing the forwarded hidden states.

    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.convbert.convbert.ConvBertPreTrainedModel

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/convbert/convbert.py
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
class ConvBertPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = ConvBertConfig
    base_model_prefix = "convbert"
    supports_gradient_checkpointing = True

    def _init_weights(self, cell):
        """Initialize the weights"""
        if isinstance(cell, nn.Linear):
            cell.weight = ms.Parameter(
                initializer(
                    Normal(sigma=self.config.initializer_range, mean=0.0),
                    cell.weight.shape,
                    cell.weight.dtype,
                )
            )
            if cell.bias is not None:
                cell.bias = ms.Parameter(
                    initializer("zeros", cell.bias.shape, cell.bias.dtype)
                )
        elif isinstance(cell, nn.Embedding):
            cell.weight = ms.Parameter(
                initializer(
                    Normal(mean=0.0, sigma=self.config.initializer_range),
                    cell.weight.shape,
                    cell.weight.dtype,
                )
            )
            # if cell.padding_idx is not None:
            #     cell.weight.data[cell.padding_idx].set_data(
            #         initializer('zeros',
            #                     cell.weight.data[cell.padding_idx].shape,
            #                     cell.weight.data[cell.padding_idx].dtype)
            #     )
        elif isinstance(cell, nn.LayerNorm):
            cell.bias = ms.Parameter(
                initializer("zeros", cell.bias.shape, cell.bias.dtype)
            )
            cell.weight = ms.Parameter(
                initializer("ones", cell.weight.shape, cell.weight.dtype)
            )

mindnlp.transformers.models.convbert.convbert.ConvBertPredictionHeadTransform

Bases: Module

ConvBertPredictionHeadTransform

Source code in mindnlp/transformers/models/convbert/convbert.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
class ConvBertPredictionHeadTransform(nn.Module):
    """
    ConvBertPredictionHeadTransform
    """
    def __init__(self, config):
        """
        Initializes a ConvBertPredictionHeadTransform object.

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

                - Type: Any
                - Purpose: Specifies the configuration settings for the transformation.
                - Restrictions: Must contain the following attributes:

                    - hidden_size: Integer representing the size of the hidden layer.
                    - hidden_act: Activation function for the hidden layer. Can be a string or a callable.
                    - layer_norm_eps: Epsilon value for LayerNorm.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided or is of an unexpected type.
            AttributeError: If the config object does not contain the required attributes.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_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(config.hidden_size, eps=config.layer_norm_eps)

    def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
        """
        This method forwards the prediction head transformation for ConvBert.

        Args:
            self (ConvBertPredictionHeadTransform): The instance of ConvBertPredictionHeadTransform.
            hidden_states (ms.Tensor): The input tensor representing hidden states.

        Returns:
            ms.Tensor: The transformed hidden states tensor.

        Raises:
            None
        """
        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.convbert.convbert.ConvBertPredictionHeadTransform.__init__(config)

Initializes a ConvBertPredictionHeadTransform object.

PARAMETER DESCRIPTION
self

The instance of the ConvBertPredictionHeadTransform class.

TYPE: ConvBertPredictionHeadTransform

config

An object containing configuration parameters for the transformation.

  • Type: Any
  • Purpose: Specifies the configuration settings for the transformation.
  • Restrictions: Must contain the following attributes:

    • hidden_size: Integer representing the size of the hidden layer.
    • hidden_act: Activation function for the hidden layer. Can be a string or a callable.
    • layer_norm_eps: Epsilon value for LayerNorm.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided or is of an unexpected type.

AttributeError

If the config object does not contain the required attributes.

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

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

            - Type: Any
            - Purpose: Specifies the configuration settings for the transformation.
            - Restrictions: Must contain the following attributes:

                - hidden_size: Integer representing the size of the hidden layer.
                - hidden_act: Activation function for the hidden layer. Can be a string or a callable.
                - layer_norm_eps: Epsilon value for LayerNorm.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided or is of an unexpected type.
        AttributeError: If the config object does not contain the required attributes.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_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(config.hidden_size, eps=config.layer_norm_eps)

mindnlp.transformers.models.convbert.convbert.ConvBertPredictionHeadTransform.forward(hidden_states)

This method forwards the prediction head transformation for ConvBert.

PARAMETER DESCRIPTION
self

The instance of ConvBertPredictionHeadTransform.

TYPE: ConvBertPredictionHeadTransform

hidden_states

The input tensor representing hidden states.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: The transformed hidden states tensor.

Source code in mindnlp/transformers/models/convbert/convbert.py
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
    """
    This method forwards the prediction head transformation for ConvBert.

    Args:
        self (ConvBertPredictionHeadTransform): The instance of ConvBertPredictionHeadTransform.
        hidden_states (ms.Tensor): The input tensor representing hidden states.

    Returns:
        ms.Tensor: The transformed hidden states tensor.

    Raises:
        None
    """
    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.convbert.convbert.ConvBertSelfAttention

Bases: Module

ConvBertSelfAttention

Source code in mindnlp/transformers/models/convbert/convbert.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
class ConvBertSelfAttention(nn.Module):
    """
    ConvBertSelfAttention
    """
    def __init__(self, config):
        '''
        Initializes a new instance of the ConvBertSelfAttention class.

        Args:
            self (object): The instance of the class.
            config (object): The configuration object containing the settings for the self-attention mechanism.

        Returns:
            None

        Raises:
            ValueError:
                If the hidden size is not divisible by the number of attention heads or if the hidden size
                is not a multiple of the number of attention heads.

        '''
        super().__init__()
        if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
            config, "embedding_size"
        ):
            raise ValueError(
                f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
                f"heads ({config.num_attention_heads})"
            )

        new_num_attention_heads = config.num_attention_heads // config.head_ratio
        if new_num_attention_heads < 1:
            self.head_ratio = config.num_attention_heads
            self.num_attention_heads = 1
        else:
            self.num_attention_heads = new_num_attention_heads
            self.head_ratio = config.head_ratio

        self.conv_kernel_size = config.conv_kernel_size
        if config.hidden_size % self.num_attention_heads != 0:
            raise ValueError("hidden_size should be divisible by num_attention_heads")

        self.attention_head_size = (config.hidden_size // self.num_attention_heads) // 2
        self.all_head_size = self.num_attention_heads * self.attention_head_size

        self.query = nn.Linear(config.hidden_size, self.all_head_size)
        self.key = nn.Linear(config.hidden_size, self.all_head_size)
        self.value = nn.Linear(config.hidden_size, self.all_head_size)

        self.key_conv_attn_layer = SeparableConv1D(
            config, config.hidden_size, self.all_head_size, self.conv_kernel_size
        )
        self.conv_kernel_layer = nn.Linear(
            self.all_head_size, self.num_attention_heads * self.conv_kernel_size
        )
        self.conv_out_layer = nn.Linear(config.hidden_size, self.all_head_size)
        self.unfold = nn.Unfold(
            ksizes=[1, self.conv_kernel_size, 1, 1],
            rates=[1, 1, 1, 1],
            strides=[1, 1, 1, 1],
            padding="same",
        )
        self.dropout = nn.Dropout(p=config.attention_probs_dropout_prob)

    def swapaxes_for_scores(self, x):
        """swapaxes for scores"""
        new_x_shape = x.shape[:-1] + (
            self.num_attention_heads,
            self.attention_head_size,
        )
        x = x.view(*new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward(
        self,
        hidden_states: ms.Tensor,
        attention_mask: Optional[ms.Tensor] = None,
        head_mask: Optional[ms.Tensor] = None,
        encoder_hidden_states: Optional[ms.Tensor] = None,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[ms.Tensor, Optional[ms.Tensor]]:
        '''
        The `forward` method in the `ConvBertSelfAttention` class performs the forwardion of self-attention
        mechanism using convolutional operations.

        Args:
            self: The instance of the ConvBertSelfAttention class.
            hidden_states (ms.Tensor):
                The input tensor of shape [batch_size, sequence_length, hidden_size] representing the hidden states
                of the input sequence.
            attention_mask (Optional[ms.Tensor]):
                An optional tensor of shape [batch_size, 1, sequence_length, sequence_length] containing attention mask
                for the input sequence. Default is None.
            head_mask (Optional[ms.Tensor]):
                An optional tensor of shape [num_attention_heads] representing the mask for attention heads.
                Default is None.
            encoder_hidden_states (Optional[ms.Tensor]):
                An optional tensor of shape [batch_size, sequence_length, hidden_size] representing the hidden states
                of the encoder. Default is None.
            output_attentions (Optional[bool]): Whether to output attention probabilities. Default is False.

        Returns:
            Tuple[ms.Tensor, Optional[ms.Tensor]]:
                A tuple containing the context layer tensor of shape [batch_size, sequence_length, hidden_size]
                and the optional attention probabilities tensor of shape
            [batch_size, num_attention_heads, sequence_length, sequence_length].

        Raises:
            None.
        '''
        mixed_query_layer = self.query(hidden_states)
        batch_size = hidden_states.shape[0]
        # If this is instantiated as a cross-attention cell, the keys
        # and values come from an encoder; the attention mask needs to be
        # such that the encoder's padding tokens are not attended to.
        if encoder_hidden_states is not None:
            mixed_key_layer = self.key(encoder_hidden_states)
            mixed_value_layer = self.value(encoder_hidden_states)
        else:
            mixed_key_layer = self.key(hidden_states)
            mixed_value_layer = self.value(hidden_states)

        mixed_key_conv_attn_layer = self.key_conv_attn_layer(
            hidden_states.swapaxes(1, 2)
        )
        mixed_key_conv_attn_layer = mixed_key_conv_attn_layer.swapaxes(1, 2)

        query_layer = self.swapaxes_for_scores(mixed_query_layer)
        key_layer = self.swapaxes_for_scores(mixed_key_layer)
        value_layer = self.swapaxes_for_scores(mixed_value_layer)
        conv_attn_layer = ops.multiply(mixed_key_conv_attn_layer, mixed_query_layer)

        conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
        conv_kernel_layer = ops.reshape(
            conv_kernel_layer, [-1, self.conv_kernel_size, 1]
        )
        conv_kernel_layer = ops.softmax(conv_kernel_layer, axis=1)

        conv_out_layer = self.conv_out_layer(hidden_states)
        conv_out_layer = ops.reshape(
            conv_out_layer, [batch_size, -1, self.all_head_size]
        )
        conv_out_layer = conv_out_layer.swapaxes(1, 2).unsqueeze(-1)
        conv_out_layer = ops.unfold(
            conv_out_layer,
            kernel_size=[self.conv_kernel_size, 1],
            dilation=1,
            padding=[(self.conv_kernel_size - 1) // 2, 0],
            stride=1,
        )
        conv_out_layer = conv_out_layer.swapaxes(1, 2).reshape(
            batch_size, -1, self.all_head_size, self.conv_kernel_size
        )
        conv_out_layer = ops.reshape(
            conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size]
        )
        conv_out_layer = ops.matmul(conv_out_layer, conv_kernel_layer)
        conv_out_layer = ops.reshape(conv_out_layer, [-1, self.all_head_size])

        # Take the dot product between "query" and "key" to get the raw attention scores.
        attention_scores = ops.matmul(query_layer, key_layer.swapaxes(-1, -2))
        attention_scores = attention_scores / math.sqrt(self.attention_head_size)
        if attention_mask is not None:
            # Apply the attention mask is (precomputed for all layers in ConvBertModel forward() function)
            attention_scores = attention_scores + attention_mask

        # Normalize the attention scores to probabilities.
        attention_probs = ops.softmax(attention_scores, axis=-1)

        # This is actually dropping out entire tokens to attend to, which might
        # seem a bit unusual, but is taken from the original Transformer paper.
        attention_probs = self.dropout(attention_probs)

        # Mask heads if we want to
        if head_mask is not None:
            attention_probs = attention_probs * head_mask

        context_layer = ops.matmul(attention_probs, value_layer)
        context_layer = context_layer.permute(0, 2, 1, 3)

        conv_out = ops.reshape(
            conv_out_layer,
            [batch_size, -1, self.num_attention_heads, self.attention_head_size],
        )
        context_layer = ops.cat([context_layer, conv_out], 2)

        # conv and context
        new_context_layer_shape = context_layer.shape[:-2] + (
            self.num_attention_heads * self.attention_head_size * 2,
        )
        context_layer = context_layer.view(*new_context_layer_shape)

        outputs = (
            (context_layer, attention_probs) if output_attentions else (context_layer,)
        )
        return outputs

mindnlp.transformers.models.convbert.convbert.ConvBertSelfAttention.__init__(config)

Initializes a new instance of the ConvBertSelfAttention class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

config

The configuration object containing the settings for the self-attention mechanism.

TYPE: object

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the hidden size is not divisible by the number of attention heads or if the hidden size is not a multiple of the number of attention heads.

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

    Args:
        self (object): The instance of the class.
        config (object): The configuration object containing the settings for the self-attention mechanism.

    Returns:
        None

    Raises:
        ValueError:
            If the hidden size is not divisible by the number of attention heads or if the hidden size
            is not a multiple of the number of attention heads.

    '''
    super().__init__()
    if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
        config, "embedding_size"
    ):
        raise ValueError(
            f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
            f"heads ({config.num_attention_heads})"
        )

    new_num_attention_heads = config.num_attention_heads // config.head_ratio
    if new_num_attention_heads < 1:
        self.head_ratio = config.num_attention_heads
        self.num_attention_heads = 1
    else:
        self.num_attention_heads = new_num_attention_heads
        self.head_ratio = config.head_ratio

    self.conv_kernel_size = config.conv_kernel_size
    if config.hidden_size % self.num_attention_heads != 0:
        raise ValueError("hidden_size should be divisible by num_attention_heads")

    self.attention_head_size = (config.hidden_size // self.num_attention_heads) // 2
    self.all_head_size = self.num_attention_heads * self.attention_head_size

    self.query = nn.Linear(config.hidden_size, self.all_head_size)
    self.key = nn.Linear(config.hidden_size, self.all_head_size)
    self.value = nn.Linear(config.hidden_size, self.all_head_size)

    self.key_conv_attn_layer = SeparableConv1D(
        config, config.hidden_size, self.all_head_size, self.conv_kernel_size
    )
    self.conv_kernel_layer = nn.Linear(
        self.all_head_size, self.num_attention_heads * self.conv_kernel_size
    )
    self.conv_out_layer = nn.Linear(config.hidden_size, self.all_head_size)
    self.unfold = nn.Unfold(
        ksizes=[1, self.conv_kernel_size, 1, 1],
        rates=[1, 1, 1, 1],
        strides=[1, 1, 1, 1],
        padding="same",
    )
    self.dropout = nn.Dropout(p=config.attention_probs_dropout_prob)

mindnlp.transformers.models.convbert.convbert.ConvBertSelfAttention.forward(hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, output_attentions=False)

The forward method in the ConvBertSelfAttention class performs the forwardion of self-attention mechanism using convolutional operations.

PARAMETER DESCRIPTION
self

The instance of the ConvBertSelfAttention class.

hidden_states

The input tensor of shape [batch_size, sequence_length, hidden_size] representing the hidden states of the input sequence.

TYPE: Tensor

attention_mask

An optional tensor of shape [batch_size, 1, sequence_length, sequence_length] containing attention mask for the input sequence. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

An optional tensor of shape [num_attention_heads] representing the mask for attention heads. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

encoder_hidden_states

An optional tensor of shape [batch_size, sequence_length, hidden_size] representing the hidden states of the encoder. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output attention probabilities. Default is False.

TYPE: Optional[bool] DEFAULT: False

RETURNS DESCRIPTION
Tensor

Tuple[ms.Tensor, Optional[ms.Tensor]]: A tuple containing the context layer tensor of shape [batch_size, sequence_length, hidden_size] and the optional attention probabilities tensor of shape

Optional[Tensor]

[batch_size, num_attention_heads, sequence_length, sequence_length].

Source code in mindnlp/transformers/models/convbert/convbert.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
def forward(
    self,
    hidden_states: ms.Tensor,
    attention_mask: Optional[ms.Tensor] = None,
    head_mask: Optional[ms.Tensor] = None,
    encoder_hidden_states: Optional[ms.Tensor] = None,
    output_attentions: Optional[bool] = False,
) -> Tuple[ms.Tensor, Optional[ms.Tensor]]:
    '''
    The `forward` method in the `ConvBertSelfAttention` class performs the forwardion of self-attention
    mechanism using convolutional operations.

    Args:
        self: The instance of the ConvBertSelfAttention class.
        hidden_states (ms.Tensor):
            The input tensor of shape [batch_size, sequence_length, hidden_size] representing the hidden states
            of the input sequence.
        attention_mask (Optional[ms.Tensor]):
            An optional tensor of shape [batch_size, 1, sequence_length, sequence_length] containing attention mask
            for the input sequence. Default is None.
        head_mask (Optional[ms.Tensor]):
            An optional tensor of shape [num_attention_heads] representing the mask for attention heads.
            Default is None.
        encoder_hidden_states (Optional[ms.Tensor]):
            An optional tensor of shape [batch_size, sequence_length, hidden_size] representing the hidden states
            of the encoder. Default is None.
        output_attentions (Optional[bool]): Whether to output attention probabilities. Default is False.

    Returns:
        Tuple[ms.Tensor, Optional[ms.Tensor]]:
            A tuple containing the context layer tensor of shape [batch_size, sequence_length, hidden_size]
            and the optional attention probabilities tensor of shape
        [batch_size, num_attention_heads, sequence_length, sequence_length].

    Raises:
        None.
    '''
    mixed_query_layer = self.query(hidden_states)
    batch_size = hidden_states.shape[0]
    # If this is instantiated as a cross-attention cell, the keys
    # and values come from an encoder; the attention mask needs to be
    # such that the encoder's padding tokens are not attended to.
    if encoder_hidden_states is not None:
        mixed_key_layer = self.key(encoder_hidden_states)
        mixed_value_layer = self.value(encoder_hidden_states)
    else:
        mixed_key_layer = self.key(hidden_states)
        mixed_value_layer = self.value(hidden_states)

    mixed_key_conv_attn_layer = self.key_conv_attn_layer(
        hidden_states.swapaxes(1, 2)
    )
    mixed_key_conv_attn_layer = mixed_key_conv_attn_layer.swapaxes(1, 2)

    query_layer = self.swapaxes_for_scores(mixed_query_layer)
    key_layer = self.swapaxes_for_scores(mixed_key_layer)
    value_layer = self.swapaxes_for_scores(mixed_value_layer)
    conv_attn_layer = ops.multiply(mixed_key_conv_attn_layer, mixed_query_layer)

    conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
    conv_kernel_layer = ops.reshape(
        conv_kernel_layer, [-1, self.conv_kernel_size, 1]
    )
    conv_kernel_layer = ops.softmax(conv_kernel_layer, axis=1)

    conv_out_layer = self.conv_out_layer(hidden_states)
    conv_out_layer = ops.reshape(
        conv_out_layer, [batch_size, -1, self.all_head_size]
    )
    conv_out_layer = conv_out_layer.swapaxes(1, 2).unsqueeze(-1)
    conv_out_layer = ops.unfold(
        conv_out_layer,
        kernel_size=[self.conv_kernel_size, 1],
        dilation=1,
        padding=[(self.conv_kernel_size - 1) // 2, 0],
        stride=1,
    )
    conv_out_layer = conv_out_layer.swapaxes(1, 2).reshape(
        batch_size, -1, self.all_head_size, self.conv_kernel_size
    )
    conv_out_layer = ops.reshape(
        conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size]
    )
    conv_out_layer = ops.matmul(conv_out_layer, conv_kernel_layer)
    conv_out_layer = ops.reshape(conv_out_layer, [-1, self.all_head_size])

    # Take the dot product between "query" and "key" to get the raw attention scores.
    attention_scores = ops.matmul(query_layer, key_layer.swapaxes(-1, -2))
    attention_scores = attention_scores / math.sqrt(self.attention_head_size)
    if attention_mask is not None:
        # Apply the attention mask is (precomputed for all layers in ConvBertModel forward() function)
        attention_scores = attention_scores + attention_mask

    # Normalize the attention scores to probabilities.
    attention_probs = ops.softmax(attention_scores, axis=-1)

    # This is actually dropping out entire tokens to attend to, which might
    # seem a bit unusual, but is taken from the original Transformer paper.
    attention_probs = self.dropout(attention_probs)

    # Mask heads if we want to
    if head_mask is not None:
        attention_probs = attention_probs * head_mask

    context_layer = ops.matmul(attention_probs, value_layer)
    context_layer = context_layer.permute(0, 2, 1, 3)

    conv_out = ops.reshape(
        conv_out_layer,
        [batch_size, -1, self.num_attention_heads, self.attention_head_size],
    )
    context_layer = ops.cat([context_layer, conv_out], 2)

    # conv and context
    new_context_layer_shape = context_layer.shape[:-2] + (
        self.num_attention_heads * self.attention_head_size * 2,
    )
    context_layer = context_layer.view(*new_context_layer_shape)

    outputs = (
        (context_layer, attention_probs) if output_attentions else (context_layer,)
    )
    return outputs

mindnlp.transformers.models.convbert.convbert.ConvBertSelfAttention.swapaxes_for_scores(x)

swapaxes for scores

Source code in mindnlp/transformers/models/convbert/convbert.py
342
343
344
345
346
347
348
349
def swapaxes_for_scores(self, x):
    """swapaxes for scores"""
    new_x_shape = x.shape[:-1] + (
        self.num_attention_heads,
        self.attention_head_size,
    )
    x = x.view(*new_x_shape)
    return x.permute(0, 2, 1, 3)

mindnlp.transformers.models.convbert.convbert.ConvBertSelfOutput

Bases: Module

ConvBertSelfOutput

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

        Args:
            self (ConvBertSelfOutput): The instance of the ConvBertSelfOutput class.
            config: The configuration object that holds various hyperparameters.

        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 = nn.Dropout(p=config.hidden_dropout_prob)

    def forward(self, hidden_states: ms.Tensor, input_tensor: ms.Tensor) -> ms.Tensor:
        """
        Constructs the output of the ConvBertSelfOutput layer.

        Args:
            self (ConvBertSelfOutput): An instance of the ConvBertSelfOutput class.
            hidden_states (ms.Tensor): The hidden states tensor of shape (batch_size, sequence_length, hidden_size).
                This tensor represents the output of the previous layer.
            input_tensor (ms.Tensor): The input tensor of shape (batch_size, sequence_length, hidden_size).
                This tensor represents the input to the layer.

        Returns:
            ms.Tensor: The output tensor of shape (batch_size, sequence_length, hidden_size).
                This tensor represents the forwarded output of the ConvBertSelfOutput layer.

        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.convbert.convbert.ConvBertSelfOutput.__init__(config)

Initializes an instance of the ConvBertSelfOutput class.

PARAMETER DESCRIPTION
self

The instance of the ConvBertSelfOutput class.

TYPE: ConvBertSelfOutput

config

The configuration object that holds various hyperparameters.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/convbert/convbert.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def __init__(self, config):
    """
    Initializes an instance of the ConvBertSelfOutput class.

    Args:
        self (ConvBertSelfOutput): The instance of the ConvBertSelfOutput class.
        config: The configuration object that holds various hyperparameters.

    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 = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.convbert.convbert.ConvBertSelfOutput.forward(hidden_states, input_tensor)

Constructs the output of the ConvBertSelfOutput layer.

PARAMETER DESCRIPTION
self

An instance of the ConvBertSelfOutput class.

TYPE: ConvBertSelfOutput

hidden_states

The hidden states tensor of shape (batch_size, sequence_length, hidden_size). This tensor represents the output of the previous layer.

TYPE: Tensor

input_tensor

The input tensor of shape (batch_size, sequence_length, hidden_size). This tensor represents the input to the layer.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: The output tensor of shape (batch_size, sequence_length, hidden_size). This tensor represents the forwarded output of the ConvBertSelfOutput layer.

Source code in mindnlp/transformers/models/convbert/convbert.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def forward(self, hidden_states: ms.Tensor, input_tensor: ms.Tensor) -> ms.Tensor:
    """
    Constructs the output of the ConvBertSelfOutput layer.

    Args:
        self (ConvBertSelfOutput): An instance of the ConvBertSelfOutput class.
        hidden_states (ms.Tensor): The hidden states tensor of shape (batch_size, sequence_length, hidden_size).
            This tensor represents the output of the previous layer.
        input_tensor (ms.Tensor): The input tensor of shape (batch_size, sequence_length, hidden_size).
            This tensor represents the input to the layer.

    Returns:
        ms.Tensor: The output tensor of shape (batch_size, sequence_length, hidden_size).
            This tensor represents the forwarded output of the ConvBertSelfOutput layer.

    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.convbert.convbert.GroupedLinearLayer

Bases: Module

GroupedLinearLayer

Source code in mindnlp/transformers/models/convbert/convbert.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
class GroupedLinearLayer(nn.Module):
    """
    GroupedLinearLayer
    """
    def __init__(self, input_size, output_size, num_groups):
        """
        Initializes a GroupedLinearLayer object.

        Args:
            self (GroupedLinearLayer): The instance of the GroupedLinearLayer class.
            input_size (int): The size of the input tensor.
            output_size (int): The size of the output tensor.
            num_groups (int): The number of groups to divide the input and output tensors into.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.input_size = input_size
        self.output_size = output_size
        self.num_groups = num_groups
        self.group_in_dim = self.input_size // self.num_groups
        self.group_out_dim = self.output_size // self.num_groups
        self.weight = nn.Parameter(
            ops.zeros((self.num_groups, self.group_in_dim, self.group_out_dim))
        )
        self.bias = nn.Parameter(ops.zeros(output_size))

    def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
        """Constructs a grouped linear layer.

        Args:
            self (GroupedLinearLayer): The instance of the GroupedLinearLayer class.
            hidden_states (ms.Tensor): The input tensor of shape [batch_size, input_size].

        Returns:
            ms.Tensor: The output tensor of shape [batch_size, output_size].

        Raises:
            TypeError: If `hidden_states` is not of type `ms.Tensor`.
            ValueError: If the shape of `hidden_states` is not compatible with the expected shape [batch_size, input_size].
            ValueError: If `self.weight` is not of shape [num_groups, group_in_dim, output_size].
            ValueError: If `self.bias` is not of shape [output_size].

        Note:
            The `hidden_states` tensor represents the input to the grouped linear layer. It is expected to have a shape
            of [batch_size, input_size].

            The grouped linear layer applies a linear transformation to the input tensor by grouping the input features
            into `num_groups` groups. The `group_in_dim` represents the number of features in each group. The output tensor
            has a shape of [batch_size, output_size].

            The linear transformation is performed by reshaping the input tensor to a shape of [batch_size * num_groups,
            group_in_dim], permuting the dimensions to [num_groups, batch_size, group_in_dim], and performing matrix
            multiplication with the weight tensor of shape [num_groups, group_in_dim, output_size]. The result tensor is
            then reshaped back to [batch_size, -1, output_size] and added with the bias tensor of shape [output_size].

            The grouped linear layer is typically used in neural network architectures to introduce non-linearity and
            increase model capacity by learning more complex relationships between input and output features.
        """
        batch_size = list(hidden_states.shape)[0]
        x = ops.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim])
        x = x.permute(1, 0, 2)
        x = ops.matmul(x, self.weight)
        x = x.permute(1, 0, 2)
        x = ops.reshape(x, [batch_size, -1, self.output_size])
        x = x + self.bias
        return x

mindnlp.transformers.models.convbert.convbert.GroupedLinearLayer.__init__(input_size, output_size, num_groups)

Initializes a GroupedLinearLayer object.

PARAMETER DESCRIPTION
self

The instance of the GroupedLinearLayer class.

TYPE: GroupedLinearLayer

input_size

The size of the input tensor.

TYPE: int

output_size

The size of the output tensor.

TYPE: int

num_groups

The number of groups to divide the input and output tensors into.

TYPE: int

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/convbert/convbert.py
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
def __init__(self, input_size, output_size, num_groups):
    """
    Initializes a GroupedLinearLayer object.

    Args:
        self (GroupedLinearLayer): The instance of the GroupedLinearLayer class.
        input_size (int): The size of the input tensor.
        output_size (int): The size of the output tensor.
        num_groups (int): The number of groups to divide the input and output tensors into.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.input_size = input_size
    self.output_size = output_size
    self.num_groups = num_groups
    self.group_in_dim = self.input_size // self.num_groups
    self.group_out_dim = self.output_size // self.num_groups
    self.weight = nn.Parameter(
        ops.zeros((self.num_groups, self.group_in_dim, self.group_out_dim))
    )
    self.bias = nn.Parameter(ops.zeros(output_size))

mindnlp.transformers.models.convbert.convbert.GroupedLinearLayer.forward(hidden_states)

Constructs a grouped linear layer.

PARAMETER DESCRIPTION
self

The instance of the GroupedLinearLayer class.

TYPE: GroupedLinearLayer

hidden_states

The input tensor of shape [batch_size, input_size].

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: The output tensor of shape [batch_size, output_size].

RAISES DESCRIPTION
TypeError

If hidden_states is not of type ms.Tensor.

ValueError

If the shape of hidden_states is not compatible with the expected shape [batch_size, input_size].

ValueError

If self.weight is not of shape [num_groups, group_in_dim, output_size].

ValueError

If self.bias is not of shape [output_size].

Note

The hidden_states tensor represents the input to the grouped linear layer. It is expected to have a shape of [batch_size, input_size].

The grouped linear layer applies a linear transformation to the input tensor by grouping the input features into num_groups groups. The group_in_dim represents the number of features in each group. The output tensor has a shape of [batch_size, output_size].

The linear transformation is performed by reshaping the input tensor to a shape of [batch_size * num_groups, group_in_dim], permuting the dimensions to [num_groups, batch_size, group_in_dim], and performing matrix multiplication with the weight tensor of shape [num_groups, group_in_dim, output_size]. The result tensor is then reshaped back to [batch_size, -1, output_size] and added with the bias tensor of shape [output_size].

The grouped linear layer is typically used in neural network architectures to introduce non-linearity and increase model capacity by learning more complex relationships between input and output features.

Source code in mindnlp/transformers/models/convbert/convbert.py
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
    """Constructs a grouped linear layer.

    Args:
        self (GroupedLinearLayer): The instance of the GroupedLinearLayer class.
        hidden_states (ms.Tensor): The input tensor of shape [batch_size, input_size].

    Returns:
        ms.Tensor: The output tensor of shape [batch_size, output_size].

    Raises:
        TypeError: If `hidden_states` is not of type `ms.Tensor`.
        ValueError: If the shape of `hidden_states` is not compatible with the expected shape [batch_size, input_size].
        ValueError: If `self.weight` is not of shape [num_groups, group_in_dim, output_size].
        ValueError: If `self.bias` is not of shape [output_size].

    Note:
        The `hidden_states` tensor represents the input to the grouped linear layer. It is expected to have a shape
        of [batch_size, input_size].

        The grouped linear layer applies a linear transformation to the input tensor by grouping the input features
        into `num_groups` groups. The `group_in_dim` represents the number of features in each group. The output tensor
        has a shape of [batch_size, output_size].

        The linear transformation is performed by reshaping the input tensor to a shape of [batch_size * num_groups,
        group_in_dim], permuting the dimensions to [num_groups, batch_size, group_in_dim], and performing matrix
        multiplication with the weight tensor of shape [num_groups, group_in_dim, output_size]. The result tensor is
        then reshaped back to [batch_size, -1, output_size] and added with the bias tensor of shape [output_size].

        The grouped linear layer is typically used in neural network architectures to introduce non-linearity and
        increase model capacity by learning more complex relationships between input and output features.
    """
    batch_size = list(hidden_states.shape)[0]
    x = ops.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim])
    x = x.permute(1, 0, 2)
    x = ops.matmul(x, self.weight)
    x = x.permute(1, 0, 2)
    x = ops.reshape(x, [batch_size, -1, self.output_size])
    x = x + self.bias
    return x

mindnlp.transformers.models.convbert.convbert.SeparableConv1D

Bases: Module

This class implements separable convolution, i.e. a depthwise and a pointwise layer

Source code in mindnlp/transformers/models/convbert/convbert.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
class SeparableConv1D(nn.Module):
    """This class implements separable convolution, i.e. a depthwise and a pointwise layer"""
    def __init__(self, config, input_filters, output_filters, kernel_size):
        """
        Initializes a SeparableConv1D instance.

        Args:
            self: The instance of the class.
            config: An object containing configuration settings.
            input_filters: An integer indicating the number of input filters.
            output_filters: An integer indicating the number of output filters.
            kernel_size: An integer specifying the size of the kernel.

        Returns:
            None.

        Raises:
            ValueError: If input_filters is not an integer.
            ValueError: If output_filters is not an integer.
            ValueError: If kernel_size is not an integer.
            ValueError: If config.initializer_range is not a valid value.
            ValueError: If pad_mode is not 'pad'.
            ValueError: If the dimensions of the weights for depthwise and pointwise convolutions do not match.
        """
        super().__init__()
        self.depthwise = nn.Conv1d(
            input_filters,
            input_filters,
            kernel_size=kernel_size,
            group=input_filters,
            pad_mode="pad",
            padding=kernel_size // 2,
            bias=False,
        )
        self.pointwise = nn.Conv1d(
            input_filters, output_filters, kernel_size=1, bias=False
        )
        self.bias = ms.Parameter(ops.zeros((output_filters, 1)))

        self.depthwise.weight = ms.Parameter(
            initializer(
                Normal(sigma=config.initializer_range, mean=0.0),
                self.depthwise.weight.shape,
                self.depthwise.weight.dtype,
            )
        )
        self.pointwise.weight = ms.Parameter(
            initializer(
                Normal(sigma=config.initializer_range, mean=0.0),
                self.pointwise.weight.shape,
                self.depthwise.weight.dtype,
            )
        )

    def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
        """
        Constructs a separable 1D convolution operation.

        Args:
            self (SeparableConv1D): An instance of the SeparableConv1D class.
            hidden_states (ms.Tensor): The input hidden states tensor to be convolved.
                Expected to be of shape (batch_size, input_channels, sequence_length).

        Returns:
            ms.Tensor: The output tensor after applying depthwise and pointwise convolutions, and adding bias.
                The shape of the output tensor is determined by the convolution operations performed.

        Raises:
            TypeError: If the input hidden_states is not a ms.Tensor object.
            ValueError: If the dimensions of the hidden_states tensor are not valid for convolution operations.
        """
        x = self.depthwise(hidden_states)
        x = self.pointwise(x)
        x += self.bias
        return x

mindnlp.transformers.models.convbert.convbert.SeparableConv1D.__init__(config, input_filters, output_filters, kernel_size)

Initializes a SeparableConv1D instance.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing configuration settings.

input_filters

An integer indicating the number of input filters.

output_filters

An integer indicating the number of output filters.

kernel_size

An integer specifying the size of the kernel.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If input_filters is not an integer.

ValueError

If output_filters is not an integer.

ValueError

If kernel_size is not an integer.

ValueError

If config.initializer_range is not a valid value.

ValueError

If pad_mode is not 'pad'.

ValueError

If the dimensions of the weights for depthwise and pointwise convolutions do not match.

Source code in mindnlp/transformers/models/convbert/convbert.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def __init__(self, config, input_filters, output_filters, kernel_size):
    """
    Initializes a SeparableConv1D instance.

    Args:
        self: The instance of the class.
        config: An object containing configuration settings.
        input_filters: An integer indicating the number of input filters.
        output_filters: An integer indicating the number of output filters.
        kernel_size: An integer specifying the size of the kernel.

    Returns:
        None.

    Raises:
        ValueError: If input_filters is not an integer.
        ValueError: If output_filters is not an integer.
        ValueError: If kernel_size is not an integer.
        ValueError: If config.initializer_range is not a valid value.
        ValueError: If pad_mode is not 'pad'.
        ValueError: If the dimensions of the weights for depthwise and pointwise convolutions do not match.
    """
    super().__init__()
    self.depthwise = nn.Conv1d(
        input_filters,
        input_filters,
        kernel_size=kernel_size,
        group=input_filters,
        pad_mode="pad",
        padding=kernel_size // 2,
        bias=False,
    )
    self.pointwise = nn.Conv1d(
        input_filters, output_filters, kernel_size=1, bias=False
    )
    self.bias = ms.Parameter(ops.zeros((output_filters, 1)))

    self.depthwise.weight = ms.Parameter(
        initializer(
            Normal(sigma=config.initializer_range, mean=0.0),
            self.depthwise.weight.shape,
            self.depthwise.weight.dtype,
        )
    )
    self.pointwise.weight = ms.Parameter(
        initializer(
            Normal(sigma=config.initializer_range, mean=0.0),
            self.pointwise.weight.shape,
            self.depthwise.weight.dtype,
        )
    )

mindnlp.transformers.models.convbert.convbert.SeparableConv1D.forward(hidden_states)

Constructs a separable 1D convolution operation.

PARAMETER DESCRIPTION
self

An instance of the SeparableConv1D class.

TYPE: SeparableConv1D

hidden_states

The input hidden states tensor to be convolved. Expected to be of shape (batch_size, input_channels, sequence_length).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

ms.Tensor: The output tensor after applying depthwise and pointwise convolutions, and adding bias. The shape of the output tensor is determined by the convolution operations performed.

RAISES DESCRIPTION
TypeError

If the input hidden_states is not a ms.Tensor object.

ValueError

If the dimensions of the hidden_states tensor are not valid for convolution operations.

Source code in mindnlp/transformers/models/convbert/convbert.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def forward(self, hidden_states: ms.Tensor) -> ms.Tensor:
    """
    Constructs a separable 1D convolution operation.

    Args:
        self (SeparableConv1D): An instance of the SeparableConv1D class.
        hidden_states (ms.Tensor): The input hidden states tensor to be convolved.
            Expected to be of shape (batch_size, input_channels, sequence_length).

    Returns:
        ms.Tensor: The output tensor after applying depthwise and pointwise convolutions, and adding bias.
            The shape of the output tensor is determined by the convolution operations performed.

    Raises:
        TypeError: If the input hidden_states is not a ms.Tensor object.
        ValueError: If the dimensions of the hidden_states tensor are not valid for convolution operations.
    """
    x = self.depthwise(hidden_states)
    x = self.pointwise(x)
    x += self.bias
    return x

mindnlp.transformers.models.convbert.convbert_config

ConvBERT model configuration

mindnlp.transformers.models.convbert.convbert_config.ConvBertConfig

Bases: PretrainedConfig

ConvBert Config

Source code in mindnlp/transformers/models/convbert/convbert_config.py
 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
class ConvBertConfig(PretrainedConfig):
    r"""
    ConvBert Config
    """
    model_type = "convbert"

    def __init__(
        self,
        vocab_size=30522,
        hidden_size=768,
        num_hidden_layers=12,
        num_attention_heads=12,
        intermediate_size=3072,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=2,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        pad_token_id=1,
        bos_token_id=0,
        eos_token_id=2,
        embedding_size=768,
        head_ratio=2,
        conv_kernel_size=9,
        num_groups=1,
        classifier_dropout=None,
        **kwargs,
    ):
        """
        Initializes a new instance of the ConvBertConfig class.

        Args:
            self: The current instance of the class.
            vocab_size (int, optional): The size of the vocabulary. Defaults to 30522.
            hidden_size (int, optional): The size of the hidden layers. Defaults to 768.
            num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
            num_attention_heads (int, optional): The number of attention heads. Defaults to 12.
            intermediate_size (int, optional): The size of the intermediate layers. Defaults to 3072.
            hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
            hidden_dropout_prob (float, optional): The dropout probability for the hidden layers. Defaults to 0.1.
            attention_probs_dropout_prob (float, optional): The dropout probability for the attention layers. Defaults to 0.1.
            max_position_embeddings (int, optional): The maximum position embeddings. Defaults to 512.
            type_vocab_size (int, optional): The size of the type vocabulary. Defaults to 2.
            initializer_range (float, optional): The range for the weight initializer. Defaults to 0.02.
            layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-12.
            pad_token_id (int, optional): The ID of the padding token. Defaults to 1.
            bos_token_id (int, optional): The ID of the beginning-of-sequence token. Defaults to 0.
            eos_token_id (int, optional): The ID of the end-of-sequence token. Defaults to 2.
            embedding_size (int, optional): The size of the embeddings. Defaults to 768.
            head_ratio (int, optional): The ratio of heads to hidden size. Defaults to 2.
            conv_kernel_size (int, optional): The size of the convolutional kernel. Defaults to 9.
            num_groups (int, optional): The number of groups for grouped convolution. Defaults to 1.
            classifier_dropout (float, optional): The dropout probability for the classifier layer. Defaults to None.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            **kwargs,
        )

        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.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.layer_norm_eps = layer_norm_eps
        self.embedding_size = embedding_size
        self.head_ratio = head_ratio
        self.conv_kernel_size = conv_kernel_size
        self.num_groups = num_groups
        self.classifier_dropout = classifier_dropout

mindnlp.transformers.models.convbert.convbert_config.ConvBertConfig.__init__(vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=1, bos_token_id=0, eos_token_id=2, embedding_size=768, head_ratio=2, conv_kernel_size=9, num_groups=1, classifier_dropout=None, **kwargs)

Initializes a new instance of the ConvBertConfig class.

PARAMETER DESCRIPTION
self

The current instance of the class.

vocab_size

The size of the vocabulary. Defaults to 30522.

TYPE: int DEFAULT: 30522

hidden_size

The size of the hidden layers. Defaults to 768.

TYPE: int DEFAULT: 768

num_hidden_layers

The number of hidden layers. Defaults to 12.

TYPE: int DEFAULT: 12

num_attention_heads

The number of attention heads. Defaults to 12.

TYPE: int DEFAULT: 12

intermediate_size

The size of the intermediate layers. Defaults to 3072.

TYPE: int DEFAULT: 3072

hidden_act

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

TYPE: str DEFAULT: 'gelu'

hidden_dropout_prob

The dropout probability for the hidden layers. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

attention_probs_dropout_prob

The dropout probability for the attention layers. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

max_position_embeddings

The maximum position embeddings. Defaults to 512.

TYPE: int DEFAULT: 512

type_vocab_size

The size of the type vocabulary. Defaults to 2.

TYPE: int DEFAULT: 2

initializer_range

The range for the weight initializer. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

layer_norm_eps

The epsilon value for layer normalization. Defaults to 1e-12.

TYPE: float DEFAULT: 1e-12

pad_token_id

The ID of the padding token. Defaults to 1.

TYPE: int DEFAULT: 1

bos_token_id

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

TYPE: int DEFAULT: 0

eos_token_id

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

TYPE: int DEFAULT: 2

embedding_size

The size of the embeddings. Defaults to 768.

TYPE: int DEFAULT: 768

head_ratio

The ratio of heads to hidden size. Defaults to 2.

TYPE: int DEFAULT: 2

conv_kernel_size

The size of the convolutional kernel. Defaults to 9.

TYPE: int DEFAULT: 9

num_groups

The number of groups for grouped convolution. Defaults to 1.

TYPE: int DEFAULT: 1

classifier_dropout

The dropout probability for the classifier layer. Defaults to None.

TYPE: float DEFAULT: None

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert_config.py
 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
def __init__(
    self,
    vocab_size=30522,
    hidden_size=768,
    num_hidden_layers=12,
    num_attention_heads=12,
    intermediate_size=3072,
    hidden_act="gelu",
    hidden_dropout_prob=0.1,
    attention_probs_dropout_prob=0.1,
    max_position_embeddings=512,
    type_vocab_size=2,
    initializer_range=0.02,
    layer_norm_eps=1e-12,
    pad_token_id=1,
    bos_token_id=0,
    eos_token_id=2,
    embedding_size=768,
    head_ratio=2,
    conv_kernel_size=9,
    num_groups=1,
    classifier_dropout=None,
    **kwargs,
):
    """
    Initializes a new instance of the ConvBertConfig class.

    Args:
        self: The current instance of the class.
        vocab_size (int, optional): The size of the vocabulary. Defaults to 30522.
        hidden_size (int, optional): The size of the hidden layers. Defaults to 768.
        num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
        num_attention_heads (int, optional): The number of attention heads. Defaults to 12.
        intermediate_size (int, optional): The size of the intermediate layers. Defaults to 3072.
        hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
        hidden_dropout_prob (float, optional): The dropout probability for the hidden layers. Defaults to 0.1.
        attention_probs_dropout_prob (float, optional): The dropout probability for the attention layers. Defaults to 0.1.
        max_position_embeddings (int, optional): The maximum position embeddings. Defaults to 512.
        type_vocab_size (int, optional): The size of the type vocabulary. Defaults to 2.
        initializer_range (float, optional): The range for the weight initializer. Defaults to 0.02.
        layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-12.
        pad_token_id (int, optional): The ID of the padding token. Defaults to 1.
        bos_token_id (int, optional): The ID of the beginning-of-sequence token. Defaults to 0.
        eos_token_id (int, optional): The ID of the end-of-sequence token. Defaults to 2.
        embedding_size (int, optional): The size of the embeddings. Defaults to 768.
        head_ratio (int, optional): The ratio of heads to hidden size. Defaults to 2.
        conv_kernel_size (int, optional): The size of the convolutional kernel. Defaults to 9.
        num_groups (int, optional): The number of groups for grouped convolution. Defaults to 1.
        classifier_dropout (float, optional): The dropout probability for the classifier layer. Defaults to None.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(
        pad_token_id=pad_token_id,
        bos_token_id=bos_token_id,
        eos_token_id=eos_token_id,
        **kwargs,
    )

    self.vocab_size = vocab_size
    self.hidden_size = hidden_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.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.layer_norm_eps = layer_norm_eps
    self.embedding_size = embedding_size
    self.head_ratio = head_ratio
    self.conv_kernel_size = conv_kernel_size
    self.num_groups = num_groups
    self.classifier_dropout = classifier_dropout

mindnlp.transformers.models.convbert.convbert_tokenizer

Tokenization classes for ConvBERT.

mindnlp.transformers.models.convbert.convbert_tokenizer.BasicTokenizer

Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).

PARAMETER DESCRIPTION
do_lower_case

Whether or not to lowercase the input when tokenizing.

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

never_split

Collection of tokens which will never be split during tokenization. Only has an effect when do_basic_tokenize=True

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

tokenize_chinese_chars

Whether or not to tokenize Chinese characters.

This should likely be deactivated for Japanese (see this issue).

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

strip_accents

Whether or not to strip all accents. If this option is not specified, then it will be determined by the value for lowercase (as in the original BERT).

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

do_split_on_punc

In some instances we want to skip the basic punctuation splitting so that later tokenization can capture the full context of the words, such as contractions.

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

Source code in mindnlp/transformers/models/convbert/convbert_tokenizer.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
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
class BasicTokenizer():
    """
    Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).

    Args:
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        never_split (`Iterable`, *optional*):
            Collection of tokens which will never be split during tokenization. Only has an effect when
            `do_basic_tokenize=True`
        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
            Whether or not to tokenize Chinese characters.

            This should likely be deactivated for Japanese (see this
            [issue](https://github.com/huggingface/transformers/issues/328)).
        strip_accents (`bool`, *optional*):
            Whether or not to strip all accents. If this option is not specified, then it will be determined by the
            value for `lowercase` (as in the original BERT).
        do_split_on_punc (`bool`, *optional*, defaults to `True`):
            In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
            the full context of the words, such as contractions.
    """
    def __init__(
        self,
        do_lower_case=True,
        never_split=None,
        tokenize_chinese_chars=True,
        strip_accents=None,
        do_split_on_punc=True,
    ):
        """
        Initializes a BasicTokenizer object with the specified parameters.

        Args:
            self (object): The instance of the BasicTokenizer class.
            do_lower_case (bool, optional):
                Indicates whether the text should be converted to lowercase. Default is True.
            never_split (list, optional):
                A list of tokens that should never be split during tokenization. Default is an empty list.
            tokenize_chinese_chars (bool, optional):
                Indicates whether Chinese characters should be tokenized individually. Default is True.
            strip_accents (None or str, optional):
                Specifies whether to strip accents from the text. Default is None.
            do_split_on_punc (bool, optional):
                Indicates whether to split tokens on punctuation marks. Default is True.

        Returns:
            None.

        Raises:
            None.
        """
        if never_split is None:
            never_split = []
        self.do_lower_case = do_lower_case
        self.never_split = set(never_split)
        self.tokenize_chinese_chars = tokenize_chinese_chars
        self.strip_accents = strip_accents
        self.do_split_on_punc = do_split_on_punc

    def tokenize(self, text, never_split=None):
        """
        Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.

        Args:
            never_split (`List[str]`, *optional*):
                Kept for backward compatibility purposes. Now implemented directly at the base class level (see
                [`PreTrainedTokenizer.tokenize`]) List of token not to split.
        """
        # union() returns a new set by concatenating the two sets.
        never_split = self.never_split.union(
            set(never_split)) if never_split else self.never_split
        text = self._clean_text(text)

        # This was added on November 1st, 2018 for the multilingual and Chinese
        # models. This is also applied to the English models now, but it doesn't
        # matter since the English models were not trained on any Chinese data
        # and generally don't have any Chinese data in them (there are Chinese
        # characters in the vocabulary because Wikipedia does have some Chinese
        # words in the English Wikipedia.).
        if self.tokenize_chinese_chars:
            text = self._tokenize_chinese_chars(text)
        # prevents treating the same character with different unicode codepoints as different characters
        unicode_normalized_text = unicodedata.normalize("NFC", text)
        orig_tokens = whitespace_tokenize(unicode_normalized_text)
        split_tokens = []
        for token in orig_tokens:
            if token not in never_split:
                if self.do_lower_case:
                    token = token.lower()
                    if self.strip_accents is not False:
                        token = self._run_strip_accents(token)
                elif self.strip_accents:
                    token = self._run_strip_accents(token)
            split_tokens.extend(self._run_split_on_punc(token, never_split))

        output_tokens = whitespace_tokenize(" ".join(split_tokens))
        return output_tokens

    def _run_strip_accents(self, text):
        """Strips accents from a piece of text."""
        text = unicodedata.normalize("NFD", text)
        output = []
        for char in text:
            cat = unicodedata.category(char)
            if cat == "Mn":
                continue
            output.append(char)
        return "".join(output)

    def _run_split_on_punc(self, text, never_split=None):
        """Splits punctuation on a piece of text."""
        if not self.do_split_on_punc or (never_split is not None and text in never_split):
            return [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 _tokenize_chinese_chars(self, text):
        """Adds whitespace around any CJK character."""
        output = []
        for char in text:
            cp = ord(char)
            if self._is_chinese_char(cp):
                output.append(" ")
                output.append(char)
                output.append(" ")
            else:
                output.append(char)
        return "".join(output)

    def _is_chinese_char(self, cp):
        """Checks whether CP is the codepoint of a CJK character."""
        # This defines a "chinese character" as anything in the CJK Unicode block:
        #   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
        #
        # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
        # despite its name. The modern Korean Hangul alphabet is a different block,
        # as is Japanese Hiragana and Katakana. Those alphabets are used to write
        # space-separated words, so they are not treated specially and handled
        # like the all of the other languages.
        if (
            (cp >= 0x4E00 and cp <= 0x9FFF)
            or (cp >= 0x3400 and cp <= 0x4DBF)  #
            or (cp >= 0x20000 and cp <= 0x2A6DF)  #
            or (cp >= 0x2A700 and cp <= 0x2B73F)  #
            or (cp >= 0x2B740 and cp <= 0x2B81F)  #
            or (cp >= 0x2B820 and cp <= 0x2CEAF)  #
            or (cp >= 0xF900 and cp <= 0xFAFF)
            or (cp >= 0x2F800 and cp <= 0x2FA1F)  #
        ):  #
            return True

        return False

    def _clean_text(self, text):
        """Performs invalid character removal and whitespace cleanup on text."""
        output = []
        for char in text:
            cp = ord(char)
            if cp == 0 or cp == 0xFFFD or _is_control(char):
                continue
            if _is_whitespace(char):
                output.append(" ")
            else:
                output.append(char)
        return "".join(output)

mindnlp.transformers.models.convbert.convbert_tokenizer.BasicTokenizer.__init__(do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None, do_split_on_punc=True)

Initializes a BasicTokenizer object with the specified parameters.

PARAMETER DESCRIPTION
self

The instance of the BasicTokenizer class.

TYPE: object

do_lower_case

Indicates whether the text should be converted to lowercase. Default is True.

TYPE: bool DEFAULT: True

never_split

A list of tokens that should never be split during tokenization. Default is an empty list.

TYPE: list DEFAULT: None

tokenize_chinese_chars

Indicates whether Chinese characters should be tokenized individually. Default is True.

TYPE: bool DEFAULT: True

strip_accents

Specifies whether to strip accents from the text. Default is None.

TYPE: None or str DEFAULT: None

do_split_on_punc

Indicates whether to split tokens on punctuation marks. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/convbert/convbert_tokenizer.py
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
def __init__(
    self,
    do_lower_case=True,
    never_split=None,
    tokenize_chinese_chars=True,
    strip_accents=None,
    do_split_on_punc=True,
):
    """
    Initializes a BasicTokenizer object with the specified parameters.

    Args:
        self (object): The instance of the BasicTokenizer class.
        do_lower_case (bool, optional):
            Indicates whether the text should be converted to lowercase. Default is True.
        never_split (list, optional):
            A list of tokens that should never be split during tokenization. Default is an empty list.
        tokenize_chinese_chars (bool, optional):
            Indicates whether Chinese characters should be tokenized individually. Default is True.
        strip_accents (None or str, optional):
            Specifies whether to strip accents from the text. Default is None.
        do_split_on_punc (bool, optional):
            Indicates whether to split tokens on punctuation marks. Default is True.

    Returns:
        None.

    Raises:
        None.
    """
    if never_split is None:
        never_split = []
    self.do_lower_case = do_lower_case
    self.never_split = set(never_split)
    self.tokenize_chinese_chars = tokenize_chinese_chars
    self.strip_accents = strip_accents
    self.do_split_on_punc = do_split_on_punc

mindnlp.transformers.models.convbert.convbert_tokenizer.BasicTokenizer.tokenize(text, never_split=None)

Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.

PARAMETER DESCRIPTION
never_split

Kept for backward compatibility purposes. Now implemented directly at the base class level (see [PreTrainedTokenizer.tokenize]) List of token not to split.

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

Source code in mindnlp/transformers/models/convbert/convbert_tokenizer.py
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
def tokenize(self, text, never_split=None):
    """
    Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.

    Args:
        never_split (`List[str]`, *optional*):
            Kept for backward compatibility purposes. Now implemented directly at the base class level (see
            [`PreTrainedTokenizer.tokenize`]) List of token not to split.
    """
    # union() returns a new set by concatenating the two sets.
    never_split = self.never_split.union(
        set(never_split)) if never_split else self.never_split
    text = self._clean_text(text)

    # This was added on November 1st, 2018 for the multilingual and Chinese
    # models. This is also applied to the English models now, but it doesn't
    # matter since the English models were not trained on any Chinese data
    # and generally don't have any Chinese data in them (there are Chinese
    # characters in the vocabulary because Wikipedia does have some Chinese
    # words in the English Wikipedia.).
    if self.tokenize_chinese_chars:
        text = self._tokenize_chinese_chars(text)
    # prevents treating the same character with different unicode codepoints as different characters
    unicode_normalized_text = unicodedata.normalize("NFC", text)
    orig_tokens = whitespace_tokenize(unicode_normalized_text)
    split_tokens = []
    for token in orig_tokens:
        if token not in never_split:
            if self.do_lower_case:
                token = token.lower()
                if self.strip_accents is not False:
                    token = self._run_strip_accents(token)
            elif self.strip_accents:
                token = self._run_strip_accents(token)
        split_tokens.extend(self._run_split_on_punc(token, never_split))

    output_tokens = whitespace_tokenize(" ".join(split_tokens))
    return output_tokens

mindnlp.transformers.models.convbert.convbert_tokenizer.ConvBertTokenizer

Bases: PreTrainedTokenizer

Construct a ConvBERT tokenizer. Based on WordPiece.

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

PARAMETER DESCRIPTION
vocab_file

File containing the vocabulary.

TYPE: `str`

do_lower_case

Whether or not to lowercase the input when tokenizing.

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

do_basic_tokenize

Whether or not to do basic tokenization before WordPiece.

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

never_split

Collection of tokens which will never be split during tokenization. Only has an effect when do_basic_tokenize=True

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

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]'

tokenize_chinese_chars

Whether or not to tokenize Chinese characters.

This should likely be deactivated for Japanese (see this issue).

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

strip_accents

Whether or not to strip all accents. If this option is not specified, then it will be determined by the value for lowercase (as in the original ConvBERT).

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

Source code in mindnlp/transformers/models/convbert/convbert_tokenizer.py
 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