Skip to content

layoutlmv2

mindnlp.transformers.models.layoutlmv2.configuration_layoutlmv2

LayoutLMv2 model configuration

mindnlp.transformers.models.layoutlmv2.configuration_layoutlmv2.LayoutLMv2Config

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [LayoutLMv2Model]. It is used to instantiate an LayoutLMv2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the LayoutLMv2 microsoft/layoutlmv2-base-uncased architecture.

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

PARAMETER DESCRIPTION
vocab_size

Vocabulary size of the LayoutLMv2 model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [LayoutLMv2Model] or [TFLayoutLMv2Model].

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

hidden_size

Dimension of the encoder layers and the pooler layer.

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

num_hidden_layers

Number of hidden layers in the Transformer encoder.

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

num_attention_heads

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

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

intermediate_size

Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.

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

hidden_act

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

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

hidden_dropout_prob

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

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

attention_probs_dropout_prob

The dropout ratio for the attention probabilities.

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

max_position_embeddings

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

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

type_vocab_size

The vocabulary size of the token_type_ids passed when calling [LayoutLMv2Model] or [TFLayoutLMv2Model].

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

initializer_range

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

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

layer_norm_eps

The epsilon used by the layer normalization layers.

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

max_2d_position_embeddings

The maximum value that the 2D position embedding might ever be used with. Typically set this to something large just in case (e.g., 1024).

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

max_rel_pos

The maximum number of relative positions to be used in the self-attention mechanism.

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

rel_pos_bins

The number of relative position bins to be used in the self-attention mechanism.

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

fast_qkv

Whether or not to use a single matrix for the queries, keys, values in the self-attention layers.

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

max_rel_2d_pos

The maximum number of relative 2D positions in the self-attention mechanism.

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

rel_2d_pos_bins

The number of 2D relative position bins in the self-attention mechanism.

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

image_feature_pool_shape

The shape of the average-pooled feature map.

TYPE: `List[int]`, *optional*, defaults to [7, 7, 256] DEFAULT: [7, 7, 256]

coordinate_size

Dimension of the coordinate embeddings.

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

shape_size

Dimension of the width and height embeddings.

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

has_relative_attention_bias

Whether or not to use a relative attention bias in the self-attention mechanism.

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

has_spatial_attention_bias

Whether or not to use a spatial attention bias in the self-attention mechanism.

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

has_visual_segment_embedding

Whether or not to add visual segment embeddings.

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

detectron2_config_args

Dictionary containing the configuration arguments of the Detectron2 visual backbone. Refer to this file for details regarding default values.

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

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

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

    Args:
        vocab_size (`int`, *optional*, defaults to 30522):
            Vocabulary size of the LayoutLMv2 model. Defines the number of different tokens that can be represented by
            the `inputs_ids` passed when calling [`LayoutLMv2Model`] or [`TFLayoutLMv2Model`].
        hidden_size (`int`, *optional*, defaults to 768):
            Dimension of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (`int`, *optional*, defaults to 3072):
            Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` are supported.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention probabilities.
        max_position_embeddings (`int`, *optional*, defaults to 512):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        type_vocab_size (`int`, *optional*, defaults to 2):
            The vocabulary size of the `token_type_ids` passed when calling [`LayoutLMv2Model`] or
            [`TFLayoutLMv2Model`].
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-12):
            The epsilon used by the layer normalization layers.
        max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
            The maximum value that the 2D position embedding might ever be used with. Typically set this to something
            large just in case (e.g., 1024).
        max_rel_pos (`int`, *optional*, defaults to 128):
            The maximum number of relative positions to be used in the self-attention mechanism.
        rel_pos_bins (`int`, *optional*, defaults to 32):
            The number of relative position bins to be used in the self-attention mechanism.
        fast_qkv (`bool`, *optional*, defaults to `True`):
            Whether or not to use a single matrix for the queries, keys, values in the self-attention layers.
        max_rel_2d_pos (`int`, *optional*, defaults to 256):
            The maximum number of relative 2D positions in the self-attention mechanism.
        rel_2d_pos_bins (`int`, *optional*, defaults to 64):
            The number of 2D relative position bins in the self-attention mechanism.
        image_feature_pool_shape (`List[int]`, *optional*, defaults to [7, 7, 256]):
            The shape of the average-pooled feature map.
        coordinate_size (`int`, *optional*, defaults to 128):
            Dimension of the coordinate embeddings.
        shape_size (`int`, *optional*, defaults to 128):
            Dimension of the width and height embeddings.
        has_relative_attention_bias (`bool`, *optional*, defaults to `True`):
            Whether or not to use a relative attention bias in the self-attention mechanism.
        has_spatial_attention_bias (`bool`, *optional*, defaults to `True`):
            Whether or not to use a spatial attention bias in the self-attention mechanism.
        has_visual_segment_embedding (`bool`, *optional*, defaults to `False`):
            Whether or not to add visual segment embeddings.
        detectron2_config_args (`dict`, *optional*):
            Dictionary containing the configuration arguments of the Detectron2 visual backbone. Refer to [this
            file](https://github.com/microsoft/unilm/blob/master/layoutlmft/layoutlmft/models/layoutlmv2/detectron2_config.py)
            for details regarding default values.

    Example:
        ```python
        >>> from transformers import LayoutLMv2Config, LayoutLMv2Model
        ...
        >>> # Initializing a LayoutLMv2 microsoft/layoutlmv2-base-uncased style configuration
        >>> configuration = LayoutLMv2Config()
        ...
        >>> # Initializing a model (with random weights) from the microsoft/layoutlmv2-base-uncased style configuration
        >>> model = LayoutLMv2Model(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "layoutlmv2"

    def __init__(
            self,
            vocab_size=30522,
            hidden_size=768,
            num_hidden_layers=12,
            num_attention_heads=12,
            intermediate_size=3072,
            hidden_act="gelu",
            hidden_dropout_prob=0.1,
            attention_probs_dropout_prob=0.1,
            max_position_embeddings=512,
            type_vocab_size=2,
            initializer_range=0.02,
            layer_norm_eps=1e-12,
            pad_token_id=0,
            max_2d_position_embeddings=1024,
            max_rel_pos=128,
            rel_pos_bins=32,
            fast_qkv=True,
            max_rel_2d_pos=256,
            rel_2d_pos_bins=64,
            image_feature_pool_shape=[7, 7, 256],
            coordinate_size=128,
            shape_size=128,
            has_relative_attention_bias=True,
            has_spatial_attention_bias=True,
            has_visual_segment_embedding=False,
            use_visual_backbone=True,
            detectron2_config_args=None,
            **kwargs,
    ):
        """
        Initializes a LayoutLMv2Config object with the specified parameters.

        Args:
            vocab_size (int): The size of the vocabulary.
            hidden_size (int): The hidden size for the model.
            num_hidden_layers (int): The number of hidden layers in the model.
            num_attention_heads (int): The number of attention heads in the model.
            intermediate_size (int): The size of the intermediate layer in the model.
            hidden_act (str): The activation function for the hidden layers.
            hidden_dropout_prob (float): The dropout probability for the hidden layers.
            attention_probs_dropout_prob (float): The dropout probability for the attention probabilities.
            max_position_embeddings (int): The maximum position embeddings allowed.
            type_vocab_size (int): The size of the type vocabulary.
            initializer_range (float): The range for parameter initialization.
            layer_norm_eps (float): The epsilon value for layer normalization.
            pad_token_id (int): The token ID for padding.
            max_2d_position_embeddings (int): The maximum 2D position embeddings allowed.
            max_rel_pos (int): The maximum relative position.
            rel_pos_bins (int): The number of relative position bins.
            fast_qkv (bool): Flag to enable fast query, key, value computation.
            max_rel_2d_pos (int): The maximum relative 2D position.
            rel_2d_pos_bins (int): The number of relative 2D position bins.
            image_feature_pool_shape (list): The shape of the image feature pool.
            coordinate_size (int): The size of coordinates.
            shape_size (int): The size of shapes.
            has_relative_attention_bias (bool): Flag indicating if relative attention bias is used.
            has_spatial_attention_bias (bool): Flag indicating if spatial attention bias is used.
            has_visual_segment_embedding (bool): Flag indicating if visual segment embedding is used.
            use_visual_backbone (bool): Flag indicating if visual backbone is used.
            detectron2_config_args (dict): Additional arguments for the Detectron2 configuration.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(
            vocab_size=vocab_size,
            hidden_size=hidden_size,
            num_hidden_layers=num_hidden_layers,
            num_attention_heads=num_attention_heads,
            intermediate_size=intermediate_size,
            hidden_act=hidden_act,
            hidden_dropout_prob=hidden_dropout_prob,
            attention_probs_dropout_prob=attention_probs_dropout_prob,
            max_position_embeddings=max_position_embeddings,
            type_vocab_size=type_vocab_size,
            initializer_range=initializer_range,
            layer_norm_eps=layer_norm_eps,
            pad_token_id=pad_token_id,
            **kwargs,
        )
        self.max_2d_position_embeddings = max_2d_position_embeddings
        self.max_rel_pos = max_rel_pos
        self.rel_pos_bins = rel_pos_bins
        self.fast_qkv = fast_qkv
        self.max_rel_2d_pos = max_rel_2d_pos
        self.rel_2d_pos_bins = rel_2d_pos_bins
        self.image_feature_pool_shape = image_feature_pool_shape
        self.coordinate_size = coordinate_size
        self.shape_size = shape_size
        self.has_relative_attention_bias = has_relative_attention_bias
        self.has_spatial_attention_bias = has_spatial_attention_bias
        self.has_visual_segment_embedding = has_visual_segment_embedding
        self.use_visual_backbone = use_visual_backbone
        self.detectron2_config_args = (
            detectron2_config_args if detectron2_config_args is not None else self.get_default_detectron2_config()
        )

    @classmethod
    def get_default_detectron2_config(cls):
        '''
        This method returns a dictionary containing the default configuration for the Detectron2 model.
        The configuration includes various settings related to the model's architecture, backbone, region of
        interest (ROI) heads, and other parameters.

        Args:
            cls (class): The class object.

        Returns:
            dict: A dictionary containing the default configuration for the Detectron2 model.

        Raises:
            None.
        '''
        return {
            "MODEL.MASK_ON": True,
            "MODEL.PIXEL_STD": [57.375, 57.120, 58.395],
            "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
            "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
            "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
            "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
            "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
            "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
            "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
            "MODEL.POST_NMS_TOPK_TEST": 1000,
            "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
            "MODEL.ROI_HEADS.NUM_CLASSES": 5,
            "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
            "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
            "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
            "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
            "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
            "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
            "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
            "MODEL.RESNETS.DEPTH": 101,
            "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
            "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
            "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
            "MODEL.RESNETS.NUM_GROUPS": 32,
            "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
            "MODEL.RESNETS.STRIDE_IN_1X1": False,
        }

    def get_detectron2_config(self):
        """
        This method generates a Detectron2 configuration for the LayoutLMv2 model.

        Args:
            self: The instance of the LayoutLMv2Config class.

        Returns:
            None.

        Raises:
            None
        """
        detectron2_config = Dict(
            {
                "MODEL": {
                    "MASK_ON": True,
                    "PIXEL_MEAN": [103.53, 116.28, 123.675],
                    "PIXEL_STD": [57.375, 57.120, 58.395],
                    "BACKBONE": {"NAME": "build_resnet_fpn_backbone"},
                    "FPN": {
                        "FUSE_TYPE": "sum",
                        "IN_FEATURES": ["res2", "res3", "res4", "res5"],
                        "NORM": "BN",
                        "OUT_CHANNELS": 256
                    },
                    "ANCHOR_GENERATOR": {"SIZES": [[32], [64], [128], [256], [512]]},
                    "RPN": {
                        "IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
                        "PRE_NMS_TOPK_TRAIN": 2000,
                        "PRE_NMS_TOPK_TEST": 1000,
                        "POST_NMS_TOPK_TRAIN": 1000,
                    },
                    "POST_NMS_TOPK_TEST": 1000,
                    "ROI_HEADS": {
                        "NAME": "StandardROIHeads",
                        "NUM_CLASSES": 5,
                        "IN_FEATURES": ["p2", "p3", "p4", "p5"],
                    },
                    "ROI_BOX_HEAD": {
                        "NAME": "FastRCNNConvFCHead",
                        "NUM_FC": 2,
                        "POOLER_RESOLUTION": 14,
                    },
                    "ROI_MASK_HEAD": {
                        "NAME": "MaskRCNNConvUpsampleHead",
                        "NUM_CONV": 4,
                        "POOLER_RESOLUTION": 7,
                    },
                    "RESNETS": {
                        "DEPTH": 101,
                        "SIZES": [[32], [64], [128], [256], [512]],
                        "ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
                        "FREEZE_AT": 2,
                        "NORM": "BN",
                        "NUM_GROUPS": 32,
                        "WIDTH_PER_GROUP": 8,
                        "STEM_IN_CHANNELS": 3,
                        "STEM_OUT_CHANNELS": 64,
                        "RES2_OUT_CHANNELS": 256,
                        "STRIDE_IN_1X1": False,
                        "RES5_DILATION": 1,
                        "NAME": "resnet101",
                        "PRETRAINED": True,
                        "NUM_CLASSES": 1000,
                        "OUT_FEATURES": ["res2", "res3", "res4", "res5"]
                    }
                }
            }
        )
        for k, v in self.detectron2_config_args.items():
            attributes = k.split(".")
            to_set = detectron2_config
            for attribute in attributes[:-1]:
                to_set = getattr(to_set, attribute)
            setattr(to_set, attributes[-1], v)

        return detectron2_config

mindnlp.transformers.models.layoutlmv2.configuration_layoutlmv2.LayoutLMv2Config.__init__(vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=0, max_2d_position_embeddings=1024, max_rel_pos=128, rel_pos_bins=32, fast_qkv=True, max_rel_2d_pos=256, rel_2d_pos_bins=64, image_feature_pool_shape=[7, 7, 256], coordinate_size=128, shape_size=128, has_relative_attention_bias=True, has_spatial_attention_bias=True, has_visual_segment_embedding=False, use_visual_backbone=True, detectron2_config_args=None, **kwargs)

Initializes a LayoutLMv2Config object with the specified parameters.

PARAMETER DESCRIPTION
vocab_size

The size of the vocabulary.

TYPE: int DEFAULT: 30522

hidden_size

The hidden size for the model.

TYPE: int DEFAULT: 768

num_hidden_layers

The number of hidden layers in the model.

TYPE: int DEFAULT: 12

num_attention_heads

The number of attention heads in the model.

TYPE: int DEFAULT: 12

intermediate_size

The size of the intermediate layer in the model.

TYPE: int DEFAULT: 3072

hidden_act

The activation function for the hidden layers.

TYPE: str DEFAULT: 'gelu'

hidden_dropout_prob

The dropout probability for the hidden layers.

TYPE: float DEFAULT: 0.1

attention_probs_dropout_prob

The dropout probability for the attention probabilities.

TYPE: float DEFAULT: 0.1

max_position_embeddings

The maximum position embeddings allowed.

TYPE: int DEFAULT: 512

type_vocab_size

The size of the type vocabulary.

TYPE: int DEFAULT: 2

initializer_range

The range for parameter initialization.

TYPE: float DEFAULT: 0.02

layer_norm_eps

The epsilon value for layer normalization.

TYPE: float DEFAULT: 1e-12

pad_token_id

The token ID for padding.

TYPE: int DEFAULT: 0

max_2d_position_embeddings

The maximum 2D position embeddings allowed.

TYPE: int DEFAULT: 1024

max_rel_pos

The maximum relative position.

TYPE: int DEFAULT: 128

rel_pos_bins

The number of relative position bins.

TYPE: int DEFAULT: 32

fast_qkv

Flag to enable fast query, key, value computation.

TYPE: bool DEFAULT: True

max_rel_2d_pos

The maximum relative 2D position.

TYPE: int DEFAULT: 256

rel_2d_pos_bins

The number of relative 2D position bins.

TYPE: int DEFAULT: 64

image_feature_pool_shape

The shape of the image feature pool.

TYPE: list DEFAULT: [7, 7, 256]

coordinate_size

The size of coordinates.

TYPE: int DEFAULT: 128

shape_size

The size of shapes.

TYPE: int DEFAULT: 128

has_relative_attention_bias

Flag indicating if relative attention bias is used.

TYPE: bool DEFAULT: True

has_spatial_attention_bias

Flag indicating if spatial attention bias is used.

TYPE: bool DEFAULT: True

has_visual_segment_embedding

Flag indicating if visual segment embedding is used.

TYPE: bool DEFAULT: False

use_visual_backbone

Flag indicating if visual backbone is used.

TYPE: bool DEFAULT: True

detectron2_config_args

Additional arguments for the Detectron2 configuration.

TYPE: dict DEFAULT: None

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/configuration_layoutlmv2.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def __init__(
        self,
        vocab_size=30522,
        hidden_size=768,
        num_hidden_layers=12,
        num_attention_heads=12,
        intermediate_size=3072,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=2,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        pad_token_id=0,
        max_2d_position_embeddings=1024,
        max_rel_pos=128,
        rel_pos_bins=32,
        fast_qkv=True,
        max_rel_2d_pos=256,
        rel_2d_pos_bins=64,
        image_feature_pool_shape=[7, 7, 256],
        coordinate_size=128,
        shape_size=128,
        has_relative_attention_bias=True,
        has_spatial_attention_bias=True,
        has_visual_segment_embedding=False,
        use_visual_backbone=True,
        detectron2_config_args=None,
        **kwargs,
):
    """
    Initializes a LayoutLMv2Config object with the specified parameters.

    Args:
        vocab_size (int): The size of the vocabulary.
        hidden_size (int): The hidden size for the model.
        num_hidden_layers (int): The number of hidden layers in the model.
        num_attention_heads (int): The number of attention heads in the model.
        intermediate_size (int): The size of the intermediate layer in the model.
        hidden_act (str): The activation function for the hidden layers.
        hidden_dropout_prob (float): The dropout probability for the hidden layers.
        attention_probs_dropout_prob (float): The dropout probability for the attention probabilities.
        max_position_embeddings (int): The maximum position embeddings allowed.
        type_vocab_size (int): The size of the type vocabulary.
        initializer_range (float): The range for parameter initialization.
        layer_norm_eps (float): The epsilon value for layer normalization.
        pad_token_id (int): The token ID for padding.
        max_2d_position_embeddings (int): The maximum 2D position embeddings allowed.
        max_rel_pos (int): The maximum relative position.
        rel_pos_bins (int): The number of relative position bins.
        fast_qkv (bool): Flag to enable fast query, key, value computation.
        max_rel_2d_pos (int): The maximum relative 2D position.
        rel_2d_pos_bins (int): The number of relative 2D position bins.
        image_feature_pool_shape (list): The shape of the image feature pool.
        coordinate_size (int): The size of coordinates.
        shape_size (int): The size of shapes.
        has_relative_attention_bias (bool): Flag indicating if relative attention bias is used.
        has_spatial_attention_bias (bool): Flag indicating if spatial attention bias is used.
        has_visual_segment_embedding (bool): Flag indicating if visual segment embedding is used.
        use_visual_backbone (bool): Flag indicating if visual backbone is used.
        detectron2_config_args (dict): Additional arguments for the Detectron2 configuration.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(
        vocab_size=vocab_size,
        hidden_size=hidden_size,
        num_hidden_layers=num_hidden_layers,
        num_attention_heads=num_attention_heads,
        intermediate_size=intermediate_size,
        hidden_act=hidden_act,
        hidden_dropout_prob=hidden_dropout_prob,
        attention_probs_dropout_prob=attention_probs_dropout_prob,
        max_position_embeddings=max_position_embeddings,
        type_vocab_size=type_vocab_size,
        initializer_range=initializer_range,
        layer_norm_eps=layer_norm_eps,
        pad_token_id=pad_token_id,
        **kwargs,
    )
    self.max_2d_position_embeddings = max_2d_position_embeddings
    self.max_rel_pos = max_rel_pos
    self.rel_pos_bins = rel_pos_bins
    self.fast_qkv = fast_qkv
    self.max_rel_2d_pos = max_rel_2d_pos
    self.rel_2d_pos_bins = rel_2d_pos_bins
    self.image_feature_pool_shape = image_feature_pool_shape
    self.coordinate_size = coordinate_size
    self.shape_size = shape_size
    self.has_relative_attention_bias = has_relative_attention_bias
    self.has_spatial_attention_bias = has_spatial_attention_bias
    self.has_visual_segment_embedding = has_visual_segment_embedding
    self.use_visual_backbone = use_visual_backbone
    self.detectron2_config_args = (
        detectron2_config_args if detectron2_config_args is not None else self.get_default_detectron2_config()
    )

mindnlp.transformers.models.layoutlmv2.configuration_layoutlmv2.LayoutLMv2Config.get_default_detectron2_config() classmethod

This method returns a dictionary containing the default configuration for the Detectron2 model. The configuration includes various settings related to the model's architecture, backbone, region of interest (ROI) heads, and other parameters.

PARAMETER DESCRIPTION
cls

The class object.

TYPE: class

RETURNS DESCRIPTION
dict

A dictionary containing the default configuration for the Detectron2 model.

Source code in mindnlp/transformers/models/layoutlmv2/configuration_layoutlmv2.py
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
@classmethod
def get_default_detectron2_config(cls):
    '''
    This method returns a dictionary containing the default configuration for the Detectron2 model.
    The configuration includes various settings related to the model's architecture, backbone, region of
    interest (ROI) heads, and other parameters.

    Args:
        cls (class): The class object.

    Returns:
        dict: A dictionary containing the default configuration for the Detectron2 model.

    Raises:
        None.
    '''
    return {
        "MODEL.MASK_ON": True,
        "MODEL.PIXEL_STD": [57.375, 57.120, 58.395],
        "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
        "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
        "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
        "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
        "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
        "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
        "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
        "MODEL.POST_NMS_TOPK_TEST": 1000,
        "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
        "MODEL.ROI_HEADS.NUM_CLASSES": 5,
        "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
        "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
        "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
        "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
        "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
        "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
        "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
        "MODEL.RESNETS.DEPTH": 101,
        "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
        "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
        "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
        "MODEL.RESNETS.NUM_GROUPS": 32,
        "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
        "MODEL.RESNETS.STRIDE_IN_1X1": False,
    }

mindnlp.transformers.models.layoutlmv2.configuration_layoutlmv2.LayoutLMv2Config.get_detectron2_config()

This method generates a Detectron2 configuration for the LayoutLMv2 model.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Config class.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/configuration_layoutlmv2.py
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
def get_detectron2_config(self):
    """
    This method generates a Detectron2 configuration for the LayoutLMv2 model.

    Args:
        self: The instance of the LayoutLMv2Config class.

    Returns:
        None.

    Raises:
        None
    """
    detectron2_config = Dict(
        {
            "MODEL": {
                "MASK_ON": True,
                "PIXEL_MEAN": [103.53, 116.28, 123.675],
                "PIXEL_STD": [57.375, 57.120, 58.395],
                "BACKBONE": {"NAME": "build_resnet_fpn_backbone"},
                "FPN": {
                    "FUSE_TYPE": "sum",
                    "IN_FEATURES": ["res2", "res3", "res4", "res5"],
                    "NORM": "BN",
                    "OUT_CHANNELS": 256
                },
                "ANCHOR_GENERATOR": {"SIZES": [[32], [64], [128], [256], [512]]},
                "RPN": {
                    "IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
                    "PRE_NMS_TOPK_TRAIN": 2000,
                    "PRE_NMS_TOPK_TEST": 1000,
                    "POST_NMS_TOPK_TRAIN": 1000,
                },
                "POST_NMS_TOPK_TEST": 1000,
                "ROI_HEADS": {
                    "NAME": "StandardROIHeads",
                    "NUM_CLASSES": 5,
                    "IN_FEATURES": ["p2", "p3", "p4", "p5"],
                },
                "ROI_BOX_HEAD": {
                    "NAME": "FastRCNNConvFCHead",
                    "NUM_FC": 2,
                    "POOLER_RESOLUTION": 14,
                },
                "ROI_MASK_HEAD": {
                    "NAME": "MaskRCNNConvUpsampleHead",
                    "NUM_CONV": 4,
                    "POOLER_RESOLUTION": 7,
                },
                "RESNETS": {
                    "DEPTH": 101,
                    "SIZES": [[32], [64], [128], [256], [512]],
                    "ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
                    "FREEZE_AT": 2,
                    "NORM": "BN",
                    "NUM_GROUPS": 32,
                    "WIDTH_PER_GROUP": 8,
                    "STEM_IN_CHANNELS": 3,
                    "STEM_OUT_CHANNELS": 64,
                    "RES2_OUT_CHANNELS": 256,
                    "STRIDE_IN_1X1": False,
                    "RES5_DILATION": 1,
                    "NAME": "resnet101",
                    "PRETRAINED": True,
                    "NUM_CLASSES": 1000,
                    "OUT_FEATURES": ["res2", "res3", "res4", "res5"]
                }
            }
        }
    )
    for k, v in self.detectron2_config_args.items():
        attributes = k.split(".")
        to_set = detectron2_config
        for attribute in attributes[:-1]:
            to_set = getattr(to_set, attribute)
        setattr(to_set, attributes[-1], v)

    return detectron2_config

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2

Image processor class for LayoutLMv2.

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2.LayoutLMv2ImageProcessor

Bases: BaseImageProcessor

Constructs a LayoutLMv2 image processor.

PARAMETER DESCRIPTION
do_resize

Whether to resize the image's (height, width) dimensions to (size["height"], size["width"]). Can be overridden by do_resize in preprocess.

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

size

224, "width": 224}): Size of the image after resizing. Can be overridden bysizeinpreprocess`.

TYPE: `Dict[str, int]` *optional*, defaults to `{"height" DEFAULT: None

resample

Resampling filter to use if resizing the image. Can be overridden by the resample parameter in the preprocess method.

TYPE: `PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR` DEFAULT: BILINEAR

apply_ocr

Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes. Can be overridden by apply_ocr in preprocess.

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

ocr_lang

The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is used. Can be overridden by ocr_lang in preprocess.

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

tesseract_config

Any additional custom configuration flags that are forwarded to the config parameter when calling Tesseract. For example: '--psm 6'. Can be overridden by tesseract_config in preprocess.

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

Source code in mindnlp/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
class LayoutLMv2ImageProcessor(BaseImageProcessor):
    r"""
    Constructs a LayoutLMv2 image processor.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image's (height, width) dimensions to `(size["height"], size["width"])`. Can be
            overridden by `do_resize` in `preprocess`.
        size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
            Size of the image after resizing. Can be overridden by `size` in `preprocess`.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
            `preprocess` method.
        apply_ocr (`bool`, *optional*, defaults to `True`):
            Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes. Can be overridden by
            `apply_ocr` in `preprocess`.
        ocr_lang (`str`, *optional*):
            The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
            used. Can be overridden by `ocr_lang` in `preprocess`.
        tesseract_config (`str`, *optional*, defaults to `""`):
            Any additional custom configuration flags that are forwarded to the `config` parameter when calling
            Tesseract. For example: '--psm 6'. Can be overridden by `tesseract_config` in `preprocess`.
    """
    model_input_names = ["pixel_values"]

    def __init__(
            self,
            do_resize: bool = True,
            size: Dict[str, int] = None,
            resample: PILImageResampling = PILImageResampling.BILINEAR,
            apply_ocr: bool = True,
            ocr_lang: Optional[str] = None,
            tesseract_config: Optional[str] = "",
            **kwargs,
    ) -> None:
        """
        Initializes a LayoutLMv2ImageProcessor object.

        Args:
            self: The LayoutLMv2ImageProcessor instance.
            do_resize (bool): Indicates whether to perform image resizing. Defaults to True.
            size (Dict[str, int]): A dictionary specifying the height and width for resizing the image.
                Defaults to {'height': 224, 'width': 224}.
            resample (PILImageResampling): The resampling filter to use when resizing the image.
                Defaults to PILImageResampling.BILINEAR.
            apply_ocr (bool): Indicates whether optical character recognition (OCR) should be applied. Defaults to True.
            ocr_lang (Optional[str]): The language for OCR. If None, the default language is used. Defaults to None.
            tesseract_config (Optional[str]): Configuration options for the Tesseract OCR engine.
                Defaults to an empty string.
            **kwargs: Additional keyword arguments.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(**kwargs)
        size = size if size is not None else {"height": 224, "width": 224}
        size = get_size_dict(size)

        self.do_resize = do_resize
        self.size = size
        self.resample = resample
        self.apply_ocr = apply_ocr
        self.ocr_lang = ocr_lang
        self.tesseract_config = tesseract_config
        self._valid_processor_keys = [
            "images",
            "do_resize",
            "size",
            "resample",
            "apply_ocr",
            "ocr_lang",
            "tesseract_config",
            "return_tensors",
            "data_format",
            "input_data_format",
        ]

    # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize
    def resize(
            self,
            image: np.ndarray,
            size: Dict[str, int],
            resample: PILImageResampling = PILImageResampling.BILINEAR,
            data_format: Optional[Union[str, ChannelDimension]] = None,
            input_data_format: Optional[Union[str, ChannelDimension]] = None,
            **kwargs,
    ) -> np.ndarray:
        """
        Resize an image to `(size["height"], size["width"])`.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
                `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
            data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the output image. If unset, the channel dimension format of the input
                image is used. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.

        Returns:
            `np.ndarray`: The resized image.
        """
        size = get_size_dict(size)
        if "height" not in size or "width" not in size:
            raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
        output_size = (size["height"], size["width"])
        return resize(
            image,
            size=output_size,
            resample=resample,
            data_format=data_format,
            input_data_format=input_data_format,
            **kwargs,
        )

    def preprocess(
            self,
            images: ImageInput,
            do_resize: bool = None,
            size: Dict[str, int] = None,
            resample: PILImageResampling = None,
            apply_ocr: bool = None,
            ocr_lang: Optional[str] = None,
            tesseract_config: Optional[str] = None,
            return_tensors: Optional[Union[str, TensorType]] = None,
            data_format: ChannelDimension = ChannelDimension.FIRST,
            input_data_format: Optional[Union[str, ChannelDimension]] = None,
            **kwargs,
    ) -> PIL.Image.Image:
        """
        Preprocess an image or batch of images.

        Args:
            images (`ImageInput`):
                Image to preprocess.
            do_resize (`bool`, *optional*, defaults to `self.do_resize`):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to `self.size`):
                Desired size of the output image after resizing.
            resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
                Resampling filter to use if resizing the image. This can be one of the enum `PIL.Image` resampling
                filter. Only has an effect if `do_resize` is set to `True`.
            apply_ocr (`bool`, *optional*, defaults to `self.apply_ocr`):
                Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes.
            ocr_lang (`str`, *optional*, defaults to `self.ocr_lang`):
                The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
                used.
            tesseract_config (`str`, *optional*, defaults to `self.tesseract_config`):
                Any additional custom configuration flags that are forwarded to the `config` parameter when calling
                Tesseract.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:

                - Unset: Return a list of `np.ndarray`.
                - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output image. Can be one of:

                - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
        """
        do_resize = do_resize if do_resize is not None else self.do_resize
        size = size if size is not None else self.size
        size = get_size_dict(size)
        resample = resample if resample is not None else self.resample
        apply_ocr = apply_ocr if apply_ocr is not None else self.apply_ocr
        ocr_lang = ocr_lang if ocr_lang is not None else self.ocr_lang
        tesseract_config = tesseract_config if tesseract_config is not None else self.tesseract_config

        images = make_list_of_images(images)

        validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)

        if not valid_images(images):
            raise ValueError(
                "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                "torch.Tensor, tf.Tensor or jax.ndarray."
            )
        validate_preprocess_arguments(
            do_resize=do_resize,
            size=size,
            resample=resample,
        )

        # All transformations expect numpy arrays.
        images = [to_numpy_array(image) for image in images]

        if input_data_format is None:
            # We assume that all images have the same channel dimension format.
            input_data_format = infer_channel_dimension_format(images[0])

        if apply_ocr:
            requires_backends(self, "pytesseract")
            words_batch = []
            boxes_batch = []
            for image in images:
                words, boxes = apply_tesseract(image, ocr_lang, tesseract_config, input_data_format=input_data_format)
                words_batch.append(words)
                boxes_batch.append(boxes)

        if do_resize:
            images = [
                self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
                for image in images
            ]

        # flip color channels from RGB to BGR (as Detectron2 requires this)
        images = [flip_channel_order(image, input_data_format=input_data_format) for image in images]
        images = [
            to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
        ]

        data = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)

        if apply_ocr:
            data["words"] = words_batch
            data["boxes"] = boxes_batch
        return data

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2.LayoutLMv2ImageProcessor.__init__(do_resize=True, size=None, resample=PILImageResampling.BILINEAR, apply_ocr=True, ocr_lang=None, tesseract_config='', **kwargs)

Initializes a LayoutLMv2ImageProcessor object.

PARAMETER DESCRIPTION
self

The LayoutLMv2ImageProcessor instance.

do_resize

Indicates whether to perform image resizing. Defaults to True.

TYPE: bool DEFAULT: True

size

A dictionary specifying the height and width for resizing the image. Defaults to {'height': 224, 'width': 224}.

TYPE: Dict[str, int] DEFAULT: None

resample

The resampling filter to use when resizing the image. Defaults to PILImageResampling.BILINEAR.

TYPE: PILImageResampling DEFAULT: BILINEAR

apply_ocr

Indicates whether optical character recognition (OCR) should be applied. Defaults to True.

TYPE: bool DEFAULT: True

ocr_lang

The language for OCR. If None, the default language is used. Defaults to None.

TYPE: Optional[str] DEFAULT: None

tesseract_config

Configuration options for the Tesseract OCR engine. Defaults to an empty string.

TYPE: Optional[str] DEFAULT: ''

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION
None

None.

Source code in mindnlp/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def __init__(
        self,
        do_resize: bool = True,
        size: Dict[str, int] = None,
        resample: PILImageResampling = PILImageResampling.BILINEAR,
        apply_ocr: bool = True,
        ocr_lang: Optional[str] = None,
        tesseract_config: Optional[str] = "",
        **kwargs,
) -> None:
    """
    Initializes a LayoutLMv2ImageProcessor object.

    Args:
        self: The LayoutLMv2ImageProcessor instance.
        do_resize (bool): Indicates whether to perform image resizing. Defaults to True.
        size (Dict[str, int]): A dictionary specifying the height and width for resizing the image.
            Defaults to {'height': 224, 'width': 224}.
        resample (PILImageResampling): The resampling filter to use when resizing the image.
            Defaults to PILImageResampling.BILINEAR.
        apply_ocr (bool): Indicates whether optical character recognition (OCR) should be applied. Defaults to True.
        ocr_lang (Optional[str]): The language for OCR. If None, the default language is used. Defaults to None.
        tesseract_config (Optional[str]): Configuration options for the Tesseract OCR engine.
            Defaults to an empty string.
        **kwargs: Additional keyword arguments.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(**kwargs)
    size = size if size is not None else {"height": 224, "width": 224}
    size = get_size_dict(size)

    self.do_resize = do_resize
    self.size = size
    self.resample = resample
    self.apply_ocr = apply_ocr
    self.ocr_lang = ocr_lang
    self.tesseract_config = tesseract_config
    self._valid_processor_keys = [
        "images",
        "do_resize",
        "size",
        "resample",
        "apply_ocr",
        "ocr_lang",
        "tesseract_config",
        "return_tensors",
        "data_format",
        "input_data_format",
    ]

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2.LayoutLMv2ImageProcessor.preprocess(images, do_resize=None, size=None, resample=None, apply_ocr=None, ocr_lang=None, tesseract_config=None, return_tensors=None, data_format=ChannelDimension.FIRST, input_data_format=None, **kwargs)

Preprocess an image or batch of images.

PARAMETER DESCRIPTION
images

Image to preprocess.

TYPE: `ImageInput`

do_resize

Whether to resize the image.

TYPE: `bool`, *optional*, defaults to `self.do_resize` DEFAULT: None

size

Desired size of the output image after resizing.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.size` DEFAULT: None

resample

Resampling filter to use if resizing the image. This can be one of the enum PIL.Image resampling filter. Only has an effect if do_resize is set to True.

TYPE: `PILImageResampling`, *optional*, defaults to `self.resample` DEFAULT: None

apply_ocr

Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes.

TYPE: `bool`, *optional*, defaults to `self.apply_ocr` DEFAULT: None

ocr_lang

The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is used.

TYPE: `str`, *optional*, defaults to `self.ocr_lang` DEFAULT: None

tesseract_config

Any additional custom configuration flags that are forwarded to the config parameter when calling Tesseract.

TYPE: `str`, *optional*, defaults to `self.tesseract_config` DEFAULT: None

return_tensors

The type of tensors to return. Can be one of:

  • Unset: Return a list of np.ndarray.
  • TensorType.TENSORFLOW or 'tf': Return a batch of type tf.Tensor.
  • TensorType.PYTORCH or 'pt': Return a batch of type torch.Tensor.
  • TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
  • TensorType.JAX or 'jax': Return a batch of type jax.numpy.ndarray.

TYPE: `str` or `TensorType`, *optional* DEFAULT: None

data_format

The channel dimension format for the output image. Can be one of:

  • ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • ChannelDimension.LAST: image in (height, width, num_channels) format.

TYPE: `ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST` DEFAULT: FIRST

Source code in mindnlp/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
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
def preprocess(
        self,
        images: ImageInput,
        do_resize: bool = None,
        size: Dict[str, int] = None,
        resample: PILImageResampling = None,
        apply_ocr: bool = None,
        ocr_lang: Optional[str] = None,
        tesseract_config: Optional[str] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        data_format: ChannelDimension = ChannelDimension.FIRST,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
) -> PIL.Image.Image:
    """
    Preprocess an image or batch of images.

    Args:
        images (`ImageInput`):
            Image to preprocess.
        do_resize (`bool`, *optional*, defaults to `self.do_resize`):
            Whether to resize the image.
        size (`Dict[str, int]`, *optional*, defaults to `self.size`):
            Desired size of the output image after resizing.
        resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
            Resampling filter to use if resizing the image. This can be one of the enum `PIL.Image` resampling
            filter. Only has an effect if `do_resize` is set to `True`.
        apply_ocr (`bool`, *optional*, defaults to `self.apply_ocr`):
            Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes.
        ocr_lang (`str`, *optional*, defaults to `self.ocr_lang`):
            The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
            used.
        tesseract_config (`str`, *optional*, defaults to `self.tesseract_config`):
            Any additional custom configuration flags that are forwarded to the `config` parameter when calling
            Tesseract.
        return_tensors (`str` or `TensorType`, *optional*):
            The type of tensors to return. Can be one of:

            - Unset: Return a list of `np.ndarray`.
            - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
            - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
            - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
            - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
        data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
            The channel dimension format for the output image. Can be one of:

            - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
    """
    do_resize = do_resize if do_resize is not None else self.do_resize
    size = size if size is not None else self.size
    size = get_size_dict(size)
    resample = resample if resample is not None else self.resample
    apply_ocr = apply_ocr if apply_ocr is not None else self.apply_ocr
    ocr_lang = ocr_lang if ocr_lang is not None else self.ocr_lang
    tesseract_config = tesseract_config if tesseract_config is not None else self.tesseract_config

    images = make_list_of_images(images)

    validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)

    if not valid_images(images):
        raise ValueError(
            "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
            "torch.Tensor, tf.Tensor or jax.ndarray."
        )
    validate_preprocess_arguments(
        do_resize=do_resize,
        size=size,
        resample=resample,
    )

    # All transformations expect numpy arrays.
    images = [to_numpy_array(image) for image in images]

    if input_data_format is None:
        # We assume that all images have the same channel dimension format.
        input_data_format = infer_channel_dimension_format(images[0])

    if apply_ocr:
        requires_backends(self, "pytesseract")
        words_batch = []
        boxes_batch = []
        for image in images:
            words, boxes = apply_tesseract(image, ocr_lang, tesseract_config, input_data_format=input_data_format)
            words_batch.append(words)
            boxes_batch.append(boxes)

    if do_resize:
        images = [
            self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
            for image in images
        ]

    # flip color channels from RGB to BGR (as Detectron2 requires this)
    images = [flip_channel_order(image, input_data_format=input_data_format) for image in images]
    images = [
        to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
    ]

    data = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)

    if apply_ocr:
        data["words"] = words_batch
        data["boxes"] = boxes_batch
    return data

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2.LayoutLMv2ImageProcessor.resize(image, size, resample=PILImageResampling.BILINEAR, data_format=None, input_data_format=None, **kwargs)

