MCPcopy Create free account
hub / github.com/MotrixLab/AiOS / PositionEmbeddingSine_1D

Class PositionEmbeddingSine_1D

detrsmpl/core/post_processing/speed_up/deciwatch.py:123–162  ·  view source on GitHub ↗

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.

Source from the content-addressed store, hash-verified

121
122
123class PositionEmbeddingSine_1D(nn.Module):
124 """This is a more standard version of the position embedding, very similar
125 to the one used by the Attention is all you need paper, generalized to work
126 on images."""
127
128 def __init__(self,
129 num_pos_feats=64,
130 temperature=10000,
131 normalize=True,
132 scale=None):
133 super().__init__()
134 self.num_pos_feats = num_pos_feats
135 self.temperature = temperature
136 self.normalize = normalize
137 if scale is not None and normalize is False:
138 raise ValueError('normalize should be True if scale is passed')
139 if scale is None:
140 scale = 2 * math.pi
141 self.scale = scale
142
143 def forward(self, B, L):
144
145 position = torch.arange(0, L, dtype=torch.float32).unsqueeze(0)
146 position = position.repeat(B, 1)
147
148 if self.normalize:
149 eps = 1e-6
150 position = position / (position[:, -1:] + eps) * self.scale
151
152 dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32)
153 dim_t = self.temperature**(2 * (torch.div(dim_t, 1)) /
154 self.num_pos_feats)
155
156 pe = torch.zeros(B, L, self.num_pos_feats * 2)
157 pe[:, :, 0::2] = torch.sin(position[:, :, None] / dim_t)
158 pe[:, :, 1::2] = torch.cos(position[:, :, None] / dim_t)
159
160 pe = pe.permute(1, 0, 2)
161
162 return pe
163
164
165class DeciWatch(nn.Module):

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected