Resize learned ViT position embeddings for a new input resolution

A ViT pretrained at one resolution has one learned position vector per grid cell. Fine-tuning at a higher resolution makes more patches, so the position table is resized like an image, while the CLS position is kept as is.

Write resize_pos_embed(pos, old_grid, new_grid). pos is (1 + gh*gw, D); row 0 is the CLS position, the rest is the grid in row-major order. old_grid = (gh, gw), new_grid = (nh, nw). Return (1 + nh*nw, D).

Resize each channel of the (gh, gw) grid with bilinear interpolation using half-pixel centres, separately along each axis:
- for output index i on an axis of old size g and new size m: src = (i + 0.5) * g / m - 0.5, clipped to [0, g - 1],
- i0 = floor(src), i1 = min(i0 + 1, g - 1), w = src - i0, value = (1 - w) * v[i0] + w * v[i1].
Resizing to the same grid must return pos unchanged. Grids may be non-square and may shrink.

Signaturedef resize_pos_embed(pos, old_grid, new_grid)

Example

a 1x2 grid with values [0, 4] (D = 1) resized to 1x4 gives [0, 1, 3, 4], with CLS in front.

Understand the idea

A ViT stores one learned position vector per grid cell. At a higher resolution the grid grows, so you resize the table like a small image, per channel, keeping the CLS row as is. Half-pixel centres treat each vector as the middle of its cell. Worked example: a 1x2 grid with values [0, 4] resized to 1x3. For an axis of old size g = 2 and new size m = 3: i = 0 gives src = 0.5 * 2 / 3 - 0.5 = -0.167, clipped to 0, value 0. i = 1 gives src = 1.5 * 2 / 3 - 0.5 = 0.5, value halfway = 2. i = 2 gives src = 1.167, clipped to 1, value 4. Result [0, 2, 4]. Rule: src = (i + 0.5) * g / m - 0.5 clipped to [0, g - 1], i0 = floor(src), i1 = min(i0 + 1, g - 1), w = src - i0, value = (1 - w) * v[i0] + w * v[i1]; do rows then columns, flatten in row-major order and put CLS back in front. Same size must return the input. Used when fine-tuning ViTs at new resolutions.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleresize_pos_embed([[9.0], [0.0], [4.0]], (1, 2), (1, 4))
  • Sample 2: same grid unchangedresize_pos_embed(_pos, (2, 3), (2, 3))