Generate positional encoding for a grid of the specified size.
(self, size: Tuple[int, int])
| 157 | |
| 158 | @torch.no_grad() |
| 159 | def forward(self, size: Tuple[int, int]) -> torch.Tensor: |
| 160 | """Generate positional encoding for a grid of the specified size.""" |
| 161 | h, w = size |
| 162 | device = self.positional_encoding_gaussian_matrix.device |
| 163 | |
| 164 | # Force fp32 (https://github.com/huggingface/transformers/pull/29285) |
| 165 | with torch.autocast(device_type=device.type, enabled=False): |
| 166 | grid = torch.ones((h, w), device=device, dtype=torch.float32) |
| 167 | y_embed = grid.cumsum(dim=0) - 0.5 |
| 168 | x_embed = grid.cumsum(dim=1) - 0.5 |
| 169 | y_embed = y_embed / h |
| 170 | x_embed = x_embed / w |
| 171 | pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) |
| 172 | |
| 173 | pe = pe.to(self.positional_encoding_gaussian_matrix.dtype) |
| 174 | return pe.permute(2, 0, 1) # C x H x W |
| 175 | |
| 176 | @torch.no_grad() |
| 177 | def forward_with_coords(self, coords_input: torch.Tensor, image_size: Tuple[int, int]) -> torch.Tensor: |
nothing calls this directly
no test coverage detected