Fine-Tuning ViT at a Higher Resolution: Interpolating the Position Embeddings
The paper fine-tunes at a higher resolution than it pre-trains, keeping the patch size, so the grid of patches grows. The learned position embeddings were trained for the old grid, so they are interpolated in 2-D according to where each patch sits in the image. Implement the grid arithmetic and that interpolation.
A ViT with patch size P cuts an H×W image into a grid of gh×gw patches, gh=H/P and gw=W/P, read in raster order (row by row). The position table pos_embed has shape (1 + g_h g_w, D): row 0 belongs to the class token, row 1+rgw+c to the patch in grid row r, column c.
Implement two functions.
grid_size(height, width, patch_size) returns the tuple (gh,gw). height and width are multiples of patch_size.
resize_pos_embed(pos_embed, old_grid, new_grid) returns the table for the grid new_grid = (g_h', g_w') as a NumPy array of shape (1 + g_h' g_w', D):
- row 0 (class token) is copied unchanged;
- the patch rows are arranged as a gh×gw grid of D-vectors and resized by bilinear interpolation, each embedding placed at the centre of its patch. Along an axis with old size g and new size g′, new index j reads the old grid at the fractional position
s=(j+0.5)g′g−0.5,
clamped to [0,g−1]. With i0=⌊s⌋, i1=min(i0+1,g−1) and t=s−i0, the value is (1−t)vi0+tvi1. Interpolate along rows and along columns this way (bilinear interpolation is the two one-dimensional steps combined);
- the result is flattened back in raster order after the class-token row.