This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images.
| 13 | |
| 14 | |
| 15 | class PositionEmbeddingSine(nn.Module): |
| 16 | """ |
| 17 | This is a more standard version of the position embedding, very similar to the one |
| 18 | used by the Attention is all you need paper, generalized to work on images. |
| 19 | """ |
| 20 | |
| 21 | def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): |
| 22 | super().__init__() |
| 23 | self.num_pos_feats = num_pos_feats |
| 24 | self.temperature = temperature |
| 25 | self.normalize = normalize |
| 26 | if scale is not None and normalize is False: |
| 27 | raise ValueError("normalize should be True if scale is passed") |
| 28 | if scale is None: |
| 29 | scale = 2 * math.pi |
| 30 | self.scale = scale |
| 31 | |
| 32 | def forward(self, x, mask=None): |
| 33 | if mask is None: |
| 34 | mask = torch.zeros((x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool) |
| 35 | not_mask = ~mask |
| 36 | y_embed = not_mask.cumsum(1, dtype=torch.float32) |
| 37 | x_embed = not_mask.cumsum(2, dtype=torch.float32) |
| 38 | if self.normalize: |
| 39 | eps = 1e-6 |
| 40 | y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale |
| 41 | x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale |
| 42 | |
| 43 | dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) |
| 44 | dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) |
| 45 | |
| 46 | pos_x = x_embed[:, :, :, None] / dim_t |
| 47 | pos_y = y_embed[:, :, :, None] / dim_t |
| 48 | pos_x = torch.stack( |
| 49 | (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 |
| 50 | ).flatten(3) |
| 51 | pos_y = torch.stack( |
| 52 | (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 |
| 53 | ).flatten(3) |
| 54 | pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) |
| 55 | return pos |
| 56 | |
| 57 | def __repr__(self, _repr_indent=4): |
| 58 | head = "Positional encoding " + self.__class__.__name__ |
| 59 | body = [ |
| 60 | "num_pos_feats: {}".format(self.num_pos_feats), |
| 61 | "temperature: {}".format(self.temperature), |
| 62 | "normalize: {}".format(self.normalize), |
| 63 | "scale: {}".format(self.scale), |
| 64 | ] |
| 65 | # _repr_indent = 4 |
| 66 | lines = [head] + [" " * _repr_indent + line for line in body] |
| 67 | return "\n".join(lines) |