Resize an image to (size["height"], size["width"]).

PARAMETER DESCRIPTION
image

Image to resize.

TYPE: `np.ndarray`

size

Dictionary in the format {"height": int, "width": int} specifying the size of the output image.

TYPE: `Dict[str, int]`

resample

PILImageResampling filter to use when resizing the image e.g. PILImageResampling.BILINEAR.

TYPE: `PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR` DEFAULT: BILINEAR

data_format

The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
  • "none" or ChannelDimension.NONE: image in (height, width) format.

TYPE: `ChannelDimension` or `str`, *optional* DEFAULT: None

input_data_format

The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
  • "none" or ChannelDimension.NONE: image in (height, width) format.

TYPE: `ChannelDimension` or `str`, *optional* DEFAULT: None

RETURNS DESCRIPTION
ndarray

np.ndarray: The resized image.

Source code in mindnlp/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def resize(
        self,
        image: np.ndarray,
        size: Dict[str, int],
        resample: PILImageResampling = PILImageResampling.BILINEAR,
        data_format: Optional[Union[str, ChannelDimension]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
) -> np.ndarray:
    """
    Resize an image to `(size["height"], size["width"])`.

    Args:
        image (`np.ndarray`):
            Image to resize.
        size (`Dict[str, int]`):
            Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
        resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
            `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
        data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the output image. If unset, the channel dimension format of the input
            image is used. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image. If unset, the channel dimension format is inferred
            from the input image. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.

    Returns:
        `np.ndarray`: The resized image.
    """
    size = get_size_dict(size)
    if "height" not in size or "width" not in size:
        raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
    output_size = (size["height"], size["width"])
    return resize(
        image,
        size=output_size,
        resample=resample,
        data_format=data_format,
        input_data_format=input_data_format,
        **kwargs,
    )

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2.apply_tesseract(image, lang, tesseract_config=None, input_data_format=None)

Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes.

Source code in mindnlp/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
 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
def apply_tesseract(
        image: np.ndarray,
        lang: Optional[str],
        tesseract_config: Optional[str] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
):
    """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes."""
    tesseract_config = tesseract_config if tesseract_config is not None else ""

    # apply OCR
    pil_image = to_pil_image(image, input_data_format=input_data_format)
    image_width, image_height = pil_image.size
    data = pytesseract.image_to_data(pil_image, lang=lang, output_type="dict", config=tesseract_config)
    words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]

    # filter empty words and corresponding coordinates
    irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
    words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
    left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
    top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
    width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
    height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]

    # turn coordinates into (left, top, left+width, top+height) format
    actual_boxes = []
    for x, y, w, h in zip(left, top, width, height):
        actual_box = [x, y, x + w, y + h]
        actual_boxes.append(actual_box)

    # finally, normalize the bounding boxes
    normalized_boxes = []
    for box in actual_boxes:
        normalized_boxes.append(normalize_box(box, image_width, image_height))

    assert len(words) == len(normalized_boxes), "Not as many words as there are bounding boxes"

    return words, normalized_boxes

mindnlp.transformers.models.layoutlmv2.image_processing_layoutlmv2.normalize_box(box, width, height)

PARAMETER DESCRIPTION
box

width

height

Source code in mindnlp/transformers/models/layoutlmv2/image_processing_layoutlmv2.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def normalize_box(box, width, height):
    """
    Args:
        box:
        width:
        height:

    Returns: list
    """
    return [
        int(1000 * (box[0] / width)),
        int(1000 * (box[1] / height)),
        int(1000 * (box[2] / width)),
        int(1000 * (box[3] / height)),
    ]

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2

Mindnlp LayoutLMv2 model.

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Attention

Bases: Module

LayoutLMv2Attention is the attention layer for LayoutLMv2. It is based on the implementation of

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2Attention(nn.Module):
    """
    LayoutLMv2Attention is the attention layer for LayoutLMv2. It is based on the implementation of
    """
    def __init__(self, config):
        """
        Initialize the LayoutLMv2Attention class.

        Args:
            self (LayoutLMv2Attention): The instance of the LayoutLMv2Attention class.
            config: Represents the configuration settings for the LayoutLMv2Attention instance.

        Returns:
            None.

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

    def forward(
            self,
            hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
            rel_pos=None,
            rel_2d_pos=None,
    ):
        """
        This method 'forward' is defined in the class 'LayoutLMv2Attention' and is responsible for
        forwarding the attention mechanism in the LayoutLMv2 model.

        Args:
            self (LayoutLMv2Attention): The instance of the LayoutLMv2Attention class.
            hidden_states (torch.Tensor): The input hidden states to the attention mechanism.
            attention_mask (torch.Tensor, optional): Mask to prevent attention to certain positions. Default is None.
            head_mask (torch.Tensor, optional): Mask to hide certain heads of the attention mechanism. Default is None.
            output_attentions (bool): Whether to output attentions weights. Default is False.
            rel_pos (torch.Tensor, optional): Relative position encoding. Default is None.
            rel_2d_pos (torch.Tensor, optional): 2D relative position encoding. Default is None.

        Returns:
            tuple: A tuple containing the attention output and additional outputs from the attention mechanism.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Attention.__init__(config)

Initialize the LayoutLMv2Attention class.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Attention class.

TYPE: LayoutLMv2Attention

config

Represents the configuration settings for the LayoutLMv2Attention instance.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def __init__(self, config):
    """
    Initialize the LayoutLMv2Attention class.

    Args:
        self (LayoutLMv2Attention): The instance of the LayoutLMv2Attention class.
        config: Represents the configuration settings for the LayoutLMv2Attention instance.

    Returns:
        None.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Attention.forward(hidden_states, attention_mask=None, head_mask=None, output_attentions=False, rel_pos=None, rel_2d_pos=None)

This method 'forward' is defined in the class 'LayoutLMv2Attention' and is responsible for forwarding the attention mechanism in the LayoutLMv2 model.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Attention class.

TYPE: LayoutLMv2Attention

hidden_states

The input hidden states to the attention mechanism.

TYPE: Tensor

attention_mask

Mask to prevent attention to certain positions. Default is None.

TYPE: Tensor DEFAULT: None

head_mask

Mask to hide certain heads of the attention mechanism. Default is None.

TYPE: Tensor DEFAULT: None

output_attentions

Whether to output attentions weights. Default is False.

TYPE: bool DEFAULT: False

rel_pos

Relative position encoding. Default is None.

TYPE: Tensor DEFAULT: None

rel_2d_pos

2D relative position encoding. Default is None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
tuple

A tuple containing the attention output and additional outputs from the attention mechanism.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(
        self,
        hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
        rel_pos=None,
        rel_2d_pos=None,
):
    """
    This method 'forward' is defined in the class 'LayoutLMv2Attention' and is responsible for
    forwarding the attention mechanism in the LayoutLMv2 model.

    Args:
        self (LayoutLMv2Attention): The instance of the LayoutLMv2Attention class.
        hidden_states (torch.Tensor): The input hidden states to the attention mechanism.
        attention_mask (torch.Tensor, optional): Mask to prevent attention to certain positions. Default is None.
        head_mask (torch.Tensor, optional): Mask to hide certain heads of the attention mechanism. Default is None.
        output_attentions (bool): Whether to output attentions weights. Default is False.
        rel_pos (torch.Tensor, optional): Relative position encoding. Default is None.
        rel_2d_pos (torch.Tensor, optional): 2D relative position encoding. Default is None.

    Returns:
        tuple: A tuple containing the attention output and additional outputs from the attention mechanism.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Embeddings

Bases: Module

Construct the embeddings from word, position and token_type embeddings.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class LayoutLMv2Embeddings(nn.Module):
    """Construct the embeddings from word, position and token_type embeddings."""
    def __init__(self, config):
        """
        Initializes the LayoutLMv2Embeddings class with the provided configuration.

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

                - vocab_size (int): The size of the vocabulary.
                - hidden_size (int): The size of the hidden layers.
                - pad_token_id (int): The padding token ID.
                - max_position_embeddings (int): The maximum position embeddings.
                - max_2d_position_embeddings (int): The maximum 2D position embeddings.
                - coordinate_size (int): The size of coordinate embeddings.
                - shape_size (int): The size of shape embeddings.
                - type_vocab_size (int): The size of the token type vocabulary.
                - layer_norm_eps (float): The epsilon value for LayerNorm.
                - hidden_dropout_prob (float): The dropout probability.

        Returns:
            None.

        Raises:
            None.
        """
        super(LayoutLMv2Embeddings, self).__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.x_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.coordinate_size)
        self.y_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.coordinate_size)
        self.h_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.shape_size)
        self.w_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.shape_size)
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)

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

        self.position_ids = mindspore.Tensor(np.arange(0, config.max_position_embeddings)).broadcast_to(
                (1, -1))

    def _calc_spatial_position_embeddings(self, bbox):
        """
        This method calculates spatial position embeddings based on the provided bounding box coordinates.

        Args:
            self: An instance of the LayoutLMv2Embeddings class.
            bbox: A tensor containing bounding box coordinates in the shape (batch_size, num_boxes, 4).
                The four coordinates represent the left, upper, right, and lower positions of each bounding box.
                The values should be within the range of 0 to 1000.

        Returns:
            spatial_position_embeddings: A tensor containing the calculated spatial position embeddings.
                The embeddings include left, upper, right, and lower position embeddings,
                as well as height and width position embeddings concatenated along the last dimension.

        Raises:
            IndexError: Raised if the coordinate values in bbox are outside the valid range of 0 to 1000.
        """
        try:
            left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0])
            upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1])
            right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2])
            lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3])
        except IndexError as e:
            raise IndexError("The `bbox` coordinate values should be within 0-1000 range.") from e

        h_position_embeddings = self.h_position_embeddings(bbox[:, :, 3] - bbox[:, :, 1])
        w_position_embeddings = self.w_position_embeddings(bbox[:, :, 2] - bbox[:, :, 0])

        spatial_position_embeddings = ops.cat(
            [
                left_position_embeddings,
                upper_position_embeddings,
                right_position_embeddings,
                lower_position_embeddings,
                h_position_embeddings,
                w_position_embeddings,
            ],
            axis=-1,
        )
        return spatial_position_embeddings

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Embeddings.__init__(config)

Initializes the LayoutLMv2Embeddings class with the provided configuration.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Embeddings class.

config

An object containing configuration parameters for the embeddings.

  • vocab_size (int): The size of the vocabulary.
  • hidden_size (int): The size of the hidden layers.
  • pad_token_id (int): The padding token ID.
  • max_position_embeddings (int): The maximum position embeddings.
  • max_2d_position_embeddings (int): The maximum 2D position embeddings.
  • coordinate_size (int): The size of coordinate embeddings.
  • shape_size (int): The size of shape embeddings.
  • type_vocab_size (int): The size of the token type vocabulary.
  • layer_norm_eps (float): The epsilon value for LayerNorm.
  • hidden_dropout_prob (float): The dropout probability.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(self, config):
    """
    Initializes the LayoutLMv2Embeddings class with the provided configuration.

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

            - vocab_size (int): The size of the vocabulary.
            - hidden_size (int): The size of the hidden layers.
            - pad_token_id (int): The padding token ID.
            - max_position_embeddings (int): The maximum position embeddings.
            - max_2d_position_embeddings (int): The maximum 2D position embeddings.
            - coordinate_size (int): The size of coordinate embeddings.
            - shape_size (int): The size of shape embeddings.
            - type_vocab_size (int): The size of the token type vocabulary.
            - layer_norm_eps (float): The epsilon value for LayerNorm.
            - hidden_dropout_prob (float): The dropout probability.

    Returns:
        None.

    Raises:
        None.
    """
    super(LayoutLMv2Embeddings, self).__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.x_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.coordinate_size)
    self.y_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.coordinate_size)
    self.h_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.shape_size)
    self.w_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.shape_size)
    self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)

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

    self.position_ids = mindspore.Tensor(np.arange(0, config.max_position_embeddings)).broadcast_to(
            (1, -1))

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Encoder

Bases: Module

LayoutLMv2Encoder is a stack of LayoutLMv2Layer. It is based on the implementation of BertEncoder.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2Encoder(nn.Module):
    """
    LayoutLMv2Encoder is a stack of LayoutLMv2Layer. It is based on the implementation of BertEncoder.
    """
    def __init__(self, config):
        '''
        Initializes a LayoutLMv2Encoder object.

        Args:
            config (object): The configuration object containing the parameters for the LayoutLMv2Encoder.
                It is used to initialize various attributes of the LayoutLMv2Encoder.

        Returns:
            None.

        Raises:
            None.
        '''
        super().__init__()
        self.config = config
        self.layer = nn.ModuleList([LayoutLMv2Layer(config) for _ in range(config.num_hidden_layers)])

        self.has_relative_attention_bias = config.has_relative_attention_bias
        self.has_spatial_attention_bias = config.has_spatial_attention_bias

        if self.has_relative_attention_bias:
            self.rel_pos_bins = config.rel_pos_bins
            self.max_rel_pos = config.max_rel_pos
            self.rel_pos_bias = nn.Linear(self.rel_pos_bins, config.num_attention_heads, bias=False)

        if self.has_spatial_attention_bias:
            self.max_rel_2d_pos = config.max_rel_2d_pos
            self.rel_2d_pos_bins = config.rel_2d_pos_bins
            self.rel_pos_x_bias = nn.Linear(self.rel_2d_pos_bins, config.num_attention_heads, bias=False)
            self.rel_pos_y_bias = nn.Linear(self.rel_2d_pos_bins, config.num_attention_heads, bias=False)

        self.gradient_checkpointing = False

    def _calculate_1d_position_embeddings(self, position_ids):
        """
        This method calculates 1D position embeddings for the LayoutLMv2Encoder.

        Args:
            self (LayoutLMv2Encoder): The instance of the LayoutLMv2Encoder class.
            position_ids (torch.Tensor): A 1D tensor representing the position IDs of tokens.
                It is used to calculate the relative position embeddings.
                Expected to be a tensor of shape (batch_size,) with integer values representing the position IDs.

        Returns:
            None: This method does not return a value. It updates the internal state of the LayoutLMv2Encoder instance
                to store the calculated relative position embeddings.

        Raises:
            RuntimeError: If the input position_ids tensor is not a torch.Tensor or has an incorrect shape.
            ValueError: If the number of buckets specified for relative position bucketing (rel_pos_bins) is less than 1.
            ValueError: If the max_distance for relative position bucketing (max_rel_pos) is less than 1.
        """
        rel_pos_mat = position_ids.unsqueeze(-2) - position_ids.unsqueeze(-1)
        rel_pos = relative_position_bucket(
            rel_pos_mat,
            num_buckets=self.rel_pos_bins,
            max_distance=self.max_rel_pos,
        )
        rel_pos = self.rel_pos_bias.weight.t()[rel_pos].permute(0, 3, 1, 2)
        return rel_pos

    def _calculate_2d_position_embeddings(self, bbox):
        """
        Method to calculate 2D position embeddings based on the given bounding box.

        Args:
            self (LayoutLMv2Encoder): The instance of the LayoutLMv2Encoder class.
            bbox (torch.Tensor): A 3D tensor representing the bounding box coordinates with shape
                (batch_size, num_boxes, 4). The bounding box tensor contains the x and y coordinates of the top-left
                and bottom-right corners of each box.

        Returns:
            None: This method does not return any value directly.
                It calculates and updates the relative 2D position embeddings.

        Raises:
            None.
        """
        position_coord_x = bbox[:, :, 0]
        position_coord_y = bbox[:, :, 3]
        rel_pos_x_2d_mat = position_coord_x.unsqueeze(-2) - position_coord_x.unsqueeze(-1)
        rel_pos_y_2d_mat = position_coord_y.unsqueeze(-2) - position_coord_y.unsqueeze(-1)
        rel_pos_x = relative_position_bucket(
            rel_pos_x_2d_mat,
            num_buckets=self.rel_2d_pos_bins,
            max_distance=self.max_rel_2d_pos,
        )
        rel_pos_y = relative_position_bucket(
            rel_pos_y_2d_mat,
            num_buckets=self.rel_2d_pos_bins,
            max_distance=self.max_rel_2d_pos,
        )
        rel_pos_x = self.rel_pos_x_bias.weight.t()[rel_pos_x].permute(0, 3, 1, 2)
        rel_pos_y = self.rel_pos_y_bias.weight.t()[rel_pos_y].permute(0, 3, 1, 2)
        rel_2d_pos = rel_pos_x + rel_pos_y
        return rel_2d_pos

    def forward(
            self,
            hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
            output_hidden_states=False,
            return_dict=True,
            bbox=None,
            position_ids=None,
    ):
        """
        This method forwards the LayoutLMv2Encoder.

        Args:
            self: The instance of the class LayoutLMv2Encoder.
            hidden_states (Tensor): The input hidden states to the encoder.
            attention_mask (Tensor, optional): Mask to avoid performing attention on padding token indices.
            head_mask (List, optional): Mask for attention heads. Defaults to None.
            output_attentions (bool, optional): Whether to output attentions. Defaults to False.
            output_hidden_states (bool, optional): Whether to output hidden states. Defaults to False.
            return_dict (bool, optional): Whether to return the output as a dictionary. Defaults to True.
            bbox (Tensor, optional): Bounding box coordinates for spatial attention bias. Defaults to None.
            position_ids (Tensor, optional): Position IDs for relative positional embeddings. Defaults to None.

        Returns:
            None.

        Raises:
            ValueError: If the input parameters are not in the expected format.
            RuntimeError: If an error occurs during the execution of the method.
            IndexError: If there is an issue with accessing elements in the head_mask list.
        """
        all_hidden_states = () if output_hidden_states else None
        all_self_attentions = () if output_attentions else None

        rel_pos = self._calculate_1d_position_embeddings(position_ids) if self.has_relative_attention_bias else None
        rel_2d_pos = self._calculate_2d_position_embeddings(bbox) if self.has_spatial_attention_bias else None

        for i, layer_module in enumerate(self.layer):
            if output_hidden_states:
                all_hidden_states = all_hidden_states + (hidden_states,)

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

            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(
                    layer_module.__call__,
                    hidden_states,
                    attention_mask,
                    layer_head_mask,
                    output_attentions,
                    rel_pos=rel_pos,
                    rel_2d_pos=rel_2d_pos,
                )
            else:
                layer_outputs = layer_module(
                    hidden_states,
                    attention_mask,
                    layer_head_mask,
                    output_attentions,
                    rel_pos=rel_pos,
                    rel_2d_pos=rel_2d_pos,
                )

            hidden_states = layer_outputs[0]
            if output_attentions:
                all_self_attentions = all_self_attentions + (layer_outputs[1],)

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Encoder.__init__(config)

Initializes a LayoutLMv2Encoder object.

PARAMETER DESCRIPTION
config

The configuration object containing the parameters for the LayoutLMv2Encoder. It is used to initialize various attributes of the LayoutLMv2Encoder.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.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
def __init__(self, config):
    '''
    Initializes a LayoutLMv2Encoder object.

    Args:
        config (object): The configuration object containing the parameters for the LayoutLMv2Encoder.
            It is used to initialize various attributes of the LayoutLMv2Encoder.

    Returns:
        None.

    Raises:
        None.
    '''
    super().__init__()
    self.config = config
    self.layer = nn.ModuleList([LayoutLMv2Layer(config) for _ in range(config.num_hidden_layers)])

    self.has_relative_attention_bias = config.has_relative_attention_bias
    self.has_spatial_attention_bias = config.has_spatial_attention_bias

    if self.has_relative_attention_bias:
        self.rel_pos_bins = config.rel_pos_bins
        self.max_rel_pos = config.max_rel_pos
        self.rel_pos_bias = nn.Linear(self.rel_pos_bins, config.num_attention_heads, bias=False)

    if self.has_spatial_attention_bias:
        self.max_rel_2d_pos = config.max_rel_2d_pos
        self.rel_2d_pos_bins = config.rel_2d_pos_bins
        self.rel_pos_x_bias = nn.Linear(self.rel_2d_pos_bins, config.num_attention_heads, bias=False)
        self.rel_pos_y_bias = nn.Linear(self.rel_2d_pos_bins, config.num_attention_heads, bias=False)

    self.gradient_checkpointing = False

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Encoder.forward(hidden_states, attention_mask=None, head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True, bbox=None, position_ids=None)

This method forwards the LayoutLMv2Encoder.

PARAMETER DESCRIPTION
self

The instance of the class LayoutLMv2Encoder.

hidden_states

The input hidden states to the encoder.

TYPE: Tensor

attention_mask

Mask to avoid performing attention on padding token indices.

TYPE: Tensor DEFAULT: None

head_mask

Mask for attention heads. Defaults to None.

TYPE: List DEFAULT: None

output_attentions

Whether to output attentions. Defaults to False.

TYPE: bool DEFAULT: False

output_hidden_states

Whether to output hidden states. Defaults to False.

TYPE: bool DEFAULT: False

return_dict

Whether to return the output as a dictionary. Defaults to True.

TYPE: bool DEFAULT: True

bbox

Bounding box coordinates for spatial attention bias. Defaults to None.

TYPE: Tensor DEFAULT: None

position_ids

Position IDs for relative positional embeddings. Defaults to None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the input parameters are not in the expected format.

RuntimeError

If an error occurs during the execution of the method.

IndexError

If there is an issue with accessing elements in the head_mask list.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(
        self,
        hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
        output_hidden_states=False,
        return_dict=True,
        bbox=None,
        position_ids=None,
):
    """
    This method forwards the LayoutLMv2Encoder.

    Args:
        self: The instance of the class LayoutLMv2Encoder.
        hidden_states (Tensor): The input hidden states to the encoder.
        attention_mask (Tensor, optional): Mask to avoid performing attention on padding token indices.
        head_mask (List, optional): Mask for attention heads. Defaults to None.
        output_attentions (bool, optional): Whether to output attentions. Defaults to False.
        output_hidden_states (bool, optional): Whether to output hidden states. Defaults to False.
        return_dict (bool, optional): Whether to return the output as a dictionary. Defaults to True.
        bbox (Tensor, optional): Bounding box coordinates for spatial attention bias. Defaults to None.
        position_ids (Tensor, optional): Position IDs for relative positional embeddings. Defaults to None.

    Returns:
        None.

    Raises:
        ValueError: If the input parameters are not in the expected format.
        RuntimeError: If an error occurs during the execution of the method.
        IndexError: If there is an issue with accessing elements in the head_mask list.
    """
    all_hidden_states = () if output_hidden_states else None
    all_self_attentions = () if output_attentions else None

    rel_pos = self._calculate_1d_position_embeddings(position_ids) if self.has_relative_attention_bias else None
    rel_2d_pos = self._calculate_2d_position_embeddings(bbox) if self.has_spatial_attention_bias else None

    for i, layer_module in enumerate(self.layer):
        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states,)

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

        if self.gradient_checkpointing and self.training:
            layer_outputs = self._gradient_checkpointing_func(
                layer_module.__call__,
                hidden_states,
                attention_mask,
                layer_head_mask,
                output_attentions,
                rel_pos=rel_pos,
                rel_2d_pos=rel_2d_pos,
            )
        else:
            layer_outputs = layer_module(
                hidden_states,
                attention_mask,
                layer_head_mask,
                output_attentions,
                rel_pos=rel_pos,
                rel_2d_pos=rel_2d_pos,
            )

        hidden_states = layer_outputs[0]
        if output_attentions:
            all_self_attentions = all_self_attentions + (layer_outputs[1],)

    if output_hidden_states:
        all_hidden_states = all_hidden_states + (hidden_states,)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForQuestionAnswering

Bases: LayoutLMv2PreTrainedModel

LayoutLMv2ForQuestionAnswering is a LayoutLMv2 model with a question answering head. It is based on the implementation of LayoutLMv2ForQuestionAnswering.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
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
class LayoutLMv2ForQuestionAnswering(LayoutLMv2PreTrainedModel):
    """

    LayoutLMv2ForQuestionAnswering is a LayoutLMv2 model with a question answering head.
    It is based on the implementation of LayoutLMv2ForQuestionAnswering.
    """
    def __init__(self, config, has_visual_segment_embedding=True):
        """
        Initialize the LayoutLMv2ForQuestionAnswering class.

        Args:
            self (LayoutLMv2ForQuestionAnswering): The object instance of the LayoutLMv2ForQuestionAnswering class.
            config (LayoutLMv2Config): The configuration object for the LayoutLMv2 model.
            has_visual_segment_embedding (bool, optional): A boolean flag indicating whether visual segment embedding
                is enabled. Defaults to True.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        config.has_visual_segment_embedding = has_visual_segment_embedding
        self.layoutlmv2 = LayoutLMv2Model(config)
        self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

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

        Args:
            self (LayoutLMv2ForQuestionAnswering): The instance of the LayoutLMv2ForQuestionAnswering class.
                This parameter represents the current instance of the LayoutLMv2ForQuestionAnswering class
                where the method is called. It is used to access the model's embeddings to retrieve the input embeddings.

        Returns:
            None: This method does not return any value. It simply returns the word embeddings from the LayoutLMv2 model.

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

    def forward(
            self,
            input_ids: Optional[mindspore.Tensor] = None,
            bbox: Optional[mindspore.Tensor] = None,
            image: Optional[mindspore.Tensor] = None,
            attention_mask: Optional[mindspore.Tensor] = None,
            token_type_ids: Optional[mindspore.Tensor] = None,
            position_ids: Optional[mindspore.Tensor] = None,
            head_mask: Optional[mindspore.Tensor] = None,
            inputs_embeds: Optional[mindspore.Tensor] = None,
            start_positions: Optional[mindspore.Tensor] = None,
            end_positions: Optional[mindspore.Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ) -> Union[Tuple, QuestionAnsweringModelOutput]:
        r"""
        Args:
            start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
                Labels for position (index) of the start of the labelled span for computing the token classification loss.
                Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
                are not taken into account for computing the loss.
            end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
                Labels for position (index) of the end of the labelled span for computing the token classification loss.
                Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
                are not taken into account for computing the loss.

        Returns:
            Union[Tuple, QuestionAnsweringModelOutput]

        Example:
            In this example below, we give the LayoutLMv2 model an image (of texts) and ask it a question. It will give us
            a prediction of what it thinks the answer is (the span of the answer within the texts parsed from the image).
            ```python
            >>> from transformers import AutoProcessor, LayoutLMv2ForQuestionAnswering, set_seed
            >>> import torch
            >>> from PIL import Image
            >>> from datasets import load_dataset
            ...
            >>> set_seed(88)
            >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
            >>> model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")
            ...
            >>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
            >>> image_path = dataset["test"][0]["file"]
            >>> image = Image.open(image_path).convert("RGB")
            >>> question = "When is coffee break?"
            >>> encoding = processor(image, question, return_tensors="pt")
            ...
            >>> outputs = model(**encoding)
            >>> predicted_start_idx = outputs.start_logits.argmax(-1).item()
            >>> predicted_end_idx = outputs.end_logits.argmax(-1).item()
            >>> predicted_start_idx, predicted_end_idx
            (154, 287)
            >>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
            >>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
            >>> predicted_answer  # results are not very good without further fine-tuning
            'council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public ...
            ```

            ```python
            >>> target_start_index = torch.tensor([7])
            >>> target_end_index = torch.tensor([14])
            >>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
            >>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
            >>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
            >>> predicted_answer_span_start, predicted_answer_span_end
            (154, 287)
            ```
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

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

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

        seq_length = input_shape[1]
        # only take the text part of the output representations
        sequence_output = outputs[0][:, :seq_length]

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

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

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

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

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForQuestionAnswering.__init__(config, has_visual_segment_embedding=True)

Initialize the LayoutLMv2ForQuestionAnswering class.

PARAMETER DESCRIPTION
self

The object instance of the LayoutLMv2ForQuestionAnswering class.

TYPE: LayoutLMv2ForQuestionAnswering

config

The configuration object for the LayoutLMv2 model.

TYPE: LayoutLMv2Config

has_visual_segment_embedding

A boolean flag indicating whether visual segment embedding is enabled. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
def __init__(self, config, has_visual_segment_embedding=True):
    """
    Initialize the LayoutLMv2ForQuestionAnswering class.

    Args:
        self (LayoutLMv2ForQuestionAnswering): The object instance of the LayoutLMv2ForQuestionAnswering class.
        config (LayoutLMv2Config): The configuration object for the LayoutLMv2 model.
        has_visual_segment_embedding (bool, optional): A boolean flag indicating whether visual segment embedding
            is enabled. Defaults to True.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    config.has_visual_segment_embedding = has_visual_segment_embedding
    self.layoutlmv2 = LayoutLMv2Model(config)
    self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForQuestionAnswering.forward(input_ids=None, bbox=None, image=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
start_positions

Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

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

end_positions

Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence are not taken into account for computing the loss.

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

RETURNS DESCRIPTION
Union[Tuple, QuestionAnsweringModelOutput]

Union[Tuple, QuestionAnsweringModelOutput]

Example

In this example below, we give the LayoutLMv2 model an image (of texts) and ask it a question. It will give us a prediction of what it thinks the answer is (the span of the answer within the texts parsed from the image).

>>> from transformers import AutoProcessor, LayoutLMv2ForQuestionAnswering, set_seed
>>> import torch
>>> from PIL import Image
>>> from datasets import load_dataset
...
>>> set_seed(88)
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")
...
>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")
>>> question = "When is coffee break?"
>>> encoding = processor(image, question, return_tensors="pt")
...
>>> outputs = model(**encoding)
>>> predicted_start_idx = outputs.start_logits.argmax(-1).item()
>>> predicted_end_idx = outputs.end_logits.argmax(-1).item()
>>> predicted_start_idx, predicted_end_idx
(154, 287)
>>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
>>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
>>> predicted_answer  # results are not very good without further fine-tuning
'council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public ...

>>> target_start_index = torch.tensor([7])
>>> target_end_index = torch.tensor([14])
>>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
>>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
>>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
>>> predicted_answer_span_start, predicted_answer_span_end
(154, 287)
Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
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
def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        bbox: Optional[mindspore.Tensor] = None,
        image: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        start_positions: Optional[mindspore.Tensor] = None,
        end_positions: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
) -> Union[Tuple, QuestionAnsweringModelOutput]:
    r"""
    Args:
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.

    Returns:
        Union[Tuple, QuestionAnsweringModelOutput]

    Example:
        In this example below, we give the LayoutLMv2 model an image (of texts) and ask it a question. It will give us
        a prediction of what it thinks the answer is (the span of the answer within the texts parsed from the image).
        ```python
        >>> from transformers import AutoProcessor, LayoutLMv2ForQuestionAnswering, set_seed
        >>> import torch
        >>> from PIL import Image
        >>> from datasets import load_dataset
        ...
        >>> set_seed(88)
        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
        >>> model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")
        ...
        >>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
        >>> image_path = dataset["test"][0]["file"]
        >>> image = Image.open(image_path).convert("RGB")
        >>> question = "When is coffee break?"
        >>> encoding = processor(image, question, return_tensors="pt")
        ...
        >>> outputs = model(**encoding)
        >>> predicted_start_idx = outputs.start_logits.argmax(-1).item()
        >>> predicted_end_idx = outputs.end_logits.argmax(-1).item()
        >>> predicted_start_idx, predicted_end_idx
        (154, 287)
        >>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
        >>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
        >>> predicted_answer  # results are not very good without further fine-tuning
        'council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public ...
        ```

        ```python
        >>> target_start_index = torch.tensor([7])
        >>> target_end_index = torch.tensor([14])
        >>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
        >>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
        >>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
        >>> predicted_answer_span_start, predicted_answer_span_end
        (154, 287)
        ```
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

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

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

    seq_length = input_shape[1]
    # only take the text part of the output representations
    sequence_output = outputs[0][:, :seq_length]

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

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

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

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

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForQuestionAnswering.get_input_embeddings()

Method to retrieve the input embeddings from LayoutLMv2 model for question answering.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2ForQuestionAnswering class. This parameter represents the current instance of the LayoutLMv2ForQuestionAnswering class where the method is called. It is used to access the model's embeddings to retrieve the input embeddings.

TYPE: LayoutLMv2ForQuestionAnswering

RETURNS DESCRIPTION
None

This method does not return any value. It simply returns the word embeddings from the LayoutLMv2 model.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from LayoutLMv2 model for question answering.

    Args:
        self (LayoutLMv2ForQuestionAnswering): The instance of the LayoutLMv2ForQuestionAnswering class.
            This parameter represents the current instance of the LayoutLMv2ForQuestionAnswering class
            where the method is called. It is used to access the model's embeddings to retrieve the input embeddings.

    Returns:
        None: This method does not return any value. It simply returns the word embeddings from the LayoutLMv2 model.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForSequenceClassification

Bases: LayoutLMv2PreTrainedModel

