configuration_layoutlmv3.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # coding=utf-8
  2. # Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """LayoutLMv3 model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import TYPE_CHECKING, Any, Optional
  19. from packaging import version
  20. from ...configuration_utils import PretrainedConfig
  21. from ...onnx import OnnxConfig
  22. from ...onnx.utils import compute_effective_axis_dimension
  23. from ...utils import logging
  24. if TYPE_CHECKING:
  25. from ...processing_utils import ProcessorMixin
  26. from ...utils import TensorType
  27. logger = logging.get_logger(__name__)
  28. class LayoutLMv3Config(PretrainedConfig):
  29. r"""
  30. This is the configuration class to store the configuration of a [`LayoutLMv3Model`]. It is used to instantiate an
  31. LayoutLMv3 model according to the specified arguments, defining the model architecture. Instantiating a
  32. configuration with the defaults will yield a similar configuration to that of the LayoutLMv3
  33. [microsoft/layoutlmv3-base](https://huggingface.co/microsoft/layoutlmv3-base) architecture.
  34. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  35. documentation from [`PretrainedConfig`] for more information.
  36. Args:
  37. vocab_size (`int`, *optional*, defaults to 50265):
  38. Vocabulary size of the LayoutLMv3 model. Defines the number of different tokens that can be represented by
  39. the `inputs_ids` passed when calling [`LayoutLMv3Model`].
  40. hidden_size (`int`, *optional*, defaults to 768):
  41. Dimension of the encoder layers and the pooler layer.
  42. num_hidden_layers (`int`, *optional*, defaults to 12):
  43. Number of hidden layers in the Transformer encoder.
  44. num_attention_heads (`int`, *optional*, defaults to 12):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. intermediate_size (`int`, *optional*, defaults to 3072):
  47. Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  48. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  49. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  50. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  51. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  52. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  53. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  54. The dropout ratio for the attention probabilities.
  55. max_position_embeddings (`int`, *optional*, defaults to 512):
  56. The maximum sequence length that this model might ever be used with. Typically set this to something large
  57. just in case (e.g., 512 or 1024 or 2048).
  58. type_vocab_size (`int`, *optional*, defaults to 2):
  59. The vocabulary size of the `token_type_ids` passed when calling [`LayoutLMv3Model`].
  60. initializer_range (`float`, *optional*, defaults to 0.02):
  61. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  62. layer_norm_eps (`float`, *optional*, defaults to 1e-5):
  63. The epsilon used by the layer normalization layers.
  64. max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
  65. The maximum value that the 2D position embedding might ever be used with. Typically set this to something
  66. large just in case (e.g., 1024).
  67. coordinate_size (`int`, *optional*, defaults to `128`):
  68. Dimension of the coordinate embeddings.
  69. shape_size (`int`, *optional*, defaults to `128`):
  70. Dimension of the width and height embeddings.
  71. has_relative_attention_bias (`bool`, *optional*, defaults to `True`):
  72. Whether or not to use a relative attention bias in the self-attention mechanism.
  73. rel_pos_bins (`int`, *optional*, defaults to 32):
  74. The number of relative position bins to be used in the self-attention mechanism.
  75. max_rel_pos (`int`, *optional*, defaults to 128):
  76. The maximum number of relative positions to be used in the self-attention mechanism.
  77. max_rel_2d_pos (`int`, *optional*, defaults to 256):
  78. The maximum number of relative 2D positions in the self-attention mechanism.
  79. rel_2d_pos_bins (`int`, *optional*, defaults to 64):
  80. The number of 2D relative position bins in the self-attention mechanism.
  81. has_spatial_attention_bias (`bool`, *optional*, defaults to `True`):
  82. Whether or not to use a spatial attention bias in the self-attention mechanism.
  83. visual_embed (`bool`, *optional*, defaults to `True`):
  84. Whether or not to add patch embeddings.
  85. input_size (`int`, *optional*, defaults to `224`):
  86. The size (resolution) of the images.
  87. num_channels (`int`, *optional*, defaults to `3`):
  88. The number of channels of the images.
  89. patch_size (`int`, *optional*, defaults to `16`)
  90. The size (resolution) of the patches.
  91. classifier_dropout (`float`, *optional*):
  92. The dropout ratio for the classification head.
  93. Example:
  94. ```python
  95. >>> from transformers import LayoutLMv3Config, LayoutLMv3Model
  96. >>> # Initializing a LayoutLMv3 microsoft/layoutlmv3-base style configuration
  97. >>> configuration = LayoutLMv3Config()
  98. >>> # Initializing a model (with random weights) from the microsoft/layoutlmv3-base style configuration
  99. >>> model = LayoutLMv3Model(configuration)
  100. >>> # Accessing the model configuration
  101. >>> configuration = model.config
  102. ```"""
  103. model_type = "layoutlmv3"
  104. def __init__(
  105. self,
  106. vocab_size=50265,
  107. hidden_size=768,
  108. num_hidden_layers=12,
  109. num_attention_heads=12,
  110. intermediate_size=3072,
  111. hidden_act="gelu",
  112. hidden_dropout_prob=0.1,
  113. attention_probs_dropout_prob=0.1,
  114. max_position_embeddings=512,
  115. type_vocab_size=2,
  116. initializer_range=0.02,
  117. layer_norm_eps=1e-5,
  118. pad_token_id=1,
  119. bos_token_id=0,
  120. eos_token_id=2,
  121. max_2d_position_embeddings=1024,
  122. coordinate_size=128,
  123. shape_size=128,
  124. has_relative_attention_bias=True,
  125. rel_pos_bins=32,
  126. max_rel_pos=128,
  127. rel_2d_pos_bins=64,
  128. max_rel_2d_pos=256,
  129. has_spatial_attention_bias=True,
  130. text_embed=True,
  131. visual_embed=True,
  132. input_size=224,
  133. num_channels=3,
  134. patch_size=16,
  135. classifier_dropout=None,
  136. **kwargs,
  137. ):
  138. super().__init__(
  139. vocab_size=vocab_size,
  140. hidden_size=hidden_size,
  141. num_hidden_layers=num_hidden_layers,
  142. num_attention_heads=num_attention_heads,
  143. intermediate_size=intermediate_size,
  144. hidden_act=hidden_act,
  145. hidden_dropout_prob=hidden_dropout_prob,
  146. attention_probs_dropout_prob=attention_probs_dropout_prob,
  147. max_position_embeddings=max_position_embeddings,
  148. type_vocab_size=type_vocab_size,
  149. initializer_range=initializer_range,
  150. layer_norm_eps=layer_norm_eps,
  151. pad_token_id=pad_token_id,
  152. bos_token_id=bos_token_id,
  153. eos_token_id=eos_token_id,
  154. **kwargs,
  155. )
  156. self.max_2d_position_embeddings = max_2d_position_embeddings
  157. self.coordinate_size = coordinate_size
  158. self.shape_size = shape_size
  159. self.has_relative_attention_bias = has_relative_attention_bias
  160. self.rel_pos_bins = rel_pos_bins
  161. self.max_rel_pos = max_rel_pos
  162. self.has_spatial_attention_bias = has_spatial_attention_bias
  163. self.rel_2d_pos_bins = rel_2d_pos_bins
  164. self.max_rel_2d_pos = max_rel_2d_pos
  165. self.text_embed = text_embed
  166. self.visual_embed = visual_embed
  167. self.input_size = input_size
  168. self.num_channels = num_channels
  169. self.patch_size = patch_size
  170. self.classifier_dropout = classifier_dropout
  171. class LayoutLMv3OnnxConfig(OnnxConfig):
  172. torch_onnx_minimum_version = version.parse("1.12")
  173. @property
  174. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  175. # The order of inputs is different for question answering and sequence classification
  176. if self.task in ["question-answering", "sequence-classification"]:
  177. return OrderedDict(
  178. [
  179. ("input_ids", {0: "batch", 1: "sequence"}),
  180. ("attention_mask", {0: "batch", 1: "sequence"}),
  181. ("bbox", {0: "batch", 1: "sequence"}),
  182. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  183. ]
  184. )
  185. else:
  186. return OrderedDict(
  187. [
  188. ("input_ids", {0: "batch", 1: "sequence"}),
  189. ("bbox", {0: "batch", 1: "sequence"}),
  190. ("attention_mask", {0: "batch", 1: "sequence"}),
  191. ("pixel_values", {0: "batch", 1: "num_channels"}),
  192. ]
  193. )
  194. @property
  195. def atol_for_validation(self) -> float:
  196. return 1e-5
  197. @property
  198. def default_onnx_opset(self) -> int:
  199. return 12
  200. def generate_dummy_inputs(
  201. self,
  202. processor: "ProcessorMixin",
  203. batch_size: int = -1,
  204. seq_length: int = -1,
  205. is_pair: bool = False,
  206. framework: Optional["TensorType"] = None,
  207. num_channels: int = 3,
  208. image_width: int = 40,
  209. image_height: int = 40,
  210. ) -> Mapping[str, Any]:
  211. """
  212. Generate inputs to provide to the ONNX exporter for the specific framework
  213. Args:
  214. processor ([`ProcessorMixin`]):
  215. The processor associated with this model configuration.
  216. batch_size (`int`, *optional*, defaults to -1):
  217. The batch size to export the model for (-1 means dynamic axis).
  218. seq_length (`int`, *optional*, defaults to -1):
  219. The sequence length to export the model for (-1 means dynamic axis).
  220. is_pair (`bool`, *optional*, defaults to `False`):
  221. Indicate if the input is a pair (sentence 1, sentence 2).
  222. framework (`TensorType`, *optional*, defaults to `None`):
  223. The framework (PyTorch or TensorFlow) that the processor will generate tensors for.
  224. num_channels (`int`, *optional*, defaults to 3):
  225. The number of channels of the generated images.
  226. image_width (`int`, *optional*, defaults to 40):
  227. The width of the generated images.
  228. image_height (`int`, *optional*, defaults to 40):
  229. The height of the generated images.
  230. Returns:
  231. Mapping[str, Any]: holding the kwargs to provide to the model's forward function
  232. """
  233. # A dummy image is used so OCR should not be applied
  234. setattr(processor.image_processor, "apply_ocr", False)
  235. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
  236. batch_size = compute_effective_axis_dimension(
  237. batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
  238. )
  239. # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
  240. token_to_add = processor.tokenizer.num_special_tokens_to_add(is_pair)
  241. seq_length = compute_effective_axis_dimension(
  242. seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
  243. )
  244. # Generate dummy inputs according to compute batch and sequence
  245. dummy_text = [[" ".join([processor.tokenizer.unk_token]) * seq_length]] * batch_size
  246. # Generate dummy bounding boxes
  247. dummy_bboxes = [[[48, 84, 73, 128]]] * batch_size
  248. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
  249. # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
  250. dummy_image = self._generate_dummy_images(batch_size, num_channels, image_height, image_width)
  251. inputs = dict(
  252. processor(
  253. dummy_image,
  254. text=dummy_text,
  255. boxes=dummy_bboxes,
  256. return_tensors=framework,
  257. )
  258. )
  259. return inputs
  260. __all__ = ["LayoutLMv3Config", "LayoutLMv3OnnxConfig"]