configuration_layoutlm.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # coding=utf-8
  2. # Copyright 2010, The Microsoft Research Asia LayoutLM Team authors
  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. """LayoutLM model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import Any, Optional
  19. from ... import PretrainedConfig, PreTrainedTokenizer
  20. from ...onnx import OnnxConfig, PatchingSpec
  21. from ...utils import TensorType, is_torch_available, logging
  22. logger = logging.get_logger(__name__)
  23. class LayoutLMConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`LayoutLMModel`]. It is used to instantiate a
  26. LayoutLM model according to the specified arguments, defining the model architecture. Instantiating a configuration
  27. with the defaults will yield a similar configuration to that of the LayoutLM
  28. [microsoft/layoutlm-base-uncased](https://huggingface.co/microsoft/layoutlm-base-uncased) architecture.
  29. Configuration objects inherit from [`BertConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`BertConfig`] for more information.
  31. Args:
  32. vocab_size (`int`, *optional*, defaults to 30522):
  33. Vocabulary size of the LayoutLM model. Defines the different tokens that can be represented by the
  34. *inputs_ids* passed to the forward method of [`LayoutLMModel`].
  35. hidden_size (`int`, *optional*, defaults to 768):
  36. Dimensionality of the encoder layers and the pooler layer.
  37. num_hidden_layers (`int`, *optional*, defaults to 12):
  38. Number of hidden layers in the Transformer encoder.
  39. num_attention_heads (`int`, *optional*, defaults to 12):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. intermediate_size (`int`, *optional*, defaults to 3072):
  42. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  43. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  44. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  45. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  46. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  47. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  48. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  49. The dropout ratio for the attention probabilities.
  50. max_position_embeddings (`int`, *optional*, defaults to 512):
  51. The maximum sequence length that this model might ever be used with. Typically set this to something large
  52. just in case (e.g., 512 or 1024 or 2048).
  53. type_vocab_size (`int`, *optional*, defaults to 2):
  54. The vocabulary size of the `token_type_ids` passed into [`LayoutLMModel`].
  55. initializer_range (`float`, *optional*, defaults to 0.02):
  56. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  57. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  58. The epsilon used by the layer normalization layers.
  59. pad_token_id (`int`, *optional*, defaults to 0):
  60. The value used to pad input_ids.
  61. use_cache (`bool`, *optional*, defaults to `True`):
  62. Whether or not the model should return the last key/values attentions (not used by all models). Only
  63. relevant if `config.is_decoder=True`.
  64. max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
  65. The maximum value that the 2D position embedding might ever used. Typically set this to something large
  66. just in case (e.g., 1024).
  67. Examples:
  68. ```python
  69. >>> from transformers import LayoutLMConfig, LayoutLMModel
  70. >>> # Initializing a LayoutLM configuration
  71. >>> configuration = LayoutLMConfig()
  72. >>> # Initializing a model (with random weights) from the configuration
  73. >>> model = LayoutLMModel(configuration)
  74. >>> # Accessing the model configuration
  75. >>> configuration = model.config
  76. ```"""
  77. model_type = "layoutlm"
  78. def __init__(
  79. self,
  80. vocab_size=30522,
  81. hidden_size=768,
  82. num_hidden_layers=12,
  83. num_attention_heads=12,
  84. intermediate_size=3072,
  85. hidden_act="gelu",
  86. hidden_dropout_prob=0.1,
  87. attention_probs_dropout_prob=0.1,
  88. max_position_embeddings=512,
  89. type_vocab_size=2,
  90. initializer_range=0.02,
  91. layer_norm_eps=1e-12,
  92. pad_token_id=0,
  93. use_cache=True,
  94. max_2d_position_embeddings=1024,
  95. **kwargs,
  96. ):
  97. super().__init__(pad_token_id=pad_token_id, **kwargs)
  98. self.vocab_size = vocab_size
  99. self.hidden_size = hidden_size
  100. self.num_hidden_layers = num_hidden_layers
  101. self.num_attention_heads = num_attention_heads
  102. self.hidden_act = hidden_act
  103. self.intermediate_size = intermediate_size
  104. self.hidden_dropout_prob = hidden_dropout_prob
  105. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  106. self.max_position_embeddings = max_position_embeddings
  107. self.type_vocab_size = type_vocab_size
  108. self.initializer_range = initializer_range
  109. self.layer_norm_eps = layer_norm_eps
  110. self.use_cache = use_cache
  111. self.max_2d_position_embeddings = max_2d_position_embeddings
  112. class LayoutLMOnnxConfig(OnnxConfig):
  113. def __init__(
  114. self,
  115. config: PretrainedConfig,
  116. task: str = "default",
  117. patching_specs: Optional[list[PatchingSpec]] = None,
  118. ):
  119. super().__init__(config, task=task, patching_specs=patching_specs)
  120. self.max_2d_positions = config.max_2d_position_embeddings - 1
  121. @property
  122. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  123. return OrderedDict(
  124. [
  125. ("input_ids", {0: "batch", 1: "sequence"}),
  126. ("bbox", {0: "batch", 1: "sequence"}),
  127. ("attention_mask", {0: "batch", 1: "sequence"}),
  128. ("token_type_ids", {0: "batch", 1: "sequence"}),
  129. ]
  130. )
  131. def generate_dummy_inputs(
  132. self,
  133. tokenizer: PreTrainedTokenizer,
  134. batch_size: int = -1,
  135. seq_length: int = -1,
  136. is_pair: bool = False,
  137. framework: Optional[TensorType] = None,
  138. ) -> Mapping[str, Any]:
  139. """
  140. Generate inputs to provide to the ONNX exporter for the specific framework
  141. Args:
  142. tokenizer: The tokenizer associated with this model configuration
  143. batch_size: The batch size (int) to export the model for (-1 means dynamic axis)
  144. seq_length: The sequence length (int) to export the model for (-1 means dynamic axis)
  145. is_pair: Indicate if the input is a pair (sentence 1, sentence 2)
  146. framework: The framework (optional) the tokenizer will generate tensor for
  147. Returns:
  148. Mapping[str, Tensor] holding the kwargs to provide to the model's forward function
  149. """
  150. input_dict = super().generate_dummy_inputs(
  151. tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
  152. )
  153. # Generate a dummy bbox
  154. box = [48, 84, 73, 128]
  155. if not framework == TensorType.PYTORCH:
  156. raise NotImplementedError("Exporting LayoutLM to ONNX is currently only supported for PyTorch.")
  157. if not is_torch_available():
  158. raise ValueError("Cannot generate dummy inputs without PyTorch installed.")
  159. import torch
  160. batch_size, seq_length = input_dict["input_ids"].shape
  161. input_dict["bbox"] = torch.tensor([*[box] * seq_length]).tile(batch_size, 1, 1)
  162. return input_dict
  163. __all__ = ["LayoutLMConfig", "LayoutLMOnnxConfig"]