LayoutLMv2ForSequenceClassification is a LayoutLMv2 model with a sequence classification head on top (a linear layer on top of the pooled output) It is based on the implementation of LayoutLMv2ForSequenceClassification.

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

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

                - Type: LayoutLMv2Config
                - Purpose: Specifies the model's configuration parameters.
                - Restrictions: None

        Returns:
            None

        Raises:
            None
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.layoutlmv2 = LayoutLMv2Model(config)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size * 3, config.num_labels)

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

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

        Args:
            self: LayoutLMv2ForSequenceClassification object.
                Represents the instance of the LayoutLMv2ForSequenceClassification class.

        Returns:
            None: This method returns None as it simply retrieves the input embeddings without any additional processing.

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

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

        Returns:
            Union[Tuple, SequenceClassifierOutput]

        Example:
            ```python
            >>> from transformers import AutoProcessor, LayoutLMv2ForSequenceClassification, set_seed
            >>> from PIL import Image
            >>> import torch
            >>> from datasets import load_dataset
            ...
            >>> set_seed(88)
            ...
            >>> dataset = load_dataset("rvl_cdip", split="train", streaming=True)
            >>> data = next(iter(dataset))
            >>> image = data["image"].convert("RGB")
            ...
            >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
            >>> model = LayoutLMv2ForSequenceClassification.from_pretrained(
            ...     "microsoft/layoutlmv2-base-uncased", num_labels=dataset.info.features["label"].num_classes
            ... )
            ...
            >>> encoding = processor(image, return_tensors="pt")
            >>> sequence_label = torch.tensor([data["label"]])
            ...
            >>> outputs = model(**encoding, labels=sequence_label)
            ...
            >>> loss, logits = outputs.loss, outputs.logits
            >>> predicted_idx = logits.argmax(axis=-1).item()
            >>> predicted_answer = dataset.info.features["label"].names[4]
            >>> predicted_idx, predicted_answer
            (4, 'advertisement')
            ```
        """
        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")
        elif input_ids is not None:
            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
            input_shape = input_ids.shape
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.shape[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        visual_shape = list(input_shape)
        visual_shape[1] = self.config.image_feature_pool_shape[0] * self.config.image_feature_pool_shape[1]
        final_shape = list(input_shape)
        final_shape[1] += visual_shape[1]

        visual_bbox = self.layoutlmv2._calc_visual_bbox(
            self.config.image_feature_pool_shape, bbox, final_shape
        )

        visual_position_ids = ops.arange(0, visual_shape[1], dtype=mindspore.int64).repeat(
            input_shape[0], 1
        )

        initial_image_embeddings = self.layoutlmv2._calc_img_embeddings(
            image=image,
            bbox=visual_bbox,
            position_ids=visual_position_ids,
        )

        outputs = self.layoutlmv2(
            input_ids=input_ids,
            bbox=bbox,
            image=image,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        if input_ids is not None:
            input_shape = input_ids.shape
        else:
            input_shape = inputs_embeds.shape[:-1]

        seq_length = input_shape[1]
        sequence_output, final_image_embeddings = outputs[0][:, :seq_length], outputs[0][:, seq_length:]

        cls_final_output = sequence_output[:, 0, :]

        # average-pool the visual embeddings
        pooled_initial_image_embeddings = initial_image_embeddings.mean(axis=1)
        pooled_final_image_embeddings = final_image_embeddings.mean(axis=1)
        # concatenate with cls_final_output
        sequence_output = ops.cat(
            [cls_final_output, pooled_initial_image_embeddings, pooled_final_image_embeddings], axis=1
        )
        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_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 = 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 = CrossEntropyLoss()
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1).astype(mindspore.int32))
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = BCEWithLogitsLoss()
                loss = loss_fct(logits, labels)
        if not return_dict:
            output = (logits,) + outputs[2:]
            return ((loss,) + output) if loss is not None else output

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForSequenceClassification.__init__(config)

Initializes a new instance of the LayoutLMv2ForSequenceClassification class.

PARAMETER DESCRIPTION
self

The object instance.

config

An instance of the LayoutLMv2Config class containing the configuration parameters for the model.

  • Type: LayoutLMv2Config
  • Purpose: Specifies the model's configuration parameters.
  • Restrictions: None

RETURNS DESCRIPTION

None

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

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

            - Type: LayoutLMv2Config
            - Purpose: Specifies the model's configuration parameters.
            - Restrictions: None

    Returns:
        None

    Raises:
        None
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.layoutlmv2 = LayoutLMv2Model(config)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size * 3, config.num_labels)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForSequenceClassification.forward(input_ids=None, bbox=None, image=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

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

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

RETURNS DESCRIPTION
Union[Tuple, SequenceClassifierOutput]

Union[Tuple, SequenceClassifierOutput]

Example
>>> from transformers import AutoProcessor, LayoutLMv2ForSequenceClassification, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset
...
>>> set_seed(88)
...
>>> dataset = load_dataset("rvl_cdip", split="train", streaming=True)
>>> data = next(iter(dataset))
>>> image = data["image"].convert("RGB")
...
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForSequenceClassification.from_pretrained(
...     "microsoft/layoutlmv2-base-uncased", num_labels=dataset.info.features["label"].num_classes
... )
...
>>> encoding = processor(image, return_tensors="pt")
>>> sequence_label = torch.tensor([data["label"]])
...
>>> outputs = model(**encoding, labels=sequence_label)
...
>>> loss, logits = outputs.loss, outputs.logits
>>> predicted_idx = logits.argmax(axis=-1).item()
>>> predicted_answer = dataset.info.features["label"].names[4]
>>> predicted_idx, predicted_answer
(4, 'advertisement')
Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
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
def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        bbox: Optional[mindspore.Tensor] = None,
        image: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
) -> Union[Tuple, SequenceClassifierOutput]:
    r"""
    Args:
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

    Returns:
        Union[Tuple, SequenceClassifierOutput]

    Example:
        ```python
        >>> from transformers import AutoProcessor, LayoutLMv2ForSequenceClassification, set_seed
        >>> from PIL import Image
        >>> import torch
        >>> from datasets import load_dataset
        ...
        >>> set_seed(88)
        ...
        >>> dataset = load_dataset("rvl_cdip", split="train", streaming=True)
        >>> data = next(iter(dataset))
        >>> image = data["image"].convert("RGB")
        ...
        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
        >>> model = LayoutLMv2ForSequenceClassification.from_pretrained(
        ...     "microsoft/layoutlmv2-base-uncased", num_labels=dataset.info.features["label"].num_classes
        ... )
        ...
        >>> encoding = processor(image, return_tensors="pt")
        >>> sequence_label = torch.tensor([data["label"]])
        ...
        >>> outputs = model(**encoding, labels=sequence_label)
        ...
        >>> loss, logits = outputs.loss, outputs.logits
        >>> predicted_idx = logits.argmax(axis=-1).item()
        >>> predicted_answer = dataset.info.features["label"].names[4]
        >>> predicted_idx, predicted_answer
        (4, 'advertisement')
        ```
    """
    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")
    elif input_ids is not None:
        self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
        input_shape = input_ids.shape
    elif inputs_embeds is not None:
        input_shape = inputs_embeds.shape[:-1]
    else:
        raise ValueError("You have to specify either input_ids or inputs_embeds")

    visual_shape = list(input_shape)
    visual_shape[1] = self.config.image_feature_pool_shape[0] * self.config.image_feature_pool_shape[1]
    final_shape = list(input_shape)
    final_shape[1] += visual_shape[1]

    visual_bbox = self.layoutlmv2._calc_visual_bbox(
        self.config.image_feature_pool_shape, bbox, final_shape
    )

    visual_position_ids = ops.arange(0, visual_shape[1], dtype=mindspore.int64).repeat(
        input_shape[0], 1
    )

    initial_image_embeddings = self.layoutlmv2._calc_img_embeddings(
        image=image,
        bbox=visual_bbox,
        position_ids=visual_position_ids,
    )

    outputs = self.layoutlmv2(
        input_ids=input_ids,
        bbox=bbox,
        image=image,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    if input_ids is not None:
        input_shape = input_ids.shape
    else:
        input_shape = inputs_embeds.shape[:-1]

    seq_length = input_shape[1]
    sequence_output, final_image_embeddings = outputs[0][:, :seq_length], outputs[0][:, seq_length:]

    cls_final_output = sequence_output[:, 0, :]

    # average-pool the visual embeddings
    pooled_initial_image_embeddings = initial_image_embeddings.mean(axis=1)
    pooled_final_image_embeddings = final_image_embeddings.mean(axis=1)
    # concatenate with cls_final_output
    sequence_output = ops.cat(
        [cls_final_output, pooled_initial_image_embeddings, pooled_final_image_embeddings], axis=1
    )
    sequence_output = self.dropout(sequence_output)
    logits = self.classifier(sequence_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 = 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 = CrossEntropyLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1).astype(mindspore.int32))
        elif self.config.problem_type == "multi_label_classification":
            loss_fct = BCEWithLogitsLoss()
            loss = loss_fct(logits, labels)
    if not return_dict:
        output = (logits,) + outputs[2:]
        return ((loss,) + output) if loss is not None else output

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForSequenceClassification.get_input_embeddings()

Method to retrieve the input embeddings from the LayoutLMv2 model for sequence classification.

PARAMETER DESCRIPTION
self

LayoutLMv2ForSequenceClassification object. Represents the instance of the LayoutLMv2ForSequenceClassification class.

RETURNS DESCRIPTION
None

This method returns None as it simply retrieves the input embeddings without any additional processing.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from the LayoutLMv2 model for sequence classification.

    Args:
        self: LayoutLMv2ForSequenceClassification object.
            Represents the instance of the LayoutLMv2ForSequenceClassification class.

    Returns:
        None: This method returns None as it simply retrieves the input embeddings without any additional processing.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForTokenClassification

Bases: LayoutLMv2PreTrainedModel

LayoutLMv2ForTokenClassification is a LayoutLMv2 model with a token classification head. It is based on the implementation of LayoutLMv2ForTokenClassification.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2ForTokenClassification(LayoutLMv2PreTrainedModel):
    """
    LayoutLMv2ForTokenClassification is a LayoutLMv2 model with a token classification head.
    It is based on the implementation of LayoutLMv2ForTokenClassification.
    """
    def __init__(self, config):
        """
        Initializes a LayoutLMv2ForTokenClassification instance.

        Args:
            self (LayoutLMv2ForTokenClassification): The instance of the LayoutLMv2ForTokenClassification class.
            config:
                An object containing the configuration settings for the LayoutLMv2 model.

                - Type: LayoutLMv2Config
                - Purpose: Specifies the configuration parameters for the model.
                - Restrictions: Must be an instance of LayoutLMv2Config.

        Returns:
            None.

        Raises:
            TypeError: If the 'config' parameter is not an instance of LayoutLMv2Config.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.layoutlmv2 = LayoutLMv2Model(config)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

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

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

        Args:
            self: An instance of the LayoutLMv2ForTokenClassification class.

        Returns:
            None: The method returns the input embeddings for the LayoutLMv2ForTokenClassification.

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

    def forward(
            self,
            input_ids: Optional[mindspore.Tensor] = None,
            bbox: Optional[mindspore.Tensor] = None,
            image: Optional[mindspore.Tensor] = None,
            attention_mask: Optional[mindspore.Tensor] = None,
            token_type_ids: Optional[mindspore.Tensor] = None,
            position_ids: Optional[mindspore.Tensor] = None,
            head_mask: Optional[mindspore.Tensor] = None,
            inputs_embeds: Optional[mindspore.Tensor] = None,
            labels: Optional[mindspore.Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ) -> Union[Tuple, TokenClassifierOutput]:
        r"""
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.

        Returns:
            Union[Tuple, TokenClassifierOutput]

        Example:
            ```python
            >>> from transformers import AutoProcessor, LayoutLMv2ForTokenClassification, set_seed
            >>> from PIL import Image
            >>> from datasets import load_dataset
            ...
            >>> set_seed(88)
            ...
            >>> datasets = load_dataset("nielsr/funsd", split="test")
            >>> labels = datasets.features["ner_tags"].feature.names
            >>> id2label = {v: k for v, k in enumerate(labels)}
            ...
            >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
            >>> model = LayoutLMv2ForTokenClassification.from_pretrained(
            ...     "microsoft/layoutlmv2-base-uncased", num_labels=len(labels)
            ... )
            ...
            >>> data = datasets[0]
            >>> image = Image.open(data["image_path"]).convert("RGB")
            >>> words = data["words"]
            >>> boxes = data["bboxes"]  # make sure to normalize your bounding boxes
            >>> word_labels = data["ner_tags"]
            >>> encoding = processor(
            ...     image,
            ...     words,
            ...     boxes=boxes,
            ...     word_labels=word_labels,
            ...     padding="max_length",
            ...     truncation=True,
            ...     return_tensors="pt",
            ... )
            ...
            >>> outputs = model(**encoding)
            >>> logits, loss = outputs.logits, outputs.loss
            ...
            >>> predicted_token_class_ids = logits.argmax(-1)
            >>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
            >>> predicted_tokens_classes[:5]
            ['B-ANSWER', 'B-HEADER', 'B-HEADER', 'B-HEADER', 'B-HEADER']
            ```
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.layoutlmv2(
            input_ids=input_ids,
            bbox=bbox,
            image=image,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        if input_ids is not None:
            input_shape = input_ids.shape
        else:
            input_shape = inputs_embeds.shape[:-1]

        seq_length = input_shape[1]
        # only take the text part of the output representations
        sequence_output = outputs[0][:, :seq_length]
        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_output)

        loss = None
        if labels is not None:
            loss_fct = CrossEntropyLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1).astype(mindspore.int32))

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

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForTokenClassification.__init__(config)

Initializes a LayoutLMv2ForTokenClassification instance.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2ForTokenClassification class.

TYPE: LayoutLMv2ForTokenClassification

config

An object containing the configuration settings for the LayoutLMv2 model.

  • Type: LayoutLMv2Config
  • Purpose: Specifies the configuration parameters for the model.
  • Restrictions: Must be an instance of LayoutLMv2Config.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the 'config' parameter is not an instance of LayoutLMv2Config.

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

    Args:
        self (LayoutLMv2ForTokenClassification): The instance of the LayoutLMv2ForTokenClassification class.
        config:
            An object containing the configuration settings for the LayoutLMv2 model.

            - Type: LayoutLMv2Config
            - Purpose: Specifies the configuration parameters for the model.
            - Restrictions: Must be an instance of LayoutLMv2Config.

    Returns:
        None.

    Raises:
        TypeError: If the 'config' parameter is not an instance of LayoutLMv2Config.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.layoutlmv2 = LayoutLMv2Model(config)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForTokenClassification.forward(input_ids=None, bbox=None, image=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

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

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

RETURNS DESCRIPTION
Union[Tuple, TokenClassifierOutput]

Union[Tuple, TokenClassifierOutput]

Example
>>> from transformers import AutoProcessor, LayoutLMv2ForTokenClassification, set_seed
>>> from PIL import Image
>>> from datasets import load_dataset
...
>>> set_seed(88)
...
>>> datasets = load_dataset("nielsr/funsd", split="test")
>>> labels = datasets.features["ner_tags"].feature.names
>>> id2label = {v: k for v, k in enumerate(labels)}
...
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
>>> model = LayoutLMv2ForTokenClassification.from_pretrained(
...     "microsoft/layoutlmv2-base-uncased", num_labels=len(labels)
... )
...
>>> data = datasets[0]
>>> image = Image.open(data["image_path"]).convert("RGB")
>>> words = data["words"]
>>> boxes = data["bboxes"]  # make sure to normalize your bounding boxes
>>> word_labels = data["ner_tags"]
>>> encoding = processor(
...     image,
...     words,
...     boxes=boxes,
...     word_labels=word_labels,
...     padding="max_length",
...     truncation=True,
...     return_tensors="pt",
... )
...
>>> outputs = model(**encoding)
>>> logits, loss = outputs.logits, outputs.loss
...
>>> predicted_token_class_ids = logits.argmax(-1)
>>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes[:5]
['B-ANSWER', 'B-HEADER', 'B-HEADER', 'B-HEADER', 'B-HEADER']
Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        bbox: Optional[mindspore.Tensor] = None,
        image: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
) -> Union[Tuple, TokenClassifierOutput]:
    r"""
    Args:
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.

    Returns:
        Union[Tuple, TokenClassifierOutput]

    Example:
        ```python
        >>> from transformers import AutoProcessor, LayoutLMv2ForTokenClassification, set_seed
        >>> from PIL import Image
        >>> from datasets import load_dataset
        ...
        >>> set_seed(88)
        ...
        >>> datasets = load_dataset("nielsr/funsd", split="test")
        >>> labels = datasets.features["ner_tags"].feature.names
        >>> id2label = {v: k for v, k in enumerate(labels)}
        ...
        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
        >>> model = LayoutLMv2ForTokenClassification.from_pretrained(
        ...     "microsoft/layoutlmv2-base-uncased", num_labels=len(labels)
        ... )
        ...
        >>> data = datasets[0]
        >>> image = Image.open(data["image_path"]).convert("RGB")
        >>> words = data["words"]
        >>> boxes = data["bboxes"]  # make sure to normalize your bounding boxes
        >>> word_labels = data["ner_tags"]
        >>> encoding = processor(
        ...     image,
        ...     words,
        ...     boxes=boxes,
        ...     word_labels=word_labels,
        ...     padding="max_length",
        ...     truncation=True,
        ...     return_tensors="pt",
        ... )
        ...
        >>> outputs = model(**encoding)
        >>> logits, loss = outputs.logits, outputs.loss
        ...
        >>> predicted_token_class_ids = logits.argmax(-1)
        >>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
        >>> predicted_tokens_classes[:5]
        ['B-ANSWER', 'B-HEADER', 'B-HEADER', 'B-HEADER', 'B-HEADER']
        ```
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.layoutlmv2(
        input_ids=input_ids,
        bbox=bbox,
        image=image,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    if input_ids is not None:
        input_shape = input_ids.shape
    else:
        input_shape = inputs_embeds.shape[:-1]

    seq_length = input_shape[1]
    # only take the text part of the output representations
    sequence_output = outputs[0][:, :seq_length]
    sequence_output = self.dropout(sequence_output)
    logits = self.classifier(sequence_output)

    loss = None
    if labels is not None:
        loss_fct = CrossEntropyLoss()
        loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1).astype(mindspore.int32))

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

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2ForTokenClassification.get_input_embeddings()

Returns the input embeddings for LayoutLMv2ForTokenClassification.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2ForTokenClassification class.

RETURNS DESCRIPTION
None

The method returns the input embeddings for the LayoutLMv2ForTokenClassification.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
def get_input_embeddings(self):
    """
    Returns the input embeddings for LayoutLMv2ForTokenClassification.

    Args:
        self: An instance of the LayoutLMv2ForTokenClassification class.

    Returns:
        None: The method returns the input embeddings for the LayoutLMv2ForTokenClassification.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Intermediate

Bases: Module

LayoutLMv2Intermediate is a simple feedforward network. It is based on the implementation of BertIntermediate.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2Intermediate(nn.Module):
    """
    LayoutLMv2Intermediate is a simple feedforward network. It is based on the implementation of BertIntermediate.
    """
    def __init__(self, config):
        """
        Initialize the LayoutLMv2Intermediate class.

        Args:
            self (object): The current instance of the class.
            config (object): An object containing configuration parameters for the intermediate layer.
                It must have the following attributes:

                - hidden_size (int): The size of the hidden layer.
                - intermediate_size (int): The size of the intermediate layer.
                - hidden_act (str or function): The activation function for the hidden layer.
                If a string, it should be a key in the ACT2FN dictionary.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided.
            ValueError: If the config parameter does not contain the required attributes.
            KeyError: If the hidden activation function specified in the config parameter
                is not found in the ACT2FN dictionary.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        if isinstance(config.hidden_act, str):
            self.intermediate_act_fn = ACT2FN[config.hidden_act]
        else:
            self.intermediate_act_fn = config.hidden_act

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        Method 'forward' in the class 'LayoutLMv2Intermediate'.

        Args:
            self: LayoutLMv2Intermediate object.
                Represents the instance of the LayoutLMv2Intermediate class.
            hidden_states: mindspore.Tensor.
                Input tensor containing hidden states that need to be processed.

        Returns:
            mindspore.Tensor.
                Processed hidden states returned after passing through the dense layer
                and intermediate activation function.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Intermediate.__init__(config)

Initialize the LayoutLMv2Intermediate class.

PARAMETER DESCRIPTION
self

The current instance of the class.

TYPE: object

config

An object containing configuration parameters for the intermediate layer. It must have the following attributes:

  • hidden_size (int): The size of the hidden layer.
  • intermediate_size (int): The size of the intermediate layer.
  • hidden_act (str or function): The activation function for the hidden layer. If a string, it should be a key in the ACT2FN dictionary.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided.

ValueError

If the config parameter does not contain the required attributes.

KeyError

