research34 min studyLesson 796 in Engineering

Resolution and packing change token geometry, masking, and actual kernel work

Count variable-resolution patch grids and distinguish logical within-image attention from padding, dense packed scores, and block-aware implementation costs.

On this page

What you’ll understand

  • Calculate variable-resolution patch counts under a chosen padding or divisibility rule.
  • Compare padded token slots with useful packed tokens.
  • Explain why a block mask alone does not prove a dense attention kernel avoids cross-block computation.

Resizing every image to one square simplifies batching but can distort aspect ratio, crop away evidence, or spend many padded positions on a narrow input. Variable-resolution encoders and packing offer another tradeoff. Their benefit depends on the processed patch grid, position scheme, attention mask, and kernels that execute it. A shorter logical token account is not automatically a measured speedup. Preserve the task information while tracing which padded or masked work the implementation actually removes.

Count the processed grid and retain its coordinates

Choose whether images are resized, cropped, or padded to patch-compatible dimensions. Under padding to whole patches, the grid uses the ceiling of height over patch size times the ceiling of width over patch size. A crop or resize has a different geometry. Preserve original-to-processed coordinates for grounding targets and report aspect-ratio cohorts. High resolution can recover small text or details, but it also changes sequence length and position behavior. Increasing raw upload pixels without checking the processor may have no effect if it always resizes to the same grid.

NaViT provides an original example of processing different aspect ratios and resolutions with patch packing and appropriate attention/position treatment. This is an architecture and training design, not permission to send arbitrary sizes into every fixed-grid vision checkpoint. A model may require learned positional interpolation, a restricted crop scheme, or particular resolution buckets. Extra class or summary features, thumbnails, and multiple crops add tokens beyond the bare grid. Match these choices with the checkpoint and its training regime before attributing a quality or efficiency change to resolution alone.

Li=⌈Hip⌉⌈Wip⌉,Lpadded=Bmax⁡iLi,Luseful=∑iLiL_i=\left\lceil\frac{H_i}{p}\right\rceil\left\lceil\frac{W_i}{p}\right\rceil,\qquad L_{\rm padded}=B\max_iL_i,\quad L_{\rm useful}=\sum_iL_i
The first formula assumes padding each positive image dimension to whole nonoverlapping p-pixel patches, without extra features. B counts images. The padded comparison uses one common sequence length for the batch, while useful counts exclude padding. Resize, crop, token dropping, summaries, and packing separators require additional explicit accounting.↔ Scroll wide equations horizontally.

Packing needs isolation between constituent images

Packing several images into one sequence can reduce unused token slots, but it must preserve each image's identity and positions. A block-diagonal attention mask can prevent one image from reading another when independent image encoding is intended. Class or pooling tokens must also attend only to their intended content. A mask bug can improve a training objective through cross-example leakage while invalidating the independent-image interpretation. Test different packed neighbors and verify that an image's output remains appropriately unchanged under the declared isolation contract.

Logical attention pairs within separate blocks total the sum of squared image lengths. A dense implementation that forms the whole packed score matrix may still allocate or compute the square of the summed lengths, even if it masks cross-image entries afterward. Block-aware or segmented kernels can change that work, but support and achieved efficiency are implementation-specific. Likewise, padding to the maximum length can perform masked work unless the kernel skips it. Report the actual execution method, peak memory, and measured completed time rather than equating logical pair counts with latency.

Nwithin=∑iLi2,Ndense pack=(∑iLi)2N_{\rm within}=\sum_iL_i^2,\qquad N_{\rm dense\ pack}=\left(\sum_iL_i\right)^2
These count score positions per attention head for independent full within-image attention versus a hypothetical fully materialized dense packed sequence. The within-image model assumes block isolation; neither number is itself a FLOP count, memory measurement, or guarantee that a particular fused kernel performs or stores all counted positions.↔ Scroll wide equations horizontally.

Evaluate information and execution together

Compare resolution and packing settings on the same task and input cohort. Keep source content, crop rules, output labels, and evaluation ownership consistent. Inspect small objects, OCR, aspect extremes, and crowded scenes rather than only an aggregate caption score. Measure preprocessing, encoder execution, connector length, and downstream language costs separately. A packing configuration can improve accelerator utilization while making a few oversized images dominate a batch's waiting time. Include admission and batching policies when turning an encoder result into a serving throughput claim.

