Patch Grid for a Resized Image
Problem Statement
A ViT-style encoder first resizes an image to a fixed square side, then cuts it into non-overlapping patch x patch tiles. Report the patch grid.
Background
If an image is resized to side x side and split into patch x patch tiles, the grid is (side // patch) rows by (side // patch) columns and the number of visual tokens is their product. When side is not divisible by patch, the leftover strip on the right/bottom is dropped (floor division) — the usual reason a "224" model uses 16-pixel patches (14x14 = 196 tokens).
Your Task
Implement:
def patch_grid(side, patch):
Return a dict with keys "rows", "cols", "num_tokens" (all ints).
Input Format
- side (int): the square side the image is resized to.
- patch (int): the patch edge length.
Output Format
A dict of three ints.
Sample
print(patch_grid(224, 16))
Output:
{'rows': 14, 'cols': 14, 'num_tokens': 196}
Example
print(patch_grid(224, 16))
{'rows': 14, 'cols': 14, 'num_tokens': 196}- Determine the number of patches that fit along one dimension by performing floor division of the image side by the patch size, which discards any remainder: .
- Assign this value to both grid dimensions since the image is square and patches are square, resulting in 14 rows and 14 columns.
- Calculate the total number of visual tokens by multiplying the number of rows by the number of columns: .
- The final output is
{'rows': 14, 'cols': 14, 'num_tokens': 196}
Constraints
1 <= patch <= side <= 4096- Use floor division; a non-divisible remainder strip is dropped.
- All three returned values are ints.