Create position_encoding.py
Browse files- position_encoding.py +86 -0
position_encoding.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
2 |
+
import math
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
|
6 |
+
from caption_project.utils import NestedTensor
|
7 |
+
|
8 |
+
|
9 |
+
class PositionEmbeddingSine(nn.Module):
|
10 |
+
"""
|
11 |
+
This is a more standard version of the position embedding, very similar to the one
|
12 |
+
used by the Attention is all you need paper, generalized to work on images.
|
13 |
+
"""
|
14 |
+
def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
|
15 |
+
super().__init__()
|
16 |
+
self.num_pos_feats = num_pos_feats
|
17 |
+
self.temperature = temperature
|
18 |
+
self.normalize = normalize
|
19 |
+
if scale is not None and normalize is False:
|
20 |
+
raise ValueError("normalize should be True if scale is passed")
|
21 |
+
if scale is None:
|
22 |
+
scale = 2 * math.pi
|
23 |
+
self.scale = scale
|
24 |
+
|
25 |
+
def forward(self, tensor_list: NestedTensor):
|
26 |
+
x = tensor_list.tensors
|
27 |
+
mask = tensor_list.mask
|
28 |
+
assert mask is not None
|
29 |
+
not_mask = ~mask
|
30 |
+
y_embed = not_mask.cumsum(1, dtype=torch.float32)
|
31 |
+
x_embed = not_mask.cumsum(2, dtype=torch.float32)
|
32 |
+
if self.normalize:
|
33 |
+
eps = 1e-6
|
34 |
+
y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
|
35 |
+
x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
|
36 |
+
|
37 |
+
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
|
38 |
+
dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
|
39 |
+
|
40 |
+
pos_x = x_embed[:, :, :, None] / dim_t
|
41 |
+
pos_y = y_embed[:, :, :, None] / dim_t
|
42 |
+
pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
43 |
+
pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
44 |
+
pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
|
45 |
+
return pos
|
46 |
+
|
47 |
+
|
48 |
+
class PositionEmbeddingLearned(nn.Module):
|
49 |
+
"""
|
50 |
+
Absolute pos embedding, learned.
|
51 |
+
"""
|
52 |
+
def __init__(self, num_pos_feats=256):
|
53 |
+
super().__init__()
|
54 |
+
self.row_embed = nn.Embedding(50, num_pos_feats)
|
55 |
+
self.col_embed = nn.Embedding(50, num_pos_feats)
|
56 |
+
self.reset_parameters()
|
57 |
+
|
58 |
+
def reset_parameters(self):
|
59 |
+
nn.init.uniform_(self.row_embed.weight)
|
60 |
+
nn.init.uniform_(self.col_embed.weight)
|
61 |
+
|
62 |
+
def forward(self, tensor_list: NestedTensor):
|
63 |
+
x = tensor_list.tensors
|
64 |
+
h, w = x.shape[-2:]
|
65 |
+
i = torch.arange(w, device=x.device)
|
66 |
+
j = torch.arange(h, device=x.device)
|
67 |
+
x_emb = self.col_embed(i)
|
68 |
+
y_emb = self.row_embed(j)
|
69 |
+
pos = torch.cat([
|
70 |
+
x_emb.unsqueeze(0).repeat(h, 1, 1),
|
71 |
+
y_emb.unsqueeze(1).repeat(1, w, 1),
|
72 |
+
], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
|
73 |
+
return pos
|
74 |
+
|
75 |
+
|
76 |
+
def build_position_encoding(config):
|
77 |
+
N_steps = config.hidden_dim // 2
|
78 |
+
if config.position_embedding in ('v2', 'sine'):
|
79 |
+
# TODO find a better way of exposing other arguments
|
80 |
+
position_embedding = PositionEmbeddingSine(N_steps, normalize=True)
|
81 |
+
elif config.position_embedding in ('v3', 'learned'):
|
82 |
+
position_embedding = PositionEmbeddingLearned(N_steps)
|
83 |
+
else:
|
84 |
+
raise ValueError(f"not supported {config.position_embedding}")
|
85 |
+
|
86 |
+
return position_embedding
|