2D Sine-Cosine Positional Embedding
Problem Statement
Build the fixed 2D sin-cos positional embedding used by many ViT/MAE implementations: concatenate an independent 1D sin-cos embedding for the row coordinate and the column coordinate.
Background
For a 1D position pos and an embedding width d (even), the sin-cos embedding uses d/2 frequencies
and emits [sin(posw_0), ..., sin(posw_{d/2-1}), cos(posw_0), ..., cos(posw_{d/2-1})].
For a 2D grid, each patch has a (row, col) coordinate. Give half the width to the row embedding and half to the column embedding, then concatenate [row_emb, col_emb] into a length-dim vector. Patches are enumerated row-major.
Your Task
Implement:
def pos_embed_2d(grid, dim):
Return a nested list of shape (grid*grid, dim), every value rounded to 4 decimals.
Input Format
- grid (int): side of the square patch grid.
- dim (int): total embedding width, divisible by 4.
Output Format
- A (grid*grid, dim) nested list, rounded to 4 decimals.
Sample
emb = pos_embed_2d(2, 4)
print(emb[0])
Output:
[0.0, 1.0, 0.0, 1.0]
Example
emb = pos_embed_2d(2, 4) print(emb[0])
[0.0, 1.0, 0.0, 1.0]
- Split the total dimension into two halves for the row and column embeddings, so each 1D embedding has width .
- Determine the coordinates for the first patch (index 0) in the grid: it is at row and column .
- Calculate the row embedding for position with width . The single frequency is . The angles are , yielding .
- Calculate the column embedding for position with width . Similarly, the angle is , yielding .
- Concatenate the row and column embeddings to form the final vector: .
- The final output is [0.0, 1.0, 0.0, 1.0]
Constraints
dimis divisible by 4; each axis getsdim/2, each withdim/4frequencies.- Position 0 gives sin=0, cos=1, so the first patch is
[0,1,...,0,1]. - Round every entry to 4 decimals; avoid emitting
-0.0.