If the hidden activation function specified in the config parameter is not found in the ACT2FN dictionary.

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

    Args:
        self (object): The current instance of the class.
        config (object): An object containing configuration parameters for the intermediate layer.
            It must have the following attributes:

            - hidden_size (int): The size of the hidden layer.
            - intermediate_size (int): The size of the intermediate layer.
            - hidden_act (str or function): The activation function for the hidden layer.
            If a string, it should be a key in the ACT2FN dictionary.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided.
        ValueError: If the config parameter does not contain the required attributes.
        KeyError: If the hidden activation function specified in the config parameter
            is not found in the ACT2FN dictionary.
    """
    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.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Intermediate.forward(hidden_states)

Method 'forward' in the class 'LayoutLMv2Intermediate'.

PARAMETER DESCRIPTION
self

LayoutLMv2Intermediate object. Represents the instance of the LayoutLMv2Intermediate class.

hidden_states

mindspore.Tensor. Input tensor containing hidden states that need to be processed.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor. Processed hidden states returned after passing through the dense layer and intermediate activation function.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    Method 'forward' in the class 'LayoutLMv2Intermediate'.

    Args:
        self: LayoutLMv2Intermediate object.
            Represents the instance of the LayoutLMv2Intermediate class.
        hidden_states: mindspore.Tensor.
            Input tensor containing hidden states that need to be processed.

    Returns:
        mindspore.Tensor.
            Processed hidden states returned after passing through the dense layer
            and intermediate activation function.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Layer

Bases: Module

LayoutLMv2Layer is made up of self-attention and feedforward network. It is based on the implementation of BertLayer.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
class LayoutLMv2Layer(nn.Module):
    """
    LayoutLMv2Layer is made up of self-attention and feedforward network. It is based on the implementation of BertLayer.
    """
    def __init__(self, config):
        """Initialize a LayoutLMv2Layer.

        Args:
            self: Instance of the LayoutLMv2Layer class.
            config:
                Configuration object containing parameters for the layer initialization.

                - Type: object
                - Purpose: To configure the layer with specific settings.
                - Restrictions: Must be a valid configuration object.

        Returns:
            None

        Raises:
            TypeError: If the config parameter is not of the expected type.
        """
        super().__init__()
        self.chunk_size_feed_forward = config.chunk_size_feed_forward
        self.seq_len_dim = 1
        self.attention = LayoutLMv2Attention(config)
        self.intermediate = LayoutLMv2Intermediate(config)
        self.output = LayoutLMv2Output(config)

    def forward(
            self,
            hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
            rel_pos=None,
            rel_2d_pos=None,
    ):
        """
        Constructs a LayoutLMv2Layer by applying the attention mechanism and feed-forward neural network to
        the input hidden states.

        Args:
            self: An instance of the LayoutLMv2Layer class.
            hidden_states (torch.Tensor): The input hidden states of shape `(batch_size, sequence_length, hidden_size)`.
            attention_mask (torch.Tensor, optional): The attention mask tensor of shape `(batch_size, sequence_length)`.
                Defaults to None.
            head_mask (torch.Tensor, optional): The tensor to mask selected heads of the multi-head attention module.
                Defaults to None.
            output_attentions (bool, optional): Whether to output the attention weights. Defaults to False.
            rel_pos (torch.Tensor, optional): The tensor of relative position encoding of shape
                `(batch_size, num_heads, sequence_length, sequence_length)`. Defaults to None.
            rel_2d_pos (torch.Tensor, optional): The tensor of 2D relative position encoding of shape
                `(batch_size, num_heads, sequence_length, sequence_length, 2)`. Defaults to None.

        Returns:
            outputs (tuple):
                A tuple of the following tensors:

                - layer_output (torch.Tensor): The output tensor of shape `(batch_size, sequence_length, hidden_size)`.
                - attention_weights (torch.Tensor, optional): The attention weights tensor of shape
                `(batch_size, num_heads, sequence_length, sequence_length)`. Only returned if `output_attentions=True`.

        Raises:
            None.
        """
        self_attention_outputs = self.attention(
            hidden_states,
            attention_mask,
            head_mask,
            output_attentions=output_attentions,
            rel_pos=rel_pos,
            rel_2d_pos=rel_2d_pos,
        )
        attention_output = self_attention_outputs[0]

        outputs = self_attention_outputs[1:]  # 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, attention_output
        )
        outputs = (layer_output,) + outputs

        return outputs

    def feed_forward_chunk(self, attention_output):
        """
        Performs a feed forward operation on the given attention output in the LayoutLMv2Layer.

        Args:
            self (LayoutLMv2Layer): An instance of the LayoutLMv2Layer class.
            attention_output: The attention output tensor to be processed.
                It should have shape (batch_size, sequence_length, hidden_size).

        Returns:
            None: This method modifies the internal state of the LayoutLMv2Layer instance.

        Raises:
            None.

        """
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        return layer_output

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Layer.__init__(config)

Initialize a LayoutLMv2Layer.

PARAMETER DESCRIPTION
self

Instance of the LayoutLMv2Layer class.

config

Configuration object containing parameters for the layer initialization.

  • Type: object
  • Purpose: To configure the layer with specific settings.
  • Restrictions: Must be a valid configuration object.

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
TypeError

If the config parameter is not of the expected type.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def __init__(self, config):
    """Initialize a LayoutLMv2Layer.

    Args:
        self: Instance of the LayoutLMv2Layer class.
        config:
            Configuration object containing parameters for the layer initialization.

            - Type: object
            - Purpose: To configure the layer with specific settings.
            - Restrictions: Must be a valid configuration object.

    Returns:
        None

    Raises:
        TypeError: If the config parameter is not of the expected type.
    """
    super().__init__()
    self.chunk_size_feed_forward = config.chunk_size_feed_forward
    self.seq_len_dim = 1
    self.attention = LayoutLMv2Attention(config)
    self.intermediate = LayoutLMv2Intermediate(config)
    self.output = LayoutLMv2Output(config)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Layer.feed_forward_chunk(attention_output)

Performs a feed forward operation on the given attention output in the LayoutLMv2Layer.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Layer class.

TYPE: LayoutLMv2Layer

attention_output

The attention output tensor to be processed. It should have shape (batch_size, sequence_length, hidden_size).

RETURNS DESCRIPTION
None

This method modifies the internal state of the LayoutLMv2Layer instance.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def feed_forward_chunk(self, attention_output):
    """
    Performs a feed forward operation on the given attention output in the LayoutLMv2Layer.

    Args:
        self (LayoutLMv2Layer): An instance of the LayoutLMv2Layer class.
        attention_output: The attention output tensor to be processed.
            It should have shape (batch_size, sequence_length, hidden_size).

    Returns:
        None: This method modifies the internal state of the LayoutLMv2Layer instance.

    Raises:
        None.

    """
    intermediate_output = self.intermediate(attention_output)
    layer_output = self.output(intermediate_output, attention_output)
    return layer_output

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Layer.forward(hidden_states, attention_mask=None, head_mask=None, output_attentions=False, rel_pos=None, rel_2d_pos=None)

Constructs a LayoutLMv2Layer by applying the attention mechanism and feed-forward neural network to the input hidden states.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Layer class.

hidden_states

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

TYPE: Tensor

attention_mask

The attention mask tensor of shape (batch_size, sequence_length). Defaults to None.

TYPE: Tensor DEFAULT: None

head_mask

The tensor to mask selected heads of the multi-head attention module. Defaults to None.

TYPE: Tensor DEFAULT: None

output_attentions

Whether to output the attention weights. Defaults to False.

TYPE: bool DEFAULT: False

rel_pos

The tensor of relative position encoding of shape (batch_size, num_heads, sequence_length, sequence_length). Defaults to None.

TYPE: Tensor DEFAULT: None

rel_2d_pos

The tensor of 2D relative position encoding of shape (batch_size, num_heads, sequence_length, sequence_length, 2). Defaults to None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
outputs

A tuple of the following tensors:

  • layer_output (torch.Tensor): The output tensor of shape (batch_size, sequence_length, hidden_size).
  • attention_weights (torch.Tensor, optional): The attention weights tensor of shape (batch_size, num_heads, sequence_length, sequence_length). Only returned if output_attentions=True.

TYPE: tuple

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(
        self,
        hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
        rel_pos=None,
        rel_2d_pos=None,
):
    """
    Constructs a LayoutLMv2Layer by applying the attention mechanism and feed-forward neural network to
    the input hidden states.

    Args:
        self: An instance of the LayoutLMv2Layer class.
        hidden_states (torch.Tensor): The input hidden states of shape `(batch_size, sequence_length, hidden_size)`.
        attention_mask (torch.Tensor, optional): The attention mask tensor of shape `(batch_size, sequence_length)`.
            Defaults to None.
        head_mask (torch.Tensor, optional): The tensor to mask selected heads of the multi-head attention module.
            Defaults to None.
        output_attentions (bool, optional): Whether to output the attention weights. Defaults to False.
        rel_pos (torch.Tensor, optional): The tensor of relative position encoding of shape
            `(batch_size, num_heads, sequence_length, sequence_length)`. Defaults to None.
        rel_2d_pos (torch.Tensor, optional): The tensor of 2D relative position encoding of shape
            `(batch_size, num_heads, sequence_length, sequence_length, 2)`. Defaults to None.

    Returns:
        outputs (tuple):
            A tuple of the following tensors:

            - layer_output (torch.Tensor): The output tensor of shape `(batch_size, sequence_length, hidden_size)`.
            - attention_weights (torch.Tensor, optional): The attention weights tensor of shape
            `(batch_size, num_heads, sequence_length, sequence_length)`. Only returned if `output_attentions=True`.

    Raises:
        None.
    """
    self_attention_outputs = self.attention(
        hidden_states,
        attention_mask,
        head_mask,
        output_attentions=output_attentions,
        rel_pos=rel_pos,
        rel_2d_pos=rel_2d_pos,
    )
    attention_output = self_attention_outputs[0]

    outputs = self_attention_outputs[1:]  # 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, attention_output
    )
    outputs = (layer_output,) + outputs

    return outputs

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Model

Bases: LayoutLMv2PreTrainedModel

LayoutLMv2Model is a LayoutLMv2 model with a visual backbone. It is based on the implementation of LayoutLMv2Model.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2Model(LayoutLMv2PreTrainedModel):
    """
    LayoutLMv2Model is a LayoutLMv2 model with a visual backbone. It is based on the implementation of LayoutLMv2Model.
    """
    def __init__(self, config):
        """
        Initializes an instance of the LayoutLMv2Model class.

        Args:
            self: The instance of the LayoutLMv2Model class.
            config:
                A configuration object containing various settings and hyperparameters for the model.

                - Type: dict
                - Purpose: Configure the model with specific settings.
                - Restrictions: Must contain specific keys and values required by the model.

        Returns:
            None.

        Raises:
            ValueError: If the provided configuration is missing required keys or has invalid values.
            TypeError: If the configuration object is not of the expected type.
        """
        super().__init__(config)
        self.config = config
        self.has_visual_segment_embedding = config.has_visual_segment_embedding
        self.use_visual_backbone = config.use_visual_backbone
        self.embeddings = LayoutLMv2Embeddings(config)
        if self.use_visual_backbone is True:
            self.visual = LayoutLMv2VisualBackbone(config)
            self.visual_proj = nn.Linear(config.image_feature_pool_shape[-1], config.hidden_size)
        if self.has_visual_segment_embedding:
            self.visual_segment_embedding = Parameter(nn.Embedding(1, config.hidden_size).weight[0])
        self.visual_LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.visual_dropout = nn.Dropout(p=config.hidden_dropout_prob)

        self.encoder = LayoutLMv2Encoder(config)
        self.pooler = LayoutLMv2Pooler(config)

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

    def get_input_embeddings(self):
        """
        This method returns the input embeddings of the LayoutLMv2Model.

        Args:
            self: The instance of the LayoutLMv2Model class.

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

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

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

        Args:
            self (LayoutLMv2Model): An instance of the LayoutLMv2Model class.
            value: The input embeddings to be set. It should be a tensor or any object that can be assigned to
                the word_embeddings attribute of the embeddings object.

        Returns:
            None.

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

    def _calc_text_embeddings(self, input_ids, bbox, position_ids, token_type_ids, inputs_embeds=None):
        """
        Calculates the text embeddings for the LayoutLMv2Model.

        Args:
            self (LayoutLMv2Model): The instance of the LayoutLMv2Model class.
            input_ids (Tensor): The input tensor of shape [batch_size, seq_length] containing the input token IDs.
            bbox (Tensor): The input tensor of shape [batch_size, seq_length, 4]
                containing the bounding box coordinates for each token.
            position_ids (Tensor): The input tensor of shape [batch_size, seq_length]
                containing the positional IDs for each token.
            token_type_ids (Tensor): The input tensor of shape [batch_size, seq_length]
                containing the token type IDs for each token.
            inputs_embeds (Tensor, optional): The optional input tensor of shape [batch_size, seq_length, hidden_size]
                containing pre-computed embeddings.

        Returns:
            Tensor: The resulting tensor of shape [batch_size, seq_length, hidden_size] containing
                the calculated text embeddings.

        Raises:
            MindSporeError: If the input_ids and inputs_embeds tensors have incompatible shapes.
            MindSporeError: If the position_ids and input_ids tensors have incompatible shapes.
            MindSporeError: If the token_type_ids and input_ids tensors have incompatible shapes.
        """
        if input_ids is not None:
            input_shape = input_ids.shape
        else:
            input_shape = inputs_embeds.shape[:-1]

        seq_length = input_shape[1]

        if position_ids is None:
            position_ids = ops.arange(seq_length, dtype=mindspore.int64)
            position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
        if token_type_ids is None:
            token_type_ids = ops.zeros_like(input_ids)

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

        position_embeddings = self.embeddings.position_embeddings(position_ids)
        spatial_position_embeddings = self.embeddings._calc_spatial_position_embeddings(bbox)
        token_type_embeddings = self.embeddings.token_type_embeddings(token_type_ids)

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

    def _calc_img_embeddings(self, image, bbox, position_ids):
        """
        Calculate image embeddings for the LayoutLMv2Model.

        Args:
            self (LayoutLMv2Model): The instance of the LayoutLMv2Model class.
            image (numpy.ndarray): The input image for which embeddings need to be calculated.
            bbox (numpy.ndarray): The bounding box coordinates associated with the image.
            position_ids (numpy.ndarray): The position IDs used for positional embeddings.

        Returns:
            The calculated embeddings are stored within the class instance.

        Raises:
            ValueError: If the image is None and visual backbone is required.
            TypeError: If the image data type cannot be converted to 'mindspore.float32'.
            AssertionError: If an unexpected condition occurs while calculating embeddings.
        """
        use_image_info = self.use_visual_backbone and image is not None
        position_embeddings = self.embeddings.position_embeddings(position_ids)
        spatial_position_embeddings = self.embeddings._calc_spatial_position_embeddings(
            bbox
        )
        if use_image_info:
            visual_embeddings = self.visual_proj(self.visual(image.astype(mindspore.float32)))
            embeddings = (
                    visual_embeddings + position_embeddings + spatial_position_embeddings
            )
        else:
            embeddings = position_embeddings + spatial_position_embeddings
        if self.has_visual_segment_embedding:
            embeddings += self.visual_segment_embedding
        embeddings = self.visual_LayerNorm(embeddings)
        embeddings = self.visual_dropout(embeddings)
        return embeddings

    def _calc_visual_bbox(self, image_feature_pool_shape, bbox, visual_shape):
        '''
        Calculate the visual bounding box based on the given image features.

        Args:
            self (LayoutLMv2Model): An instance of the LayoutLMv2Model class.
            image_feature_pool_shape (tuple): The shape of the image feature pool as (y_size, x_size).
            bbox (tensor): The bounding box tensor.
            visual_shape (tuple): The desired shape of the visual bounding box.

        Returns:
            visual_bbox (tensor): The calculated visual bounding box tensor.

        Raises:
            None.
        '''
        x_size = image_feature_pool_shape[1]
        y_size = image_feature_pool_shape[0]
        visual_bbox_x = mindspore.Tensor(
            np.arange(0, 1000 * (x_size + 1), 1000) // x_size, dtype=mindspore.int64
        )
        visual_bbox_y = mindspore.Tensor(
            np.arange(0, 1000 * (y_size + 1), 1000) // y_size, dtype=mindspore.int64
        )
        expand_shape = image_feature_pool_shape[0:2]
        expand_shape = tuple(expand_shape)
        visual_bbox = ops.stack(
            [
                visual_bbox_x[:-1].broadcast_to(expand_shape),
                visual_bbox_y[:-1].broadcast_to(expand_shape[::-1]).transpose((1, 0)),
                visual_bbox_x[1:].broadcast_to(expand_shape),
                visual_bbox_y[1:].broadcast_to(expand_shape[::-1]).transpose((1, 0)),
            ],
            axis=-1,
        ).reshape((expand_shape[0] * expand_shape[1], ops.shape(bbox)[-1]))
        visual_bbox = visual_bbox.broadcast_to(
            (visual_shape[0], visual_bbox.shape[0], visual_bbox.shape[1])
        )
        return visual_bbox

    def _get_input_shape(self, input_ids=None, inputs_embeds=None):
        """
        Returns the shape of the input tensor for the LayoutLMv2Model.

        Args:
            self (LayoutLMv2Model): The instance of the LayoutLMv2Model class.
            input_ids (Optional[torch.Tensor]): The input tensor representing the tokenized input sequence.
                Default: None.
            inputs_embeds (Optional[torch.Tensor]): The input tensor representing the embedded input sequence.
                Default: None.

        Returns:
            torch.Size or Tuple[int]: The shape of the input tensor, excluding the batch size dimension.

        Raises:
            ValueError: If both input_ids and inputs_embeds are specified.
            ValueError: If neither input_ids nor inputs_embeds are specified.

        Note:
            - It is required to specify either input_ids or inputs_embeds.
            - If input_ids is specified, the shape of the input_ids tensor is returned.
            - If inputs_embeds is specified, the shape of the inputs_embeds tensor,
            excluding the last dimension, is returned.
            - The shape represents the dimensions of the input tensor, excluding the batch size dimension.
        """
        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")
        elif input_ids is not None:
            return input_ids.shape
        elif inputs_embeds is not None:
            return inputs_embeds.shape[:-1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

    def forward(
            self,
            input_ids: Optional[mindspore.Tensor] = None,
            bbox: Optional[mindspore.Tensor] = None,
            image: Optional[mindspore.Tensor] = None,
            attention_mask: Optional[mindspore.Tensor] = None,
            token_type_ids: Optional[mindspore.Tensor] = None,
            position_ids: Optional[mindspore.Tensor] = None,
            head_mask: Optional[mindspore.Tensor] = None,
            inputs_embeds: Optional[mindspore.Tensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ) -> Union[Tuple, BaseModelOutputWithPooling]:
        r"""
        Return:
            Union[Tuple, BaseModelOutputWithPooling]

        Example:
            ```python
            >>> from transformers import AutoProcessor, LayoutLMv2Model, set_seed
            >>> from PIL import Image
            >>> import torch
            >>> from datasets import load_dataset
            ...
            >>> set_seed(88)
            ...
            >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
            >>> model = LayoutLMv2Model.from_pretrained("microsoft/layoutlmv2-base-uncased")
            ...
            ...
            >>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
            >>> image_path = dataset["test"][0]["file"]
            >>> image = Image.open(image_path).convert("RGB")
            ...
            >>> encoding = processor(image, return_tensors="pt")
            ...
            >>> outputs = model(**encoding)
            >>> last_hidden_states = outputs.last_hidden_state
            ...
            >>> last_hidden_states.shape
            ops.Size([1, 342, 768])
            ```
        """
        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

        input_shape = self._get_input_shape(input_ids, inputs_embeds)

        visual_shape = list(input_shape)
        visual_shape[1] = self.config.image_feature_pool_shape[0] * self.config.image_feature_pool_shape[1]
        # visual_shape = ops.Size(visual_shape)
        # needs a new copy of input_shape for tracing. Otherwise wrong dimensions will occur
        final_shape = list(self._get_input_shape(input_ids, inputs_embeds))
        final_shape[1] += visual_shape[1]
        # final_shape = ops.Size(final_shape)

        visual_bbox = self._calc_visual_bbox(self.config.image_feature_pool_shape, bbox, final_shape)
        final_bbox = ops.cat([bbox, visual_bbox], axis=1)

        if attention_mask is None:
            attention_mask = ops.ones(input_shape)

        visual_attention_mask = ops.ones(tuple(visual_shape), dtype=mindspore.float32)
        attention_mask = attention_mask.astype(visual_attention_mask.dtype)
        final_attention_mask = ops.cat([attention_mask, visual_attention_mask], axis=1)

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

        if position_ids is None:
            seq_length = input_shape[1]
            position_ids = self.embeddings.position_ids[:, :seq_length]
            position_ids = position_ids.broadcast_to(input_shape)

        visual_position_ids = mindspore.Tensor(np.arange(0, visual_shape[1])).broadcast_to(
            (input_shape[0], visual_shape[1])
        )
        position_ids = position_ids.astype(visual_position_ids.dtype)
        final_position_ids = ops.cat([position_ids, visual_position_ids], axis=1)

        if bbox is None:
            bbox = ops.zeros(tuple(list(input_shape) + [4]), dtype=mindspore.int64)

        text_layout_emb = self._calc_text_embeddings(
            input_ids=input_ids,
            bbox=bbox,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            inputs_embeds=inputs_embeds,
        )

        visual_emb = self._calc_img_embeddings(
            image=image,
            bbox=visual_bbox,
            position_ids=visual_position_ids,
        )
        final_emb = ops.cat([text_layout_emb, visual_emb], axis=1)

        extended_attention_mask = final_attention_mask.unsqueeze(1).unsqueeze(2)

        extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)
        extended_attention_mask = (1.0 - extended_attention_mask) * mindspore.tensor(
            np.finfo(mindspore.dtype_to_nptype(self.dtype)).min)

        if head_mask is not None:
            if head_mask.dim() == 1:
                head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
                head_mask = head_mask.broadcast_to(self.config.num_hidden_layers, -1, -1, -1, -1)
            elif head_mask.dim() == 2:
                head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)
            head_mask_dtype = next(iter(self.parameters_dict().items()))[1].dtype
            head_mask = head_mask.to(dtype=head_mask_dtype)
        else:
            head_mask = [None] * self.config.num_hidden_layers

        encoder_outputs = self.encoder(
            final_emb,
            extended_attention_mask,
            bbox=final_bbox,
            position_ids=final_position_ids,
            head_mask=head_mask,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        sequence_output = encoder_outputs[0]
        pooled_output = self.pooler(sequence_output)

        if not return_dict:
            return (sequence_output, pooled_output) + encoder_outputs[1:]

        return BaseModelOutputWithPooling(
            last_hidden_state=sequence_output,
            pooler_output=pooled_output,
            hidden_states=encoder_outputs.hidden_states,
            attentions=encoder_outputs.attentions,
        )

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Model.__init__(config)

Initializes an instance of the LayoutLMv2Model class.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Model class.

config

A configuration object containing various settings and hyperparameters for the model.

  • Type: dict
  • Purpose: Configure the model with specific settings.
  • Restrictions: Must contain specific keys and values required by the model.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the provided configuration is missing required keys or has invalid values.

TypeError

If the configuration object is not of the expected type.

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

    Args:
        self: The instance of the LayoutLMv2Model class.
        config:
            A configuration object containing various settings and hyperparameters for the model.

            - Type: dict
            - Purpose: Configure the model with specific settings.
            - Restrictions: Must contain specific keys and values required by the model.

    Returns:
        None.

    Raises:
        ValueError: If the provided configuration is missing required keys or has invalid values.
        TypeError: If the configuration object is not of the expected type.
    """
    super().__init__(config)
    self.config = config
    self.has_visual_segment_embedding = config.has_visual_segment_embedding
    self.use_visual_backbone = config.use_visual_backbone
    self.embeddings = LayoutLMv2Embeddings(config)
    if self.use_visual_backbone is True:
        self.visual = LayoutLMv2VisualBackbone(config)
        self.visual_proj = nn.Linear(config.image_feature_pool_shape[-1], config.hidden_size)
    if self.has_visual_segment_embedding:
        self.visual_segment_embedding = Parameter(nn.Embedding(1, config.hidden_size).weight[0])
    self.visual_LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.visual_dropout = nn.Dropout(p=config.hidden_dropout_prob)

    self.encoder = LayoutLMv2Encoder(config)
    self.pooler = LayoutLMv2Pooler(config)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Model.forward(input_ids=None, bbox=None, image=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Return

Union[Tuple, BaseModelOutputWithPooling]

Example
>>> from transformers import AutoProcessor, LayoutLMv2Model, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset
...
>>> set_seed(88)
...
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2Model.from_pretrained("microsoft/layoutlmv2-base-uncased")
...
...
>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")
...
>>> encoding = processor(image, return_tensors="pt")
...
>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state
...
>>> last_hidden_states.shape
ops.Size([1, 342, 768])
Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        bbox: Optional[mindspore.Tensor] = None,
        image: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        position_ids: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
    r"""
    Return:
        Union[Tuple, BaseModelOutputWithPooling]

    Example:
        ```python
        >>> from transformers import AutoProcessor, LayoutLMv2Model, set_seed
        >>> from PIL import Image
        >>> import torch
        >>> from datasets import load_dataset
        ...
        >>> set_seed(88)
        ...
        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
        >>> model = LayoutLMv2Model.from_pretrained("microsoft/layoutlmv2-base-uncased")
        ...
        ...
        >>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
        >>> image_path = dataset["test"][0]["file"]
        >>> image = Image.open(image_path).convert("RGB")
        ...
        >>> encoding = processor(image, return_tensors="pt")
        ...
        >>> outputs = model(**encoding)
        >>> last_hidden_states = outputs.last_hidden_state
        ...
        >>> last_hidden_states.shape
        ops.Size([1, 342, 768])
        ```
    """
    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

    input_shape = self._get_input_shape(input_ids, inputs_embeds)

    visual_shape = list(input_shape)
    visual_shape[1] = self.config.image_feature_pool_shape[0] * self.config.image_feature_pool_shape[1]
    # visual_shape = ops.Size(visual_shape)
    # needs a new copy of input_shape for tracing. Otherwise wrong dimensions will occur
    final_shape = list(self._get_input_shape(input_ids, inputs_embeds))
    final_shape[1] += visual_shape[1]
    # final_shape = ops.Size(final_shape)

    visual_bbox = self._calc_visual_bbox(self.config.image_feature_pool_shape, bbox, final_shape)
    final_bbox = ops.cat([bbox, visual_bbox], axis=1)

    if attention_mask is None:
        attention_mask = ops.ones(input_shape)

    visual_attention_mask = ops.ones(tuple(visual_shape), dtype=mindspore.float32)
    attention_mask = attention_mask.astype(visual_attention_mask.dtype)
    final_attention_mask = ops.cat([attention_mask, visual_attention_mask], axis=1)

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

    if position_ids is None:
        seq_length = input_shape[1]
        position_ids = self.embeddings.position_ids[:, :seq_length]
        position_ids = position_ids.broadcast_to(input_shape)

    visual_position_ids = mindspore.Tensor(np.arange(0, visual_shape[1])).broadcast_to(
        (input_shape[0], visual_shape[1])
    )
    position_ids = position_ids.astype(visual_position_ids.dtype)
    final_position_ids = ops.cat([position_ids, visual_position_ids], axis=1)

    if bbox is None:
        bbox = ops.zeros(tuple(list(input_shape) + [4]), dtype=mindspore.int64)

    text_layout_emb = self._calc_text_embeddings(
        input_ids=input_ids,
        bbox=bbox,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        inputs_embeds=inputs_embeds,
    )

    visual_emb = self._calc_img_embeddings(
        image=image,
        bbox=visual_bbox,
        position_ids=visual_position_ids,
    )
    final_emb = ops.cat([text_layout_emb, visual_emb], axis=1)

    extended_attention_mask = final_attention_mask.unsqueeze(1).unsqueeze(2)

    extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)
    extended_attention_mask = (1.0 - extended_attention_mask) * mindspore.tensor(
        np.finfo(mindspore.dtype_to_nptype(self.dtype)).min)

    if head_mask is not None:
        if head_mask.dim() == 1:
            head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
            head_mask = head_mask.broadcast_to(self.config.num_hidden_layers, -1, -1, -1, -1)
        elif head_mask.dim() == 2:
            head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)
        head_mask_dtype = next(iter(self.parameters_dict().items()))[1].dtype
        head_mask = head_mask.to(dtype=head_mask_dtype)
    else:
        head_mask = [None] * self.config.num_hidden_layers

    encoder_outputs = self.encoder(
        final_emb,
        extended_attention_mask,
        bbox=final_bbox,
        position_ids=final_position_ids,
        head_mask=head_mask,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    sequence_output = encoder_outputs[0]
    pooled_output = self.pooler(sequence_output)

    if not return_dict:
        return (sequence_output, pooled_output) + encoder_outputs[1:]

    return BaseModelOutputWithPooling(
        last_hidden_state=sequence_output,
        pooler_output=pooled_output,
        hidden_states=encoder_outputs.hidden_states,
        attentions=encoder_outputs.attentions,
    )

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Model.get_input_embeddings()

This method returns the input embeddings of the LayoutLMv2Model.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Model class.

RETURNS DESCRIPTION
None

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

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def get_input_embeddings(self):
    """
    This method returns the input embeddings of the LayoutLMv2Model.

    Args:
        self: The instance of the LayoutLMv2Model class.

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

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Model.set_input_embeddings(value)

Sets the input embeddings for the LayoutLMv2Model.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Model class.

TYPE: LayoutLMv2Model

value

The input embeddings to be set. It should be a tensor or any object that can be assigned to the word_embeddings attribute of the embeddings object.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
def set_input_embeddings(self, value):
    """
    Sets the input embeddings for the LayoutLMv2Model.

    Args:
        self (LayoutLMv2Model): An instance of the LayoutLMv2Model class.
        value: The input embeddings to be set. It should be a tensor or any object that can be assigned to
            the word_embeddings attribute of the embeddings object.

    Returns:
        None.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Output

Bases: Module

LayoutLMv2Output is the output layer for LayoutLMv2Intermediate. It is based on the implementation of BertOutput.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2Output(nn.Module):
    """
    LayoutLMv2Output is the output layer for LayoutLMv2Intermediate. It is based on the implementation of BertOutput.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the LayoutLMv2Output class.

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

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of the expected type.
            ValueError: If the config parameters do not meet the required constraints.
            RuntimeError: If an error occurs during the initialization process.
        """
        super().__init__()
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def forward(self, hidden_states: mindspore.Tensor, input_tensor: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs the LayoutLMv2Output for the given hidden states and input tensor.

        Args:
            self (LayoutLMv2Output): An instance of the LayoutLMv2Output class.
            hidden_states (mindspore.Tensor): A tensor representing the hidden states.
                This tensor is expected to have a shape of (batch_size, sequence_length, hidden_size).
            input_tensor (mindspore.Tensor): A tensor representing the input.
                This tensor is expected to have the same shape as the hidden states.

        Returns:
            mindspore.Tensor: A tensor representing the forwarded LayoutLMv2Output.
                This tensor has the same shape as the hidden states.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Output.__init__(config)

Initializes a new instance of the LayoutLMv2Output class.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Output class.

config

An object containing configuration parameters for the LayoutLMv2Output model.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of the expected type.

ValueError

If the config parameters do not meet the required constraints.

RuntimeError

If an error occurs during the initialization process.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
def __init__(self, config):
    """
    Initializes a new instance of the LayoutLMv2Output class.

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

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of the expected type.
        ValueError: If the config parameters do not meet the required constraints.
        RuntimeError: If an error occurs during the initialization process.
    """
    super().__init__()
    self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
    self.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Output.forward(hidden_states, input_tensor)

Constructs the LayoutLMv2Output for the given hidden states and input tensor.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Output class.

TYPE: LayoutLMv2Output

hidden_states

A tensor representing the hidden states. This tensor is expected to have a shape of (batch_size, sequence_length, hidden_size).

TYPE: Tensor

input_tensor

A tensor representing the input. This tensor is expected to have the same shape as the hidden states.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: A tensor representing the forwarded LayoutLMv2Output. This tensor has the same shape as the hidden states.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def forward(self, hidden_states: mindspore.Tensor, input_tensor: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs the LayoutLMv2Output for the given hidden states and input tensor.

    Args:
        self (LayoutLMv2Output): An instance of the LayoutLMv2Output class.
        hidden_states (mindspore.Tensor): A tensor representing the hidden states.
            This tensor is expected to have a shape of (batch_size, sequence_length, hidden_size).
        input_tensor (mindspore.Tensor): A tensor representing the input.
            This tensor is expected to have the same shape as the hidden states.

    Returns:
        mindspore.Tensor: A tensor representing the forwarded LayoutLMv2Output.
            This tensor has the same shape as the hidden states.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Pooler

Bases: Module

LayoutLMv2Pooler is a simple feedforward network. It is based on the implementation of BertPooler.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2Pooler(nn.Module):
    """
    LayoutLMv2Pooler is a simple feedforward network. It is based on the implementation of BertPooler.
    """
    def __init__(self, config):
        """
        Initializes a new instance of the LayoutLMv2Pooler class.

        Args:
            self (LayoutLMv2Pooler): The current instance of the LayoutLMv2Pooler class.
            config: The configuration object specifying the settings for the LayoutLMv2Pooler.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.activation = nn.Tanh()

    def forward(self, hidden_states):
        """
        Constructs the pooled output tensor for the LayoutLMv2Pooler class.

        Args:
            self: An instance of the LayoutLMv2Pooler class.
            hidden_states (torch.Tensor): A tensor of shape (batch_size, sequence_length, hidden_size)
                representing the hidden states of the input sequence.

        Returns:
            torch.Tensor: A tensor of shape (batch_size, hidden_size) representing the pooled output.

        Raises:
            None.

        This method takes the hidden states of the input sequence and applies pooling to obtain a
        pooled output tensor. It first selects the first token tensor from the hidden states tensor
        using slicing, and then passes it through a dense layer. The resulting tensor is then
        activated using the specified activation function. Finally, the pooled output tensor is
        returned.
        """
        # 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.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Pooler.__init__(config)

Initializes a new instance of the LayoutLMv2Pooler class.

PARAMETER DESCRIPTION
self

The current instance of the LayoutLMv2Pooler class.

TYPE: LayoutLMv2Pooler

config

The configuration object specifying the settings for the LayoutLMv2Pooler.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
def __init__(self, config):
    """
    Initializes a new instance of the LayoutLMv2Pooler class.

    Args:
        self (LayoutLMv2Pooler): The current instance of the LayoutLMv2Pooler class.
        config: The configuration object specifying the settings for the LayoutLMv2Pooler.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.dense = nn.Linear(config.hidden_size, config.hidden_size)
    self.activation = nn.Tanh()

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2Pooler.forward(hidden_states)

Constructs the pooled output tensor for the LayoutLMv2Pooler class.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Pooler class.

hidden_states

A tensor of shape (batch_size, sequence_length, hidden_size) representing the hidden states of the input sequence.

TYPE: Tensor

RETURNS DESCRIPTION

torch.Tensor: A tensor of shape (batch_size, hidden_size) representing the pooled output.

This method takes the hidden states of the input sequence and applies pooling to obtain a pooled output tensor. It first selects the first token tensor from the hidden states tensor using slicing, and then passes it through a dense layer. The resulting tensor is then activated using the specified activation function. Finally, the pooled output tensor is returned.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(self, hidden_states):
    """
    Constructs the pooled output tensor for the LayoutLMv2Pooler class.

    Args:
        self: An instance of the LayoutLMv2Pooler class.
        hidden_states (torch.Tensor): A tensor of shape (batch_size, sequence_length, hidden_size)
            representing the hidden states of the input sequence.

    Returns:
        torch.Tensor: A tensor of shape (batch_size, hidden_size) representing the pooled output.

    Raises:
        None.

    This method takes the hidden states of the input sequence and applies pooling to obtain a
    pooled output tensor. It first selects the first token tensor from the hidden states tensor
    using slicing, and then passes it through a dense layer. The resulting tensor is then
    activated using the specified activation function. Finally, the pooled output tensor is
    returned.
    """
    # 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.layoutlmv2.modeling_layoutlmv2.LayoutLMv2PreTrainedModel

Bases: PreTrainedModel

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

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2PreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    _keys_to_ignore_on_load_unexpected = ['num_batches_tracked']
    config_class = LayoutLMv2Config
    pretrained_model_archive_map = LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST
    base_model_prefix = "layoutlmv2"

    def _init_weights(self, cell):
        """Initialize the weights"""
        if isinstance(cell, nn.Linear):
            cell.weight.set_data(initializer(Normal(sigma=self.config.initializer_range),
                                             cell.weight.shape, cell.weight.dtype))
            if cell.bias:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.Embedding):
            weight = np.random.normal(0.0, self.config.initializer_range, cell.weight.shape)
            if cell.padding_idx is not None:
                weight[cell.padding_idx] = 0
            cell.weight.set_data(Tensor(weight, dtype=cell.weight.dtype))
        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.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfAttention

Bases: Module

LayoutLMv2SelfAttention is the self-attention layer for LayoutLMv2. It is based on the implementation of

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
class LayoutLMv2SelfAttention(nn.Module):
    """
    LayoutLMv2SelfAttention is the self-attention layer for LayoutLMv2. It is based on the implementation of
    """
    def __init__(self, config):
        """
        Initializes the LayoutLMv2SelfAttention class.

        Args:
            self (LayoutLMv2SelfAttention): An instance of the LayoutLMv2SelfAttention class.
            config (object): The configuration object that contains the settings for the self-attention layer.

        Returns:
            None.

        Raises:
            ValueError: If the hidden size is not a multiple of the number of attention heads and the configuration
                object does not have an 'embedding_size' attribute.

        This method initializes the LayoutLMv2SelfAttention class by setting the necessary attributes and layers.
        It checks if the hidden size is divisible by the number of attention heads and raises a ValueError if not.
        The method also determines if the fast_qkv (fast query, key, value) method should be used based on the configuration.
        If fast_qkv is enabled, it creates a dense layer for the query, key, and value (qkv_linear), along with biases
        (q_bias and v_bias). Otherwise, it creates separate dense layers for query, key, and value. Finally, it sets the
        dropout layer based on the configuration's attention_probs_dropout_prob value.
        """
        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.fast_qkv = config.fast_qkv
        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.has_relative_attention_bias = config.has_relative_attention_bias
        self.has_spatial_attention_bias = config.has_spatial_attention_bias

        if config.fast_qkv:
            self.qkv_linear = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=False)
            self.q_bias = Parameter(initializer(Constant(0.0), [1, 1, self.all_head_size], mindspore.float32))
            self.v_bias = Parameter(initializer(Constant(0.0), [1, 1, self.all_head_size], mindspore.float32))
        else:
            self.query = nn.Linear(config.hidden_size, self.all_head_size)
            self.key = nn.Linear(config.hidden_size, self.all_head_size)
            self.value = nn.Linear(config.hidden_size, self.all_head_size)

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

    def transpose_for_scores(self, x):
        """
        Args:
            self (LayoutLMv2SelfAttention): The instance of the LayoutLMv2SelfAttention class.
            x (tensor): The input tensor to be transposed for attention scores calculation.

        Returns:
            tensor: The transposed tensor for attention scores calculation. 
                It has the shape (batch_size, num_attention_heads, sequence_length, attention_head_size).

        Raises:
            None
        """
        new_x_shape = x.shape[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = x.view(*new_x_shape)
        return x.permute(0, 2, 1, 3)

    def compute_qkv(self, hidden_states):
        """
        This method computes the query, key, and value tensors for LayoutLMv2 self-attention mechanism.

        Args:
            self (LayoutLMv2SelfAttention): The instance of LayoutLMv2SelfAttention class.
            hidden_states (tensor): The input tensor representing the hidden states.

        Returns:
            (tuple): A tuple containing the query (q), key (k), and value (v) tensors.

        Raises:
            ValueError: If the dimensions of the query (q) tensor and the q_bias tensor do not match.
            ValueError: If the dimensions of the value (v) tensor and the v_bias tensor do not match.
        """
        if self.fast_qkv:
            qkv = self.qkv_linear(hidden_states)
            q, k, v = ops.chunk(qkv, 3, axis=-1)
            if q.ndimension() == self.q_bias.ndimension():
                q = q + self.q_bias
                v = v + self.v_bias
            else:
                _sz = (1,) * (q.ndimension() - 1) + (-1,)
                q = q + self.q_bias.view(*_sz)
                v = v + self.v_bias.view(*_sz)
        else:
            q = self.query(hidden_states)
            k = self.key(hidden_states)
            v = self.value(hidden_states)
        return q, k, v

    def forward(
            self,
            hidden_states,
            attention_mask=None,
            head_mask=None,
            output_attentions=False,
            rel_pos=None,
            rel_2d_pos=None,
    ):
        """
        Constructs the self-attention mechanism for the LayoutLMv2 model.

        Args:
            self (LayoutLMv2SelfAttention): The instance of the LayoutLMv2SelfAttention class.
            hidden_states (Tensor): The input hidden states with shape (batch_size, sequence_length, hidden_size).
            attention_mask (Tensor, optional): The attention mask with shape (batch_size, sequence_length). 
                It is a binary mask where 1's indicate the positions to attend and 0's indicate the positions to
                ignore. Defaults to None.
            head_mask (Tensor, optional): The head mask with shape (num_heads,) or (num_layers, num_heads). 
                It masks the attention weights of specific heads. Defaults to None.
            output_attentions (bool, optional): Whether to output the attention probabilities. Defaults to False.
            rel_pos (Tensor, optional): The relative position bias with shape 
                (num_heads, sequence_length, sequence_length). It contains relative position information between 
                each token pair. Defaults to None.
            rel_2d_pos (Tensor, optional): The relative 2D position bias with shape 
                (num_heads, sequence_length, sequence_length). It contains relative 2D position information 
                between each token pair. Defaults to None.

        Returns:
            tuple: A tuple containing the context layer and attention probabilities 
                if output_attentions is True, otherwise only the context layer.

                - context_layer (Tensor): The output context layer with shape (batch_size, sequence_length, hidden_size).
                - attention_probs (Tensor, optional): The attention probabilities with shape 
                (batch_size, num_heads, sequence_length, sequence_length) if output_attentions is True.

        Raises:
            None
        """
        q, k, v = self.compute_qkv(hidden_states)

        # (B, L, H*D) -> (B, H, L, D)
        query_layer = self.transpose_for_scores(q)
        key_layer = self.transpose_for_scores(k)
        value_layer = self.transpose_for_scores(v)

        query_layer = query_layer / math.sqrt(self.attention_head_size)
        # [BSZ, NAT, L, L]
        attention_scores = ops.matmul(query_layer, key_layer.swapaxes(-1, -2))
        if self.has_relative_attention_bias:
            attention_scores += rel_pos
        if self.has_spatial_attention_bias:
            attention_scores += rel_2d_pos
        attention_scores = ops.masked_fill(
            attention_scores.astype(mindspore.float32), ops.stop_gradient(attention_mask.astype(mindspore.bool_)),
            float("-1e10")
        )
        attention_probs = ops.softmax(attention_scores, axis=-1, dtype=mindspore.float32).type_as(value_layer)
        # 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)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfAttention.__init__(config)

Initializes the LayoutLMv2SelfAttention class.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2SelfAttention class.

TYPE: LayoutLMv2SelfAttention

config

The configuration object that contains the settings for the self-attention layer.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the hidden size is not a multiple of the number of attention heads and the configuration object does not have an 'embedding_size' attribute.

This method initializes the LayoutLMv2SelfAttention class by setting the necessary attributes and layers. It checks if the hidden size is divisible by the number of attention heads and raises a ValueError if not. The method also determines if the fast_qkv (fast query, key, value) method should be used based on the configuration. If fast_qkv is enabled, it creates a dense layer for the query, key, and value (qkv_linear), along with biases (q_bias and v_bias). Otherwise, it creates separate dense layers for query, key, and value. Finally, it sets the dropout layer based on the configuration's attention_probs_dropout_prob value.

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

    Args:
        self (LayoutLMv2SelfAttention): An instance of the LayoutLMv2SelfAttention class.
        config (object): The configuration object that contains the settings for the self-attention layer.

    Returns:
        None.

    Raises:
        ValueError: If the hidden size is not a multiple of the number of attention heads and the configuration
            object does not have an 'embedding_size' attribute.

    This method initializes the LayoutLMv2SelfAttention class by setting the necessary attributes and layers.
    It checks if the hidden size is divisible by the number of attention heads and raises a ValueError if not.
    The method also determines if the fast_qkv (fast query, key, value) method should be used based on the configuration.
    If fast_qkv is enabled, it creates a dense layer for the query, key, and value (qkv_linear), along with biases
    (q_bias and v_bias). Otherwise, it creates separate dense layers for query, key, and value. Finally, it sets the
    dropout layer based on the configuration's attention_probs_dropout_prob value.
    """
    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.fast_qkv = config.fast_qkv
    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.has_relative_attention_bias = config.has_relative_attention_bias
    self.has_spatial_attention_bias = config.has_spatial_attention_bias

    if config.fast_qkv:
        self.qkv_linear = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=False)
        self.q_bias = Parameter(initializer(Constant(0.0), [1, 1, self.all_head_size], mindspore.float32))
        self.v_bias = Parameter(initializer(Constant(0.0), [1, 1, self.all_head_size], mindspore.float32))
    else:
        self.query = nn.Linear(config.hidden_size, self.all_head_size)
        self.key = nn.Linear(config.hidden_size, self.all_head_size)
        self.value = nn.Linear(config.hidden_size, self.all_head_size)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfAttention.compute_qkv(hidden_states)

This method computes the query, key, and value tensors for LayoutLMv2 self-attention mechanism.

PARAMETER DESCRIPTION
self

The instance of LayoutLMv2SelfAttention class.

TYPE: LayoutLMv2SelfAttention

hidden_states

The input tensor representing the hidden states.

TYPE: tensor

RETURNS DESCRIPTION
tuple

A tuple containing the query (q), key (k), and value (v) tensors.

RAISES DESCRIPTION
ValueError

If the dimensions of the query (q) tensor and the q_bias tensor do not match.

ValueError

If the dimensions of the value (v) tensor and the v_bias tensor do not match.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def compute_qkv(self, hidden_states):
    """
    This method computes the query, key, and value tensors for LayoutLMv2 self-attention mechanism.

    Args:
        self (LayoutLMv2SelfAttention): The instance of LayoutLMv2SelfAttention class.
        hidden_states (tensor): The input tensor representing the hidden states.

    Returns:
        (tuple): A tuple containing the query (q), key (k), and value (v) tensors.

    Raises:
        ValueError: If the dimensions of the query (q) tensor and the q_bias tensor do not match.
        ValueError: If the dimensions of the value (v) tensor and the v_bias tensor do not match.
    """
    if self.fast_qkv:
        qkv = self.qkv_linear(hidden_states)
        q, k, v = ops.chunk(qkv, 3, axis=-1)
        if q.ndimension() == self.q_bias.ndimension():
            q = q + self.q_bias
            v = v + self.v_bias
        else:
            _sz = (1,) * (q.ndimension() - 1) + (-1,)
            q = q + self.q_bias.view(*_sz)
            v = v + self.v_bias.view(*_sz)
    else:
        q = self.query(hidden_states)
        k = self.key(hidden_states)
        v = self.value(hidden_states)
    return q, k, v

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfAttention.forward(hidden_states, attention_mask=None, head_mask=None, output_attentions=False, rel_pos=None, rel_2d_pos=None)

Constructs the self-attention mechanism for the LayoutLMv2 model.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2SelfAttention class.

TYPE: LayoutLMv2SelfAttention

hidden_states

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

TYPE: Tensor

attention_mask

The attention mask with shape (batch_size, sequence_length). It is a binary mask where 1's indicate the positions to attend and 0's indicate the positions to ignore. Defaults to None.

TYPE: Tensor DEFAULT: None

head_mask

The head mask with shape (num_heads,) or (num_layers, num_heads). It masks the attention weights of specific heads. Defaults to None.

TYPE: Tensor DEFAULT: None

output_attentions

Whether to output the attention probabilities. Defaults to False.

TYPE: bool DEFAULT: False

rel_pos

The relative position bias with shape (num_heads, sequence_length, sequence_length). It contains relative position information between each token pair. Defaults to None.

TYPE: Tensor DEFAULT: None

rel_2d_pos

The relative 2D position bias with shape (num_heads, sequence_length, sequence_length). It contains relative 2D position information between each token pair. Defaults to None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
tuple

A tuple containing the context layer and attention probabilities if output_attentions is True, otherwise only the context layer.

  • context_layer (Tensor): The output context layer with shape (batch_size, sequence_length, hidden_size).
  • attention_probs (Tensor, optional): The attention probabilities with shape (batch_size, num_heads, sequence_length, sequence_length) if output_attentions is True.
Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def forward(
        self,
        hidden_states,
        attention_mask=None,
        head_mask=None,
        output_attentions=False,
        rel_pos=None,
        rel_2d_pos=None,
):
    """
    Constructs the self-attention mechanism for the LayoutLMv2 model.

    Args:
        self (LayoutLMv2SelfAttention): The instance of the LayoutLMv2SelfAttention class.
        hidden_states (Tensor): The input hidden states with shape (batch_size, sequence_length, hidden_size).
        attention_mask (Tensor, optional): The attention mask with shape (batch_size, sequence_length). 
            It is a binary mask where 1's indicate the positions to attend and 0's indicate the positions to
            ignore. Defaults to None.
        head_mask (Tensor, optional): The head mask with shape (num_heads,) or (num_layers, num_heads). 
            It masks the attention weights of specific heads. Defaults to None.
        output_attentions (bool, optional): Whether to output the attention probabilities. Defaults to False.
        rel_pos (Tensor, optional): The relative position bias with shape 
            (num_heads, sequence_length, sequence_length). It contains relative position information between 
            each token pair. Defaults to None.
        rel_2d_pos (Tensor, optional): The relative 2D position bias with shape 
            (num_heads, sequence_length, sequence_length). It contains relative 2D position information 
            between each token pair. Defaults to None.

    Returns:
        tuple: A tuple containing the context layer and attention probabilities 
            if output_attentions is True, otherwise only the context layer.

            - context_layer (Tensor): The output context layer with shape (batch_size, sequence_length, hidden_size).
            - attention_probs (Tensor, optional): The attention probabilities with shape 
            (batch_size, num_heads, sequence_length, sequence_length) if output_attentions is True.

    Raises:
        None
    """
    q, k, v = self.compute_qkv(hidden_states)

    # (B, L, H*D) -> (B, H, L, D)
    query_layer = self.transpose_for_scores(q)
    key_layer = self.transpose_for_scores(k)
    value_layer = self.transpose_for_scores(v)

    query_layer = query_layer / math.sqrt(self.attention_head_size)
    # [BSZ, NAT, L, L]
    attention_scores = ops.matmul(query_layer, key_layer.swapaxes(-1, -2))
    if self.has_relative_attention_bias:
        attention_scores += rel_pos
    if self.has_spatial_attention_bias:
        attention_scores += rel_2d_pos
    attention_scores = ops.masked_fill(
        attention_scores.astype(mindspore.float32), ops.stop_gradient(attention_mask.astype(mindspore.bool_)),
        float("-1e10")
    )
    attention_probs = ops.softmax(attention_scores, axis=-1, dtype=mindspore.float32).type_as(value_layer)
    # 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)

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfAttention.transpose_for_scores(x)

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2SelfAttention class.

TYPE: LayoutLMv2SelfAttention

x

The input tensor to be transposed for attention scores calculation.

TYPE: tensor

RETURNS DESCRIPTION
tensor

The transposed tensor for attention scores calculation. It has the shape (batch_size, num_attention_heads, sequence_length, attention_head_size).

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def transpose_for_scores(self, x):
    """
    Args:
        self (LayoutLMv2SelfAttention): The instance of the LayoutLMv2SelfAttention class.
        x (tensor): The input tensor to be transposed for attention scores calculation.

    Returns:
        tensor: The transposed tensor for attention scores calculation. 
            It has the shape (batch_size, num_attention_heads, sequence_length, attention_head_size).

    Raises:
        None
    """
    new_x_shape = x.shape[:-1] + (self.num_attention_heads, self.attention_head_size)
    x = x.view(*new_x_shape)
    return x.permute(0, 2, 1, 3)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfOutput

Bases: Module

