modeling_superpoint.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. # Copyright 2024 The HuggingFace 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. """PyTorch SuperPoint model."""
  15. from dataclasses import dataclass
  16. from typing import Optional, Union
  17. import torch
  18. from torch import nn
  19. from transformers import PreTrainedModel
  20. from transformers.modeling_outputs import (
  21. BaseModelOutputWithNoAttention,
  22. )
  23. from transformers.models.superpoint.configuration_superpoint import SuperPointConfig
  24. from ...utils import (
  25. ModelOutput,
  26. auto_docstring,
  27. logging,
  28. )
  29. logger = logging.get_logger(__name__)
  30. def remove_keypoints_from_borders(
  31. keypoints: torch.Tensor, scores: torch.Tensor, border: int, height: int, width: int
  32. ) -> tuple[torch.Tensor, torch.Tensor]:
  33. """Removes keypoints (and their associated scores) that are too close to the border"""
  34. mask_h = (keypoints[:, 0] >= border) & (keypoints[:, 0] < (height - border))
  35. mask_w = (keypoints[:, 1] >= border) & (keypoints[:, 1] < (width - border))
  36. mask = mask_h & mask_w
  37. return keypoints[mask], scores[mask]
  38. def top_k_keypoints(keypoints: torch.Tensor, scores: torch.Tensor, k: int) -> tuple[torch.Tensor, torch.Tensor]:
  39. """Keeps the k keypoints with highest score"""
  40. if k >= len(keypoints):
  41. return keypoints, scores
  42. scores, indices = torch.topk(scores, k, dim=0)
  43. return keypoints[indices], scores
  44. def simple_nms(scores: torch.Tensor, nms_radius: int) -> torch.Tensor:
  45. """Applies non-maximum suppression on scores"""
  46. if nms_radius < 0:
  47. raise ValueError("Expected positive values for nms_radius")
  48. def max_pool(x):
  49. return nn.functional.max_pool2d(x, kernel_size=nms_radius * 2 + 1, stride=1, padding=nms_radius)
  50. zeros = torch.zeros_like(scores)
  51. max_mask = scores == max_pool(scores)
  52. for _ in range(2):
  53. supp_mask = max_pool(max_mask.float()) > 0
  54. supp_scores = torch.where(supp_mask, zeros, scores)
  55. new_max_mask = supp_scores == max_pool(supp_scores)
  56. max_mask = max_mask | (new_max_mask & (~supp_mask))
  57. return torch.where(max_mask, scores, zeros)
  58. @dataclass
  59. @auto_docstring(
  60. custom_intro="""
  61. Base class for outputs of image point description models. Due to the nature of keypoint detection, the number of
  62. keypoints is not fixed and can vary from image to image, which makes batching non-trivial. In the batch of images,
  63. the maximum number of keypoints is set as the dimension of the keypoints, scores and descriptors tensors. The mask
  64. tensor is used to indicate which values in the keypoints, scores and descriptors tensors are keypoint information
  65. and which are padding.
  66. """
  67. )
  68. class SuperPointKeypointDescriptionOutput(ModelOutput):
  69. r"""
  70. loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
  71. Loss computed during training.
  72. keypoints (`torch.FloatTensor` of shape `(batch_size, num_keypoints, 2)`):
  73. Relative (x, y) coordinates of predicted keypoints in a given image.
  74. scores (`torch.FloatTensor` of shape `(batch_size, num_keypoints)`):
  75. Scores of predicted keypoints.
  76. descriptors (`torch.FloatTensor` of shape `(batch_size, num_keypoints, descriptor_size)`):
  77. Descriptors of predicted keypoints.
  78. mask (`torch.BoolTensor` of shape `(batch_size, num_keypoints)`):
  79. Mask indicating which values in keypoints, scores and descriptors are keypoint information.
  80. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or
  81. when `config.output_hidden_states=True`):
  82. Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
  83. one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
  84. (also called feature maps) of the model at the output of each stage.
  85. """
  86. loss: Optional[torch.FloatTensor] = None
  87. keypoints: Optional[torch.IntTensor] = None
  88. scores: Optional[torch.FloatTensor] = None
  89. descriptors: Optional[torch.FloatTensor] = None
  90. mask: Optional[torch.BoolTensor] = None
  91. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  92. class SuperPointConvBlock(nn.Module):
  93. def __init__(
  94. self, config: SuperPointConfig, in_channels: int, out_channels: int, add_pooling: bool = False
  95. ) -> None:
  96. super().__init__()
  97. self.conv_a = nn.Conv2d(
  98. in_channels,
  99. out_channels,
  100. kernel_size=3,
  101. stride=1,
  102. padding=1,
  103. )
  104. self.conv_b = nn.Conv2d(
  105. out_channels,
  106. out_channels,
  107. kernel_size=3,
  108. stride=1,
  109. padding=1,
  110. )
  111. self.relu = nn.ReLU(inplace=True)
  112. self.pool = nn.MaxPool2d(kernel_size=2, stride=2) if add_pooling else None
  113. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  114. hidden_states = self.relu(self.conv_a(hidden_states))
  115. hidden_states = self.relu(self.conv_b(hidden_states))
  116. if self.pool is not None:
  117. hidden_states = self.pool(hidden_states)
  118. return hidden_states
  119. class SuperPointEncoder(nn.Module):
  120. """
  121. SuperPoint encoder module. It is made of 4 convolutional layers with ReLU activation and max pooling, reducing the
  122. dimensionality of the image.
  123. """
  124. def __init__(self, config: SuperPointConfig) -> None:
  125. super().__init__()
  126. # SuperPoint uses 1 channel images
  127. self.input_dim = 1
  128. conv_blocks = []
  129. conv_blocks.append(
  130. SuperPointConvBlock(config, self.input_dim, config.encoder_hidden_sizes[0], add_pooling=True)
  131. )
  132. for i in range(1, len(config.encoder_hidden_sizes) - 1):
  133. conv_blocks.append(
  134. SuperPointConvBlock(
  135. config, config.encoder_hidden_sizes[i - 1], config.encoder_hidden_sizes[i], add_pooling=True
  136. )
  137. )
  138. conv_blocks.append(
  139. SuperPointConvBlock(
  140. config, config.encoder_hidden_sizes[-2], config.encoder_hidden_sizes[-1], add_pooling=False
  141. )
  142. )
  143. self.conv_blocks = nn.ModuleList(conv_blocks)
  144. def forward(
  145. self,
  146. input,
  147. output_hidden_states: Optional[bool] = False,
  148. return_dict: Optional[bool] = True,
  149. ) -> Union[tuple, BaseModelOutputWithNoAttention]:
  150. all_hidden_states = () if output_hidden_states else None
  151. for conv_block in self.conv_blocks:
  152. input = conv_block(input)
  153. if output_hidden_states:
  154. all_hidden_states = all_hidden_states + (input,)
  155. output = input
  156. if not return_dict:
  157. return tuple(v for v in [output, all_hidden_states] if v is not None)
  158. return BaseModelOutputWithNoAttention(
  159. last_hidden_state=output,
  160. hidden_states=all_hidden_states,
  161. )
  162. class SuperPointInterestPointDecoder(nn.Module):
  163. """
  164. The SuperPointInterestPointDecoder uses the output of the SuperPointEncoder to compute the keypoint with scores.
  165. The scores are first computed by a convolutional layer, then a softmax is applied to get a probability distribution
  166. over the 65 possible keypoint classes. The keypoints are then extracted from the scores by thresholding and
  167. non-maximum suppression. Post-processing is then applied to remove keypoints too close to the image borders as well
  168. as to keep only the k keypoints with highest score.
  169. """
  170. def __init__(self, config: SuperPointConfig) -> None:
  171. super().__init__()
  172. self.keypoint_threshold = config.keypoint_threshold
  173. self.max_keypoints = config.max_keypoints
  174. self.nms_radius = config.nms_radius
  175. self.border_removal_distance = config.border_removal_distance
  176. self.relu = nn.ReLU(inplace=True)
  177. self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
  178. self.conv_score_a = nn.Conv2d(
  179. config.encoder_hidden_sizes[-1],
  180. config.decoder_hidden_size,
  181. kernel_size=3,
  182. stride=1,
  183. padding=1,
  184. )
  185. self.conv_score_b = nn.Conv2d(
  186. config.decoder_hidden_size, config.keypoint_decoder_dim, kernel_size=1, stride=1, padding=0
  187. )
  188. def forward(self, encoded: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
  189. scores = self._get_pixel_scores(encoded)
  190. keypoints, scores = self._extract_keypoints(scores)
  191. return keypoints, scores
  192. def _get_pixel_scores(self, encoded: torch.Tensor) -> torch.Tensor:
  193. """Based on the encoder output, compute the scores for each pixel of the image"""
  194. scores = self.relu(self.conv_score_a(encoded))
  195. scores = self.conv_score_b(scores)
  196. scores = nn.functional.softmax(scores, 1)[:, :-1]
  197. batch_size, _, height, width = scores.shape
  198. scores = scores.permute(0, 2, 3, 1).reshape(batch_size, height, width, 8, 8)
  199. scores = scores.permute(0, 1, 3, 2, 4).reshape(batch_size, height * 8, width * 8)
  200. scores = simple_nms(scores, self.nms_radius)
  201. return scores
  202. def _extract_keypoints(self, scores: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
  203. """
  204. Based on their scores, extract the pixels that represent the keypoints that will be used for descriptors computation.
  205. The keypoints are in the form of relative (x, y) coordinates.
  206. """
  207. _, height, width = scores.shape
  208. # Threshold keypoints by score value
  209. keypoints = torch.nonzero(scores[0] > self.keypoint_threshold)
  210. scores = scores[0][tuple(keypoints.t())]
  211. # Discard keypoints near the image borders
  212. keypoints, scores = remove_keypoints_from_borders(
  213. keypoints, scores, self.border_removal_distance, height * 8, width * 8
  214. )
  215. # Keep the k keypoints with highest score
  216. if self.max_keypoints >= 0:
  217. keypoints, scores = top_k_keypoints(keypoints, scores, self.max_keypoints)
  218. # Convert (y, x) to (x, y)
  219. keypoints = torch.flip(keypoints, [1]).to(scores.dtype)
  220. return keypoints, scores
  221. class SuperPointDescriptorDecoder(nn.Module):
  222. """
  223. The SuperPointDescriptorDecoder uses the outputs of both the SuperPointEncoder and the
  224. SuperPointInterestPointDecoder to compute the descriptors at the keypoints locations.
  225. The descriptors are first computed by a convolutional layer, then normalized to have a norm of 1. The descriptors
  226. are then interpolated at the keypoints locations.
  227. """
  228. def __init__(self, config: SuperPointConfig) -> None:
  229. super().__init__()
  230. self.relu = nn.ReLU(inplace=True)
  231. self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
  232. self.conv_descriptor_a = nn.Conv2d(
  233. config.encoder_hidden_sizes[-1],
  234. config.decoder_hidden_size,
  235. kernel_size=3,
  236. stride=1,
  237. padding=1,
  238. )
  239. self.conv_descriptor_b = nn.Conv2d(
  240. config.decoder_hidden_size,
  241. config.descriptor_decoder_dim,
  242. kernel_size=1,
  243. stride=1,
  244. padding=0,
  245. )
  246. def forward(self, encoded: torch.Tensor, keypoints: torch.Tensor) -> torch.Tensor:
  247. """Based on the encoder output and the keypoints, compute the descriptors for each keypoint"""
  248. descriptors = self.conv_descriptor_b(self.relu(self.conv_descriptor_a(encoded)))
  249. descriptors = nn.functional.normalize(descriptors, p=2, dim=1)
  250. descriptors = self._sample_descriptors(keypoints[None], descriptors[0][None], 8)[0]
  251. # [descriptor_dim, num_keypoints] -> [num_keypoints, descriptor_dim]
  252. descriptors = torch.transpose(descriptors, 0, 1)
  253. return descriptors
  254. @staticmethod
  255. def _sample_descriptors(keypoints, descriptors, scale: int = 8) -> torch.Tensor:
  256. """Interpolate descriptors at keypoint locations"""
  257. batch_size, num_channels, height, width = descriptors.shape
  258. keypoints = keypoints - scale / 2 + 0.5
  259. divisor = torch.tensor([[(width * scale - scale / 2 - 0.5), (height * scale - scale / 2 - 0.5)]])
  260. divisor = divisor.to(keypoints)
  261. keypoints /= divisor
  262. keypoints = keypoints * 2 - 1 # normalize to (-1, 1)
  263. kwargs = {"align_corners": True}
  264. # [batch_size, num_channels, num_keypoints, 2] -> [batch_size, num_channels, num_keypoints, 2]
  265. keypoints = keypoints.view(batch_size, 1, -1, 2)
  266. descriptors = nn.functional.grid_sample(descriptors, keypoints, mode="bilinear", **kwargs)
  267. # [batch_size, descriptor_decoder_dim, num_channels, num_keypoints] -> [batch_size, descriptor_decoder_dim, num_keypoints]
  268. descriptors = descriptors.reshape(batch_size, num_channels, -1)
  269. descriptors = nn.functional.normalize(descriptors, p=2, dim=1)
  270. return descriptors
  271. @auto_docstring
  272. class SuperPointPreTrainedModel(PreTrainedModel):
  273. config: SuperPointConfig
  274. base_model_prefix = "superpoint"
  275. main_input_name = "pixel_values"
  276. supports_gradient_checkpointing = False
  277. def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
  278. """Initialize the weights"""
  279. if isinstance(module, (nn.Linear, nn.Conv2d)):
  280. # Slightly different from the TF version which uses truncated_normal for initialization
  281. # cf https://github.com/pytorch/pytorch/pull/5617
  282. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  283. if module.bias is not None:
  284. module.bias.data.zero_()
  285. elif isinstance(module, nn.LayerNorm):
  286. module.bias.data.zero_()
  287. module.weight.data.fill_(1.0)
  288. def extract_one_channel_pixel_values(self, pixel_values: torch.FloatTensor) -> torch.FloatTensor:
  289. """
  290. Assuming pixel_values has shape (batch_size, 3, height, width), and that all channels values are the same,
  291. extract the first channel value to get a tensor of shape (batch_size, 1, height, width) for SuperPoint. This is
  292. a workaround for the issue discussed in :
  293. https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446
  294. Args:
  295. pixel_values: torch.FloatTensor of shape (batch_size, 3, height, width)
  296. Returns:
  297. pixel_values: torch.FloatTensor of shape (batch_size, 1, height, width)
  298. """
  299. return pixel_values[:, 0, :, :][:, None, :, :]
  300. @auto_docstring(
  301. custom_intro="""
  302. SuperPoint model outputting keypoints and descriptors.
  303. """
  304. )
  305. class SuperPointForKeypointDetection(SuperPointPreTrainedModel):
  306. """
  307. SuperPoint model. It consists of a SuperPointEncoder, a SuperPointInterestPointDecoder and a
  308. SuperPointDescriptorDecoder. SuperPoint was proposed in `SuperPoint: Self-Supervised Interest Point Detection and
  309. Description <https://huggingface.co/papers/1712.07629>`__ by Daniel DeTone, Tomasz Malisiewicz, and Andrew Rabinovich. It
  310. is a fully convolutional neural network that extracts keypoints and descriptors from an image. It is trained in a
  311. self-supervised manner, using a combination of a photometric loss and a loss based on the homographic adaptation of
  312. keypoints. It is made of a convolutional encoder and two decoders: one for keypoints and one for descriptors.
  313. """
  314. def __init__(self, config: SuperPointConfig) -> None:
  315. super().__init__(config)
  316. self.config = config
  317. self.encoder = SuperPointEncoder(config)
  318. self.keypoint_decoder = SuperPointInterestPointDecoder(config)
  319. self.descriptor_decoder = SuperPointDescriptorDecoder(config)
  320. self.post_init()
  321. @auto_docstring
  322. def forward(
  323. self,
  324. pixel_values: torch.FloatTensor,
  325. labels: Optional[torch.LongTensor] = None,
  326. output_hidden_states: Optional[bool] = None,
  327. return_dict: Optional[bool] = None,
  328. ) -> Union[tuple, SuperPointKeypointDescriptionOutput]:
  329. r"""
  330. Examples:
  331. ```python
  332. >>> from transformers import AutoImageProcessor, SuperPointForKeypointDetection
  333. >>> import torch
  334. >>> from PIL import Image
  335. >>> import requests
  336. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  337. >>> image = Image.open(requests.get(url, stream=True).raw)
  338. >>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
  339. >>> model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")
  340. >>> inputs = processor(image, return_tensors="pt")
  341. >>> outputs = model(**inputs)
  342. ```"""
  343. loss = None
  344. if labels is not None:
  345. raise ValueError("SuperPoint does not support training for now.")
  346. output_hidden_states = (
  347. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  348. )
  349. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  350. pixel_values = self.extract_one_channel_pixel_values(pixel_values)
  351. batch_size, _, height, width = pixel_values.shape
  352. encoder_outputs = self.encoder(
  353. pixel_values,
  354. output_hidden_states=output_hidden_states,
  355. return_dict=return_dict,
  356. )
  357. last_hidden_state = encoder_outputs[0]
  358. list_keypoints_scores = [
  359. self.keypoint_decoder(last_hidden_state[None, ...]) for last_hidden_state in last_hidden_state
  360. ]
  361. list_keypoints = [keypoints_scores[0] for keypoints_scores in list_keypoints_scores]
  362. list_scores = [keypoints_scores[1] for keypoints_scores in list_keypoints_scores]
  363. list_descriptors = [
  364. self.descriptor_decoder(last_hidden_state[None, ...], keypoints[None, ...])
  365. for last_hidden_state, keypoints in zip(last_hidden_state, list_keypoints)
  366. ]
  367. maximum_num_keypoints = max(keypoints.shape[0] for keypoints in list_keypoints)
  368. keypoints = torch.zeros((batch_size, maximum_num_keypoints, 2), device=pixel_values.device)
  369. scores = torch.zeros((batch_size, maximum_num_keypoints), device=pixel_values.device)
  370. descriptors = torch.zeros(
  371. (batch_size, maximum_num_keypoints, self.config.descriptor_decoder_dim),
  372. device=pixel_values.device,
  373. )
  374. mask = torch.zeros((batch_size, maximum_num_keypoints), device=pixel_values.device, dtype=torch.int)
  375. for i, (_keypoints, _scores, _descriptors) in enumerate(zip(list_keypoints, list_scores, list_descriptors)):
  376. keypoints[i, : _keypoints.shape[0]] = _keypoints
  377. scores[i, : _scores.shape[0]] = _scores
  378. descriptors[i, : _descriptors.shape[0]] = _descriptors
  379. mask[i, : _scores.shape[0]] = 1
  380. # Convert to relative coordinates
  381. keypoints = keypoints / torch.tensor([width, height], device=keypoints.device)
  382. hidden_states = encoder_outputs[1] if output_hidden_states else None
  383. if not return_dict:
  384. return tuple(v for v in [loss, keypoints, scores, descriptors, mask, hidden_states] if v is not None)
  385. return SuperPointKeypointDescriptionOutput(
  386. loss=loss,
  387. keypoints=keypoints,
  388. scores=scores,
  389. descriptors=descriptors,
  390. mask=mask,
  391. hidden_states=hidden_states,
  392. )
  393. __all__ = ["SuperPointForKeypointDetection", "SuperPointPreTrainedModel"]