跳转至

luke

mindnlp.transformers.models.luke.luke

MindNlp LUKE model

mindnlp.transformers.models.luke.luke.EntityPredictionHead

Bases: Module

EntityPredictionHead

Source code in mindnlp/transformers/models/luke/luke.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
class EntityPredictionHead(nn.Module):
    """
    EntityPredictionHead
    """
    def __init__(self, config):
        """
        Initialize the EntityPredictionHead instance.

        Args:
            self (EntityPredictionHead): The EntityPredictionHead instance.
            config (object): The configuration object containing parameters for entity prediction head.
                This object should have attributes required for initializing the EntityPredictionHead instance.
                It must be provided as an argument during initialization.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided or is of an incorrect type.
            ValueError: If the config object does not contain the required attributes for initialization.
            RuntimeError: If there is an issue with initializing any component within the EntityPredictionHead instance.
        """
        super().__init__()
        self.config = config
        self.transform = EntityPredictionHeadTransform(config)
        self.decoder = nn.Linear(config.entity_emb_size, config.entity_vocab_size, bias=False)
        self.bias = mindspore.Parameter(ops.zeros((config.entity_vocab_size,)))

    def construct(self, hidden_states):
        """
        Method to construct the entity prediction head using the given hidden states.

        Args:
            self (EntityPredictionHead): An instance of the EntityPredictionHead class.
            hidden_states (tensor): The hidden states to be used for constructing the entity prediction head.
                Should be a tensor representing the hidden states of the input data.

        Returns:
            None: This method does not return any value.
                The entity prediction head is constructed and updated within the class instance.

        Raises:
            TypeError: If the input hidden_states is not of type tensor.
            ValueError: If the hidden_states tensor is empty or has invalid dimensions.
        """
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states) + self.bias

        return hidden_states

mindnlp.transformers.models.luke.luke.EntityPredictionHead.__init__(config)

Initialize the EntityPredictionHead instance.

PARAMETER DESCRIPTION
self

The EntityPredictionHead instance.

TYPE: EntityPredictionHead

config

The configuration object containing parameters for entity prediction head. This object should have attributes required for initializing the EntityPredictionHead instance. It must be provided as an argument during initialization.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

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

ValueError

If the config object does not contain the required attributes for initialization.

RuntimeError

If there is an issue with initializing any component within the EntityPredictionHead instance.

Source code in mindnlp/transformers/models/luke/luke.py
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
def __init__(self, config):
    """
    Initialize the EntityPredictionHead instance.

    Args:
        self (EntityPredictionHead): The EntityPredictionHead instance.
        config (object): The configuration object containing parameters for entity prediction head.
            This object should have attributes required for initializing the EntityPredictionHead instance.
            It must be provided as an argument during initialization.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided or is of an incorrect type.
        ValueError: If the config object does not contain the required attributes for initialization.
        RuntimeError: If there is an issue with initializing any component within the EntityPredictionHead instance.
    """
    super().__init__()
    self.config = config
    self.transform = EntityPredictionHeadTransform(config)
    self.decoder = nn.Linear(config.entity_emb_size, config.entity_vocab_size, bias=False)
    self.bias = mindspore.Parameter(ops.zeros((config.entity_vocab_size,)))

mindnlp.transformers.models.luke.luke.EntityPredictionHead.construct(hidden_states)

Method to construct the entity prediction head using the given hidden states.

PARAMETER DESCRIPTION
self

An instance of the EntityPredictionHead class.

TYPE: EntityPredictionHead

hidden_states

The hidden states to be used for constructing the entity prediction head. Should be a tensor representing the hidden states of the input data.

TYPE: tensor

RETURNS DESCRIPTION
None

This method does not return any value. The entity prediction head is constructed and updated within the class instance.

RAISES DESCRIPTION
TypeError

If the input hidden_states is not of type tensor.

ValueError

If the hidden_states tensor is empty or has invalid dimensions.

Source code in mindnlp/transformers/models/luke/luke.py
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
def construct(self, hidden_states):
    """
    Method to construct the entity prediction head using the given hidden states.

    Args:
        self (EntityPredictionHead): An instance of the EntityPredictionHead class.
        hidden_states (tensor): The hidden states to be used for constructing the entity prediction head.
            Should be a tensor representing the hidden states of the input data.

    Returns:
        None: This method does not return any value.
            The entity prediction head is constructed and updated within the class instance.

    Raises:
        TypeError: If the input hidden_states is not of type tensor.
        ValueError: If the hidden_states tensor is empty or has invalid dimensions.
    """
    hidden_states = self.transform(hidden_states)
    hidden_states = self.decoder(hidden_states) + self.bias

    return hidden_states

mindnlp.transformers.models.luke.luke.EntityPredictionHeadTransform

Bases: Module

EntityPredictionHeadTransform

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

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

                - Type: Any
                - Purpose: Specifies the configuration settings for the EntityPredictionHeadTransform instance.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            TypeError: If the config.hidden_act parameter is not a string or a valid activation function.
            ValueError: If the config.entity_emb_size is invalid or the config.layer_norm_eps is not
                within the valid range.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.entity_emb_size)
        if isinstance(config.hidden_act, str):
            self.transform_act_fn = ACT2FN[config.hidden_act]
        else:
            self.transform_act_fn = config.hidden_act
        self.layer_norm = nn.LayerNorm([config.entity_emb_size, ], eps=config.layer_norm_eps)

    def construct(self, hidden_states):
        """
        Method to construct the entity prediction head transformation.

        Args:
            self (EntityPredictionHeadTransform): An instance of the EntityPredictionHeadTransform class.
            hidden_states (tensor): The input hidden states to be transformed.
                It should be a tensor representing the hidden states of the model.

        Returns:
            tensor: The transformed hidden states after passing through the dense layer,
                activation function, and layer normalization.
                It retains the same shape and structure as the input hidden states.

        Raises:
            None.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.transform_act_fn(hidden_states)
        hidden_states = self.layer_norm(hidden_states)
        return hidden_states

mindnlp.transformers.models.luke.luke.EntityPredictionHeadTransform.__init__(config)

Initializes the EntityPredictionHeadTransform class.

PARAMETER DESCRIPTION
self

The instance of the EntityPredictionHeadTransform class.

config

An object containing configuration parameters for the EntityPredictionHeadTransform class.

  • Type: Any
  • Purpose: Specifies the configuration settings for the EntityPredictionHeadTransform instance.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

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

ValueError

If the config.entity_emb_size is invalid or the config.layer_norm_eps is not within the valid range.

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

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

            - Type: Any
            - Purpose: Specifies the configuration settings for the EntityPredictionHeadTransform instance.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        TypeError: If the config.hidden_act parameter is not a string or a valid activation function.
        ValueError: If the config.entity_emb_size is invalid or the config.layer_norm_eps is not
            within the valid range.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.entity_emb_size)
    if isinstance(config.hidden_act, str):
        self.transform_act_fn = ACT2FN[config.hidden_act]
    else:
        self.transform_act_fn = config.hidden_act
    self.layer_norm = nn.LayerNorm([config.entity_emb_size, ], eps=config.layer_norm_eps)

mindnlp.transformers.models.luke.luke.EntityPredictionHeadTransform.construct(hidden_states)

Method to construct the entity prediction head transformation.

PARAMETER DESCRIPTION
self

An instance of the EntityPredictionHeadTransform class.

TYPE: EntityPredictionHeadTransform

hidden_states

The input hidden states to be transformed. It should be a tensor representing the hidden states of the model.

TYPE: tensor

RETURNS DESCRIPTION
tensor

The transformed hidden states after passing through the dense layer, activation function, and layer normalization. It retains the same shape and structure as the input hidden states.

Source code in mindnlp/transformers/models/luke/luke.py
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
def construct(self, hidden_states):
    """
    Method to construct the entity prediction head transformation.

    Args:
        self (EntityPredictionHeadTransform): An instance of the EntityPredictionHeadTransform class.
        hidden_states (tensor): The input hidden states to be transformed.
            It should be a tensor representing the hidden states of the model.

    Returns:
        tensor: The transformed hidden states after passing through the dense layer,
            activation function, and layer normalization.
            It retains the same shape and structure as the input hidden states.

    Raises:
        None.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.transform_act_fn(hidden_states)
    hidden_states = self.layer_norm(hidden_states)
    return hidden_states

mindnlp.transformers.models.luke.luke.LukeAttention

Bases: Module

LukeAttention

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

        Args:
            self (LukeAttention): The current instance of the LukeAttention class.
            config: The configuration object for the attention mechanism.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.self = LukeSelfAttention(config)
        self.output = LukeSelfOutput(config)
        self.pruned_heads = set()

    def prune_heads(self, heads):
        """
        NotImplementedError
        """
        raise NotImplementedError("LUKE does not support the pruning of attention heads")

    def construct(
            self,
            word_hidden_states,
            entity_hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
    ):
        """
        Constructs the attention mechanism in the LukeAttention class.

        Args:
            self (LukeAttention): The instance of the LukeAttention class.
            word_hidden_states (tensor): The hidden states of words. Shape: (batch_size, word_seq_len, hidden_size).
            entity_hidden_states (tensor): The hidden states of entities. Shape: (batch_size, entity_seq_len, hidden_size).
            attention_mask (tensor, optional): Mask to avoid performing attention on padding tokens.
                Shape: (batch_size, 1, word_seq_len, entity_seq_len).
            head_mask (tensor, optional): Mask to exclude certain attention heads. Shape: (num_attention_heads,).
            output_attentions (bool): Whether to output attentions. Default is False.

        Returns:
            tuple: A tuple containing word_attention_output and entity_attention_output
                if entity_hidden_states is not None, else None.

                - word_attention_output (tensor): The attention output for word hidden states.
                Shape: (batch_size, word_seq_len, hidden_size).
                - entity_attention_output (tensor or None): The attention output for entity hidden states
                if entity_hidden_states is not None, else None.
                - additional outputs: Additional outputs returned by the attention mechanism.

        Raises:
            ValueError: If the shapes of word_hidden_states and entity_hidden_states are incompatible.
            RuntimeError: If an error occurs during the attention computation.
            IndexError: If the attention indices are out of bounds.
        """
        word_size = word_hidden_states.shape[1]
        self_outputs = self.self(
            word_hidden_states,
            entity_hidden_states,
            attention_mask,
            head_mask,
            output_attentions,
        )
        if entity_hidden_states is None:
            concat_self_outputs = self_outputs[0]
            concat_hidden_states = word_hidden_states
        else:
            concat_self_outputs = ops.cat(self_outputs[:2], axis=1)
            concat_hidden_states = ops.cat([word_hidden_states, entity_hidden_states], axis=1)

        attention_output = self.output(concat_self_outputs, concat_hidden_states)

        word_attention_output = attention_output[:, :word_size, :]
        if entity_hidden_states is None:
            entity_attention_output = None
        else:
            entity_attention_output = attention_output[:, word_size:, :]

        # add attentions if we output them
        outputs = (word_attention_output, entity_attention_output) + self_outputs[2:]

        return outputs

mindnlp.transformers.models.luke.luke.LukeAttention.__init__(config)

Initializes a new instance of the LukeAttention class.

PARAMETER DESCRIPTION
self

The current instance of the LukeAttention class.

TYPE: LukeAttention

config

The configuration object for the attention mechanism.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def __init__(self, config):
    """
    Initializes a new instance of the LukeAttention class.

    Args:
        self (LukeAttention): The current instance of the LukeAttention class.
        config: The configuration object for the attention mechanism.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.self = LukeSelfAttention(config)
    self.output = LukeSelfOutput(config)
    self.pruned_heads = set()

mindnlp.transformers.models.luke.luke.LukeAttention.construct(word_hidden_states, entity_hidden_states, attention_mask=None, head_mask=None, output_attentions=False)

Constructs the attention mechanism in the LukeAttention class.

PARAMETER DESCRIPTION
self

The instance of the LukeAttention class.

TYPE: LukeAttention

word_hidden_states

The hidden states of words. Shape: (batch_size, word_seq_len, hidden_size).

TYPE: tensor

entity_hidden_states

The hidden states of entities. Shape: (batch_size, entity_seq_len, hidden_size).

TYPE: tensor

attention_mask

Mask to avoid performing attention on padding tokens. Shape: (batch_size, 1, word_seq_len, entity_seq_len).

TYPE: tensor DEFAULT: None

head_mask

Mask to exclude certain attention heads. Shape: (num_attention_heads,).

TYPE: tensor DEFAULT: None

output_attentions

Whether to output attentions. Default is False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple

A tuple containing word_attention_output and entity_attention_output if entity_hidden_states is not None, else None.

  • word_attention_output (tensor): The attention output for word hidden states. Shape: (batch_size, word_seq_len, hidden_size).
  • entity_attention_output (tensor or None): The attention output for entity hidden states if entity_hidden_states is not None, else None.
  • additional outputs: Additional outputs returned by the attention mechanism.
RAISES DESCRIPTION
ValueError

If the shapes of word_hidden_states and entity_hidden_states are incompatible.

RuntimeError

If an error occurs during the attention computation.

IndexError

If the attention indices are out of bounds.

Source code in mindnlp/transformers/models/luke/luke.py
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
def construct(
        self,
        word_hidden_states,
        entity_hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
):
    """
    Constructs the attention mechanism in the LukeAttention class.

    Args:
        self (LukeAttention): The instance of the LukeAttention class.
        word_hidden_states (tensor): The hidden states of words. Shape: (batch_size, word_seq_len, hidden_size).
        entity_hidden_states (tensor): The hidden states of entities. Shape: (batch_size, entity_seq_len, hidden_size).
        attention_mask (tensor, optional): Mask to avoid performing attention on padding tokens.
            Shape: (batch_size, 1, word_seq_len, entity_seq_len).
        head_mask (tensor, optional): Mask to exclude certain attention heads. Shape: (num_attention_heads,).
        output_attentions (bool): Whether to output attentions. Default is False.

    Returns:
        tuple: A tuple containing word_attention_output and entity_attention_output
            if entity_hidden_states is not None, else None.

            - word_attention_output (tensor): The attention output for word hidden states.
            Shape: (batch_size, word_seq_len, hidden_size).
            - entity_attention_output (tensor or None): The attention output for entity hidden states
            if entity_hidden_states is not None, else None.
            - additional outputs: Additional outputs returned by the attention mechanism.

    Raises:
        ValueError: If the shapes of word_hidden_states and entity_hidden_states are incompatible.
        RuntimeError: If an error occurs during the attention computation.
        IndexError: If the attention indices are out of bounds.
    """
    word_size = word_hidden_states.shape[1]
    self_outputs = self.self(
        word_hidden_states,
        entity_hidden_states,
        attention_mask,
        head_mask,
        output_attentions,
    )
    if entity_hidden_states is None:
        concat_self_outputs = self_outputs[0]
        concat_hidden_states = word_hidden_states
    else:
        concat_self_outputs = ops.cat(self_outputs[:2], axis=1)
        concat_hidden_states = ops.cat([word_hidden_states, entity_hidden_states], axis=1)

    attention_output = self.output(concat_self_outputs, concat_hidden_states)

    word_attention_output = attention_output[:, :word_size, :]
    if entity_hidden_states is None:
        entity_attention_output = None
    else:
        entity_attention_output = attention_output[:, word_size:, :]

    # add attentions if we output them
    outputs = (word_attention_output, entity_attention_output) + self_outputs[2:]

    return outputs

mindnlp.transformers.models.luke.luke.LukeAttention.prune_heads(heads)

NotImplementedError

Source code in mindnlp/transformers/models/luke/luke.py
476
477
478
479
480
def prune_heads(self, heads):
    """
    NotImplementedError
    """
    raise NotImplementedError("LUKE does not support the pruning of attention heads")

mindnlp.transformers.models.luke.luke.LukeEmbeddings

Bases: Module

LukeEmbeddings

Source code in mindnlp/transformers/models/luke/luke.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class LukeEmbeddings(nn.Module):
    """
    LukeEmbeddings
    """
    def __init__(self, config: LukeConfig):
        """
        Initializes an instance of the LukeEmbeddings class.

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

                - vocab_size (int): The size of the vocabulary.
                - hidden_size (int): The size of the hidden state.
                - pad_token_id (int): The index of the padding token in the vocabulary.
                - max_position_embeddings (int): The maximum number of positions for positional embeddings.
                - 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 hidden layers.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
        self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

        # End copy
        self.padding_idx = config.pad_token_id
        self.position_embeddings = nn.Embedding(
            config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
        )

    def construct(
            self,
            input_ids=None,
            token_type_ids=None,
            position_ids=None,
            inputs_embeds=None,
    ):
        """
        Args:
            self (LukeEmbeddings): The instance of the LukeEmbeddings class.
            input_ids (Tensor, optional): A 2-D tensor containing the input token IDs. Defaults to None.
            token_type_ids (Tensor, optional): A 2-D tensor containing the token type IDs. Defaults to None.
            position_ids (Tensor, optional): A 2-D tensor containing the position IDs. Defaults to None.
            inputs_embeds (Tensor, optional): A 3-D tensor containing the input embeddings. Defaults to None.

        Returns:
            None.

        Raises:
            ValueError: If both input_ids and inputs_embeds are None.
            ValueError: If input_ids and inputs_embeds have mismatched shapes.
            TypeError: If the data type of token_type_ids is not int64.
        """
        if position_ids is None:
            if input_ids is not None:
                # Create the position ids from the input token ids. Any padded tokens remain padded.
                position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
            else:
                position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)

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

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

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

        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.layer_norm(embeddings)
        embeddings = self.dropout(embeddings)
        return embeddings

    def create_position_ids_from_inputs_embeds(self, inputs_embeds):
        """
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
        """
        input_shape = inputs_embeds.shape()[:-1]
        sequence_length = input_shape[1]

        position_ids = mindspore.numpy.arange(
            self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=mindspore.int64
        )
        return ops.broadcast_to(position_ids.unsqueeze(0), input_shape)

mindnlp.transformers.models.luke.luke.LukeEmbeddings.__init__(config)

Initializes an instance of the LukeEmbeddings class.

PARAMETER DESCRIPTION
self

The instance of the class itself.

config

An object of the LukeConfig class containing configuration parameters.

  • vocab_size (int): The size of the vocabulary.
  • hidden_size (int): The size of the hidden state.
  • pad_token_id (int): The index of the padding token in the vocabulary.
  • max_position_embeddings (int): The maximum number of positions for positional embeddings.
  • 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 hidden layers.

TYPE: LukeConfig

RETURNS DESCRIPTION

None

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

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

            - vocab_size (int): The size of the vocabulary.
            - hidden_size (int): The size of the hidden state.
            - pad_token_id (int): The index of the padding token in the vocabulary.
            - max_position_embeddings (int): The maximum number of positions for positional embeddings.
            - 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 hidden layers.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
    self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
    self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
    self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    # End copy
    self.padding_idx = config.pad_token_id
    self.position_embeddings = nn.Embedding(
        config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
    )

mindnlp.transformers.models.luke.luke.LukeEmbeddings.construct(input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None)

PARAMETER DESCRIPTION
self

The instance of the LukeEmbeddings class.

TYPE: LukeEmbeddings

input_ids

A 2-D tensor containing the input token IDs. Defaults to None.

TYPE: Tensor DEFAULT: None

token_type_ids

A 2-D tensor containing the token type IDs. Defaults to None.

TYPE: Tensor DEFAULT: None

position_ids

A 2-D tensor containing the position IDs. Defaults to None.

TYPE: Tensor DEFAULT: None

inputs_embeds

A 3-D tensor containing the input embeddings. Defaults to None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If both input_ids and inputs_embeds are None.

ValueError

If input_ids and inputs_embeds have mismatched shapes.

TypeError

If the data type of token_type_ids is not int64.

Source code in mindnlp/transformers/models/luke/luke.py
 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
def construct(
        self,
        input_ids=None,
        token_type_ids=None,
        position_ids=None,
        inputs_embeds=None,
):
    """
    Args:
        self (LukeEmbeddings): The instance of the LukeEmbeddings class.
        input_ids (Tensor, optional): A 2-D tensor containing the input token IDs. Defaults to None.
        token_type_ids (Tensor, optional): A 2-D tensor containing the token type IDs. Defaults to None.
        position_ids (Tensor, optional): A 2-D tensor containing the position IDs. Defaults to None.
        inputs_embeds (Tensor, optional): A 3-D tensor containing the input embeddings. Defaults to None.

    Returns:
        None.

    Raises:
        ValueError: If both input_ids and inputs_embeds are None.
        ValueError: If input_ids and inputs_embeds have mismatched shapes.
        TypeError: If the data type of token_type_ids is not int64.
    """
    if position_ids is None:
        if input_ids is not None:
            # Create the position ids from the input token ids. Any padded tokens remain padded.
            position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
        else:
            position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)

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

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

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

    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.layer_norm(embeddings)
    embeddings = self.dropout(embeddings)
    return embeddings

mindnlp.transformers.models.luke.luke.LukeEmbeddings.create_position_ids_from_inputs_embeds(inputs_embeds)

We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

Source code in mindnlp/transformers/models/luke/luke.py
125
126
127
128
129
130
131
132
133
134
135
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
    """
    We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
    """
    input_shape = inputs_embeds.shape()[:-1]
    sequence_length = input_shape[1]

    position_ids = mindspore.numpy.arange(
        self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=mindspore.int64
    )
    return ops.broadcast_to(position_ids.unsqueeze(0), input_shape)

mindnlp.transformers.models.luke.luke.LukeEncoder

Bases: Module

LukeEncoder

Source code in mindnlp/transformers/models/luke/luke.py
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
class LukeEncoder(nn.Module):
    """
    LukeEncoder
    """
    def __init__(self, config):
        """Initialize a LukeEncoder object.

        Args:
            self (LukeEncoder): The LukeEncoder instance.
            config (dict): A dictionary containing configuration parameters for the encoder.

        Returns:
            None.

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

    def construct(
            self,
            word_hidden_states,
            entity_hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
            output_hidden_states=False,
            return_dict=True,
    ):
        """
        This method constructs the hidden states and attentions for a LukeEncoder model.

        Args:
            self: The instance of the LukeEncoder class.
            word_hidden_states: The hidden states of words, of shape (batch_size, sequence_length, hidden_size).
            entity_hidden_states: The hidden states of entities, of shape (batch_size, num_entities, hidden_size).
            attention_mask: An optional tensor of shape (batch_size, sequence_length) containing attention mask values.
            head_mask: An optional tensor of shape (num_layers, num_attention_heads) providing a mask for attention heads.
            output_attentions: A boolean flag indicating whether to output attention weights.
            output_hidden_states: A boolean flag indicating whether to output hidden states.
            return_dict: A boolean flag indicating whether to return the output as a dictionary.

        Returns:
            None

        Raises:
            ValueError: If the dimensions of input tensors are not valid.
            TypeError: If the input parameters are not of the expected types.
            IndexError: If the head mask dimensions do not match the expected shape.
        """
        all_word_hidden_states = () if output_hidden_states else None
        all_entity_hidden_states = () if output_hidden_states else None
        all_self_attentions = () if output_attentions else None

        for i, layer_module in enumerate(self.layer):
            if output_hidden_states:
                all_word_hidden_states = all_word_hidden_states + (word_hidden_states,)
                all_entity_hidden_states = all_entity_hidden_states + (entity_hidden_states,)

            layer_head_mask = head_mask[i] if head_mask is not None else None
            # TODO
            # if self.gradient_checkpointing and self.training:
            #
            #     def create_custom_forward(module):
            #         def custom_forward(*inputs):
            #             return module(*inputs, output_attentions)
            #
            #         return custom_forward
            #
            #     layer_outputs = torch.utils.checkpoint.checkpoint(
            #         create_custom_forward(layer_module),
            #         word_hidden_states,
            #         entity_hidden_states,
            #         attention_mask,
            #         layer_head_mask,
            #     )
            layer_outputs = layer_module(
                word_hidden_states,
                entity_hidden_states,
                attention_mask,
                layer_head_mask,
                output_attentions,
            )

            word_hidden_states = layer_outputs[0]

            if entity_hidden_states is not None:
                entity_hidden_states = layer_outputs[1]

            if output_attentions:
                all_self_attentions = all_self_attentions + (layer_outputs[2],)

        if output_hidden_states:
            all_word_hidden_states = all_word_hidden_states + (word_hidden_states,)
            all_entity_hidden_states = all_entity_hidden_states + (entity_hidden_states,)
        if not return_dict:
            return tuple(
                v
                for v in [
                    word_hidden_states,
                    all_word_hidden_states,
                    all_self_attentions,
                    entity_hidden_states,
                    all_entity_hidden_states,
                ]
                if v is not None
            )
        return {
            "last_hidden_state": word_hidden_states,
            "hidden_states": all_word_hidden_states,
            "attentions": all_self_attentions,
            "entity_last_hidden_state": entity_hidden_states,
            "entity_hidden_states": all_entity_hidden_states,
        }

mindnlp.transformers.models.luke.luke.LukeEncoder.__init__(config)

Initialize a LukeEncoder object.

PARAMETER DESCRIPTION
self

The LukeEncoder instance.

TYPE: LukeEncoder

config

A dictionary containing configuration parameters for the encoder.

TYPE: dict

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
def __init__(self, config):
    """Initialize a LukeEncoder object.

    Args:
        self (LukeEncoder): The LukeEncoder instance.
        config (dict): A dictionary containing configuration parameters for the encoder.

    Returns:
        None.

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

mindnlp.transformers.models.luke.luke.LukeEncoder.construct(word_hidden_states, entity_hidden_states, attention_mask=None, head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True)

This method constructs the hidden states and attentions for a LukeEncoder model.

PARAMETER DESCRIPTION
self

The instance of the LukeEncoder class.

word_hidden_states

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

entity_hidden_states

The hidden states of entities, of shape (batch_size, num_entities, hidden_size).

attention_mask

An optional tensor of shape (batch_size, sequence_length) containing attention mask values.

DEFAULT: None

head_mask

An optional tensor of shape (num_layers, num_attention_heads) providing a mask for attention heads.

DEFAULT: None

output_attentions

A boolean flag indicating whether to output attention weights.

DEFAULT: False

output_hidden_states

A boolean flag indicating whether to output hidden states.

DEFAULT: False

return_dict

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

DEFAULT: True

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the dimensions of input tensors are not valid.

TypeError

If the input parameters are not of the expected types.

IndexError

If the head mask dimensions do not match the expected shape.

Source code in mindnlp/transformers/models/luke/luke.py
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def construct(
        self,
        word_hidden_states,
        entity_hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
        output_hidden_states=False,
        return_dict=True,
):
    """
    This method constructs the hidden states and attentions for a LukeEncoder model.

    Args:
        self: The instance of the LukeEncoder class.
        word_hidden_states: The hidden states of words, of shape (batch_size, sequence_length, hidden_size).
        entity_hidden_states: The hidden states of entities, of shape (batch_size, num_entities, hidden_size).
        attention_mask: An optional tensor of shape (batch_size, sequence_length) containing attention mask values.
        head_mask: An optional tensor of shape (num_layers, num_attention_heads) providing a mask for attention heads.
        output_attentions: A boolean flag indicating whether to output attention weights.
        output_hidden_states: A boolean flag indicating whether to output hidden states.
        return_dict: A boolean flag indicating whether to return the output as a dictionary.

    Returns:
        None

    Raises:
        ValueError: If the dimensions of input tensors are not valid.
        TypeError: If the input parameters are not of the expected types.
        IndexError: If the head mask dimensions do not match the expected shape.
    """
    all_word_hidden_states = () if output_hidden_states else None
    all_entity_hidden_states = () if output_hidden_states else None
    all_self_attentions = () if output_attentions else None

    for i, layer_module in enumerate(self.layer):
        if output_hidden_states:
            all_word_hidden_states = all_word_hidden_states + (word_hidden_states,)
            all_entity_hidden_states = all_entity_hidden_states + (entity_hidden_states,)

        layer_head_mask = head_mask[i] if head_mask is not None else None
        # TODO
        # if self.gradient_checkpointing and self.training:
        #
        #     def create_custom_forward(module):
        #         def custom_forward(*inputs):
        #             return module(*inputs, output_attentions)
        #
        #         return custom_forward
        #
        #     layer_outputs = torch.utils.checkpoint.checkpoint(
        #         create_custom_forward(layer_module),
        #         word_hidden_states,
        #         entity_hidden_states,
        #         attention_mask,
        #         layer_head_mask,
        #     )
        layer_outputs = layer_module(
            word_hidden_states,
            entity_hidden_states,
            attention_mask,
            layer_head_mask,
            output_attentions,
        )

        word_hidden_states = layer_outputs[0]

        if entity_hidden_states is not None:
            entity_hidden_states = layer_outputs[1]

        if output_attentions:
            all_self_attentions = all_self_attentions + (layer_outputs[2],)

    if output_hidden_states:
        all_word_hidden_states = all_word_hidden_states + (word_hidden_states,)
        all_entity_hidden_states = all_entity_hidden_states + (entity_hidden_states,)
    if not return_dict:
        return tuple(
            v
            for v in [
                word_hidden_states,
                all_word_hidden_states,
                all_self_attentions,
                entity_hidden_states,
                all_entity_hidden_states,
            ]
            if v is not None
        )
    return {
        "last_hidden_state": word_hidden_states,
        "hidden_states": all_word_hidden_states,
        "attentions": all_self_attentions,
        "entity_last_hidden_state": entity_hidden_states,
        "entity_hidden_states": all_entity_hidden_states,
    }

mindnlp.transformers.models.luke.luke.LukeEntityEmbeddings

Bases: Module

LukeEntityEmbeddings

Source code in mindnlp/transformers/models/luke/luke.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
class LukeEntityEmbeddings(nn.Module):
    """
    LukeEntityEmbeddings
    """
    def __init__(self, config: LukeConfig):
        """
        Initializes the LukeEntityEmbeddings class.

        Args:
            self: The instance of the class.
            config (LukeConfig): An instance of LukeConfig containing the configuration parameters for the entity embeddings.
                It specifies the entity vocabulary size, entity embedding size, hidden size, maximum position embeddings,
                type vocabulary size, and layer normalization epsilon.
                It is used to configure the entity embeddings, position embeddings, token type embeddings,
                layer normalization, and dropout.

        Returns:
            None.

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

        self.entity_embeddings = nn.Embedding(config.entity_vocab_size, config.entity_emb_size, padding_idx=0)
        if config.entity_emb_size != config.hidden_size:
            self.entity_embedding_dense = nn.Linear(config.entity_emb_size, config.hidden_size, bias=False)

        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)

        self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def construct(
            self, entity_ids, position_ids, token_type_ids=None
    ):
        """
        This method constructs entity embeddings by combining entity, position, and token type embeddings.

        Args:
            self: The instance of the LukeEntityEmbeddings class.
            entity_ids (Tensor): A tensor containing the entity IDs for which embeddings need to be constructed.
            position_ids (Tensor): A tensor containing the position IDs representing the position of each entity.
            token_type_ids (Tensor, optional): A tensor containing the token type IDs. Defaults to None.
                If not provided, it is initialized as zeros_like(entity_ids).

        Returns:
            embeddings (Tensor): The combined embeddings of entities, positions,
                and token types after normalization and dropout.

        Raises:
            ValueError: If the dimensions of entity_embeddings and hidden_size do not match.
            TypeError: If entity_ids, position_ids, or token_type_ids are not of type Tensor.
            ValueError: If the position_ids contain values less than -1.
            RuntimeError: If any runtime error occurs during the computation process.
        """
        if token_type_ids is None:
            token_type_ids = ops.zeros_like(entity_ids)

        entity_embeddings = self.entity_embeddings(entity_ids)
        if self.config.entity_emb_size != self.config.hidden_size:
            entity_embeddings = self.entity_embedding_dense(entity_embeddings)

        position_embeddings = self.position_embeddings(ops.clamp(position_ids, min=0))
        position_embedding_mask = ops.cast(position_ids != -1, position_embeddings.dtype).unsqueeze(-1)
        position_embeddings = position_embeddings * position_embedding_mask
        position_embeddings = position_embeddings.sum(axis=-2)
        position_embeddings = position_embeddings / position_embedding_mask.sum(axis=-2).clamp(min=1e-7)

        token_type_embeddings = self.token_type_embeddings(token_type_ids)

        embeddings = entity_embeddings + position_embeddings + token_type_embeddings
        embeddings = self.layer_norm(embeddings)
        embeddings = self.dropout(embeddings)

        return embeddings

mindnlp.transformers.models.luke.luke.LukeEntityEmbeddings.__init__(config)

Initializes the LukeEntityEmbeddings class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An instance of LukeConfig containing the configuration parameters for the entity embeddings. It specifies the entity vocabulary size, entity embedding size, hidden size, maximum position embeddings, type vocabulary size, and layer normalization epsilon. It is used to configure the entity embeddings, position embeddings, token type embeddings, layer normalization, and dropout.

TYPE: LukeConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def __init__(self, config: LukeConfig):
    """
    Initializes the LukeEntityEmbeddings class.

    Args:
        self: The instance of the class.
        config (LukeConfig): An instance of LukeConfig containing the configuration parameters for the entity embeddings.
            It specifies the entity vocabulary size, entity embedding size, hidden size, maximum position embeddings,
            type vocabulary size, and layer normalization epsilon.
            It is used to configure the entity embeddings, position embeddings, token type embeddings,
            layer normalization, and dropout.

    Returns:
        None.

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

    self.entity_embeddings = nn.Embedding(config.entity_vocab_size, config.entity_emb_size, padding_idx=0)
    if config.entity_emb_size != config.hidden_size:
        self.entity_embedding_dense = nn.Linear(config.entity_emb_size, config.hidden_size, bias=False)

    self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
    self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)

    self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.luke.luke.LukeEntityEmbeddings.construct(entity_ids, position_ids, token_type_ids=None)

This method constructs entity embeddings by combining entity, position, and token type embeddings.

PARAMETER DESCRIPTION
self

The instance of the LukeEntityEmbeddings class.

entity_ids

A tensor containing the entity IDs for which embeddings need to be constructed.

