Papers
Topics
Authors
Recent
Search
2000 character limit reached

Patch n’ Pack for Vision Transformers

Updated 23 December 2025
  • Patch n’ Pack is a technique for training Vision Transformers on images with arbitrary resolutions by packing patch tokens from multiple images into fixed-size sequences.
  • It employs patch-wise tokenization, dynamic token dropping, and greedy packing with self-attention masking to efficiently process variable-length image data.
  • This method improves throughput, model accuracy, and robustness across diverse tasks while requiring minimal changes to standard ViT pipelines.

Patch n’ Pack sequence packing is a method for efficiently training Vision Transformer (ViT) models on images of arbitrary resolutions and aspect ratios by organizing variable-length patch token sequences from multiple images into packed, fixed-size token sequences. This approach enables native resolution processing, increases throughput, and enhances model robustness while imposing minimal changes to standard ViT pipelines. Patch n’ Pack underpins NaViT (Native Resolution ViT), which supports diverse downstream vision tasks and facilitates superior trade-offs between compute cost and model accuracy (Dehghani et al., 2023).

1. Image Patching and Tokenization

Patch n’ Pack operates on the principle of patch-wise tokenization. Given an image with height HH and width WW, non-overlapping patches of size p×pp \times p are extracted. The number of patches (tokens) per image is L=(H/p)(W/p)L = (H/p)\cdot(W/p). Each patch is flattened to a vector xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3} and projected to the transformer’s model dimension DD via a linear layer, producing embedded tokens zRDz \in \mathbb{R}^D. A positional embedding of dimension DD is added to each token, with the particular embedding scheme elaborated in Section 5.

2. Mathematical Formulation of Sequence Packing

Patch n’ Pack packs tokens from multiple images into sequences of fixed maximum length LmaxL_{\max}, processing them jointly in a single forward pass. Let LiL_i denote the number of tokens for image WW0 (potentially after patch dropping). Packing proceeds by concatenating the token sequences from images WW1 such that:

WW2

Unused positions in the packed sequence are filled with a special PAD token. In practice, WW3 sequences per minibatch are constructed, shaping the input tensor as WW4.

Token-dropping: Accelerating training, an image-specific random drop rate WW5 reduces its token count to:

WW6

The drop rates may be drawn from constant values, Beta distributions, or adapted dynamically based on training progression (WW7).

Self-attention masking: To preserve independence between images packed together, a binary mask WW8 is used:

WW9

This mask is added to attention logits, ensuring self-attention occurs only within an image.

Pooling and loss: A masked [CLS]-style pooling head extracts one feature vector per image for downstream loss calculation (e.g., cross-entropy, distributed contrastive loss). Contrastive pretraining uses chunked loss computation to avoid quadratic scaling with sequence length.

3. Packing Algorithm and Pseudo-code

The Patch n’ Pack algorithm follows a two-phase process: preparing tokens with optional dropping and resolution sampling, followed by greedy packing and attention masking. The pseudo-code below summarizes the approach:

DD9

Unused positions are padded, and attention and pooling structures are adjusted according to the packed boundaries (Dehghani et al., 2023).

4. Computational Complexity and Efficiency

Patch n’ Pack sequence packing introduces several efficiency and complexity considerations:

  • Attention Overhead: The cost scales as p×pp \times p0 for self-attention. Empirically, the increase in compute over single-image ViT is less than 10% for large models, as attention dominates less relative to growing MLP size.
  • Throughput: Standard ViT processes one image per forward pass (p×pp \times p1 tokens). NaViT typically packs p×pp \times p2–6 images per sequence for p×pp \times p3 tokens, maintaining wall-clock time. In JFT pretraining, this yields approximately five times greater image throughput per compute budget.
  • Memory: The packed tensor p×pp \times p4 avoids dynamic fragmentation. Additional overhead for attention masks is negligible. Padding is minimized (<2% tokens) with appropriate p×pp \times p5 and resolution sampling.
  • Padding: Efficient packing and flexible image sizing result in minimal wasted compute for PAD tokens.

Summary Table: Packing vs Standard ViT

Aspect Standard ViT Patch n’ Pack (NaViT)
Sequence length p×pp \times p6 (fixed-p×pp \times p7) p×pp \times p8 (packed)
Images per pass p×pp \times p9 L=(H/p)(W/p)L = (H/p)\cdot(W/p)0–6
Attention cost L=(H/p)(W/p)L = (H/p)\cdot(W/p)1 L=(H/p)(W/p)L = (H/p)\cdot(W/p)2 (~L=(H/p)(W/p)L = (H/p)\cdot(W/p)310% extra)
Padding overhead 0 L=(H/p)(W/p)L = (H/p)\cdot(W/p)42%

