KBench / tools /factory /specs /any_res_image_split.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
9.28 kB
"""Spec for `any-res-image-split` — LLaVA-NeXT / AnyRes tiling of a high-resolution image into ViT tiles."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec
SPEC = TaskSpec(
name="any-res-image-split",
title="Write a fast AnyRes image tiling + normalise kernel",
blurb=("High-resolution VLMs (LLaVA-NeXT, InternVL, MiniCPM-V) do not resize a 1344x1344 document down "
"to 336x336 — they cut it into a grid of ViT-sized tiles and add one downscaled thumbnail for "
"global context. The preprocessing kernel reads raw channel-last uint8 pixels, normalises them, "
"transposes to channel-first, scatters them into per-tile buffers and area-pools the thumbnail. "
"On a batch of document pages it moves gigabytes and it sits directly in the request latency."),
keywords=["mle", "kernel-generation", "vision-language", "anyres", "preprocessing", "tiling",
"multimodal", "memory-bound"],
module="anyres_split.py",
func="any_res_image_split",
signature="any_res_image_split(pixels, mean, std, gh, gw)",
returns_doc="""Split a high-resolution image into a grid of normalised tiles plus a thumbnail.
Args:
pixels: (B, gh*P, gw*P, 3) uint8 — decoded pages/images, HWC, values 0..255.
mean: (3,) float32 — per-channel mean, applied AFTER dividing by 255.
std: (3,) float32 — per-channel standard deviation.
gh: int — tile grid height.
gw: int — tile grid width.
Returns:
(tiles, thumb) where
tiles: (B, gh*gw, 3, P, P) bfloat16 — row-major tiles, channel-first.
thumb: (B, 3, P, P) bfloat16 — the whole image area-averaged down to one tile.""",
reference_imports="import torch\nimport torch.nn.functional as F",
reference_src='''
def any_res_image_split(pixels, mean, std, gh, gw):
"""Normalise, transpose, tile, and area-pool, in fp32.
Correct and simple — it is the numerical SPECIFICATION, not a performance target.
"""
B, H, W, _ = pixels.shape
P = H // gh
x = pixels.float().div(255.0).sub(mean.view(1, 1, 1, 3)).div(std.view(1, 1, 1, 3))
x = x.permute(0, 3, 1, 2).contiguous() # (B, 3, H, W)
t = x.view(B, 3, gh, P, gw, P).permute(0, 2, 4, 1, 3, 5) # b gh gw c P P
tiles = t.reshape(B, gh * gw, 3, P, P).contiguous()
thumb = F.avg_pool2d(x, kernel_size=(gh, gw)) # exact area average -> (B, 3, P, P)
return tiles.to(torch.bfloat16), thumb.to(torch.bfloat16)
''',
make_inputs_src='''
def _mk(B, GH, GW, P, seed):
gen = torch.Generator(device="cuda").manual_seed(seed)
pixels = torch.randint(0, 256, (B, GH * P, GW * P, 3), device="cuda", dtype=torch.uint8, generator=gen)
mean = torch.tensor([0.48145466, 0.4578275, 0.40821073], device="cuda", dtype=torch.float32)
std = torch.tensor([0.26862954, 0.26130258, 0.27577711], device="cuda", dtype=torch.float32)
return pixels, mean, std, GH, GW
''',
flops_src='''
def canonical_work(B, GH, GW, P):
"""BYTES moved, from the SHAPE ALONE.
The uint8 image is read once (B * GH*P * GW*P * 3 bytes) and GH*GW + 1 bf16 tiles of 3*P*P elements are
written per image. The thumbnail is produced from the same pass over the pixels, so the source is counted
once. Bandwidth kernel: the score is achieved GB/s against that fixed byte count.
"""
return B * (GH * P) * (GW * P) * 3 + (GH * GW + 1) * B * 3 * P * P * 2
''',
flops_formula="B * (GH*P) * (GW*P) * 3 + (GH*GW + 1) * B * 3 * P * P * 2",
metric="GB/s",
compare="tuple",
tuple_names=("tiles", "thumb"),
tol=8e-3,
shape_names=("B", "GH", "GW", "P"),
grader_shapes=[(96, 4, 4, 336), (128, 3, 4, 336), (64, 5, 5, 336),
(256, 2, 3, 336), (48, 4, 4, 448)],
measure_shapes=[(80, 4, 4, 336), (112, 3, 4, 336), (52, 5, 5, 336),
(208, 2, 3, 336), (40, 4, 4, 448)],
measure_quick_shapes=[(8, 4, 4, 336), (16, 2, 2, 336), (4, 5, 5, 336)],
correct_shapes=[(3, 2, 3, 37), (5, 1, 1, 336), (7, 3, 2, 49), (2, 4, 4, 336)],
spec_md="""The image is exactly `gh` by `gw` tiles of `P x P` pixels. With `H = gh*P`, `W = gw*P`:
```
xn[b, y, x, c] = (pixels[b, y, x, c] / 255 - mean[c]) / std[c] # fp32
tiles[b, i*gw + j, c, u, v] = xn[b, i*P + u, j*P + v, c] # row-major tile order
thumb[b, c, u, v] = mean over (dy, dx) in [0,gh) x [0,gw) of
xn[b, u*gh + dy, v*gw + dx, c] # exact area average
```
Both outputs are the normalised pixels, only re-arranged and (for the thumbnail) averaged; the thumbnail is
an **exact area average** over a `gh x gw` box, which is what `avg_pool2d` with kernel `(gh, gw)` computes —
no interpolation, no antialias filter, no alignment subtleties.
Note the two different re-orderings: the tiles need the channel axis moved from last to third
(a 3-way transpose of the innermost dimension), while the thumbnail needs a strided reduction whose stride is
the *grid* size, not the tile size.
The division by 255 happens **first**, then the per-channel mean and std (the CLIP constants).
`/app/reference.py` normalises the whole image into an fp32 channel-last tensor, `permute`s it to
channel-first with a full copy, then makes another copy for the tiles and runs `avg_pool2d` for the
thumbnail. That is the numerical specification, and it moves the pixel data about eight times.""",
contract_md="""| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `pixels` | `(B, gh*P, gw*P, 3)` | `uint8` | decoded images, **channel-last**, contiguous |
| `mean` | `(3,)` | `float32` | per-channel mean, applied after `/255` |
| `std` | `(3,)` | `float32` | per-channel std |
| `gh` | — | `int` | tile grid height |
| `gw` | — | `int` | tile grid width |
**Return** a 2-tuple `(tiles, thumb)` **in that order**:
| out | shape | dtype |
|-----|-------|-------|
| `tiles` | `(B, gh*gw, 3, P, P)` | `bfloat16` |
| `thumb` | `(B, 3, P, P)` | `bfloat16` |
`pixels` is **read-only**. `P` is 336 or 448 in the graded shapes but 37 and 49 appear in the correctness
shapes, so do not assume `P` is a multiple of anything; `gh` and `gw` are independent and range over 1–5.
`gh == gw == 1` is legal (the thumbnail is then a copy of the single tile).""",
regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): tile size
`P` in {336, 448}, grids from 1x1 to 5x5 (LLaVA-NeXT allows up to 4 tiles + thumbnail; InternVL up to 12),
and `B` — pages or images per batch — from 48 to 256. Every graded shape moves **1.5–2.7 GiB**, dominated by
the bf16 tile writes.""",
correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32) within
**relative Frobenius error `8e-3`** at every graded shape, including the timed ones. `thumb` is an exact area
average, so a bilinear or nearest-neighbour approximation of it is a wrong answer, not a fast one.""",
perf_md="""One read of the uint8 source and one write of each output is the roofline. The writes dominate:
bf16 tiles are twice the bytes of the uint8 source, and there are `gh*gw + 1` tile-sized outputs.
The reference's problem is that it makes four full-size passes (fp32 normalise, fp32 permute copy, fp32 tile
copy, then the pool) at 4 bytes per element instead of 1 in and 2 out.
The kernel has two layout jobs at once. The tiles need the channel axis moved from the innermost position to
the outermost: a thread that reads three adjacent bytes (one pixel) must write them 128 KB apart. Reading a
row of pixels into shared memory and writing out three separate contiguous runs per channel is the standard
fix, and it is what makes the store side coalesced.
The thumbnail is the second job: it needs a `gh x gw` box average, and its source boxes are *not* the tiles —
box `(u, v)` straddles all `gh*gw` tiles. A block that already holds a strip of pixel rows can accumulate the
thumbnail partials for free while it writes the tiles, which is why `canonical_work` counts the source only
once; producing the thumbnail from a second pass over HBM is a measurable loss.
Watch the tail: a pixel row is `gw*P*3` bytes with `P` = 336 (odd multiple of 3), so row starts are not
16-byte aligned for every `(b, y)`.""",
precision_md="""Pixels are **uint8**, outputs are **bfloat16**, the normalisation constants are fp32.
Normalise in fp32 and round once when storing.
For the thumbnail, accumulate the `gh*gw` (up to 25) terms in **fp32** before dividing. Averaging in bf16
costs about a digit here and is measurable against the gate.
The tolerance was measured against an independent implementation that normalises to bf16 first and averages
the thumbnail in fp32: the observed relative error was ~2e-3, dominated by the single bf16 rounding of the
output, so the `8e-3` gate is about 4x that.
**fp8 is not acceptable** for the outputs — the contract fixes them at bf16, and the normalised pixel range
(roughly `[-1.8, 2.2]`) would lose ~6% relative accuracy in e4m3.""",
).validate()