LayoutLMv2SelfOutput is the output layer for LayoutLMv2Attention. It is based on the implementation of BertSelfOutput.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
class LayoutLMv2SelfOutput(nn.Module):
    """
    LayoutLMv2SelfOutput is the output layer for LayoutLMv2Attention. It is based on the implementation of BertSelfOutput.
    """
    def __init__(self, config):
        """
        Initializes the LayoutLMv2SelfOutput class.

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

                - hidden_size (int): The size of the hidden state.
                - layer_norm_eps (float): The epsilon value for LayerNorm.
                - 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.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

    def forward(self, hidden_states, input_tensor):
        """
        Constructs the self-attention output of the LayoutLMv2 transformer model.

        Args:
            self (LayoutLMv2SelfOutput): An instance of the LayoutLMv2SelfOutput class.
            hidden_states (torch.Tensor): The input hidden states tensor of shape (batch_size, sequence_length, hidden_size).
                These are the intermediate outputs of the self-attention layer.
            input_tensor (torch.Tensor): The input tensor of shape (batch_size, sequence_length, hidden_size).
                This tensor represents the input embeddings to the self-attention layer.

        Returns:
            torch.Tensor: The output tensor of shape (batch_size, sequence_length, hidden_size).
                This tensor represents the forwarded self-attention output.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfOutput.__init__(config)

Initializes the LayoutLMv2SelfOutput 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 state.
  • layer_norm_eps (float): The epsilon value for LayerNorm.
  • hidden_dropout_prob (float): The dropout probability for hidden layers.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def __init__(self, config):
    """
    Initializes the LayoutLMv2SelfOutput class.

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

            - hidden_size (int): The size of the hidden state.
            - layer_norm_eps (float): The epsilon value for LayerNorm.
            - 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.LayerNorm = nn.LayerNorm([config.hidden_size], eps=config.layer_norm_eps)
    self.dropout = nn.Dropout(p=config.hidden_dropout_prob)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2SelfOutput.forward(hidden_states, input_tensor)

Constructs the self-attention output of the LayoutLMv2 transformer model.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2SelfOutput class.

TYPE: LayoutLMv2SelfOutput

hidden_states

The input hidden states tensor of shape (batch_size, sequence_length, hidden_size). These are the intermediate outputs of the self-attention layer.

TYPE: Tensor

input_tensor

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

TYPE: Tensor

RETURNS DESCRIPTION

torch.Tensor: The output tensor of shape (batch_size, sequence_length, hidden_size). This tensor represents the forwarded self-attention output.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def forward(self, hidden_states, input_tensor):
    """
    Constructs the self-attention output of the LayoutLMv2 transformer model.

    Args:
        self (LayoutLMv2SelfOutput): An instance of the LayoutLMv2SelfOutput class.
        hidden_states (torch.Tensor): The input hidden states tensor of shape (batch_size, sequence_length, hidden_size).
            These are the intermediate outputs of the self-attention layer.
        input_tensor (torch.Tensor): The input tensor of shape (batch_size, sequence_length, hidden_size).
            This tensor represents the input embeddings to the self-attention layer.

    Returns:
        torch.Tensor: The output tensor of shape (batch_size, sequence_length, hidden_size).
            This tensor represents the forwarded self-attention output.

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

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2VisualBackbone

Bases: Module

LayoutLMv2VisualBackbone is a visual backbone for LayoutLMv2. It is based on the implementation of VisualBackboneBase.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
 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
class LayoutLMv2VisualBackbone(nn.Module):
    """
    LayoutLMv2VisualBackbone is a visual backbone for LayoutLMv2. It is based on the implementation of VisualBackboneBase.
    """
    def __init__(self, config):
        """
        Initializes an instance of the LayoutLMv2VisualBackbone class.

        Args:
            self: The instance of the class itself.
            config: An object that contains configuration parameters.

        Returns:
            None.

        Raises:
            ValueError: If the lengths of the pixel mean and pixel standard deviation in the configuration are not equal.
        """
        super(LayoutLMv2VisualBackbone, self).__init__()
        self.cfg = config.get_detectron2_config()
        self.backbone = build_resnet_fpn_backbone(self.cfg)

        if len(self.cfg.MODEL.PIXEL_MEAN) != len(self.cfg.MODEL.PIXEL_STD):
            raise ValueError(
                "cfg.model.pixel_mean is not equal with cfg.model.pixel_std."
            )
        num_channels = len(self.cfg.MODEL.PIXEL_MEAN)

        self.pixel_mean = Parameter(
            mindspore.Tensor(self.cfg.MODEL.PIXEL_MEAN).reshape((num_channels, 1, 1)),
            name="pixel_mean",
            requires_grad=False,
        )
        self.pixel_std = Parameter(
            mindspore.Tensor(self.cfg.MODEL.PIXEL_STD).reshape((num_channels, 1, 1)),
            name="pixel_std",
            requires_grad=False,
        )

        self.out_feature_key = "p2"
        self.pool_shape = tuple(config.image_feature_pool_shape[:2])  # (7,7)
        if len(config.image_feature_pool_shape) == 2:
            config.image_feature_pool_shape.append(
                self.backbone.output_shape()[self.out_feature_key].channels
            )

        input_shape = (224, 224)
        outsize = config.image_feature_pool_shape[0]  # (7,7)
        insize = (input_shape[0] + 4 - 1) // 4
        shape_info = self.backbone.output_shape()[self.out_feature_key]
        channels = shape_info.channels
        stride = insize // outsize
        kernel = insize - (outsize - 1) * stride

        self.weight = mindspore.Tensor(np.ones([channels, 1, kernel, kernel]), dtype=mindspore.float32) / (
                kernel * kernel)
        self.conv2d = ops.Conv2D(channels, kernel, stride=stride, group=channels)

    def pool(self, features):
        """
        To enhance performance, customize the AdaptiveAvgPool2d layer
        """
        features = self.conv2d(features, self.weight)
        return features

    def freeze(self):
        """
        Freeze parameters
        """
        for param in self.trainable_params():
            param.requires_grad = False

    def forward(self, images):
        """
        This method 'forward' is defined within the class 'LayoutLMv2VisualBackbone'
        and is responsible for processing images through the visual backbone network.

        Args:
            self:
                An instance of the 'LayoutLMv2VisualBackbone' class.

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

            images:
                The input images to be processed by the visual backbone.

                - Type: N-dimensional array
                - Purpose: Represents the input images for processing.
                - Restrictions: Must be compatible with the model input size.

        Returns:
            features:
                The processed features of the input images after passing through the visual backbone network.

                - Type: Numpy array
                - Purpose: Represents the extracted features from the input images.

        Raises:
            None.
        """
        images_input = (images - self.pixel_mean) / self.pixel_std
        features = self.backbone(images_input)
        for item in features:
            if item[0] == self.out_feature_key:
                features = item[1]
        features = self.pool(features)
        return features.flatten(start_dim=2).transpose(0, 2, 1)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2VisualBackbone.__init__(config)

Initializes an instance of the LayoutLMv2VisualBackbone class.

PARAMETER DESCRIPTION
self

The instance of the class itself.

config