TYPE: Tensor

position_ids

A tensor containing the position IDs representing the position of each entity.

TYPE: Tensor

token_type_ids

A tensor containing the token type IDs. Defaults to None. If not provided, it is initialized as zeros_like(entity_ids).

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
embeddings

The combined embeddings of entities, positions, and token types after normalization and dropout.

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If the dimensions of entity_embeddings and hidden_size do not match.

TypeError

If entity_ids, position_ids, or token_type_ids are not of type Tensor.

ValueError

If the position_ids contain values less than -1.

RuntimeError

If any runtime error occurs during the computation process.

Source code in mindnlp/transformers/models/luke/luke.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def construct(
        self, entity_ids, position_ids, token_type_ids=None
):
    """
    This method constructs entity embeddings by combining entity, position, and token type embeddings.

    Args:
        self: The instance of the LukeEntityEmbeddings class.
        entity_ids (Tensor): A tensor containing the entity IDs for which embeddings need to be constructed.
        position_ids (Tensor): A tensor containing the position IDs representing the position of each entity.
        token_type_ids (Tensor, optional): A tensor containing the token type IDs. Defaults to None.
            If not provided, it is initialized as zeros_like(entity_ids).

    Returns:
        embeddings (Tensor): The combined embeddings of entities, positions,
            and token types after normalization and dropout.

    Raises:
        ValueError: If the dimensions of entity_embeddings and hidden_size do not match.
        TypeError: If entity_ids, position_ids, or token_type_ids are not of type Tensor.
        ValueError: If the position_ids contain values less than -1.
        RuntimeError: If any runtime error occurs during the computation process.
    """
    if token_type_ids is None:
        token_type_ids = ops.zeros_like(entity_ids)

    entity_embeddings = self.entity_embeddings(entity_ids)
    if self.config.entity_emb_size != self.config.hidden_size:
        entity_embeddings = self.entity_embedding_dense(entity_embeddings)

    position_embeddings = self.position_embeddings(ops.clamp(position_ids, min=0))
    position_embedding_mask = ops.cast(position_ids != -1, position_embeddings.dtype).unsqueeze(-1)
    position_embeddings = position_embeddings * position_embedding_mask
    position_embeddings = position_embeddings.sum(axis=-2)
    position_embeddings = position_embeddings / position_embedding_mask.sum(axis=-2).clamp(min=1e-7)

    token_type_embeddings = self.token_type_embeddings(token_type_ids)

    embeddings = entity_embeddings + position_embeddings + token_type_embeddings
    embeddings = self.layer_norm(embeddings)
    embeddings = self.dropout(embeddings)

    return embeddings

mindnlp.transformers.models.luke.luke.LukeForEntityClassification

Bases: LukePreTrainedModel

LukeForEntityClassification

Source code in mindnlp/transformers/models/luke/luke.py
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
class LukeForEntityClassification(LukePreTrainedModel):
    """
    LukeForEntityClassification
    """
    def __init__(self, config):
        """
        Initializes a new instance of the LukeForEntityClassification class.

        Args:
            self: The instance of the class.
            config:
                A configuration object containing the settings for the LukeForEntityClassification model.

                - Type: object
                - Purpose: Specifies the configuration settings for the model.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of the expected type.
            ValueError: If the config parameter does not contain the required settings.
            RuntimeError: If there is an issue with the initialization process.
        """
        super().__init__(config)

        self.luke = LukeModel(config)

        self.num_labels = config.num_labels
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Constructs the LukeForEntityClassification model.

        Args:
            self (LukeForEntityClassification): The instance of the LukeForEntityClassification class.
            input_ids (Optional[Tensor]): The input tensor containing the indices of input sequence tokens in the vocabulary.
            attention_mask (Optional[Tensor]): The optional mask tensor, usually used to ignore padding tokens.
            token_type_ids (Optional[Tensor]): The optional tensor containing the type ids of input sequence tokens.
            position_ids (Optional[Tensor]): The optional tensor containing the positions ids of input sequence tokens.
            entity_ids (Optional[Tensor]): The optional tensor containing the indices of entity tokens in the vocabulary.
            entity_attention_mask (Optional[Tensor]): The optional mask tensor for entity tokens.
            entity_token_type_ids (Optional[Tensor]): The optional tensor containing the type ids of entity sequence tokens.
            entity_position_ids (Optional[Tensor]): The optional tensor containing the positions ids of entity sequence tokens.
            head_mask (Optional[Tensor]): The optional mask tensor for attention heads.
            inputs_embeds (Optional[Tensor]): The optional tensor containing the embeddings of input sequence tokens.
            labels (Optional[Tensor]): The optional tensor containing the labels of the entity classification task.
            output_attentions (Optional[bool]): Whether to return the attentions weights of the model.
            output_hidden_states (Optional[bool]): Whether to return the hidden states of the model.
            return_dict (Optional[bool]): Whether to return a dictionary instead of a tuple.

        Returns:
            Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]]: A tuple containing
                the loss, logits, hidden states, entity hidden states, and attentions weights (if available) respectively.

        Raises:
            None.

        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        feature_vector = outputs['entity_last_hidden_state'][:, 0, :]
        feature_vector = self.dropout(feature_vector)
        logits = self.classifier(feature_vector)

        loss = None
        if labels is not None:
            if labels.ndim == 1:
                loss = ops.cross_entropy(logits, labels)
            else:
                loss = ops.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits), Tensor(),
                                                            Tensor())
        return tuple(
            v
            for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForEntityClassification.__init__(config)

Initializes a new instance of the LukeForEntityClassification class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

A configuration object containing the settings for the LukeForEntityClassification model.

  • Type: object
  • Purpose: Specifies the configuration settings for the model.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of the expected type.

ValueError

If the config parameter does not contain the required settings.

RuntimeError

If there is an issue with the initialization process.

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

    Args:
        self: The instance of the class.
        config:
            A configuration object containing the settings for the LukeForEntityClassification model.

            - Type: object
            - Purpose: Specifies the configuration settings for the model.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of the expected type.
        ValueError: If the config parameter does not contain the required settings.
        RuntimeError: If there is an issue with the initialization process.
    """
    super().__init__(config)

    self.luke = LukeModel(config)

    self.num_labels = config.num_labels
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

mindnlp.transformers.models.luke.luke.LukeForEntityClassification.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the LukeForEntityClassification model.

PARAMETER DESCRIPTION
self

The instance of the LukeForEntityClassification class.

TYPE: LukeForEntityClassification

input_ids

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

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The optional mask tensor, usually used to ignore padding tokens.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The optional tensor containing the type ids of input sequence tokens.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The optional tensor containing the positions ids of input sequence tokens.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

The optional tensor containing the indices of entity tokens in the vocabulary.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

The optional mask tensor for entity tokens.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

The optional tensor containing the type ids of entity sequence tokens.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

The optional tensor containing the positions ids of entity sequence tokens.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The optional mask tensor for attention heads.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The optional tensor containing the embeddings of input sequence tokens.

TYPE: Optional[Tensor] DEFAULT: None

labels

The optional tensor containing the labels of the entity classification task.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to return the attentions weights of the model.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to return the hidden states of the model.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary instead of a tuple.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION

Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]]: A tuple containing the loss, logits, hidden states, entity hidden states, and attentions weights (if available) respectively.

Source code in mindnlp/transformers/models/luke/luke.py
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Constructs the LukeForEntityClassification model.

    Args:
        self (LukeForEntityClassification): The instance of the LukeForEntityClassification class.
        input_ids (Optional[Tensor]): The input tensor containing the indices of input sequence tokens in the vocabulary.
        attention_mask (Optional[Tensor]): The optional mask tensor, usually used to ignore padding tokens.
        token_type_ids (Optional[Tensor]): The optional tensor containing the type ids of input sequence tokens.
        position_ids (Optional[Tensor]): The optional tensor containing the positions ids of input sequence tokens.
        entity_ids (Optional[Tensor]): The optional tensor containing the indices of entity tokens in the vocabulary.
        entity_attention_mask (Optional[Tensor]): The optional mask tensor for entity tokens.
        entity_token_type_ids (Optional[Tensor]): The optional tensor containing the type ids of entity sequence tokens.
        entity_position_ids (Optional[Tensor]): The optional tensor containing the positions ids of entity sequence tokens.
        head_mask (Optional[Tensor]): The optional mask tensor for attention heads.
        inputs_embeds (Optional[Tensor]): The optional tensor containing the embeddings of input sequence tokens.
        labels (Optional[Tensor]): The optional tensor containing the labels of the entity classification task.
        output_attentions (Optional[bool]): Whether to return the attentions weights of the model.
        output_hidden_states (Optional[bool]): Whether to return the hidden states of the model.
        return_dict (Optional[bool]): Whether to return a dictionary instead of a tuple.

    Returns:
        Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]]: A tuple containing
            the loss, logits, hidden states, entity hidden states, and attentions weights (if available) respectively.

    Raises:
        None.

    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    feature_vector = outputs['entity_last_hidden_state'][:, 0, :]
    feature_vector = self.dropout(feature_vector)
    logits = self.classifier(feature_vector)

    loss = None
    if labels is not None:
        if labels.ndim == 1:
            loss = ops.cross_entropy(logits, labels)
        else:
            loss = ops.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits), Tensor(),
                                                        Tensor())
    return tuple(
        v
        for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForEntityPairClassification

Bases: LukePreTrainedModel

LukeForEntityPairClassification

Source code in mindnlp/transformers/models/luke/luke.py
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
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
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
class LukeForEntityPairClassification(LukePreTrainedModel):
    """
    LukeForEntityPairClassification
    """
    def __init__(self, config):
        """
        Initializes a new instance of LukeForEntityPairClassification.

        Args:
            self: The object instance itself.
            config:
                The configuration object containing various parameters.

                - Type: object
                - Purpose: Contains the configuration settings for the Luke model.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None.

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

        self.luke = LukeModel(config)

        self.num_labels = config.num_labels
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size * 2, config.num_labels, bias=False)

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        This method 'construct' in the class 'LukeForEntityPairClassification' is responsible for constructing
        the model and performing entity pair classification.

        Args:
            self: The instance of the class.
            input_ids (Optional[Tensor]): Input tensor containing token indices. Default is None.
            attention_mask (Optional[Tensor]): Mask tensor for the input, indicating which tokens should be attended to.
                Default is None.
            token_type_ids (Optional[Tensor]): Tensor specifying the type of token (e.g., segment A or B). Default is None.
            position_ids (Optional[Tensor]): Tensor specifying the position of tokens. Default is None.
            entity_ids (Optional[Tensor]): Tensor containing entity indices.
            entity_attention_mask (Optional[Tensor]): Mask tensor for entity inputs. Default is None.
            entity_token_type_ids (Optional[Tensor]): Tensor specifying the type of entity token. Default is None.
            entity_position_ids (Optional[Tensor]): Tensor specifying the position of entity tokens. Default is None.
            head_mask (Optional[Tensor]): Mask tensor for attention heads. Default is None.
            inputs_embeds (Optional[Tensor]): Additional embeddings to be added to the model input embeddings.
                Default is None.
            labels (Optional[Tensor]): Tensor containing the classification labels. 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 as output. Default is None.

        Returns:
            Tuple:
                A tuple containing elements that are not None among loss (if labels provided), logits, hidden states,
                entity hidden states, and attentions. Returns None if all elements are None.

        Raises:
            ValueError: If labels are provided but have an incorrect shape for cross-entropy computation.
            TypeError: If the input types are not as expected by the method.
            RuntimeError: If there are runtime issues during the execution of the method.
        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        feature_vector = ops.cat(
            [outputs['entity_last_hidden_state'][:, 0, :], outputs['entity_last_hidden_state'][:, 1, :]], axis=1
        )
        feature_vector = self.dropout(feature_vector)
        logits = self.classifier(feature_vector)

        loss = None
        if labels is not None:
            if labels.ndim == 1:
                loss = ops.cross_entropy(logits, labels)
            else:
                loss = ops.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits), Tensor(),
                                                            Tensor())
        return tuple(
            v
            for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForEntityPairClassification.__init__(config)

Initializes a new instance of LukeForEntityPairClassification.

PARAMETER DESCRIPTION
self

The object instance itself.

config

The configuration object containing various parameters.

  • Type: object
  • Purpose: Contains the configuration settings for the Luke model.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None.

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

    Args:
        self: The object instance itself.
        config:
            The configuration object containing various parameters.

            - Type: object
            - Purpose: Contains the configuration settings for the Luke model.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None.

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

    self.luke = LukeModel(config)

    self.num_labels = config.num_labels
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size * 2, config.num_labels, bias=False)

mindnlp.transformers.models.luke.luke.LukeForEntityPairClassification.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

This method 'construct' in the class 'LukeForEntityPairClassification' is responsible for constructing the model and performing entity pair classification.

PARAMETER DESCRIPTION
self

The instance of the class.

input_ids

Input tensor containing token indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

Mask tensor for the input, indicating which tokens should be attended to. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

Tensor specifying the type of token (e.g., segment A or B). Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

Tensor specifying the position of tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

Tensor containing entity indices.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

Mask tensor for entity inputs. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

Tensor specifying the type of entity token. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

Tensor specifying the position of entity tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

Mask tensor for attention heads. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

Additional embeddings to be added to the model input embeddings. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

labels

Tensor containing the classification labels. 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 as output. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Tuple

A tuple containing elements that are not None among loss (if labels provided), logits, hidden states, entity hidden states, and attentions. Returns None if all elements are None.

RAISES DESCRIPTION
ValueError

If labels are provided but have an incorrect shape for cross-entropy computation.

TypeError

If the input types are not as expected by the method.

RuntimeError

If there are runtime issues during the execution of the method.