5. Pipeline Modifications for Packed Sequences

Integrating Patch n’ Pack requires minor but essential changes to the ViT pipeline:

  • Masked Self-Attention: The attention softmax incorporates per-batch masks L=(H/p)(W/p)L = (H/p)\cdot(W/p)5 to prevent inter-image token attention.
  • Masked Pooling Head: Pooling heads (CLS or attention-pooling) must recognize sequence boundaries, producing one vector per image.
  • Factorized Positional Embeddings: Single-image ViTs employ 1D positional embeddings. For variable aspect ratio and resolution, 2D factorized positional embeddings are used:

L=(H/p)(W/p)L = (H/p)\cdot(W/p)6

where L=(H/p)(W/p)L = (H/p)\cdot(W/p)7 are normalized token coordinates, and L=(H/p)(W/p)L = (H/p)\cdot(W/p)8 are learnable or sinusoidal mappings L=(H/p)(W/p)L = (H/p)\cdot(W/p)9. This formulation generalizes to unseen resolutions and aspect ratios, supporting smooth scaling and extrapolation.

At inference, the framework supports arbitrary choice of image resolution and packing structure, enabling performance-cost trade-offs without architectural changes.

6. Empirical Evaluation and Trade-Offs

Experiments reveal several notable trade-offs and performance characteristics:

  • Pre-training Efficiency: NaViT-B/16 achieves top ViT-B/16 performance on JFT pretraining in xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}0 TPU-hours versus xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}1 more compute for ViT-B/16, mainly by seeing xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}2 more images via packing and token dropping.
  • Variable Resolution Training: Sampling xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}3 and preserving aspect ratio outperforms fixed-resolution baselines across budgets. At inference, NaViT allows for smooth cost-accuracy calibration based on input resolution.
  • Token-Dropping Strategies: Using per-image drop rates from a Beta distribution and decaying the drop rate yields xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}4–xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}5 accuracy gains at constant compute.
  • Downstream and OOD Robustness:
    • On zero-shot and linear-probe ImageNet, NaViT surpasses compute-matched ViT by xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}6–xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}7.
    • On robustness datasets (ImageNet-A, ObjectNet), gains up to xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}8 are observed.
    • Calibration error remains stable at xpatchRpp3x_{\text{patch}}\in \mathbb{R}^{p\cdot p\cdot 3}9 for 128–1024 tokens/sequences.
    • For semantic segmentation (ADE20k), DD0–DD1 mIoU at matched finetune FLOPs.
    • For detection (LVIS rare classes), DD2 APDD3 vs ViT-L/14.
    • On FairFace and CelebA, DD4–DD5 label accuracy is achieved using frozen NaViT.
    • In video (Kinetics400), NaViT-L matches ViViT-L (80.4\%) in DD6 fewer epochs.
  • Inference Cascades: Utilizing low-token models to filter easy examples and cascading to higher-token models on hard fractions yields Pareto-optimal latency/accuracy trade-offs.

The approach integrates with minimal effort into existing ViT pipelines, requiring only data loader changes (for sequence packing, resolution, and drop-rate sampling), attention masking, and factorized positional embeddings. The resulting framework delivers DD7–DD8 more images per compute hour, enhanced transfer effectiveness, improved robustness, and flexible test-time configuration (Dehghani et al., 2023).

7. Applications and Implications

Patch n’ Pack is compatible with supervised and contrastive image-text pretraining and applies to tasks including image and video classification, object detection, semantic segmentation, and fairness or robustness benchmarking. Its ability to handle native image resolutions and manage cost-accuracy trade-offs at inference provides a flexible tool for practical deployment. The architectural changes are limited in scope, enabling broad applicability for ViT-style models. This approach marks a shift from the fixed-resolution, CNN-inspired pipelines towards a more adaptive, sequence-based vision modeling paradigm. A plausible implication is the increasing relevance of sequence-packing and patch-level model design for scalable, heterogeneous vision workloads (Dehghani et al., 2023).

Definition Search Book Streamline Icon: https://streamlinehq.com
References (1)

Topic to Video (Beta)

No one has generated a video about this topic yet.

Whiteboard

No one has generated a whiteboard explanation for this topic yet.

Follow Topic

Get notified by email when new papers are published related to Patch n’ Pack Sequence Packing.