An object that contains configuration parameters.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the lengths of the pixel mean and pixel standard deviation in the configuration are not equal.

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

    Args:
        self: The instance of the class itself.
        config: An object that contains configuration parameters.

    Returns:
        None.

    Raises:
        ValueError: If the lengths of the pixel mean and pixel standard deviation in the configuration are not equal.
    """
    super(LayoutLMv2VisualBackbone, self).__init__()
    self.cfg = config.get_detectron2_config()
    self.backbone = build_resnet_fpn_backbone(self.cfg)

    if len(self.cfg.MODEL.PIXEL_MEAN) != len(self.cfg.MODEL.PIXEL_STD):
        raise ValueError(
            "cfg.model.pixel_mean is not equal with cfg.model.pixel_std."
        )
    num_channels = len(self.cfg.MODEL.PIXEL_MEAN)

    self.pixel_mean = Parameter(
        mindspore.Tensor(self.cfg.MODEL.PIXEL_MEAN).reshape((num_channels, 1, 1)),
        name="pixel_mean",
        requires_grad=False,
    )
    self.pixel_std = Parameter(
        mindspore.Tensor(self.cfg.MODEL.PIXEL_STD).reshape((num_channels, 1, 1)),
        name="pixel_std",
        requires_grad=False,
    )

    self.out_feature_key = "p2"
    self.pool_shape = tuple(config.image_feature_pool_shape[:2])  # (7,7)
    if len(config.image_feature_pool_shape) == 2:
        config.image_feature_pool_shape.append(
            self.backbone.output_shape()[self.out_feature_key].channels
        )

    input_shape = (224, 224)
    outsize = config.image_feature_pool_shape[0]  # (7,7)
    insize = (input_shape[0] + 4 - 1) // 4
    shape_info = self.backbone.output_shape()[self.out_feature_key]
    channels = shape_info.channels
    stride = insize // outsize
    kernel = insize - (outsize - 1) * stride

    self.weight = mindspore.Tensor(np.ones([channels, 1, kernel, kernel]), dtype=mindspore.float32) / (
            kernel * kernel)
    self.conv2d = ops.Conv2D(channels, kernel, stride=stride, group=channels)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2VisualBackbone.forward(images)

This method 'forward' is defined within the class 'LayoutLMv2VisualBackbone' and is responsible for processing images through the visual backbone network.

PARAMETER DESCRIPTION
self

An instance of the 'LayoutLMv2VisualBackbone' class.

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

images

The input images to be processed by the visual backbone.

  • Type: N-dimensional array
  • Purpose: Represents the input images for processing.
  • Restrictions: Must be compatible with the model input size.

RETURNS DESCRIPTION
features

The processed features of the input images after passing through the visual backbone network.

  • Type: Numpy array
  • Purpose: Represents the extracted features from the input images.
Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
 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
def forward(self, images):
    """
    This method 'forward' is defined within the class 'LayoutLMv2VisualBackbone'
    and is responsible for processing images through the visual backbone network.

    Args:
        self:
            An instance of the 'LayoutLMv2VisualBackbone' class.

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

        images:
            The input images to be processed by the visual backbone.

            - Type: N-dimensional array
            - Purpose: Represents the input images for processing.
            - Restrictions: Must be compatible with the model input size.

    Returns:
        features:
            The processed features of the input images after passing through the visual backbone network.

            - Type: Numpy array
            - Purpose: Represents the extracted features from the input images.

    Raises:
        None.
    """
    images_input = (images - self.pixel_mean) / self.pixel_std
    features = self.backbone(images_input)
    for item in features:
        if item[0] == self.out_feature_key:
            features = item[1]
    features = self.pool(features)
    return features.flatten(start_dim=2).transpose(0, 2, 1)

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2VisualBackbone.freeze()

Freeze parameters

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
973
974
975
976
977
978
def freeze(self):
    """
    Freeze parameters
    """
    for param in self.trainable_params():
        param.requires_grad = False

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.LayoutLMv2VisualBackbone.pool(features)

To enhance performance, customize the AdaptiveAvgPool2d layer

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
966
967
968
969
970
971
def pool(self, features):
    """
    To enhance performance, customize the AdaptiveAvgPool2d layer
    """
    features = self.conv2d(features, self.weight)
    return features

mindnlp.transformers.models.layoutlmv2.modeling_layoutlmv2.relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128)

Calculate the relative position bucket.

PARAMETER DESCRIPTION
relative_position

A tensor containing the relative position.

TYPE: Tensor

bidirectional

A boolean flag indicating whether to use bidirectional buckets (default: True).

TYPE: bool DEFAULT: True

num_buckets

An integer specifying the number of buckets to use (default: 32).

TYPE: int DEFAULT: 32

max_distance

An integer representing the maximum distance to bucket (default: 128).

TYPE: int DEFAULT: 128

RETURNS DESCRIPTION

mindspore.Tensor: A tensor containing the calculated relative position bucket.

RAISES DESCRIPTION
TypeError

If the input tensor 'relative_position' is not a valid tensor.

ValueError

If the 'num_buckets' or 'max_distance' values are less than or equal to zero.

Source code in mindnlp/transformers/models/layoutlmv2/modeling_layoutlmv2.py
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
def relative_position_bucket(
        relative_position, bidirectional=True, num_buckets=32, max_distance=128
):
    '''Calculate the relative position bucket.

    Args:
        relative_position (mindspore.Tensor): A tensor containing the relative position.
        bidirectional (bool): A boolean flag indicating whether to use bidirectional buckets (default: True).
        num_buckets (int): An integer specifying the number of buckets to use (default: 32).
        max_distance (int): An integer representing the maximum distance to bucket (default: 128).

    Returns:
        mindspore.Tensor: A tensor containing the calculated relative position bucket.

    Raises:
        TypeError: If the input tensor 'relative_position' is not a valid tensor.
        ValueError: If the 'num_buckets' or 'max_distance' values are less than or equal to zero.
    '''
    ret = 0
    if bidirectional:
        num_buckets //= 2
        ret += (relative_position > 0).astype(mindspore.int64) * num_buckets
        n = ops.abs(relative_position)
    else:
        n = ops.maximum(
            -relative_position, ops.zeros_like(relative_position)
        )  # to be confirmed
    # Now n is in the range [0, inf)
    # half of the buckets are for exact increments in positions
    max_exact = num_buckets // 2
    is_small = n < max_exact

    # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
    val_if_large = max_exact + (
            ops.log(n.astype(mindspore.float32) / max_exact) / math.log(max_distance / max_exact) * (
            num_buckets - max_exact)
    ).astype(mindspore.int64)

    val_if_large = ops.minimum(
        val_if_large, ops.full_like(val_if_large, num_buckets - 1)
    )

    ret += ops.where(is_small, n, val_if_large)
    return ret

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2

Processor class for LayoutLMv2.

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor

Bases: ProcessorMixin

Constructs a LayoutLMv2 processor which combines a LayoutLMv2 image processor and a LayoutLMv2 tokenizer into a single processor.

[LayoutLMv2Processor] offers all the functionalities you need to prepare data for the model.

It first uses [LayoutLMv2ImageProcessor] to resize document images to a fixed size, and optionally applies OCR to get words and normalized bounding boxes. These are then provided to [LayoutLMv2Tokenizer] or [LayoutLMv2TokenizerFast], which turns the words and bounding boxes into token-level input_ids, attention_mask, token_type_ids, bbox. Optionally, one can provide integer word_labels, which are turned into token-level labels for token classification tasks (such as FUNSD, CORD).

PARAMETER DESCRIPTION
image_processor

An instance of [LayoutLMv2ImageProcessor]. The image processor is a required input.

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

tokenizer

An instance of [LayoutLMv2Tokenizer] or [LayoutLMv2TokenizerFast]. The tokenizer is a required input.

TYPE: `LayoutLMv2Tokenizer` or `LayoutLMv2TokenizerFast`, *optional* DEFAULT: None

Source code in mindnlp/transformers/models/layoutlmv2/processing_layoutlmv2.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
class LayoutLMv2Processor(ProcessorMixin):
    r"""
    Constructs a LayoutLMv2 processor which combines a LayoutLMv2 image processor and a LayoutLMv2 tokenizer into a
    single processor.

    [`LayoutLMv2Processor`] offers all the functionalities you need to prepare data for the model.

    It first uses [`LayoutLMv2ImageProcessor`] to resize document images to a fixed size, and optionally applies OCR to
    get words and normalized bounding boxes. These are then provided to [`LayoutLMv2Tokenizer`] or
    [`LayoutLMv2TokenizerFast`], which turns the words and bounding boxes into token-level `input_ids`,
    `attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide integer `word_labels`, which are turned
    into token-level `labels` for token classification tasks (such as FUNSD, CORD).

    Args:
        image_processor (`LayoutLMv2ImageProcessor`, *optional*):
            An instance of [`LayoutLMv2ImageProcessor`]. The image processor is a required input.
        tokenizer (`LayoutLMv2Tokenizer` or `LayoutLMv2TokenizerFast`, *optional*):
            An instance of [`LayoutLMv2Tokenizer`] or [`LayoutLMv2TokenizerFast`]. The tokenizer is a required input.
    """
    attributes = ["image_processor", "tokenizer"]
    image_processor_class = "LayoutLMv2ImageProcessor"
    tokenizer_class = ("LayoutLMv2Tokenizer", "LayoutLMv2TokenizerFast")

    def __init__(self, image_processor=None, tokenizer=None, **kwargs):
        """
        Initialize the LayoutLMv2Processor class.

        Args:
            self (object): The instance of the class.
            image_processor (object): An object representing the image processor.
                It can be an instance of a specific image processing class or None.
                If None, it will default to the value of 'feature_extractor'.
            tokenizer (object): An object representing the tokenizer to be used.
                This should be a valid tokenizer object required for processing the input data.

        Returns:
            None.

        Raises:
            ValueError: If either 'image_processor' is not provided or if 'tokenizer' is not specified.
            FutureWarning: If the 'feature_extractor' argument is used (deprecated) in place of 'image_processor'.
        """
        feature_extractor = None
        if "feature_extractor" in kwargs:
            warnings.warn(
                "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                " instead.",
                FutureWarning,
            )
            feature_extractor = kwargs.pop("feature_extractor")

        image_processor = image_processor if image_processor is not None else feature_extractor
        if image_processor is None:
            raise ValueError("You need to specify an `image_processor`.")
        if tokenizer is None:
            raise ValueError("You need to specify a `tokenizer`.")

        super().__init__(image_processor, tokenizer)

    def __call__(
            self,
            images,
            text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
            text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
            boxes: Union[List[List[int]], List[List[List[int]]]] = None,
            word_labels: Optional[Union[List[int], List[List[int]]]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = False,
            max_length: Optional[int] = None,
            stride: int = 0,
            pad_to_multiple_of: Optional[int] = 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,
            return_tensors: Optional[Union[str, TensorType]] = None,
            **kwargs,
    ) -> BatchEncoding:
        """
        This method first forwards the `images` argument to [`~LayoutLMv2ImageProcessor.__call__`]. In case
        [`LayoutLMv2ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
        bounding boxes along with the additional arguments to [`~LayoutLMv2Tokenizer.__call__`] and returns the output,
        together with resized `images`. In case [`LayoutLMv2ImageProcessor`] was initialized with `apply_ocr` set to
        `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along with the additional
        arguments to [`~LayoutLMv2Tokenizer.__call__`] and returns the output, together with resized `images``.

        Please refer to the docstring of the above two methods for more information.
        """
        # verify input
        if self.image_processor.apply_ocr and (boxes is not None):
            raise ValueError(
                "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
            )

        if self.image_processor.apply_ocr and (word_labels is not None):
            raise ValueError(
                "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
            )

        if return_overflowing_tokens is True and return_offsets_mapping is False:
            raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")

        # first, apply the image processor
        features = self.image_processor(images=images, return_tensors=return_tensors)

        # second, apply the tokenizer
        if text is not None and self.image_processor.apply_ocr and text_pair is None:
            if isinstance(text, str):
                text = [text]  # add batch dimension (as the image processor always adds a batch dimension)
            text_pair = features["words"]

        encoded_inputs = self.tokenizer(
            text=text if text is not None else features["words"],
            text_pair=text_pair if text_pair is not None else None,
            boxes=boxes if boxes is not None else features["boxes"],
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            stride=stride,
            pad_to_multiple_of=pad_to_multiple_of,
            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,
            return_tensors=return_tensors,
            **kwargs,
        )

        # add pixel values
        images = features.pop("pixel_values")
        if return_overflowing_tokens is True:
            images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
        encoded_inputs["image"] = images

        return encoded_inputs

    def get_overflowing_images(self, images, overflow_to_sample_mapping):
        """

        Args:
            images: List of images
            overflow_to_sample_mapping: List of indices of samples that have overflowing tokens

        Returns:
            List of images that correspond to samples with overflowing tokens
        """
        # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
        images_with_overflow = []
        for sample_idx in overflow_to_sample_mapping:
            images_with_overflow.append(images[sample_idx])

        if len(images_with_overflow) != len(overflow_to_sample_mapping):
            raise ValueError(
                "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
                f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
            )

        return images_with_overflow

    def batch_decode(self, *args, **kwargs):
        """
        This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        """
        return self.tokenizer.batch_decode(*args, **kwargs)

    def decode(self, *args, **kwargs):
        """
        This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
        to the docstring of this method for more information.
        """
        return self.tokenizer.decode(*args, **kwargs)

    @property
    def model_input_names(self):
        """
        This method returns a list of input names used by the LayoutLMv2Processor.

        Args:
            self (LayoutLMv2Processor): The instance of the LayoutLMv2Processor.

        Returns:
            list: A list containing the input names, including 'input_ids', 'bbox', 'token_type_ids',
                'attention_mask', and 'image'.

        Raises:
            None.
        """
        return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]

    @property
    def feature_extractor_class(self):
        """
        Deprecated property, will be removed in v5. Use `image_processor_class` instead.
        """
        warnings.warn(
            "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
            FutureWarning,
        )
        return self.image_processor_class

    @property
    def feature_extractor(self):
        """
        Deprecated property, will be removed in v5. Use `image_processor` instead.
        """
        warnings.warn(
            "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
            FutureWarning,
        )
        return self.image_processor

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.feature_extractor property

Deprecated property, will be removed in v5. Use image_processor instead.

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.feature_extractor_class property

Deprecated property, will be removed in v5. Use image_processor_class instead.

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.model_input_names property

This method returns a list of input names used by the LayoutLMv2Processor.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Processor.

TYPE: LayoutLMv2Processor

RETURNS DESCRIPTION
list

A list containing the input names, including 'input_ids', 'bbox', 'token_type_ids', 'attention_mask', and 'image'.

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.__call__(images, text=None, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=False, max_length=None, stride=0, pad_to_multiple_of=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, return_tensors=None, **kwargs)

This method first forwards the images argument to [~LayoutLMv2ImageProcessor.__call__]. In case [LayoutLMv2ImageProcessor] was initialized with apply_ocr set to True, it passes the obtained words and bounding boxes along with the additional arguments to [~LayoutLMv2Tokenizer.__call__] and returns the output, together with resized images. In case [LayoutLMv2ImageProcessor] was initialized with apply_ocr set to False, it passes the words (text/text_pair`) and `boxes` specified by the user along with the additional arguments to [`~LayoutLMv2Tokenizer.__call__`] and returns the output, together with resized `images.

Please refer to the docstring of the above two methods for more information.

Source code in mindnlp/transformers/models/layoutlmv2/processing_layoutlmv2.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def __call__(
        self,
        images,
        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
        text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
        boxes: Union[List[List[int]], List[List[List[int]]]] = None,
        word_labels: Optional[Union[List[int], List[List[int]]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = False,
        max_length: Optional[int] = None,
        stride: int = 0,
        pad_to_multiple_of: Optional[int] = 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,
        return_tensors: Optional[Union[str, TensorType]] = None,
        **kwargs,
) -> BatchEncoding:
    """
    This method first forwards the `images` argument to [`~LayoutLMv2ImageProcessor.__call__`]. In case
    [`LayoutLMv2ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
    bounding boxes along with the additional arguments to [`~LayoutLMv2Tokenizer.__call__`] and returns the output,
    together with resized `images`. In case [`LayoutLMv2ImageProcessor`] was initialized with `apply_ocr` set to
    `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along with the additional
    arguments to [`~LayoutLMv2Tokenizer.__call__`] and returns the output, together with resized `images``.

    Please refer to the docstring of the above two methods for more information.
    """
    # verify input
    if self.image_processor.apply_ocr and (boxes is not None):
        raise ValueError(
            "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
        )

    if self.image_processor.apply_ocr and (word_labels is not None):
        raise ValueError(
            "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
        )

    if return_overflowing_tokens is True and return_offsets_mapping is False:
        raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")

    # first, apply the image processor
    features = self.image_processor(images=images, return_tensors=return_tensors)

    # second, apply the tokenizer
    if text is not None and self.image_processor.apply_ocr and text_pair is None:
        if isinstance(text, str):
            text = [text]  # add batch dimension (as the image processor always adds a batch dimension)
        text_pair = features["words"]

    encoded_inputs = self.tokenizer(
        text=text if text is not None else features["words"],
        text_pair=text_pair if text_pair is not None else None,
        boxes=boxes if boxes is not None else features["boxes"],
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding=padding,
        truncation=truncation,
        max_length=max_length,
        stride=stride,
        pad_to_multiple_of=pad_to_multiple_of,
        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,
        return_tensors=return_tensors,
        **kwargs,
    )

    # add pixel values
    images = features.pop("pixel_values")
    if return_overflowing_tokens is True:
        images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
    encoded_inputs["image"] = images

    return encoded_inputs

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.__init__(image_processor=None, tokenizer=None, **kwargs)

Initialize the LayoutLMv2Processor class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

image_processor

An object representing the image processor. It can be an instance of a specific image processing class or None. If None, it will default to the value of 'feature_extractor'.

TYPE: object DEFAULT: None

tokenizer

An object representing the tokenizer to be used. This should be a valid tokenizer object required for processing the input data.

TYPE: object DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If either 'image_processor' is not provided or if 'tokenizer' is not specified.

FutureWarning

If the 'feature_extractor' argument is used (deprecated) in place of 'image_processor'.

Source code in mindnlp/transformers/models/layoutlmv2/processing_layoutlmv2.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
    """
    Initialize the LayoutLMv2Processor class.

    Args:
        self (object): The instance of the class.
        image_processor (object): An object representing the image processor.
            It can be an instance of a specific image processing class or None.
            If None, it will default to the value of 'feature_extractor'.
        tokenizer (object): An object representing the tokenizer to be used.
            This should be a valid tokenizer object required for processing the input data.

    Returns:
        None.

    Raises:
        ValueError: If either 'image_processor' is not provided or if 'tokenizer' is not specified.
        FutureWarning: If the 'feature_extractor' argument is used (deprecated) in place of 'image_processor'.
    """
    feature_extractor = None
    if "feature_extractor" in kwargs:
        warnings.warn(
            "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
            " instead.",
            FutureWarning,
        )
        feature_extractor = kwargs.pop("feature_extractor")

    image_processor = image_processor if image_processor is not None else feature_extractor
    if image_processor is None:
        raise ValueError("You need to specify an `image_processor`.")
    if tokenizer is None:
        raise ValueError("You need to specify a `tokenizer`.")

    super().__init__(image_processor, tokenizer)

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.batch_decode(*args, **kwargs)

This method forwards all its arguments to PreTrainedTokenizer's [~PreTrainedTokenizer.batch_decode]. Please refer to the docstring of this method for more information.

Source code in mindnlp/transformers/models/layoutlmv2/processing_layoutlmv2.py
196
197
198
199
200
201
def batch_decode(self, *args, **kwargs):
    """
    This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
    refer to the docstring of this method for more information.
    """
    return self.tokenizer.batch_decode(*args, **kwargs)

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.decode(*args, **kwargs)

This method forwards all its arguments to PreTrainedTokenizer's [~PreTrainedTokenizer.decode]. Please refer to the docstring of this method for more information.

Source code in mindnlp/transformers/models/layoutlmv2/processing_layoutlmv2.py
203
204
205
206
207
208
def decode(self, *args, **kwargs):
    """
    This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
    to the docstring of this method for more information.
    """
    return self.tokenizer.decode(*args, **kwargs)

mindnlp.transformers.models.layoutlmv2.processing_layoutlmv2.LayoutLMv2Processor.get_overflowing_images(images, overflow_to_sample_mapping)

PARAMETER DESCRIPTION
images

List of images

overflow_to_sample_mapping

List of indices of samples that have overflowing tokens

RETURNS DESCRIPTION

List of images that correspond to samples with overflowing tokens

Source code in mindnlp/transformers/models/layoutlmv2/processing_layoutlmv2.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def get_overflowing_images(self, images, overflow_to_sample_mapping):
    """

    Args:
        images: List of images
        overflow_to_sample_mapping: List of indices of samples that have overflowing tokens

    Returns:
        List of images that correspond to samples with overflowing tokens
    """
    # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
    images_with_overflow = []
    for sample_idx in overflow_to_sample_mapping:
        images_with_overflow.append(images[sample_idx])

    if len(images_with_overflow) != len(overflow_to_sample_mapping):
        raise ValueError(
            "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
            f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
        )

    return images_with_overflow

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2

Tokenization class for LayoutLMv2.

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.BasicTokenizer

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

PARAMETER DESCRIPTION
do_lower_case

Whether or not to lowercase the input when tokenizing.

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

never_split

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

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

tokenize_chinese_chars

Whether or not to tokenize Chinese characters.

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

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

strip_accents

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

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

do_split_on_punc

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

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
class BasicTokenizer:
    """
    Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).

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

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

        Args:
            self: The object itself.
            do_lower_case (bool): A boolean indicating whether to convert the text to lowercase. Defaults to True.
            never_split (list): A list of tokens that should never be split during tokenization. Defaults to None.
            tokenize_chinese_chars (bool): A boolean indicating whether to tokenize Chinese characters. Defaults to True.
            strip_accents (str or None): A string indicating whether to strip accents from the text. Defaults to None.
            do_split_on_punc (bool): A boolean indicating whether to split tokens on punctuation. Defaults to True.

        Returns:
            None.

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

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

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

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

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

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

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

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

    def _tokenize_chinese_chars(self, text):
        """Adds whitespace around any CJK character."""
        output = []
        for char in text:
            cp = ord(char)
            if self._is_chinese_char(cp):
                output.append(" ")
                output.append(char)
                output.append(" ")
            else:
                output.append(char)
        return "".join(output)

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

        return False

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

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

Initializes a new instance of the BasicTokenizer class.

PARAMETER DESCRIPTION
self

The object itself.

do_lower_case

A boolean indicating whether to convert the text to lowercase. Defaults to True.

TYPE: bool DEFAULT: True

never_split

A list of tokens that should never be split during tokenization. Defaults to None.

TYPE: list DEFAULT: None

tokenize_chinese_chars

A boolean indicating whether to tokenize Chinese characters. Defaults to True.

TYPE: bool DEFAULT: True

strip_accents

A string indicating whether to strip accents from the text. Defaults to None.

TYPE: str or None DEFAULT: None

do_split_on_punc

A boolean indicating whether to split tokens on punctuation. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def __init__(
        self,
        do_lower_case=True,
        never_split=None,
        tokenize_chinese_chars=True,
        strip_accents=None,
        do_split_on_punc=True,
):
    """
    Initializes a new instance of the BasicTokenizer class.

    Args:
        self: The object itself.
        do_lower_case (bool): A boolean indicating whether to convert the text to lowercase. Defaults to True.
        never_split (list): A list of tokens that should never be split during tokenization. Defaults to None.
        tokenize_chinese_chars (bool): A boolean indicating whether to tokenize Chinese characters. Defaults to True.
        strip_accents (str or None): A string indicating whether to strip accents from the text. Defaults to None.
        do_split_on_punc (bool): A boolean indicating whether to split tokens on punctuation. Defaults to True.

    Returns:
        None.

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

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.BasicTokenizer.tokenize(text, never_split=None)

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

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

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

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

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

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer

Bases: PreTrainedTokenizer

Construct a LayoutLMv2 tokenizer. Based on WordPiece. [LayoutLMv2Tokenizer] can be used to turn words, word-level bounding boxes and optional word labels to token-level input_ids, attention_mask, token_type_ids, bbox, and optional labels (for token classification).

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

[LayoutLMv2Tokenizer] runs end-to-end tokenization: punctuation splitting and wordpiece. It also turns the word-level bounding boxes into token-level bounding boxes.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
 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
class LayoutLMv2Tokenizer(PreTrainedTokenizer):
    r"""
    Construct a LayoutLMv2 tokenizer. Based on WordPiece. [`LayoutLMv2Tokenizer`] can be used to turn words, word-level
    bounding boxes and optional word labels to token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`, and
    optional `labels` (for token classification).

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

    [`LayoutLMv2Tokenizer`] runs end-to-end tokenization: punctuation splitting and wordpiece. It also turns the
    word-level bounding boxes into token-level bounding boxes.

    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION

    def __init__(
            self,
            vocab_file,
            do_lower_case=True,
            do_basic_tokenize=True,
            never_split=None,
            unk_token="[UNK]",
            sep_token="[SEP]",
            pad_token="[PAD]",
            cls_token="[CLS]",
            mask_token="[MASK]",
            cls_token_box=[0, 0, 0, 0],
            sep_token_box=[1000, 1000, 1000, 1000],
            pad_token_box=[0, 0, 0, 0],
            pad_token_label=-100,
            only_label_first_subword=True,
            tokenize_chinese_chars=True,
            strip_accents=None,
            model_max_length: int = 512,
            additional_special_tokens: Optional[List[str]] = None,
            **kwargs,
    ):
        """
        Initializes a LayoutLMv2Tokenizer object.

        Args:
            self: The instance of the class.
            vocab_file (str): The path to the vocabulary file.
            do_lower_case (bool, optional): Whether to lowercase the input text. Defaults to True.
            do_basic_tokenize (bool, optional): Whether to perform basic tokenization. Defaults to True.
            never_split (list, optional): List of tokens that should not be split. Defaults to None.
            unk_token (str, optional): The unknown token. Defaults to '[UNK]'.
            sep_token (str, optional): The separator token. Defaults to '[SEP]'.
            pad_token (str, optional): The padding token. Defaults to '[PAD]'.
            cls_token (str, optional): The classification token. Defaults to '[CLS]'.
            mask_token (str, optional): The masking token. Defaults to '[MASK]'.
            cls_token_box (list, optional): The bounding box coordinates for the classification token. Defaults to [0, 0, 0, 0].
            sep_token_box (list, optional): The bounding box coordinates for the separator token. Defaults to [1000, 1000, 1000, 1000].
            pad_token_box (list, optional): The bounding box coordinates for the padding token. Defaults to [0, 0, 0, 0].
            pad_token_label (int, optional): The label for the padding token. Defaults to -100.
            only_label_first_subword (bool, optional): Whether to only label the first subword. Defaults to True.
            tokenize_chinese_chars (bool, optional): Whether to tokenize Chinese characters. Defaults to True.
            strip_accents (str, optional): The accents to strip. Defaults to None.
            model_max_length (int, optional): The maximum length of the model. Defaults to 512.
            additional_special_tokens (list, optional): Additional special tokens. Defaults to None.

        Returns:
            None

        Raises:
            ValueError: If the vocabulary file cannot be found at the specified path.
        """
        sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
        unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
        pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
        cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
        mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token

        if not os.path.isfile(vocab_file):
            raise ValueError(
                f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
                " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
            )
        self.vocab = load_vocab(vocab_file)
        self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
        self.do_basic_tokenize = do_basic_tokenize
        if do_basic_tokenize:
            self.basic_tokenizer = BasicTokenizer(
                do_lower_case=do_lower_case,
                never_split=never_split,
                tokenize_chinese_chars=tokenize_chinese_chars,
                strip_accents=strip_accents,
            )
        self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))

        # additional properties
        self.cls_token_box = cls_token_box
        self.sep_token_box = sep_token_box
        self.pad_token_box = pad_token_box
        self.pad_token_label = pad_token_label
        self.only_label_first_subword = only_label_first_subword
        super().__init__(
            do_lower_case=do_lower_case,
            do_basic_tokenize=do_basic_tokenize,
            never_split=never_split,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            cls_token_box=cls_token_box,
            sep_token_box=sep_token_box,
            pad_token_box=pad_token_box,
            pad_token_label=pad_token_label,
            only_label_first_subword=only_label_first_subword,
            tokenize_chinese_chars=tokenize_chinese_chars,
            strip_accents=strip_accents,
            model_max_length=model_max_length,
            additional_special_tokens=additional_special_tokens,
            **kwargs,
        )

    @property
    def do_lower_case(self):
        """
        Whether or not to lowercase the input when tokenizing.
        """
        return self.basic_tokenizer.do_lower_case

    @property
    def vocab_size(self):
        """Return the size of the vocabulary used by the LayoutLMv2Tokenizer.

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

        Returns:
            None.

        Raises:
            None.
        """
        return len(self.vocab)

    def get_vocab(self):
        """
        Returns the combined vocabulary of the LayoutLMv2Tokenizer instance and any additional tokens that have been added.

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

        Returns:
            dict: A dictionary representing the combined vocabulary of the LayoutLMv2Tokenizer instance
                and any additional tokens that have been added.

        Raises:
            None.

        """
        return dict(self.vocab, **self.added_tokens_encoder)

    def _tokenize(self, text):
        """
        This method '_tokenize' is defined within the 'LayoutLMv2Tokenizer' class and is responsible
        for tokenizing the input text.

        Args:
            self: The instance of the 'LayoutLMv2Tokenizer' class.
            text (str): The input text to be tokenized.

        Returns:
            list: A list of tokens resulting from the tokenization process.

        Raises:
            None.
        """
        split_tokens = []
        if self.do_basic_tokenize:
            for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
                # If the token is part of the never_split set
                if token in self.basic_tokenizer.never_split:
                    split_tokens.append(token)
                else:
                    split_tokens += self.wordpiece_tokenizer.tokenize(token)
        else:
            split_tokens = self.wordpiece_tokenizer.tokenize(text)
        return split_tokens

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

    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        return self.ids_to_tokens.get(index, self.unk_token)

    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        out_string = " ".join(tokens).replace(" ##", "").strip()
        return out_string

    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 BERT sequence has the following format:

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

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

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """
        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
        cls = [self.cls_token_id]
        sep = [self.sep_token_id]
        return cls + token_ids_0 + sep + token_ids_1 + sep

    def get_special_tokens_mask(
            self, token_ids_0: 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 not None:
            return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
        return [1] + ([0] * len(token_ids_0)) + [1]

    def create_token_type_ids_from_sequences(
            self, token_ids_0: 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. A BERT sequence
        pair mask has the following format:

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

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

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

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

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary to a file in the specified directory.

        Args:
            self (LayoutLMv2Tokenizer): The instance of the LayoutLMv2Tokenizer class.
            save_directory (str): The directory where the vocabulary file will be saved.
            filename_prefix (Optional[str]): A prefix to be added to the filename. Defaults to None.

        Returns:
            Tuple[str]: A tuple containing the file path of the saved vocabulary.

        Raises:
            IOError: If an I/O error occurs while writing the vocabulary file.
            ValueError: If the provided save_directory is invalid or if the vocabulary indices are not consecutive.

        """
        index = 0
        if os.path.isdir(save_directory):
            vocab_file = os.path.join(
                save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
            )
        else:
            vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
        with open(vocab_file, "w", encoding="utf-8") as writer:
            for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
                if index != token_index:
                    logger.warning(
                        f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
                        " Please check that the vocabulary is not corrupted!"
                    )
                    index = token_index
                writer.write(token + "\n")
                index += 1
        return (vocab_file,)

    def __call__(
            self,
            text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
            text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
            boxes: Union[List[List[int]], List[List[List[int]]]] = None,
            word_labels: Optional[Union[List[int], List[List[int]]]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> BatchEncoding:
        """
        Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
        sequences with word-level normalized bounding boxes and optional labels.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
                (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
                words).
            text_pair (`List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
                (pretokenized string).
            boxes (`List[List[int]]`, `List[List[List[int]]]`):
                Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
            word_labels (`List[int]`, `List[List[int]]`, *optional*):
                Word-level integer labels (for token classification tasks such as FUNSD, CORD).
        """
        # Input type checking for clearer error
        def _is_valid_text_input(t):
            if isinstance(t, str):
                # Strings are fine
                return True
            if isinstance(t, (list, tuple)):
                # List are fine as long as they are...
                if len(t) == 0:
                    # ... empty
                    return True
                if isinstance(t[0], str):
                    # ... list of strings
                    return True
                if isinstance(t[0], (list, tuple)):
                    # ... list with an empty list or with a list of strings
                    return len(t[0]) == 0 or isinstance(t[0][0], str)
            return False

        if text_pair is not None:
            # in case text + text_pair are provided, text = questions, text_pair = words
            if not _is_valid_text_input(text):
                raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
            if not isinstance(text_pair, (list, tuple)):
                raise ValueError(
                    "Words must be of type `List[str]` (single pretokenized example), "
                    "or `List[List[str]]` (batch of pretokenized examples)."
                )
        else:
            # in case only text is provided => must be words
            if not isinstance(text, (list, tuple)):
                raise ValueError(
                    "Words must be of type `List[str]` (single pretokenized example), "
                    "or `List[List[str]]` (batch of pretokenized examples)."
                )

        if text_pair is not None:
            is_batched = isinstance(text, (list, tuple))
        else:
            is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))

        words = text if text_pair is None else text_pair
        if boxes is None:
            raise ValueError("You must provide corresponding bounding boxes")
        if is_batched:
            if len(words) != len(boxes):
                raise ValueError("You must provide words and boxes for an equal amount of examples")
            for words_example, boxes_example in zip(words, boxes):
                if len(words_example) != len(boxes_example):
                    raise ValueError("You must provide as many words as there are bounding boxes")
        else:
            if len(words) != len(boxes):
                raise ValueError("You must provide as many words as there are bounding boxes")

        if is_batched:
            if text_pair is not None and len(text) != len(text_pair):
                raise ValueError(
                    f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
                    f" {len(text_pair)}."
                )
            batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
            is_pair = bool(text_pair is not None)
            return self.batch_encode_plus(
                batch_text_or_text_pairs=batch_text_or_text_pairs,
                is_pair=is_pair,
                boxes=boxes,
                word_labels=word_labels,
                add_special_tokens=add_special_tokens,
                padding=padding,
                truncation=truncation,
                max_length=max_length,
                stride=stride,
                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,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            stride=stride,
            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 batch_encode_plus(
            self,
            batch_text_or_text_pairs: Union[
                List[TextInput],
                List[TextInputPair],
                List[PreTokenizedInput],
            ],
            is_pair: bool = None,
            boxes: Optional[List[List[List[int]]]] = None,
            word_labels: Optional[Union[List[int], List[List[int]]]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> BatchEncoding:
        """
        Encodes a batch of text or text pairs using the LayoutLMv2 model.

        Args:
            self (LayoutLMv2Tokenizer): An instance of the LayoutLMv2Tokenizer class.
            batch_text_or_text_pairs (Union[List[TextInput], List[TextInputPair], List[PreTokenizedInput]]):
                A list of input texts or text pairs to be encoded. The input can be either a single text, a text
                pair, or a pre-tokenized input.
            is_pair (bool, optional): Indicates whether the input is a text pair. Defaults to None.
            boxes (Optional[List[List[List[int]]]], optional): A list of bounding boxes for each token in the input.
                Defaults to None.
            word_labels (Optional[Union[List[int], List[List[int]]]], optional): A list of word labels for each token
                in the input. Defaults to None.
            add_special_tokens (bool, optional): Indicates whether to add special tokens to the input. Defaults to True.
            padding (Union[bool, str, PaddingStrategy], optional): Specifies the padding strategy to use.
                Defaults to False.
            truncation (Union[bool, str, TruncationStrategy], optional): Specifies the truncation strategy to use.
                Defaults to None.
            max_length (Optional[int], optional): The maximum sequence length after tokenization. Defaults to None.
            stride (int, optional): The stride for splitting the input into multiple chunks. Defaults to 0.
            pad_to_multiple_of (Optional[int], optional): Pad the sequence length to a multiple of this value.
                Defaults to None.
            return_tensors (Optional[Union[str, TensorType]], optional): Specifies the type of tensors to return.
                Defaults to None.
            return_token_type_ids (Optional[bool], optional): Indicates whether to return token type IDs.
                Defaults to None.
            return_attention_mask (Optional[bool], optional): Indicates whether to return attention masks.
                Defaults to None.
            return_overflowing_tokens (bool, optional): Indicates whether to return overflowing tokens.
                Defaults to False.
            return_special_tokens_mask (bool, optional): Indicates whether to return a mask indicating the special tokens.
                Defaults to False.
            return_offsets_mapping (bool, optional): Indicates whether to return the offsets mapping of tokens to
                original text. Defaults to False.
            return_length (bool, optional): Indicates whether to return the lengths of encoded sequences.
                Defaults to False.
            verbose (bool, optional): Indicates whether to print informative messages. Defaults to True.
            **kwargs: Additional keyword arguments for customizing the encoding process.

        Returns:
            BatchEncoding:
                A dictionary-like object containing the encoded batch, with the following keys:

                - 'input_ids': The input token IDs.
                - 'attention_mask': The attention mask indicating which tokens to attend to.
                - 'token_type_ids': The token type IDs indicating the segment type of each token.
                - 'overflowing_tokens': The list of overflowing tokens if return_overflowing_tokens=True.
                - 'special_tokens_mask': The mask indicating the special tokens if return_special_tokens_mask=True.
                - 'offset_mapping': The mapping of tokens to their corresponding positions in the original text
                if return_offsets_mapping=True.
                - 'length': The length of each encoded sequence if return_length=True.

        Raises:
            None.
        """
        # 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,
        )

        return self._batch_encode_plus(
            batch_text_or_text_pairs=batch_text_or_text_pairs,
            is_pair=is_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            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 _batch_encode_plus(
            self,
            batch_text_or_text_pairs: Union[
                List[TextInput],
                List[TextInputPair],
                List[PreTokenizedInput],
            ],
            is_pair: bool = None,
            boxes: Optional[List[List[List[int]]]] = None,
            word_labels: Optional[List[List[int]]] = 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,
            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,
            **kwargs,
    ) -> BatchEncoding:
        """
        Batch encodes a batch of text or text pairs using the LayoutLMv2Tokenizer.

        Args:
            self (LayoutLMv2Tokenizer): The instance of the LayoutLMv2Tokenizer class.
            batch_text_or_text_pairs (Union[List[TextInput], List[TextInputPair], List[PreTokenizedInput]]):
                A list of input text or text pairs to be encoded.
            is_pair (bool, optional): Specifies whether the input is a text pair. Defaults to None.
            boxes (Optional[List[List[List[int]]]], optional): The bounding boxes for each word in the input text.
                Defaults to None.
            word_labels (Optional[List[List[int]]], optional): The labels for each word in the input text.
                Defaults to None.
            add_special_tokens (bool, optional): Specifies whether to add special tokens. Defaults to True.
            padding_strategy (PaddingStrategy, optional): The strategy for padding the input.
                Defaults to PaddingStrategy.DO_NOT_PAD.
            truncation_strategy (TruncationStrategy, optional): The strategy for truncating the input.
                Defaults to TruncationStrategy.DO_NOT_TRUNCATE.
            max_length (Optional[int], optional): The maximum length of the encoded output. Defaults to None.
            stride (int, optional): The stride for splitting the input into overlapping chunks. Defaults to 0.
            pad_to_multiple_of (Optional[int], optional): The value to which the input length will be padded.
                Defaults to None.
            return_tensors (Optional[Union[str, TensorType]], optional): Specifies the type of tensors to return.
                Defaults to None.
            return_token_type_ids (Optional[bool], optional): Specifies whether to return token type IDs.
                Defaults to None.
            return_attention_mask (Optional[bool], optional): Specifies whether to return attention masks.
                Defaults to None.
            return_overflowing_tokens (bool, optional): Specifies whether to return overflowing tokens.
            qDefaults to False.
            return_special_tokens_mask (bool, optional): Specifies whether to return special tokens masks.
                Defaults to False.
            return_offsets_mapping (bool, optional): Specifies whether to return offsets mapping. Defaults to False.
            return_length (bool, optional): Specifies whether to return the length of each encoded input.
                Defaults to False.
            verbose (bool, optional): Specifies whether to print detailed information during encoding. Defaults to True.

        Returns:
            BatchEncoding: A dictionary-like object containing the encoded inputs.

        Raises:
            NotImplementedError: Raised when the 'return_offsets_mapping' parameter is set to True.
                This feature is not available when using Python tokenizers.
                To use this feature, change your tokenizer to one deriving from transformers.PreTrainedTokenizerFast.
        """
        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."
            )

        batch_outputs = self._batch_prepare_for_model(
            batch_text_or_text_pairs=batch_text_or_text_pairs,
            is_pair=is_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_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 _batch_prepare_for_model(
            self,
            batch_text_or_text_pairs,
            is_pair: bool = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[List[int]]] = 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,
            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_outputs = {}
        for idx, example in enumerate(zip(batch_text_or_text_pairs, boxes)):
            batch_text_or_text_pair, boxes_example = example
            outputs = self.prepare_for_model(
                batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
                batch_text_or_text_pair[1] if is_pair else None,
                boxes_example,
                word_labels=word_labels[idx] if word_labels is not None else None,
                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,
                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 encode(
            self,
            text: Union[TextInput, PreTokenizedInput],
            text_pair: Optional[PreTokenizedInput] = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[int]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> List[int]:
        """
        This method encodes the input text and returns a list of integer input ids.

        Args:
            self: The LayoutLMv2Tokenizer instance.
            text (Union[TextInput, PreTokenizedInput]): The input text to encode. It can be either a TextInput object
                or a PreTokenizedInput object.
            text_pair (Optional[PreTokenizedInput]): The optional second input text to be encoded.
                It should be a PreTokenizedInput object.
            boxes (Optional[List[List[int]]]): The optional bounding boxes for each token in the input text.
                Each box is represented as a list of four integers [x_min, y_min, x_max, y_max].
            word_labels (Optional[List[int]]): The optional word labels associated with each token in the input text.
                It should be a list of integers.
            add_special_tokens (bool): Whether to add special tokens like [CLS], [SEP], etc. Default is True.
            padding (Union[bool, str, PaddingStrategy]): The padding strategy to apply.
                It can be a boolean value, a string, or a PaddingStrategy object. Default is False.
            truncation (Union[bool, str, TruncationStrategy]): The truncation strategy to apply.
                It can be a boolean value, a string, or a TruncationStrategy object. Default is None.
            max_length (Optional[int]): The maximum length of the encoded sequence.
                If provided, the sequence is truncated or padded to this length.
            stride (int): The stride used for tokenization. Default is 0.
            pad_to_multiple_of (Optional[int]): If specified, the sequence is padded to a multiple of this value.
            return_tensors (Optional[Union[str, TensorType]]): The type of tensor to return.
                It can be a string or a TensorType object.
            return_token_type_ids (Optional[bool]): Whether to return token type ids.
            return_attention_mask (Optional[bool]): Whether to return attention mask.
            return_overflowing_tokens (bool): Whether to return overflowing tokens.
            return_special_tokens_mask (bool): Whether to return special tokens mask.
            return_offsets_mapping (bool): Whether to return the mapping from tokens to character offsets.
            return_length (bool): Whether to return the length of the encoded inputs.
            verbose (bool): Whether to print verbose logs. Default is True.
            **kwargs: Additional keyword arguments.

        Returns:
            List[int]: A list of integer input ids representing the encoded input text.

        Raises:
            None.
        """
        encoded_inputs = self.encode_plus(
            text=text,
            text_pair=text_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            stride=stride,
            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 encoded_inputs["input_ids"]

    def encode_plus(
            self,
            text: Union[TextInput, PreTokenizedInput],
            text_pair: Optional[PreTokenizedInput] = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[int]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> BatchEncoding:
        """
        Tokenize and prepare for the model a sequence or a pair of sequences.
        .. warning:: This method is deprecated, `__call__` should be used instead.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
            text_pair (`List[str]` or `List[int]`, *optional*):
                Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
                list of list of strings (words of a batch of examples).
        """
        # 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,
        )

        return self._encode_plus(
            text=text,
            boxes=boxes,
            text_pair=text_pair,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            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: Union[TextInput, PreTokenizedInput],
            text_pair: Optional[PreTokenizedInput] = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[int]] = 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,
            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,
            **kwargs,
    ) -> BatchEncoding:
        """Encodes the given inputs into a batch of tensors with additional special tokens for LayoutLMv2 model.

        Args:
            self (LayoutLMv2Tokenizer): The instance of the LayoutLMv2Tokenizer class.
            text (Union[TextInput, PreTokenizedInput]): The input text to be encoded.
                It can be either a raw string or a list of tokens.
            text_pair (Optional[PreTokenizedInput]): The second input text to be encoded in case of sequence pairs.
                It can be either a raw string or a list of tokens. Default is None.
            boxes (Optional[List[List[int]]]): The bounding boxes of the tokens in the text. Default is None.
            word_labels (Optional[List[int]]): The labels for each word token in the text. Default is None.
            add_special_tokens (bool): Whether to add special tokens to the encoded inputs. Default is True.
            padding_strategy (PaddingStrategy): The strategy to use for padding. Default is PaddingStrategy.DO_NOT_PAD.
            truncation_strategy (TruncationStrategy): The strategy to use for truncation.
                Default is TruncationStrategy.DO_NOT_TRUNCATE.
            max_length (Optional[int]): The maximum length of the encoded inputs. Default is None.
            stride (int): The stride to use when overflowing tokens. Default is 0.
            pad_to_multiple_of (Optional[int]): The value to pad the sequence length to a multiple of. Default is None.
            return_tensors (Optional[Union[str, TensorType]]): The type of tensors to return. Default is None.
            return_token_type_ids (Optional[bool]): Whether to return token type IDs. Default is None.
            return_attention_mask (Optional[bool]): Whether to return attention masks. Default is None.
            return_overflowing_tokens (bool): Whether to return overflowing tokens. Default is False.
            return_special_tokens_mask (bool): Whether to return a mask indicating the special tokens. Default is False.
            return_offsets_mapping (bool): Whether to return the offsets mapping. Default is False.
            return_length (bool): Whether to return the length of the encoded inputs. Default is False.
            verbose (bool): Whether to print verbose logs during encoding. Default is True.
            **kwargs: Additional keyword arguments.

        Returns:
            BatchEncoding: A batch of encoded inputs in the form of tensors.

        Raises:
            NotImplementedError: If return_offsets_mapping is set to True.
                This feature 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 can be found at
                https://github.com/huggingface/transformers/pull/2674.
        """
        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"
            )

        return self.prepare_for_model(
            text=text,
            text_pair=text_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding_strategy.value,
            truncation=truncation_strategy.value,
            max_length=max_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 prepare_for_model(
            self,
            text: Union[TextInput, PreTokenizedInput],
            text_pair: Optional[PreTokenizedInput] = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[int]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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 or a pair of sequences 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 *text_pair* 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.

        Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
        token-level `labels`. The word label is used for the first token of the word, while remaining tokens are
        labeled with -100, such that they will be ignored by the loss function.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
            text_pair (`List[str]` or `List[int]`, *optional*):
                Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
                list of list of strings (words of a batch of examples).
        """
        # 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,
        )

        tokens = []
        pair_tokens = []
        token_boxes = []
        pair_token_boxes = []
        labels = []

        if text_pair is None:
            if word_labels is None:
                # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)
                for word, box in zip(text, boxes):
                    if len(word) < 1:  # skip empty words
                        continue
                    word_tokens = self.tokenize(word)
                    tokens.extend(word_tokens)
                    token_boxes.extend([box] * len(word_tokens))
            else:
                # CASE 2: token classification (training)
                for word, box, label in zip(text, boxes, word_labels):
                    if len(word) < 1:  # skip empty words
                        continue
                    word_tokens = self.tokenize(word)
                    tokens.extend(word_tokens)
                    token_boxes.extend([box] * len(word_tokens))
                    if self.only_label_first_subword:
                        # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                        labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
                    else:
                        labels.extend([label] * len(word_tokens))
        else:
            # CASE 3: document visual question answering (inference)
            # text = question
            # text_pair = words
            tokens = self.tokenize(text)
            token_boxes = [self.pad_token_box for _ in range(len(tokens))]

            for word, box in zip(text_pair, boxes):
                if len(word) < 1:  # skip empty words
                    continue
                word_tokens = self.tokenize(word)
                pair_tokens.extend(word_tokens)
                pair_token_boxes.extend([box] * len(word_tokens))

        # Create ids + pair_ids
        ids = self.convert_tokens_to_ids(tokens)
        pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else 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`."
            )

        # Compute the total size of the returned encodings
        pair = bool(pair_ids is not None)
        len_ids = len(ids)
        len_pair_ids = len(pair_ids) if pair else 0
        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
        overflowing_tokens = []
        overflowing_token_boxes = []
        overflowing_labels = []
        if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
            (
                ids,
                token_boxes,
                pair_ids,
                pair_token_boxes,
                labels,
                overflowing_tokens,
                overflowing_token_boxes,
                overflowing_labels,
            ) = self.truncate_sequences(
                ids,
                token_boxes,
                pair_ids=pair_ids,
                pair_token_boxes=pair_token_boxes,
                labels=labels,
                num_tokens_to_remove=total_len - max_length,
                truncation_strategy=truncation_strategy,
                stride=stride,
            )

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

        # 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 = {}

        if return_overflowing_tokens:
            encoded_inputs["overflowing_tokens"] = overflowing_tokens
            encoded_inputs["overflowing_token_boxes"] = overflowing_token_boxes
            encoded_inputs["overflowing_labels"] = overflowing_labels
            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)
            token_boxes = [self.cls_token_box] + token_boxes + [self.sep_token_box]
            if pair_token_boxes:
                pair_token_boxes = pair_token_boxes + [self.sep_token_box]
            if labels:
                labels = [self.pad_token_label] + labels + [self.pad_token_label]
        else:
            sequence = ids + pair_ids if pair else ids
            token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])

        # Build output dictionary
        encoded_inputs["input_ids"] = sequence
        encoded_inputs["bbox"] = token_boxes + pair_token_boxes
        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)

        if labels:
            encoded_inputs["labels"] = labels

        # 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,
                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 truncate_sequences(
            self,
            ids: List[int],
            token_boxes: List[List[int]],
            pair_ids: Optional[List[int]] = None,
            pair_token_boxes: Optional[List[List[int]]] = None,
            labels: Optional[List[int]] = None,
            num_tokens_to_remove: int = 0,
            truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
            stride: int = 0,
    ) -> Tuple[List[int], List[int], List[int]]:
        """
        Truncates a sequence pair in-place following the strategy.

        Args:
            ids (`List[int]`):
                Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
                `convert_tokens_to_ids` methods.
            token_boxes (`List[List[int]]`):
                Bounding boxes of the first sequence.
            pair_ids (`List[int]`, *optional*):
                Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
                and `convert_tokens_to_ids` methods.
            pair_token_boxes (`List[List[int]]`, *optional*):
                Bounding boxes of the second sequence.
            labels (`List[int]`, *optional*):
                Labels of the first sequence (for token classification tasks).
            num_tokens_to_remove (`int`, *optional*, defaults to 0):
                Number of tokens to remove using the truncation strategy.
            truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
                The strategy to follow for truncation. Can be:

                - `'longest_first'`: Truncate 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. This will truncate
                token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
                batch of pairs) is provided.
                - `'only_first'`: Truncate 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. This will only
                truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `'only_second'`: Truncate 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. This will only
                truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
                than the model maximum admissible input size).
            stride (`int`, *optional*, defaults to 0):
                If set to a positive number, the overflowing tokens returned will contain some tokens from the main
                sequence returned. The value of this argument defines the number of additional tokens.

        Returns:
            `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
                overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
                of sequences (or a batch of pairs) is provided.
        """
        if num_tokens_to_remove <= 0:
            return ids, token_boxes, pair_ids, pair_token_boxes, labels, [], [], []

        if not isinstance(truncation_strategy, TruncationStrategy):
            truncation_strategy = TruncationStrategy(truncation_strategy)

        overflowing_tokens = []
        overflowing_token_boxes = []
        overflowing_labels = []
        if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
                truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
        ):
            if len(ids) > num_tokens_to_remove:
                window_len = min(len(ids), stride + num_tokens_to_remove)
                overflowing_tokens = ids[-window_len:]
                overflowing_token_boxes = token_boxes[-window_len:]
                overflowing_labels = labels[-window_len:]
                ids = ids[:-num_tokens_to_remove]
                token_boxes = token_boxes[:-num_tokens_to_remove]
                labels = labels[:-num_tokens_to_remove]
            else:
                error_msg = (
                    f"We need to remove {num_tokens_to_remove} to truncate the input "
                    f"but the first sequence has a length {len(ids)}. "
                )
                if truncation_strategy == TruncationStrategy.ONLY_FIRST:
                    error_msg = (
                            error_msg + "Please select another truncation strategy than "
                                        f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
                    )
                logger.error(error_msg)
        elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
            logger.warning(
                "Be aware, overflowing tokens are not returned for the setting you have chosen,"
                f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
                "truncation strategy. So the returned list will always be empty even if some "
                "tokens have been removed."
            )
            for _ in range(num_tokens_to_remove):
                if pair_ids is None or len(ids) > len(pair_ids):
                    ids = ids[:-1]
                    token_boxes = token_boxes[:-1]
                    labels = labels[:-1]
                else:
                    pair_ids = pair_ids[:-1]
                    pair_token_boxes = pair_token_boxes[:-1]
        elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
            if len(pair_ids) > num_tokens_to_remove:
                window_len = min(len(pair_ids), stride + num_tokens_to_remove)
                overflowing_tokens = pair_ids[-window_len:]
                overflowing_token_boxes = pair_token_boxes[-window_len:]
                pair_ids = pair_ids[:-num_tokens_to_remove]
                pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
            else:
                logger.error(
                    f"We need to remove {num_tokens_to_remove} to truncate the input "
                    f"but the second sequence has a length {len(pair_ids)}. "
                    f"Please select another truncation strategy than {truncation_strategy}, "
                    "for instance 'longest_first' or 'only_first'."
                )

        return (
            ids,
            token_boxes,
            pair_ids,
            pair_token_boxes,
            labels,
            overflowing_tokens,
            overflowing_token_boxes,
            overflowing_labels,
        )

    def _pad(
            self,
            encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
            max_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.
            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)
        """
        # Load from model defaults
        if return_attention_mask is None:
            return_attention_mask = "attention_mask" in self.model_input_names

        required_input = encoded_inputs[self.model_input_names[0]]

        if padding_strategy == PaddingStrategy.LONGEST:
            max_length = len(required_input)

        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

        needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length

        # Initialize attention mask if not present.
        if return_attention_mask and "attention_mask" not in encoded_inputs:
            encoded_inputs["attention_mask"] = [1] * len(required_input)

        if needs_to_be_padded:
            difference = max_length - len(required_input)
            if self.padding_side == "right":
                if return_attention_mask:
                    encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
                if "token_type_ids" in encoded_inputs:
                    encoded_inputs["token_type_ids"] = (
                            encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
                    )
                if "bbox" in encoded_inputs:
                    encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
                if "labels" in encoded_inputs:
                    encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
                if "special_tokens_mask" in encoded_inputs:
                    encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
                encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
            elif self.padding_side == "left":
                if return_attention_mask:
                    encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
                if "token_type_ids" in encoded_inputs:
                    encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
                        "token_type_ids"
                    ]
                if "bbox" in encoded_inputs:
                    encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
                if "labels" in encoded_inputs:
                    encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
                if "special_tokens_mask" in encoded_inputs:
                    encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
                encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
            else:
                raise ValueError("Invalid padding strategy:" + str(self.padding_side))

        return encoded_inputs

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.do_lower_case property

Whether or not to lowercase the input when tokenizing.

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.vocab_size property

Return the size of the vocabulary used by the LayoutLMv2Tokenizer.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Tokenizer class.

TYPE: LayoutLMv2Tokenizer

RETURNS DESCRIPTION

None.

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.__call__(text, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences with word-level normalized bounding boxes and optional labels.

PARAMETER DESCRIPTION
text

The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings (words of a single example or questions of a batch of examples) or a list of list of strings (batch of words).

TYPE: `str`, `List[str]`, `List[List[str]]`

text_pair

The sequence or batch of sequences to be encoded. Each sequence should be a list of strings (pretokenized string).

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

boxes

Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.

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

word_labels

Word-level integer labels (for token classification tasks such as FUNSD, CORD).

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def __call__(
        self,
        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
        text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
        boxes: Union[List[List[int]], List[List[List[int]]]] = None,
        word_labels: Optional[Union[List[int], List[List[int]]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> BatchEncoding:
    """
    Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
    sequences with word-level normalized bounding boxes and optional labels.

    Args:
        text (`str`, `List[str]`, `List[List[str]]`):
            The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
            (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
            words).
        text_pair (`List[str]`, `List[List[str]]`):
            The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
            (pretokenized string).
        boxes (`List[List[int]]`, `List[List[List[int]]]`):
            Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
        word_labels (`List[int]`, `List[List[int]]`, *optional*):
            Word-level integer labels (for token classification tasks such as FUNSD, CORD).
    """
    # Input type checking for clearer error
    def _is_valid_text_input(t):
        if isinstance(t, str):
            # Strings are fine
            return True
        if isinstance(t, (list, tuple)):
            # List are fine as long as they are...
            if len(t) == 0:
                # ... empty
                return True
            if isinstance(t[0], str):
                # ... list of strings
                return True
            if isinstance(t[0], (list, tuple)):
                # ... list with an empty list or with a list of strings
                return len(t[0]) == 0 or isinstance(t[0][0], str)
        return False

    if text_pair is not None:
        # in case text + text_pair are provided, text = questions, text_pair = words
        if not _is_valid_text_input(text):
            raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
        if not isinstance(text_pair, (list, tuple)):
            raise ValueError(
                "Words must be of type `List[str]` (single pretokenized example), "
                "or `List[List[str]]` (batch of pretokenized examples)."
            )
    else:
        # in case only text is provided => must be words
        if not isinstance(text, (list, tuple)):
            raise ValueError(
                "Words must be of type `List[str]` (single pretokenized example), "
                "or `List[List[str]]` (batch of pretokenized examples)."
            )

    if text_pair is not None:
        is_batched = isinstance(text, (list, tuple))
    else:
        is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))

    words = text if text_pair is None else text_pair
    if boxes is None:
        raise ValueError("You must provide corresponding bounding boxes")
    if is_batched:
        if len(words) != len(boxes):
            raise ValueError("You must provide words and boxes for an equal amount of examples")
        for words_example, boxes_example in zip(words, boxes):
            if len(words_example) != len(boxes_example):
                raise ValueError("You must provide as many words as there are bounding boxes")
    else:
        if len(words) != len(boxes):
            raise ValueError("You must provide as many words as there are bounding boxes")

    if is_batched:
        if text_pair is not None and len(text) != len(text_pair):
            raise ValueError(
                f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
                f" {len(text_pair)}."
            )
        batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
        is_pair = bool(text_pair is not None)
        return self.batch_encode_plus(
            batch_text_or_text_pairs=batch_text_or_text_pairs,
            is_pair=is_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            stride=stride,
            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,
        boxes=boxes,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding=padding,
        truncation=truncation,
        max_length=max_length,
        stride=stride,
        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.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.__init__(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', cls_token_box=[0, 0, 0, 0], sep_token_box=[1000, 1000, 1000, 1000], pad_token_box=[0, 0, 0, 0], pad_token_label=-100, only_label_first_subword=True, tokenize_chinese_chars=True, strip_accents=None, model_max_length=512, additional_special_tokens=None, **kwargs)

Initializes a LayoutLMv2Tokenizer object.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

The path to the vocabulary file.

TYPE: str

do_lower_case

Whether to lowercase the input text. Defaults to True.

TYPE: bool DEFAULT: True

do_basic_tokenize

Whether to perform basic tokenization. Defaults to True.

TYPE: bool DEFAULT: True

never_split

List of tokens that should not be split. Defaults to None.

TYPE: list DEFAULT: None

unk_token

The unknown token. Defaults to '[UNK]'.

TYPE: str DEFAULT: '[UNK]'

sep_token

The separator token. Defaults to '[SEP]'.

TYPE: str DEFAULT: '[SEP]'

pad_token

The padding token. Defaults to '[PAD]'.

TYPE: str DEFAULT: '[PAD]'

cls_token

The classification token. Defaults to '[CLS]'.

TYPE: str DEFAULT: '[CLS]'

mask_token

The masking token. Defaults to '[MASK]'.

TYPE: str DEFAULT: '[MASK]'

cls_token_box

The bounding box coordinates for the classification token. Defaults to [0, 0, 0, 0].

TYPE: list DEFAULT: [0, 0, 0, 0]

sep_token_box

The bounding box coordinates for the separator token. Defaults to [1000, 1000, 1000, 1000].

TYPE: list DEFAULT: [1000, 1000, 1000, 1000]

pad_token_box

The bounding box coordinates for the padding token. Defaults to [0, 0, 0, 0].

TYPE: list DEFAULT: [0, 0, 0, 0]

pad_token_label

The label for the padding token. Defaults to -100.

TYPE: int DEFAULT: -100

only_label_first_subword

Whether to only label the first subword. Defaults to True.

TYPE: bool DEFAULT: True

tokenize_chinese_chars

Whether to tokenize Chinese characters. Defaults to True.

TYPE: bool DEFAULT: True

strip_accents

The accents to strip. Defaults to None.

TYPE: str DEFAULT: None

model_max_length

The maximum length of the model. Defaults to 512.

TYPE: int DEFAULT: 512

additional_special_tokens

Additional special tokens. Defaults to None.

TYPE: list DEFAULT: None

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ValueError

If the vocabulary file cannot be found at the specified path.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def __init__(
        self,
        vocab_file,
        do_lower_case=True,
        do_basic_tokenize=True,
        never_split=None,
        unk_token="[UNK]",
        sep_token="[SEP]",
        pad_token="[PAD]",
        cls_token="[CLS]",
        mask_token="[MASK]",
        cls_token_box=[0, 0, 0, 0],
        sep_token_box=[1000, 1000, 1000, 1000],
        pad_token_box=[0, 0, 0, 0],
        pad_token_label=-100,
        only_label_first_subword=True,
        tokenize_chinese_chars=True,
        strip_accents=None,
        model_max_length: int = 512,
        additional_special_tokens: Optional[List[str]] = None,
        **kwargs,
):
    """
    Initializes a LayoutLMv2Tokenizer object.

    Args:
        self: The instance of the class.
        vocab_file (str): The path to the vocabulary file.
        do_lower_case (bool, optional): Whether to lowercase the input text. Defaults to True.
        do_basic_tokenize (bool, optional): Whether to perform basic tokenization. Defaults to True.
        never_split (list, optional): List of tokens that should not be split. Defaults to None.
        unk_token (str, optional): The unknown token. Defaults to '[UNK]'.
        sep_token (str, optional): The separator token. Defaults to '[SEP]'.
        pad_token (str, optional): The padding token. Defaults to '[PAD]'.
        cls_token (str, optional): The classification token. Defaults to '[CLS]'.
        mask_token (str, optional): The masking token. Defaults to '[MASK]'.
        cls_token_box (list, optional): The bounding box coordinates for the classification token. Defaults to [0, 0, 0, 0].
        sep_token_box (list, optional): The bounding box coordinates for the separator token. Defaults to [1000, 1000, 1000, 1000].
        pad_token_box (list, optional): The bounding box coordinates for the padding token. Defaults to [0, 0, 0, 0].
        pad_token_label (int, optional): The label for the padding token. Defaults to -100.
        only_label_first_subword (bool, optional): Whether to only label the first subword. Defaults to True.
        tokenize_chinese_chars (bool, optional): Whether to tokenize Chinese characters. Defaults to True.
        strip_accents (str, optional): The accents to strip. Defaults to None.
        model_max_length (int, optional): The maximum length of the model. Defaults to 512.
        additional_special_tokens (list, optional): Additional special tokens. Defaults to None.

    Returns:
        None

    Raises:
        ValueError: If the vocabulary file cannot be found at the specified path.
    """
    sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
    unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
    pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
    cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
    mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token

    if not os.path.isfile(vocab_file):
        raise ValueError(
            f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
            " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
        )
    self.vocab = load_vocab(vocab_file)
    self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
    self.do_basic_tokenize = do_basic_tokenize
    if do_basic_tokenize:
        self.basic_tokenizer = BasicTokenizer(
            do_lower_case=do_lower_case,
            never_split=never_split,
            tokenize_chinese_chars=tokenize_chinese_chars,
            strip_accents=strip_accents,
        )
    self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))

    # additional properties
    self.cls_token_box = cls_token_box
    self.sep_token_box = sep_token_box
    self.pad_token_box = pad_token_box
    self.pad_token_label = pad_token_label
    self.only_label_first_subword = only_label_first_subword
    super().__init__(
        do_lower_case=do_lower_case,
        do_basic_tokenize=do_basic_tokenize,
        never_split=never_split,
        unk_token=unk_token,
        sep_token=sep_token,
        pad_token=pad_token,
        cls_token=cls_token,
        mask_token=mask_token,
        cls_token_box=cls_token_box,
        sep_token_box=sep_token_box,
        pad_token_box=pad_token_box,
        pad_token_label=pad_token_label,
        only_label_first_subword=only_label_first_subword,
        tokenize_chinese_chars=tokenize_chinese_chars,
        strip_accents=strip_accents,
        model_max_length=model_max_length,
        additional_special_tokens=additional_special_tokens,
        **kwargs,
    )

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.batch_encode_plus(batch_text_or_text_pairs, is_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

Encodes a batch of text or text pairs using the LayoutLMv2 model.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2Tokenizer class.

TYPE: LayoutLMv2Tokenizer

batch_text_or_text_pairs

A list of input texts or text pairs to be encoded. The input can be either a single text, a text pair, or a pre-tokenized input.

TYPE: Union[List[TextInput], List[TextInputPair], List[PreTokenizedInput]]

is_pair

Indicates whether the input is a text pair. Defaults to None.

TYPE: bool DEFAULT: None

boxes

A list of bounding boxes for each token in the input. Defaults to None.

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

word_labels

A list of word labels for each token in the input. Defaults to None.

TYPE: Optional[Union[List[int], List[List[int]]]] DEFAULT: None

add_special_tokens

Indicates whether to add special tokens to the input. Defaults to True.

TYPE: bool DEFAULT: True

padding

Specifies the padding strategy to use. Defaults to False.

TYPE: Union[bool, str, PaddingStrategy] DEFAULT: False

truncation

Specifies the truncation strategy to use. Defaults to None.

TYPE: Union[bool, str, TruncationStrategy] DEFAULT: None

max_length

The maximum sequence length after tokenization. Defaults to None.

TYPE: Optional[int] DEFAULT: None

stride

The stride for splitting the input into multiple chunks. Defaults to 0.

TYPE: int DEFAULT: 0

pad_to_multiple_of

Pad the sequence length to a multiple of this value. Defaults to None.

TYPE: Optional[int] DEFAULT: None

return_tensors

Specifies the type of tensors to return. Defaults to None.

TYPE: Optional[Union[str, TensorType]] DEFAULT: None

return_token_type_ids

Indicates whether to return token type IDs. Defaults to None.

TYPE: Optional[bool] DEFAULT: None

return_attention_mask

Indicates whether to return attention masks. Defaults to None.

TYPE: Optional[bool] DEFAULT: None

return_overflowing_tokens

Indicates whether to return overflowing tokens. Defaults to False.

TYPE: bool DEFAULT: False

return_special_tokens_mask

Indicates whether to return a mask indicating the special tokens. Defaults to False.

TYPE: bool DEFAULT: False

return_offsets_mapping

Indicates whether to return the offsets mapping of tokens to original text. Defaults to False.

TYPE: bool DEFAULT: False

return_length

Indicates whether to return the lengths of encoded sequences. Defaults to False.

TYPE: bool DEFAULT: False

verbose

Indicates whether to print informative messages. Defaults to True.

TYPE: bool DEFAULT: True

**kwargs

Additional keyword arguments for customizing the encoding process.

DEFAULT: {}

RETURNS DESCRIPTION
BatchEncoding

A dictionary-like object containing the encoded batch, with the following keys:

  • 'input_ids': The input token IDs.
  • 'attention_mask': The attention mask indicating which tokens to attend to.
  • 'token_type_ids': The token type IDs indicating the segment type of each token.
  • 'overflowing_tokens': The list of overflowing tokens if return_overflowing_tokens=True.
  • 'special_tokens_mask': The mask indicating the special tokens if return_special_tokens_mask=True.
  • 'offset_mapping': The mapping of tokens to their corresponding positions in the original text if return_offsets_mapping=True.
  • 'length': The length of each encoded sequence if return_length=True.

TYPE: BatchEncoding

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def batch_encode_plus(
        self,
        batch_text_or_text_pairs: Union[
            List[TextInput],
            List[TextInputPair],
            List[PreTokenizedInput],
        ],
        is_pair: bool = None,
        boxes: Optional[List[List[List[int]]]] = None,
        word_labels: Optional[Union[List[int], List[List[int]]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> BatchEncoding:
    """
    Encodes a batch of text or text pairs using the LayoutLMv2 model.

    Args:
        self (LayoutLMv2Tokenizer): An instance of the LayoutLMv2Tokenizer class.
        batch_text_or_text_pairs (Union[List[TextInput], List[TextInputPair], List[PreTokenizedInput]]):
            A list of input texts or text pairs to be encoded. The input can be either a single text, a text
            pair, or a pre-tokenized input.
        is_pair (bool, optional): Indicates whether the input is a text pair. Defaults to None.
        boxes (Optional[List[List[List[int]]]], optional): A list of bounding boxes for each token in the input.
            Defaults to None.
        word_labels (Optional[Union[List[int], List[List[int]]]], optional): A list of word labels for each token
            in the input. Defaults to None.
        add_special_tokens (bool, optional): Indicates whether to add special tokens to the input. Defaults to True.
        padding (Union[bool, str, PaddingStrategy], optional): Specifies the padding strategy to use.
            Defaults to False.
        truncation (Union[bool, str, TruncationStrategy], optional): Specifies the truncation strategy to use.
            Defaults to None.
        max_length (Optional[int], optional): The maximum sequence length after tokenization. Defaults to None.
        stride (int, optional): The stride for splitting the input into multiple chunks. Defaults to 0.
        pad_to_multiple_of (Optional[int], optional): Pad the sequence length to a multiple of this value.
            Defaults to None.
        return_tensors (Optional[Union[str, TensorType]], optional): Specifies the type of tensors to return.
            Defaults to None.
        return_token_type_ids (Optional[bool], optional): Indicates whether to return token type IDs.
            Defaults to None.
        return_attention_mask (Optional[bool], optional): Indicates whether to return attention masks.
            Defaults to None.
        return_overflowing_tokens (bool, optional): Indicates whether to return overflowing tokens.
            Defaults to False.
        return_special_tokens_mask (bool, optional): Indicates whether to return a mask indicating the special tokens.
            Defaults to False.
        return_offsets_mapping (bool, optional): Indicates whether to return the offsets mapping of tokens to
            original text. Defaults to False.
        return_length (bool, optional): Indicates whether to return the lengths of encoded sequences.
            Defaults to False.
        verbose (bool, optional): Indicates whether to print informative messages. Defaults to True.
        **kwargs: Additional keyword arguments for customizing the encoding process.

    Returns:
        BatchEncoding:
            A dictionary-like object containing the encoded batch, with the following keys:

            - 'input_ids': The input token IDs.
            - 'attention_mask': The attention mask indicating which tokens to attend to.
            - 'token_type_ids': The token type IDs indicating the segment type of each token.
            - 'overflowing_tokens': The list of overflowing tokens if return_overflowing_tokens=True.
            - 'special_tokens_mask': The mask indicating the special tokens if return_special_tokens_mask=True.
            - 'offset_mapping': The mapping of tokens to their corresponding positions in the original text
            if return_offsets_mapping=True.
            - 'length': The length of each encoded sequence if return_length=True.

    Raises:
        None.
    """
    # 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,
    )

    return self._batch_encode_plus(
        batch_text_or_text_pairs=batch_text_or_text_pairs,
        is_pair=is_pair,
        boxes=boxes,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding_strategy=padding_strategy,
        truncation_strategy=truncation_strategy,
        max_length=max_length,
        stride=stride,
        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.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.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 BERT sequence has the following format:

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

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

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION
List[int]

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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 BERT sequence has the following format:

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

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

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """
    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + token_ids_1 + sep

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.convert_tokens_to_string(tokens)

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
408
409
410
411
def convert_tokens_to_string(self, tokens):
    """Converts a sequence of tokens (string) in a single string."""
    out_string = " ".join(tokens).replace(" ##", "").strip()
    return out_string

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

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

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

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

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

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
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. A BERT sequence
    pair mask has the following format:

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

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

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

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

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.encode(text, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

This method encodes the input text and returns a list of integer input ids.

PARAMETER DESCRIPTION
self

The LayoutLMv2Tokenizer instance.

text

The input text to encode. It can be either a TextInput object or a PreTokenizedInput object.

TYPE: Union[TextInput, PreTokenizedInput]

text_pair

The optional second input text to be encoded. It should be a PreTokenizedInput object.

TYPE: Optional[PreTokenizedInput] DEFAULT: None

boxes

The optional bounding boxes for each token in the input text. Each box is represented as a list of four integers [x_min, y_min, x_max, y_max].

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

word_labels

The optional word labels associated with each token in the input text. It should be a list of integers.

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

add_special_tokens

Whether to add special tokens like [CLS], [SEP], etc. Default is True.

TYPE: bool DEFAULT: True

padding

The padding strategy to apply. It can be a boolean value, a string, or a PaddingStrategy object. Default is False.

TYPE: Union[bool, str, PaddingStrategy] DEFAULT: False

truncation

The truncation strategy to apply. It can be a boolean value, a string, or a TruncationStrategy object. Default is None.

TYPE: Union[bool, str, TruncationStrategy] DEFAULT: None

max_length

The maximum length of the encoded sequence. If provided, the sequence is truncated or padded to this length.

TYPE: Optional[int] DEFAULT: None

stride

The stride used for tokenization. Default is 0.

TYPE: int DEFAULT: 0

pad_to_multiple_of

If specified, the sequence is padded to a multiple of this value.

TYPE: Optional[int] DEFAULT: None

return_tensors

The type of tensor to return. It can be a string or a TensorType object.

TYPE: Optional[Union[str, TensorType]] DEFAULT: None

return_token_type_ids

Whether to return token type ids.

TYPE: Optional[bool] DEFAULT: None

return_attention_mask

Whether to return attention mask.

TYPE: Optional[bool] DEFAULT: None

return_overflowing_tokens

Whether to return overflowing tokens.

TYPE: bool DEFAULT: False

return_special_tokens_mask

Whether to return special tokens mask.

TYPE: bool DEFAULT: False

return_offsets_mapping

Whether to return the mapping from tokens to character offsets.

TYPE: bool DEFAULT: False

return_length

Whether to return the length of the encoded inputs.

TYPE: bool DEFAULT: False

verbose

Whether to print verbose logs. Default is True.

TYPE: bool DEFAULT: True

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION
List[int]

List[int]: A list of integer input ids representing the encoded input text.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
def encode(
        self,
        text: Union[TextInput, PreTokenizedInput],
        text_pair: Optional[PreTokenizedInput] = None,
        boxes: Optional[List[List[int]]] = None,
        word_labels: Optional[List[int]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> List[int]:
    """
    This method encodes the input text and returns a list of integer input ids.

    Args:
        self: The LayoutLMv2Tokenizer instance.
        text (Union[TextInput, PreTokenizedInput]): The input text to encode. It can be either a TextInput object
            or a PreTokenizedInput object.
        text_pair (Optional[PreTokenizedInput]): The optional second input text to be encoded.
            It should be a PreTokenizedInput object.
        boxes (Optional[List[List[int]]]): The optional bounding boxes for each token in the input text.
            Each box is represented as a list of four integers [x_min, y_min, x_max, y_max].
        word_labels (Optional[List[int]]): The optional word labels associated with each token in the input text.
            It should be a list of integers.
        add_special_tokens (bool): Whether to add special tokens like [CLS], [SEP], etc. Default is True.
        padding (Union[bool, str, PaddingStrategy]): The padding strategy to apply.
            It can be a boolean value, a string, or a PaddingStrategy object. Default is False.
        truncation (Union[bool, str, TruncationStrategy]): The truncation strategy to apply.
            It can be a boolean value, a string, or a TruncationStrategy object. Default is None.
        max_length (Optional[int]): The maximum length of the encoded sequence.
            If provided, the sequence is truncated or padded to this length.
        stride (int): The stride used for tokenization. Default is 0.
        pad_to_multiple_of (Optional[int]): If specified, the sequence is padded to a multiple of this value.
        return_tensors (Optional[Union[str, TensorType]]): The type of tensor to return.
            It can be a string or a TensorType object.
        return_token_type_ids (Optional[bool]): Whether to return token type ids.
        return_attention_mask (Optional[bool]): Whether to return attention mask.
        return_overflowing_tokens (bool): Whether to return overflowing tokens.
        return_special_tokens_mask (bool): Whether to return special tokens mask.
        return_offsets_mapping (bool): Whether to return the mapping from tokens to character offsets.
        return_length (bool): Whether to return the length of the encoded inputs.
        verbose (bool): Whether to print verbose logs. Default is True.
        **kwargs: Additional keyword arguments.

    Returns:
        List[int]: A list of integer input ids representing the encoded input text.

    Raises:
        None.
    """
    encoded_inputs = self.encode_plus(
        text=text,
        text_pair=text_pair,
        boxes=boxes,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding=padding,
        truncation=truncation,
        max_length=max_length,
        stride=stride,
        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 encoded_inputs["input_ids"]

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.encode_plus(text, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated, __call__ should be used instead.

PARAMETER DESCRIPTION
text

The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.

TYPE: `str`, `List[str]`, `List[List[str]]`

text_pair

Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a list of list of strings (words of a batch of examples).

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def encode_plus(
        self,
        text: Union[TextInput, PreTokenizedInput],
        text_pair: Optional[PreTokenizedInput] = None,
        boxes: Optional[List[List[int]]] = None,
        word_labels: Optional[List[int]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> BatchEncoding:
    """
    Tokenize and prepare for the model a sequence or a pair of sequences.
    .. warning:: This method is deprecated, `__call__` should be used instead.

    Args:
        text (`str`, `List[str]`, `List[List[str]]`):
            The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
        text_pair (`List[str]` or `List[int]`, *optional*):
            Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
            list of list of strings (words of a batch of examples).
    """
    # 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,
    )

    return self._encode_plus(
        text=text,
        boxes=boxes,
        text_pair=text_pair,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding_strategy=padding_strategy,
        truncation_strategy=truncation_strategy,
        max_length=max_length,
        stride=stride,
        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.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.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/layoutlmv2/tokenization_layoutlmv2.py
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
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 not None:
        return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
    return [1] + ([0] * len(token_ids_0)) + [1]

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.get_vocab()

Returns the combined vocabulary of the LayoutLMv2Tokenizer instance and any additional tokens that have been added.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Tokenizer class.

TYPE: LayoutLMv2Tokenizer

RETURNS DESCRIPTION
dict

A dictionary representing the combined vocabulary of the LayoutLMv2Tokenizer instance and any additional tokens that have been added.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def get_vocab(self):
    """
    Returns the combined vocabulary of the LayoutLMv2Tokenizer instance and any additional tokens that have been added.

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

    Returns:
        dict: A dictionary representing the combined vocabulary of the LayoutLMv2Tokenizer instance
            and any additional tokens that have been added.

    Raises:
        None.

    """
    return dict(self.vocab, **self.added_tokens_encoder)

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.prepare_for_model(text, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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 or a pair of sequences 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 text_pair 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.

Word-level boxes are turned into token-level bbox. If provided, word-level word_labels are turned into token-level labels. The word label is used for the first token of the word, while remaining tokens are labeled with -100, such that they will be ignored by the loss function.

PARAMETER DESCRIPTION
text

The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.

TYPE: `str`, `List[str]`, `List[List[str]]`

text_pair

Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a list of list of strings (words of a batch of examples).

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def prepare_for_model(
        self,
        text: Union[TextInput, PreTokenizedInput],
        text_pair: Optional[PreTokenizedInput] = None,
        boxes: Optional[List[List[int]]] = None,
        word_labels: Optional[List[int]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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 or a pair of sequences 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 *text_pair* 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.

    Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
    token-level `labels`. The word label is used for the first token of the word, while remaining tokens are
    labeled with -100, such that they will be ignored by the loss function.

    Args:
        text (`str`, `List[str]`, `List[List[str]]`):
            The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
        text_pair (`List[str]` or `List[int]`, *optional*):
            Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
            list of list of strings (words of a batch of examples).
    """
    # 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,
    )

    tokens = []
    pair_tokens = []
    token_boxes = []
    pair_token_boxes = []
    labels = []

    if text_pair is None:
        if word_labels is None:
            # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)
            for word, box in zip(text, boxes):
                if len(word) < 1:  # skip empty words
                    continue
                word_tokens = self.tokenize(word)
                tokens.extend(word_tokens)
                token_boxes.extend([box] * len(word_tokens))
        else:
            # CASE 2: token classification (training)
            for word, box, label in zip(text, boxes, word_labels):
                if len(word) < 1:  # skip empty words
                    continue
                word_tokens = self.tokenize(word)
                tokens.extend(word_tokens)
                token_boxes.extend([box] * len(word_tokens))
                if self.only_label_first_subword:
                    # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                    labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
                else:
                    labels.extend([label] * len(word_tokens))
    else:
        # CASE 3: document visual question answering (inference)
        # text = question
        # text_pair = words
        tokens = self.tokenize(text)
        token_boxes = [self.pad_token_box for _ in range(len(tokens))]

        for word, box in zip(text_pair, boxes):
            if len(word) < 1:  # skip empty words
                continue
            word_tokens = self.tokenize(word)
            pair_tokens.extend(word_tokens)
            pair_token_boxes.extend([box] * len(word_tokens))

    # Create ids + pair_ids
    ids = self.convert_tokens_to_ids(tokens)
    pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else 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`."
        )

    # Compute the total size of the returned encodings
    pair = bool(pair_ids is not None)
    len_ids = len(ids)
    len_pair_ids = len(pair_ids) if pair else 0
    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
    overflowing_tokens = []
    overflowing_token_boxes = []
    overflowing_labels = []
    if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
        (
            ids,
            token_boxes,
            pair_ids,
            pair_token_boxes,
            labels,
            overflowing_tokens,
            overflowing_token_boxes,
            overflowing_labels,
        ) = self.truncate_sequences(
            ids,
            token_boxes,
            pair_ids=pair_ids,
            pair_token_boxes=pair_token_boxes,
            labels=labels,
            num_tokens_to_remove=total_len - max_length,
            truncation_strategy=truncation_strategy,
            stride=stride,
        )

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

    # 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 = {}

    if return_overflowing_tokens:
        encoded_inputs["overflowing_tokens"] = overflowing_tokens
        encoded_inputs["overflowing_token_boxes"] = overflowing_token_boxes
        encoded_inputs["overflowing_labels"] = overflowing_labels
        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)
        token_boxes = [self.cls_token_box] + token_boxes + [self.sep_token_box]
        if pair_token_boxes:
            pair_token_boxes = pair_token_boxes + [self.sep_token_box]
        if labels:
            labels = [self.pad_token_label] + labels + [self.pad_token_label]
    else:
        sequence = ids + pair_ids if pair else ids
        token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])

    # Build output dictionary
    encoded_inputs["input_ids"] = sequence
    encoded_inputs["bbox"] = token_boxes + pair_token_boxes
    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)

    if labels:
        encoded_inputs["labels"] = labels

    # 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,
            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.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary to a file in the specified directory.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2Tokenizer class.