The roofline lab illustrates one ceiling change without implementing packing. Reset, set both I=4 FLOP/byte and B=50 decimal GB/s, predict 200 GFLOP/s, then Play. Reset and set both I=8 and B=50 for 400. The fixed compute cap is 1000 GFLOP/s and playback traces the synthetic min(1000,B×I) roof. There are no image grids, positional encodings, block masks, padding, or variable-length kernels. Use the explicit length and score-position calculations to form a hypothesis, then validate whether the actual implementation removes the presumed work.

Fewer padded tokens do not automatically mean fewer dense packed scores

Three processed images have dimensions 224×224,336×224,448×224, with 16-pixel nonoverlapping patches and no extra features. All dimensions are divisible. Compare useful tokens, max-length padding, independent within-image score positions, and a fully dense packed score matrix per head.

  1. Grid lengths are 14×14=196,21×14=294, and 28×14=392. Useful tokens total 882, while a three-image max-length padded batch has 3×392=1176 slots, including 294 padding slots or 25% of its capacity.

  2. Independent within-image full-attention score positions total 196²+294²+392²=278516. A dense padded batch would have 3×392²=460992 positions per head if all padded scores were formed.

  3. A fully dense packed sequence of length 882 would form 882²=777924 score positions before masking. Packing needs a suitable implementation to exploit block structure; merely applying a block mask does not prove this larger dense matrix was avoided.

The result

Token packing and attention execution are separate resource questions. The shape arithmetic motivates measurements but does not predict a universal speedup or preserve grounding automatically.

Explore the model

Interactive lab

Interactive lab · roofline

A changed arithmetic intensity is a hypothesis, not a patch-packing measurement

Reset, set both I=4 FLOP/byte and B=50 decimal GB/s, predict 200 GFLOP/s, then Play. Reset and re-enter both I=8 and B=50 for 400. The model has a fixed 1000 GFLOP/s roof and no image patches, padding, attention masks, position encoding, or variable-length kernels. It is not an encoder or packing benchmark.

A changed arithmetic intensity is a hypothesis, not a patch-packing measurementSynthetic roofline ceiling min(1000, B·I), in GFLOP/s, with B in decimal GB/s and I in FLOP/byte. Playback traces the roof without changing the selected kernel. This upper-bound model is not a measured throughput prediction, hardware comparison or price model. Current readings: Attainable ceiling: 640 GFLOP/s; Ridge intensity: 12.5 FLOP/byte; Ceiling regime: Memory-bound ceiling. All parameters are adjustable with the labeled controls below.Hypothetical roofline upper bound: 640 GFLOP per second at operational intensity 8 FLOP per byte and bandwidth 80 gigabytes per second.0.1110641101001000Operational intensity · FLOP/byte · log scaleCeiling · GFLOP/s · log scalePeak: 1000
Attainable ceiling / kernelBandwidth roof / traceCompute ceiling
Attainable ceiling
640 GFLOP/s
Ridge intensity
12.5 FLOP/byte
Ceiling regime
Memory-bound ceiling
t = 0 s

Synthetic roofline ceiling min(1000, B·I), in GFLOP/s, with B in decimal GB/s and I in FLOP/byte. Playback traces the roof without changing the selected kernel. This upper-bound model is not a measured throughput prediction, hardware comparison or price model. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forVerify which logical work the real kernel skips and whether the changed resolution preserves task information.

Check your understanding

Several images are packed into one sequence with a block-diagonal mask. What determines whether cross-block score work is avoided?

Try it yourself

Two processed images have dimensions 128×128 and 256×128 with 16-pixel patches, no extras, and exact divisibility. Find their token lengths, useful-token total, max-length padded slots, and padding fraction.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Each image width has eight patches; compare the two height grids and divide unused slots by total padded slots.

Compare with the solution

Lengths are 8×8=64 and 16×8=128. Useful tokens total 192, while two sequences padded to 128 use 256 slots. Padding is 64/256=25%. This token fraction is not automatically the same fraction of latency or attention memory saved by a packing implementation.

Take it with you

  • Resolution and aspect handling define the processed patch grid and available evidence.
  • Packing needs correct identity, positions, and block isolation.
  • Logical token savings, score positions, actual kernel work, and end-task quality need separate checks.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.