Build 2D sine-cosine position embeddings
Why it matters MAE and many ViT backbones use fixed 2D sin-cos embeddings instead of learned ones.
Fixed 2D position embeddings for ViTs use half the dimensions for the row and half for the column.
Write sincos_2d(h, w, dim) with dim divisible by 4. Let q = dim // 4 and omega_i = 1 / 10000^(i / q) for i < q. For patch (r, c) in row-major order, the embedding is [sin(c * omega), cos(c * omega), sin(r * omega), cos(r * omega)] concatenated. Return the (h * w, dim) array.
def sincos_2d(h, w, dim)Example
sincos_2d(1, 1, 4) is [[0, 1, 0, 1]].
Understand the idea
A vision transformer needs to know where each patch sits in the grid. Fixed 2D sine-cosine embeddings give every patch a vector built from its column and row numbers: half the dimensions encode the column, half encode the row, each with sines and cosines at several frequencies. Worked example: dim 8, so q = 2 and omega = [1, 1 / 10000^(1/2)] = [1, 0.01]. In a grid of width 3, patch (row 1, column 2) is index 1 * 3 + 2 = 5. Its embedding is [sin(2), sin(0.02), cos(2), cos(0.02), sin(1), sin(0.01), cos(1), cos(0.01)] = [0.909, 0.020, -0.416, 1.000, 0.841, 0.010, 0.540, 1.000]. Rule: q = dim // 4; omega_i = 1 / 10000^(i / q) for i = 0 .. q - 1; for each patch in row-major order (row r from 0 to h - 1, column c from 0 to w - 1), concatenate sin(c * omega), cos(c * omega), sin(r * omega), cos(r * omega). Row-major order with matching indexing matters; mixing up rows and columns only shows on non-square grids. Used in: MAE and other ViTs that use fixed position embeddings.