PIXELBANKv9.1.0
Menu

Problem Statement

Many recent VLMs (InternVL, some LLaVA variants) shrink the number of visual tokens with a pixel-shuffle (space-to-depth): a grid x grid feature map of width C becomes a (grid/r) x (grid/r) map of width Crr by folding each r x r spatial block into the channel dimension. Report the resulting token count and channel width, and the compression ratio.

Background

Attention cost is quadratic in token count, so halving the grid side (r=2) cuts tokens 4x while preserving information by widening channels 4x. The new token count is (grid // r) ** 2 and the new channel width is C * r * r. The token compression ratio is r*r.

Your Task

Implement:

def pixel_shuffle_tokens(grid, channels, r):

Return a dict with "tokens", "channels", "ratio" (all ints). grid is divisible by r.

Input Format

  • grid (int), channels (int), r (int); grid % r == 0.

Output Format

  • A dict of three ints.

Sample

print(pixel_shuffle_tokens(24, 1024, 2))

Output:

{'tokens': 144, 'channels': 4096, 'ratio': 4}

Example:

Input:
print(pixel_shuffle_tokens(24, 1024, 2))
Output:
{'tokens': 144, 'channels': 4096, 'ratio': 4}
Reasoning:
  • The spatial grid is reduced by the shuffle factor rr to determine the new side length: 24/2=1224 / 2 = 12.
  • The new token count is calculated by squaring the reduced side length, representing the total number of visual tokens: 122=14412^2 = 144.
  • The channel width is expanded by the square of the shuffle factor to preserve the total information volume: 1024×22=40961024 \times 2^2 = 4096.
  • The compression ratio is the square of the shuffle factor, indicating how many original tokens are merged into one: 22=42^2 = 4.
  • The final output is {'tokens': 144, 'channels': 4096, 'ratio': 4}

Constraints:

  • grid % r == 0, 1 <= r <= grid.
  • tokens = (grid // r) ** 2, channels = channels_in * r * r, ratio = r * r.
  • Return ints.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Pixel-Shuffle Token Downsampling - Medium | PixelBank