Positional encoding using random spatial frequencies.
| 173 | |
| 174 | |
| 175 | class PositionEmbeddingRandom(nn.Module): |
| 176 | """ |
| 177 | Positional encoding using random spatial frequencies. |
| 178 | """ |
| 179 | |
| 180 | def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: |
| 181 | super().__init__() |
| 182 | if scale is None or scale <= 0.0: |
| 183 | scale = 1.0 |
| 184 | self.register_buffer( |
| 185 | "positional_encoding_gaussian_matrix", |
| 186 | scale * torch.randn((2, num_pos_feats)), |
| 187 | ) |
| 188 | |
| 189 | def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: |
| 190 | """Positionally encode points that are normalized to [0,1].""" |
| 191 | # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape |
| 192 | coords = 2 * coords - 1 |
| 193 | coords = coords @ self.positional_encoding_gaussian_matrix |
| 194 | coords = 2 * np.pi * coords |
| 195 | # outputs d_1 x ... x d_n x C shape |
| 196 | return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) |
| 197 | |
| 198 | def forward(self, size: Tuple[int, int]) -> torch.Tensor: |
| 199 | """Generate positional encoding for a grid of the specified size.""" |
| 200 | h, w = size |
| 201 | device: Any = self.positional_encoding_gaussian_matrix.device |
| 202 | grid = torch.ones((h, w), device=device, dtype=torch.float32) |
| 203 | y_embed = grid.cumsum(dim=0) - 0.5 |
| 204 | x_embed = grid.cumsum(dim=1) - 0.5 |
| 205 | y_embed = y_embed / h |
| 206 | x_embed = x_embed / w |
| 207 | |
| 208 | pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) |
| 209 | return pe.permute(2, 0, 1) # C x H x W |
| 210 | |
| 211 | def forward_with_coords( |
| 212 | self, coords_input: torch.Tensor, image_size: Tuple[int, int] |
| 213 | ) -> torch.Tensor: |
| 214 | """Positionally encode points that are not normalized to [0,1].""" |
| 215 | coords = coords_input.clone() |
| 216 | coords[:, :, 0] = coords[:, :, 0] / image_size[1] |
| 217 | coords[:, :, 1] = coords[:, :, 1] / image_size[0] |
| 218 | return self._pe_encoding(coords.to(torch.float)) # B x N x C |
| 219 | |
| 220 | |
| 221 | class LayerNorm2d(nn.Module): |