configuration_lightglue.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/lightglue/modular_lightglue.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_lightglue.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2025 The HuggingFace 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 ...configuration_utils import PretrainedConfig
  21. from ..auto import CONFIG_MAPPING, AutoConfig
  22. from ..superpoint import SuperPointConfig
  23. class LightGlueConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`LightGlueForKeypointMatching`]. It is used to
  26. instantiate a LightGlue model according to the specified arguments, defining the model architecture. Instantiating a
  27. configuration with the defaults will yield a similar configuration to that of the LightGlue
  28. [ETH-CVG/lightglue_superpoint](https://huggingface.co/ETH-CVG/lightglue_superpoint) architecture.
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information.
  31. Args:
  32. keypoint_detector_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SuperPointConfig`):
  33. The config object or dictionary of the keypoint detector.
  34. descriptor_dim (`int`, *optional*, defaults to 256):
  35. The dimension of the descriptors.
  36. num_hidden_layers (`int`, *optional*, defaults to 9):
  37. The number of self and cross attention layers.
  38. num_attention_heads (`int`, *optional*, defaults to 4):
  39. The number of heads in the multi-head attention.
  40. num_key_value_heads (`int`, *optional*):
  41. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  42. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  43. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  44. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  45. by meanpooling all the original heads within that group. For more details checkout [this
  46. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  47. `num_attention_heads`.
  48. depth_confidence (`float`, *optional*, defaults to 0.95):
  49. The confidence threshold used to perform early stopping
  50. width_confidence (`float`, *optional*, defaults to 0.99):
  51. The confidence threshold used to prune points
  52. filter_threshold (`float`, *optional*, defaults to 0.1):
  53. The confidence threshold used to filter matches
  54. initializer_range (`float`, *optional*, defaults to 0.02):
  55. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  56. hidden_act (`str`, *optional*, defaults to `"gelu"`):
  57. The activation function to be used in the hidden layers.
  58. attention_dropout (`float`, *optional*, defaults to 0.0):
  59. The dropout ratio for the attention probabilities.
  60. attention_bias (`bool`, *optional*, defaults to `True`):
  61. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  62. trust_remote_code (`bool`, *optional*, defaults to `False`):
  63. Whether to trust remote code when using other models than SuperPoint as keypoint detector.
  64. Examples:
  65. ```python
  66. >>> from transformers import LightGlueConfig, LightGlueForKeypointMatching
  67. >>> # Initializing a LightGlue style configuration
  68. >>> configuration = LightGlueConfig()
  69. >>> # Initializing a model from the LightGlue style configuration
  70. >>> model = LightGlueForKeypointMatching(configuration)
  71. >>> # Accessing the model configuration
  72. >>> configuration = model.config
  73. ```
  74. """
  75. model_type = "lightglue"
  76. sub_configs = {"keypoint_detector_config": AutoConfig}
  77. def __init__(
  78. self,
  79. keypoint_detector_config: SuperPointConfig = None,
  80. descriptor_dim: int = 256,
  81. num_hidden_layers: int = 9,
  82. num_attention_heads: int = 4,
  83. num_key_value_heads=None,
  84. depth_confidence: float = 0.95,
  85. width_confidence: float = 0.99,
  86. filter_threshold: float = 0.1,
  87. initializer_range: float = 0.02,
  88. hidden_act: str = "gelu",
  89. attention_dropout=0.0,
  90. attention_bias=True,
  91. trust_remote_code: bool = False,
  92. **kwargs,
  93. ):
  94. # LightGlue can be used with other models than SuperPoint as keypoint detector
  95. # We provide the trust_remote_code argument to allow the use of other models
  96. # that are not registered in the CONFIG_MAPPING dictionary (for example DISK)
  97. self.trust_remote_code = trust_remote_code
  98. if descriptor_dim % num_attention_heads != 0:
  99. raise ValueError("descriptor_dim % num_heads is different from zero")
  100. self.descriptor_dim = descriptor_dim
  101. self.num_hidden_layers = num_hidden_layers
  102. self.num_attention_heads = num_attention_heads
  103. # for backward compatibility
  104. if num_key_value_heads is None:
  105. num_key_value_heads = num_attention_heads
  106. self.num_key_value_heads = num_key_value_heads
  107. self.depth_confidence = depth_confidence
  108. self.width_confidence = width_confidence
  109. self.filter_threshold = filter_threshold
  110. self.initializer_range = initializer_range
  111. # Keypoint Detector is forced into eager attention mode because SuperPoint does not have Attention
  112. # See https://github.com/huggingface/transformers/pull/31718#discussion_r2109733153
  113. if isinstance(keypoint_detector_config, dict):
  114. keypoint_detector_config["model_type"] = keypoint_detector_config.get("model_type", "superpoint")
  115. if keypoint_detector_config["model_type"] not in CONFIG_MAPPING:
  116. keypoint_detector_config = AutoConfig.from_pretrained(
  117. keypoint_detector_config["_name_or_path"], trust_remote_code=self.trust_remote_code
  118. )
  119. else:
  120. keypoint_detector_config = CONFIG_MAPPING[keypoint_detector_config["model_type"]](
  121. **keypoint_detector_config, attn_implementation="eager"
  122. )
  123. if keypoint_detector_config is None:
  124. keypoint_detector_config = CONFIG_MAPPING["superpoint"](attn_implementation="eager")
  125. self.keypoint_detector_config = keypoint_detector_config
  126. self.hidden_size = descriptor_dim
  127. self.intermediate_size = descriptor_dim * 2
  128. self.hidden_act = hidden_act
  129. self.attention_dropout = attention_dropout
  130. self.attention_bias = attention_bias
  131. super().__init__(**kwargs)
  132. __all__ = ["LightGlueConfig"]