superglue.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. # %BANNER_BEGIN%
  2. # ---------------------------------------------------------------------
  3. # %COPYRIGHT_BEGIN%
  4. #
  5. # Magic Leap, Inc. ("COMPANY") CONFIDENTIAL
  6. #
  7. # Unpublished Copyright (c) 2020
  8. # Magic Leap, Inc., All Rights Reserved.
  9. #
  10. # NOTICE: All information contained herein is, and remains the property
  11. # of COMPANY. The intellectual and technical concepts contained herein
  12. # are proprietary to COMPANY and may be covered by U.S. and Foreign
  13. # Patents, patents in process, and are protected by trade secret or
  14. # copyright law. Dissemination of this information or reproduction of
  15. # this material is strictly forbidden unless prior written permission is
  16. # obtained from COMPANY. Access to the source code contained herein is
  17. # hereby forbidden to anyone except current COMPANY employees, managers
  18. # or contractors who have executed Confidentiality and Non-disclosure
  19. # agreements explicitly covering such access.
  20. #
  21. # The copyright notice above does not evidence any actual or intended
  22. # publication or disclosure of this source code, which includes
  23. # information that is confidential and/or proprietary, and is a trade
  24. # secret, of COMPANY. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION,
  25. # PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS
  26. # SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF COMPANY IS
  27. # STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS AND
  28. # INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE
  29. # CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS
  30. # TO REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE,
  31. # USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.
  32. #
  33. # %COPYRIGHT_END%
  34. # ----------------------------------------------------------------------
  35. # %AUTHORS_BEGIN%
  36. #
  37. # Originating Authors: Paul-Edouard Sarlin
  38. #
  39. # %AUTHORS_END%
  40. # --------------------------------------------------------------------*/
  41. # %BANNER_END%
  42. from copy import deepcopy
  43. from typing import List, Tuple
  44. import torch
  45. from torch import nn
  46. def MLP(channels: List[int], do_bn: bool = True) -> nn.Module:
  47. """ Multi-layer perceptron """
  48. n = len(channels)
  49. layers = []
  50. for i in range(1, n):
  51. layers.append(
  52. nn.Conv1d(channels[i - 1], channels[i], kernel_size=1, bias=True))
  53. if i < (n-1):
  54. if do_bn:
  55. layers.append(nn.BatchNorm1d(channels[i]))
  56. layers.append(nn.ReLU())
  57. return nn.Sequential(*layers)
  58. def normalize_keypoints(kpts, image_shape):
  59. """ Normalize keypoints locations based on image image_shape"""
  60. height, width = image_shape[:2]
  61. one = kpts.new_tensor(1)
  62. size = torch.stack([one*width, one*height])[None]
  63. center = size / 2
  64. scaling = size.max(1, keepdim=True).values * 0.7
  65. return (kpts - center[:, None, :]) / scaling[:, None, :]
  66. class KeypointEncoder(nn.Module):
  67. """ Joint encoding of visual appearance and location using MLPs"""
  68. def __init__(self, feature_dim: int, layers: List[int]) -> None:
  69. super().__init__()
  70. self.encoder = MLP([3] + layers + [feature_dim])
  71. nn.init.constant_(self.encoder[-1].bias, 0.0)
  72. def forward(self, kpts, scores):
  73. inputs = [kpts.transpose(1, 2), scores.unsqueeze(1)]
  74. return self.encoder(torch.cat(inputs, dim=1))
  75. def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> Tuple[torch.Tensor,torch.Tensor]:
  76. dim = query.shape[1]
  77. scores = torch.einsum('bdhn,bdhm->bhnm', query, key) / dim**.5
  78. prob = torch.nn.functional.softmax(scores, dim=-1)
  79. return torch.einsum('bhnm,bdhm->bdhn', prob, value), prob
  80. class MultiHeadedAttention(nn.Module):
  81. """ Multi-head attention to increase model expressivitiy """
  82. def __init__(self, num_heads: int, d_model: int):
  83. super().__init__()
  84. assert d_model % num_heads == 0
  85. self.dim = d_model // num_heads
  86. self.num_heads = num_heads
  87. self.merge = nn.Conv1d(d_model, d_model, kernel_size=1)
  88. self.proj = nn.ModuleList([deepcopy(self.merge) for _ in range(3)])
  89. def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
  90. batch_dim = query.size(0)
  91. query, key, value = [l(x).view(batch_dim, self.dim, self.num_heads, -1)
  92. for l, x in zip(self.proj, (query, key, value))]
  93. x, _ = attention(query, key, value)
  94. return self.merge(x.contiguous().view(batch_dim, self.dim*self.num_heads, -1))
  95. class AttentionalPropagation(nn.Module):
  96. def __init__(self, feature_dim: int, num_heads: int):
  97. super().__init__()
  98. self.attn = MultiHeadedAttention(num_heads, feature_dim)
  99. self.mlp = MLP([feature_dim*2, feature_dim*2, feature_dim])
  100. nn.init.constant_(self.mlp[-1].bias, 0.0)
  101. def forward(self, x: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
  102. message = self.attn(x, source, source)
  103. return self.mlp(torch.cat([x, message], dim=1))
  104. class AttentionalGNN(nn.Module):
  105. def __init__(self, feature_dim: int, layer_names: List[str]) -> None:
  106. super().__init__()
  107. self.layers = nn.ModuleList([
  108. AttentionalPropagation(feature_dim, 4)
  109. for _ in range(len(layer_names))])
  110. self.names = layer_names
  111. def forward(self, desc0: torch.Tensor, desc1: torch.Tensor) -> Tuple[torch.Tensor,torch.Tensor]:
  112. for layer, name in zip(self.layers, self.names):
  113. if name == 'cross':
  114. src0, src1 = desc1, desc0
  115. else: # if name == 'self':
  116. src0, src1 = desc0, desc1
  117. delta0, delta1 = layer(desc0, src0), layer(desc1, src1)
  118. desc0, desc1 = (desc0 + delta0), (desc1 + delta1)
  119. return desc0, desc1
  120. def log_sinkhorn_iterations(Z: torch.Tensor, log_mu: torch.Tensor, log_nu: torch.Tensor, iters: int) -> torch.Tensor:
  121. """ Perform Sinkhorn Normalization in Log-space for stability"""
  122. u, v = torch.zeros_like(log_mu), torch.zeros_like(log_nu)
  123. for _ in range(iters):
  124. u = log_mu - torch.logsumexp(Z + v.unsqueeze(1), dim=2)
  125. v = log_nu - torch.logsumexp(Z + u.unsqueeze(2), dim=1)
  126. return Z + u.unsqueeze(2) + v.unsqueeze(1)
  127. def log_optimal_transport(scores: torch.Tensor, alpha: torch.Tensor, iters: int) -> torch.Tensor:
  128. """ Perform Differentiable Optimal Transport in Log-space for stability"""
  129. b, m, n = scores.shape
  130. one = scores.new_tensor(1)
  131. ms, ns = (m*one).to(scores), (n*one).to(scores)
  132. bins0 = alpha.expand(b, m, 1)
  133. bins1 = alpha.expand(b, 1, n)
  134. alpha = alpha.expand(b, 1, 1)
  135. couplings = torch.cat([torch.cat([scores, bins0], -1),
  136. torch.cat([bins1, alpha], -1)], 1)
  137. norm = - (ms + ns).log()
  138. log_mu = torch.cat([norm.expand(m), ns.log()[None] + norm])
  139. log_nu = torch.cat([norm.expand(n), ms.log()[None] + norm])
  140. log_mu, log_nu = log_mu[None].expand(b, -1), log_nu[None].expand(b, -1)
  141. Z = log_sinkhorn_iterations(couplings, log_mu, log_nu, iters)
  142. Z = Z - norm # multiply probabilities by M+N
  143. return Z
  144. def arange_like(x, dim: int):
  145. return x.new_ones(x.shape[dim]).cumsum(0) - 1 # traceable in 1.1
  146. class SuperGlue(nn.Module):
  147. """SuperGlue feature matching middle-end
  148. Given two sets of keypoints and locations, we determine the
  149. correspondences by:
  150. 1. Keypoint Encoding (normalization + visual feature and location fusion)
  151. 2. Graph Neural Network with multiple self and cross-attention layers
  152. 3. Final projection layer
  153. 4. Optimal Transport Layer (a differentiable Hungarian matching algorithm)
  154. 5. Thresholding matrix based on mutual exclusivity and a match_threshold
  155. The correspondence ids use -1 to indicate non-matching points.
  156. Paul-Edouard Sarlin, Daniel DeTone, Tomasz Malisiewicz, and Andrew
  157. Rabinovich. SuperGlue: Learning Feature Matching with Graph Neural
  158. Networks. In CVPR, 2020. https://arxiv.org/abs/1911.11763
  159. """
  160. default_config = {
  161. 'descriptor_dim': 256,
  162. 'weights': 'indoor',
  163. 'keypoint_encoder': [32, 64, 128, 256],
  164. 'GNN_layers': ['self', 'cross'] * 9,
  165. 'sinkhorn_iterations': 100,
  166. 'match_threshold': 0.2,
  167. }
  168. def __init__(self, config):
  169. super().__init__()
  170. self.config = {**self.default_config, **config}
  171. self.kenc = KeypointEncoder(
  172. self.config['descriptor_dim'], self.config['keypoint_encoder'])
  173. self.gnn = AttentionalGNN(
  174. feature_dim=self.config['descriptor_dim'], layer_names=self.config['GNN_layers'])
  175. self.final_proj = nn.Conv1d(
  176. self.config['descriptor_dim'], self.config['descriptor_dim'],
  177. kernel_size=1, bias=True)
  178. bin_score = torch.nn.Parameter(torch.tensor(1.))
  179. self.register_parameter('bin_score', bin_score)
  180. def forward(self, data):
  181. """Run SuperGlue on a pair of keypoints and descriptors"""
  182. desc0, desc1 = data['descriptors0'], data['descriptors1']
  183. kpts0, kpts1 = data['keypoints0'], data['keypoints1']
  184. if kpts0.shape[1] == 0 or kpts1.shape[1] == 0: # no keypoints
  185. shape0, shape1 = kpts0.shape[:-1], kpts1.shape[:-1]
  186. return {
  187. 'matches0': kpts0.new_full(shape0, -1, dtype=torch.int),
  188. 'matches1': kpts1.new_full(shape1, -1, dtype=torch.int),
  189. 'matching_scores0': kpts0.new_zeros(shape0),
  190. 'matching_scores1': kpts1.new_zeros(shape1),
  191. }
  192. # Keypoint normalization.
  193. kpts0 = normalize_keypoints(kpts0, data['image0_shape'])
  194. kpts1 = normalize_keypoints(kpts1, data['image1_shape'])
  195. # Keypoint MLP encoder.
  196. desc0 = desc0 + self.kenc(kpts0, data['scores0'])
  197. desc1 = desc1 + self.kenc(kpts1, data['scores1'])
  198. del data
  199. # Multi-layer Transformer network.
  200. desc0, desc1 = self.gnn(desc0, desc1)
  201. # Final MLP projection.
  202. mdesc0, mdesc1 = self.final_proj(desc0), self.final_proj(desc1)
  203. # Compute matching descriptor distance.
  204. scores = torch.einsum('bdn,bdm->bnm', mdesc0, mdesc1)
  205. scores = scores / self.config['descriptor_dim']**.5
  206. # Run the optimal transport.
  207. scores = log_optimal_transport(
  208. scores, self.bin_score,
  209. iters=self.config['sinkhorn_iterations'])
  210. # Get the matches with score above "match_threshold".
  211. max0, max1 = scores[:, :-1, :-1].max(2), scores[:, :-1, :-1].max(1)
  212. indices0, indices1 = max0.indices, max1.indices
  213. mutual0 = arange_like(indices0, 1)[None] == indices1.gather(1, indices0)
  214. mutual1 = arange_like(indices1, 1)[None] == indices0.gather(1, indices1)
  215. zero = scores.new_tensor(0)
  216. mscores0 = torch.where(mutual0, max0.values.exp(), zero)
  217. mscores1 = torch.where(mutual1, mscores0.gather(1, indices1), zero)
  218. valid0 = mutual0 & (mscores0 > self.config['match_threshold'])
  219. valid1 = mutual1 & valid0.gather(1, indices1)
  220. indices0 = torch.where(valid0, indices0, indices0.new_tensor(-1))
  221. indices1 = torch.where(valid1, indices1, indices1.new_tensor(-1))
  222. return {
  223. 'matches0': indices0, # use -1 for invalid match
  224. 'matches1': indices1, # use -1 for invalid match
  225. 'matching_scores0': mscores0,
  226. 'matching_scores1': mscores1,
  227. }