Reassemble an image from ViT patch vectors

Why it matters MAE reconstruction, ViT segmentation heads and image tokenizers all need this inverse of patchify.

Masked autoencoders and ViT decoders output one vector per patch, which has to be folded back into an image.

Write unpatchify(patches, H, W, p). patches is (N, p * p * C) where N = (H / p) * (W / p), patches are in row-major order over the grid, and each vector is a p x p x C block flattened in (row, column, channel) order. Return the (H, W, C) image.

Signaturedef unpatchify(patches, H, W, p)

Example

unpatchify(arange(8).reshape(2, 4), 2, 4, 2) is a (2, 4, 1) image whose single channel is [[0, 1, 4, 5], [2, 3, 6, 7]].

Understand the idea

A ViT cuts the image into square tiles and turns each tile into a flat list of numbers. To get the picture back you do the reverse: turn each list back into a tile and put the tiles in their places on the grid. The only subtle part is that a row of the image runs through several tiles, so the tile rows and grid rows must be interleaved, like laying floor tiles row by row.

Tiny example: a 2 x 4 image with 2 x 2 patches has 2 patches, [0, 1, 2, 3] and [4, 5, 6, 7]. Patch 0 becomes [[0, 1], [2, 3]] on the left, patch 1 becomes [[4, 5], [6, 7]] on the right. The image rows are [0, 1, 4, 5] and [2, 3, 6, 7].

Rule: reshape(gh, gw, p, p, C), transpose(0, 2, 1, 3, 4), reshape(H, W, C).

Masked autoencoders compute their pixel loss after exactly this step.

Shapes and data flow

(N, p*p*C) -> (gh, gw, p, p, C) -> (gh, p, gw, p, C) -> (H, W, C)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleunpatchify(np.arange(8).reshape(2, 4), 2, 4, 2)[:, :, 0]
  • Sample 2: rgbunpatchify(np.arange(48).reshape(4, 12), 4, 4, 2)[:, :, 1]
  • Test 3: round trip_roundtrip()