TYPE: LayoutLMv2Tokenizer

save_directory

The directory where the vocabulary file will be saved.

TYPE: str

filename_prefix

A prefix to be added to the filename. Defaults to None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the file path of the saved vocabulary.

RAISES DESCRIPTION
IOError

If an I/O error occurs while writing the vocabulary file.

ValueError

If the provided save_directory is invalid or if the vocabulary indices are not consecutive.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary to a file in the specified directory.

    Args:
        self (LayoutLMv2Tokenizer): The instance of the LayoutLMv2Tokenizer class.
        save_directory (str): The directory where the vocabulary file will be saved.
        filename_prefix (Optional[str]): A prefix to be added to the filename. Defaults to None.

    Returns:
        Tuple[str]: A tuple containing the file path of the saved vocabulary.

    Raises:
        IOError: If an I/O error occurs while writing the vocabulary file.
        ValueError: If the provided save_directory is invalid or if the vocabulary indices are not consecutive.

    """
    index = 0
    if os.path.isdir(save_directory):
        vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )
    else:
        vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
    with open(vocab_file, "w", encoding="utf-8") as writer:
        for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
            if index != token_index:
                logger.warning(
                    f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
                    " Please check that the vocabulary is not corrupted!"
                )
                index = token_index
            writer.write(token + "\n")
            index += 1
    return (vocab_file,)

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.LayoutLMv2Tokenizer.truncate_sequences(ids, token_boxes, pair_ids=None, pair_token_boxes=None, labels=None, num_tokens_to_remove=0, truncation_strategy='longest_first', stride=0)

Truncates a sequence pair in-place following the strategy.

PARAMETER DESCRIPTION
ids

Tokenized input ids of the first sequence. Can be obtained from a string by chaining the tokenize and convert_tokens_to_ids methods.

TYPE: `List[int]`

token_boxes

Bounding boxes of the first sequence.

TYPE: `List[List[int]]`

pair_ids

Tokenized input ids of the second sequence. Can be obtained from a string by chaining the tokenize and convert_tokens_to_ids methods.

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

pair_token_boxes

Bounding boxes of the second sequence.

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

labels

Labels of the first sequence (for token classification tasks).

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

num_tokens_to_remove

Number of tokens to remove using the truncation strategy.

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

truncation_strategy

The strategy to follow for truncation. Can be:

  • 'longest_first': Truncate 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. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
  • 'only_first': Truncate 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. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  • 'only_second': Truncate 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. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  • 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).

TYPE: `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False` DEFAULT: 'longest_first'

stride

If set to a positive number, the overflowing tokens returned will contain some tokens from the main sequence returned. The value of this argument defines the number of additional tokens.

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

RETURNS DESCRIPTION
Tuple[List[int], List[int], List[int]]

Tuple[List[int], List[int], List[int]]: The truncated ids, the truncated pair_ids and the list of overflowing tokens. Note: The longest_first strategy returns empty list of overflowing tokens if a pair of sequences (or a batch of pairs) is provided.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.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
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
def truncate_sequences(
        self,
        ids: List[int],
        token_boxes: List[List[int]],
        pair_ids: Optional[List[int]] = None,
        pair_token_boxes: Optional[List[List[int]]] = None,
        labels: Optional[List[int]] = None,
        num_tokens_to_remove: int = 0,
        truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
        stride: int = 0,
) -> Tuple[List[int], List[int], List[int]]:
    """
    Truncates a sequence pair in-place following the strategy.

    Args:
        ids (`List[int]`):
            Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
            `convert_tokens_to_ids` methods.
        token_boxes (`List[List[int]]`):
            Bounding boxes of the first sequence.
        pair_ids (`List[int]`, *optional*):
            Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
            and `convert_tokens_to_ids` methods.
        pair_token_boxes (`List[List[int]]`, *optional*):
            Bounding boxes of the second sequence.
        labels (`List[int]`, *optional*):
            Labels of the first sequence (for token classification tasks).
        num_tokens_to_remove (`int`, *optional*, defaults to 0):
            Number of tokens to remove using the truncation strategy.
        truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
            The strategy to follow for truncation. Can be:

            - `'longest_first'`: Truncate 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. This will truncate
            token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
            batch of pairs) is provided.
            - `'only_first'`: Truncate 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. This will only
            truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `'only_second'`: Truncate 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. This will only
            truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
            than the model maximum admissible input size).
        stride (`int`, *optional*, defaults to 0):
            If set to a positive number, the overflowing tokens returned will contain some tokens from the main
            sequence returned. The value of this argument defines the number of additional tokens.

    Returns:
        `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
            overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
            of sequences (or a batch of pairs) is provided.
    """
    if num_tokens_to_remove <= 0:
        return ids, token_boxes, pair_ids, pair_token_boxes, labels, [], [], []

    if not isinstance(truncation_strategy, TruncationStrategy):
        truncation_strategy = TruncationStrategy(truncation_strategy)

    overflowing_tokens = []
    overflowing_token_boxes = []
    overflowing_labels = []
    if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
            truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
    ):
        if len(ids) > num_tokens_to_remove:
            window_len = min(len(ids), stride + num_tokens_to_remove)
            overflowing_tokens = ids[-window_len:]
            overflowing_token_boxes = token_boxes[-window_len:]
            overflowing_labels = labels[-window_len:]
            ids = ids[:-num_tokens_to_remove]
            token_boxes = token_boxes[:-num_tokens_to_remove]
            labels = labels[:-num_tokens_to_remove]
        else:
            error_msg = (
                f"We need to remove {num_tokens_to_remove} to truncate the input "
                f"but the first sequence has a length {len(ids)}. "
            )
            if truncation_strategy == TruncationStrategy.ONLY_FIRST:
                error_msg = (
                        error_msg + "Please select another truncation strategy than "
                                    f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
                )
            logger.error(error_msg)
    elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
        logger.warning(
            "Be aware, overflowing tokens are not returned for the setting you have chosen,"
            f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
            "truncation strategy. So the returned list will always be empty even if some "
            "tokens have been removed."
        )
        for _ in range(num_tokens_to_remove):
            if pair_ids is None or len(ids) > len(pair_ids):
                ids = ids[:-1]
                token_boxes = token_boxes[:-1]
                labels = labels[:-1]
            else:
                pair_ids = pair_ids[:-1]
                pair_token_boxes = pair_token_boxes[:-1]
    elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
        if len(pair_ids) > num_tokens_to_remove:
            window_len = min(len(pair_ids), stride + num_tokens_to_remove)
            overflowing_tokens = pair_ids[-window_len:]
            overflowing_token_boxes = pair_token_boxes[-window_len:]
            pair_ids = pair_ids[:-num_tokens_to_remove]
            pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
        else:
            logger.error(
                f"We need to remove {num_tokens_to_remove} to truncate the input "
                f"but the second sequence has a length {len(pair_ids)}. "
                f"Please select another truncation strategy than {truncation_strategy}, "
                "for instance 'longest_first' or 'only_first'."
            )

    return (
        ids,
        token_boxes,
        pair_ids,
        pair_token_boxes,
        labels,
        overflowing_tokens,
        overflowing_token_boxes,
        overflowing_labels,
    )

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.WordpieceTokenizer

Runs WordPiece tokenization.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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 WordpieceTokenizer:
    """Runs WordPiece tokenization."""
    def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
        """
        Initializes a new instance of the WordpieceTokenizer class.

        Args:
            self (WordpieceTokenizer): The instance of the WordpieceTokenizer class.
            vocab (list): A list of strings representing the vocabulary.
            unk_token (str): The unknown token to be used for out-of-vocabulary words.
            max_input_chars_per_word (int, optional): The maximum number of characters per word. Defaults to 100.

        Returns:
            None.

        Raises:
            None.

        """
        self.vocab = vocab
        self.unk_token = unk_token
        self.max_input_chars_per_word = max_input_chars_per_word

    def tokenize(self, text):
        """
        Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
        tokenization using the given vocabulary.

        For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.

        Args:
            text: A single token or whitespace separated tokens. This should have
                already been passed through *BasicTokenizer*.

        Returns:
            A list of wordpiece tokens.
        """
        output_tokens = []
        for token in whitespace_tokenize(text):
            chars = list(token)
            if len(chars) > self.max_input_chars_per_word:
                output_tokens.append(self.unk_token)
                continue

            is_bad = False
            start = 0
            sub_tokens = []
            while start < len(chars):
                end = len(chars)
                cur_substr = None
                while start < end:
                    substr = "".join(chars[start:end])
                    if start > 0:
                        substr = "##" + substr
                    if substr in self.vocab:
                        cur_substr = substr
                        break
                    end -= 1
                if cur_substr is None:
                    is_bad = True
                    break
                sub_tokens.append(cur_substr)
                start = end

            if is_bad:
                output_tokens.append(self.unk_token)
            else:
                output_tokens.extend(sub_tokens)
        return output_tokens

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.WordpieceTokenizer.__init__(vocab, unk_token, max_input_chars_per_word=100)

Initializes a new instance of the WordpieceTokenizer class.

PARAMETER DESCRIPTION
self

The instance of the WordpieceTokenizer class.

TYPE: WordpieceTokenizer

vocab

A list of strings representing the vocabulary.

TYPE: list

unk_token

The unknown token to be used for out-of-vocabulary words.

TYPE: str

max_input_chars_per_word

The maximum number of characters per word. Defaults to 100.

TYPE: int DEFAULT: 100

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
    """
    Initializes a new instance of the WordpieceTokenizer class.

    Args:
        self (WordpieceTokenizer): The instance of the WordpieceTokenizer class.
        vocab (list): A list of strings representing the vocabulary.
        unk_token (str): The unknown token to be used for out-of-vocabulary words.
        max_input_chars_per_word (int, optional): The maximum number of characters per word. Defaults to 100.

    Returns:
        None.

    Raises:
        None.

    """
    self.vocab = vocab
    self.unk_token = unk_token
    self.max_input_chars_per_word = max_input_chars_per_word

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.WordpieceTokenizer.tokenize(text)

Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary.

For example, input = "unaffable" wil return as output ["un", "##aff", "##able"].

PARAMETER DESCRIPTION
text

A single token or whitespace separated tokens. This should have already been passed through BasicTokenizer.

RETURNS DESCRIPTION

A list of wordpiece tokens.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
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 tokenize(self, text):
    """
    Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
    tokenization using the given vocabulary.

    For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.

    Args:
        text: A single token or whitespace separated tokens. This should have
            already been passed through *BasicTokenizer*.

    Returns:
        A list of wordpiece tokens.
    """
    output_tokens = []
    for token in whitespace_tokenize(text):
        chars = list(token)
        if len(chars) > self.max_input_chars_per_word:
            output_tokens.append(self.unk_token)
            continue

        is_bad = False
        start = 0
        sub_tokens = []
        while start < len(chars):
            end = len(chars)
            cur_substr = None
            while start < end:
                substr = "".join(chars[start:end])
                if start > 0:
                    substr = "##" + substr
                if substr in self.vocab:
                    cur_substr = substr
                    break
                end -= 1
            if cur_substr is None:
                is_bad = True
                break
            sub_tokens.append(cur_substr)
            start = end

        if is_bad:
            output_tokens.append(self.unk_token)
        else:
            output_tokens.extend(sub_tokens)
    return output_tokens

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.load_vocab(vocab_file)

Loads a vocabulary file into a dictionary.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
169
170
171
172
173
174
175
176
177
def load_vocab(vocab_file):
    """Loads a vocabulary file into a dictionary."""
    vocab = collections.OrderedDict()
    with open(vocab_file, "r", encoding="utf-8") as reader:
        tokens = reader.readlines()
    for index, token in enumerate(tokens):
        token = token.rstrip("\n")
        vocab[token] = index
    return vocab

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.subfinder(mylist, pattern)

PARAMETER DESCRIPTION
mylist

A list in which to search for the pattern.

pattern

A list that we are trying to find in mylist.

RETURNS DESCRIPTION

Conditional return: The first matching pattern found in mylist and its starting index. If no match is found, returns None and 0.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def subfinder(mylist, pattern):
    """
    Args:
        mylist: A list in which to search for the pattern.
        pattern: A list that we are trying to find in mylist.

    Returns:
        Conditional return:
            The first matching pattern found in mylist and its starting index.
            If no match is found, returns None and 0.
    """
    matches = []
    indices = []
    for idx, i in enumerate(range(len(mylist))):
        if mylist[i] == pattern[0] and mylist[i: i + len(pattern)] == pattern:
            matches.append(pattern)
            indices.append(idx)
    if matches:
        return matches[0], indices[0]
    return None, 0

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2.whitespace_tokenize(text)

Runs basic whitespace cleaning and splitting on a piece of text.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
180
181
182
183
184
185
186
def whitespace_tokenize(text):
    """Runs basic whitespace cleaning and splitting on a piece of text."""
    text = text.strip()
    if not text:
        return []
    tokens = text.split()
    return tokens

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast

Fast tokenization class for LayoutLMv2. It overwrites 2 methods of the slow tokenizer class, namely _batch_encode_plus and _encode_plus, in which the Rust tokenizer is used.

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast

Bases: PreTrainedTokenizerFast

Construct a "fast" LayoutLMv2 tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.

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

PARAMETER DESCRIPTION
vocab_file

File containing the vocabulary.

TYPE: `str` DEFAULT: None

do_lower_case

Whether or not to lowercase the input when tokenizing.

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

unk_token

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

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

sep_token

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

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

pad_token

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

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

cls_token

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

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

mask_token

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

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

cls_token_box

The bounding box to use for the special [CLS] token.

TYPE: `List[int]`, *optional*, defaults to `[0, 0, 0, 0]` DEFAULT: [0, 0, 0, 0]

sep_token_box

The bounding box to use for the special [SEP] token.

TYPE: `List[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]` DEFAULT: [1000, 1000, 1000, 1000]

pad_token_box

The bounding box to use for the special [PAD] token.

TYPE: `List[int]`, *optional*, defaults to `[0, 0, 0, 0]` DEFAULT: [0, 0, 0, 0]

pad_token_label

The label to use for padding tokens. Defaults to -100, which is the ignore_index of PyTorch's CrossEntropyLoss.

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

only_label_first_subword

Whether or not to only label the first subword, in case word labels are provided.

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

tokenize_chinese_chars

Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this issue).

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

strip_accents

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

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
class LayoutLMv2TokenizerFast(PreTrainedTokenizerFast):
    r"""
    Construct a "fast" LayoutLMv2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.

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

    Args:
        vocab_file (`str`):
            File containing the vocabulary.
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        unk_token (`str`, *optional*, defaults to `"[UNK]"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        sep_token (`str`, *optional*, defaults to `"[SEP]"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        pad_token (`str`, *optional*, defaults to `"[PAD]"`):
            The token used for padding, for example when batching sequences of different lengths.
        cls_token (`str`, *optional*, defaults to `"[CLS]"`):
            The classifier token which is used when doing sequence classification (classification of the whole sequence
            instead of per-token classification). It is the first token of the sequence when built with special tokens.
        mask_token (`str`, *optional*, defaults to `"[MASK]"`):
            The token used for masking values. This is the token used when training this model with masked language
            modeling. This is the token which the model will try to predict.
        cls_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
            The bounding box to use for the special [CLS] token.
        sep_token_box (`List[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
            The bounding box to use for the special [SEP] token.
        pad_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
            The bounding box to use for the special [PAD] token.
        pad_token_label (`int`, *optional*, defaults to -100):
            The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
            CrossEntropyLoss.
        only_label_first_subword (`bool`, *optional*, defaults to `True`):
            Whether or not to only label the first subword, in case word labels are provided.
        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
            Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
            issue](https://github.com/huggingface/transformers/issues/328)).
        strip_accents (`bool`, *optional*):
            Whether or not to strip all accents. If this option is not specified, then it will be determined by the
            value for `lowercase` (as in the original LayoutLMv2).
    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    slow_tokenizer_class = LayoutLMv2Tokenizer

    def __init__(
            self,
            vocab_file=None,
            tokenizer_file=None,
            do_lower_case=True,
            unk_token="[UNK]",
            sep_token="[SEP]",
            pad_token="[PAD]",
            cls_token="[CLS]",
            mask_token="[MASK]",
            cls_token_box=[0, 0, 0, 0],
            sep_token_box=[1000, 1000, 1000, 1000],
            pad_token_box=[0, 0, 0, 0],
            pad_token_label=-100,
            only_label_first_subword=True,
            tokenize_chinese_chars=True,
            strip_accents=None,
            **kwargs,
    ):
        """
        This method initializes an instance of the LayoutLMv2TokenizerFast class.

        Args:
            self: The instance of the class.
            vocab_file (str): Path to the vocabulary file. Defaults to None.
            tokenizer_file (str): Path to the tokenizer file. Defaults to None.
            do_lower_case (bool): Flag indicating whether to convert tokens to lowercase. Defaults to True.
            unk_token (str): The token representing unknown words. Defaults to '[UNK]'.
            sep_token (str): The separator token. Defaults to '[SEP]'.
            pad_token (str): The padding token. Defaults to '[PAD]'.
            cls_token (str): The classification token. Defaults to '[CLS]'.
            mask_token (str): The masking token. Defaults to '[MASK]'.
            cls_token_box (list): A list of four integer values representing the bounding box for
                the classification token. Defaults to [0, 0, 0, 0].
            sep_token_box (list): A list of four integer values representing the bounding box for
                the separator token. Defaults to [1000, 1000, 1000, 1000].
            pad_token_box (list): A list of four integer values representing the bounding box for
                the padding token. Defaults to [0, 0, 0, 0].
            pad_token_label (int): The label for padding tokens. Defaults to -100.
            only_label_first_subword (bool): Flag indicating whether to only label the first subword. Defaults to True.
            tokenize_chinese_chars (bool): Flag indicating whether to tokenize Chinese characters. Defaults to True.
            strip_accents (str): Method for stripping accents. Defaults to None.

        Returns:
            None.

        Raises:
            ValueError: If an invalid argument is provided.
            TypeError: If input types are incorrect.
            FileNotFoundError: If the specified vocab_file or tokenizer_file is not found.
            JSONDecodeError: If there is an issue decoding the pre_tok_state JSON.
            AttributeError: If there is an issue with setting the backend_tokenizer normalizer.
            KeyError: If required keys are missing in the pre_tok_state.
        """
        super().__init__(
            vocab_file,
            tokenizer_file=tokenizer_file,
            do_lower_case=do_lower_case,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            cls_token_box=cls_token_box,
            sep_token_box=sep_token_box,
            pad_token_box=pad_token_box,
            pad_token_label=pad_token_label,
            only_label_first_subword=only_label_first_subword,
            tokenize_chinese_chars=tokenize_chinese_chars,
            strip_accents=strip_accents,
            **kwargs,
        )

        pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
        if (
                pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
                or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
        ):
            pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
            pre_tok_state["lowercase"] = do_lower_case
            pre_tok_state["strip_accents"] = strip_accents
            self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)

        self.do_lower_case = do_lower_case

        # additional properties
        self.cls_token_box = cls_token_box
        self.sep_token_box = sep_token_box
        self.pad_token_box = pad_token_box
        self.pad_token_label = pad_token_label
        self.only_label_first_subword = only_label_first_subword

    def __call__(
            self,
            text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
            text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
            boxes: Union[List[List[int]], List[List[List[int]]]] = None,
            word_labels: Optional[Union[List[int], List[List[int]]]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> BatchEncoding:
        """
        Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
        sequences with word-level normalized bounding boxes and optional labels.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
                (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
                words).
            text_pair (`List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
                (pretokenized string).
            boxes (`List[List[int]]`, `List[List[List[int]]]`):
                Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
            word_labels (`List[int]`, `List[List[int]]`, *optional*):
                Word-level integer labels (for token classification tasks such as FUNSD, CORD).
        """
        # Input type checking for clearer error
        def _is_valid_text_input(t):
            if isinstance(t, str):
                # Strings are fine
                return True
            if isinstance(t, (list, tuple)):
                # List are fine as long as they are...
                if len(t) == 0:
                    # ... empty
                    return True
                if isinstance(t[0], str):
                    # ... list of strings
                    return True
                if isinstance(t[0], (list, tuple)):
                    # ... list with an empty list or with a list of strings
                    return len(t[0]) == 0 or isinstance(t[0][0], str)
            return False

        if text_pair is not None:
            # in case text + text_pair are provided, text = questions, text_pair = words
            if not _is_valid_text_input(text):
                raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
            if not isinstance(text_pair, (list, tuple)):
                raise ValueError(
                    "Words must be of type `List[str]` (single pretokenized example), "
                    "or `List[List[str]]` (batch of pretokenized examples)."
                )
        else:
            # in case only text is provided => must be words
            if not isinstance(text, (list, tuple)):
                raise ValueError(
                    "Words must be of type `List[str]` (single pretokenized example), "
                    "or `List[List[str]]` (batch of pretokenized examples)."
                )

        if text_pair is not None:
            is_batched = isinstance(text, (list, tuple))
        else:
            is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))

        words = text if text_pair is None else text_pair
        if boxes is None:
            raise ValueError("You must provide corresponding bounding boxes")
        if is_batched:
            if len(words) != len(boxes):
                raise ValueError("You must provide words and boxes for an equal amount of examples")
            for words_example, boxes_example in zip(words, boxes):
                if len(words_example) != len(boxes_example):
                    raise ValueError("You must provide as many words as there are bounding boxes")
        else:
            if len(words) != len(boxes):
                raise ValueError("You must provide as many words as there are bounding boxes")

        if is_batched:
            if text_pair is not None and len(text) != len(text_pair):
                raise ValueError(
                    f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
                    f" {len(text_pair)}."
                )
            batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
            is_pair = bool(text_pair is not None)
            return self.batch_encode_plus(
                batch_text_or_text_pairs=batch_text_or_text_pairs,
                is_pair=is_pair,
                boxes=boxes,
                word_labels=word_labels,
                add_special_tokens=add_special_tokens,
                padding=padding,
                truncation=truncation,
                max_length=max_length,
                stride=stride,
                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,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            stride=stride,
            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 batch_encode_plus(
            self,
            batch_text_or_text_pairs: Union[
                List[TextInput],
                List[TextInputPair],
                List[PreTokenizedInput],
            ],
            is_pair: bool = None,
            boxes: Optional[List[List[List[int]]]] = None,
            word_labels: Optional[Union[List[int], List[List[int]]]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> BatchEncoding:
        """
        This method encodes a batch of text or text pairs using LayoutLMv2TokenizerFast.

        Args:
            self: The instance of the LayoutLMv2TokenizerFast class.
            batch_text_or_text_pairs (List[TextInput] or List[TextInputPair] or List[PreTokenizedInput]):
                A list of text inputs or text pairs to be encoded.
            is_pair (bool, optional): Specifies whether the input is a text pair. Default is None.
            boxes (List[List[List[int]]], optional): Optional bounding boxes for text elements in the input text.
                Default is None.
            word_labels (List[int] or List[List[int]], optional): Optional word labels for the input text.
                Default is None.
            add_special_tokens (bool): Whether to add special tokens to the encoded inputs. Default is True.
            padding (bool or str or PaddingStrategy): Padding strategy to apply. Default is False.
            truncation (bool or str or TruncationStrategy, optional): Truncation strategy to apply. Default is None.
            max_length (int, optional): Maximum length of the encoded inputs. Default is None.
            stride (int): The stride to use for overflowing tokens. Default is 0.
            pad_to_multiple_of (int, optional): Pad the sequence length to a multiple of this value. Default is None.
            return_tensors (str or TensorType, optional): Specifies the tensor type to return. Default is None.
            return_token_type_ids (bool, optional): Whether to return token type IDs. Default is None.
            return_attention_mask (bool, optional): Whether to return attention masks. Default is None.
            return_overflowing_tokens (bool): Whether to return overflowing tokens. Default is False.
            return_special_tokens_mask (bool): Whether to return a special tokens mask. Default is False.
            return_offsets_mapping (bool): Whether to return offsets mapping. Default is False.
            return_length (bool): Whether to return the lengths of the encoded inputs. Default is False.
            verbose (bool): Verbosity flag. Default is True.
            **kwargs: Additional keyword arguments for customization.

        Returns:
            BatchEncoding: A dictionary-like object containing the encoded inputs with various attributes.

        Raises:
            None
        """
        # 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,
        )

        return self._batch_encode_plus(
            batch_text_or_text_pairs=batch_text_or_text_pairs,
            is_pair=is_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            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 tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
        """
        Tokenizes a given text using the LayoutLMv2TokenizerFast.

        Args:
            self (LayoutLMv2TokenizerFast): An instance of the LayoutLMv2TokenizerFast class.
            text (str): The input text to be tokenized.
            pair (str, optional): The second input text if tokenizing a pair of texts. Defaults to None.
            add_special_tokens (bool, optional): Whether to add special tokens to the input sequence. Defaults to False.
            **kwargs: Additional keyword arguments to be passed to the underlying tokenizer.

        Returns:
            List[str]: A list of tokens representing the tokenized input text.

        Raises:
            None.

        """
        batched_input = [(text, pair)] if pair else [text]
        encodings = self._tokenizer.encode_batch(
            batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
        )

        return encodings[0].tokens

    def encode_plus(
            self,
            text: Union[TextInput, PreTokenizedInput],
            text_pair: Optional[PreTokenizedInput] = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[int]] = None,
            add_special_tokens: bool = True,
            padding: Union[bool, str, PaddingStrategy] = False,
            truncation: Union[bool, str, TruncationStrategy] = None,
            max_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,
            **kwargs,
    ) -> BatchEncoding:
        """
        Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
        `__call__` should be used instead.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
            text_pair (`List[str]` or `List[int]`, *optional*):
                Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
                list of list of strings (words of a batch of examples).
        """
        # 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,
        )

        return self._encode_plus(
            text=text,
            boxes=boxes,
            text_pair=text_pair,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            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 _batch_encode_plus(
            self,
            batch_text_or_text_pairs: Union[
                List[TextInput],
                List[TextInputPair],
                List[PreTokenizedInput],
            ],
            is_pair: bool = None,
            boxes: Optional[List[List[List[int]]]] = None,
            word_labels: Optional[List[List[int]]] = 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,
            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_offsets_mapping: bool = False,
            return_length: bool = False,
            verbose: bool = True,
    ) -> BatchEncoding:
        """
        This method performs batch encoding for the LayoutLMv2TokenizerFast class.

        Args:
            self: The instance of the LayoutLMv2TokenizerFast class.
            batch_text_or_text_pairs (Union[List[TextInput], List[TextInputPair], List[PreTokenizedInput]]):
                A list of input text or text pairs to be encoded.
            is_pair (bool): A flag indicating whether the input consists of text pairs.
            boxes (Optional[List[List[List[int]]]): Optional bounding boxes for the input text or text pairs.
            word_labels (Optional[List[List[int]]]): Optional word labels for the input text or text pairs.
            add_special_tokens (bool): Flag to indicate whether to add special tokens during encoding.
            padding_strategy (PaddingStrategy): The strategy for padding the sequences.
            truncation_strategy (TruncationStrategy): The strategy for truncating the sequences.
            max_length (Optional[int]): The maximum length of the encoded sequences.
            stride (int): The stride for truncation.
            pad_to_multiple_of (Optional[int]): Value to pad the sequence length to a multiple of this value.
            return_tensors (Optional[str]): Optional flag to indicate the type of tensor to return.
            return_token_type_ids (Optional[bool]): Optional flag to indicate whether to return token type IDs.
            return_attention_mask (Optional[bool]): Optional flag to indicate whether to return attention masks.
            return_overflowing_tokens (bool): Flag to indicate whether to return overflowing tokens.
            return_special_tokens_mask (bool): Flag to indicate whether to return special tokens masks.
            return_offsets_mapping (bool): Flag to indicate whether to return offset mappings.
            return_length (bool): Flag to indicate whether to return the length of the encoded sequences.
            verbose (bool): Flag to indicate whether to display verbose output.

        Returns:
            BatchEncoding: A dictionary containing sanitized tokens and encodings.

        Raises:
            TypeError: If batch_text_or_text_pairs is not a list.
            ValueError: If the ID of a token is not recognized.
        """
        if not isinstance(batch_text_or_text_pairs, list):
            raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")

        # Set the truncation and padding strategy and restore the initial configuration
        self.set_truncation_and_padding(
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            pad_to_multiple_of=pad_to_multiple_of,
        )

        if is_pair:
            batch_text_or_text_pairs = [(text.split(), text_pair) for text, text_pair in batch_text_or_text_pairs]

        encodings = self._tokenizer.encode_batch(
            batch_text_or_text_pairs,
            add_special_tokens=add_special_tokens,
            is_pretokenized=True,  # we set this to True as LayoutLMv2 always expects pretokenized inputs
        )

        # Convert encoding to dict
        # `Tokens` has type: Tuple[
        #                       List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
        #                       List[EncodingFast]
        #                    ]
        # with nested dimensions corresponding to batch, overflows, sequence length
        tokens_and_encodings = [
            self._convert_encoding(
                encoding=encoding,
                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=True
                if word_labels is not None
                else return_offsets_mapping,  # we use offsets to create the labels
                return_length=return_length,
                verbose=verbose,
            )
            for encoding in encodings
        ]

        # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
        # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
        # (we say ~ because the number of overflow varies with the example in the batch)
        #
        # To match each overflowing sample with the original sample in the batch
        # we add an overflow_to_sample_mapping array (see below)
        sanitized_tokens = {}
        for key in tokens_and_encodings[0][0].keys():
            stack = [e for item, _ in tokens_and_encodings for e in item[key]]
            sanitized_tokens[key] = stack
        sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]

        # If returning overflowing tokens, we need to return a mapping
        # from the batch idx to the original sample
        if return_overflowing_tokens:
            overflow_to_sample_mapping = []
            for i, (toks, _) in enumerate(tokens_and_encodings):
                overflow_to_sample_mapping += [i] * len(toks["input_ids"])
            sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping

        for input_ids in sanitized_tokens["input_ids"]:
            self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)

        # create the token boxes
        token_boxes = []
        for batch_index in range(len(sanitized_tokens["input_ids"])):
            if return_overflowing_tokens:
                original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
            else:
                original_index = batch_index
            token_boxes_example = []
            for token_id, sequence_id, word_id in zip(
                    sanitized_tokens["input_ids"][batch_index],
                    sanitized_encodings[batch_index].sequence_ids,
                    sanitized_encodings[batch_index].word_ids,
            ):
                if word_id is not None:
                    if is_pair and sequence_id == 0:
                        token_boxes_example.append(self.pad_token_box)
                    else:
                        token_boxes_example.append(boxes[original_index][word_id])
                else:
                    if token_id == self.cls_token_id:
                        token_boxes_example.append(self.cls_token_box)
                    elif token_id == self.sep_token_id:
                        token_boxes_example.append(self.sep_token_box)
                    elif token_id == self.pad_token_id:
                        token_boxes_example.append(self.pad_token_box)
                    else:
                        raise ValueError("Id not recognized")
            token_boxes.append(token_boxes_example)

        sanitized_tokens["bbox"] = token_boxes

        # optionally, create the labels
        if word_labels is not None:
            labels = []
            for batch_index in range(len(sanitized_tokens["input_ids"])):
                if return_overflowing_tokens:
                    original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
                else:
                    original_index = batch_index
                labels_example = []
                for token_id, offset, word_id in zip(
                        sanitized_tokens["input_ids"][batch_index],
                        sanitized_tokens["offset_mapping"][batch_index],
                        sanitized_encodings[batch_index].word_ids,
                ):
                    if word_id is not None:
                        if self.only_label_first_subword:
                            if offset[0] == 0:
                                # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                                labels_example.append(word_labels[original_index][word_id])
                            else:
                                labels_example.append(self.pad_token_label)
                        else:
                            labels_example.append(word_labels[original_index][word_id])
                    else:
                        labels_example.append(self.pad_token_label)
                labels.append(labels_example)

            sanitized_tokens["labels"] = labels
            # finally, remove offsets if the user didn't want them
            if not return_offsets_mapping:
                del sanitized_tokens["offset_mapping"]

        return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)

    def _encode_plus(
            self,
            text: Union[TextInput, PreTokenizedInput],
            text_pair: Optional[PreTokenizedInput] = None,
            boxes: Optional[List[List[int]]] = None,
            word_labels: Optional[List[int]] = 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,
            stride: int = 0,
            pad_to_multiple_of: Optional[int] = None,
            return_tensors: Optional[bool] = 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:
        """
        This method encodes the input text and optional text pair into a batch of tokenized and encoded outputs.
        It provides various options for special tokens, padding and truncation strategies, and return types.

        Args:
            self: The instance of the LayoutLMv2TokenizerFast class.
            text (Union[TextInput, PreTokenizedInput]): The input text to be encoded.
                It can be either a plain TextInput or a PreTokenizedInput.
            text_pair (Optional[PreTokenizedInput]): Optional input text pair to be encoded. Defaults to None.
            boxes (Optional[List[List[int]]]): Optional bounding boxes for each token in the input text.
                Defaults to None.
            word_labels (Optional[List[int]]): Optional word labels for each token in the input text. Defaults to None.
            add_special_tokens (bool): Whether to add special tokens (e.g., [CLS], [SEP]) to the encoded output.
                Defaults to True.
            padding_strategy (PaddingStrategy): The padding strategy to use. Defaults to PaddingStrategy.DO_NOT_PAD.
            truncation_strategy (TruncationStrategy): The truncation strategy to use.
                Defaults to TruncationStrategy.DO_NOT_TRUNCATE.
            max_length (Optional[int]): The maximum length of the encoded output. Defaults to None.
            stride (int): The stride to use for overflowing tokens. Defaults to 0.
            pad_to_multiple_of (Optional[int]): The padding length will be a multiple of this value. Defaults to None.
            return_tensors (Optional[bool]): Whether to return the encoded output as PyTorch/TensorFlow tensors.
                Defaults to None.
            return_token_type_ids (Optional[bool]): Whether to return the token type IDs. Defaults to None.
            return_attention_mask (Optional[bool]): Whether to return the attention mask. Defaults to None.
            return_overflowing_tokens (bool): Whether to return overflowing tokens if the input length exceeds max_length.
                Defaults to False.
            return_special_tokens_mask (bool): Whether to return a mask indicating the position of special tokens.
                Defaults to False.
            return_offsets_mapping (bool): Whether to return the mapping from token indices to character offsets.
                Defaults to False.
            return_length (bool): Whether to return the length of each encoded sequence. Defaults to False.
            verbose (bool): Whether to enable verbose logging. Defaults to True.
            **kwargs: Additional keyword arguments for future extensibility.

        Returns:
            BatchEncoding: A dictionary-like object containing the encoded inputs with optional additional
                information such as token type IDs, attention mask, and more.

        Raises:
            None.
        """
        # make it a batched input
        # 2 options:
        # 1) only text, in case text must be a list of str
        # 2) text + text_pair, in which case text = str and text_pair a list of str
        batched_input = [(text, text_pair)] if text_pair else [text]
        batched_boxes = [boxes]
        batched_word_labels = [word_labels] if word_labels is not None else None
        batched_output = self._batch_encode_plus(
            batched_input,
            is_pair=bool(text_pair is not None),
            boxes=batched_boxes,
            word_labels=batched_word_labels,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            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 tensor is None, then we can remove the leading batch axis
        # Overflowing tokens are returned as a batch of output so we keep them in this case
        if return_tensors is None and not return_overflowing_tokens:
            batched_output = BatchEncoding(
                {
                    key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
                    for key, value in batched_output.items()
                },
                batched_output.encodings,
            )

        self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)

        return batched_output

    def _pad(
            self,
            encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
            max_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.
            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)
        """
        # Load from model defaults
        if return_attention_mask is None:
            return_attention_mask = "attention_mask" in self.model_input_names

        required_input = encoded_inputs[self.model_input_names[0]]

        if padding_strategy == PaddingStrategy.LONGEST:
            max_length = len(required_input)

        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

        needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length

        # Initialize attention mask if not present.
        if return_attention_mask and "attention_mask" not in encoded_inputs:
            encoded_inputs["attention_mask"] = [1] * len(required_input)

        if needs_to_be_padded:
            difference = max_length - len(required_input)
            if self.padding_side == "right":
                if return_attention_mask:
                    encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
                if "token_type_ids" in encoded_inputs:
                    encoded_inputs["token_type_ids"] = (
                            encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
                    )
                if "bbox" in encoded_inputs:
                    encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
                if "labels" in encoded_inputs:
                    encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
                if "special_tokens_mask" in encoded_inputs:
                    encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
                encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
            elif self.padding_side == "left":
                if return_attention_mask:
                    encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
                if "token_type_ids" in encoded_inputs:
                    encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
                        "token_type_ids"
                    ]
                if "bbox" in encoded_inputs:
                    encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
                if "labels" in encoded_inputs:
                    encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
                if "special_tokens_mask" in encoded_inputs:
                    encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
                encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
            else:
                raise ValueError("Invalid padding strategy:" + str(self.padding_side))

        return encoded_inputs

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

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

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

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """
        output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]

        if token_ids_1:
            output += token_ids_1 + [self.sep_token_id]

        return output

    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. A BERT sequence
        pair mask has the following format:

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

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

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

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

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary files of the LayoutLMv2TokenizerFast model.

        Args:
            self: Instance of the LayoutLMv2TokenizerFast class.
            save_directory (str): The directory where the vocabulary files will be saved.
            filename_prefix (Optional[str], optional): Prefix to be added to the filename of the vocabulary files.
                Defaults to None.

        Returns:
            Tuple[str]: A tuple containing the paths to the saved vocabulary files.

        Raises:
            This method does not raise any exceptions.
        """
        files = self._tokenizer.model.save(save_directory, name=filename_prefix)
        return tuple(files)

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.__call__(text, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences with word-level normalized bounding boxes and optional labels.

PARAMETER DESCRIPTION
text

The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings (words of a single example or questions of a batch of examples) or a list of list of strings (batch of words).

TYPE: `str`, `List[str]`, `List[List[str]]`

text_pair

The sequence or batch of sequences to be encoded. Each sequence should be a list of strings (pretokenized string).

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

boxes

Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.

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

word_labels

Word-level integer labels (for token classification tasks such as FUNSD, CORD).

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
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
def __call__(
        self,
        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
        text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
        boxes: Union[List[List[int]], List[List[List[int]]]] = None,
        word_labels: Optional[Union[List[int], List[List[int]]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> BatchEncoding:
    """
    Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
    sequences with word-level normalized bounding boxes and optional labels.

    Args:
        text (`str`, `List[str]`, `List[List[str]]`):
            The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
            (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
            words).
        text_pair (`List[str]`, `List[List[str]]`):
            The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
            (pretokenized string).
        boxes (`List[List[int]]`, `List[List[List[int]]]`):
            Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
        word_labels (`List[int]`, `List[List[int]]`, *optional*):
            Word-level integer labels (for token classification tasks such as FUNSD, CORD).
    """
    # Input type checking for clearer error
    def _is_valid_text_input(t):
        if isinstance(t, str):
            # Strings are fine
            return True
        if isinstance(t, (list, tuple)):
            # List are fine as long as they are...
            if len(t) == 0:
                # ... empty
                return True
            if isinstance(t[0], str):
                # ... list of strings
                return True
            if isinstance(t[0], (list, tuple)):
                # ... list with an empty list or with a list of strings
                return len(t[0]) == 0 or isinstance(t[0][0], str)
        return False

    if text_pair is not None:
        # in case text + text_pair are provided, text = questions, text_pair = words
        if not _is_valid_text_input(text):
            raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
        if not isinstance(text_pair, (list, tuple)):
            raise ValueError(
                "Words must be of type `List[str]` (single pretokenized example), "
                "or `List[List[str]]` (batch of pretokenized examples)."
            )
    else:
        # in case only text is provided => must be words
        if not isinstance(text, (list, tuple)):
            raise ValueError(
                "Words must be of type `List[str]` (single pretokenized example), "
                "or `List[List[str]]` (batch of pretokenized examples)."
            )

    if text_pair is not None:
        is_batched = isinstance(text, (list, tuple))
    else:
        is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))

    words = text if text_pair is None else text_pair
    if boxes is None:
        raise ValueError("You must provide corresponding bounding boxes")
    if is_batched:
        if len(words) != len(boxes):
            raise ValueError("You must provide words and boxes for an equal amount of examples")
        for words_example, boxes_example in zip(words, boxes):
            if len(words_example) != len(boxes_example):
                raise ValueError("You must provide as many words as there are bounding boxes")
    else:
        if len(words) != len(boxes):
            raise ValueError("You must provide as many words as there are bounding boxes")

    if is_batched:
        if text_pair is not None and len(text) != len(text_pair):
            raise ValueError(
                f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
                f" {len(text_pair)}."
            )
        batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
        is_pair = bool(text_pair is not None)
        return self.batch_encode_plus(
            batch_text_or_text_pairs=batch_text_or_text_pairs,
            is_pair=is_pair,
            boxes=boxes,
            word_labels=word_labels,
            add_special_tokens=add_special_tokens,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            stride=stride,
            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,
        boxes=boxes,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding=padding,
        truncation=truncation,
        max_length=max_length,
        stride=stride,
        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.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.__init__(vocab_file=None, tokenizer_file=None, do_lower_case=True, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', cls_token_box=[0, 0, 0, 0], sep_token_box=[1000, 1000, 1000, 1000], pad_token_box=[0, 0, 0, 0], pad_token_label=-100, only_label_first_subword=True, tokenize_chinese_chars=True, strip_accents=None, **kwargs)

This method initializes an instance of the LayoutLMv2TokenizerFast class.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

Path to the vocabulary file. Defaults to None.

TYPE: str DEFAULT: None

tokenizer_file

Path to the tokenizer file. Defaults to None.

TYPE: str DEFAULT: None

do_lower_case

Flag indicating whether to convert tokens to lowercase. Defaults to True.

TYPE: bool DEFAULT: True

unk_token

The token representing unknown words. Defaults to '[UNK]'.

TYPE: str DEFAULT: '[UNK]'

sep_token

The separator token. Defaults to '[SEP]'.

TYPE: str DEFAULT: '[SEP]'

pad_token

The padding token. Defaults to '[PAD]'.

TYPE: str DEFAULT: '[PAD]'

cls_token

The classification token. Defaults to '[CLS]'.

TYPE: str DEFAULT: '[CLS]'

mask_token

The masking token. Defaults to '[MASK]'.

TYPE: str DEFAULT: '[MASK]'

cls_token_box

A list of four integer values representing the bounding box for the classification token. Defaults to [0, 0, 0, 0].

TYPE: list DEFAULT: [0, 0, 0, 0]

sep_token_box

A list of four integer values representing the bounding box for the separator token. Defaults to [1000, 1000, 1000, 1000].

TYPE: list DEFAULT: [1000, 1000, 1000, 1000]

pad_token_box

A list of four integer values representing the bounding box for the padding token. Defaults to [0, 0, 0, 0].

TYPE: list DEFAULT: [0, 0, 0, 0]

pad_token_label

The label for padding tokens. Defaults to -100.

TYPE: int DEFAULT: -100

only_label_first_subword

Flag indicating whether to only label the first subword. Defaults to True.

TYPE: bool DEFAULT: True

tokenize_chinese_chars

Flag indicating whether to tokenize Chinese characters. Defaults to True.

TYPE: bool DEFAULT: True

strip_accents

Method for stripping accents. Defaults to None.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If an invalid argument is provided.

TypeError

If input types are incorrect.

FileNotFoundError

If the specified vocab_file or tokenizer_file is not found.

JSONDecodeError

If there is an issue decoding the pre_tok_state JSON.

AttributeError

If there is an issue with setting the backend_tokenizer normalizer.

KeyError

If required keys are missing in the pre_tok_state.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def __init__(
        self,
        vocab_file=None,
        tokenizer_file=None,
        do_lower_case=True,
        unk_token="[UNK]",
        sep_token="[SEP]",
        pad_token="[PAD]",
        cls_token="[CLS]",
        mask_token="[MASK]",
        cls_token_box=[0, 0, 0, 0],
        sep_token_box=[1000, 1000, 1000, 1000],
        pad_token_box=[0, 0, 0, 0],
        pad_token_label=-100,
        only_label_first_subword=True,
        tokenize_chinese_chars=True,
        strip_accents=None,
        **kwargs,
):
    """
    This method initializes an instance of the LayoutLMv2TokenizerFast class.

    Args:
        self: The instance of the class.
        vocab_file (str): Path to the vocabulary file. Defaults to None.
        tokenizer_file (str): Path to the tokenizer file. Defaults to None.
        do_lower_case (bool): Flag indicating whether to convert tokens to lowercase. Defaults to True.
        unk_token (str): The token representing unknown words. Defaults to '[UNK]'.
        sep_token (str): The separator token. Defaults to '[SEP]'.
        pad_token (str): The padding token. Defaults to '[PAD]'.
        cls_token (str): The classification token. Defaults to '[CLS]'.
        mask_token (str): The masking token. Defaults to '[MASK]'.
        cls_token_box (list): A list of four integer values representing the bounding box for
            the classification token. Defaults to [0, 0, 0, 0].
        sep_token_box (list): A list of four integer values representing the bounding box for
            the separator token. Defaults to [1000, 1000, 1000, 1000].
        pad_token_box (list): A list of four integer values representing the bounding box for
            the padding token. Defaults to [0, 0, 0, 0].
        pad_token_label (int): The label for padding tokens. Defaults to -100.
        only_label_first_subword (bool): Flag indicating whether to only label the first subword. Defaults to True.
        tokenize_chinese_chars (bool): Flag indicating whether to tokenize Chinese characters. Defaults to True.
        strip_accents (str): Method for stripping accents. Defaults to None.

    Returns:
        None.

    Raises:
        ValueError: If an invalid argument is provided.
        TypeError: If input types are incorrect.
        FileNotFoundError: If the specified vocab_file or tokenizer_file is not found.
        JSONDecodeError: If there is an issue decoding the pre_tok_state JSON.
        AttributeError: If there is an issue with setting the backend_tokenizer normalizer.
        KeyError: If required keys are missing in the pre_tok_state.
    """
    super().__init__(
        vocab_file,
        tokenizer_file=tokenizer_file,
        do_lower_case=do_lower_case,
        unk_token=unk_token,
        sep_token=sep_token,
        pad_token=pad_token,
        cls_token=cls_token,
        mask_token=mask_token,
        cls_token_box=cls_token_box,
        sep_token_box=sep_token_box,
        pad_token_box=pad_token_box,
        pad_token_label=pad_token_label,
        only_label_first_subword=only_label_first_subword,
        tokenize_chinese_chars=tokenize_chinese_chars,
        strip_accents=strip_accents,
        **kwargs,
    )

    pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
    if (
            pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
            or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
    ):
        pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
        pre_tok_state["lowercase"] = do_lower_case
        pre_tok_state["strip_accents"] = strip_accents
        self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)

    self.do_lower_case = do_lower_case

    # additional properties
    self.cls_token_box = cls_token_box
    self.sep_token_box = sep_token_box
    self.pad_token_box = pad_token_box
    self.pad_token_label = pad_token_label
    self.only_label_first_subword = only_label_first_subword

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.batch_encode_plus(batch_text_or_text_pairs, is_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

This method encodes a batch of text or text pairs using LayoutLMv2TokenizerFast.

PARAMETER DESCRIPTION
self

The instance of the LayoutLMv2TokenizerFast class.

batch_text_or_text_pairs

A list of text inputs or text pairs to be encoded.

TYPE: List[TextInput] or List[TextInputPair] or List[PreTokenizedInput]

is_pair

Specifies whether the input is a text pair. Default is None.

TYPE: bool DEFAULT: None

boxes

Optional bounding boxes for text elements in the input text. Default is None.

TYPE: List[List[List[int]]] DEFAULT: None

word_labels

Optional word labels for the input text. Default is None.

TYPE: List[int] or List[List[int]] DEFAULT: None

add_special_tokens

Whether to add special tokens to the encoded inputs. Default is True.

TYPE: bool DEFAULT: True

padding

Padding strategy to apply. Default is False.

TYPE: bool or str or PaddingStrategy DEFAULT: False

truncation

Truncation strategy to apply. Default is None.

TYPE: bool or str or TruncationStrategy DEFAULT: None

max_length

Maximum length of the encoded inputs. Default is None.

TYPE: int DEFAULT: None

stride

The stride to use for overflowing tokens. Default is 0.

TYPE: int DEFAULT: 0

pad_to_multiple_of

Pad the sequence length to a multiple of this value. Default is None.

TYPE: int DEFAULT: None

return_tensors

Specifies the tensor type to return. Default is None.

TYPE: str or TensorType DEFAULT: None

return_token_type_ids

Whether to return token type IDs. Default is None.

TYPE: bool DEFAULT: None

return_attention_mask

Whether to return attention masks. Default is None.

TYPE: bool DEFAULT: None

return_overflowing_tokens

Whether to return overflowing tokens. Default is False.

TYPE: bool DEFAULT: False

return_special_tokens_mask

Whether to return a special tokens mask. Default is False.

TYPE: bool DEFAULT: False

return_offsets_mapping

Whether to return offsets mapping. Default is False.

TYPE: bool DEFAULT: False

return_length

Whether to return the lengths of the encoded inputs. Default is False.

TYPE: bool DEFAULT: False

verbose

Verbosity flag. Default is True.

TYPE: bool DEFAULT: True

**kwargs

Additional keyword arguments for customization.

DEFAULT: {}

RETURNS DESCRIPTION
BatchEncoding

A dictionary-like object containing the encoded inputs with various attributes.

TYPE: BatchEncoding

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
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
def batch_encode_plus(
        self,
        batch_text_or_text_pairs: Union[
            List[TextInput],
            List[TextInputPair],
            List[PreTokenizedInput],
        ],
        is_pair: bool = None,
        boxes: Optional[List[List[List[int]]]] = None,
        word_labels: Optional[Union[List[int], List[List[int]]]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> BatchEncoding:
    """
    This method encodes a batch of text or text pairs using LayoutLMv2TokenizerFast.

    Args:
        self: The instance of the LayoutLMv2TokenizerFast class.
        batch_text_or_text_pairs (List[TextInput] or List[TextInputPair] or List[PreTokenizedInput]):
            A list of text inputs or text pairs to be encoded.
        is_pair (bool, optional): Specifies whether the input is a text pair. Default is None.
        boxes (List[List[List[int]]], optional): Optional bounding boxes for text elements in the input text.
            Default is None.
        word_labels (List[int] or List[List[int]], optional): Optional word labels for the input text.
            Default is None.
        add_special_tokens (bool): Whether to add special tokens to the encoded inputs. Default is True.
        padding (bool or str or PaddingStrategy): Padding strategy to apply. Default is False.
        truncation (bool or str or TruncationStrategy, optional): Truncation strategy to apply. Default is None.
        max_length (int, optional): Maximum length of the encoded inputs. Default is None.
        stride (int): The stride to use for overflowing tokens. Default is 0.
        pad_to_multiple_of (int, optional): Pad the sequence length to a multiple of this value. Default is None.
        return_tensors (str or TensorType, optional): Specifies the tensor type to return. Default is None.
        return_token_type_ids (bool, optional): Whether to return token type IDs. Default is None.
        return_attention_mask (bool, optional): Whether to return attention masks. Default is None.
        return_overflowing_tokens (bool): Whether to return overflowing tokens. Default is False.
        return_special_tokens_mask (bool): Whether to return a special tokens mask. Default is False.
        return_offsets_mapping (bool): Whether to return offsets mapping. Default is False.
        return_length (bool): Whether to return the lengths of the encoded inputs. Default is False.
        verbose (bool): Verbosity flag. Default is True.
        **kwargs: Additional keyword arguments for customization.

    Returns:
        BatchEncoding: A dictionary-like object containing the encoded inputs with various attributes.

    Raises:
        None
    """
    # 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,
    )

    return self._batch_encode_plus(
        batch_text_or_text_pairs=batch_text_or_text_pairs,
        is_pair=is_pair,
        boxes=boxes,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding_strategy=padding_strategy,
        truncation_strategy=truncation_strategy,
        max_length=max_length,
        stride=stride,
        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.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.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 BERT sequence has the following format:

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

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

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

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

RETURNS DESCRIPTION

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    """
    Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    adding special tokens. A BERT sequence has the following format:

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

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

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """
    output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]

    if token_ids_1:
        output += token_ids_1 + [self.sep_token_id]

    return output

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

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

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

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

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

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
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
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. A BERT sequence
    pair mask has the following format:

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

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

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

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

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.encode_plus(text, text_pair=None, boxes=None, word_labels=None, add_special_tokens=True, padding=False, truncation=None, max_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, **kwargs)

Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated, __call__ should be used instead.

PARAMETER DESCRIPTION
text

The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.

TYPE: `str`, `List[str]`, `List[List[str]]`

text_pair

Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a list of list of strings (words of a batch of examples).

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

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
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
def encode_plus(
        self,
        text: Union[TextInput, PreTokenizedInput],
        text_pair: Optional[PreTokenizedInput] = None,
        boxes: Optional[List[List[int]]] = None,
        word_labels: Optional[List[int]] = None,
        add_special_tokens: bool = True,
        padding: Union[bool, str, PaddingStrategy] = False,
        truncation: Union[bool, str, TruncationStrategy] = None,
        max_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,
        **kwargs,
) -> BatchEncoding:
    """
    Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
    `__call__` should be used instead.

    Args:
        text (`str`, `List[str]`, `List[List[str]]`):
            The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
        text_pair (`List[str]` or `List[int]`, *optional*):
            Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
            list of list of strings (words of a batch of examples).
    """
    # 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,
    )

    return self._encode_plus(
        text=text,
        boxes=boxes,
        text_pair=text_pair,
        word_labels=word_labels,
        add_special_tokens=add_special_tokens,
        padding_strategy=padding_strategy,
        truncation_strategy=truncation_strategy,
        max_length=max_length,
        stride=stride,
        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.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary files of the LayoutLMv2TokenizerFast model.

PARAMETER DESCRIPTION
self

Instance of the LayoutLMv2TokenizerFast class.

save_directory

The directory where the vocabulary files will be saved.

TYPE: str

filename_prefix

Prefix to be added to the filename of the vocabulary files. Defaults to None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the paths to the saved vocabulary files.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary files of the LayoutLMv2TokenizerFast model.

    Args:
        self: Instance of the LayoutLMv2TokenizerFast class.
        save_directory (str): The directory where the vocabulary files will be saved.
        filename_prefix (Optional[str], optional): Prefix to be added to the filename of the vocabulary files.
            Defaults to None.

    Returns:
        Tuple[str]: A tuple containing the paths to the saved vocabulary files.

    Raises:
        This method does not raise any exceptions.
    """
    files = self._tokenizer.model.save(save_directory, name=filename_prefix)
    return tuple(files)

