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