Learned Query Compression Ratio
Problem Statement
A resampler (Q-Former, Perceiver) reads N patch tokens with Q learned queries and emits exactly Q tokens, regardless of N. Given a batch of images at possibly different resolutions, report how many tokens the LM sees with and without the resampler and the overall savings.
Background
Without a resampler, the LM ingests the raw patch tokens, sum_i N_i. With a resampler of Q queries, each image contributes exactly Q tokens, so the LM ingests Q * num_images. The token reduction ratio is raw_total / resampled_total.
Your Task
Implement:
def resampler_savings(patch_counts, num_queries):
Return a dict with "raw_total", "resampled_total", "ratio" where ratio is rounded to 4 decimals.
Input Format
- patch_counts: list of per-image patch-token counts.
- num_queries (int): the resampler's query count Q.
Output Format
- A dict: two ints and one float.
Sample
print(resampler_savings([576, 576, 2304], 64))
Output:
{'raw_total': 3456, 'resampled_total': 192, 'ratio': 18.0}
Example
print(resampler_savings([576, 576, 2304], 64))
{'raw_total': 3456, 'resampled_total': 192, 'ratio': 18.0}- Calculate the total number of raw patch tokens by summing the counts for all images: .
- Determine the total resampled tokens by multiplying the number of images (3) by the number of learned queries (64): .
- Compute the compression ratio by dividing the raw total by the resampled total: .
- The final output is
{'raw_total': 3456, 'resampled_total': 192, 'ratio': 18.0}
Constraints
1 <= len(patch_counts) <= 100000,num_queries >= 1.resampled_total = num_queries * len(patch_counts).ratiorounded to 4 decimals.