You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

positional_encoding.py 6.6 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. from mmcv.cnn.bricks.transformer import POSITIONAL_ENCODING
  6. from mmcv.runner import BaseModule
  7. @POSITIONAL_ENCODING.register_module()
  8. class SinePositionalEncoding(BaseModule):
  9. """Position encoding with sine and cosine functions.
  10. See `End-to-End Object Detection with Transformers
  11. <https://arxiv.org/pdf/2005.12872>`_ for details.
  12. Args:
  13. num_feats (int): The feature dimension for each position
  14. along x-axis or y-axis. Note the final returned dimension
  15. for each position is 2 times of this value.
  16. temperature (int, optional): The temperature used for scaling
  17. the position embedding. Defaults to 10000.
  18. normalize (bool, optional): Whether to normalize the position
  19. embedding. Defaults to False.
  20. scale (float, optional): A scale factor that scales the position
  21. embedding. The scale will be used only when `normalize` is True.
  22. Defaults to 2*pi.
  23. eps (float, optional): A value added to the denominator for
  24. numerical stability. Defaults to 1e-6.
  25. offset (float): offset add to embed when do the normalization.
  26. Defaults to 0.
  27. init_cfg (dict or list[dict], optional): Initialization config dict.
  28. Default: None
  29. """
  30. def __init__(self,
  31. num_feats,
  32. temperature=10000,
  33. normalize=False,
  34. scale=2 * math.pi,
  35. eps=1e-6,
  36. offset=0.,
  37. init_cfg=None):
  38. super(SinePositionalEncoding, self).__init__(init_cfg)
  39. if normalize:
  40. assert isinstance(scale, (float, int)), 'when normalize is set,' \
  41. 'scale should be provided and in float or int type, ' \
  42. f'found {type(scale)}'
  43. self.num_feats = num_feats
  44. self.temperature = temperature
  45. self.normalize = normalize
  46. self.scale = scale
  47. self.eps = eps
  48. self.offset = offset
  49. def forward(self, mask):
  50. """Forward function for `SinePositionalEncoding`.
  51. Args:
  52. mask (Tensor): ByteTensor mask. Non-zero values representing
  53. ignored positions, while zero values means valid positions
  54. for this image. Shape [bs, h, w].
  55. Returns:
  56. pos (Tensor): Returned position embedding with shape
  57. [bs, num_feats*2, h, w].
  58. """
  59. # For convenience of exporting to ONNX, it's required to convert
  60. # `masks` from bool to int.
  61. mask = mask.to(torch.int)
  62. not_mask = 1 - mask # logical_not
  63. y_embed = not_mask.cumsum(1, dtype=torch.float32)
  64. x_embed = not_mask.cumsum(2, dtype=torch.float32)
  65. if self.normalize:
  66. y_embed = (y_embed + self.offset) / \
  67. (y_embed[:, -1:, :] + self.eps) * self.scale
  68. x_embed = (x_embed + self.offset) / \
  69. (x_embed[:, :, -1:] + self.eps) * self.scale
  70. dim_t = torch.arange(
  71. self.num_feats, dtype=torch.float32, device=mask.device)
  72. dim_t = self.temperature**(2 * (dim_t // 2) / self.num_feats)
  73. pos_x = x_embed[:, :, :, None] / dim_t
  74. pos_y = y_embed[:, :, :, None] / dim_t
  75. # use `view` instead of `flatten` for dynamically exporting to ONNX
  76. B, H, W = mask.size()
  77. pos_x = torch.stack(
  78. (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()),
  79. dim=4).view(B, H, W, -1)
  80. pos_y = torch.stack(
  81. (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()),
  82. dim=4).view(B, H, W, -1)
  83. pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
  84. return pos
  85. def __repr__(self):
  86. """str: a string that describes the module"""
  87. repr_str = self.__class__.__name__
  88. repr_str += f'(num_feats={self.num_feats}, '
  89. repr_str += f'temperature={self.temperature}, '
  90. repr_str += f'normalize={self.normalize}, '
  91. repr_str += f'scale={self.scale}, '
  92. repr_str += f'eps={self.eps})'
  93. return repr_str
  94. @POSITIONAL_ENCODING.register_module()
  95. class LearnedPositionalEncoding(BaseModule):
  96. """Position embedding with learnable embedding weights.
  97. Args:
  98. num_feats (int): The feature dimension for each position
  99. along x-axis or y-axis. The final returned dimension for
  100. each position is 2 times of this value.
  101. row_num_embed (int, optional): The dictionary size of row embeddings.
  102. Default 50.
  103. col_num_embed (int, optional): The dictionary size of col embeddings.
  104. Default 50.
  105. init_cfg (dict or list[dict], optional): Initialization config dict.
  106. """
  107. def __init__(self,
  108. num_feats,
  109. row_num_embed=50,
  110. col_num_embed=50,
  111. init_cfg=dict(type='Uniform', layer='Embedding')):
  112. super(LearnedPositionalEncoding, self).__init__(init_cfg)
  113. self.row_embed = nn.Embedding(row_num_embed, num_feats)
  114. self.col_embed = nn.Embedding(col_num_embed, num_feats)
  115. self.num_feats = num_feats
  116. self.row_num_embed = row_num_embed
  117. self.col_num_embed = col_num_embed
  118. def forward(self, mask):
  119. """Forward function for `LearnedPositionalEncoding`.
  120. Args:
  121. mask (Tensor): ByteTensor mask. Non-zero values representing
  122. ignored positions, while zero values means valid positions
  123. for this image. Shape [bs, h, w].
  124. Returns:
  125. pos (Tensor): Returned position embedding with shape
  126. [bs, num_feats*2, h, w].
  127. """
  128. h, w = mask.shape[-2:]
  129. x = torch.arange(w, device=mask.device)
  130. y = torch.arange(h, device=mask.device)
  131. x_embed = self.col_embed(x)
  132. y_embed = self.row_embed(y)
  133. pos = torch.cat(
  134. (x_embed.unsqueeze(0).repeat(h, 1, 1), y_embed.unsqueeze(1).repeat(
  135. 1, w, 1)),
  136. dim=-1).permute(2, 0,
  137. 1).unsqueeze(0).repeat(mask.shape[0], 1, 1, 1)
  138. return pos
  139. def __repr__(self):
  140. """str: a string that describes the module"""
  141. repr_str = self.__class__.__name__
  142. repr_str += f'(num_feats={self.num_feats}, '
  143. repr_str += f'row_num_embed={self.row_num_embed}, '
  144. repr_str += f'col_num_embed={self.col_num_embed})'
  145. return repr_str

No Description

Contributors (1)