Pixel-Shuffle Token Downsampling
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
print(pixel_shuffle_tokens(24, 1024, 2))
{'tokens': 144, 'channels': 4096, 'ratio': 4}- The spatial grid is reduced by the shuffle factor to determine the new side length: .
- The new token count is calculated by squaring the reduced side length, representing the total number of visual tokens: .
- The channel width is expanded by the square of the shuffle factor to preserve the total information volume: .
- The compression ratio is the square of the shuffle factor, indicating how many original tokens are merged into one: .
- 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.