A Photo Read Like a Sentence

Using Vision ModelsMedium+20 XP+20

A Photo Read Like a Sentence

A Vision Transformer never slides a filter across an image. It cuts the image into fixed squares and treats each square as a token, exactly the way a language model treats a word. Before any attention can happen, something has to do the cutting.

Task: write patchify(image, p) that turns an image into its list of patch tokens.

  • image[r][c] is the pixel at row r, column c, given as a list of channel values. A colour pixel might be [red, green, blue]; a grayscale pixel is a list holding one number.
  • Each patch is a p×pp \times pp×p square. Patches are taken in reading order: left to right across the top band of rows, then left to right across the next band down, and so on.
  • Each token is its patch flattened into one list: the patch's top row first, left to right, then its next row, and so on, with each pixel contributing all of its channel values in order. A patch of a CCC-channel image therefore becomes a list of p×p×Cp \times p \times Cp×p×C numbers.
  • If the height or width isn't a multiple of ppp, the leftover rows at the bottom or columns at the right can't fill a whole patch and are dropped.

Return the list of tokens.

For example, in a 4×4 grayscale image whose pixel at row rrr, column ccc holds 10r+c10r + c10r+c, the first token for p=2p = 2p=2 is [0, 1, 10, 11].

A Vision Transformer does not slide anything across this image.

Examples

image = [[[10 * r + c] for c in range(4)] for r in range(4)]
p = 2
returns [[0, 1, 10, 11], [2, 3, 12, 13], [20, 21, 30, 31], [22, 23, 32, 33]]
image = [[[r, c, r + c] for c in range(4)] for r in range(2)]
p = 2
returns [[0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 2], [0, 2, 2, 0, 3, 3, 1, 2, 3, 1, 3, 4]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run