Source code in mindnlp/transformers/models/luke/luke.py
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
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
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    This method 'construct' in the class 'LukeForEntityPairClassification' is responsible for constructing
    the model and performing entity pair classification.

    Args:
        self: The instance of the class.
        input_ids (Optional[Tensor]): Input tensor containing token indices. Default is None.
        attention_mask (Optional[Tensor]): Mask tensor for the input, indicating which tokens should be attended to.
            Default is None.
        token_type_ids (Optional[Tensor]): Tensor specifying the type of token (e.g., segment A or B). Default is None.
        position_ids (Optional[Tensor]): Tensor specifying the position of tokens. Default is None.
        entity_ids (Optional[Tensor]): Tensor containing entity indices.
        entity_attention_mask (Optional[Tensor]): Mask tensor for entity inputs. Default is None.
        entity_token_type_ids (Optional[Tensor]): Tensor specifying the type of entity token. Default is None.
        entity_position_ids (Optional[Tensor]): Tensor specifying the position of entity tokens. Default is None.
        head_mask (Optional[Tensor]): Mask tensor for attention heads. Default is None.
        inputs_embeds (Optional[Tensor]): Additional embeddings to be added to the model input embeddings.
            Default is None.
        labels (Optional[Tensor]): Tensor containing the classification labels. 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 as output. Default is None.

    Returns:
        Tuple:
            A tuple containing elements that are not None among loss (if labels provided), logits, hidden states,
            entity hidden states, and attentions. Returns None if all elements are None.

    Raises:
        ValueError: If labels are provided but have an incorrect shape for cross-entropy computation.
        TypeError: If the input types are not as expected by the method.
        RuntimeError: If there are runtime issues during the execution of the method.
    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    feature_vector = ops.cat(
        [outputs['entity_last_hidden_state'][:, 0, :], outputs['entity_last_hidden_state'][:, 1, :]], axis=1
    )
    feature_vector = self.dropout(feature_vector)
    logits = self.classifier(feature_vector)

    loss = None
    if labels is not None:
        if labels.ndim == 1:
            loss = ops.cross_entropy(logits, labels)
        else:
            loss = ops.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits), Tensor(),
                                                        Tensor())
    return tuple(
        v
        for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForEntitySpanClassification

Bases: LukePreTrainedModel

LukeForEntitySpanClassification

Source code in mindnlp/transformers/models/luke/luke.py
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
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
class LukeForEntitySpanClassification(LukePreTrainedModel):
    """
    LukeForEntitySpanClassification
    """
    def __init__(self, config):
        """
        Initializes an instance of the LukeForEntitySpanClassification class.

        Args:
            self: The instance of the class.
            config: The configuration object containing various settings and parameters for the model.
                It should be an instance of the configuration class specific to LukeForEntitySpanClassification.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of the expected type.
            ValueError: If the configuration provided is invalid or missing required parameters.
            RuntimeError: If there is an issue with the initialization process.
        """
        super().__init__(config)

        self.luke = LukeModel(config)

        self.num_labels = config.num_labels
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size * 3, config.num_labels)

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask=None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            entity_start_positions: Optional[Tensor] = None,
            entity_end_positions: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Constructs the forward pass of LukeForEntitySpanClassification model.

        Args:
            self (LukeForEntitySpanClassification): The instance of the LukeForEntitySpanClassification class.
            input_ids (Optional[Tensor]): The input tensor of shape (batch_size, sequence_length) containing the
                input tokens indices.
            attention_mask (Tensor): The attention mask tensor of shape (batch_size, sequence_length) containing
                the attention mask values.
            token_type_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the token type ids.
            position_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the position ids.
            entity_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing the entity ids.
            entity_attention_mask (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the entity attention mask values.
            entity_token_type_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the entity token type ids.
            entity_position_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the entity position ids.
            entity_start_positions (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the start positions of the entities.
            entity_end_positions (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
                the end positions of the entities.
            head_mask (Optional[Tensor]): The tensor of shape (batch_size, num_heads) containing the head mask values.
            inputs_embeds (Optional[Tensor]): The tensor of shape (batch_size, sequence_length, hidden_size) containing
                the input embeddings.
            labels (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing the labels.
            output_attentions (Optional[bool]): Whether to output the attentions.
            output_hidden_states (Optional[bool]): Whether to output the hidden states.
            return_dict (Optional[bool]): Whether to return a dictionary instead of a tuple.

        Returns:
            tuple: Tuple of values containing the loss (Tensor), logits (Tensor), hidden states (Tensor),
                entity hidden states (Tensor), and attentions (Tensor) if not None.

        Raises:
            None.
        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        hidden_size = outputs['last_hidden_state'].shape[-1]
        entity_start_positions = ops.BroadcastTo(shape=(-1, -1, hidden_size))(entity_start_positions.unsqueeze(-1))
        start_states = ops.gather_elements(outputs['last_hidden_state'], -2, entity_start_positions)

        entity_end_positions = ops.BroadcastTo(shape=(-1, -1, hidden_size))(entity_end_positions.unsqueeze(-1))
        end_states = ops.gather_elements(outputs['last_hidden_state'], -2, entity_end_positions)

        feature_vector = ops.cat([start_states, end_states, outputs['entity_last_hidden_state']], axis=2)
        feature_vector = self.dropout(feature_vector)
        logits = self.classifier(feature_vector)

        loss = None
        if labels is not None:
            if labels.ndim == 2:
                loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
            else:
                loss = ops.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits),
                                                            weight=None, pos_weight=None)

        return tuple(
            v
            for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForEntitySpanClassification.__init__(config)

Initializes an instance of the LukeForEntitySpanClassification class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

The configuration object containing various settings and parameters for the model. It should be an instance of the configuration class specific to LukeForEntitySpanClassification.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of the expected type.

ValueError

If the configuration provided is invalid or missing required parameters.

RuntimeError

If there is an issue with the initialization process.

Source code in mindnlp/transformers/models/luke/luke.py
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def __init__(self, config):
    """
    Initializes an instance of the LukeForEntitySpanClassification class.

    Args:
        self: The instance of the class.
        config: The configuration object containing various settings and parameters for the model.
            It should be an instance of the configuration class specific to LukeForEntitySpanClassification.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of the expected type.
        ValueError: If the configuration provided is invalid or missing required parameters.
        RuntimeError: If there is an issue with the initialization process.
    """
    super().__init__(config)

    self.luke = LukeModel(config)

    self.num_labels = config.num_labels
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size * 3, config.num_labels)

mindnlp.transformers.models.luke.luke.LukeForEntitySpanClassification.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, entity_start_positions=None, entity_end_positions=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the forward pass of LukeForEntitySpanClassification model.

PARAMETER DESCRIPTION
self

The instance of the LukeForEntitySpanClassification class.

TYPE: LukeForEntitySpanClassification

input_ids

The input tensor of shape (batch_size, sequence_length) containing the input tokens indices.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask tensor of shape (batch_size, sequence_length) containing the attention mask values.

TYPE: Tensor DEFAULT: None

token_type_ids

The tensor of shape (batch_size, sequence_length) containing the token type ids.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The tensor of shape (batch_size, sequence_length) containing the position ids.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

The tensor of shape (batch_size, sequence_length) containing the entity ids.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

The tensor of shape (batch_size, sequence_length) containing the entity attention mask values.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

The tensor of shape (batch_size, sequence_length) containing the entity token type ids.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

The tensor of shape (batch_size, sequence_length) containing the entity position ids.

TYPE: Optional[Tensor] DEFAULT: None

entity_start_positions

The tensor of shape (batch_size, sequence_length) containing the start positions of the entities.

TYPE: Optional[Tensor] DEFAULT: None

entity_end_positions

The tensor of shape (batch_size, sequence_length) containing the end positions of the entities.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The tensor of shape (batch_size, num_heads) containing the head mask values.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The tensor of shape (batch_size, sequence_length, hidden_size) containing the input embeddings.

TYPE: Optional[Tensor] DEFAULT: None

labels

The tensor of shape (batch_size, sequence_length) containing the labels.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output the attentions.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output the hidden states.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary instead of a tuple.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
tuple

Tuple of values containing the loss (Tensor), logits (Tensor), hidden states (Tensor), entity hidden states (Tensor), and attentions (Tensor) if not None.

Source code in mindnlp/transformers/models/luke/luke.py
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
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask=None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        entity_start_positions: Optional[Tensor] = None,
        entity_end_positions: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Constructs the forward pass of LukeForEntitySpanClassification model.

    Args:
        self (LukeForEntitySpanClassification): The instance of the LukeForEntitySpanClassification class.
        input_ids (Optional[Tensor]): The input tensor of shape (batch_size, sequence_length) containing the
            input tokens indices.
        attention_mask (Tensor): The attention mask tensor of shape (batch_size, sequence_length) containing
            the attention mask values.
        token_type_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the token type ids.
        position_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the position ids.
        entity_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing the entity ids.
        entity_attention_mask (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the entity attention mask values.
        entity_token_type_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the entity token type ids.
        entity_position_ids (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the entity position ids.
        entity_start_positions (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the start positions of the entities.
        entity_end_positions (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing
            the end positions of the entities.
        head_mask (Optional[Tensor]): The tensor of shape (batch_size, num_heads) containing the head mask values.
        inputs_embeds (Optional[Tensor]): The tensor of shape (batch_size, sequence_length, hidden_size) containing
            the input embeddings.
        labels (Optional[Tensor]): The tensor of shape (batch_size, sequence_length) containing the labels.
        output_attentions (Optional[bool]): Whether to output the attentions.
        output_hidden_states (Optional[bool]): Whether to output the hidden states.
        return_dict (Optional[bool]): Whether to return a dictionary instead of a tuple.

    Returns:
        tuple: Tuple of values containing the loss (Tensor), logits (Tensor), hidden states (Tensor),
            entity hidden states (Tensor), and attentions (Tensor) if not None.

    Raises:
        None.
    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    hidden_size = outputs['last_hidden_state'].shape[-1]
    entity_start_positions = ops.BroadcastTo(shape=(-1, -1, hidden_size))(entity_start_positions.unsqueeze(-1))
    start_states = ops.gather_elements(outputs['last_hidden_state'], -2, entity_start_positions)

    entity_end_positions = ops.BroadcastTo(shape=(-1, -1, hidden_size))(entity_end_positions.unsqueeze(-1))
    end_states = ops.gather_elements(outputs['last_hidden_state'], -2, entity_end_positions)

    feature_vector = ops.cat([start_states, end_states, outputs['entity_last_hidden_state']], axis=2)
    feature_vector = self.dropout(feature_vector)
    logits = self.classifier(feature_vector)

    loss = None
    if labels is not None:
        if labels.ndim == 2:
            loss = ops.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
        else:
            loss = ops.binary_cross_entropy_with_logits(logits.view(-1), labels.view(-1).type_as(logits),
                                                        weight=None, pos_weight=None)

    return tuple(
        v
        for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForMaskedLM

Bases: LukePreTrainedModel

LukeForMaskedLM

Source code in mindnlp/transformers/models/luke/luke.py
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
class LukeForMaskedLM(LukePreTrainedModel):
    """
    LukeForMaskedLM
    """
    _keys_to_ignore_on_save = [
        r"lm_head.decoder.weight",
        r"lm_head.decoder.bias",
        r"entity_predictions.decoder.weight",
    ]
    _keys_to_ignore_on_load_missing = [
        r"position_ids",
        r"lm_head.decoder.weight",
        r"lm_head.decoder.bias",
        r"entity_predictions.decoder.weight",
    ]

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

        Args:
            self: The current instance of the 'LukeForMaskedLM' class.
            config: An object of type 'ConfigBase' containing the configuration parameters for the model.

        Returns:
            None.

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

        self.luke = LukeModel(config)

        self.lm_head = LukeLMHead(config)
        self.entity_predictions = EntityPredictionHead(config)

        self.loss_fn = nn.CrossEntropyLoss(ignore_index=-1)

    def tie_weights(self):
        """tie_weight"""
        super().tie_weights()
        self._tie_or_clone_weights(self.entity_predictions.decoder, self.luke.entity_embeddings.entity_embeddings)

    def get_output_embeddings(self):
        """get_output_embeddings"""
        return self.lm_head.decoder

    def set_output_embeddings(self, new_embeddings):
        """set_output_embeddings"""
        self.lm_head.decoder = new_embeddings

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            entity_labels: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Constructs the outputs for the LukeForMaskedLM model.

        Args:
            self (LukeForMaskedLM): The instance of the LukeForMaskedLM class.
            input_ids (Optional[Tensor]): The input token IDs. Default: None.
            attention_mask (Optional[Tensor]): The attention mask. Default: None.
            token_type_ids (Optional[Tensor]): The token type IDs. Default: None.
            position_ids (Optional[Tensor]): The position IDs. Default: None.
            entity_ids (Optional[Tensor]): The entity IDs. Default: None.
            entity_attention_mask (Optional[Tensor]): The entity attention mask. Default: None.
            entity_token_type_ids (Optional[Tensor]): The entity token type IDs. Default: None.
            entity_position_ids (Optional[Tensor]): The entity position IDs. Default: None.
            labels (Optional[Tensor]): The labels for masked language modeling. Default: None.
            entity_labels (Optional[Tensor]): The labels for entity prediction. Default: None.
            head_mask (Optional[Tensor]): The head mask. Default: None.
            inputs_embeds (Optional[Tensor]): The input embeddings. Default: None.
            output_attentions (Optional[bool]): Whether to output attentions. Default: None.
            output_hidden_states (Optional[bool]): Whether to output hidden states. Default: None.
            return_dict (Optional[bool]): Whether to return a dictionary output. Default: None.

        Returns:
            Tuple of (loss, mlm_loss, mep_loss, logits, entity_logits, hidden_states, entity_hidden_states, attentions):

                - loss (Tensor or None): The total loss. None if no loss is calculated.
                - mlm_loss (Tensor or None): The loss for masked language modeling.
                None if no loss is calculated.
                - mep_loss (Tensor or None): The loss for entity prediction. None if no loss is calculated.
                - logits (Tensor or None): The logits for masked language modeling.
                - entity_logits (Tensor or None): The logits for entity prediction.
                - hidden_states (Tuple[Tensor] or None): The hidden states of the model. None if not returned.
                - entity_hidden_states (Tuple[Tensor] or None): The hidden states for entity prediction.
                None if not returned.
                - attentions (Tuple[Tensor] or None): The attentions of the model. None if not returned.

        Raises:
            None.
        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        loss = None
        mlm_loss = None
        logits = self.lm_head(outputs['last_hidden_state'])
        if labels is not None:
            mlm_loss = self.loss_fn(logits.view(-1, self.config.vocab_size), labels.view(-1))
            if loss is None:
                loss = mlm_loss

        mep_loss = None
        entity_logits = None
        if outputs['entity_last_hidden_state'] is not None:
            entity_logits = self.entity_predictions(outputs['entity_last_hidden_state'])
            if entity_labels is not None:
                mep_loss = self.loss_fn(entity_logits.view(-1, self.config.entity_vocab_size), entity_labels.view(-1))
                if loss is None:
                    loss = mep_loss
                else:
                    loss = loss + mep_loss
        return tuple(
            v
            for v in [
                loss,
                mlm_loss,
                mep_loss,
                logits,
                entity_logits,
                outputs['hidden_states'],
                outputs['entity_hidden_states'],
                outputs['attentions'],
            ]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForMaskedLM.__init__(config)

Initializes an instance of the 'LukeForMaskedLM' class.

PARAMETER DESCRIPTION
self

The current instance of the 'LukeForMaskedLM' class.

config

An object of type 'ConfigBase' containing the configuration parameters for the model.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
def __init__(self, config):
    """
    Initializes an instance of the 'LukeForMaskedLM' class.

    Args:
        self: The current instance of the 'LukeForMaskedLM' class.
        config: An object of type 'ConfigBase' containing the configuration parameters for the model.

    Returns:
        None.

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

    self.luke = LukeModel(config)

    self.lm_head = LukeLMHead(config)
    self.entity_predictions = EntityPredictionHead(config)

    self.loss_fn = nn.CrossEntropyLoss(ignore_index=-1)

mindnlp.transformers.models.luke.luke.LukeForMaskedLM.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, labels=None, entity_labels=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the outputs for the LukeForMaskedLM model.

PARAMETER DESCRIPTION
self

The instance of the LukeForMaskedLM class.

TYPE: LukeForMaskedLM

input_ids

The input token IDs. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The token type IDs. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The position IDs. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

The entity IDs. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

The entity attention mask. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

The entity token type IDs. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

The entity position IDs. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

labels

The labels for masked language modeling. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

entity_labels

The labels for entity prediction. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The head mask. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The input embeddings. Default: None.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output attentions. Default: None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output hidden states. Default: None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary output. Default: None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION

Tuple of (loss, mlm_loss, mep_loss, logits, entity_logits, hidden_states, entity_hidden_states, attentions):

  • loss (Tensor or None): The total loss. None if no loss is calculated.
  • mlm_loss (Tensor or None): The loss for masked language modeling. None if no loss is calculated.
  • mep_loss (Tensor or None): The loss for entity prediction. None if no loss is calculated.
  • logits (Tensor or None): The logits for masked language modeling.
  • entity_logits (Tensor or None): The logits for entity prediction.
  • hidden_states (Tuple[Tensor] or None): The hidden states of the model. None if not returned.
  • entity_hidden_states (Tuple[Tensor] or None): The hidden states for entity prediction. None if not returned.
  • attentions (Tuple[Tensor] or None): The attentions of the model. None if not returned.
Source code in mindnlp/transformers/models/luke/luke.py
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        entity_labels: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Constructs the outputs for the LukeForMaskedLM model.

    Args:
        self (LukeForMaskedLM): The instance of the LukeForMaskedLM class.
        input_ids (Optional[Tensor]): The input token IDs. Default: None.
        attention_mask (Optional[Tensor]): The attention mask. Default: None.
        token_type_ids (Optional[Tensor]): The token type IDs. Default: None.
        position_ids (Optional[Tensor]): The position IDs. Default: None.
        entity_ids (Optional[Tensor]): The entity IDs. Default: None.
        entity_attention_mask (Optional[Tensor]): The entity attention mask. Default: None.
        entity_token_type_ids (Optional[Tensor]): The entity token type IDs. Default: None.
        entity_position_ids (Optional[Tensor]): The entity position IDs. Default: None.
        labels (Optional[Tensor]): The labels for masked language modeling. Default: None.
        entity_labels (Optional[Tensor]): The labels for entity prediction. Default: None.
        head_mask (Optional[Tensor]): The head mask. Default: None.
        inputs_embeds (Optional[Tensor]): The input embeddings. Default: None.
        output_attentions (Optional[bool]): Whether to output attentions. Default: None.
        output_hidden_states (Optional[bool]): Whether to output hidden states. Default: None.
        return_dict (Optional[bool]): Whether to return a dictionary output. Default: None.

    Returns:
        Tuple of (loss, mlm_loss, mep_loss, logits, entity_logits, hidden_states, entity_hidden_states, attentions):

            - loss (Tensor or None): The total loss. None if no loss is calculated.
            - mlm_loss (Tensor or None): The loss for masked language modeling.
            None if no loss is calculated.
            - mep_loss (Tensor or None): The loss for entity prediction. None if no loss is calculated.
            - logits (Tensor or None): The logits for masked language modeling.
            - entity_logits (Tensor or None): The logits for entity prediction.
            - hidden_states (Tuple[Tensor] or None): The hidden states of the model. None if not returned.
            - entity_hidden_states (Tuple[Tensor] or None): The hidden states for entity prediction.
            None if not returned.
            - attentions (Tuple[Tensor] or None): The attentions of the model. None if not returned.

    Raises:
        None.
    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    loss = None
    mlm_loss = None
    logits = self.lm_head(outputs['last_hidden_state'])
    if labels is not None:
        mlm_loss = self.loss_fn(logits.view(-1, self.config.vocab_size), labels.view(-1))
        if loss is None:
            loss = mlm_loss

    mep_loss = None
    entity_logits = None
    if outputs['entity_last_hidden_state'] is not None:
        entity_logits = self.entity_predictions(outputs['entity_last_hidden_state'])
        if entity_labels is not None:
            mep_loss = self.loss_fn(entity_logits.view(-1, self.config.entity_vocab_size), entity_labels.view(-1))
            if loss is None:
                loss = mep_loss
            else:
                loss = loss + mep_loss
    return tuple(
        v
        for v in [
            loss,
            mlm_loss,
            mep_loss,
            logits,
            entity_logits,
            outputs['hidden_states'],
            outputs['entity_hidden_states'],
            outputs['attentions'],
        ]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForMaskedLM.get_output_embeddings()

get_output_embeddings

Source code in mindnlp/transformers/models/luke/luke.py
1518
1519
1520
def get_output_embeddings(self):
    """get_output_embeddings"""
    return self.lm_head.decoder

mindnlp.transformers.models.luke.luke.LukeForMaskedLM.set_output_embeddings(new_embeddings)

set_output_embeddings

Source code in mindnlp/transformers/models/luke/luke.py
1522
1523
1524
def set_output_embeddings(self, new_embeddings):
    """set_output_embeddings"""
    self.lm_head.decoder = new_embeddings

mindnlp.transformers.models.luke.luke.LukeForMaskedLM.tie_weights()

tie_weight

Source code in mindnlp/transformers/models/luke/luke.py
1513
1514
1515
1516
def tie_weights(self):
    """tie_weight"""
    super().tie_weights()
    self._tie_or_clone_weights(self.entity_predictions.decoder, self.luke.entity_embeddings.entity_embeddings)

mindnlp.transformers.models.luke.luke.LukeForMultipleChoice

Bases: LukePreTrainedModel

LukeForMultipleChoice

Source code in mindnlp/transformers/models/luke/luke.py
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
class LukeForMultipleChoice(LukePreTrainedModel):
    """
    LukeForMultipleChoice
    """
    def __init__(self, config):
        """
        Initializes an instance of the LukeForMultipleChoice class.

        Args:
            self: The instance of the class.
            config: An object containing the configuration settings for the model (type: <class 'config'>).

        Returns:
            None.

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

        self.luke = LukeModel(config)
        self.dropout = nn.Dropout(p=
                                  config.classifier_dropout
                                  if config.classifier_dropout is not None
                                  else config.hidden_dropout_prob
                                  )
        self.classifier = nn.Linear(config.hidden_size, 1)

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Constructs the LukeForMultipleChoice model.

        Args:
            self (LukeForMultipleChoice): The instance of the LukeForMultipleChoice class.
            input_ids (Optional[Tensor]): The input sequence token IDs of shape [batch_size, num_choices, sequence_length].
                (default: None)
            attention_mask (Optional[Tensor]): The attention mask tensor of shape [batch_size, num_choices, sequence_length].
                (default: None)
            token_type_ids (Optional[Tensor]): The token type IDs tensor of shape [batch_size, num_choices, sequence_length].
                (default: None)
            position_ids (Optional[Tensor]): The position IDs tensor of shape [batch_size, num_choices, sequence_length].
                (default: None)
            entity_ids (Optional[Tensor]): The entity token IDs tensor of shape [batch_size, num_choices, entity_length].
                (default: None)
            entity_attention_mask (Optional[Tensor]): The entity attention mask tensor of
                shape [batch_size, num_choices, entity_length]. (default: None)
            entity_token_type_ids (Optional[Tensor]): The entity token type IDs tensor of
                shape [batch_size, num_choices, entity_length]. (default: None)
            entity_position_ids (Optional[Tensor]): The entity position IDs tensor of
                shape [batch_size, num_choices, entity_length]. (default: None)
            head_mask (Optional[Tensor]): The head mask tensor of shape [num_hidden_layers, num_attention_heads].
                (default: None)
            inputs_embeds (Optional[Tensor]): The input embeddings tensor of shape
                [batch_size, num_choices, sequence_length, hidden_size]. (default: None)
            labels (Optional[Tensor]): The labels tensor of shape [batch_size]. (default: None)
            output_attentions (Optional[bool]): Whether to output attentions. (default: None)
            output_hidden_states (Optional[bool]): Whether to output hidden states. (default: None)
            return_dict (Optional[bool]): Whether to return a dictionary instead of a tuple of outputs. (default: None)

        Returns:
            tuple:
                Tuple of (loss, reshaped_logits, hidden_states, entity_hidden_states, attentions):

                - loss (Optional[Tensor]): The training loss tensor. Returns None if labels are not provided.
                - reshaped_logits (Tensor): The reshaped logits tensor of shape [batch_size * num_choices, num_choices].
                - hidden_states (Optional[List[Tensor]]): The hidden states of the model at the output of each layer.
                Returns None if output_hidden_states is set to False.
                - entity_hidden_states (Optional[List[Tensor]]): The hidden states of the model for the entity
                embeddings at the output of each layer. Returns None if output_hidden_states is set to False or
                entity embeddings are not provided.
                - attentions (Optional[List[Tensor]]): The attention weights of the model at the output of each layer.
                Returns None if output_attentions is set to False.

        Raises:
            None.
        """
        return_dict = True
        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
        )

        entity_ids = entity_ids.view(-1, entity_ids.shape[-1]) if entity_ids is not None else None
        entity_attention_mask = (
            entity_attention_mask.view(-1, entity_attention_mask.shape[-1])
            if entity_attention_mask is not None
            else None
        )
        entity_token_type_ids = (
            entity_token_type_ids.view(-1, entity_token_type_ids.shape[-1])
            if entity_token_type_ids is not None
            else None
        )
        entity_position_ids = (
            entity_position_ids.view(-1, entity_position_ids.shape[-2], entity_position_ids.shape[-1])
            if entity_position_ids is not None
            else None
        )

        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        pooled_output = outputs['pooler_output']

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

        loss = None
        if labels is not None:
            loss_fct = nn.CrossEntropyLoss()
            loss = loss_fct(reshaped_logits, labels)

        return tuple(
            v
            for v in [
                loss,
                reshaped_logits,
                outputs['hidden_states'],
                outputs['entity_hidden_states'],
                outputs['attentions'],
            ]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForMultipleChoice.__init__(config)

Initializes an instance of the LukeForMultipleChoice class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration settings for the model (type: ).

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
def __init__(self, config):
    """
    Initializes an instance of the LukeForMultipleChoice class.

    Args:
        self: The instance of the class.
        config: An object containing the configuration settings for the model (type: <class 'config'>).

    Returns:
        None.

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

    self.luke = LukeModel(config)
    self.dropout = nn.Dropout(p=
                              config.classifier_dropout
                              if config.classifier_dropout is not None
                              else config.hidden_dropout_prob
                              )
    self.classifier = nn.Linear(config.hidden_size, 1)

mindnlp.transformers.models.luke.luke.LukeForMultipleChoice.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the LukeForMultipleChoice model.

PARAMETER DESCRIPTION
self

The instance of the LukeForMultipleChoice class.

TYPE: LukeForMultipleChoice

input_ids

The input sequence token IDs of shape [batch_size, num_choices, sequence_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask tensor of shape [batch_size, num_choices, sequence_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The token type IDs tensor of shape [batch_size, num_choices, sequence_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The position IDs tensor of shape [batch_size, num_choices, sequence_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

The entity token IDs tensor of shape [batch_size, num_choices, entity_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

The entity attention mask tensor of shape [batch_size, num_choices, entity_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

The entity token type IDs tensor of shape [batch_size, num_choices, entity_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

The entity position IDs tensor of shape [batch_size, num_choices, entity_length]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The head mask tensor of shape [num_hidden_layers, num_attention_heads]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The input embeddings tensor of shape [batch_size, num_choices, sequence_length, hidden_size]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

labels

The labels tensor of shape [batch_size]. (default: None)

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output attentions. (default: None)

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output hidden states. (default: None)

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary instead of a tuple of outputs. (default: None)

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
tuple

Tuple of (loss, reshaped_logits, hidden_states, entity_hidden_states, attentions):

  • loss (Optional[Tensor]): The training loss tensor. Returns None if labels are not provided.
  • reshaped_logits (Tensor): The reshaped logits tensor of shape [batch_size * num_choices, num_choices].
  • hidden_states (Optional[List[Tensor]]): The hidden states of the model at the output of each layer. Returns None if output_hidden_states is set to False.
  • entity_hidden_states (Optional[List[Tensor]]): The hidden states of the model for the entity embeddings at the output of each layer. Returns None if output_hidden_states is set to False or entity embeddings are not provided.
  • attentions (Optional[List[Tensor]]): The attention weights of the model at the output of each layer. Returns None if output_attentions is set to False.
Source code in mindnlp/transformers/models/luke/luke.py
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Constructs the LukeForMultipleChoice model.

    Args:
        self (LukeForMultipleChoice): The instance of the LukeForMultipleChoice class.
        input_ids (Optional[Tensor]): The input sequence token IDs of shape [batch_size, num_choices, sequence_length].
            (default: None)
        attention_mask (Optional[Tensor]): The attention mask tensor of shape [batch_size, num_choices, sequence_length].
            (default: None)
        token_type_ids (Optional[Tensor]): The token type IDs tensor of shape [batch_size, num_choices, sequence_length].
            (default: None)
        position_ids (Optional[Tensor]): The position IDs tensor of shape [batch_size, num_choices, sequence_length].
            (default: None)
        entity_ids (Optional[Tensor]): The entity token IDs tensor of shape [batch_size, num_choices, entity_length].
            (default: None)
        entity_attention_mask (Optional[Tensor]): The entity attention mask tensor of
            shape [batch_size, num_choices, entity_length]. (default: None)
        entity_token_type_ids (Optional[Tensor]): The entity token type IDs tensor of
            shape [batch_size, num_choices, entity_length]. (default: None)
        entity_position_ids (Optional[Tensor]): The entity position IDs tensor of
            shape [batch_size, num_choices, entity_length]. (default: None)
        head_mask (Optional[Tensor]): The head mask tensor of shape [num_hidden_layers, num_attention_heads].
            (default: None)
        inputs_embeds (Optional[Tensor]): The input embeddings tensor of shape
            [batch_size, num_choices, sequence_length, hidden_size]. (default: None)
        labels (Optional[Tensor]): The labels tensor of shape [batch_size]. (default: None)
        output_attentions (Optional[bool]): Whether to output attentions. (default: None)
        output_hidden_states (Optional[bool]): Whether to output hidden states. (default: None)
        return_dict (Optional[bool]): Whether to return a dictionary instead of a tuple of outputs. (default: None)

    Returns:
        tuple:
            Tuple of (loss, reshaped_logits, hidden_states, entity_hidden_states, attentions):

            - loss (Optional[Tensor]): The training loss tensor. Returns None if labels are not provided.
            - reshaped_logits (Tensor): The reshaped logits tensor of shape [batch_size * num_choices, num_choices].
            - hidden_states (Optional[List[Tensor]]): The hidden states of the model at the output of each layer.
            Returns None if output_hidden_states is set to False.
            - entity_hidden_states (Optional[List[Tensor]]): The hidden states of the model for the entity
            embeddings at the output of each layer. Returns None if output_hidden_states is set to False or
            entity embeddings are not provided.
            - attentions (Optional[List[Tensor]]): The attention weights of the model at the output of each layer.
            Returns None if output_attentions is set to False.

    Raises:
        None.
    """
    return_dict = True
    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
    )

    entity_ids = entity_ids.view(-1, entity_ids.shape[-1]) if entity_ids is not None else None
    entity_attention_mask = (
        entity_attention_mask.view(-1, entity_attention_mask.shape[-1])
        if entity_attention_mask is not None
        else None
    )
    entity_token_type_ids = (
        entity_token_type_ids.view(-1, entity_token_type_ids.shape[-1])
        if entity_token_type_ids is not None
        else None
    )
    entity_position_ids = (
        entity_position_ids.view(-1, entity_position_ids.shape[-2], entity_position_ids.shape[-1])
        if entity_position_ids is not None
        else None
    )

    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    pooled_output = outputs['pooler_output']

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

    loss = None
    if labels is not None:
        loss_fct = nn.CrossEntropyLoss()
        loss = loss_fct(reshaped_logits, labels)

    return tuple(
        v
        for v in [
            loss,
            reshaped_logits,
            outputs['hidden_states'],
            outputs['entity_hidden_states'],
            outputs['attentions'],
        ]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForQuestionAnswering

Bases: LukePreTrainedModel

LukeForQuestionAnswering

Source code in mindnlp/transformers/models/luke/luke.py
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
class LukeForQuestionAnswering(LukePreTrainedModel):
    """
    LukeForQuestionAnswering
    """
    def __init__(self, config):
        """
        Initializes the LukeForQuestionAnswering class.

        Args:
            self (LukeForQuestionAnswering): The instance of the LukeForQuestionAnswering class.
            config: The configuration object containing the settings for the Luke model.
                This parameter is required and should be an instance of the configuration class for Luke models.
                It must include the following attributes:

                - num_labels (int): The number of labels for the question answering task.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided or is of an incorrect type.
            ValueError: If the num_labels attribute is not specified in the config object.
        """
        super().__init__(config)

        self.num_labels = config.num_labels

        self.luke = LukeModel(config, add_pooling_layer=False)
        self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            start_positions: Optional[Tensor] = None,
            end_positions: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Constructs the forward pass of the LukeForQuestionAnswering model.

        Args:
            self (LukeForQuestionAnswering): An instance of the LukeForQuestionAnswering class.
            input_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the input token IDs.
            attention_mask (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the attention mask.
            token_type_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the token type IDs.
            position_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the position IDs.
            entity_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the entity IDs.
            entity_attention_mask (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length)
                containing the entity attention mask.
            entity_token_type_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length)
                containing the entity token type IDs.
            entity_position_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length)
                containing the entity position IDs.
            head_mask (Optional[Tensor]): Input tensor of shape (batch_size, num_heads) containing the head mask.
            inputs_embeds (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length, hidden_size)
                containing the embedded inputs.
            start_positions (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the
                start positions for answer span prediction.
            end_positions (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the
                end positions for answer span prediction.
            output_attentions (Optional[bool]): Whether to output attentions weights. Default: None.
            output_hidden_states (Optional[bool]): Whether to output hidden states. Default: None.
            return_dict (Optional[bool]): Whether to return a dictionary as output. Default: None.

        Returns:
            tuple:
                A tuple containing the following elements:

                - total_loss (Optional[Tensor]): The total loss if start_positions and end_positions are provided.
                None otherwise.
                - start_logits (Optional[Tensor]): Tensor of shape (batch_size, sequence_length) containing
                the predicted start logits.
                - end_logits (Optional[Tensor]): Tensor of shape (batch_size, sequence_length) containing
                the predicted end logits.
                - hidden_states (Optional[List[Tensor]]): List of tensors containing the hidden states of
                the model at each layer.
                - entity_hidden_states (Optional[List[Tensor]]): List of tensors containing the hidden states of
                the entity encoder at each layer.
                - attentions (Optional[List[Tensor]]): List of tensors containing the attention weights of
                the model at each layer.

        Raises:
            None.
        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_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['last_hidden_state']

        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.clamp_(0, ignored_index)
            end_positions.clamp_(0, ignored_index)

            loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
            start_loss = loss_fct(start_logits, start_positions)
            end_loss = loss_fct(end_logits, end_positions)
            total_loss = (start_loss + end_loss) / 2

        return tuple(
            v
            for v in [
                total_loss,
                start_logits,
                end_logits,
                outputs['hidden_states'],
                outputs['entity_hidden_states'],
                outputs['attentions'],
            ]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForQuestionAnswering.__init__(config)

Initializes the LukeForQuestionAnswering class.

PARAMETER DESCRIPTION
self

The instance of the LukeForQuestionAnswering class.

TYPE: LukeForQuestionAnswering

config

The configuration object containing the settings for the Luke model. This parameter is required and should be an instance of the configuration class for Luke models. It must include the following attributes:

  • num_labels (int): The number of labels for the question answering task.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

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

ValueError

If the num_labels attribute is not specified in the config object.

Source code in mindnlp/transformers/models/luke/luke.py
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
def __init__(self, config):
    """
    Initializes the LukeForQuestionAnswering class.

    Args:
        self (LukeForQuestionAnswering): The instance of the LukeForQuestionAnswering class.
        config: The configuration object containing the settings for the Luke model.
            This parameter is required and should be an instance of the configuration class for Luke models.
            It must include the following attributes:

            - num_labels (int): The number of labels for the question answering task.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided or is of an incorrect type.
        ValueError: If the num_labels attribute is not specified in the config object.
    """
    super().__init__(config)

    self.num_labels = config.num_labels

    self.luke = LukeModel(config, add_pooling_layer=False)
    self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

mindnlp.transformers.models.luke.luke.LukeForQuestionAnswering.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_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 forward pass of the LukeForQuestionAnswering model.

PARAMETER DESCRIPTION
self

An instance of the LukeForQuestionAnswering class.

TYPE: LukeForQuestionAnswering

input_ids

Input tensor of shape (batch_size, sequence_length) containing the input token IDs.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

Input tensor of shape (batch_size, sequence_length) containing the attention mask.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

Input tensor of shape (batch_size, sequence_length) containing the token type IDs.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

Input tensor of shape (batch_size, sequence_length) containing the position IDs.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

Input tensor of shape (batch_size, sequence_length) containing the entity IDs.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

Input tensor of shape (batch_size, sequence_length) containing the entity attention mask.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

Input tensor of shape (batch_size, sequence_length) containing the entity token type IDs.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

Input tensor of shape (batch_size, sequence_length) containing the entity position IDs.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

Input tensor of shape (batch_size, num_heads) containing the head mask.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

Input tensor of shape (batch_size, sequence_length, hidden_size) containing the embedded inputs.

TYPE: Optional[Tensor] DEFAULT: None

start_positions

Input tensor of shape (batch_size, sequence_length) containing the start positions for answer span prediction.

TYPE: Optional[Tensor] DEFAULT: None

end_positions

Input tensor of shape (batch_size, sequence_length) containing the end positions for answer span prediction.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to output attentions weights. Default: None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output hidden states. Default: None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary as output. Default: None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
tuple

A tuple containing the following elements:

  • total_loss (Optional[Tensor]): The total loss if start_positions and end_positions are provided. None otherwise.
  • start_logits (Optional[Tensor]): Tensor of shape (batch_size, sequence_length) containing the predicted start logits.
  • end_logits (Optional[Tensor]): Tensor of shape (batch_size, sequence_length) containing the predicted end logits.
  • hidden_states (Optional[List[Tensor]]): List of tensors containing the hidden states of the model at each layer.
  • entity_hidden_states (Optional[List[Tensor]]): List of tensors containing the hidden states of the entity encoder at each layer.
  • attentions (Optional[List[Tensor]]): List of tensors containing the attention weights of the model at each layer.
Source code in mindnlp/transformers/models/luke/luke.py
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        start_positions: Optional[Tensor] = None,
        end_positions: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Constructs the forward pass of the LukeForQuestionAnswering model.

    Args:
        self (LukeForQuestionAnswering): An instance of the LukeForQuestionAnswering class.
        input_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the input token IDs.
        attention_mask (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the attention mask.
        token_type_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the token type IDs.
        position_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the position IDs.
        entity_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the entity IDs.
        entity_attention_mask (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length)
            containing the entity attention mask.
        entity_token_type_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length)
            containing the entity token type IDs.
        entity_position_ids (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length)
            containing the entity position IDs.
        head_mask (Optional[Tensor]): Input tensor of shape (batch_size, num_heads) containing the head mask.
        inputs_embeds (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length, hidden_size)
            containing the embedded inputs.
        start_positions (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the
            start positions for answer span prediction.
        end_positions (Optional[Tensor]): Input tensor of shape (batch_size, sequence_length) containing the
            end positions for answer span prediction.
        output_attentions (Optional[bool]): Whether to output attentions weights. Default: None.
        output_hidden_states (Optional[bool]): Whether to output hidden states. Default: None.
        return_dict (Optional[bool]): Whether to return a dictionary as output. Default: None.

    Returns:
        tuple:
            A tuple containing the following elements:

            - total_loss (Optional[Tensor]): The total loss if start_positions and end_positions are provided.
            None otherwise.
            - start_logits (Optional[Tensor]): Tensor of shape (batch_size, sequence_length) containing
            the predicted start logits.
            - end_logits (Optional[Tensor]): Tensor of shape (batch_size, sequence_length) containing
            the predicted end logits.
            - hidden_states (Optional[List[Tensor]]): List of tensors containing the hidden states of
            the model at each layer.
            - entity_hidden_states (Optional[List[Tensor]]): List of tensors containing the hidden states of
            the entity encoder at each layer.
            - attentions (Optional[List[Tensor]]): List of tensors containing the attention weights of
            the model at each layer.

    Raises:
        None.
    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_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['last_hidden_state']

    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.clamp_(0, ignored_index)
        end_positions.clamp_(0, ignored_index)

        loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
        start_loss = loss_fct(start_logits, start_positions)
        end_loss = loss_fct(end_logits, end_positions)
        total_loss = (start_loss + end_loss) / 2

    return tuple(
        v
        for v in [
            total_loss,
            start_logits,
            end_logits,
            outputs['hidden_states'],
            outputs['entity_hidden_states'],
            outputs['attentions'],
        ]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForSequenceClassification

Bases: LukePreTrainedModel

LukeForSequenceClassification

Source code in mindnlp/transformers/models/luke/luke.py
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
class LukeForSequenceClassification(LukePreTrainedModel):
    """
    LukeForSequenceClassification
    """
    def __init__(self, config):
        """
        Initializes a LukeForSequenceClassification instance.

        Args:
            self (LukeForSequenceClassification): The current instance of the LukeForSequenceClassification class.
            config (LukeConfig): The configuration object containing various settings for the Luke model.
                It must include the number of labels (num_labels) for classification tasks.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type LukeConfig.
            ValueError: If the num_labels attribute is missing in the config object.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.luke = LukeModel(config)
        self.dropout = nn.Dropout(p=
                                  config.classifier_dropout
                                  if config.classifier_dropout is not None
                                  else config.hidden_dropout_prob
                                  )
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        self.post_init()

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Method 'construct' in the class 'LukeForSequenceClassification'.

        Args:
            self: The object instance.
            input_ids (Optional[Tensor]): Input IDs for the model. Default is None.
            attention_mask (Optional[Tensor]): Mask to avoid performing attention on padding tokens. Default is None.
            token_type_ids (Optional[Tensor]): Segment token indices to differentiate between two sequences.
                Default is None.
            position_ids (Optional[Tensor]): Position indices for the input tokens. Default is None.
            entity_ids (Optional[Tensor]): Entity IDs for the input. Default is None.
            entity_attention_mask (Optional[Tensor]): Mask for entity attention. Default is None.
            entity_token_type_ids (Optional[Tensor]): Segment token indices for entities. Default is None.
            entity_position_ids (Optional[Tensor]): Position indices for entity tokens. Default is None.
            head_mask (Optional[Tensor]): Mask to nullify specific heads of the model. Default is None.
            inputs_embeds (Optional[Tensor]): Optional input embeddings. Default is None.
            labels (Optional[Tensor]): Labels for the input. 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 as a dictionary. Default is None.

        Returns:
            tuple: A tuple containing loss, logits, hidden states, entity hidden states, and attentions
                if they are not None. Otherwise, returns None.

        Raises:
            ValueError: If the configuration problem type is not recognized.
            RuntimeError: If an unexpected error occurs during the computation.
            TypeError: If the input types are incorrect.
        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        pooled_output = outputs['pooler_output']

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

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

            if self.config.problem_type == "regression":
                loss_fct = nn.MSELoss()
                if self.num_labels == 1:
                    loss = loss_fct(logits.squeeze(), labels.squeeze())
                else:
                    loss = loss_fct(logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss_fct = nn.CrossEntropyLoss()
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = nn.BCEWithLogitsLoss()
                loss = loss_fct(logits, labels)

        return tuple(
            v
            for v in
            [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForSequenceClassification.__init__(config)

Initializes a LukeForSequenceClassification instance.

PARAMETER DESCRIPTION
self

The current instance of the LukeForSequenceClassification class.

TYPE: LukeForSequenceClassification

config

The configuration object containing various settings for the Luke model. It must include the number of labels (num_labels) for classification tasks.

TYPE: LukeConfig

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type LukeConfig.

ValueError

If the num_labels attribute is missing in the config object.

Source code in mindnlp/transformers/models/luke/luke.py
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
def __init__(self, config):
    """
    Initializes a LukeForSequenceClassification instance.

    Args:
        self (LukeForSequenceClassification): The current instance of the LukeForSequenceClassification class.
        config (LukeConfig): The configuration object containing various settings for the Luke model.
            It must include the number of labels (num_labels) for classification tasks.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type LukeConfig.
        ValueError: If the num_labels attribute is missing in the config object.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.luke = LukeModel(config)
    self.dropout = nn.Dropout(p=
                              config.classifier_dropout
                              if config.classifier_dropout is not None
                              else config.hidden_dropout_prob
                              )
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

    self.post_init()

mindnlp.transformers.models.luke.luke.LukeForSequenceClassification.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Method 'construct' in the class 'LukeForSequenceClassification'.

PARAMETER DESCRIPTION
self

The object instance.

input_ids

Input IDs for the model. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

Mask to avoid performing attention on padding tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

Segment token indices to differentiate between two sequences. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

Position indices for the input tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

Entity IDs for the input. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

Mask for entity attention. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

Segment token indices for entities. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

Position indices for entity tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

Mask to nullify specific heads of the model. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

Optional input embeddings. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

labels

Labels for the input. 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 as a dictionary. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
tuple

A tuple containing loss, logits, hidden states, entity hidden states, and attentions if they are not None. Otherwise, returns None.

RAISES DESCRIPTION
ValueError

If the configuration problem type is not recognized.

RuntimeError

If an unexpected error occurs during the computation.

TypeError

If the input types are incorrect.

Source code in mindnlp/transformers/models/luke/luke.py
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Method 'construct' in the class 'LukeForSequenceClassification'.

    Args:
        self: The object instance.
        input_ids (Optional[Tensor]): Input IDs for the model. Default is None.
        attention_mask (Optional[Tensor]): Mask to avoid performing attention on padding tokens. Default is None.
        token_type_ids (Optional[Tensor]): Segment token indices to differentiate between two sequences.
            Default is None.
        position_ids (Optional[Tensor]): Position indices for the input tokens. Default is None.
        entity_ids (Optional[Tensor]): Entity IDs for the input. Default is None.
        entity_attention_mask (Optional[Tensor]): Mask for entity attention. Default is None.
        entity_token_type_ids (Optional[Tensor]): Segment token indices for entities. Default is None.
        entity_position_ids (Optional[Tensor]): Position indices for entity tokens. Default is None.
        head_mask (Optional[Tensor]): Mask to nullify specific heads of the model. Default is None.
        inputs_embeds (Optional[Tensor]): Optional input embeddings. Default is None.
        labels (Optional[Tensor]): Labels for the input. 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 as a dictionary. Default is None.

    Returns:
        tuple: A tuple containing loss, logits, hidden states, entity hidden states, and attentions
            if they are not None. Otherwise, returns None.

    Raises:
        ValueError: If the configuration problem type is not recognized.
        RuntimeError: If an unexpected error occurs during the computation.
        TypeError: If the input types are incorrect.
    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    pooled_output = outputs['pooler_output']

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

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

        if self.config.problem_type == "regression":
            loss_fct = nn.MSELoss()
            if self.num_labels == 1:
                loss = loss_fct(logits.squeeze(), labels.squeeze())
            else:
                loss = loss_fct(logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss_fct = nn.CrossEntropyLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
        elif self.config.problem_type == "multi_label_classification":
            loss_fct = nn.BCEWithLogitsLoss()
            loss = loss_fct(logits, labels)

    return tuple(
        v
        for v in
        [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeForTokenClassification

Bases: LukePreTrainedModel

LukeForTokenClassification

Source code in mindnlp/transformers/models/luke/luke.py
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
class LukeForTokenClassification(LukePreTrainedModel):
    """
    LukeForTokenClassification
    """
    def __init__(self, config):
        """
        Initializes a new instance of the LukeForTokenClassification class.

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

                - Type: LukeConfig
                - Purpose: This parameter specifies the configuration settings for the model.
                - Restrictions: None

        Returns:
            None

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

        self.luke = LukeModel(config, add_pooling_layer=False)
        self.dropout = nn.Dropout(p=
                                  config.classifier_dropout
                                  if config.classifier_dropout is not None
                                  else config.hidden_dropout_prob
                                  )
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            labels: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        """
        Constructs the model for token classification using the Luke architecture.

        Args:
            self: The object instance.
            input_ids (Optional[Tensor]): The input tensor of token indices. Default is None.
            attention_mask (Optional[Tensor]): The attention mask tensor. Default is None.
            token_type_ids (Optional[Tensor]): The tensor indicating token types. Default is None.
            position_ids (Optional[Tensor]): The tensor indicating token positions. Default is None.
            entity_ids (Optional[Tensor]): The tensor representing entity indices. Default is None.
            entity_attention_mask (Optional[Tensor]): The attention mask for entity tokens. Default is None.
            entity_token_type_ids (Optional[Tensor]): The tensor indicating entity token types. Default is None.
            entity_position_ids (Optional[Tensor]): The tensor indicating entity token positions. Default is None.
            head_mask (Optional[Tensor]): The tensor for masking heads. Default is None.
            inputs_embeds (Optional[Tensor]): The embedded input tensor. Default is None.
            labels (Optional[Tensor]): The tensor of labels for token classification. 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. Default is None.

        Returns:
            Tuple[Optional[Tensor], Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor]]:
                A tuple containing the loss, logits, hidden states, entity hidden states, and attentions.
                Any element that is not None is included in the tuple.

        Raises:
            None
        """
        return_dict = True
        outputs = self.luke(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_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['last_hidden_state']
        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_output)
        loss = None
        if labels is not None:
            loss_fct = nn.CrossEntropyLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
        return tuple(
            v
            for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
            if v is not None
        )

mindnlp.transformers.models.luke.luke.LukeForTokenClassification.__init__(config)

Initializes a new instance of the LukeForTokenClassification class.

PARAMETER DESCRIPTION
self

The object itself.

config

An instance of class 'LukeConfig' containing the configuration parameters for the LukeForTokenClassification model.

  • Type: LukeConfig
  • Purpose: This parameter specifies the configuration settings for the model.
  • Restrictions: None

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/luke/luke.py
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
def __init__(self, config):
    """
    Initializes a new instance of the LukeForTokenClassification class.

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

            - Type: LukeConfig
            - Purpose: This parameter specifies the configuration settings for the model.
            - Restrictions: None

    Returns:
        None

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

    self.luke = LukeModel(config, add_pooling_layer=False)
    self.dropout = nn.Dropout(p=
                              config.classifier_dropout
                              if config.classifier_dropout is not None
                              else config.hidden_dropout_prob
                              )
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

mindnlp.transformers.models.luke.luke.LukeForTokenClassification.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the model for token classification using the Luke architecture.

PARAMETER DESCRIPTION
self

The object instance.

input_ids

The input tensor of token indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask tensor. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The tensor indicating token types. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The tensor indicating token positions. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

The tensor representing entity indices. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

The attention mask for entity tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

The tensor indicating entity token types. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

The tensor indicating entity token positions. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The tensor for masking heads. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The embedded input tensor. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

labels

The tensor of labels for token classification. 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. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION

Tuple[Optional[Tensor], Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor]]: A tuple containing the loss, logits, hidden states, entity hidden states, and attentions. Any element that is not None is included in the tuple.

Source code in mindnlp/transformers/models/luke/luke.py
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        labels: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    """
    Constructs the model for token classification using the Luke architecture.

    Args:
        self: The object instance.
        input_ids (Optional[Tensor]): The input tensor of token indices. Default is None.
        attention_mask (Optional[Tensor]): The attention mask tensor. Default is None.
        token_type_ids (Optional[Tensor]): The tensor indicating token types. Default is None.
        position_ids (Optional[Tensor]): The tensor indicating token positions. Default is None.
        entity_ids (Optional[Tensor]): The tensor representing entity indices. Default is None.
        entity_attention_mask (Optional[Tensor]): The attention mask for entity tokens. Default is None.
        entity_token_type_ids (Optional[Tensor]): The tensor indicating entity token types. Default is None.
        entity_position_ids (Optional[Tensor]): The tensor indicating entity token positions. Default is None.
        head_mask (Optional[Tensor]): The tensor for masking heads. Default is None.
        inputs_embeds (Optional[Tensor]): The embedded input tensor. Default is None.
        labels (Optional[Tensor]): The tensor of labels for token classification. 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. Default is None.

    Returns:
        Tuple[Optional[Tensor], Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor]]:
            A tuple containing the loss, logits, hidden states, entity hidden states, and attentions.
            Any element that is not None is included in the tuple.

    Raises:
        None
    """
    return_dict = True
    outputs = self.luke(
        input_ids=input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        entity_ids=entity_ids,
        entity_attention_mask=entity_attention_mask,
        entity_token_type_ids=entity_token_type_ids,
        entity_position_ids=entity_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['last_hidden_state']
    sequence_output = self.dropout(sequence_output)
    logits = self.classifier(sequence_output)
    loss = None
    if labels is not None:
        loss_fct = nn.CrossEntropyLoss()
        loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
    return tuple(
        v
        for v in [loss, logits, outputs['hidden_states'], outputs['entity_hidden_states'], outputs['attentions']]
        if v is not None
    )

mindnlp.transformers.models.luke.luke.LukeIntermediate

Bases: Module

LukeIntermediate

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

        Args:
            self: The instance of the LukeIntermediate class.
            config:
                A configuration object that contains parameters for initializing the instance.

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

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided.
            ValueError: If the config parameter is provided but is not in the correct format.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        if isinstance(config.hidden_act, str):
            self.intermediate_act_fn = ACT2FN[config.hidden_act]
        else:
            self.intermediate_act_fn = config.hidden_act

    def construct(self, hidden_states: Tensor) -> Tensor:
        """
        Constructs the intermediate hidden states in the LukeIntermediate class.

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

        Returns:
            Tensor: The intermediate hidden states after applying the dense layer and intermediate activation function.

        Raises:
            None.

        This method takes in the instance of the LukeIntermediate class and the input hidden states.
        It applies a dense layer to the hidden states and then applies the intermediate activation function.
        The resulting intermediate hidden states are returned as a Tensor.

        No exceptions are raised by this method.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        return hidden_states

mindnlp.transformers.models.luke.luke.LukeIntermediate.__init__(config)

Initializes an instance of the LukeIntermediate class.

PARAMETER DESCRIPTION
self

The instance of the LukeIntermediate class.

config

A configuration object that contains parameters for initializing the instance.

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

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided.

ValueError

If the config parameter is provided but is not in the correct format.

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

    Args:
        self: The instance of the LukeIntermediate class.
        config:
            A configuration object that contains parameters for initializing the instance.

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

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided.
        ValueError: If the config parameter is provided but is not in the correct format.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
    if isinstance(config.hidden_act, str):
        self.intermediate_act_fn = ACT2FN[config.hidden_act]
    else:
        self.intermediate_act_fn = config.hidden_act

mindnlp.transformers.models.luke.luke.LukeIntermediate.construct(hidden_states)

Constructs the intermediate hidden states in the LukeIntermediate class.

PARAMETER DESCRIPTION
self

The instance of the LukeIntermediate class.

hidden_states

The input hidden states.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The intermediate hidden states after applying the dense layer and intermediate activation function.

TYPE: Tensor

This method takes in the instance of the LukeIntermediate class and the input hidden states. It applies a dense layer to the hidden states and then applies the intermediate activation function. The resulting intermediate hidden states are returned as a Tensor.

No exceptions are raised by this method.

Source code in mindnlp/transformers/models/luke/luke.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def construct(self, hidden_states: Tensor) -> Tensor:
    """
    Constructs the intermediate hidden states in the LukeIntermediate class.

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

    Returns:
        Tensor: The intermediate hidden states after applying the dense layer and intermediate activation function.

    Raises:
        None.

    This method takes in the instance of the LukeIntermediate class and the input hidden states.
    It applies a dense layer to the hidden states and then applies the intermediate activation function.
    The resulting intermediate hidden states are returned as a Tensor.

    No exceptions are raised by this method.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.intermediate_act_fn(hidden_states)
    return hidden_states

mindnlp.transformers.models.luke.luke.LukeLMHead

Bases: Module

LukeLMead

Source code in mindnlp/transformers/models/luke/luke.py
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
class LukeLMHead(nn.Module):
    """LukeLMead"""
    def __init__(self, config):
        """
        Initializes the LukeLMHead class.

        Args:
            self (object): The instance of the LukeLMHead class.
            config (object):
                An instance of the configuration class containing the following attributes:

                - hidden_size (int): The size of the hidden layers.
                - vocab_size (int): The size of the vocabulary.
                - layer_norm_eps (float): The epsilon value for layer normalization.

        Returns:
            None.

        Raises:
            TypeError: If the provided config parameter is not of the correct type.
            ValueError: If the hidden_size or vocab_size attributes in the config are not positive integers.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)

        self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
        self.bias = mindspore.Parameter(ops.zeros(config.vocab_size))
        self.decoder.bias = self.bias

    def construct(self, features, **kwargs):
        """
        Constructs the output of the LukeLMHead model by performing a series of operations on the input features.

        Args:
            self (LukeLMHead): The instance of the LukeLMHead class.
            features (tensor): The input features to be processed by the model.

        Returns:
            tensor: The output tensor after processing the input features through the model.

        Raises:
            None.
        """
        # hidden
        x = self.dense(features)
        x = ops.gelu(x)
        x = self.layer_norm(x)
        # project back to size of vocabulary with bias
        # endecoded
        x = self.decoder(x)

        return x

    def _tie_weights(self):
        '''
        This method ties the weights of the LukeLMHead model's decoder with its bias.

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

        Returns:
            None.

        Raises:
            None.
        '''
        # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
        # For accelerate compatibility and to not break backward compatibility
        if self.decoder.bias.device.type == "meta":
            self.decoder.bias = self.bias
        else:
            self.bias = self.decoder.bias

mindnlp.transformers.models.luke.luke.LukeLMHead.__init__(config)

Initializes the LukeLMHead class.

PARAMETER DESCRIPTION
self

The instance of the LukeLMHead class.

TYPE: object

config

An instance of the configuration class containing the following attributes:

  • hidden_size (int): The size of the hidden layers.
  • vocab_size (int): The size of the vocabulary.
  • layer_norm_eps (float): The epsilon value for layer normalization.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the provided config parameter is not of the correct type.

ValueError

If the hidden_size or vocab_size attributes in the config are not positive integers.

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

    Args:
        self (object): The instance of the LukeLMHead class.
        config (object):
            An instance of the configuration class containing the following attributes:

            - hidden_size (int): The size of the hidden layers.
            - vocab_size (int): The size of the vocabulary.
            - layer_norm_eps (float): The epsilon value for layer normalization.

    Returns:
        None.

    Raises:
        TypeError: If the provided config parameter is not of the correct type.
        ValueError: If the hidden_size or vocab_size attributes in the config are not positive integers.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_size)
    self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)

    self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
    self.bias = mindspore.Parameter(ops.zeros(config.vocab_size))
    self.decoder.bias = self.bias

mindnlp.transformers.models.luke.luke.LukeLMHead.construct(features, **kwargs)

Constructs the output of the LukeLMHead model by performing a series of operations on the input features.

PARAMETER DESCRIPTION
self

The instance of the LukeLMHead class.

TYPE: LukeLMHead

features

The input features to be processed by the model.

TYPE: tensor

RETURNS DESCRIPTION
tensor

The output tensor after processing the input features through the model.

Source code in mindnlp/transformers/models/luke/luke.py
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
def construct(self, features, **kwargs):
    """
    Constructs the output of the LukeLMHead model by performing a series of operations on the input features.

    Args:
        self (LukeLMHead): The instance of the LukeLMHead class.
        features (tensor): The input features to be processed by the model.

    Returns:
        tensor: The output tensor after processing the input features through the model.

    Raises:
        None.
    """
    # hidden
    x = self.dense(features)
    x = ops.gelu(x)
    x = self.layer_norm(x)
    # project back to size of vocabulary with bias
    # endecoded
    x = self.decoder(x)

    return x

mindnlp.transformers.models.luke.luke.LukeLayer

Bases: Module

LukeOutput

Source code in mindnlp/transformers/models/luke/luke.py
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
class LukeLayer(nn.Module):
    """
    LukeOutput
    """
    def __init__(self, config):
        """
        Initializes a new instance of the LukeLayer class.

        Args:
            self: The object itself.
            config:
                An instance of the configuration class containing the following attributes:

                - chunk_size_feed_forward (int): The size of chunks to feed forward through the layer.
                - seq_len_dim (int): The dimension of the sequence length.

        Returns:
            None

        Raises:
            None
        """
        super().__init__()
        self.chunk_size_feed_forward = config.chunk_size_feed_forward
        self.seq_len_dim = 1
        self.attention = LukeAttention(config)
        self.intermediate = LukeIntermediate(config)
        self.output = LukeOutput(config)

    def construct(
            self,
            word_hidden_states,
            entity_hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
    ):
        """
        Constructs the LukeLayer.

        Args:
            self (LukeLayer): The instance of the LukeLayer class.
            word_hidden_states (Tensor): The hidden states of the word inputs.
                It has shape [batch_size, seq_length, hidden_size].
            entity_hidden_states (Tensor): The hidden states of the entity inputs.
                It has shape [batch_size, seq_length, hidden_size].
            attention_mask (Tensor, optional): The attention mask to avoid performing attention on padding tokens.
                It has shape [batch_size, seq_length]. Defaults to None.
            head_mask (Tensor, optional): The mask to nullify selected heads of the self-attention modules.
                It has shape [num_heads, seq_length, seq_length]. Defaults to None.
            output_attentions (bool, optional): Whether to output attention weights. Defaults to False.

        Returns:
            Tuple[Tensor, Tensor, Tuple]:
                A tuple containing:

                - word_layer_output (Tensor): The layer output for word inputs.
                    It has shape [batch_size, word_size, hidden_size].
                - entity_layer_output (Tensor): The layer output for entity inputs.
                    It has shape [batch_size, entity_size, hidden_size].
                - outputs (Tuple): Additional outputs from the attention layer.

        Raises:
            None.
        """
        word_size = word_hidden_states.shape[1]

        self_attention_outputs = self.attention(
            word_hidden_states,
            entity_hidden_states,
            attention_mask,
            head_mask,
            output_attentions=output_attentions,
        )
        if entity_hidden_states is None:
            concat_attention_output = self_attention_outputs[0]
        else:
            concat_attention_output = ops.cat(self_attention_outputs[:2], axis=1)

        outputs = self_attention_outputs[2:]  # add self attentions if we output attention weights

        layer_output = apply_chunking_to_forward(
            self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, concat_attention_output
        )
        word_layer_output = layer_output[:, :word_size, :]
        if entity_hidden_states is None:
            entity_layer_output = None
        else:
            entity_layer_output = layer_output[:, word_size:, :]

        outputs = (word_layer_output, entity_layer_output) + outputs

        return outputs

    def feed_forward_chunk(self, attention_output):
        """
        This function applies transformations to an input tensor
        using two other layers  to produce an output tensor.
        """
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        return layer_output

mindnlp.transformers.models.luke.luke.LukeLayer.__init__(config)

Initializes a new instance of the LukeLayer class.

PARAMETER DESCRIPTION
self

The object itself.

config

An instance of the configuration class containing the following attributes:

  • chunk_size_feed_forward (int): The size of chunks to feed forward through the layer.
  • seq_len_dim (int): The dimension of the sequence length.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/luke/luke.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
def __init__(self, config):
    """
    Initializes a new instance of the LukeLayer class.

    Args:
        self: The object itself.
        config:
            An instance of the configuration class containing the following attributes:

            - chunk_size_feed_forward (int): The size of chunks to feed forward through the layer.
            - seq_len_dim (int): The dimension of the sequence length.

    Returns:
        None

    Raises:
        None
    """
    super().__init__()
    self.chunk_size_feed_forward = config.chunk_size_feed_forward
    self.seq_len_dim = 1
    self.attention = LukeAttention(config)
    self.intermediate = LukeIntermediate(config)
    self.output = LukeOutput(config)

mindnlp.transformers.models.luke.luke.LukeLayer.construct(word_hidden_states, entity_hidden_states, attention_mask=None, head_mask=None, output_attentions=False)

Constructs the LukeLayer.

PARAMETER DESCRIPTION
self

The instance of the LukeLayer class.

TYPE: LukeLayer

word_hidden_states

The hidden states of the word inputs. It has shape [batch_size, seq_length, hidden_size].

TYPE: Tensor

entity_hidden_states

The hidden states of the entity inputs. It has shape [batch_size, seq_length, hidden_size].

TYPE: Tensor

attention_mask

The attention mask to avoid performing attention on padding tokens. It has shape [batch_size, seq_length]. Defaults to None.

TYPE: Tensor DEFAULT: None

head_mask

The mask to nullify selected heads of the self-attention modules. It has shape [num_heads, seq_length, seq_length]. Defaults to None.

TYPE: Tensor DEFAULT: None

output_attentions

Whether to output attention weights. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

Tuple[Tensor, Tensor, Tuple]: A tuple containing:

  • word_layer_output (Tensor): The layer output for word inputs. It has shape [batch_size, word_size, hidden_size].
  • entity_layer_output (Tensor): The layer output for entity inputs. It has shape [batch_size, entity_size, hidden_size].
  • outputs (Tuple): Additional outputs from the attention layer.
Source code in mindnlp/transformers/models/luke/luke.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def construct(
        self,
        word_hidden_states,
        entity_hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
):
    """
    Constructs the LukeLayer.

    Args:
        self (LukeLayer): The instance of the LukeLayer class.
        word_hidden_states (Tensor): The hidden states of the word inputs.
            It has shape [batch_size, seq_length, hidden_size].
        entity_hidden_states (Tensor): The hidden states of the entity inputs.
            It has shape [batch_size, seq_length, hidden_size].
        attention_mask (Tensor, optional): The attention mask to avoid performing attention on padding tokens.
            It has shape [batch_size, seq_length]. Defaults to None.
        head_mask (Tensor, optional): The mask to nullify selected heads of the self-attention modules.
            It has shape [num_heads, seq_length, seq_length]. Defaults to None.
        output_attentions (bool, optional): Whether to output attention weights. Defaults to False.

    Returns:
        Tuple[Tensor, Tensor, Tuple]:
            A tuple containing:

            - word_layer_output (Tensor): The layer output for word inputs.
                It has shape [batch_size, word_size, hidden_size].
            - entity_layer_output (Tensor): The layer output for entity inputs.
                It has shape [batch_size, entity_size, hidden_size].
            - outputs (Tuple): Additional outputs from the attention layer.

    Raises:
        None.
    """
    word_size = word_hidden_states.shape[1]

    self_attention_outputs = self.attention(
        word_hidden_states,
        entity_hidden_states,
        attention_mask,
        head_mask,
        output_attentions=output_attentions,
    )
    if entity_hidden_states is None:
        concat_attention_output = self_attention_outputs[0]
    else:
        concat_attention_output = ops.cat(self_attention_outputs[:2], axis=1)

    outputs = self_attention_outputs[2:]  # add self attentions if we output attention weights

    layer_output = apply_chunking_to_forward(
        self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, concat_attention_output
    )
    word_layer_output = layer_output[:, :word_size, :]
    if entity_hidden_states is None:
        entity_layer_output = None
    else:
        entity_layer_output = layer_output[:, word_size:, :]

    outputs = (word_layer_output, entity_layer_output) + outputs

    return outputs

mindnlp.transformers.models.luke.luke.LukeLayer.feed_forward_chunk(attention_output)

This function applies transformations to an input tensor using two other layers to produce an output tensor.

Source code in mindnlp/transformers/models/luke/luke.py
759
760
761
762
763
764
765
766
def feed_forward_chunk(self, attention_output):
    """
    This function applies transformations to an input tensor
    using two other layers  to produce an output tensor.
    """
    intermediate_output = self.intermediate(attention_output)
    layer_output = self.output(intermediate_output, attention_output)
    return layer_output

mindnlp.transformers.models.luke.luke.LukeModel

Bases: LukePreTrainedModel

LukeModel

Source code in mindnlp/transformers/models/luke/luke.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
class LukeModel(LukePreTrainedModel):
    """
    LukeModel
    """
    _keys_to_ignore_on_load_missing = [r"position_ids"]

    def __init__(self, config: LukeConfig, add_pooling_layer: bool = True):
        """
        Initializes a new LukeModel instance.

        Args:
            self: The instance of the LukeModel class.
            config (LukeConfig): An instance of LukeConfig containing the configuration for the model.
            add_pooling_layer (bool, optional): A boolean indicating whether to add a pooling layer. Defaults to True.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not an instance of LukeConfig.
            ValueError: If the add_pooling_layer parameter is not a boolean.
        """
        super().__init__(config)
        self.config = config

        self.embeddings = LukeEmbeddings(config)
        self.entity_embeddings = LukeEntityEmbeddings(config)
        self.encoder = LukeEncoder(config)

        self.pooler = LukePooler(config) if add_pooling_layer else None

    def get_input_embeddings(self):
        """
        This method retrieves the input embeddings from the LukeModel class.

        Args:
            self: The instance of the LukeModel class.

        Returns:
            The word embeddings for the input.

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

    def set_input_embeddings(self, new_embeddings):
        """
        Sets the input embeddings of the LukeModel.

        Args:
            self (LukeModel): The LukeModel instance to which the input embeddings will be set.
            new_embeddings (any): New embeddings to be set as input embeddings for the LukeModel.

        Returns:
            None.

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

    def get_entity_embeddings(self):
        """get_entity_embeddings"""
        return self.entity_embeddings.entity_embeddings

    def set_entity_embeddings(self, new_embeddings):
        """set_entity_embeddings"""
        self.entity_embeddings.entity_embeddings = new_embeddings

    def _prune_heads(self, heads_to_prune):
        """
        Method to prune attention heads in a LUKE model.

        Args:
            self (LukeModel): The instance of LukeModel.
            heads_to_prune (int): The number of attention heads to prune from the model.
                It specifies which attention heads should be pruned.

        Returns:
            None.

        Raises:
            NotImplementedError: Raised when an attempt is made to prune attention heads in a LUKE model.
                LUKE does not support the pruning of attention heads, so this operation is not allowed.
        """
        raise NotImplementedError("LUKE does not support the pruning of attention heads")

    def construct(
            self,
            input_ids: Optional[Tensor] = None,
            attention_mask: Optional[Tensor] = None,
            token_type_ids: Optional[Tensor] = None,
            position_ids: Optional[Tensor] = None,
            entity_ids: Optional[Tensor] = None,
            entity_attention_mask: Optional[Tensor] = None,
            entity_token_type_ids: Optional[Tensor] = None,
            entity_position_ids: Optional[Tensor] = None,
            head_mask: Optional[Tensor] = None,
            inputs_embeds: Optional[Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ):
        '''
        The 'construct' method in the 'LukeModel' class is responsible for constructing the model
        based on the provided inputs and configuration.

        Args:
            self: The instance of the class.
            input_ids (Optional[Tensor]): The input tensor representing the token ids. Default is None.
            attention_mask (Optional[Tensor]): The attention mask tensor indicating the positions of the padded tokens.
                Default is None.
            token_type_ids (Optional[Tensor]): The tensor representing the token type ids. Default is None.
            position_ids (Optional[Tensor]): The tensor representing the position ids. Default is None.
            entity_ids (Optional[Tensor]): The tensor representing the entity ids. Default is None.
            entity_attention_mask (Optional[Tensor]): The attention mask tensor for entity tokens. Default is None.
            entity_token_type_ids (Optional[Tensor]): The tensor representing the token type ids for entities.
                Default is None.
            entity_position_ids (Optional[Tensor]): The tensor representing the position ids for entities.
                Default is None.
            head_mask (Optional[Tensor]): The tensor representing the head mask. Default is None.
            inputs_embeds (Optional[Tensor]): The embedded inputs tensor. Default is None.
            output_attentions (Optional[bool]): Whether to return attentions. Default is None.
            output_hidden_states (Optional[bool]): Whether to return hidden states. Default is None.
            return_dict (Optional[bool]): Whether to return a dictionary. Default is None.

        Returns:
            None.

        Raises:
            ValueError:
                - If both input_ids and inputs_embeds are specified simultaneously.
                - If neither input_ids nor inputs_embeds is 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 and inputs_embeds is None:
            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((batch_size, seq_length))
        if token_type_ids is None:
            token_type_ids = ops.zeros(input_shape, dtype=mindspore.int64)
        if entity_ids is not None:
            entity_seq_length = entity_ids.shape[1]
            if entity_attention_mask is None:
                entity_attention_mask = ops.ones((batch_size, entity_seq_length))
            if entity_token_type_ids is None:
                entity_token_type_ids = ops.zeros((batch_size, entity_seq_length), dtype=mindspore.int64)

        head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)

        # First, compute word embeddings
        word_embedding_output = self.embeddings(
            input_ids=input_ids,
            position_ids=position_ids,
            token_type_ids=token_type_ids,
            inputs_embeds=inputs_embeds,
        )

        # Second, compute extended attention mask
        extended_attention_mask = self.get_extended_attention_mask(attention_mask, entity_attention_mask)

        # Third, compute entity embeddings and concatenate with word embeddings
        if entity_ids is None:
            entity_embedding_output = None
        else:
            entity_embedding_output = self.entity_embeddings(entity_ids, entity_position_ids, entity_token_type_ids)

        encoder_outputs = self.encoder(
            word_embedding_output,
            entity_embedding_output,
            attention_mask=extended_attention_mask,
            head_mask=head_mask,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        sequence_output = encoder_outputs[0] if not return_dict else tuple(
            i for i in encoder_outputs.values() if i is not None)[0]

        pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
        if not return_dict:
            return (sequence_output, pooled_output) + encoder_outputs[1:]

        return {
            'last_hidden_state': sequence_output,
            'pooler_output': pooled_output,
            'hidden_states': encoder_outputs['hidden_states'],
            'attentions': encoder_outputs['attentions'],
            'entity_last_hidden_state': encoder_outputs['entity_last_hidden_state'],
            'entity_hidden_states': encoder_outputs['entity_hidden_states']
        }

    def get_extended_attention_mask(
            self, attention_mask: Tensor, input_shape: Tuple[int], dtype=None
    ):
        """
        This method 'get_extended_attention_mask' in the class 'LukeModel' takes 4 parameters:

        Args:
            self: Represents the instance of the class.
            attention_mask (Tensor): A 2D or 3D tensor representing the attention mask.
                This tensor is concatenated with 'input_shape' if provided.
            input_shape (Tuple[int]): A tuple containing the shape information to be concatenated with 'attention_mask'.
                Set to None if not provided.
            dtype: Data type for the extended attention mask. Default is None.

        Returns:
            None.

        Raises:
            ValueError: Raised when the shape of the 'attention_mask' is incorrect.
        """
        if input_shape is not None:
            attention_mask = ops.cat([attention_mask, input_shape], axis=-1)

        if attention_mask.dim() == 3:
            extended_attention_mask = attention_mask[:, None, :, :]
        elif attention_mask.dim() == 2:
            extended_attention_mask = attention_mask[:, None, None, :]
        else:
            raise ValueError(f"Wrong shape for attention_mask (shape {attention_mask.shape})")

        extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)  # fp16 compatibility
        extended_attention_mask = (1.0 - extended_attention_mask) * Tensor(
            np.finfo(mindspore.dtype_to_nptype(self.dtype)).min)

        return extended_attention_mask

mindnlp.transformers.models.luke.luke.LukeModel.__init__(config, add_pooling_layer=True)

Initializes a new LukeModel instance.

PARAMETER DESCRIPTION
self

The instance of the LukeModel class.

config

An instance of LukeConfig containing the configuration for the model.

TYPE: LukeConfig

add_pooling_layer

A boolean indicating whether to add a pooling layer. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not an instance of LukeConfig.

ValueError

If the add_pooling_layer parameter is not a boolean.

Source code in mindnlp/transformers/models/luke/luke.py
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
def __init__(self, config: LukeConfig, add_pooling_layer: bool = True):
    """
    Initializes a new LukeModel instance.

    Args:
        self: The instance of the LukeModel class.
        config (LukeConfig): An instance of LukeConfig containing the configuration for the model.
        add_pooling_layer (bool, optional): A boolean indicating whether to add a pooling layer. Defaults to True.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not an instance of LukeConfig.
        ValueError: If the add_pooling_layer parameter is not a boolean.
    """
    super().__init__(config)
    self.config = config

    self.embeddings = LukeEmbeddings(config)
    self.entity_embeddings = LukeEntityEmbeddings(config)
    self.encoder = LukeEncoder(config)

    self.pooler = LukePooler(config) if add_pooling_layer else None

mindnlp.transformers.models.luke.luke.LukeModel.construct(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, entity_ids=None, entity_attention_mask=None, entity_token_type_ids=None, entity_position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)

The 'construct' method in the 'LukeModel' class is responsible for constructing the model based on the provided inputs and configuration.

PARAMETER DESCRIPTION
self

The instance of the class.

input_ids

The input tensor representing the token ids. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask tensor indicating the positions of the padded tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

token_type_ids

The tensor representing the token type ids. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

position_ids

The tensor representing the position ids. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_ids

The tensor representing the entity ids. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_attention_mask

The attention mask tensor for entity tokens. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_token_type_ids

The tensor representing the token type ids for entities. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

entity_position_ids

The tensor representing the position ids for entities. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The tensor representing the head mask. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The embedded inputs tensor. Default is None.

TYPE: Optional[Tensor] DEFAULT: None

output_attentions

Whether to return attentions. Default is None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to return hidden states. Default is None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary. Default is None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError
  • If both input_ids and inputs_embeds are specified simultaneously.
  • If neither input_ids nor inputs_embeds is specified.
Source code in mindnlp/transformers/models/luke/luke.py
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
def construct(
        self,
        input_ids: Optional[Tensor] = None,
        attention_mask: Optional[Tensor] = None,
        token_type_ids: Optional[Tensor] = None,
        position_ids: Optional[Tensor] = None,
        entity_ids: Optional[Tensor] = None,
        entity_attention_mask: Optional[Tensor] = None,
        entity_token_type_ids: Optional[Tensor] = None,
        entity_position_ids: Optional[Tensor] = None,
        head_mask: Optional[Tensor] = None,
        inputs_embeds: Optional[Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
):
    '''
    The 'construct' method in the 'LukeModel' class is responsible for constructing the model
    based on the provided inputs and configuration.

    Args:
        self: The instance of the class.
        input_ids (Optional[Tensor]): The input tensor representing the token ids. Default is None.
        attention_mask (Optional[Tensor]): The attention mask tensor indicating the positions of the padded tokens.
            Default is None.
        token_type_ids (Optional[Tensor]): The tensor representing the token type ids. Default is None.
        position_ids (Optional[Tensor]): The tensor representing the position ids. Default is None.
        entity_ids (Optional[Tensor]): The tensor representing the entity ids. Default is None.
        entity_attention_mask (Optional[Tensor]): The attention mask tensor for entity tokens. Default is None.
        entity_token_type_ids (Optional[Tensor]): The tensor representing the token type ids for entities.
            Default is None.
        entity_position_ids (Optional[Tensor]): The tensor representing the position ids for entities.
            Default is None.
        head_mask (Optional[Tensor]): The tensor representing the head mask. Default is None.
        inputs_embeds (Optional[Tensor]): The embedded inputs tensor. Default is None.
        output_attentions (Optional[bool]): Whether to return attentions. Default is None.
        output_hidden_states (Optional[bool]): Whether to return hidden states. Default is None.
        return_dict (Optional[bool]): Whether to return a dictionary. Default is None.

    Returns:
        None.

    Raises:
        ValueError:
            - If both input_ids and inputs_embeds are specified simultaneously.
            - If neither input_ids nor inputs_embeds is 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 and inputs_embeds is None:
        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((batch_size, seq_length))
    if token_type_ids is None:
        token_type_ids = ops.zeros(input_shape, dtype=mindspore.int64)
    if entity_ids is not None:
        entity_seq_length = entity_ids.shape[1]
        if entity_attention_mask is None:
            entity_attention_mask = ops.ones((batch_size, entity_seq_length))
        if entity_token_type_ids is None:
            entity_token_type_ids = ops.zeros((batch_size, entity_seq_length), dtype=mindspore.int64)

    head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)

    # First, compute word embeddings
    word_embedding_output = self.embeddings(
        input_ids=input_ids,
        position_ids=position_ids,
        token_type_ids=token_type_ids,
        inputs_embeds=inputs_embeds,
    )

    # Second, compute extended attention mask
    extended_attention_mask = self.get_extended_attention_mask(attention_mask, entity_attention_mask)

    # Third, compute entity embeddings and concatenate with word embeddings
    if entity_ids is None:
        entity_embedding_output = None
    else:
        entity_embedding_output = self.entity_embeddings(entity_ids, entity_position_ids, entity_token_type_ids)

    encoder_outputs = self.encoder(
        word_embedding_output,
        entity_embedding_output,
        attention_mask=extended_attention_mask,
        head_mask=head_mask,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    sequence_output = encoder_outputs[0] if not return_dict else tuple(
        i for i in encoder_outputs.values() if i is not None)[0]

    pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
    if not return_dict:
        return (sequence_output, pooled_output) + encoder_outputs[1:]

    return {
        'last_hidden_state': sequence_output,
        'pooler_output': pooled_output,
        'hidden_states': encoder_outputs['hidden_states'],
        'attentions': encoder_outputs['attentions'],
        'entity_last_hidden_state': encoder_outputs['entity_last_hidden_state'],
        'entity_hidden_states': encoder_outputs['entity_hidden_states']
    }

mindnlp.transformers.models.luke.luke.LukeModel.get_entity_embeddings()

get_entity_embeddings

Source code in mindnlp/transformers/models/luke/luke.py
1205
1206
1207
def get_entity_embeddings(self):
    """get_entity_embeddings"""
    return self.entity_embeddings.entity_embeddings

mindnlp.transformers.models.luke.luke.LukeModel.get_extended_attention_mask(attention_mask, input_shape, dtype=None)

This method 'get_extended_attention_mask' in the class 'LukeModel' takes 4 parameters:

PARAMETER DESCRIPTION
self

Represents the instance of the class.

attention_mask

A 2D or 3D tensor representing the attention mask. This tensor is concatenated with 'input_shape' if provided.

TYPE: Tensor

input_shape

A tuple containing the shape information to be concatenated with 'attention_mask'. Set to None if not provided.

TYPE: Tuple[int]

dtype

Data type for the extended attention mask. Default is None.

DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

Raised when the shape of the 'attention_mask' is incorrect.

Source code in mindnlp/transformers/models/luke/luke.py
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
def get_extended_attention_mask(
        self, attention_mask: Tensor, input_shape: Tuple[int], dtype=None
):
    """
    This method 'get_extended_attention_mask' in the class 'LukeModel' takes 4 parameters:

    Args:
        self: Represents the instance of the class.
        attention_mask (Tensor): A 2D or 3D tensor representing the attention mask.
            This tensor is concatenated with 'input_shape' if provided.
        input_shape (Tuple[int]): A tuple containing the shape information to be concatenated with 'attention_mask'.
            Set to None if not provided.
        dtype: Data type for the extended attention mask. Default is None.

    Returns:
        None.

    Raises:
        ValueError: Raised when the shape of the 'attention_mask' is incorrect.
    """
    if input_shape is not None:
        attention_mask = ops.cat([attention_mask, input_shape], axis=-1)

    if attention_mask.dim() == 3:
        extended_attention_mask = attention_mask[:, None, :, :]
    elif attention_mask.dim() == 2:
        extended_attention_mask = attention_mask[:, None, None, :]
    else:
        raise ValueError(f"Wrong shape for attention_mask (shape {attention_mask.shape})")

    extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)  # fp16 compatibility
    extended_attention_mask = (1.0 - extended_attention_mask) * Tensor(
        np.finfo(mindspore.dtype_to_nptype(self.dtype)).min)

    return extended_attention_mask

mindnlp.transformers.models.luke.luke.LukeModel.get_input_embeddings()

This method retrieves the input embeddings from the LukeModel class.

PARAMETER DESCRIPTION
self

The instance of the LukeModel class.

RETURNS DESCRIPTION

The word embeddings for the input.

Source code in mindnlp/transformers/models/luke/luke.py
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
def get_input_embeddings(self):
    """
    This method retrieves the input embeddings from the LukeModel class.

    Args:
        self: The instance of the LukeModel class.

    Returns:
        The word embeddings for the input.

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

mindnlp.transformers.models.luke.luke.LukeModel.set_entity_embeddings(new_embeddings)

set_entity_embeddings

Source code in mindnlp/transformers/models/luke/luke.py
1209
1210
1211
def set_entity_embeddings(self, new_embeddings):
    """set_entity_embeddings"""
    self.entity_embeddings.entity_embeddings = new_embeddings

mindnlp.transformers.models.luke.luke.LukeModel.set_input_embeddings(new_embeddings)

Sets the input embeddings of the LukeModel.

PARAMETER DESCRIPTION
self

The LukeModel instance to which the input embeddings will be set.

TYPE: LukeModel

new_embeddings

New embeddings to be set as input embeddings for the LukeModel.

TYPE: any

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
def set_input_embeddings(self, new_embeddings):
    """
    Sets the input embeddings of the LukeModel.

    Args:
        self (LukeModel): The LukeModel instance to which the input embeddings will be set.
        new_embeddings (any): New embeddings to be set as input embeddings for the LukeModel.

    Returns:
        None.

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

mindnlp.transformers.models.luke.luke.LukeOutput

Bases: Module

LukeOutput

Source code in mindnlp/transformers/models/luke/luke.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
class LukeOutput(nn.Module):
    """
    LukeOutput
    """
    def __init__(self, config):
        """
        Initializes an instance of the LukeOutput class.

        Args:
            self (object): The instance of the LukeOutput class.
            config (object): An object containing configuration parameters for the LukeOutput instance.
                The config object is expected to have the following attributes:

                - 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 hidden layers.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided.
            ValueError: If any of the required attributes in the config object are missing or have invalid values.
        """
        super().__init__()
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def construct(self, hidden_states: Tensor, input_tensor: Tensor) -> Tensor:
        """
        Constructs the output tensor for the LukeOutput class.

        Args:
            self: An instance of the LukeOutput class.
            hidden_states (Tensor): The hidden states tensor.
                This tensor represents the intermediate hidden states of the model.
                It should have a shape of (batch_size, sequence_length, hidden_size).
            input_tensor (Tensor): The input tensor.
                This tensor represents the input to the layer.
                It should have a shape of (batch_size, sequence_length, hidden_size).

        Returns:
            Tensor: The constructed output tensor.
                This tensor is obtained by applying the dense layer, dropout, and layer normalization
                to the hidden states tensor and adding it to the input tensor.
                The returned tensor has the same shape as the input tensor.

        Raises:
            None.

        Note:
            The 'construct' method is responsible for transforming the hidden states tensor using the dense layer,
            applying dropout for regularization, and adding the transformed tensor to the input tensor.
            The resulting tensor represents the final output of the LukeOutput layer.
        """
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.layer_norm(hidden_states + input_tensor)
        return hidden_states

mindnlp.transformers.models.luke.luke.LukeOutput.__init__(config)

Initializes an instance of the LukeOutput class.

PARAMETER DESCRIPTION
self

The instance of the LukeOutput class.

TYPE: object

config

An object containing configuration parameters for the LukeOutput instance. The config object is expected to have the following attributes:

  • 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 hidden layers.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided.

ValueError

If any of the required attributes in the config object are missing or have invalid values.

Source code in mindnlp/transformers/models/luke/luke.py
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def __init__(self, config):
    """
    Initializes an instance of the LukeOutput class.

    Args:
        self (object): The instance of the LukeOutput class.
        config (object): An object containing configuration parameters for the LukeOutput instance.
            The config object is expected to have the following attributes:

            - 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 hidden layers.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided.
        ValueError: If any of the required attributes in the config object are missing or have invalid values.
    """
    super().__init__()
    self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
    self.layer_norm = nn.LayerNorm([config.hidden_size, ], eps=config.layer_norm_eps)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.luke.luke.LukeOutput.construct(hidden_states, input_tensor)

Constructs the output tensor for the LukeOutput class.

PARAMETER DESCRIPTION
self

An instance of the LukeOutput class.

hidden_states

The hidden states tensor. This tensor represents the intermediate hidden states of the model. It should have a shape of (batch_size, sequence_length, hidden_size).

TYPE: Tensor

input_tensor

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

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The constructed output tensor. This tensor is obtained by applying the dense layer, dropout, and layer normalization to the hidden states tensor and adding it to the input tensor. The returned tensor has the same shape as the input tensor.

TYPE: Tensor

Note

The 'construct' method is responsible for transforming the hidden states tensor using the dense layer, applying dropout for regularization, and adding the transformed tensor to the input tensor. The resulting tensor represents the final output of the LukeOutput layer.

Source code in mindnlp/transformers/models/luke/luke.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def construct(self, hidden_states: Tensor, input_tensor: Tensor) -> Tensor:
    """
    Constructs the output tensor for the LukeOutput class.

    Args:
        self: An instance of the LukeOutput class.
        hidden_states (Tensor): The hidden states tensor.
            This tensor represents the intermediate hidden states of the model.
            It should have a shape of (batch_size, sequence_length, hidden_size).
        input_tensor (Tensor): The input tensor.
            This tensor represents the input to the layer.
            It should have a shape of (batch_size, sequence_length, hidden_size).

    Returns:
        Tensor: The constructed output tensor.
            This tensor is obtained by applying the dense layer, dropout, and layer normalization
            to the hidden states tensor and adding it to the input tensor.
            The returned tensor has the same shape as the input tensor.

    Raises:
        None.

    Note:
        The 'construct' method is responsible for transforming the hidden states tensor using the dense layer,
        applying dropout for regularization, and adding the transformed tensor to the input tensor.
        The resulting tensor represents the final output of the LukeOutput layer.
    """
    hidden_states = self.dense(hidden_states)
    hidden_states = self.dropout(hidden_states)
    hidden_states = self.layer_norm(hidden_states + input_tensor)
    return hidden_states

mindnlp.transformers.models.luke.luke.LukePooler

Bases: Module

LukePooler

Source code in mindnlp/transformers/models/luke/luke.py
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
class LukePooler(nn.Module):
    """
    LukePooler
    """
    def __init__(self, config):
        """
        Initializes an instance of the LukePooler class.

        Args:
            self (object): The instance of the LukePooler class.
            config (object): An object containing configuration parameters for the LukePooler.
                This parameter is required to configure the dense layer and activation function.
                It should have a 'hidden_size' attribute specifying the size of the hidden layer.
                Raises a TypeError if config is not provided or if hidden_size is missing.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is missing or if the 'hidden_size' attribute is not present
                in the config object.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.activation = nn.Tanh()

    def construct(self, hidden_states: Tensor) -> Tensor:
        """
        This method constructs a pooled output tensor based on the hidden states provided.

        Args:
            self: An instance of the LukePooler class.
            hidden_states (Tensor): A tensor containing hidden states from which the pooled output will be constructed.
                It is expected to have shape (batch_size, sequence_length, hidden_size).

        Returns:
            Tensor: A tensor representing the pooled output obtained from the hidden states.
                It is obtained by applying a dense layer followed by an activation function to the
                first token's hidden state.

        Raises:
            None
        """
        # We "pool" the model by simply taking the hidden state corresponding
        # to the first token.
        first_token_tensor = hidden_states[:, 0]
        pooled_output = self.dense(first_token_tensor)
        pooled_output = self.activation(pooled_output)
        return pooled_output

mindnlp.transformers.models.luke.luke.LukePooler.__init__(config)

Initializes an instance of the LukePooler class.

PARAMETER DESCRIPTION
self

The instance of the LukePooler class.

TYPE: object

config

An object containing configuration parameters for the LukePooler. This parameter is required to configure the dense layer and activation function. It should have a 'hidden_size' attribute specifying the size of the hidden layer. Raises a TypeError if config is not provided or if hidden_size is missing.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is missing or if the 'hidden_size' attribute is not present in the config object.

Source code in mindnlp/transformers/models/luke/luke.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
def __init__(self, config):
    """
    Initializes an instance of the LukePooler class.

    Args:
        self (object): The instance of the LukePooler class.
        config (object): An object containing configuration parameters for the LukePooler.
            This parameter is required to configure the dense layer and activation function.
            It should have a 'hidden_size' attribute specifying the size of the hidden layer.
            Raises a TypeError if config is not provided or if hidden_size is missing.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is missing or if the 'hidden_size' attribute is not present
            in the config object.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_size)
    self.activation = nn.Tanh()

mindnlp.transformers.models.luke.luke.LukePooler.construct(hidden_states)

This method constructs a pooled output tensor based on the hidden states provided.

PARAMETER DESCRIPTION
self

An instance of the LukePooler class.

hidden_states

A tensor containing hidden states from which the pooled output will be constructed. It is expected to have shape (batch_size, sequence_length, hidden_size).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

A tensor representing the pooled output obtained from the hidden states. It is obtained by applying a dense layer followed by an activation function to the first token's hidden state.

TYPE: Tensor

Source code in mindnlp/transformers/models/luke/luke.py
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def construct(self, hidden_states: Tensor) -> Tensor:
    """
    This method constructs a pooled output tensor based on the hidden states provided.

    Args:
        self: An instance of the LukePooler class.
        hidden_states (Tensor): A tensor containing hidden states from which the pooled output will be constructed.
            It is expected to have shape (batch_size, sequence_length, hidden_size).

    Returns:
        Tensor: A tensor representing the pooled output obtained from the hidden states.
            It is obtained by applying a dense layer followed by an activation function to the
            first token's hidden state.

    Raises:
        None
    """
    # We "pool" the model by simply taking the hidden state corresponding
    # to the first token.
    first_token_tensor = hidden_states[:, 0]
    pooled_output = self.dense(first_token_tensor)
    pooled_output = self.activation(pooled_output)
    return pooled_output

mindnlp.transformers.models.luke.luke.LukePreTrainedModel

Bases: PreTrainedModel

LukePreTrainedModel

Source code in mindnlp/transformers/models/luke/luke.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
class LukePreTrainedModel(PreTrainedModel):
    """
    LukePreTrainedModel
    """
    config_class = LukeConfig
    base_model_prefix = "luke"
    supports_gradient_checkpointing = True
    _no_split_modules = ["LukeAttention", "LukeEntityEmbeddings"]

    def get_input_embeddings(self) -> "nn.Module":
        """
        Method to retrieve the input embeddings for the LukePreTrainedModel.

        Args:
            self: Instance of the LukePreTrainedModel class.
                This parameter refers to the current instance of the LukePreTrainedModel class.
                It is used to access the attributes and methods associated with the instance.

        Returns:
            nn.Module: An object of type nn.Module.
                The return value is the input embeddings of the model stored in an nn.Module object.
                This object contains the embeddings that represent the input data for the model.

        Raises:
            None
        """

    def set_input_embeddings(self, new_embeddings: "nn.Module"):
        """
        This method sets the input embeddings for the LukePreTrainedModel.

        Args:
            self (LukePreTrainedModel): The instance of the LukePreTrainedModel class.
            new_embeddings (nn.Module): The new input embeddings to be set for the model. It should be an instance of 'nn.Module'.

        Returns:
            None.

        Raises:
            None
        """

    def resize_position_embeddings(self, new_num_position_embeddings: int):
        """
        Resize the position embeddings to accommodate a new number of position embeddings in the LukePreTrainedModel.

        Args:
            self (LukePreTrainedModel): The instance of the LukePreTrainedModel class.
            new_num_position_embeddings (int): The new number of position embeddings to resize to.
                Must be a positive integer.

        Returns:
            None.

        Raises:
            None.
        """

    def get_position_embeddings(self):
        """
        This method retrieves the position embeddings for the LukePreTrainedModel.

        Args:
            self: An instance of the LukePreTrainedModel class.

        Returns:
            None.

        Raises:
            None.
        """

    def _init_weights(self, cell: nn.Module):
        """Initialize the weights"""
        if isinstance(cell, nn.Linear):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            cell.weight.set_data(initializer(Normal(self.config.initializer_range),
                                                    cell.weight.shape, cell.weight.dtype))
            if cell.bias:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.Embedding):
            if cell.embedding_size == 1:  # embedding for bias parameters
                cell.weight.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
            else:
                weight = initializer(Normal(self.config.initializer_range),
                                                        cell.weight.shape,
                                                        cell.weight.dtype)
                if cell.padding_idx is not None:
                    weight[cell.padding_idx] = 0
                cell.weight.set_data(weight)
        elif isinstance(cell, nn.LayerNorm):
            cell.weight.set_data(initializer('ones', cell.weight.shape, cell.weight.dtype))
            cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))

mindnlp.transformers.models.luke.luke.LukePreTrainedModel.get_input_embeddings()

Method to retrieve the input embeddings for the LukePreTrainedModel.

PARAMETER DESCRIPTION
self

Instance of the LukePreTrainedModel class. This parameter refers to the current instance of the LukePreTrainedModel class. It is used to access the attributes and methods associated with the instance.

RETURNS DESCRIPTION
Module

nn.Module: An object of type nn.Module. The return value is the input embeddings of the model stored in an nn.Module object. This object contains the embeddings that represent the input data for the model.

Source code in mindnlp/transformers/models/luke/luke.py
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
def get_input_embeddings(self) -> "nn.Module":
    """
    Method to retrieve the input embeddings for the LukePreTrainedModel.

    Args:
        self: Instance of the LukePreTrainedModel class.
            This parameter refers to the current instance of the LukePreTrainedModel class.
            It is used to access the attributes and methods associated with the instance.

    Returns:
        nn.Module: An object of type nn.Module.
            The return value is the input embeddings of the model stored in an nn.Module object.
            This object contains the embeddings that represent the input data for the model.

    Raises:
        None
    """

mindnlp.transformers.models.luke.luke.LukePreTrainedModel.get_position_embeddings()

This method retrieves the position embeddings for the LukePreTrainedModel.

PARAMETER DESCRIPTION
self

An instance of the LukePreTrainedModel class.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
def get_position_embeddings(self):
    """
    This method retrieves the position embeddings for the LukePreTrainedModel.

    Args:
        self: An instance of the LukePreTrainedModel class.

    Returns:
        None.

    Raises:
        None.
    """

mindnlp.transformers.models.luke.luke.LukePreTrainedModel.resize_position_embeddings(new_num_position_embeddings)

Resize the position embeddings to accommodate a new number of position embeddings in the LukePreTrainedModel.

PARAMETER DESCRIPTION
self

The instance of the LukePreTrainedModel class.

TYPE: LukePreTrainedModel

new_num_position_embeddings

The new number of position embeddings to resize to. Must be a positive integer.

TYPE: int

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def resize_position_embeddings(self, new_num_position_embeddings: int):
    """
    Resize the position embeddings to accommodate a new number of position embeddings in the LukePreTrainedModel.

    Args:
        self (LukePreTrainedModel): The instance of the LukePreTrainedModel class.
        new_num_position_embeddings (int): The new number of position embeddings to resize to.
            Must be a positive integer.

    Returns:
        None.

    Raises:
        None.
    """

mindnlp.transformers.models.luke.luke.LukePreTrainedModel.set_input_embeddings(new_embeddings)

This method sets the input embeddings for the LukePreTrainedModel.

PARAMETER DESCRIPTION
self

The instance of the LukePreTrainedModel class.

TYPE: LukePreTrainedModel

new_embeddings

The new input embeddings to be set for the model. It should be an instance of 'nn.Module'.

TYPE: Module

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def set_input_embeddings(self, new_embeddings: "nn.Module"):
    """
    This method sets the input embeddings for the LukePreTrainedModel.

    Args:
        self (LukePreTrainedModel): The instance of the LukePreTrainedModel class.
        new_embeddings (nn.Module): The new input embeddings to be set for the model. It should be an instance of 'nn.Module'.

    Returns:
        None.

    Raises:
        None
    """

mindnlp.transformers.models.luke.luke.LukeSelfAttention

Bases: Module

LukeSelfAttention

Source code in mindnlp/transformers/models/luke/luke.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
class LukeSelfAttention(nn.Module):
    """
    LukeSelfAttention
    """
    def __init__(self, config):
        """
        Initializes a new instance of the LukeSelfAttention class.

        Args:
            self: The instance of the class.
            config: An object containing the configuration parameters for the LukeSelfAttention model.
                It should have the following attributes:

                - hidden_size (int): The hidden size of the model.
                - num_attention_heads (int): The number of attention heads.
                - embedding_size (int, optional): The embedding size. (default: None)
                - use_entity_aware_attention (bool): Whether to use entity-aware attention or not.

        Returns:
            None

        Raises:
            ValueError: If the hidden size is not a multiple of the number of attention heads and the
                config object doesn't have the 'embedding_size' attribute.

        Note:
            The hidden size must be divisible by the number of attention heads.
            If it is not, and the config object doesn't have the 'embedding_size' attribute, a ValueError is raised.
            The 'query', 'key', and 'value' parameters are dense layers used for attention computation.
            If 'use_entity_aware_attention' is True, additional dense layers ('w2e_query', 'e2w_query', and 'e2e_query')
            are used for entity-aware attention.
            The 'dropout' parameter is a dropout layer used for attention probabilities dropout.

        """
        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}."
            )

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

        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)

        if self.use_entity_aware_attention:
            self.w2e_query = nn.Linear(config.hidden_size, self.all_head_size)
            self.e2w_query = nn.Linear(config.hidden_size, self.all_head_size)
            self.e2e_query = nn.Linear(config.hidden_size, self.all_head_size)

        self.dropout = nn.Dropout(p=config.attention_probs_dropout_prob)

    def transpose_for_scores(self, input_x):
        """
        transpose_for_scores
        """
        new_input_x_shape = input_x.shape[:-1] + (self.num_attention_heads, self.attention_head_size)
        input_x = input_x.view(*new_input_x_shape)
        return input_x.permute(0, 2, 1, 3)

    def construct(
            self,
            word_hidden_states,
            entity_hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
    ):
        '''
        Constructs the self-attention mechanism for the LukeSelfAttention class.

        Args:
            self (LukeSelfAttention): An instance of the LukeSelfAttention class.
            word_hidden_states (Tensor): The hidden states of the word input sequence.
                Shape: (batch_size, sequence_length, hidden_size).
            entity_hidden_states (Tensor): The hidden states of the entity input sequence.
                Shape: (batch_size, entity_length, hidden_size).
            attention_mask (Tensor, optional): An optional mask tensor indicating which positions should be attended to
                and which should be ignored. Shape: (batch_size, sequence_length, sequence_length) or
                (batch_size, 1, 1, sequence_length).
            head_mask (Tensor, optional): An optional mask tensor indicating which heads should be masked out of the
                attention calculation. Shape: (num_attention_heads, sequence_length, sequence_length) or
                (batch_size, num_attention_heads, sequence_length, sequence_length).
            output_attentions (bool, optional): Whether to include attention probabilities in the output.
                Defaults to False.

        Returns:
            Tuple[Tensor or None, Tensor or None, Tensor or None]: 
                A tuple containing the output word hidden states, output entity hidden states, and 
                attention probabilities (optional).

                - output_word_hidden_states (Tensor or None): The output hidden states of the word input sequence. 
                Shape: (batch_size, sequence_length, hidden_size).
                - output_entity_hidden_states (Tensor or None): The output hidden states of the entity input sequence. 
                Shape: (batch_size, entity_length, hidden_size).
                - attention_probs (Tensor or None): The attention probabilities. Only included if output_attentions 
                is set to True. Shape: (batch_size, num_attention_heads, sequence_length, sequence_length).

        Raises:
            ValueError: If the shape of word_hidden_states and entity_hidden_states are incompatible.
            ValueError: If the shape of attention_mask is invalid.
            ValueError: If the shape of head_mask is invalid.
        '''
        word_size = word_hidden_states.shape[1]

        if entity_hidden_states is None:
            concat_hidden_states = word_hidden_states
        else:
            concat_hidden_states = ops.cat((word_hidden_states, entity_hidden_states), axis=1)

        key_layer = self.transpose_for_scores(self.key(concat_hidden_states))
        value_layer = self.transpose_for_scores(self.value(concat_hidden_states))

        if self.use_entity_aware_attention and entity_hidden_states is not None:
            # compute query vectors using word-word (w2w), word-entity (w2e), entity-word (e2w), entity-entity (e2e)
            # query layers
            w2w_query_layer = self.transpose_for_scores(self.query(word_hidden_states))
            w2e_query_layer = self.transpose_for_scores(self.w2e_query(word_hidden_states))
            e2w_query_layer = self.transpose_for_scores(self.e2w_query(entity_hidden_states))
            e2e_query_layer = self.transpose_for_scores(self.e2e_query(entity_hidden_states))

            # compute w2w, w2e, e2w, and e2e key vectors used with the query vectors computed above
            w2w_key_layer = key_layer[:, :, :word_size, :]
            e2w_key_layer = key_layer[:, :, :word_size, :]
            w2e_key_layer = key_layer[:, :, word_size:, :]
            e2e_key_layer = key_layer[:, :, word_size:, :]

            # compute attention scores based on the dot product between the query and key vectors
            w2w_attention_scores = ops.matmul(w2w_query_layer, w2w_key_layer.swapaxes(-1, -2))
            w2e_attention_scores = ops.matmul(w2e_query_layer, w2e_key_layer.swapaxes(-1, -2))
            e2w_attention_scores = ops.matmul(e2w_query_layer, e2w_key_layer.swapaxes(-1, -2))
            e2e_attention_scores = ops.matmul(e2e_query_layer, e2e_key_layer.swapaxes(-1, -2))

            # combine attention scores to create the final attention score matrix
            word_attention_scores = ops.cat([w2w_attention_scores, w2e_attention_scores], axis=3)
            entity_attention_scores = ops.cat([e2w_attention_scores, e2e_attention_scores], axis=3)
            attention_scores = ops.cat([word_attention_scores, entity_attention_scores], axis=2)

        else:
            query_layer = self.transpose_for_scores(self.query(concat_hidden_states))
            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 LukeModel 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)
        new_context_layer_shape = context_layer.shape[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(*new_context_layer_shape)

        output_word_hidden_states = context_layer[:, :word_size, :]
        if entity_hidden_states is None:
            output_entity_hidden_states = None
        else:
            output_entity_hidden_states = context_layer[:, word_size:, :]

        if output_attentions:
            outputs = (output_word_hidden_states, output_entity_hidden_states, attention_probs)
        else:
            outputs = (output_word_hidden_states, output_entity_hidden_states)

        return outputs

mindnlp.transformers.models.luke.luke.LukeSelfAttention.__init__(config)

Initializes a new instance of the LukeSelfAttention class.

PARAMETER DESCRIPTION
self

The instance of the class.

config

An object containing the configuration parameters for the LukeSelfAttention model. It should have the following attributes:

  • hidden_size (int): The hidden size of the model.
  • num_attention_heads (int): The number of attention heads.
  • embedding_size (int, optional): The embedding size. (default: None)
  • use_entity_aware_attention (bool): Whether to use entity-aware attention or not.

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the hidden size is not a multiple of the number of attention heads and the config object doesn't have the 'embedding_size' attribute.

Note

The hidden size must be divisible by the number of attention heads. If it is not, and the config object doesn't have the 'embedding_size' attribute, a ValueError is raised. The 'query', 'key', and 'value' parameters are dense layers used for attention computation. If 'use_entity_aware_attention' is True, additional dense layers ('w2e_query', 'e2w_query', and 'e2e_query') are used for entity-aware attention. The 'dropout' parameter is a dropout layer used for attention probabilities dropout.

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

    Args:
        self: The instance of the class.
        config: An object containing the configuration parameters for the LukeSelfAttention model.
            It should have the following attributes:

            - hidden_size (int): The hidden size of the model.
            - num_attention_heads (int): The number of attention heads.
            - embedding_size (int, optional): The embedding size. (default: None)
            - use_entity_aware_attention (bool): Whether to use entity-aware attention or not.

    Returns:
        None

    Raises:
        ValueError: If the hidden size is not a multiple of the number of attention heads and the
            config object doesn't have the 'embedding_size' attribute.

    Note:
        The hidden size must be divisible by the number of attention heads.
        If it is not, and the config object doesn't have the 'embedding_size' attribute, a ValueError is raised.
        The 'query', 'key', and 'value' parameters are dense layers used for attention computation.
        If 'use_entity_aware_attention' is True, additional dense layers ('w2e_query', 'e2w_query', and 'e2e_query')
        are used for entity-aware attention.
        The 'dropout' parameter is a dropout layer used for attention probabilities dropout.

    """
    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}."
        )

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

    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)

    if self.use_entity_aware_attention:
        self.w2e_query = nn.Linear(config.hidden_size, self.all_head_size)
        self.e2w_query = nn.Linear(config.hidden_size, self.all_head_size)
        self.e2e_query = nn.Linear(config.hidden_size, self.all_head_size)

    self.dropout = nn.Dropout(p=config.attention_probs_dropout_prob)

mindnlp.transformers.models.luke.luke.LukeSelfAttention.construct(word_hidden_states, entity_hidden_states, attention_mask=None, head_mask=None, output_attentions=False)

Constructs the self-attention mechanism for the LukeSelfAttention class.

PARAMETER DESCRIPTION
self

An instance of the LukeSelfAttention class.

TYPE: LukeSelfAttention

word_hidden_states

The hidden states of the word input sequence. Shape: (batch_size, sequence_length, hidden_size).

TYPE: Tensor

entity_hidden_states

The hidden states of the entity input sequence. Shape: (batch_size, entity_length, hidden_size).

TYPE: Tensor

attention_mask

An optional mask tensor indicating which positions should be attended to and which should be ignored. Shape: (batch_size, sequence_length, sequence_length) or (batch_size, 1, 1, sequence_length).

TYPE: Tensor DEFAULT: None

head_mask

An optional mask tensor indicating which heads should be masked out of the attention calculation. Shape: (num_attention_heads, sequence_length, sequence_length) or (batch_size, num_attention_heads, sequence_length, sequence_length).

TYPE: Tensor DEFAULT: None

output_attentions

Whether to include attention probabilities in the output. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

Tuple[Tensor or None, Tensor or None, Tensor or None]: A tuple containing the output word hidden states, output entity hidden states, and attention probabilities (optional).

  • output_word_hidden_states (Tensor or None): The output hidden states of the word input sequence. Shape: (batch_size, sequence_length, hidden_size).
  • output_entity_hidden_states (Tensor or None): The output hidden states of the entity input sequence. Shape: (batch_size, entity_length, hidden_size).
  • attention_probs (Tensor or None): The attention probabilities. Only included if output_attentions is set to True. Shape: (batch_size, num_attention_heads, sequence_length, sequence_length).
RAISES DESCRIPTION
ValueError

If the shape of word_hidden_states and entity_hidden_states are incompatible.

ValueError

If the shape of attention_mask is invalid.

ValueError

If the shape of head_mask is invalid.

Source code in mindnlp/transformers/models/luke/luke.py
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
def construct(
        self,
        word_hidden_states,
        entity_hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
):
    '''
    Constructs the self-attention mechanism for the LukeSelfAttention class.

    Args:
        self (LukeSelfAttention): An instance of the LukeSelfAttention class.
        word_hidden_states (Tensor): The hidden states of the word input sequence.
            Shape: (batch_size, sequence_length, hidden_size).
        entity_hidden_states (Tensor): The hidden states of the entity input sequence.
            Shape: (batch_size, entity_length, hidden_size).
        attention_mask (Tensor, optional): An optional mask tensor indicating which positions should be attended to
            and which should be ignored. Shape: (batch_size, sequence_length, sequence_length) or
            (batch_size, 1, 1, sequence_length).
        head_mask (Tensor, optional): An optional mask tensor indicating which heads should be masked out of the
            attention calculation. Shape: (num_attention_heads, sequence_length, sequence_length) or
            (batch_size, num_attention_heads, sequence_length, sequence_length).
        output_attentions (bool, optional): Whether to include attention probabilities in the output.
            Defaults to False.

    Returns:
        Tuple[Tensor or None, Tensor or None, Tensor or None]: 
            A tuple containing the output word hidden states, output entity hidden states, and 
            attention probabilities (optional).

            - output_word_hidden_states (Tensor or None): The output hidden states of the word input sequence. 
            Shape: (batch_size, sequence_length, hidden_size).
            - output_entity_hidden_states (Tensor or None): The output hidden states of the entity input sequence. 
            Shape: (batch_size, entity_length, hidden_size).
            - attention_probs (Tensor or None): The attention probabilities. Only included if output_attentions 
            is set to True. Shape: (batch_size, num_attention_heads, sequence_length, sequence_length).

    Raises:
        ValueError: If the shape of word_hidden_states and entity_hidden_states are incompatible.
        ValueError: If the shape of attention_mask is invalid.
        ValueError: If the shape of head_mask is invalid.
    '''
    word_size = word_hidden_states.shape[1]

    if entity_hidden_states is None:
        concat_hidden_states = word_hidden_states
    else:
        concat_hidden_states = ops.cat((word_hidden_states, entity_hidden_states), axis=1)

    key_layer = self.transpose_for_scores(self.key(concat_hidden_states))
    value_layer = self.transpose_for_scores(self.value(concat_hidden_states))

    if self.use_entity_aware_attention and entity_hidden_states is not None:
        # compute query vectors using word-word (w2w), word-entity (w2e), entity-word (e2w), entity-entity (e2e)
        # query layers
        w2w_query_layer = self.transpose_for_scores(self.query(word_hidden_states))
        w2e_query_layer = self.transpose_for_scores(self.w2e_query(word_hidden_states))
        e2w_query_layer = self.transpose_for_scores(self.e2w_query(entity_hidden_states))
        e2e_query_layer = self.transpose_for_scores(self.e2e_query(entity_hidden_states))

        # compute w2w, w2e, e2w, and e2e key vectors used with the query vectors computed above
        w2w_key_layer = key_layer[:, :, :word_size, :]
        e2w_key_layer = key_layer[:, :, :word_size, :]
        w2e_key_layer = key_layer[:, :, word_size:, :]
        e2e_key_layer = key_layer[:, :, word_size:, :]

        # compute attention scores based on the dot product between the query and key vectors
        w2w_attention_scores = ops.matmul(w2w_query_layer, w2w_key_layer.swapaxes(-1, -2))
        w2e_attention_scores = ops.matmul(w2e_query_layer, w2e_key_layer.swapaxes(-1, -2))
        e2w_attention_scores = ops.matmul(e2w_query_layer, e2w_key_layer.swapaxes(-1, -2))
        e2e_attention_scores = ops.matmul(e2e_query_layer, e2e_key_layer.swapaxes(-1, -2))

        # combine attention scores to create the final attention score matrix
        word_attention_scores = ops.cat([w2w_attention_scores, w2e_attention_scores], axis=3)
        entity_attention_scores = ops.cat([e2w_attention_scores, e2e_attention_scores], axis=3)
        attention_scores = ops.cat([word_attention_scores, entity_attention_scores], axis=2)

    else:
        query_layer = self.transpose_for_scores(self.query(concat_hidden_states))
        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 LukeModel 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)
    new_context_layer_shape = context_layer.shape[:-2] + (self.all_head_size,)
    context_layer = context_layer.view(*new_context_layer_shape)

    output_word_hidden_states = context_layer[:, :word_size, :]
    if entity_hidden_states is None:
        output_entity_hidden_states = None
    else:
        output_entity_hidden_states = context_layer[:, word_size:, :]

    if output_attentions:
        outputs = (output_word_hidden_states, output_entity_hidden_states, attention_probs)
    else:
        outputs = (output_word_hidden_states, output_entity_hidden_states)

    return outputs

mindnlp.transformers.models.luke.luke.LukeSelfAttention.transpose_for_scores(input_x)

transpose_for_scores

Source code in mindnlp/transformers/models/luke/luke.py
275
276
277
278
279
280
281
def transpose_for_scores(self, input_x):
    """
    transpose_for_scores
    """
    new_input_x_shape = input_x.shape[:-1] + (self.num_attention_heads, self.attention_head_size)
    input_x = input_x.view(*new_input_x_shape)
    return input_x.permute(0, 2, 1, 3)

mindnlp.transformers.models.luke.luke.LukeSelfOutput

Bases: Module

LukeSelfOutput

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

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

                - 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 hidden layers.

        Returns:
            None.

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

    def construct(self, hidden_states: Tensor, input_tensor: Tensor) -> Tensor:
        """
        Constructs the output of the self-attention layer in the Luke model.

        Args:
            self: The instance of the LukeSelfOutput class.
            hidden_states (Tensor): The hidden states of the self-attention layer.
                Shape: (batch_size, sequence_length, hidden_size).
            input_tensor (Tensor): The input tensor to be added to the output of the layer normalization.
                Shape: (batch_size, sequence_length, hidden_size).

        Returns:
            Tensor: The output tensor of the self-attention layer.
                Shape: (batch_size, sequence_length, hidden_size).

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

mindnlp.transformers.models.luke.luke.LukeSelfOutput.__init__(config)

Initializes an instance of the LukeSelfOutput class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

config

An object containing configuration parameters.

  • 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 hidden layers.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/luke/luke.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def __init__(self, config):
    """
    Initializes an instance of the LukeSelfOutput class.

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

            - 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 hidden layers.

    Returns:
        None.

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

mindnlp.transformers.models.luke.luke.LukeSelfOutput.construct(hidden_states, input_tensor)

Constructs the output of the self-attention layer in the Luke model.

PARAMETER DESCRIPTION
self

The instance of the LukeSelfOutput class.

hidden_states

The hidden states of the self-attention layer. Shape: (batch_size, sequence_length, hidden_size).

TYPE: Tensor

input_tensor

The input tensor to be added to the output of the layer normalization. Shape: (batch_size, sequence_length, hidden_size).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The output tensor of the self-attention layer. Shape: (batch_size, sequence_length, hidden_size).

TYPE: Tensor

Source code in mindnlp/transformers/models/luke/luke.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def construct(self, hidden_states: Tensor, input_tensor: Tensor) -> Tensor:
    """
    Constructs the output of the self-attention layer in the Luke model.

    Args:
        self: The instance of the LukeSelfOutput class.
        hidden_states (Tensor): The hidden states of the self-attention layer.
            Shape: (batch_size, sequence_length, hidden_size).
        input_tensor (Tensor): The input tensor to be added to the output of the layer normalization.
            Shape: (batch_size, sequence_length, hidden_size).

    Returns:
        Tensor: The output tensor of the self-attention layer.
            Shape: (batch_size, sequence_length, hidden_size).

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

mindnlp.transformers.models.luke.luke.apply_chunking_to_forward(forward_fn, chunk_size, chunk_dim, *input_tensors)

This function chunks the input_tensors into smaller input tensor parts of size chunk_size over the dimension chunk_dim. It then applies a layer forward_fn to each chunk independently to save memory.

Source code in mindnlp/transformers/models/luke/luke.py
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
def apply_chunking_to_forward(
        forward_fn: Callable[..., mindspore.Tensor], chunk_size: int, chunk_dim: int, *input_tensors
) -> mindspore.Tensor:
    """
    This function chunks the `input_tensors` into smaller input tensor parts
    of size `chunk_size` over the dimension
    `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory.
    """
    assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors"

    # inspect.signature exist since python 3.5 and is a python method
    # -> no problem with backward compatibility
    num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters)
    if num_args_in_forward_chunk_fn != len(input_tensors):
        raise ValueError(
            f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input "
            "tensors are given"
        )

    if chunk_size > 0:
        tensor_shape = input_tensors[0].shape[chunk_dim]
        for input_tensor in input_tensors:
            if input_tensor.shape[chunk_dim] != tensor_shape:
                raise ValueError(
                    f"All input tenors have to be of the same shape: {tensor_shape}, "
                    f"found shape {input_tensor.shape[chunk_dim]}"
                )

        if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
            raise ValueError(
                f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk "
                f"size {chunk_size}"
            )

        num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size

        # chunk input tensor into tuples
        input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors)
        # apply forward fn to every tuple
        output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks))
        # concatenate output at same dimension
        return ops.cat(output_chunks, axis=chunk_dim)

    return forward_fn(*input_tensors)

mindnlp.transformers.models.luke.luke.create_position_ids_from_input_ids(input_ids, padding_idx)

Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's utils.make_positions.

Source code in mindnlp/transformers/models/luke/luke.py
1389
1390
1391
1392
1393
1394
1395
1396
def create_position_ids_from_input_ids(input_ids, padding_idx):
    """
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's `utils.make_positions`.
    """
    mask = ops.not_equal(input_ids, padding_idx).astype(mindspore.int32)
    incremental_indices = ops.cumsum(mask, -1).astype(mindspore.int32) * mask
    return incremental_indices.astype(mindspore.int64) + padding_idx

mindnlp.transformers.models.luke.luke_config

LUKE configuration

mindnlp.transformers.models.luke.luke_config.LukeConfig

Bases: PretrainedConfig

Configurations for Luke

Source code in mindnlp/transformers/models/luke/luke_config.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class LukeConfig(PretrainedConfig):
    """
    Configurations for Luke
    """
    def __init__(
            self,
            vocab_size=100,
            entity_vocab_size=500,
            hidden_size=128,
            entity_emb_size=256,
            num_hidden_layers=12,
            num_attention_heads=16,
            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,
            use_entity_aware_attention=True,
            classifier_dropout=None,
            pad_token_id=1,
            bos_token_id=0,
            eos_token_id=2,
            **kwargs,
    ):
        """Constructs LukeConfig."""
        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.entity_vocab_size = entity_vocab_size
        self.hidden_size = hidden_size
        self.entity_emb_size = entity_emb_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.hidden_act = hidden_act
        self.intermediate_size = intermediate_size
        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.use_entity_aware_attention = use_entity_aware_attention
        self.classifier_dropout = classifier_dropout

mindnlp.transformers.models.luke.luke_config.LukeConfig.__init__(vocab_size=100, entity_vocab_size=500, hidden_size=128, entity_emb_size=256, num_hidden_layers=12, num_attention_heads=16, 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, use_entity_aware_attention=True, classifier_dropout=None, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs)

Constructs LukeConfig.

Source code in mindnlp/transformers/models/luke/luke_config.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def __init__(
        self,
        vocab_size=100,
        entity_vocab_size=500,
        hidden_size=128,
        entity_emb_size=256,
        num_hidden_layers=12,
        num_attention_heads=16,
        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,
        use_entity_aware_attention=True,
        classifier_dropout=None,
        pad_token_id=1,
        bos_token_id=0,
        eos_token_id=2,
        **kwargs,
):
    """Constructs LukeConfig."""
    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.entity_vocab_size = entity_vocab_size
    self.hidden_size = hidden_size
    self.entity_emb_size = entity_emb_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.hidden_act = hidden_act
    self.intermediate_size = intermediate_size
    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.use_entity_aware_attention = use_entity_aware_attention
    self.classifier_dropout = classifier_dropout

mindnlp.transformers.models.luke.tokenization_luke

Tokenization classes for LUKE.

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer

Bases: PreTrainedTokenizer

Constructs a LUKE tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beginning of the sentence (without space) or not:

Example
>>> from transformers import LukeTokenizer
...
>>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base")
>>> tokenizer("Hello world")["input_ids"]
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")["input_ids"]
[0, 20920, 232, 2]

You can get around that behavior by passing add_prefix_space=True when instantiating this tokenizer or when you call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

When used with is_split_into_words=True, this tokenizer will add a space before each word (even the first one).

This tokenizer inherits from [PreTrainedTokenizer] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. It also creates entity sequences, namely entity_ids, entity_attention_mask, entity_token_type_ids, and entity_position_ids to be used by the LUKE model.

PARAMETER DESCRIPTION
vocab_file

Path to the vocabulary file.

TYPE: `str`

merges_file

Path to the merges file.

TYPE: `str`

entity_vocab_file

Path to the entity vocabulary file.

TYPE: `str`

task

Task for which you want to prepare sequences. One of "entity_classification", "entity_pair_classification", or "entity_span_classification". If you specify this argument, the entity sequence is automatically created based on the given entity span(s).

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

max_entity_length

The maximum length of entity_ids.

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

max_mention_length

The maximum number of tokens inside an entity span.

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

entity_token_1

The special token used to represent an entity span in a word token sequence. This token is only used when task is set to "entity_classification" or "entity_pair_classification".

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

entity_token_2

The special token used to represent an entity span in a word token sequence. This token is only used when task is set to "entity_pair_classification".

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

errors

Paradigm to follow when decoding bytes to UTF-8. See bytes.decode for more information.

TYPE: `str`, *optional*, defaults to `"replace"` DEFAULT: 'replace'

bos_token

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

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

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

eos_token

The end of sequence token.

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

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

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 `"</s>"` DEFAULT: '</s>'

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 `"<s>"` DEFAULT: '<s>'

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

pad_token

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

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

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

add_prefix_space

Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (LUKE tokenizer detect beginning of words by the preceding space).

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 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
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
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
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
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
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
class LukeTokenizer(PreTrainedTokenizer):
    """
    Constructs a LUKE tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.

    This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
    be encoded differently whether it is at the beginning of the sentence (without space) or not:

    Example:
        ```python
        >>> from transformers import LukeTokenizer
        ...
        >>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base")
        >>> tokenizer("Hello world")["input_ids"]
        [0, 31414, 232, 2]
        >>> tokenizer(" Hello world")["input_ids"]
        [0, 20920, 232, 2]
        ```

    You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
    call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

    <Tip>

    When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).

    </Tip>

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    this superclass for more information regarding those methods. It also creates entity sequences, namely
    `entity_ids`, `entity_attention_mask`, `entity_token_type_ids`, and `entity_position_ids` to be used by the LUKE
    model.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        entity_vocab_file (`str`):
            Path to the entity vocabulary file.
        task (`str`, *optional*):
            Task for which you want to prepare sequences. One of `"entity_classification"`,
            `"entity_pair_classification"`, or `"entity_span_classification"`. If you specify this argument, the entity
            sequence is automatically created based on the given entity span(s).
        max_entity_length (`int`, *optional*, defaults to 32):
            The maximum length of `entity_ids`.
        max_mention_length (`int`, *optional*, defaults to 30):
            The maximum number of tokens inside an entity span.
        entity_token_1 (`str`, *optional*, defaults to `<ent>`):
            The special token used to represent an entity span in a word token sequence. This token is only used when
            `task` is set to `"entity_classification"` or `"entity_pair_classification"`.
        entity_token_2 (`str`, *optional*, defaults to `<ent2>`):
            The special token used to represent an entity span in a word token sequence. This token is only used when
            `task` is set to `"entity_pair_classification"`.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

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

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            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.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            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.
        unk_token (`str`, *optional*, defaults to `"<unk>"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        mask_token (`str`, *optional*, defaults to `"<mask>"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word. (LUKE tokenizer detect beginning of words by the preceding space).
    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        merges_file,
        entity_vocab_file,
        task=None,
        max_entity_length=32,
        max_mention_length=30,
        entity_token_1="<ent>",
        entity_token_2="<ent2>",
        entity_unk_token="[UNK]",
        entity_pad_token="[PAD]",
        entity_mask_token="[MASK]",
        entity_mask2_token="[MASK2]",
        errors="replace",
        bos_token="<s>",
        eos_token="</s>",
        sep_token="</s>",
        cls_token="<s>",
        unk_token="<unk>",
        pad_token="<pad>",
        mask_token="<mask>",
        add_prefix_space=False,
        **kwargs,
    ):
        """Initialize the LukeTokenizer class.

        This method initializes an instance of the LukeTokenizer class. It takes the following parameters:

        Args:
            self: The instance of the class.
            vocab_file (str): The path to the vocabulary file.
            merges_file (str): The path to the merges file.
            entity_vocab_file (str): The path to the entity vocabulary file.
            task (str, optional): The task for which the tokenizer is used. Defaults to None.
            max_entity_length (int, optional): The maximum length of the entity. Defaults to 32.
            max_mention_length (int, optional): The maximum length of the mention. Defaults to 30.
            entity_token_1 (str, optional): The first entity token. Defaults to '<ent>'.
            entity_token_2 (str, optional): The second entity token. Defaults to '<ent2>'.
            entity_unk_token (str, optional): The unknown entity token. Defaults to '[UNK]'.
            entity_pad_token (str, optional): The padding entity token. Defaults to '[PAD]'.
            entity_mask_token (str, optional): The masked entity token. Defaults to '[MASK]'.
            entity_mask2_token (str, optional): The second masked entity token. Defaults to '[MASK2]'.
            errors (str, optional): The error handling strategy. Defaults to 'replace'.
            bos_token (str, optional): The beginning of sentence token. Defaults to '<s>'.
            eos_token (str, optional): The end of sentence token. Defaults to '</s>'.
            sep_token (str, optional): The separator token. Defaults to '</s>'.
            cls_token (str, optional): The classification token. Defaults to '<s>'.
            unk_token (str, optional): The unknown token. Defaults to '<unk>'.
            pad_token (str, optional): The padding token. Defaults to '<pad>'.
            mask_token (str, optional): The masked token. Defaults to '<mask>'.
            add_prefix_space (bool, optional): Whether to add space before the token. Defaults to False.

        Returns:
            None

        Raises:
            ValueError: If the specified entity special token is not found in the entity vocabulary file.
            ValueError: If the task is not supported. Select task from ['entity_classification',
                'entity_pair_classification', 'entity_span_classification'] only.
        """
        bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
        eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
        sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
        cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
        unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
        pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token

        # Mask token behave like a normal word, i.e. include the space before it
        mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token

        with open(vocab_file, encoding="utf-8") as vocab_handle:
            self.encoder = json.load(vocab_handle)
        self.decoder = {v: k for k, v in self.encoder.items()}
        self.errors = errors  # how to handle errors in decoding
        self.byte_encoder = bytes_to_unicode()
        self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
        with open(merges_file, encoding="utf-8") as merges_handle:
            bpe_merges = merges_handle.read().split("\n")[1:-1]
        bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
        self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
        self.cache = {}
        self.add_prefix_space = add_prefix_space

        # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
        self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")

        # we add 2 special tokens for downstream tasks
        # for more information about lstrip and rstrip, see https://github.com/huggingface/transformers/pull/2778
        entity_token_1 = (
            AddedToken(entity_token_1, lstrip=False, rstrip=False)
            if isinstance(entity_token_1, str)
            else entity_token_1
        )
        entity_token_2 = (
            AddedToken(entity_token_2, lstrip=False, rstrip=False)
            if isinstance(entity_token_2, str)
            else entity_token_2
        )
        kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", [])
        kwargs["additional_special_tokens"] += [entity_token_1, entity_token_2]

        with open(entity_vocab_file, encoding="utf-8") as entity_vocab_handle:
            self.entity_vocab = json.load(entity_vocab_handle)
        for entity_special_token in [entity_unk_token, entity_pad_token, entity_mask_token, entity_mask2_token]:
            if entity_special_token not in self.entity_vocab:
                raise ValueError(
                    f"Specified entity special token ``{entity_special_token}`` is not found in entity_vocab. "
                    f"Probably an incorrect entity vocab file is loaded: {entity_vocab_file}."
                )
        self.entity_unk_token_id = self.entity_vocab[entity_unk_token]
        self.entity_pad_token_id = self.entity_vocab[entity_pad_token]
        self.entity_mask_token_id = self.entity_vocab[entity_mask_token]
        self.entity_mask2_token_id = self.entity_vocab[entity_mask2_token]

        self.task = task
        if task is None or task == "entity_span_classification":
            self.max_entity_length = max_entity_length
        elif task == "entity_classification":
            self.max_entity_length = 1
        elif task == "entity_pair_classification":
            self.max_entity_length = 2
        else:
            raise ValueError(
                f"Task {task} not supported. Select task from ['entity_classification', 'entity_pair_classification',"
                " 'entity_span_classification'] only."
            )

        self.max_mention_length = max_mention_length

        super().__init__(
            errors=errors,
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            sep_token=sep_token,
            cls_token=cls_token,
            pad_token=pad_token,
            mask_token=mask_token,
            add_prefix_space=add_prefix_space,
            task=task,
            max_entity_length=32,
            max_mention_length=30,
            entity_token_1="<ent>",
            entity_token_2="<ent2>",
            entity_unk_token=entity_unk_token,
            entity_pad_token=entity_pad_token,
            entity_mask_token=entity_mask_token,
            entity_mask2_token=entity_mask2_token,
            **kwargs,
        )

    @property
    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Luke, RoBERTa->LUKE
    def vocab_size(self):
        """
        Returns the size of the vocabulary.

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

        Returns:
            int: The number of items in the encoder, representing the size of the vocabulary.

        Raises:
            None.
        """
        return len(self.encoder)

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_vocab with Roberta->Luke, RoBERTa->LUKE
    def get_vocab(self):
        """
        Retrieves the vocabulary dictionary for the 'LukeTokenizer' class.

        Args:
            self: An instance of the 'LukeTokenizer' class.

        Returns:
            dict: A dictionary containing the vocabulary of the tokenizer. The keys are the tokens
                and the values are their corresponding IDs.

        Raises:
            None.
        """
        vocab = dict(self.encoder).copy()
        vocab.update(self.added_tokens_encoder)
        return vocab

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.bpe with Roberta->Luke, RoBERTa->LUKE
    def bpe(self, token):
        """
        This method 'bpe' in the class 'LukeTokenizer' performs Byte Pair Encoding (BPE) on the input token.

        Args:
            self (LukeTokenizer): The instance of the LukeTokenizer class.
            token (str): The input token to be processed using Byte Pair Encoding.

        Returns:
            str: The processed token after applying Byte Pair Encoding.

        Raises:
            ValueError: If the input token is empty.
            TypeError: If the input token is not a string.
        """
        if token in self.cache:
            return self.cache[token]
        word = tuple(token)
        pairs = get_pairs(word)

        if not pairs:
            return token

        while True:
            bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
            if bigram not in self.bpe_ranks:
                break
            first, second = bigram
            new_word = []
            i = 0
            while i < len(word):
                try:
                    j = word.index(first, i)
                except ValueError:
                    new_word.extend(word[i:])
                    break
                else:
                    new_word.extend(word[i:j])
                    i = j

                if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
                    new_word.append(first + second)
                    i += 2
                else:
                    new_word.append(word[i])
                    i += 1
            new_word = tuple(new_word)
            word = new_word
            if len(word) == 1:
                break
            pairs = get_pairs(word)
        word = " ".join(word)
        self.cache[token] = word
        return word

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._tokenize with Roberta->Luke, RoBERTa->LUKE
    def _tokenize(self, text):
        """Tokenize a string."""
        bpe_tokens = []
        for token in re.findall(self.pat, text):
            token = "".join(
                self.byte_encoder[b] for b in token.encode("utf-8")
            )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
            bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
        return bpe_tokens

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_token_to_id with Roberta->Luke, RoBERTa->LUKE
    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.encoder.get(token, self.encoder.get(self.unk_token))

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_id_to_token with Roberta->Luke, RoBERTa->LUKE
    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        return self.decoder.get(index)

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.convert_tokens_to_string with Roberta->Luke, RoBERTa->LUKE
    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        text = "".join(tokens)
        text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
        return text

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.build_inputs_with_special_tokens with Roberta->Luke, RoBERTa->LUKE
    def build_inputs_with_special_tokens(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A LUKE sequence has the following format:

        - single sequence: `<s> X </s>`
        - pair of sequences: `<s> A </s></s> B </s>`

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

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """
        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
        cls = [self.cls_token_id]
        sep = [self.sep_token_id]
        return cls + token_ids_0 + sep + sep + token_ids_1 + sep

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_special_tokens_mask with Roberta->Luke, RoBERTa->LUKE
    def get_special_tokens_mask(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
    ) -> List[int]:
        """
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

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

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        """
        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
            )

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

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.create_token_type_ids_from_sequences with Roberta->Luke, RoBERTa->LUKE
    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. LUKE does not
        make use of token type ids, therefore a list of zeros is returned.

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

        Returns:
            `List[int]`: List of zeros.
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]

        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

    # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.prepare_for_tokenization with Roberta->Luke, RoBERTa->LUKE
    def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
        """
        Prepares the input text for tokenization by adding a prefix space if necessary.

        Args:
            self (LukeTokenizer): An instance of the LukeTokenizer class.
            text (str): The input text to be tokenized.
            is_split_into_words (bool): A flag indicating if the input text is already split into words.
                Defaults to False.

        Returns:
            None: The method modifies the input text in-place.

        Raises:
            None.
        """
        add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
        if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
            text = " " + text
        return (text, kwargs)

    def __call__(
        self,
        text: Union[TextInput, List[TextInput]],
        text_pair: Optional[Union[TextInput, List[TextInput]]] = None,
        entity_spans: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
        entity_spans_pair: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
        entities: Optional[Union[EntityInput, List[EntityInput]]] = None,
        entities_pair: Optional[Union[EntityInput, List[EntityInput]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        stride: int = 0,
        is_split_into_words: Optional[bool] = False,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
        **kwargs,
    ) -> BatchEncoding:
        """
        Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
        sequences, depending on the task you want to prepare them for.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
                tokenizer does not support tokenization based on pretokenized strings.
            text_pair (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
                tokenizer does not support tokenization based on pretokenized strings.
            entity_spans (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
                The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
                with two integers denoting character-based start and end positions of entities. If you specify
                `"entity_classification"` or `"entity_pair_classification"` as the `task` argument in the forwardor,
                the length of each sequence must be 1 or 2, respectively. If you specify `entities`, the length of each
                sequence must be equal to the length of each sequence of `entities`.
            entity_spans_pair (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
                The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
                with two integers denoting character-based start and end positions of entities. If you specify the
                `task` argument in the forwardor, this argument is ignored. If you specify `entities_pair`, the
                length of each sequence must be equal to the length of each sequence of `entities_pair`.
            entities (`List[str]`, `List[List[str]]`, *optional*):
                The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
                representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
                Angeles). This argument is ignored if you specify the `task` argument in the forwardor. The length of
                each sequence must be equal to the length of each sequence of `entity_spans`. If you specify
                `entity_spans` without specifying this argument, the entity sequence or the batch of entity sequences
                is automatically forwarded by filling it with the [MASK] entity.
            entities_pair (`List[str]`, `List[List[str]]`, *optional*):
                The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
                representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
                Angeles). This argument is ignored if you specify the `task` argument in the forwardor. The length of
                each sequence must be equal to the length of each sequence of `entity_spans_pair`. If you specify
                `entity_spans_pair` without specifying this argument, the entity sequence or the batch of entity
                sequences is automatically forwarded by filling it with the [MASK] entity.
            max_entity_length (`int`, *optional*):
                The maximum length of `entity_ids`.
        """
        # Input type checking for clearer error
        is_valid_single_text = isinstance(text, str)
        is_valid_batch_text = isinstance(text, (list, tuple)) and (len(text) == 0 or (isinstance(text[0], str)))
        if not (is_valid_single_text or is_valid_batch_text):
            raise ValueError("text input must be of type `str` (single example) or `List[str]` (batch).")

        is_valid_single_text_pair = isinstance(text_pair, str)
        is_valid_batch_text_pair = isinstance(text_pair, (list, tuple)) and (
            len(text_pair) == 0 or isinstance(text_pair[0], str)
        )
        if not (text_pair is None or is_valid_single_text_pair or is_valid_batch_text_pair):
            raise ValueError("text_pair input must be of type `str` (single example) or `List[str]` (batch).")

        is_batched = bool(isinstance(text, (list, tuple)))

        if is_batched:
            batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
            if entities is None:
                batch_entities_or_entities_pairs = None
            else:
                batch_entities_or_entities_pairs = (
                    list(zip(entities, entities_pair)) if entities_pair is not None else entities
                )

            if entity_spans is None:
                batch_entity_spans_or_entity_spans_pairs = None
            else:
                batch_entity_spans_or_entity_spans_pairs = (
                    list(zip(entity_spans, entity_spans_pair)) if entity_spans_pair is not None else entity_spans
                )

            return self.batch_encode_plus(
                batch_text_or_text_pairs=batch_text_or_text_pairs,
                batch_entity_spans_or_entity_spans_pairs=batch_entity_spans_or_entity_spans_pairs,
                batch_entities_or_entities_pairs=batch_entities_or_entities_pairs,
                add_special_tokens=add_special_tokens,
                padding=padding,
                truncation=truncation,
                max_length=max_length,
                max_entity_length=max_entity_length,
                stride=stride,
                is_split_into_words=is_split_into_words,
                pad_to_multiple_of=pad_to_multiple_of,
                return_tensors=return_tensors,
                return_token_type_ids=return_token_type_ids,
                return_attention_mask=return_attention_mask,
                return_overflowing_tokens=return_overflowing_tokens,
                return_special_tokens_mask=return_special_tokens_mask,
                return_offsets_mapping=return_offsets_mapping,
                return_length=return_length,
                verbose=verbose,
                **kwargs,
            )
        return self.encode_plus(
            text=text,
            text_pair=text_pair,
            entity_spans=entity_spans,
            entity_spans_pair=entity_spans_pair,
            entities=entities,
            entities_pair=entities_pair,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            max_entity_length=max_entity_length,
            stride=stride,
            is_split_into_words=is_split_into_words,
            pad_to_multiple_of=pad_to_multiple_of,
            return_tensors=return_tensors,
            return_token_type_ids=return_token_type_ids,
            return_attention_mask=return_attention_mask,
            return_overflowing_tokens=return_overflowing_tokens,
            return_special_tokens_mask=return_special_tokens_mask,
            return_offsets_mapping=return_offsets_mapping,
            return_length=return_length,
            verbose=verbose,
            **kwargs,
        )

    def _encode_plus(
        self,
        text: TextInput,
        text_pair: Optional[TextInput] = None,
        entity_spans: Optional[EntitySpanInput] = None,
        entity_spans_pair: Optional[EntitySpanInput] = None,
        entities: Optional[EntityInput] = None,
        entities_pair: Optional[EntityInput] = None,
        add_special_tokens: bool = True,
        padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
        truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        stride: int = 0,
        is_split_into_words: Optional[bool] = False,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
        **kwargs,
    ) -> BatchEncoding:
        """Encodes the inputs for the LukeTokenizer.

        Args:
            self (LukeTokenizer): The instance of the LukeTokenizer class.
            text (TextInput): The input text to be encoded. It can be a single sentence or a sequence of sentences.
            text_pair (Optional[TextInput], optional): The second input text to be encoded.
                It can be a single sentence or a sequence of sentences. Defaults to None.
            entity_spans (Optional[EntitySpanInput], optional): The input entity spans to be encoded. Defaults to None.
            entity_spans_pair (Optional[EntitySpanInput], optional): The second input entity spans to be encoded.
                Defaults to None.
            entities (Optional[EntityInput], optional): The input entities to be encoded. Defaults to None.
            entities_pair (Optional[EntityInput], optional): The second input entities to be encoded. Defaults to None.
            add_special_tokens (bool, optional): Whether to add special tokens to the encoded inputs. Defaults to True.
            padding_strategy (PaddingStrategy, optional): The strategy to use for padding.
                Defaults to PaddingStrategy.DO_NOT_PAD.
            truncation_strategy (TruncationStrategy, optional): The strategy to use for truncation.
                Defaults to TruncationStrategy.DO_NOT_TRUNCATE.
            max_length (Optional[int], optional): The maximum sequence length after encoding. Defaults to None.
            max_entity_length (Optional[int], optional): The maximum entity span length after encoding. Defaults to None.
            stride (int, optional): The stride to use for overflowing tokens. Defaults to 0.
            is_split_into_words (Optional[bool], optional): Whether the input text is already split into words.
                Defaults to False.
            pad_to_multiple_of (Optional[int], optional): The padding length will be a multiple of this value.
                Defaults to None.
            return_tensors (Optional[Union[str, TensorType]], optional): The type of tensors to return. Defaults to None.
            return_token_type_ids (Optional[bool], optional): Whether to return token type IDs. Defaults to None.
            return_attention_mask (Optional[bool], optional): Whether to return attention masks. Defaults to None.
            return_overflowing_tokens (bool, optional): Whether to return the overflowing tokens. Defaults to False.
            return_special_tokens_mask (bool, optional): Whether to return the special tokens mask. Defaults to False.
            return_offsets_mapping (bool, optional): Whether to return the offsets mapping. Defaults to False.
            return_length (bool, optional): Whether to return the length of the encoded inputs. Defaults to False.
            verbose (bool, optional): Whether to print verbose logs. Defaults to True.
            **kwargs: Additional keyword arguments.

        Returns:
            BatchEncoding: The encoded inputs as a BatchEncoding object.

        Raises:
            NotImplementedError: If return_offsets_mapping is requested.
            NotImplementedError: If is_split_into_words is True and not supported by the tokenizer.
        """
        if return_offsets_mapping:
            raise NotImplementedError(
                "return_offset_mapping is not available when using Python tokenizers. "
                "To use this feature, change your tokenizer to one deriving from "
                "transformers.PreTrainedTokenizerFast. "
                "More information on available tokenizers at "
                "https://github.com/huggingface/transformers/pull/2674"
            )

        if is_split_into_words:
            raise NotImplementedError("is_split_into_words is not supported in this tokenizer.")

        (
            first_ids,
            second_ids,
            first_entity_ids,
            second_entity_ids,
            first_entity_token_spans,
            second_entity_token_spans,
        ) = self._create_input_sequence(
            text=text,
            text_pair=text_pair,
            entities=entities,
            entities_pair=entities_pair,
            entity_spans=entity_spans,
            entity_spans_pair=entity_spans_pair,
            **kwargs,
        )

        # prepare_for_model will create the attention_mask and token_type_ids
        return self.prepare_for_model(
            first_ids,
            pair_ids=second_ids,
            entity_ids=first_entity_ids,
            pair_entity_ids=second_entity_ids,
            entity_token_spans=first_entity_token_spans,
            pair_entity_token_spans=second_entity_token_spans,
            add_special_tokens=add_special_tokens,
            padding=padding_strategy.value,
            truncation=truncation_strategy.value,
            max_length=max_length,
            max_entity_length=max_entity_length,
            stride=stride,
            pad_to_multiple_of=pad_to_multiple_of,
            return_tensors=return_tensors,
            prepend_batch_axis=True,
            return_attention_mask=return_attention_mask,
            return_token_type_ids=return_token_type_ids,
            return_overflowing_tokens=return_overflowing_tokens,
            return_special_tokens_mask=return_special_tokens_mask,
            return_length=return_length,
            verbose=verbose,
        )

    def _batch_encode_plus(
        self,
        batch_text_or_text_pairs: Union[List[TextInput], List[TextInputPair]],
        batch_entity_spans_or_entity_spans_pairs: Optional[
            Union[List[EntitySpanInput], List[Tuple[EntitySpanInput, EntitySpanInput]]]
        ] = None,
        batch_entities_or_entities_pairs: Optional[
            Union[List[EntityInput], List[Tuple[EntityInput, EntityInput]]]
        ] = None,
        add_special_tokens: bool = True,
        padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
        truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        stride: int = 0,
        is_split_into_words: Optional[bool] = False,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
        **kwargs,
    ) -> BatchEncoding:
        """
        Performs batch encoding of text and entity inputs for the LukeTokenizer class.

        Args:
            self (LukeTokenizer): The LukeTokenizer instance.
            batch_text_or_text_pairs (Union[List[TextInput], List[TextInputPair]]):
                A list of text inputs or text pairs to be encoded.
            batch_entity_spans_or_entity_spans_pairs (Optional[Union[List[EntitySpanInput], List[Tuple[EntitySpanInput, EntitySpanInput]]]]):
                A list of entity span inputs or entity span input pairs to be encoded. Defaults to None.
            batch_entities_or_entities_pairs (Optional[Union[List[EntityInput], List[Tuple[EntityInput, EntityInput]]]]):
                A list of entity inputs or entity input pairs to be encoded. Defaults to None.
            add_special_tokens (bool): Whether to add special tokens to the encoded inputs. Defaults to True.
            padding_strategy (PaddingStrategy): The strategy to use for padding. Defaults to PaddingStrategy.DO_NOT_PAD.
            truncation_strategy (TruncationStrategy): The strategy to use for truncation.
                Defaults to TruncationStrategy.DO_NOT_TRUNCATE.
            max_length (Optional[int]): The maximum length of the encoded inputs. Defaults to None.
            max_entity_length (Optional[int]): The maximum length of the encoded entity inputs. Defaults to None.
            stride (int): The stride to use when truncating the inputs. Defaults to 0.
            is_split_into_words (Optional[bool]): Whether the inputs are already split into words. Defaults to False.
            pad_to_multiple_of (Optional[int]): Pad the inputs to a multiple of this value. Defaults to None.
            return_tensors (Optional[Union[str, TensorType]]): The type of tensor to return. Defaults to None.
            return_token_type_ids (Optional[bool]): Whether to return token type ids. Defaults to None.
            return_attention_mask (Optional[bool]): Whether to return attention masks. Defaults to None.
            return_overflowing_tokens (bool): Whether to return overflowing tokens. Defaults to False.
            return_special_tokens_mask (bool): Whether to return special tokens masks. Defaults to False.
            return_offsets_mapping (bool): Whether to return character offsets mapping. Defaults to False.
            return_length (bool): Whether to return the lengths of the encoded inputs. Defaults to False.
            verbose (bool): Whether to print information about the encoding process. Defaults to True.

        Returns:
            BatchEncoding: The encoded batch inputs.

        Raises:
            NotImplementedError: If return_offsets_mapping is used with a tokenizer that does not support it.
            NotImplementedError: If is_split_into_words is used with this tokenizer.

        """
        if return_offsets_mapping:
            raise NotImplementedError(
                "return_offset_mapping is not available when using Python tokenizers. "
                "To use this feature, change your tokenizer to one deriving from "
                "transformers.PreTrainedTokenizerFast."
            )

        if is_split_into_words:
            raise NotImplementedError("is_split_into_words is not supported in this tokenizer.")

        # input_ids is a list of tuples (one for each example in the batch)
        input_ids = []
        entity_ids = []
        entity_token_spans = []
        for index, text_or_text_pair in enumerate(batch_text_or_text_pairs):
            if not isinstance(text_or_text_pair, (list, tuple)):
                text, text_pair = text_or_text_pair, None
            else:
                text, text_pair = text_or_text_pair

            entities, entities_pair = None, None
            if batch_entities_or_entities_pairs is not None:
                entities_or_entities_pairs = batch_entities_or_entities_pairs[index]
                if entities_or_entities_pairs:
                    if isinstance(entities_or_entities_pairs[0], str):
                        entities, entities_pair = entities_or_entities_pairs, None
                    else:
                        entities, entities_pair = entities_or_entities_pairs

            entity_spans, entity_spans_pair = None, None
            if batch_entity_spans_or_entity_spans_pairs is not None:
                entity_spans_or_entity_spans_pairs = batch_entity_spans_or_entity_spans_pairs[index]
                if len(entity_spans_or_entity_spans_pairs) > 0 and isinstance(
                    entity_spans_or_entity_spans_pairs[0], list
                ):
                    entity_spans, entity_spans_pair = entity_spans_or_entity_spans_pairs
                else:
                    entity_spans, entity_spans_pair = entity_spans_or_entity_spans_pairs, None

            (
                first_ids,
                second_ids,
                first_entity_ids,
                second_entity_ids,
                first_entity_token_spans,
                second_entity_token_spans,
            ) = self._create_input_sequence(
                text=text,
                text_pair=text_pair,
                entities=entities,
                entities_pair=entities_pair,
                entity_spans=entity_spans,
                entity_spans_pair=entity_spans_pair,
                **kwargs,
            )
            input_ids.append((first_ids, second_ids))
            entity_ids.append((first_entity_ids, second_entity_ids))
            entity_token_spans.append((first_entity_token_spans, second_entity_token_spans))

        batch_outputs = self._batch_prepare_for_model(
            input_ids,
            batch_entity_ids_pairs=entity_ids,
            batch_entity_token_spans_pairs=entity_token_spans,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            max_entity_length=max_entity_length,
            stride=stride,
            pad_to_multiple_of=pad_to_multiple_of,
            return_attention_mask=return_attention_mask,
            return_token_type_ids=return_token_type_ids,
            return_overflowing_tokens=return_overflowing_tokens,
            return_special_tokens_mask=return_special_tokens_mask,
            return_length=return_length,
            return_tensors=return_tensors,
            verbose=verbose,
        )

        return BatchEncoding(batch_outputs)

    def _check_entity_input_format(self, entities: Optional[EntityInput], entity_spans: Optional[EntitySpanInput]):
        """
        This method '_check_entity_input_format' in the class 'LukeTokenizer' validates the input format for entities and entity spans.

        Args:
            self: The instance of the class.
            entities (Optional[EntityInput]): A list of entity names. If specified, it should be given as a list of entity names.
            entity_spans (Optional[EntitySpanInput]): A list of tuples containing the start and end character indices.
                If specified, it should be given as a list of tuples containing the start and end character indices.

        Returns:
            None.

        Raises:
            ValueError:
                - If 'entity_spans' is not given as a list.
                - If 'entity_spans' is given as a list, but the first element is not a tuple containing
                the start and end character indices.
                - If 'entities' is specified but not given as a list.
                - If 'entities' is given as a list, but the first element is not a string.
                - If the length of 'entities' is not equal to the length of 'entity_spans' when both are specified.
        """
        if not isinstance(entity_spans, list):
            raise ValueError("entity_spans should be given as a list")
        if len(entity_spans) > 0 and not isinstance(entity_spans[0], tuple):
            raise ValueError(
                "entity_spans should be given as a list of tuples containing the start and end character indices"
            )

        if entities is not None:
            if not isinstance(entities, list):
                raise ValueError("If you specify entities, they should be given as a list")

            if len(entities) > 0 and not isinstance(entities[0], str):
                raise ValueError("If you specify entities, they should be given as a list of entity names")

            if len(entities) != len(entity_spans):
                raise ValueError("If you specify entities, entities and entity_spans must be the same length")

    def _create_input_sequence(
        self,
        text: TextInput,
        text_pair: Optional[TextInput] = None,
        entities: Optional[EntityInput] = None,
        entities_pair: Optional[EntityInput] = None,
        entity_spans: Optional[EntitySpanInput] = None,
        entity_spans_pair: Optional[EntitySpanInput] = None,
        **kwargs,
    ) -> Tuple[list, list, list, list, list, list]:
        """
        Create input sequences for the LukeTokenizer.

        Args:
            self (LukeTokenizer): An instance of the LukeTokenizer class.
            text (TextInput): The main input text to be tokenized.
            text_pair (Optional[TextInput]): An optional pair of input text to be tokenized. Default is None.
            entities (Optional[EntityInput]): An optional list of entities in the main input text. Default is None.
            entities_pair (Optional[EntityInput]): An optional list of entities in the pair input text. Default is None.
            entity_spans (Optional[EntitySpanInput]): An optional list of tuples representing the start and end character
                indices of the entities in the main input text. Default is None.
            entity_spans_pair (Optional[EntitySpanInput]): An optional list of tuples representing the start and end
                character indices of the entities in the pair input text. Default is None.
            **kwargs: Additional keyword arguments.

        Returns:
            Tuple[list, list, list, list, list, list]:
                A tuple containing six lists:

                - first_ids: A list of token IDs for the main input text.
                - second_ids: A list of token IDs for the pair input text.
                - first_entity_ids: A list of entity IDs for the entities in the main input text.
                - second_entity_ids: A list of entity IDs for the entities in the pair input text.
                - first_entity_token_spans: A list of token spans for the entities in the main input text.
                - second_entity_token_spans: A list of token spans for the entities in the pair input text.

        Raises:
            ValueError: If the task is not supported or if the entity spans are not in the correct format.
        """
        def get_input_ids(text):
            tokens = self.tokenize(text, **kwargs)
            return self.convert_tokens_to_ids(tokens)

        def get_input_ids_and_entity_token_spans(text, entity_spans):
            if entity_spans is None:
                return get_input_ids(text), None

            cur = 0
            input_ids = []
            entity_token_spans = [None] * len(entity_spans)

            split_char_positions = sorted(frozenset(itertools.chain(*entity_spans)))
            char_pos2token_pos = {}

            for split_char_position in split_char_positions:
                orig_split_char_position = split_char_position
                if (
                    split_char_position > 0 and text[split_char_position - 1] == " "
                ):  # whitespace should be prepended to the following token
                    split_char_position -= 1
                if cur != split_char_position:
                    input_ids += get_input_ids(text[cur:split_char_position])
                    cur = split_char_position
                char_pos2token_pos[orig_split_char_position] = len(input_ids)

            input_ids += get_input_ids(text[cur:])

            entity_token_spans = [
                (char_pos2token_pos[char_start], char_pos2token_pos[char_end]) for char_start, char_end in entity_spans
            ]

            return input_ids, entity_token_spans

        first_ids, second_ids = None, None
        first_entity_ids, second_entity_ids = None, None
        first_entity_token_spans, second_entity_token_spans = None, None

        if self.task is None:
            if entity_spans is None:
                first_ids = get_input_ids(text)
            else:
                self._check_entity_input_format(entities, entity_spans)

                first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
                if entities is None:
                    first_entity_ids = [self.entity_mask_token_id] * len(entity_spans)
                else:
                    first_entity_ids = [self.entity_vocab.get(entity, self.entity_unk_token_id) for entity in entities]

            if text_pair is not None:
                if entity_spans_pair is None:
                    second_ids = get_input_ids(text_pair)
                else:
                    self._check_entity_input_format(entities_pair, entity_spans_pair)

                    second_ids, second_entity_token_spans = get_input_ids_and_entity_token_spans(
                        text_pair, entity_spans_pair
                    )
                    if entities_pair is None:
                        second_entity_ids = [self.entity_mask_token_id] * len(entity_spans_pair)
                    else:
                        second_entity_ids = [
                            self.entity_vocab.get(entity, self.entity_unk_token_id) for entity in entities_pair
                        ]

        elif self.task == "entity_classification":
            if not (isinstance(entity_spans, list) and len(entity_spans) == 1 and isinstance(entity_spans[0], tuple)):
                raise ValueError(
                    "Entity spans should be a list containing a single tuple "
                    "containing the start and end character indices of an entity"
                )
            first_entity_ids = [self.entity_mask_token_id]
            first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)

            # add special tokens to input ids
            entity_token_start, entity_token_end = first_entity_token_spans[0]
            first_ids = (
                first_ids[:entity_token_end] + [self.additional_special_tokens_ids[0]] + first_ids[entity_token_end:]
            )
            first_ids = (
                first_ids[:entity_token_start]
                + [self.additional_special_tokens_ids[0]]
                + first_ids[entity_token_start:]
            )
            first_entity_token_spans = [(entity_token_start, entity_token_end + 2)]

        elif self.task == "entity_pair_classification":
            if not (
                isinstance(entity_spans, list)
                and len(entity_spans) == 2
                and isinstance(entity_spans[0], tuple)
                and isinstance(entity_spans[1], tuple)
            ):
                raise ValueError(
                    "Entity spans should be provided as a list of two tuples, "
                    "each tuple containing the start and end character indices of an entity"
                )

            first_entity_ids = [self.entity_mask_token_id, self.entity_mask2_token_id]
            first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)

            head_token_span, tail_token_span = first_entity_token_spans
            token_span_with_special_token_ids = [
                (head_token_span, self.additional_special_tokens_ids[0]),
                (tail_token_span, self.additional_special_tokens_ids[1]),
            ]
            if head_token_span[0] < tail_token_span[0]:
                first_entity_token_spans[0] = (head_token_span[0], head_token_span[1] + 2)
                first_entity_token_spans[1] = (tail_token_span[0] + 2, tail_token_span[1] + 4)
                token_span_with_special_token_ids = reversed(token_span_with_special_token_ids)
            else:
                first_entity_token_spans[0] = (head_token_span[0] + 2, head_token_span[1] + 4)
                first_entity_token_spans[1] = (tail_token_span[0], tail_token_span[1] + 2)

            for (entity_token_start, entity_token_end), special_token_id in token_span_with_special_token_ids:
                first_ids = first_ids[:entity_token_end] + [special_token_id] + first_ids[entity_token_end:]
                first_ids = first_ids[:entity_token_start] + [special_token_id] + first_ids[entity_token_start:]

        elif self.task == "entity_span_classification":
            if not (isinstance(entity_spans, list) and len(entity_spans) > 0 and isinstance(entity_spans[0], tuple)):
                raise ValueError(
                    "Entity spans should be provided as a list of tuples, "
                    "each tuple containing the start and end character indices of an entity"
                )

            first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
            first_entity_ids = [self.entity_mask_token_id] * len(entity_spans)

        else:
            raise ValueError(f"Task {self.task} not supported")

        return (
            first_ids,
            second_ids,
            first_entity_ids,
            second_entity_ids,
            first_entity_token_spans,
            second_entity_token_spans,
        )

    def _batch_prepare_for_model(
        self,
        batch_ids_pairs: List[Tuple[List[int], None]],
        batch_entity_ids_pairs: List[Tuple[Optional[List[int]], Optional[List[int]]]],
        batch_entity_token_spans_pairs: List[Tuple[Optional[List[Tuple[int, int]]], Optional[List[Tuple[int, int]]]]],
        add_special_tokens: bool = True,
        padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
        truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        stride: int = 0,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[str] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_length: bool = False,
        verbose: bool = True,
    ) -> BatchEncoding:
        """
        Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
        adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
        manages a moving window (with user defined stride) for overflowing tokens


        Args:
            batch_ids_pairs: list of tokenized input ids or input ids pairs
            batch_entity_ids_pairs: list of entity ids or entity ids pairs
            batch_entity_token_spans_pairs: list of entity spans or entity spans pairs
            max_entity_length: The maximum length of the entity sequence.
        """
        batch_outputs = {}
        for input_ids, entity_ids, entity_token_span_pairs in zip(
            batch_ids_pairs, batch_entity_ids_pairs, batch_entity_token_spans_pairs
        ):
            first_ids, second_ids = input_ids
            first_entity_ids, second_entity_ids = entity_ids
            first_entity_token_spans, second_entity_token_spans = entity_token_span_pairs
            outputs = self.prepare_for_model(
                first_ids,
                second_ids,
                entity_ids=first_entity_ids,
                pair_entity_ids=second_entity_ids,
                entity_token_spans=first_entity_token_spans,
                pair_entity_token_spans=second_entity_token_spans,
                add_special_tokens=add_special_tokens,
                padding=PaddingStrategy.DO_NOT_PAD.value,  # we pad in batch afterward
                truncation=truncation_strategy.value,
                max_length=max_length,
                max_entity_length=max_entity_length,
                stride=stride,
                pad_to_multiple_of=None,  # we pad in batch afterward
                return_attention_mask=False,  # we pad in batch afterward
                return_token_type_ids=return_token_type_ids,
                return_overflowing_tokens=return_overflowing_tokens,
                return_special_tokens_mask=return_special_tokens_mask,
                return_length=return_length,
                return_tensors=None,  # We convert the whole batch to tensors at the end
                prepend_batch_axis=False,
                verbose=verbose,
            )

            for key, value in outputs.items():
                if key not in batch_outputs:
                    batch_outputs[key] = []
                batch_outputs[key].append(value)

        batch_outputs = self.pad(
            batch_outputs,
            padding=padding_strategy.value,
            max_length=max_length,
            pad_to_multiple_of=pad_to_multiple_of,
            return_attention_mask=return_attention_mask,
        )

        batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)

        return batch_outputs

    def prepare_for_model(
        self,
        ids: List[int],
        pair_ids: Optional[List[int]] = None,
        entity_ids: Optional[List[int]] = None,
        pair_entity_ids: Optional[List[int]] = None,
        entity_token_spans: Optional[List[Tuple[int, int]]] = None,
        pair_entity_token_spans: Optional[List[Tuple[int, int]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        stride: int = 0,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
        prepend_batch_axis: bool = False,
        **kwargs,
    ) -> BatchEncoding:
        """
        Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids,
        entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing
        while taking into account the special tokens and manages a moving window (with user defined stride) for
        overflowing tokens. Please Note, for *pair_ids* different than `None` and *truncation_strategy = longest_first*
        or `True`, it is not possible to return overflowing tokens. Such a combination of arguments will raise an
        error.

        Args:
            ids (`List[int]`):
                Tokenized input ids of the first sequence.
            pair_ids (`List[int]`, *optional*):
                Tokenized input ids of the second sequence.
            entity_ids (`List[int]`, *optional*):
                Entity ids of the first sequence.
            pair_entity_ids (`List[int]`, *optional*):
                Entity ids of the second sequence.
            entity_token_spans (`List[Tuple[int, int]]`, *optional*):
                Entity spans of the first sequence.
            pair_entity_token_spans (`List[Tuple[int, int]]`, *optional*):
                Entity spans of the second sequence.
            max_entity_length (`int`, *optional*):
                The maximum length of the entity sequence.
        """
        # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
        padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            pad_to_multiple_of=pad_to_multiple_of,
            verbose=verbose,
            **kwargs,
        )

        # Compute lengths
        pair = bool(pair_ids is not None)
        len_ids = len(ids)
        len_pair_ids = len(pair_ids) if pair else 0

        if return_token_type_ids and not add_special_tokens:
            raise ValueError(
                "Asking to return token_type_ids while setting add_special_tokens to False "
                "results in an undefined behavior. Please set add_special_tokens to True or "
                "set return_token_type_ids to None."
            )
        if (
            return_overflowing_tokens
            and truncation_strategy == TruncationStrategy.LONGEST_FIRST
            and pair_ids is not None
        ):
            raise ValueError(
                "Not possible to return overflowing tokens for pair of sequences with the "
                "`longest_first`. Please select another truncation strategy than `longest_first`, "
                "for instance `only_second` or `only_first`."
            )

        # Load from model defaults
        if return_token_type_ids is None:
            return_token_type_ids = "token_type_ids" in self.model_input_names
        if return_attention_mask is None:
            return_attention_mask = "attention_mask" in self.model_input_names

        encoded_inputs = {}

        # Compute the total size of the returned word encodings
        total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)

        # Truncation: Handle max sequence length and max_entity_length
        overflowing_tokens = []
        if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
            # truncate words up to max_length
            ids, pair_ids, overflowing_tokens = self.truncate_sequences(
                ids,
                pair_ids=pair_ids,
                num_tokens_to_remove=total_len - max_length,
                truncation_strategy=truncation_strategy,
                stride=stride,
            )

        if return_overflowing_tokens:
            encoded_inputs["overflowing_tokens"] = overflowing_tokens
            encoded_inputs["num_truncated_tokens"] = total_len - max_length

        # Add special tokens
        if add_special_tokens:
            sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
            token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
            entity_token_offset = 1  # 1 * <s> token
            pair_entity_token_offset = len(ids) + 3  # 1 * <s> token & 2 * <sep> tokens
        else:
            sequence = ids + pair_ids if pair else ids
            token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
            entity_token_offset = 0
            pair_entity_token_offset = len(ids)

        # Build output dictionary
        encoded_inputs["input_ids"] = sequence
        if return_token_type_ids:
            encoded_inputs["token_type_ids"] = token_type_ids
        if return_special_tokens_mask:
            if add_special_tokens:
                encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
            else:
                encoded_inputs["special_tokens_mask"] = [0] * len(sequence)

        # Set max entity length
        if not max_entity_length:
            max_entity_length = self.max_entity_length

        if entity_ids is not None:
            total_entity_len = 0
            num_invalid_entities = 0
            valid_entity_ids = [ent_id for ent_id, span in zip(entity_ids, entity_token_spans) if span[1] <= len(ids)]
            valid_entity_token_spans = [span for span in entity_token_spans if span[1] <= len(ids)]

            total_entity_len += len(valid_entity_ids)
            num_invalid_entities += len(entity_ids) - len(valid_entity_ids)

            valid_pair_entity_ids, valid_pair_entity_token_spans = None, None
            if pair_entity_ids is not None:
                valid_pair_entity_ids = [
                    ent_id
                    for ent_id, span in zip(pair_entity_ids, pair_entity_token_spans)
                    if span[1] <= len(pair_ids)
                ]
                valid_pair_entity_token_spans = [span for span in pair_entity_token_spans if span[1] <= len(pair_ids)]
                total_entity_len += len(valid_pair_entity_ids)
                num_invalid_entities += len(pair_entity_ids) - len(valid_pair_entity_ids)

            if num_invalid_entities != 0:
                logger.warning(
                    f"{num_invalid_entities} entities are ignored because their entity spans are invalid due to the"
                    " truncation of input tokens"
                )

            if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and total_entity_len > max_entity_length:
                # truncate entities up to max_entity_length
                valid_entity_ids, valid_pair_entity_ids, overflowing_entities = self.truncate_sequences(
                    valid_entity_ids,
                    pair_ids=valid_pair_entity_ids,
                    num_tokens_to_remove=total_entity_len - max_entity_length,
                    truncation_strategy=truncation_strategy,
                    stride=stride,
                )
                valid_entity_token_spans = valid_entity_token_spans[: len(valid_entity_ids)]
                if valid_pair_entity_token_spans is not None:
                    valid_pair_entity_token_spans = valid_pair_entity_token_spans[: len(valid_pair_entity_ids)]

            if return_overflowing_tokens:
                encoded_inputs["overflowing_entities"] = overflowing_entities
                encoded_inputs["num_truncated_entities"] = total_entity_len - max_entity_length

            final_entity_ids = valid_entity_ids + valid_pair_entity_ids if valid_pair_entity_ids else valid_entity_ids
            encoded_inputs["entity_ids"] = list(final_entity_ids)
            entity_position_ids = []
            entity_start_positions = []
            entity_end_positions = []
            for token_spans, offset in (
                (valid_entity_token_spans, entity_token_offset),
                (valid_pair_entity_token_spans, pair_entity_token_offset),
            ):
                if token_spans is not None:
                    for start, end in token_spans:
                        start += offset
                        end += offset
                        position_ids = list(range(start, end))[: self.max_mention_length]
                        position_ids += [-1] * (self.max_mention_length - end + start)
                        entity_position_ids.append(position_ids)
                        entity_start_positions.append(start)
                        entity_end_positions.append(end - 1)

            encoded_inputs["entity_position_ids"] = entity_position_ids
            if self.task == "entity_span_classification":
                encoded_inputs["entity_start_positions"] = entity_start_positions
                encoded_inputs["entity_end_positions"] = entity_end_positions

            if return_token_type_ids:
                encoded_inputs["entity_token_type_ids"] = [0] * len(encoded_inputs["entity_ids"])

        # Check lengths
        self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)

        # Padding
        if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
            encoded_inputs = self.pad(
                encoded_inputs,
                max_length=max_length,
                max_entity_length=max_entity_length,
                padding=padding_strategy.value,
                pad_to_multiple_of=pad_to_multiple_of,
                return_attention_mask=return_attention_mask,
            )

        if return_length:
            encoded_inputs["length"] = len(encoded_inputs["input_ids"])

        batch_outputs = BatchEncoding(
            encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
        )

        return batch_outputs

    def pad(
        self,
        encoded_inputs: Union[
            BatchEncoding,
            List[BatchEncoding],
            Dict[str, EncodedInput],
            Dict[str, List[EncodedInput]],
            List[Dict[str, EncodedInput]],
        ],
        padding: Union[bool, str, PaddingStrategy] = True,
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        pad_to_multiple_of: Optional[int] = None,
        return_attention_mask: Optional[bool] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        verbose: bool = True,
    ) -> BatchEncoding:
        """
        Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
        in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with
        `self.padding_side`, `self.pad_token_id` and `self.pad_token_type_id`) .. note:: If the `encoded_inputs` passed
        are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the result will use the same type unless
        you provide a different tensor type with `return_tensors`. In the case of PyTorch tensors, you will lose the
        specific device of your tensors however.

        Args:
            encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
                Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
                tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
                List[int]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
                collate function. Instead of `List[int]` you can have tensors (numpy arrays, PyTorch tensors or
                TensorFlow tensors), see the note above for the return type.
            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
                 Select a strategy to pad the returned sequences (according to the model's padding side and padding
                 index) among:

                - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
                sequence if provided).
                - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
                acceptable input length for the model if that argument is not provided.
                - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
                lengths).
            max_length (`int`, *optional*):
                Maximum length of the returned list and optionally padding length (see above).
            max_entity_length (`int`, *optional*):
                The maximum length of the entity sequence.
            pad_to_multiple_of (`int`, *optional*):
                If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
                the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
            return_attention_mask (`bool`, *optional*):
                Whether to return the attention mask. If left to the default, will return the attention mask according
                to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention
                masks?](../glossary#attention-mask)
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
            verbose (`bool`, *optional*, defaults to `True`):
                Whether or not to print more information and warnings.
        """
        # If we have a list of dicts, let's convert it in a dict of lists
        # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
        if isinstance(encoded_inputs, (list, tuple)) and isinstance(encoded_inputs[0], Mapping):
            encoded_inputs = {key: [example[key] for example in encoded_inputs] for key in encoded_inputs[0].keys()}

        # The model's main input name, usually `input_ids`, has be passed for padding
        if self.model_input_names[0] not in encoded_inputs:
            raise ValueError(
                "You should supply an encoding or a list of encodings to this method "
                f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
            )

        required_input = encoded_inputs[self.model_input_names[0]]

        if not required_input:
            if return_attention_mask:
                encoded_inputs["attention_mask"] = []
            return encoded_inputs

        # If we have PyTorch/TF/NumPy tensors/arrays as inputs, we cast them as python objects
        # and rebuild them afterwards if no return_tensors is specified
        # Note that we lose the specific device the tensor may be on for PyTorch

        first_element = required_input[0]
        if isinstance(first_element, (list, tuple)):
            # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
            index = 0
            while len(required_input[index]) == 0:
                index += 1
            if index < len(required_input):
                first_element = required_input[index][0]
        # At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
        if not isinstance(first_element, (int, list, tuple)):
            if is_mindspore_tensor(first_element):
                return_tensors = "ms" if return_tensors is None else return_tensors
            elif isinstance(first_element, np.ndarray):
                return_tensors = "np" if return_tensors is None else return_tensors
            else:
                raise ValueError(
                    f"type of {first_element} unknown: {type(first_element)}. "
                    "Should be one of a python, numpy, pytorch or tensorflow object."
                )

            for key, value in encoded_inputs.items():
                encoded_inputs[key] = to_py_obj(value)

        # Convert padding_strategy in PaddingStrategy
        padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
            padding=padding, max_length=max_length, verbose=verbose
        )

        if max_entity_length is None:
            max_entity_length = self.max_entity_length

        required_input = encoded_inputs[self.model_input_names[0]]
        if required_input and not isinstance(required_input[0], (list, tuple)):
            encoded_inputs = self._pad(
                encoded_inputs,
                max_length=max_length,
                max_entity_length=max_entity_length,
                padding_strategy=padding_strategy,
                pad_to_multiple_of=pad_to_multiple_of,
                return_attention_mask=return_attention_mask,
            )
            return BatchEncoding(encoded_inputs, tensor_type=return_tensors)

        batch_size = len(required_input)
        if any(len(v) != batch_size for v in encoded_inputs.values()):
            raise ValueError("Some items in the output dictionary have a different batch size than others.")

        if padding_strategy == PaddingStrategy.LONGEST:
            max_length = max(len(inputs) for inputs in required_input)
            max_entity_length = (
                max(len(inputs) for inputs in encoded_inputs["entity_ids"]) if "entity_ids" in encoded_inputs else 0
            )
            padding_strategy = PaddingStrategy.MAX_LENGTH

        batch_outputs = {}
        for i in range(batch_size):
            inputs = {k: v[i] for k, v in encoded_inputs.items()}
            outputs = self._pad(
                inputs,
                max_length=max_length,
                max_entity_length=max_entity_length,
                padding_strategy=padding_strategy,
                pad_to_multiple_of=pad_to_multiple_of,
                return_attention_mask=return_attention_mask,
            )

            for key, value in outputs.items():
                if key not in batch_outputs:
                    batch_outputs[key] = []
                batch_outputs[key].append(value)

        return BatchEncoding(batch_outputs, tensor_type=return_tensors)

    def _pad(
        self,
        encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
        max_length: Optional[int] = None,
        max_entity_length: Optional[int] = None,
        padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
        pad_to_multiple_of: Optional[int] = None,
        return_attention_mask: Optional[bool] = None,
    ) -> dict:
        """
        Pad encoded inputs (on left/right and up to predefined length or max length in the batch)


        Args:
            encoded_inputs:
                Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
            max_length: maximum length of the returned list and optionally padding length (see below).
                Will truncate by taking into account the special tokens.
            max_entity_length: The maximum length of the entity sequence.
            padding_strategy:
                PaddingStrategy to use for padding.

                - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
                - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
                - PaddingStrategy.DO_NOT_PAD: Do not pad

                The tokenizer padding sides are defined in self.padding_side:

                - 'left': pads on the left of the sequences
                - 'right': pads on the right of the sequences
            pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
                This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
                `>= 7.5` (Volta).
            return_attention_mask:
                (optional) Set to False to avoid returning attention mask (default: set to model specifics)
        """
        entities_provided = bool("entity_ids" in encoded_inputs)

        # Load from model defaults
        if return_attention_mask is None:
            return_attention_mask = "attention_mask" in self.model_input_names

        if padding_strategy == PaddingStrategy.LONGEST:
            max_length = len(encoded_inputs["input_ids"])
            if entities_provided:
                max_entity_length = len(encoded_inputs["entity_ids"])

        if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
            max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

        if (
            entities_provided
            and max_entity_length is not None
            and pad_to_multiple_of is not None
            and (max_entity_length % pad_to_multiple_of != 0)
        ):
            max_entity_length = ((max_entity_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

        needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and (
            len(encoded_inputs["input_ids"]) != max_length
            or (entities_provided and len(encoded_inputs["entity_ids"]) != max_entity_length)
        )

        # Initialize attention mask if not present.
        if return_attention_mask and "attention_mask" not in encoded_inputs:
            encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
        if entities_provided and return_attention_mask and "entity_attention_mask" not in encoded_inputs:
            encoded_inputs["entity_attention_mask"] = [1] * len(encoded_inputs["entity_ids"])

        if needs_to_be_padded:
            difference = max_length - len(encoded_inputs["input_ids"])
            if entities_provided:
                entity_difference = max_entity_length - len(encoded_inputs["entity_ids"])
            if self.padding_side == "right":
                if return_attention_mask:
                    encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
                    if entities_provided:
                        encoded_inputs["entity_attention_mask"] = (
                            encoded_inputs["entity_attention_mask"] + [0] * entity_difference
                        )
                if "token_type_ids" in encoded_inputs:
                    encoded_inputs["token_type_ids"] = encoded_inputs["token_type_ids"] + [0] * difference
                    if entities_provided:
                        encoded_inputs["entity_token_type_ids"] = (
                            encoded_inputs["entity_token_type_ids"] + [0] * entity_difference
                        )
                if "special_tokens_mask" in encoded_inputs:
                    encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
                encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
                if entities_provided:
                    encoded_inputs["entity_ids"] = (
                        encoded_inputs["entity_ids"] + [self.entity_pad_token_id] * entity_difference
                    )
                    encoded_inputs["entity_position_ids"] = (
                        encoded_inputs["entity_position_ids"] + [[-1] * self.max_mention_length] * entity_difference
                    )
                    if self.task == "entity_span_classification":
                        encoded_inputs["entity_start_positions"] = (
                            encoded_inputs["entity_start_positions"] + [0] * entity_difference
                        )
                        encoded_inputs["entity_end_positions"] = (
                            encoded_inputs["entity_end_positions"] + [0] * entity_difference
                        )

            elif self.padding_side == "left":
                if return_attention_mask:
                    encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
                    if entities_provided:
                        encoded_inputs["entity_attention_mask"] = [0] * entity_difference + encoded_inputs[
                            "entity_attention_mask"
                        ]
                if "token_type_ids" in encoded_inputs:
                    encoded_inputs["token_type_ids"] = [0] * difference + encoded_inputs["token_type_ids"]
                    if entities_provided:
                        encoded_inputs["entity_token_type_ids"] = [0] * entity_difference + encoded_inputs[
                            "entity_token_type_ids"
                        ]
                if "special_tokens_mask" in encoded_inputs:
                    encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
                encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
                if entities_provided:
                    encoded_inputs["entity_ids"] = [self.entity_pad_token_id] * entity_difference + encoded_inputs[
                        "entity_ids"
                    ]
                    encoded_inputs["entity_position_ids"] = [
                        [-1] * self.max_mention_length
                    ] * entity_difference + encoded_inputs["entity_position_ids"]
                    if self.task == "entity_span_classification":
                        encoded_inputs["entity_start_positions"] = [0] * entity_difference + encoded_inputs[
                            "entity_start_positions"
                        ]
                        encoded_inputs["entity_end_positions"] = [0] * entity_difference + encoded_inputs[
                            "entity_end_positions"
                        ]
            else:
                raise ValueError("Invalid padding strategy:" + str(self.padding_side))

        return encoded_inputs

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary to specified directory with an optional filename prefix.

        Args:
            self: Instance of LukeTokenizer class.
            save_directory (str): The directory path where the vocabulary files will be saved.
            filename_prefix (Optional[str]): An optional prefix to be added to the filename. Default is None.

        Returns:
            Tuple[str]: A tuple containing paths to the saved vocabulary files - vocab_file, merge_file,
                and entity_vocab_file.

        Raises:
            FileNotFoundError: If the specified save_directory does not exist.
            IOError: If there is an issue with reading or writing the vocabulary files.
            ValueError: If the provided filename_prefix is not a string.
            Exception: Any other unexpected error that may occur during the execution of the method.
        """
        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )
        merge_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
        )

        with open(vocab_file, "w", encoding="utf-8") as f:
            f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

        index = 0
        with open(merge_file, "w", encoding="utf-8") as writer:
            writer.write("#version: 0.2\n")
            for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
                if index != token_index:
                    logger.warning(
                        f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                        " Please check that the tokenizer is not corrupted!"
                    )
                    index = token_index
                writer.write(" ".join(bpe_tokens) + "\n")
                index += 1

        entity_vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["entity_vocab_file"]
        )

        with open(entity_vocab_file, "w", encoding="utf-8") as f:
            f.write(json.dumps(self.entity_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

        return vocab_file, merge_file, entity_vocab_file

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.vocab_size property

Returns the size of the vocabulary.

PARAMETER DESCRIPTION
self

The instance of the LukeTokenizer class.

TYPE: LukeTokenizer

RETURNS DESCRIPTION
int

The number of items in the encoder, representing the size of the vocabulary.

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.__call__(text, text_pair=None, entity_spans=None, entity_spans_pair=None, entities=None, entities_pair=None, add_special_tokens=True, padding=False, truncation=None, max_length=None, max_entity_length=None, stride=0, is_split_into_words=False, pad_to_multiple_of=None, return_tensors=None, return_token_type_ids=None, return_attention_mask=None, return_overflowing_tokens=False, return_special_tokens_mask=False, return_offsets_mapping=False, return_length=False, verbose=True, **kwargs)

Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences, depending on the task you want to prepare them for.

PARAMETER DESCRIPTION
text

The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this tokenizer does not support tokenization based on pretokenized strings.

TYPE: `str`, `List[str]`, `List[List[str]]`

text_pair

The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this tokenizer does not support tokenization based on pretokenized strings.

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

entity_spans

The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each with two integers denoting character-based start and end positions of entities. If you specify "entity_classification" or "entity_pair_classification" as the task argument in the forwardor, the length of each sequence must be 1 or 2, respectively. If you specify entities, the length of each sequence must be equal to the length of each sequence of entities.

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

entity_spans_pair

The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each with two integers denoting character-based start and end positions of entities. If you specify the task argument in the forwardor, this argument is ignored. If you specify entities_pair, the length of each sequence must be equal to the length of each sequence of entities_pair.

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

entities

The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los Angeles). This argument is ignored if you specify the task argument in the forwardor. The length of each sequence must be equal to the length of each sequence of entity_spans. If you specify entity_spans without specifying this argument, the entity sequence or the batch of entity sequences is automatically forwarded by filling it with the [MASK] entity.

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

entities_pair

The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los Angeles). This argument is ignored if you specify the task argument in the forwardor. The length of each sequence must be equal to the length of each sequence of entity_spans_pair. If you specify entity_spans_pair without specifying this argument, the entity sequence or the batch of entity sequences is automatically forwarded by filling it with the [MASK] entity.

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

max_entity_length

The maximum length of entity_ids.

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
def __call__(
    self,
    text: Union[TextInput, List[TextInput]],
    text_pair: Optional[Union[TextInput, List[TextInput]]] = None,
    entity_spans: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
    entity_spans_pair: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
    entities: Optional[Union[EntityInput, List[EntityInput]]] = None,
    entities_pair: Optional[Union[EntityInput, List[EntityInput]]] = None,
    add_special_tokens: bool = True,
    padding: Union[bool, str, PaddingStrategy] = False,
    truncation: Union[bool, str, TruncationStrategy] = None,
    max_length: Optional[int] = None,
    max_entity_length: Optional[int] = None,
    stride: int = 0,
    is_split_into_words: Optional[bool] = False,
    pad_to_multiple_of: Optional[int] = None,
    return_tensors: Optional[Union[str, TensorType]] = None,
    return_token_type_ids: Optional[bool] = None,
    return_attention_mask: Optional[bool] = None,
    return_overflowing_tokens: bool = False,
    return_special_tokens_mask: bool = False,
    return_offsets_mapping: bool = False,
    return_length: bool = False,
    verbose: bool = True,
    **kwargs,
) -> BatchEncoding:
    """
    Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
    sequences, depending on the task you want to prepare them for.

    Args:
        text (`str`, `List[str]`, `List[List[str]]`):
            The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
            tokenizer does not support tokenization based on pretokenized strings.
        text_pair (`str`, `List[str]`, `List[List[str]]`):
            The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
            tokenizer does not support tokenization based on pretokenized strings.
        entity_spans (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
            The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
            with two integers denoting character-based start and end positions of entities. If you specify
            `"entity_classification"` or `"entity_pair_classification"` as the `task` argument in the forwardor,
            the length of each sequence must be 1 or 2, respectively. If you specify `entities`, the length of each
            sequence must be equal to the length of each sequence of `entities`.
        entity_spans_pair (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
            The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
            with two integers denoting character-based start and end positions of entities. If you specify the
            `task` argument in the forwardor, this argument is ignored. If you specify `entities_pair`, the
            length of each sequence must be equal to the length of each sequence of `entities_pair`.
        entities (`List[str]`, `List[List[str]]`, *optional*):
            The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
            representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
            Angeles). This argument is ignored if you specify the `task` argument in the forwardor. The length of
            each sequence must be equal to the length of each sequence of `entity_spans`. If you specify
            `entity_spans` without specifying this argument, the entity sequence or the batch of entity sequences
            is automatically forwarded by filling it with the [MASK] entity.
        entities_pair (`List[str]`, `List[List[str]]`, *optional*):
            The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
            representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
            Angeles). This argument is ignored if you specify the `task` argument in the forwardor. The length of
            each sequence must be equal to the length of each sequence of `entity_spans_pair`. If you specify
            `entity_spans_pair` without specifying this argument, the entity sequence or the batch of entity
            sequences is automatically forwarded by filling it with the [MASK] entity.
        max_entity_length (`int`, *optional*):
            The maximum length of `entity_ids`.
    """
    # Input type checking for clearer error
    is_valid_single_text = isinstance(text, str)
    is_valid_batch_text = isinstance(text, (list, tuple)) and (len(text) == 0 or (isinstance(text[0], str)))
    if not (is_valid_single_text or is_valid_batch_text):
        raise ValueError("text input must be of type `str` (single example) or `List[str]` (batch).")

    is_valid_single_text_pair = isinstance(text_pair, str)
    is_valid_batch_text_pair = isinstance(text_pair, (list, tuple)) and (
        len(text_pair) == 0 or isinstance(text_pair[0], str)
    )
    if not (text_pair is None or is_valid_single_text_pair or is_valid_batch_text_pair):
        raise ValueError("text_pair input must be of type `str` (single example) or `List[str]` (batch).")

    is_batched = bool(isinstance(text, (list, tuple)))

    if is_batched:
        batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
        if entities is None:
            batch_entities_or_entities_pairs = None
        else:
            batch_entities_or_entities_pairs = (
                list(zip(entities, entities_pair)) if entities_pair is not None else entities
            )

        if entity_spans is None:
            batch_entity_spans_or_entity_spans_pairs = None
        else:
            batch_entity_spans_or_entity_spans_pairs = (
                list(zip(entity_spans, entity_spans_pair)) if entity_spans_pair is not None else entity_spans
            )

        return self.batch_encode_plus(
            batch_text_or_text_pairs=batch_text_or_text_pairs,
            batch_entity_spans_or_entity_spans_pairs=batch_entity_spans_or_entity_spans_pairs,
            batch_entities_or_entities_pairs=batch_entities_or_entities_pairs,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            max_entity_length=max_entity_length,
            stride=stride,
            is_split_into_words=is_split_into_words,
            pad_to_multiple_of=pad_to_multiple_of,
            return_tensors=return_tensors,
            return_token_type_ids=return_token_type_ids,
            return_attention_mask=return_attention_mask,
            return_overflowing_tokens=return_overflowing_tokens,
            return_special_tokens_mask=return_special_tokens_mask,
            return_offsets_mapping=return_offsets_mapping,
            return_length=return_length,
            verbose=verbose,
            **kwargs,
        )
    return self.encode_plus(
        text=text,
        text_pair=text_pair,
        entity_spans=entity_spans,
        entity_spans_pair=entity_spans_pair,
        entities=entities,
        entities_pair=entities_pair,
        add_special_tokens=add_special_tokens,
        padding=padding,
        truncation=truncation,
        max_length=max_length,
        max_entity_length=max_entity_length,
        stride=stride,
        is_split_into_words=is_split_into_words,
        pad_to_multiple_of=pad_to_multiple_of,
        return_tensors=return_tensors,
        return_token_type_ids=return_token_type_ids,
        return_attention_mask=return_attention_mask,
        return_overflowing_tokens=return_overflowing_tokens,
        return_special_tokens_mask=return_special_tokens_mask,
        return_offsets_mapping=return_offsets_mapping,
        return_length=return_length,
        verbose=verbose,
        **kwargs,
    )

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.__init__(vocab_file, merges_file, entity_vocab_file, task=None, max_entity_length=32, max_mention_length=30, entity_token_1='<ent>', entity_token_2='<ent2>', entity_unk_token='[UNK]', entity_pad_token='[PAD]', entity_mask_token='[MASK]', entity_mask2_token='[MASK2]', errors='replace', bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_token='<s>', unk_token='<unk>', pad_token='<pad>', mask_token='<mask>', add_prefix_space=False, **kwargs)

Initialize the LukeTokenizer class.

This method initializes an instance of the LukeTokenizer class. It takes the following parameters:

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

The path to the vocabulary file.

TYPE: str

merges_file

The path to the merges file.

TYPE: str

entity_vocab_file

The path to the entity vocabulary file.

TYPE: str

task

The task for which the tokenizer is used. Defaults to None.

TYPE: str DEFAULT: None

max_entity_length

The maximum length of the entity. Defaults to 32.

TYPE: int DEFAULT: 32

max_mention_length

The maximum length of the mention. Defaults to 30.

TYPE: int DEFAULT: 30

entity_token_1

The first entity token. Defaults to ''.

TYPE: str DEFAULT: '<ent>'

entity_token_2

The second entity token. Defaults to ''.

TYPE: str DEFAULT: '<ent2>'

entity_unk_token

The unknown entity token. Defaults to '[UNK]'.

TYPE: str DEFAULT: '[UNK]'

entity_pad_token

The padding entity token. Defaults to '[PAD]'.

TYPE: str DEFAULT: '[PAD]'

entity_mask_token

The masked entity token. Defaults to '[MASK]'.

TYPE: str DEFAULT: '[MASK]'

entity_mask2_token

The second masked entity token. Defaults to '[MASK2]'.

TYPE: str DEFAULT: '[MASK2]'

errors

The error handling strategy. Defaults to 'replace'.

TYPE: str DEFAULT: 'replace'

bos_token

The beginning of sentence token. Defaults to ''.

TYPE: str DEFAULT: '<s>'

eos_token

The end of sentence token. Defaults to ''.

TYPE: str DEFAULT: '</s>'

sep_token

The separator token. Defaults to ''.

TYPE: str DEFAULT: '</s>'

cls_token

The classification token. Defaults to ''.

TYPE: str DEFAULT: '<s>'

unk_token

The unknown token. Defaults to ''.

TYPE: str DEFAULT: '<unk>'

pad_token

The padding token. Defaults to ''.

TYPE: str DEFAULT: '<pad>'

mask_token

The masked token. Defaults to ''.

TYPE: str DEFAULT: '<mask>'

add_prefix_space

Whether to add space before the token. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the specified entity special token is not found in the entity vocabulary file.

ValueError

If the task is not supported. Select task from ['entity_classification', 'entity_pair_classification', 'entity_span_classification'] only.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
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
def __init__(
    self,
    vocab_file,
    merges_file,
    entity_vocab_file,
    task=None,
    max_entity_length=32,
    max_mention_length=30,
    entity_token_1="<ent>",
    entity_token_2="<ent2>",
    entity_unk_token="[UNK]",
    entity_pad_token="[PAD]",
    entity_mask_token="[MASK]",
    entity_mask2_token="[MASK2]",
    errors="replace",
    bos_token="<s>",
    eos_token="</s>",
    sep_token="</s>",
    cls_token="<s>",
    unk_token="<unk>",
    pad_token="<pad>",
    mask_token="<mask>",
    add_prefix_space=False,
    **kwargs,
):
    """Initialize the LukeTokenizer class.

    This method initializes an instance of the LukeTokenizer class. It takes the following parameters:

    Args:
        self: The instance of the class.
        vocab_file (str): The path to the vocabulary file.
        merges_file (str): The path to the merges file.
        entity_vocab_file (str): The path to the entity vocabulary file.
        task (str, optional): The task for which the tokenizer is used. Defaults to None.
        max_entity_length (int, optional): The maximum length of the entity. Defaults to 32.
        max_mention_length (int, optional): The maximum length of the mention. Defaults to 30.
        entity_token_1 (str, optional): The first entity token. Defaults to '<ent>'.
        entity_token_2 (str, optional): The second entity token. Defaults to '<ent2>'.
        entity_unk_token (str, optional): The unknown entity token. Defaults to '[UNK]'.
        entity_pad_token (str, optional): The padding entity token. Defaults to '[PAD]'.
        entity_mask_token (str, optional): The masked entity token. Defaults to '[MASK]'.
        entity_mask2_token (str, optional): The second masked entity token. Defaults to '[MASK2]'.
        errors (str, optional): The error handling strategy. Defaults to 'replace'.
        bos_token (str, optional): The beginning of sentence token. Defaults to '<s>'.
        eos_token (str, optional): The end of sentence token. Defaults to '</s>'.
        sep_token (str, optional): The separator token. Defaults to '</s>'.
        cls_token (str, optional): The classification token. Defaults to '<s>'.
        unk_token (str, optional): The unknown token. Defaults to '<unk>'.
        pad_token (str, optional): The padding token. Defaults to '<pad>'.
        mask_token (str, optional): The masked token. Defaults to '<mask>'.
        add_prefix_space (bool, optional): Whether to add space before the token. Defaults to False.

    Returns:
        None

    Raises:
        ValueError: If the specified entity special token is not found in the entity vocabulary file.
        ValueError: If the task is not supported. Select task from ['entity_classification',
            'entity_pair_classification', 'entity_span_classification'] only.
    """
    bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
    eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
    sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
    cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
    unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
    pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token

    # Mask token behave like a normal word, i.e. include the space before it
    mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token

    with open(vocab_file, encoding="utf-8") as vocab_handle:
        self.encoder = json.load(vocab_handle)
    self.decoder = {v: k for k, v in self.encoder.items()}
    self.errors = errors  # how to handle errors in decoding
    self.byte_encoder = bytes_to_unicode()
    self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
    with open(merges_file, encoding="utf-8") as merges_handle:
        bpe_merges = merges_handle.read().split("\n")[1:-1]
    bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
    self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
    self.cache = {}
    self.add_prefix_space = add_prefix_space

    # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
    self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")

    # we add 2 special tokens for downstream tasks
    # for more information about lstrip and rstrip, see https://github.com/huggingface/transformers/pull/2778
    entity_token_1 = (
        AddedToken(entity_token_1, lstrip=False, rstrip=False)
        if isinstance(entity_token_1, str)
        else entity_token_1
    )
    entity_token_2 = (
        AddedToken(entity_token_2, lstrip=False, rstrip=False)
        if isinstance(entity_token_2, str)
        else entity_token_2
    )
    kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", [])
    kwargs["additional_special_tokens"] += [entity_token_1, entity_token_2]

    with open(entity_vocab_file, encoding="utf-8") as entity_vocab_handle:
        self.entity_vocab = json.load(entity_vocab_handle)
    for entity_special_token in [entity_unk_token, entity_pad_token, entity_mask_token, entity_mask2_token]:
        if entity_special_token not in self.entity_vocab:
            raise ValueError(
                f"Specified entity special token ``{entity_special_token}`` is not found in entity_vocab. "
                f"Probably an incorrect entity vocab file is loaded: {entity_vocab_file}."
            )
    self.entity_unk_token_id = self.entity_vocab[entity_unk_token]
    self.entity_pad_token_id = self.entity_vocab[entity_pad_token]
    self.entity_mask_token_id = self.entity_vocab[entity_mask_token]
    self.entity_mask2_token_id = self.entity_vocab[entity_mask2_token]

    self.task = task
    if task is None or task == "entity_span_classification":
        self.max_entity_length = max_entity_length
    elif task == "entity_classification":
        self.max_entity_length = 1
    elif task == "entity_pair_classification":
        self.max_entity_length = 2
    else:
        raise ValueError(
            f"Task {task} not supported. Select task from ['entity_classification', 'entity_pair_classification',"
            " 'entity_span_classification'] only."
        )

    self.max_mention_length = max_mention_length

    super().__init__(
        errors=errors,
        bos_token=bos_token,
        eos_token=eos_token,
        unk_token=unk_token,
        sep_token=sep_token,
        cls_token=cls_token,
        pad_token=pad_token,
        mask_token=mask_token,
        add_prefix_space=add_prefix_space,
        task=task,
        max_entity_length=32,
        max_mention_length=30,
        entity_token_1="<ent>",
        entity_token_2="<ent2>",
        entity_unk_token=entity_unk_token,
        entity_pad_token=entity_pad_token,
        entity_mask_token=entity_mask_token,
        entity_mask2_token=entity_mask2_token,
        **kwargs,
    )

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.bpe(token)

This method 'bpe' in the class 'LukeTokenizer' performs Byte Pair Encoding (BPE) on the input token.

PARAMETER DESCRIPTION
self

The instance of the LukeTokenizer class.

TYPE: LukeTokenizer

token

The input token to be processed using Byte Pair Encoding.

TYPE: str

RETURNS DESCRIPTION
str

The processed token after applying Byte Pair Encoding.

RAISES DESCRIPTION
ValueError

If the input token is empty.

TypeError

If the input token is not a string.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
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
def bpe(self, token):
    """
    This method 'bpe' in the class 'LukeTokenizer' performs Byte Pair Encoding (BPE) on the input token.

    Args:
        self (LukeTokenizer): The instance of the LukeTokenizer class.
        token (str): The input token to be processed using Byte Pair Encoding.

    Returns:
        str: The processed token after applying Byte Pair Encoding.

    Raises:
        ValueError: If the input token is empty.
        TypeError: If the input token is not a string.
    """
    if token in self.cache:
        return self.cache[token]
    word = tuple(token)
    pairs = get_pairs(word)

    if not pairs:
        return token

    while True:
        bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
        if bigram not in self.bpe_ranks:
            break
        first, second = bigram
        new_word = []
        i = 0
        while i < len(word):
            try:
                j = word.index(first, i)
            except ValueError:
                new_word.extend(word[i:])
                break
            else:
                new_word.extend(word[i:j])
                i = j

            if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
                new_word.append(first + second)
                i += 2
            else:
                new_word.append(word[i])
                i += 1
        new_word = tuple(new_word)
        word = new_word
        if len(word) == 1:
            break
        pairs = get_pairs(word)
    word = " ".join(word)
    self.cache[token] = word
    return word

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

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

  • single sequence: <s> X </s>
  • pair of sequences: <s> A </s></s> B </s>
PARAMETER DESCRIPTION
token_ids_0

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

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION
List[int]

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def build_inputs_with_special_tokens(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    adding special tokens. A LUKE sequence has the following format:

    - single sequence: `<s> X </s>`
    - pair of sequences: `<s> A </s></s> B </s>`

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

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """
    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + sep + token_ids_1 + sep

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.convert_tokens_to_string(tokens)

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
558
559
560
561
562
def convert_tokens_to_string(self, tokens):
    """Converts a sequence of tokens (string) in a single string."""
    text = "".join(tokens)
    text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
    return text

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Create a mask from the two sequences passed to be used in a sequence-pair classification task. LUKE does not make use of token type ids, therefore a list of zeros is returned.

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION
List[int]

List[int]: List of zeros.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
def create_token_type_ids_from_sequences(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Create a mask from the two sequences passed to be used in a sequence-pair classification task. LUKE does not
    make use of token type ids, therefore a list of zeros is returned.

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

    Returns:
        `List[int]`: List of zeros.
    """
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]

    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.get_special_tokens_mask(token_ids_0, token_ids_1=None, already_has_special_tokens=False)

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

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

already_has_special_tokens

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

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

RETURNS DESCRIPTION
List[int]

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
def get_special_tokens_mask(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
    """
    Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
    special tokens using the tokenizer `prepare_for_model` method.

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

    Returns:
        `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
    """
    if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
        )

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

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.get_vocab()

Retrieves the vocabulary dictionary for the 'LukeTokenizer' class.

PARAMETER DESCRIPTION
self

An instance of the 'LukeTokenizer' class.

RETURNS DESCRIPTION
dict

A dictionary containing the vocabulary of the tokenizer. The keys are the tokens and the values are their corresponding IDs.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def get_vocab(self):
    """
    Retrieves the vocabulary dictionary for the 'LukeTokenizer' class.

    Args:
        self: An instance of the 'LukeTokenizer' class.

    Returns:
        dict: A dictionary containing the vocabulary of the tokenizer. The keys are the tokens
            and the values are their corresponding IDs.

    Raises:
        None.
    """
    vocab = dict(self.encoder).copy()
    vocab.update(self.added_tokens_encoder)
    return vocab

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.pad(encoded_inputs, padding=True, max_length=None, max_entity_length=None, pad_to_multiple_of=None, return_attention_mask=None, return_tensors=None, verbose=True)

Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with self.padding_side, self.pad_token_id and self.pad_token_type_id) .. note:: If the encoded_inputs passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the result will use the same type unless you provide a different tensor type with return_tensors. In the case of PyTorch tensors, you will lose the specific device of your tensors however.

PARAMETER DESCRIPTION
encoded_inputs

Tokenized inputs. Can represent one input ([BatchEncoding] or Dict[str, List[int]]) or a batch of tokenized inputs (list of [BatchEncoding], Dict[str, List[List[int]]] or List[Dict[str, List[int]]]) so you can use this method during preprocessing as well as in a PyTorch Dataloader collate function. Instead of List[int] you can have tensors (numpy arrays, PyTorch tensors or TensorFlow tensors), see the note above for the return type.

TYPE: [`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`

padding

Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among:

  • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
  • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
  • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).

TYPE: `bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True` DEFAULT: True

max_length

Maximum length of the returned list and optionally padding length (see above).

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

max_entity_length

The maximum length of the entity sequence.

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

pad_to_multiple_of

If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).

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

return_attention_mask

Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer's default, defined by the return_outputs attribute. What are attention masks?

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

return_tensors

If set, will return tensors instead of list of python integers. Acceptable values are:

  • 'tf': Return TensorFlow tf.constant objects.
  • 'pt': Return PyTorch torch.Tensor objects.
  • 'np': Return Numpy np.ndarray objects.

TYPE: `str` or [`~utils.TensorType`], *optional* DEFAULT: None

verbose

Whether or not to print more information and warnings.

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
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
1707
1708
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
def pad(
    self,
    encoded_inputs: Union[
        BatchEncoding,
        List[BatchEncoding],
        Dict[str, EncodedInput],
        Dict[str, List[EncodedInput]],
        List[Dict[str, EncodedInput]],
    ],
    padding: Union[bool, str, PaddingStrategy] = True,
    max_length: Optional[int] = None,
    max_entity_length: Optional[int] = None,
    pad_to_multiple_of: Optional[int] = None,
    return_attention_mask: Optional[bool] = None,
    return_tensors: Optional[Union[str, TensorType]] = None,
    verbose: bool = True,
) -> BatchEncoding:
    """
    Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
    in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with
    `self.padding_side`, `self.pad_token_id` and `self.pad_token_type_id`) .. note:: If the `encoded_inputs` passed
    are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the result will use the same type unless
    you provide a different tensor type with `return_tensors`. In the case of PyTorch tensors, you will lose the
    specific device of your tensors however.

    Args:
        encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
            Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
            tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
            List[int]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
            collate function. Instead of `List[int]` you can have tensors (numpy arrays, PyTorch tensors or
            TensorFlow tensors), see the note above for the return type.
        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
             Select a strategy to pad the returned sequences (according to the model's padding side and padding
             index) among:

            - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
            sequence if provided).
            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
            acceptable input length for the model if that argument is not provided.
            - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
            lengths).
        max_length (`int`, *optional*):
            Maximum length of the returned list and optionally padding length (see above).
        max_entity_length (`int`, *optional*):
            The maximum length of the entity sequence.
        pad_to_multiple_of (`int`, *optional*):
            If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
            the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
        return_attention_mask (`bool`, *optional*):
            Whether to return the attention mask. If left to the default, will return the attention mask according
            to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention
            masks?](../glossary#attention-mask)
        return_tensors (`str` or [`~utils.TensorType`], *optional*):
            If set, will return tensors instead of list of python integers. Acceptable values are:

            - `'tf'`: Return TensorFlow `tf.constant` objects.
            - `'pt'`: Return PyTorch `torch.Tensor` objects.
            - `'np'`: Return Numpy `np.ndarray` objects.
        verbose (`bool`, *optional*, defaults to `True`):
            Whether or not to print more information and warnings.
    """
    # If we have a list of dicts, let's convert it in a dict of lists
    # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
    if isinstance(encoded_inputs, (list, tuple)) and isinstance(encoded_inputs[0], Mapping):
        encoded_inputs = {key: [example[key] for example in encoded_inputs] for key in encoded_inputs[0].keys()}

    # The model's main input name, usually `input_ids`, has be passed for padding
    if self.model_input_names[0] not in encoded_inputs:
        raise ValueError(
            "You should supply an encoding or a list of encodings to this method "
            f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
        )

    required_input = encoded_inputs[self.model_input_names[0]]

    if not required_input:
        if return_attention_mask:
            encoded_inputs["attention_mask"] = []
        return encoded_inputs

    # If we have PyTorch/TF/NumPy tensors/arrays as inputs, we cast them as python objects
    # and rebuild them afterwards if no return_tensors is specified
    # Note that we lose the specific device the tensor may be on for PyTorch

    first_element = required_input[0]
    if isinstance(first_element, (list, tuple)):
        # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
        index = 0
        while len(required_input[index]) == 0:
            index += 1
        if index < len(required_input):
            first_element = required_input[index][0]
    # At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
    if not isinstance(first_element, (int, list, tuple)):
        if is_mindspore_tensor(first_element):
            return_tensors = "ms" if return_tensors is None else return_tensors
        elif isinstance(first_element, np.ndarray):
            return_tensors = "np" if return_tensors is None else return_tensors
        else:
            raise ValueError(
                f"type of {first_element} unknown: {type(first_element)}. "
                "Should be one of a python, numpy, pytorch or tensorflow object."
            )

        for key, value in encoded_inputs.items():
            encoded_inputs[key] = to_py_obj(value)

    # Convert padding_strategy in PaddingStrategy
    padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
        padding=padding, max_length=max_length, verbose=verbose
    )

    if max_entity_length is None:
        max_entity_length = self.max_entity_length

    required_input = encoded_inputs[self.model_input_names[0]]
    if required_input and not isinstance(required_input[0], (list, tuple)):
        encoded_inputs = self._pad(
            encoded_inputs,
            max_length=max_length,
            max_entity_length=max_entity_length,
            padding_strategy=padding_strategy,
            pad_to_multiple_of=pad_to_multiple_of,
            return_attention_mask=return_attention_mask,
        )
        return BatchEncoding(encoded_inputs, tensor_type=return_tensors)

    batch_size = len(required_input)
    if any(len(v) != batch_size for v in encoded_inputs.values()):
        raise ValueError("Some items in the output dictionary have a different batch size than others.")

    if padding_strategy == PaddingStrategy.LONGEST:
        max_length = max(len(inputs) for inputs in required_input)
        max_entity_length = (
            max(len(inputs) for inputs in encoded_inputs["entity_ids"]) if "entity_ids" in encoded_inputs else 0
        )
        padding_strategy = PaddingStrategy.MAX_LENGTH

    batch_outputs = {}
    for i in range(batch_size):
        inputs = {k: v[i] for k, v in encoded_inputs.items()}
        outputs = self._pad(
            inputs,
            max_length=max_length,
            max_entity_length=max_entity_length,
            padding_strategy=padding_strategy,
            pad_to_multiple_of=pad_to_multiple_of,
            return_attention_mask=return_attention_mask,
        )

        for key, value in outputs.items():
            if key not in batch_outputs:
                batch_outputs[key] = []
            batch_outputs[key].append(value)

    return BatchEncoding(batch_outputs, tensor_type=return_tensors)

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.prepare_for_model(ids, pair_ids=None, entity_ids=None, pair_entity_ids=None, entity_token_spans=None, pair_entity_token_spans=None, add_special_tokens=True, padding=False, truncation=None, max_length=None, max_entity_length=None, stride=0, pad_to_multiple_of=None, return_tensors=None, return_token_type_ids=None, return_attention_mask=None, return_overflowing_tokens=False, return_special_tokens_mask=False, return_offsets_mapping=False, return_length=False, verbose=True, prepend_batch_axis=False, **kwargs)

Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids, entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and manages a moving window (with user defined stride) for overflowing tokens. Please Note, for pair_ids different than None and truncation_strategy = longest_first or True, it is not possible to return overflowing tokens. Such a combination of arguments will raise an error.

PARAMETER DESCRIPTION
ids

Tokenized input ids of the first sequence.

TYPE: `List[int]`

pair_ids

Tokenized input ids of the second sequence.

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

entity_ids

Entity ids of the first sequence.

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

pair_entity_ids

Entity ids of the second sequence.

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

entity_token_spans

Entity spans of the first sequence.

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

pair_entity_token_spans

Entity spans of the second sequence.

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

max_entity_length

The maximum length of the entity sequence.

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

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
def prepare_for_model(
    self,
    ids: List[int],
    pair_ids: Optional[List[int]] = None,
    entity_ids: Optional[List[int]] = None,
    pair_entity_ids: Optional[List[int]] = None,
    entity_token_spans: Optional[List[Tuple[int, int]]] = None,
    pair_entity_token_spans: Optional[List[Tuple[int, int]]] = None,
    add_special_tokens: bool = True,
    padding: Union[bool, str, PaddingStrategy] = False,
    truncation: Union[bool, str, TruncationStrategy] = None,
    max_length: Optional[int] = None,
    max_entity_length: Optional[int] = None,
    stride: int = 0,
    pad_to_multiple_of: Optional[int] = None,
    return_tensors: Optional[Union[str, TensorType]] = None,
    return_token_type_ids: Optional[bool] = None,
    return_attention_mask: Optional[bool] = None,
    return_overflowing_tokens: bool = False,
    return_special_tokens_mask: bool = False,
    return_offsets_mapping: bool = False,
    return_length: bool = False,
    verbose: bool = True,
    prepend_batch_axis: bool = False,
    **kwargs,
) -> BatchEncoding:
    """
    Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids,
    entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing
    while taking into account the special tokens and manages a moving window (with user defined stride) for
    overflowing tokens. Please Note, for *pair_ids* different than `None` and *truncation_strategy = longest_first*
    or `True`, it is not possible to return overflowing tokens. Such a combination of arguments will raise an
    error.

    Args:
        ids (`List[int]`):
            Tokenized input ids of the first sequence.
        pair_ids (`List[int]`, *optional*):
            Tokenized input ids of the second sequence.
        entity_ids (`List[int]`, *optional*):
            Entity ids of the first sequence.
        pair_entity_ids (`List[int]`, *optional*):
            Entity ids of the second sequence.
        entity_token_spans (`List[Tuple[int, int]]`, *optional*):
            Entity spans of the first sequence.
        pair_entity_token_spans (`List[Tuple[int, int]]`, *optional*):
            Entity spans of the second sequence.
        max_entity_length (`int`, *optional*):
            The maximum length of the entity sequence.
    """
    # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
    padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
        padding=padding,
        truncation=truncation,
        max_length=max_length,
        pad_to_multiple_of=pad_to_multiple_of,
        verbose=verbose,
        **kwargs,
    )

    # Compute lengths
    pair = bool(pair_ids is not None)
    len_ids = len(ids)
    len_pair_ids = len(pair_ids) if pair else 0

    if return_token_type_ids and not add_special_tokens:
        raise ValueError(
            "Asking to return token_type_ids while setting add_special_tokens to False "
            "results in an undefined behavior. Please set add_special_tokens to True or "
            "set return_token_type_ids to None."
        )
    if (
        return_overflowing_tokens
        and truncation_strategy == TruncationStrategy.LONGEST_FIRST
        and pair_ids is not None
    ):
        raise ValueError(
            "Not possible to return overflowing tokens for pair of sequences with the "
            "`longest_first`. Please select another truncation strategy than `longest_first`, "
            "for instance `only_second` or `only_first`."
        )

    # Load from model defaults
    if return_token_type_ids is None:
        return_token_type_ids = "token_type_ids" in self.model_input_names
    if return_attention_mask is None:
        return_attention_mask = "attention_mask" in self.model_input_names

    encoded_inputs = {}

    # Compute the total size of the returned word encodings
    total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)

    # Truncation: Handle max sequence length and max_entity_length
    overflowing_tokens = []
    if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
        # truncate words up to max_length
        ids, pair_ids, overflowing_tokens = self.truncate_sequences(
            ids,
            pair_ids=pair_ids,
            num_tokens_to_remove=total_len - max_length,
            truncation_strategy=truncation_strategy,
            stride=stride,
        )

    if return_overflowing_tokens:
        encoded_inputs["overflowing_tokens"] = overflowing_tokens
        encoded_inputs["num_truncated_tokens"] = total_len - max_length

    # Add special tokens
    if add_special_tokens:
        sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
        token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
        entity_token_offset = 1  # 1 * <s> token
        pair_entity_token_offset = len(ids) + 3  # 1 * <s> token & 2 * <sep> tokens
    else:
        sequence = ids + pair_ids if pair else ids
        token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
        entity_token_offset = 0
        pair_entity_token_offset = len(ids)

    # Build output dictionary
    encoded_inputs["input_ids"] = sequence
    if return_token_type_ids:
        encoded_inputs["token_type_ids"] = token_type_ids
    if return_special_tokens_mask:
        if add_special_tokens:
            encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
        else:
            encoded_inputs["special_tokens_mask"] = [0] * len(sequence)

    # Set max entity length
    if not max_entity_length:
        max_entity_length = self.max_entity_length

    if entity_ids is not None:
        total_entity_len = 0
        num_invalid_entities = 0
        valid_entity_ids = [ent_id for ent_id, span in zip(entity_ids, entity_token_spans) if span[1] <= len(ids)]
        valid_entity_token_spans = [span for span in entity_token_spans if span[1] <= len(ids)]

        total_entity_len += len(valid_entity_ids)
        num_invalid_entities += len(entity_ids) - len(valid_entity_ids)

        valid_pair_entity_ids, valid_pair_entity_token_spans = None, None
        if pair_entity_ids is not None:
            valid_pair_entity_ids = [
                ent_id
                for ent_id, span in zip(pair_entity_ids, pair_entity_token_spans)
                if span[1] <= len(pair_ids)
            ]
            valid_pair_entity_token_spans = [span for span in pair_entity_token_spans if span[1] <= len(pair_ids)]
            total_entity_len += len(valid_pair_entity_ids)
            num_invalid_entities += len(pair_entity_ids) - len(valid_pair_entity_ids)

        if num_invalid_entities != 0:
            logger.warning(
                f"{num_invalid_entities} entities are ignored because their entity spans are invalid due to the"
                " truncation of input tokens"
            )

        if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and total_entity_len > max_entity_length:
            # truncate entities up to max_entity_length
            valid_entity_ids, valid_pair_entity_ids, overflowing_entities = self.truncate_sequences(
                valid_entity_ids,
                pair_ids=valid_pair_entity_ids,
                num_tokens_to_remove=total_entity_len - max_entity_length,
                truncation_strategy=truncation_strategy,
                stride=stride,
            )
            valid_entity_token_spans = valid_entity_token_spans[: len(valid_entity_ids)]
            if valid_pair_entity_token_spans is not None:
                valid_pair_entity_token_spans = valid_pair_entity_token_spans[: len(valid_pair_entity_ids)]

        if return_overflowing_tokens:
            encoded_inputs["overflowing_entities"] = overflowing_entities
            encoded_inputs["num_truncated_entities"] = total_entity_len - max_entity_length

        final_entity_ids = valid_entity_ids + valid_pair_entity_ids if valid_pair_entity_ids else valid_entity_ids
        encoded_inputs["entity_ids"] = list(final_entity_ids)
        entity_position_ids = []
        entity_start_positions = []
        entity_end_positions = []
        for token_spans, offset in (
            (valid_entity_token_spans, entity_token_offset),
            (valid_pair_entity_token_spans, pair_entity_token_offset),
        ):
            if token_spans is not None:
                for start, end in token_spans:
                    start += offset
                    end += offset
                    position_ids = list(range(start, end))[: self.max_mention_length]
                    position_ids += [-1] * (self.max_mention_length - end + start)
                    entity_position_ids.append(position_ids)
                    entity_start_positions.append(start)
                    entity_end_positions.append(end - 1)

        encoded_inputs["entity_position_ids"] = entity_position_ids
        if self.task == "entity_span_classification":
            encoded_inputs["entity_start_positions"] = entity_start_positions
            encoded_inputs["entity_end_positions"] = entity_end_positions

        if return_token_type_ids:
            encoded_inputs["entity_token_type_ids"] = [0] * len(encoded_inputs["entity_ids"])

    # Check lengths
    self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)

    # Padding
    if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
        encoded_inputs = self.pad(
            encoded_inputs,
            max_length=max_length,
            max_entity_length=max_entity_length,
            padding=padding_strategy.value,
            pad_to_multiple_of=pad_to_multiple_of,
            return_attention_mask=return_attention_mask,
        )

    if return_length:
        encoded_inputs["length"] = len(encoded_inputs["input_ids"])

    batch_outputs = BatchEncoding(
        encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
    )

    return batch_outputs

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.prepare_for_tokenization(text, is_split_into_words=False, **kwargs)

Prepares the input text for tokenization by adding a prefix space if necessary.

PARAMETER DESCRIPTION
self

An instance of the LukeTokenizer class.

TYPE: LukeTokenizer

text

The input text to be tokenized.

TYPE: str

is_split_into_words

A flag indicating if the input text is already split into words. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
None

The method modifies the input text in-place.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
    """
    Prepares the input text for tokenization by adding a prefix space if necessary.

    Args:
        self (LukeTokenizer): An instance of the LukeTokenizer class.
        text (str): The input text to be tokenized.
        is_split_into_words (bool): A flag indicating if the input text is already split into words.
            Defaults to False.

    Returns:
        None: The method modifies the input text in-place.

    Raises:
        None.
    """
    add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
    if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
        text = " " + text
    return (text, kwargs)

mindnlp.transformers.models.luke.tokenization_luke.LukeTokenizer.save_vocabulary(save_directory, filename_prefix=None)

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

PARAMETER DESCRIPTION
self

Instance of LukeTokenizer class.

save_directory

The directory path where the vocabulary files will be saved.

TYPE: str

filename_prefix

An optional prefix to be added to the filename. Default is None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing paths to the saved vocabulary files - vocab_file, merge_file, and entity_vocab_file.

RAISES DESCRIPTION
FileNotFoundError

If the specified save_directory does not exist.

IOError

If there is an issue with reading or writing the vocabulary files.

ValueError

If the provided filename_prefix is not a string.

Exception

Any other unexpected error that may occur during the execution of the method.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary to specified directory with an optional filename prefix.

    Args:
        self: Instance of LukeTokenizer class.
        save_directory (str): The directory path where the vocabulary files will be saved.
        filename_prefix (Optional[str]): An optional prefix to be added to the filename. Default is None.

    Returns:
        Tuple[str]: A tuple containing paths to the saved vocabulary files - vocab_file, merge_file,
            and entity_vocab_file.

    Raises:
        FileNotFoundError: If the specified save_directory does not exist.
        IOError: If there is an issue with reading or writing the vocabulary files.
        ValueError: If the provided filename_prefix is not a string.
        Exception: Any other unexpected error that may occur during the execution of the method.
    """
    if not os.path.isdir(save_directory):
        logger.error(f"Vocabulary path ({save_directory}) should be a directory")
        return
    vocab_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
    )
    merge_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
    )

    with open(vocab_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

    index = 0
    with open(merge_file, "w", encoding="utf-8") as writer:
        writer.write("#version: 0.2\n")
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
            if index != token_index:
                logger.warning(
                    f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                    " Please check that the tokenizer is not corrupted!"
                )
                index = token_index
            writer.write(" ".join(bpe_tokens) + "\n")
            index += 1

    entity_vocab_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["entity_vocab_file"]
    )

    with open(entity_vocab_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(self.entity_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

    return vocab_file, merge_file, entity_vocab_file

mindnlp.transformers.models.luke.tokenization_luke.bytes_to_unicode() cached

Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on.

The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def bytes_to_unicode():
    """
    Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
    characters the bpe code barfs on.

    The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
    if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
    decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
    tables between utf-8 bytes and unicode strings.
    """
    bs = (
        list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
    )
    cs = bs[:]
    n = 0
    for b in range(2**8):
        if b not in bs:
            bs.append(b)
            cs.append(2**8 + n)
            n += 1
    cs = [chr(n) for n in cs]
    return dict(zip(bs, cs))

mindnlp.transformers.models.luke.tokenization_luke.get_pairs(word)

Return set of symbol pairs in a word.

Word is represented as tuple of symbols (symbols being variable-length strings).

Source code in mindnlp/transformers/models/luke/tokenization_luke.py
178
179
180
181
182
183
184
185
186
187
188
189
def get_pairs(word):
    """
    Return set of symbol pairs in a word.

    Word is represented as tuple of symbols (symbols being variable-length strings).
    """
    pairs = set()
    prev_char = word[0]
    for char in word[1:]:
        pairs.add((prev_char, char))
        prev_char = char
    return pairs