mindnlp.transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.tokenize(text, pair=None, add_special_tokens=False, **kwargs)

Tokenizes a given text using the LayoutLMv2TokenizerFast.

PARAMETER DESCRIPTION
self

An instance of the LayoutLMv2TokenizerFast class.

TYPE: LayoutLMv2TokenizerFast

text

The input text to be tokenized.

TYPE: str

pair

The second input text if tokenizing a pair of texts. Defaults to None.

TYPE: str DEFAULT: None

add_special_tokens

Whether to add special tokens to the input sequence. Defaults to False.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments to be passed to the underlying tokenizer.

DEFAULT: {}

RETURNS DESCRIPTION
List[str]

List[str]: A list of tokens representing the tokenized input text.

Source code in mindnlp/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
    """
    Tokenizes a given text using the LayoutLMv2TokenizerFast.

    Args:
        self (LayoutLMv2TokenizerFast): An instance of the LayoutLMv2TokenizerFast class.
        text (str): The input text to be tokenized.
        pair (str, optional): The second input text if tokenizing a pair of texts. Defaults to None.
        add_special_tokens (bool, optional): Whether to add special tokens to the input sequence. Defaults to False.
        **kwargs: Additional keyword arguments to be passed to the underlying tokenizer.

    Returns:
        List[str]: A list of tokens representing the tokenized input text.

    Raises:
        None.

    """
    batched_input = [(text, pair)] if pair else [text]
    encodings = self._tokenizer.encode_batch(
        batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
    )

    return encodings[0].tokens