configuration_layoutlmv2.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright Microsoft Research and The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """LayoutLMv2 model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...utils import auto_docstring, is_detectron2_available
  18. # soft dependency
  19. if is_detectron2_available():
  20. import detectron2
  21. @auto_docstring(checkpoint="microsoft/layoutlmv2-base-uncased")
  22. @strict
  23. class LayoutLMv2Config(PreTrainedConfig):
  24. r"""
  25. max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
  26. The maximum value that the 2D position embedding might ever be used with. Typically set this to something
  27. large just in case (e.g., 1024).
  28. max_rel_pos (`int`, *optional*, defaults to 128):
  29. The maximum number of relative positions to be used in the self-attention mechanism.
  30. rel_pos_bins (`int`, *optional*, defaults to 32):
  31. The number of relative position bins to be used in the self-attention mechanism.
  32. fast_qkv (`bool`, *optional*, defaults to `True`):
  33. Whether or not to use a single matrix for the queries, keys, values in the self-attention layers.
  34. max_rel_2d_pos (`int`, *optional*, defaults to 256):
  35. The maximum number of relative 2D positions in the self-attention mechanism.
  36. rel_2d_pos_bins (`int`, *optional*, defaults to 64):
  37. The number of 2D relative position bins in the self-attention mechanism.
  38. convert_sync_batchnorm (`bool`, *optional*, defaults to `True`):
  39. Whether or not to convert batch normalization layers to synchronized batch normalization layers.
  40. image_feature_pool_shape (`list[int]`, *optional*, defaults to `[7, 7, 256]`):
  41. The shape of the average-pooled feature map.
  42. coordinate_size (`int`, *optional*, defaults to 128):
  43. Dimension of the coordinate embeddings.
  44. shape_size (`int`, *optional*, defaults to 128):
  45. Dimension of the width and height embeddings.
  46. has_relative_attention_bias (`bool`, *optional*, defaults to `True`):
  47. Whether or not to use a relative attention bias in the self-attention mechanism.
  48. has_spatial_attention_bias (`bool`, *optional*, defaults to `True`):
  49. Whether or not to use a spatial attention bias in the self-attention mechanism.
  50. has_visual_segment_embedding (`bool`, *optional*, defaults to `False`):
  51. Whether or not to add visual segment embeddings.
  52. detectron2_config_args (`dict`, *optional*):
  53. Dictionary containing the configuration arguments of the Detectron2 visual backbone. Refer to [this
  54. file](https://github.com/microsoft/unilm/blob/master/layoutlmft/layoutlmft/models/layoutlmv2/detectron2_config.py)
  55. for details regarding default values.
  56. Example:
  57. ```python
  58. >>> from transformers import LayoutLMv2Config, LayoutLMv2Model
  59. >>> # Initializing a LayoutLMv2 microsoft/layoutlmv2-base-uncased style configuration
  60. >>> configuration = LayoutLMv2Config()
  61. >>> # Initializing a model (with random weights) from the microsoft/layoutlmv2-base-uncased style configuration
  62. >>> model = LayoutLMv2Model(configuration)
  63. >>> # Accessing the model configuration
  64. >>> configuration = model.config
  65. ```"""
  66. model_type = "layoutlmv2"
  67. vocab_size: int = 30522
  68. hidden_size: int = 768
  69. num_hidden_layers: int = 12
  70. num_attention_heads: int = 12
  71. intermediate_size: int = 3072
  72. hidden_act: str = "gelu"
  73. hidden_dropout_prob: float | int = 0.1
  74. attention_probs_dropout_prob: float | int = 0.1
  75. max_position_embeddings: int = 512
  76. type_vocab_size: int = 2
  77. initializer_range: float = 0.02
  78. layer_norm_eps: float = 1e-12
  79. pad_token_id: int | None = 0
  80. max_2d_position_embeddings: int = 1024
  81. max_rel_pos: int = 128
  82. rel_pos_bins: int = 32
  83. fast_qkv: bool = True
  84. max_rel_2d_pos: int = 256
  85. rel_2d_pos_bins: int = 64
  86. convert_sync_batchnorm: bool = True
  87. image_feature_pool_shape: list[int] | tuple[int, ...] = (7, 7, 256)
  88. coordinate_size: int = 128
  89. shape_size: int = 128
  90. has_relative_attention_bias: bool = True
  91. has_spatial_attention_bias: bool = True
  92. has_visual_segment_embedding: bool = False
  93. detectron2_config_args: dict | None = None
  94. def __post_init__(self, **kwargs):
  95. super().__post_init__(**kwargs)
  96. self.detectron2_config_args = (
  97. self.detectron2_config_args
  98. if self.detectron2_config_args is not None
  99. else self.get_default_detectron2_config()
  100. )
  101. @classmethod
  102. def get_default_detectron2_config(cls):
  103. return {
  104. "MODEL.MASK_ON": True,
  105. "MODEL.PIXEL_STD": [57.375, 57.120, 58.395],
  106. "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
  107. "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
  108. "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
  109. "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
  110. "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
  111. "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
  112. "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
  113. "MODEL.POST_NMS_TOPK_TEST": 1000,
  114. "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
  115. "MODEL.ROI_HEADS.NUM_CLASSES": 5,
  116. "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
  117. "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
  118. "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
  119. "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
  120. "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
  121. "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
  122. "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
  123. "MODEL.RESNETS.DEPTH": 101,
  124. "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
  125. "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
  126. "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
  127. "MODEL.RESNETS.NUM_GROUPS": 32,
  128. "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
  129. "MODEL.RESNETS.STRIDE_IN_1X1": False,
  130. }
  131. def get_detectron2_config(self):
  132. detectron2_config = detectron2.config.get_cfg()
  133. for k, v in self.detectron2_config_args.items():
  134. attributes = k.split(".")
  135. to_set = detectron2_config
  136. for attribute in attributes[:-1]:
  137. to_set = getattr(to_set, attribute)
  138. setattr(to_set, attributes[-1], v)
  139. return detectron2_config
  140. __all__ = ["LayoutLMv2Config"]