Creates 2D sinusoidal positional embeddings. Args: embed_dim (`int`): The embedding dimension. grid_size (`int`): The size of the grid height and width. cls_token (`bool`, defaults to `False`): Whether or not to add a classificati
(
embed_dim,
grid_size,
cls_token=False,
extra_tokens=0,
interpolation_scale=1.0,
base_size=16,
device: torch.device | None = None,
output_type: str = "np",
)
| 218 | |
| 219 | |
| 220 | def get_2d_sincos_pos_embed( |
| 221 | embed_dim, |
| 222 | grid_size, |
| 223 | cls_token=False, |
| 224 | extra_tokens=0, |
| 225 | interpolation_scale=1.0, |
| 226 | base_size=16, |
| 227 | device: torch.device | None = None, |
| 228 | output_type: str = "np", |
| 229 | ): |
| 230 | """ |
| 231 | Creates 2D sinusoidal positional embeddings. |
| 232 | |
| 233 | Args: |
| 234 | embed_dim (`int`): |
| 235 | The embedding dimension. |
| 236 | grid_size (`int`): |
| 237 | The size of the grid height and width. |
| 238 | cls_token (`bool`, defaults to `False`): |
| 239 | Whether or not to add a classification token. |
| 240 | extra_tokens (`int`, defaults to `0`): |
| 241 | The number of extra tokens to add. |
| 242 | interpolation_scale (`float`, defaults to `1.0`): |
| 243 | The scale of the interpolation. |
| 244 | |
| 245 | Returns: |
| 246 | pos_embed (`torch.Tensor`): |
| 247 | Shape is either `[grid_size * grid_size, embed_dim]` if not using cls_token, or `[1 + grid_size*grid_size, |
| 248 | embed_dim]` if using cls_token |
| 249 | """ |
| 250 | if output_type == "np": |
| 251 | deprecation_message = ( |
| 252 | "`get_2d_sincos_pos_embed` uses `torch` and supports `device`." |
| 253 | " `from_numpy` is no longer required." |
| 254 | " Pass `output_type='pt' to use the new version now." |
| 255 | ) |
| 256 | deprecate("output_type=='np'", "0.33.0", deprecation_message, standard_warn=False) |
| 257 | return get_2d_sincos_pos_embed_np( |
| 258 | embed_dim=embed_dim, |
| 259 | grid_size=grid_size, |
| 260 | cls_token=cls_token, |
| 261 | extra_tokens=extra_tokens, |
| 262 | interpolation_scale=interpolation_scale, |
| 263 | base_size=base_size, |
| 264 | ) |
| 265 | if isinstance(grid_size, int): |
| 266 | grid_size = (grid_size, grid_size) |
| 267 | |
| 268 | grid_h = ( |
| 269 | torch.arange(grid_size[0], device=device, dtype=torch.float32) |
| 270 | / (grid_size[0] / base_size) |
| 271 | / interpolation_scale |
| 272 | ) |
| 273 | grid_w = ( |
| 274 | torch.arange(grid_size[1], device=device, dtype=torch.float32) |
| 275 | / (grid_size[1] / base_size) |
| 276 | / interpolation_scale |
| 277 | ) |
no test coverage detected
searching dependent graphs…