position_encoding.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import math
  6. from typing import Any, Optional, Tuple
  7. import numpy as np
  8. import torch
  9. from torch import nn
  10. class PositionEmbeddingSine(nn.Module):
  11. """
  12. This is a more standard version of the position embedding, very similar to the one
  13. used by the Attention Is All You Need paper, generalized to work on images.
  14. """
  15. def __init__(
  16. self,
  17. num_pos_feats,
  18. temperature: int = 10000,
  19. normalize: bool = True,
  20. scale: Optional[float] = None,
  21. ):
  22. super().__init__()
  23. assert num_pos_feats % 2 == 0, "Expecting even model width"
  24. self.num_pos_feats = num_pos_feats // 2
  25. self.temperature = temperature
  26. self.normalize = normalize
  27. if scale is not None and normalize is False:
  28. raise ValueError("normalize should be True if scale is passed")
  29. if scale is None:
  30. scale = 2 * math.pi
  31. self.scale = scale
  32. self.cache = {}
  33. def _encode_xy(self, x, y):
  34. # The positions are expected to be normalized
  35. assert len(x) == len(y) and x.ndim == y.ndim == 1
  36. x_embed = x * self.scale
  37. y_embed = y * self.scale
  38. dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
  39. dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
  40. pos_x = x_embed[:, None] / dim_t
  41. pos_y = y_embed[:, None] / dim_t
  42. pos_x = torch.stack(
  43. (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2
  44. ).flatten(1)
  45. pos_y = torch.stack(
  46. (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2
  47. ).flatten(1)
  48. return pos_x, pos_y
  49. @torch.no_grad()
  50. def encode_boxes(self, x, y, w, h):
  51. pos_x, pos_y = self._encode_xy(x, y)
  52. pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1)
  53. return pos
  54. encode = encode_boxes # Backwards compatibility
  55. @torch.no_grad()
  56. def encode_points(self, x, y, labels):
  57. (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape
  58. assert bx == by and nx == ny and bx == bl and nx == nl
  59. pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten())
  60. pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1)
  61. pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2)
  62. return pos
  63. @torch.no_grad()
  64. def forward(self, x: torch.Tensor):
  65. cache_key = (x.shape[-2], x.shape[-1])
  66. if cache_key in self.cache:
  67. return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1)
  68. y_embed = (
  69. torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device)
  70. .view(1, -1, 1)
  71. .repeat(x.shape[0], 1, x.shape[-1])
  72. )
  73. x_embed = (
  74. torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device)
  75. .view(1, 1, -1)
  76. .repeat(x.shape[0], x.shape[-2], 1)
  77. )
  78. if self.normalize:
  79. eps = 1e-6
  80. y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
  81. x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
  82. dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
  83. dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
  84. pos_x = x_embed[:, :, :, None] / dim_t
  85. pos_y = y_embed[:, :, :, None] / dim_t
  86. pos_x = torch.stack(
  87. (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
  88. ).flatten(3)
  89. pos_y = torch.stack(
  90. (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
  91. ).flatten(3)
  92. pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
  93. self.cache[cache_key] = pos[0]
  94. return pos
  95. class PositionEmbeddingRandom(nn.Module):
  96. """
  97. Positional encoding using random spatial frequencies.
  98. """
  99. def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
  100. super().__init__()
  101. if scale is None or scale <= 0.0:
  102. scale = 1.0
  103. self.register_buffer(
  104. "positional_encoding_gaussian_matrix",
  105. scale * torch.randn((2, num_pos_feats)),
  106. )
  107. def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
  108. """Positionally encode points that are normalized to [0,1]."""
  109. # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
  110. coords = 2 * coords - 1
  111. coords = coords @ self.positional_encoding_gaussian_matrix
  112. coords = 2 * np.pi * coords
  113. # outputs d_1 x ... x d_n x C shape
  114. return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
  115. def forward(self, size: Tuple[int, int]) -> torch.Tensor:
  116. """Generate positional encoding for a grid of the specified size."""
  117. h, w = size
  118. device: Any = self.positional_encoding_gaussian_matrix.device
  119. grid = torch.ones((h, w), device=device, dtype=torch.float32)
  120. y_embed = grid.cumsum(dim=0) - 0.5
  121. x_embed = grid.cumsum(dim=1) - 0.5
  122. y_embed = y_embed / h
  123. x_embed = x_embed / w
  124. pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
  125. return pe.permute(2, 0, 1) # C x H x W
  126. def forward_with_coords(
  127. self, coords_input: torch.Tensor, image_size: Tuple[int, int]
  128. ) -> torch.Tensor:
  129. """Positionally encode points that are not normalized to [0,1]."""
  130. coords = coords_input.clone()
  131. coords[:, :, 0] = coords[:, :, 0] / image_size[1]
  132. coords[:, :, 1] = coords[:, :, 1] / image_size[0]
  133. return self._pe_encoding(coords.to(torch.float)) # B x N x C
  134. # Rotary Positional Encoding, adapted from:
  135. # 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py
  136. # 2. https://github.com/naver-ai/rope-vit
  137. # 3. https://github.com/lucidrains/rotary-embedding-torch
  138. def init_t_xy(end_x: int, end_y: int):
  139. t = torch.arange(end_x * end_y, dtype=torch.float32)
  140. t_x = (t % end_x).float()
  141. t_y = torch.div(t, end_x, rounding_mode="floor").float()
  142. return t_x, t_y
  143. def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0):
  144. freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
  145. freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
  146. t_x, t_y = init_t_xy(end_x, end_y)
  147. freqs_x = torch.outer(t_x, freqs_x)
  148. freqs_y = torch.outer(t_y, freqs_y)
  149. freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
  150. freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
  151. return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1)
  152. def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
  153. ndim = x.ndim
  154. assert 0 <= 1 < ndim
  155. assert freqs_cis.shape == (x.shape[-2], x.shape[-1])
  156. shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)]
  157. return freqs_cis.view(*shape)
  158. def apply_rotary_enc(
  159. xq: torch.Tensor,
  160. xk: torch.Tensor,
  161. freqs_cis: torch.Tensor,
  162. repeat_freqs_k: bool = False,
  163. ):
  164. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  165. xk_ = (
  166. torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  167. if xk.shape[-2] != 0
  168. else None
  169. )
  170. freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
  171. xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
  172. if xk_ is None:
  173. # no keys to rotate, due to dropout
  174. return xq_out.type_as(xq).to(xq.device), xk
  175. # repeat freqs along seq_len dim to match k seq_len
  176. if repeat_freqs_k:
  177. r = xk_.shape[-2] // xq_.shape[-2]
  178. if freqs_cis.is_cuda:
  179. freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1)
  180. else:
  181. # torch.repeat on complex numbers may not be supported on non-CUDA devices
  182. # (freqs_cis has 4 dims and we repeat on dim 2) so we use expand + flatten
  183. freqs_cis = freqs_cis.unsqueeze(2).expand(-1, -1, r, -1, -1).flatten(2, 3)
  184. xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
  185. return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device)