position_encoding.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # Copyright (c) 2021 PaddlePaddle Authors. 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. #
  15. # Modified from DETR (https://github.com/facebookresearch/detr)
  16. # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
  17. from __future__ import absolute_import
  18. from __future__ import division
  19. from __future__ import print_function
  20. import math
  21. import paddle
  22. import paddle.nn as nn
  23. from ppdet.core.workspace import register, serializable
  24. @register
  25. @serializable
  26. class PositionEmbedding(nn.Layer):
  27. def __init__(self,
  28. num_pos_feats=128,
  29. temperature=10000,
  30. normalize=True,
  31. scale=None,
  32. embed_type='sine',
  33. num_embeddings=50,
  34. offset=0.):
  35. super(PositionEmbedding, self).__init__()
  36. assert embed_type in ['sine', 'learned']
  37. self.embed_type = embed_type
  38. self.offset = offset
  39. self.eps = 1e-6
  40. if self.embed_type == 'sine':
  41. self.num_pos_feats = num_pos_feats
  42. self.temperature = temperature
  43. self.normalize = normalize
  44. if scale is not None and normalize is False:
  45. raise ValueError("normalize should be True if scale is passed")
  46. if scale is None:
  47. scale = 2 * math.pi
  48. self.scale = scale
  49. elif self.embed_type == 'learned':
  50. self.row_embed = nn.Embedding(num_embeddings, num_pos_feats)
  51. self.col_embed = nn.Embedding(num_embeddings, num_pos_feats)
  52. else:
  53. raise ValueError(f"not supported {self.embed_type}")
  54. def forward(self, mask):
  55. """
  56. Args:
  57. mask (Tensor): [B, H, W]
  58. Returns:
  59. pos (Tensor): [B, C, H, W]
  60. """
  61. assert mask.dtype == paddle.bool
  62. if self.embed_type == 'sine':
  63. mask = mask.astype('float32')
  64. y_embed = mask.cumsum(1, dtype='float32')
  65. x_embed = mask.cumsum(2, dtype='float32')
  66. if self.normalize:
  67. y_embed = (y_embed + self.offset) / (
  68. y_embed[:, -1:, :] + self.eps) * self.scale
  69. x_embed = (x_embed + self.offset) / (
  70. x_embed[:, :, -1:] + self.eps) * self.scale
  71. dim_t = 2 * (paddle.arange(self.num_pos_feats) //
  72. 2).astype('float32')
  73. dim_t = self.temperature**(dim_t / self.num_pos_feats)
  74. pos_x = x_embed.unsqueeze(-1) / dim_t
  75. pos_y = y_embed.unsqueeze(-1) / dim_t
  76. pos_x = paddle.stack(
  77. (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()),
  78. axis=4).flatten(3)
  79. pos_y = paddle.stack(
  80. (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()),
  81. axis=4).flatten(3)
  82. pos = paddle.concat((pos_y, pos_x), axis=3).transpose([0, 3, 1, 2])
  83. return pos
  84. elif self.embed_type == 'learned':
  85. h, w = mask.shape[-2:]
  86. i = paddle.arange(w)
  87. j = paddle.arange(h)
  88. x_emb = self.col_embed(i)
  89. y_emb = self.row_embed(j)
  90. pos = paddle.concat(
  91. [
  92. x_emb.unsqueeze(0).repeat(h, 1, 1),
  93. y_emb.unsqueeze(1).repeat(1, w, 1),
  94. ],
  95. axis=-1).transpose([2, 0, 1]).unsqueeze(0).tile(mask.shape[0],
  96. 1, 1, 1)
  97. return pos
  98. else:
  99. raise ValueError(f"not supported {self.embed_type}")