configuration_layoutxlm.py 7.6 KB

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