NaViT Sequence Packing
Training and inference strategy from NaViT (Google, 2023) for processing variable-resolution images in a ViT without padding waste. Used by MoonViT and increasingly common in production vision encoders.
How it works
Instead of padding all images in a batch to the same size:
- Patchify each image independently → variable-length token sequences
- Concatenate all sequences end-to-end into one flat 1D tensor
- Record cumulative lengths in
cu_seqlens(shape:[B+1], values:[0, N_1, N_1+N_2, ...]) - Run attention with block-diagonal masking: token attends only to tokens from the same image
Why it’s efficient
- No compute spent on padding tokens
- FlashAttention’s
flash_attn_varlen_funcnatively supports this viacu_seqlens— no explicit masking matrix needed - Packs more real signal per GPU memory allocation
Attention masking
The effective attention pattern is block-diagonal: