Implement pixel shuffle (depth to space) upsampling

Why it matters ESPCN-style super-resolution and some segmentation heads upsample with pixel shuffle instead of transposed conv.

Super-resolution models upsample by predicting r^2 times more channels and then rearranging them into a larger image.

Write pixel_shuffle(x, r). x is (C * r * r, H, W). Return y of shape (C, H * r, W * r) with y[c, h * r + i, w * r + j] = x[c * r * r + i * r + j, h, w].

Signaturedef pixel_shuffle(x, r)

Example

pixel_shuffle(arange(4).reshape(4, 1, 1), 2) is [[[0, 1], [2, 3]]].

Understand the idea

To make an image r times bigger, a network can predict r x r values for every low-resolution pixel, stored as extra channels. Pixel shuffle then lays those values out as a small r x r tile in the bigger image. Nothing is computed, it is just rearranging, like taking 4 stacked cards and laying them out as a 2 x 2 square.

Tiny example: 4 channels holding 0, 1, 2, 3 at one pixel, r = 2. They become the 2 x 2 tile [[0, 1], [2, 3]]: channel i * 2 + j goes to row i, column j of the tile.

Rule: y[c, h r + i, w r + j] = x[c r^2 + i r + j, h, w].

It is used in real-time super-resolution and as a cheap upsampler that avoids the checkerboard artifacts of transposed convolution.

Shapes and data flow

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

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

  • Sample 1: examplepixel_shuffle(np.arange(4).reshape(4, 1, 1), 2)
  • Sample 2: 2x2 gridpixel_shuffle(np.arange(16).reshape(4, 2, 2), 2)