configuration_layoutlmv2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # coding=utf-8
  2. # Copyright 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. """LayoutLMv2 model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import is_detectron2_available, logging
  18. logger = logging.get_logger(__name__)
  19. # soft dependency
  20. if is_detectron2_available():
  21. import detectron2
  22. class LayoutLMv2Config(PretrainedConfig):
  23. r"""
  24. This is the configuration class to store the configuration of a [`LayoutLMv2Model`]. It is used to instantiate an
  25. LayoutLMv2 model according to the specified arguments, defining the model architecture. Instantiating a
  26. configuration with the defaults will yield a similar configuration to that of the LayoutLMv2
  27. [microsoft/layoutlmv2-base-uncased](https://huggingface.co/microsoft/layoutlmv2-base-uncased) architecture.
  28. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  29. documentation from [`PretrainedConfig`] for more information.
  30. Args:
  31. vocab_size (`int`, *optional*, defaults to 30522):
  32. Vocabulary size of the LayoutLMv2 model. Defines the number of different tokens that can be represented by
  33. the `inputs_ids` passed when calling [`LayoutLMv2Model`] or [`TFLayoutLMv2Model`].
  34. hidden_size (`int`, *optional*, defaults to 768):
  35. Dimension of the encoder layers and the pooler layer.
  36. num_hidden_layers (`int`, *optional*, defaults to 12):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 12):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. intermediate_size (`int`, *optional*, defaults to 3072):
  41. Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  42. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  43. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  44. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  45. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  46. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  47. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  48. The dropout ratio for the attention probabilities.
  49. max_position_embeddings (`int`, *optional*, defaults to 512):
  50. The maximum sequence length that this model might ever be used with. Typically set this to something large
  51. just in case (e.g., 512 or 1024 or 2048).
  52. type_vocab_size (`int`, *optional*, defaults to 2):
  53. The vocabulary size of the `token_type_ids` passed when calling [`LayoutLMv2Model`] or
  54. [`TFLayoutLMv2Model`].
  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. max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
  60. The maximum value that the 2D position embedding might ever be used with. Typically set this to something
  61. large just in case (e.g., 1024).
  62. max_rel_pos (`int`, *optional*, defaults to 128):
  63. The maximum number of relative positions to be used in the self-attention mechanism.
  64. rel_pos_bins (`int`, *optional*, defaults to 32):
  65. The number of relative position bins to be used in the self-attention mechanism.
  66. fast_qkv (`bool`, *optional*, defaults to `True`):
  67. Whether or not to use a single matrix for the queries, keys, values in the self-attention layers.
  68. max_rel_2d_pos (`int`, *optional*, defaults to 256):
  69. The maximum number of relative 2D positions in the self-attention mechanism.
  70. rel_2d_pos_bins (`int`, *optional*, defaults to 64):
  71. The number of 2D relative position bins in the self-attention mechanism.
  72. image_feature_pool_shape (`list[int]`, *optional*, defaults to [7, 7, 256]):
  73. The shape of the average-pooled feature map.
  74. coordinate_size (`int`, *optional*, defaults to 128):
  75. Dimension of the coordinate embeddings.
  76. shape_size (`int`, *optional*, defaults to 128):
  77. Dimension of the width and height embeddings.
  78. has_relative_attention_bias (`bool`, *optional*, defaults to `True`):
  79. Whether or not to use a relative attention bias in the self-attention mechanism.
  80. has_spatial_attention_bias (`bool`, *optional*, defaults to `True`):
  81. Whether or not to use a spatial attention bias in the self-attention mechanism.
  82. has_visual_segment_embedding (`bool`, *optional*, defaults to `False`):
  83. Whether or not to add visual segment embeddings.
  84. detectron2_config_args (`dict`, *optional*):
  85. Dictionary containing the configuration arguments of the Detectron2 visual backbone. Refer to [this
  86. file](https://github.com/microsoft/unilm/blob/master/layoutlmft/layoutlmft/models/layoutlmv2/detectron2_config.py)
  87. for details regarding default values.
  88. Example:
  89. ```python
  90. >>> from transformers import LayoutLMv2Config, LayoutLMv2Model
  91. >>> # Initializing a LayoutLMv2 microsoft/layoutlmv2-base-uncased style configuration
  92. >>> configuration = LayoutLMv2Config()
  93. >>> # Initializing a model (with random weights) from the microsoft/layoutlmv2-base-uncased style configuration
  94. >>> model = LayoutLMv2Model(configuration)
  95. >>> # Accessing the model configuration
  96. >>> configuration = model.config
  97. ```"""
  98. model_type = "layoutlmv2"
  99. def __init__(
  100. self,
  101. vocab_size=30522,
  102. hidden_size=768,
  103. num_hidden_layers=12,
  104. num_attention_heads=12,
  105. intermediate_size=3072,
  106. hidden_act="gelu",
  107. hidden_dropout_prob=0.1,
  108. attention_probs_dropout_prob=0.1,
  109. max_position_embeddings=512,
  110. type_vocab_size=2,
  111. initializer_range=0.02,
  112. layer_norm_eps=1e-12,
  113. pad_token_id=0,
  114. max_2d_position_embeddings=1024,
  115. max_rel_pos=128,
  116. rel_pos_bins=32,
  117. fast_qkv=True,
  118. max_rel_2d_pos=256,
  119. rel_2d_pos_bins=64,
  120. convert_sync_batchnorm=True,
  121. image_feature_pool_shape=[7, 7, 256],
  122. coordinate_size=128,
  123. shape_size=128,
  124. has_relative_attention_bias=True,
  125. has_spatial_attention_bias=True,
  126. has_visual_segment_embedding=False,
  127. detectron2_config_args=None,
  128. **kwargs,
  129. ):
  130. super().__init__(
  131. vocab_size=vocab_size,
  132. hidden_size=hidden_size,
  133. num_hidden_layers=num_hidden_layers,
  134. num_attention_heads=num_attention_heads,
  135. intermediate_size=intermediate_size,
  136. hidden_act=hidden_act,
  137. hidden_dropout_prob=hidden_dropout_prob,
  138. attention_probs_dropout_prob=attention_probs_dropout_prob,
  139. max_position_embeddings=max_position_embeddings,
  140. type_vocab_size=type_vocab_size,
  141. initializer_range=initializer_range,
  142. layer_norm_eps=layer_norm_eps,
  143. pad_token_id=pad_token_id,
  144. **kwargs,
  145. )
  146. self.max_2d_position_embeddings = max_2d_position_embeddings
  147. self.max_rel_pos = max_rel_pos
  148. self.rel_pos_bins = rel_pos_bins
  149. self.fast_qkv = fast_qkv
  150. self.max_rel_2d_pos = max_rel_2d_pos
  151. self.rel_2d_pos_bins = rel_2d_pos_bins
  152. self.convert_sync_batchnorm = convert_sync_batchnorm
  153. self.image_feature_pool_shape = image_feature_pool_shape
  154. self.coordinate_size = coordinate_size
  155. self.shape_size = shape_size
  156. self.has_relative_attention_bias = has_relative_attention_bias
  157. self.has_spatial_attention_bias = has_spatial_attention_bias
  158. self.has_visual_segment_embedding = has_visual_segment_embedding
  159. self.detectron2_config_args = (
  160. detectron2_config_args if detectron2_config_args is not None else self.get_default_detectron2_config()
  161. )
  162. @classmethod
  163. def get_default_detectron2_config(cls):
  164. return {
  165. "MODEL.MASK_ON": True,
  166. "MODEL.PIXEL_STD": [57.375, 57.120, 58.395],
  167. "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
  168. "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
  169. "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
  170. "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
  171. "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
  172. "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
  173. "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
  174. "MODEL.POST_NMS_TOPK_TEST": 1000,
  175. "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
  176. "MODEL.ROI_HEADS.NUM_CLASSES": 5,
  177. "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
  178. "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
  179. "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
  180. "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
  181. "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
  182. "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
  183. "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
  184. "MODEL.RESNETS.DEPTH": 101,
  185. "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
  186. "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
  187. "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
  188. "MODEL.RESNETS.NUM_GROUPS": 32,
  189. "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
  190. "MODEL.RESNETS.STRIDE_IN_1X1": False,
  191. }
  192. def get_detectron2_config(self):
  193. detectron2_config = detectron2.config.get_cfg()
  194. for k, v in self.detectron2_config_args.items():
  195. attributes = k.split(".")
  196. to_set = detectron2_config
  197. for attribute in attributes[:-1]:
  198. to_set = getattr(to_set, attribute)
  199. setattr(to_set, attributes[-1], v)
  200. return detectron2_config
  201. __all__ = ["LayoutLMv2Config"]