position_encoding.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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=2 * math.pi,
  32. embed_type='sine',
  33. num_embeddings=50,
  34. offset=0.,
  35. eps=1e-6):
  36. super(PositionEmbedding, self).__init__()
  37. assert embed_type in ['sine', 'learned']
  38. self.embed_type = embed_type
  39. self.offset = offset
  40. self.eps = eps
  41. if self.embed_type == 'sine':
  42. self.num_pos_feats = num_pos_feats
  43. self.temperature = temperature
  44. self.normalize = normalize
  45. self.scale = scale
  46. elif self.embed_type == 'learned':
  47. self.row_embed = nn.Embedding(num_embeddings, num_pos_feats)
  48. self.col_embed = nn.Embedding(num_embeddings, num_pos_feats)
  49. else:
  50. raise ValueError(f"{self.embed_type} is not supported.")
  51. def forward(self, mask):
  52. """
  53. Args:
  54. mask (Tensor): [B, H, W]
  55. Returns:
  56. pos (Tensor): [B, H, W, C]
  57. """
  58. if self.embed_type == 'sine':
  59. y_embed = mask.cumsum(1)
  60. x_embed = mask.cumsum(2)
  61. if self.normalize:
  62. y_embed = (y_embed + self.offset) / (
  63. y_embed[:, -1:, :] + self.eps) * self.scale
  64. x_embed = (x_embed + self.offset) / (
  65. x_embed[:, :, -1:] + self.eps) * self.scale
  66. dim_t = 2 * (paddle.arange(self.num_pos_feats) //
  67. 2).astype('float32')
  68. dim_t = self.temperature**(dim_t / self.num_pos_feats)
  69. pos_x = x_embed.unsqueeze(-1) / dim_t
  70. pos_y = y_embed.unsqueeze(-1) / dim_t
  71. pos_x = paddle.stack(
  72. (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()),
  73. axis=4).flatten(3)
  74. pos_y = paddle.stack(
  75. (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()),
  76. axis=4).flatten(3)
  77. return paddle.concat((pos_y, pos_x), axis=3)
  78. elif self.embed_type == 'learned':
  79. h, w = mask.shape[-2:]
  80. i = paddle.arange(w)
  81. j = paddle.arange(h)
  82. x_emb = self.col_embed(i)
  83. y_emb = self.row_embed(j)
  84. return paddle.concat(
  85. [
  86. x_emb.unsqueeze(0).tile([h, 1, 1]),
  87. y_emb.unsqueeze(1).tile([1, w, 1]),
  88. ],
  89. axis=-1).unsqueeze(0)
  90. else:
  91. raise ValueError(f"not supported {self.embed_type}")