RoPE for image tokens with 2d structure. Args: embed_dim: (`int`): The embedding dimension size crops_coords (`Tuple[int]`) The top-left and bottom-right coordinates of the crop. grid_size (`Tuple[int]`): The grid size of the positional embedding. us
(embed_dim, crops_coords, grid_size, use_real=True)
| 511 | |
| 512 | |
| 513 | def get_2d_rotary_pos_embed(embed_dim, crops_coords, grid_size, use_real=True): |
| 514 | """ |
| 515 | RoPE for image tokens with 2d structure. |
| 516 | |
| 517 | Args: |
| 518 | embed_dim: (`int`): |
| 519 | The embedding dimension size |
| 520 | crops_coords (`Tuple[int]`) |
| 521 | The top-left and bottom-right coordinates of the crop. |
| 522 | grid_size (`Tuple[int]`): |
| 523 | The grid size of the positional embedding. |
| 524 | use_real (`bool`): |
| 525 | If True, return real part and imaginary part separately. Otherwise, return complex numbers. |
| 526 | |
| 527 | Returns: |
| 528 | `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`. |
| 529 | """ |
| 530 | start, stop = crops_coords |
| 531 | grid_h = np.linspace(start[0], stop[0], grid_size[0], endpoint=False, dtype=np.float32) |
| 532 | grid_w = np.linspace(start[1], stop[1], grid_size[1], endpoint=False, dtype=np.float32) |
| 533 | grid = np.meshgrid(grid_w, grid_h) # here w goes first |
| 534 | grid = np.stack(grid, axis=0) # [2, W, H] |
| 535 | |
| 536 | grid = grid.reshape([2, 1, *grid.shape[1:]]) |
| 537 | pos_embed = get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=use_real) |
| 538 | return pos_embed |
| 539 | |
| 540 | |
| 541 | def get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=False): |
no test coverage detected