configuration_detr.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # coding=utf-8
  2. # Copyright 2021 Facebook AI 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. """DETR model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from packaging import version
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. from ...utils.backbone_utils import verify_backbone_config_arguments
  23. from ..auto import CONFIG_MAPPING
  24. logger = logging.get_logger(__name__)
  25. class DetrConfig(PretrainedConfig):
  26. r"""
  27. This is the configuration class to store the configuration of a [`DetrModel`]. It is used to instantiate a DETR
  28. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  29. defaults will yield a similar configuration to that of the DETR
  30. [facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50) architecture.
  31. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  32. documentation from [`PretrainedConfig`] for more information.
  33. Args:
  34. use_timm_backbone (`bool`, *optional*, defaults to `True`):
  35. Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
  36. API.
  37. backbone_config (`PretrainedConfig` or `dict`, *optional*):
  38. The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
  39. case it will default to `ResNetConfig()`.
  40. num_channels (`int`, *optional*, defaults to 3):
  41. The number of input channels.
  42. num_queries (`int`, *optional*, defaults to 100):
  43. Number of object queries, i.e. detection slots. This is the maximal number of objects [`DetrModel`] can
  44. detect in a single image. For COCO, we recommend 100 queries.
  45. d_model (`int`, *optional*, defaults to 256):
  46. This parameter is a general dimension parameter, defining dimensions for components such as the encoder layer and projection parameters in the decoder layer, among others.
  47. encoder_layers (`int`, *optional*, defaults to 6):
  48. Number of encoder layers.
  49. decoder_layers (`int`, *optional*, defaults to 6):
  50. Number of decoder layers.
  51. encoder_attention_heads (`int`, *optional*, defaults to 8):
  52. Number of attention heads for each attention layer in the Transformer encoder.
  53. decoder_attention_heads (`int`, *optional*, defaults to 8):
  54. Number of attention heads for each attention layer in the Transformer decoder.
  55. decoder_ffn_dim (`int`, *optional*, defaults to 2048):
  56. Dimension of the "intermediate" (often named feed-forward) layer in decoder.
  57. encoder_ffn_dim (`int`, *optional*, defaults to 2048):
  58. Dimension of the "intermediate" (often named feed-forward) layer in decoder.
  59. activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
  60. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  61. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  62. dropout (`float`, *optional*, defaults to 0.1):
  63. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  64. attention_dropout (`float`, *optional*, defaults to 0.0):
  65. The dropout ratio for the attention probabilities.
  66. activation_dropout (`float`, *optional*, defaults to 0.0):
  67. The dropout ratio for activations inside the fully connected layer.
  68. init_std (`float`, *optional*, defaults to 0.02):
  69. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  70. init_xavier_std (`float`, *optional*, defaults to 1):
  71. The scaling factor used for the Xavier initialization gain in the HM Attention map module.
  72. encoder_layerdrop (`float`, *optional*, defaults to 0.0):
  73. The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  74. for more details.
  75. decoder_layerdrop (`float`, *optional*, defaults to 0.0):
  76. The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  77. for more details.
  78. auxiliary_loss (`bool`, *optional*, defaults to `False`):
  79. Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
  80. position_embedding_type (`str`, *optional*, defaults to `"sine"`):
  81. Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
  82. backbone (`str`, *optional*, defaults to `"resnet50"`):
  83. Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
  84. will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
  85. is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
  86. use_pretrained_backbone (`bool`, *optional*, `True`):
  87. Whether to use pretrained weights for the backbone.
  88. backbone_kwargs (`dict`, *optional*):
  89. Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
  90. e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
  91. dilation (`bool`, *optional*, defaults to `False`):
  92. Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
  93. `use_timm_backbone` = `True`.
  94. class_cost (`float`, *optional*, defaults to 1):
  95. Relative weight of the classification error in the Hungarian matching cost.
  96. bbox_cost (`float`, *optional*, defaults to 5):
  97. Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
  98. giou_cost (`float`, *optional*, defaults to 2):
  99. Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
  100. mask_loss_coefficient (`float`, *optional*, defaults to 1):
  101. Relative weight of the Focal loss in the panoptic segmentation loss.
  102. dice_loss_coefficient (`float`, *optional*, defaults to 1):
  103. Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
  104. bbox_loss_coefficient (`float`, *optional*, defaults to 5):
  105. Relative weight of the L1 bounding box loss in the object detection loss.
  106. giou_loss_coefficient (`float`, *optional*, defaults to 2):
  107. Relative weight of the generalized IoU loss in the object detection loss.
  108. eos_coefficient (`float`, *optional*, defaults to 0.1):
  109. Relative classification weight of the 'no-object' class in the object detection loss.
  110. Examples:
  111. ```python
  112. >>> from transformers import DetrConfig, DetrModel
  113. >>> # Initializing a DETR facebook/detr-resnet-50 style configuration
  114. >>> configuration = DetrConfig()
  115. >>> # Initializing a model (with random weights) from the facebook/detr-resnet-50 style configuration
  116. >>> model = DetrModel(configuration)
  117. >>> # Accessing the model configuration
  118. >>> configuration = model.config
  119. ```"""
  120. model_type = "detr"
  121. keys_to_ignore_at_inference = ["past_key_values"]
  122. attribute_map = {
  123. "hidden_size": "d_model",
  124. "num_attention_heads": "encoder_attention_heads",
  125. }
  126. def __init__(
  127. self,
  128. use_timm_backbone=True,
  129. backbone_config=None,
  130. num_channels=3,
  131. num_queries=100,
  132. encoder_layers=6,
  133. encoder_ffn_dim=2048,
  134. encoder_attention_heads=8,
  135. decoder_layers=6,
  136. decoder_ffn_dim=2048,
  137. decoder_attention_heads=8,
  138. encoder_layerdrop=0.0,
  139. decoder_layerdrop=0.0,
  140. is_encoder_decoder=True,
  141. activation_function="relu",
  142. d_model=256,
  143. dropout=0.1,
  144. attention_dropout=0.0,
  145. activation_dropout=0.0,
  146. init_std=0.02,
  147. init_xavier_std=1.0,
  148. auxiliary_loss=False,
  149. position_embedding_type="sine",
  150. backbone="resnet50",
  151. use_pretrained_backbone=True,
  152. backbone_kwargs=None,
  153. dilation=False,
  154. class_cost=1,
  155. bbox_cost=5,
  156. giou_cost=2,
  157. mask_loss_coefficient=1,
  158. dice_loss_coefficient=1,
  159. bbox_loss_coefficient=5,
  160. giou_loss_coefficient=2,
  161. eos_coefficient=0.1,
  162. **kwargs,
  163. ):
  164. # We default to values which were previously hard-coded in the model. This enables configurability of the config
  165. # while keeping the default behavior the same.
  166. if use_timm_backbone and backbone_kwargs is None:
  167. backbone_kwargs = {}
  168. if dilation:
  169. backbone_kwargs["output_stride"] = 16
  170. backbone_kwargs["out_indices"] = [1, 2, 3, 4]
  171. backbone_kwargs["in_chans"] = num_channels
  172. # Backwards compatibility
  173. elif not use_timm_backbone and backbone in (None, "resnet50"):
  174. if backbone_config is None:
  175. logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
  176. backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
  177. elif isinstance(backbone_config, dict):
  178. backbone_model_type = backbone_config.get("model_type")
  179. config_class = CONFIG_MAPPING[backbone_model_type]
  180. backbone_config = config_class.from_dict(backbone_config)
  181. backbone = None
  182. # set timm attributes to None
  183. dilation = None
  184. verify_backbone_config_arguments(
  185. use_timm_backbone=use_timm_backbone,
  186. use_pretrained_backbone=use_pretrained_backbone,
  187. backbone=backbone,
  188. backbone_config=backbone_config,
  189. backbone_kwargs=backbone_kwargs,
  190. )
  191. self.use_timm_backbone = use_timm_backbone
  192. self.backbone_config = backbone_config
  193. self.num_channels = num_channels
  194. self.num_queries = num_queries
  195. self.d_model = d_model
  196. self.encoder_ffn_dim = encoder_ffn_dim
  197. self.encoder_layers = encoder_layers
  198. self.encoder_attention_heads = encoder_attention_heads
  199. self.decoder_ffn_dim = decoder_ffn_dim
  200. self.decoder_layers = decoder_layers
  201. self.decoder_attention_heads = decoder_attention_heads
  202. self.dropout = dropout
  203. self.attention_dropout = attention_dropout
  204. self.activation_dropout = activation_dropout
  205. self.activation_function = activation_function
  206. self.init_std = init_std
  207. self.init_xavier_std = init_xavier_std
  208. self.encoder_layerdrop = encoder_layerdrop
  209. self.decoder_layerdrop = decoder_layerdrop
  210. self.num_hidden_layers = encoder_layers
  211. self.auxiliary_loss = auxiliary_loss
  212. self.position_embedding_type = position_embedding_type
  213. self.backbone = backbone
  214. self.use_pretrained_backbone = use_pretrained_backbone
  215. self.backbone_kwargs = backbone_kwargs
  216. self.dilation = dilation
  217. # Hungarian matcher
  218. self.class_cost = class_cost
  219. self.bbox_cost = bbox_cost
  220. self.giou_cost = giou_cost
  221. # Loss coefficients
  222. self.mask_loss_coefficient = mask_loss_coefficient
  223. self.dice_loss_coefficient = dice_loss_coefficient
  224. self.bbox_loss_coefficient = bbox_loss_coefficient
  225. self.giou_loss_coefficient = giou_loss_coefficient
  226. self.eos_coefficient = eos_coefficient
  227. super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
  228. @property
  229. def num_attention_heads(self) -> int:
  230. return self.encoder_attention_heads
  231. @property
  232. def hidden_size(self) -> int:
  233. return self.d_model
  234. @property
  235. def sub_configs(self):
  236. return (
  237. {"backbone_config": type(self.backbone_config)}
  238. if getattr(self, "backbone_config", None) is not None
  239. else {}
  240. )
  241. @classmethod
  242. def from_backbone_config(cls, backbone_config: PretrainedConfig, **kwargs):
  243. """Instantiate a [`DetrConfig`] (or a derived class) from a pre-trained backbone model configuration.
  244. Args:
  245. backbone_config ([`PretrainedConfig`]):
  246. The backbone configuration.
  247. Returns:
  248. [`DetrConfig`]: An instance of a configuration object
  249. """
  250. return cls(backbone_config=backbone_config, **kwargs)
  251. class DetrOnnxConfig(OnnxConfig):
  252. torch_onnx_minimum_version = version.parse("1.11")
  253. @property
  254. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  255. return OrderedDict(
  256. [
  257. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  258. ("pixel_mask", {0: "batch"}),
  259. ]
  260. )
  261. @property
  262. def atol_for_validation(self) -> float:
  263. return 1e-5
  264. @property
  265. def default_onnx_opset(self) -> int:
  266. return 12
  267. __all__ = ["DetrConfig", "DetrOnnxConfig"]