Post

The Padding Tax: What Your Batch Shape Actually Bills You For

The Padding Tax: What Your Batch Shape Actually Bills You For

The short version A batch is a tensor, and a tensor has one width. Every request shorter than the longest one in its batch gets filled out with pad tokens, and the model processes those pads exactly like real tokens. On a 5,000-request trace with a realistic heavy tail, batching in arrival order at 32 per batch spent 80.4% of its processed slots on padding. Length-sorted batching cut that to 3.8%, but only because 5,000 queued requests gave the sorter enough neighbours to work with. Packing removed the padding altogether, at 5.10x fewer slots. Every number below comes from the code in this post, run twice with identical output.

The bill is in the shape, not the model

Nobody buys padding on purpose. It arrives with the tensor. A batch of prompts of 42, 61 and 900 tokens becomes a tensor of shape (3, 900), and the first two rows are 858 and 839 pad tokens. The attention mask tells the model to ignore them. It does not tell the GPU to skip them: the projections, the MLP, the memory traffic and the kernel launches all work over the padded width.

Measure it in slots, the number of token positions the model processes:

\[\text{slots} = \sum_{b \in \text{batches}} |b| \cdot \max_{i \in b} L_i \qquad \text{waste} = 1 - \frac{\sum_i L_i}{\text{slots}}\]

The mask is a correctness device, not an efficiency one. It stops pad positions from influencing the output; it does not shorten the matmul, the softmax or the write to the KV cache. Where attention is computed over the full padded width, a batch that is three-quarters pads spends three-quarters of its attention budget multiplying values by a mask that zeroes them out. On most hardware the arithmetic still happens, and the memory still moves.

This is not a fringe effect at the edges of a pipeline. Krell and co-authors measured it across common NLP datasets and found that up to half of all tokens can be padding, rising to 89% on a short-sequence task like GLUE-cola at width 128. Hugging Face keeps a whole padding-free training guide because the default collator pads each batch to its longest member.

The two traces below are the experiment for the rest of the post: 5,000 chat-shaped prompts from a lognormal draw clipped at 4,096 tokens, and 5,000 document-shaped prompts drawn narrow around 1,200. Three batching policies run over each.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import numpy as np

RNG = np.random.default_rng(7)

def chat_trace(n=5000):
    """Short prompts, heavy tail: most well under 300 tokens, a few very long."""
    x = RNG.lognormal(mean=np.log(160), sigma=0.95, size=n)
    return np.clip(x, 8, 4096).astype(int)

def doc_trace(n=5000):
    """Long documents, modest spread around 1,200 tokens."""
    x = RNG.normal(1200, 160, size=n)
    return np.clip(x, 64, 4096).astype(int)

def padded_cost(lengths, batch=32, order="arrival"):
    """Tokens the model actually processes when every batch is padded to its own max."""
    idx = np.argsort(lengths, kind="stable") if order == "sorted" else np.arange(len(lengths))
    L = lengths[idx]
    processed = 0
    for start in range(0, len(L), batch):
        chunk = L[start:start + batch]
        processed += len(chunk) * int(chunk.max())
    return processed, int(L.sum())

def report(name, lengths):
    true = int(lengths.sum())
    out = [f"{name}: {len(lengths)} requests, {true:,} real tokens, "
           f"mean {lengths.mean():.0f}, p95 {np.percentile(lengths, 95):.0f}, max {lengths.max()}"]
    for label, kw in (("fixed 4096", dict(batch=len(lengths))),
                      ("arrival order", dict(batch=32)),
                      ("length-sorted", dict(batch=32, order="sorted"))):
        processed, _ = padded_cost(lengths, **kw)
        out.append(f"  {label:14s} {processed:10,d} processed   waste {100*(1-true/processed):5.1f}%")
    return out

chat, docs = chat_trace(), doc_trace()
for line in report("chat", chat) + report("documents", docs):
    print(line)
1
2
3
4
5
6
7
8
chat: 5000 requests, 1,223,960 real tokens, mean 245, p95 754, max 4096
  fixed 4096     20,480,000 processed   waste  94.0%
  arrival order   6,238,680 processed   waste  80.4%
  length-sorted   1,272,832 processed   waste   3.8%
documents: 5000 requests, 5,993,049 real tokens, mean 1199, p95 1460, max 1802
  fixed 4096      9,010,000 processed   waste  33.5%
  arrival order   7,632,032 processed   waste  21.5%
  length-sorted   6,009,296 processed   waste   0.3%

Read the first two rows of each block. Fixed width at 4,096 is what a pipeline with a hard max_length does to every request, and on chat traffic it wastes 94.0% of the work: 20.5M slots for 1.2M real tokens. Arrival-order batching at 32 is the common middle ground and still wastes 80.4%. The same policy on documents wastes 21.5%, because those lengths already sit close together. That is the first hint that the driver is spread, not absolute length.

Where the waste comes from

Padding waste in one batch is $1 - \text{mean}(b)/\max(b)$. A batch of 32 draws from a heavy tail has a large maximum and a small mean, so the ratio collapses. The size of the bill is therefore set by the coefficient of variation of your request lengths, not by their average.

To check that directly, sweep the lognormal spread parameter and re-measure at a fixed batch of 32:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np

def trace(sigma, n=5000, seed=7):
    rng = np.random.default_rng(seed)
    x = rng.lognormal(mean=np.log(160), sigma=sigma, size=n)
    return np.clip(x, 8, 4096).astype(int)

def waste(lengths, batch=32, order="arrival"):
    idx = np.argsort(lengths, kind="stable") if order == "sorted" else np.arange(len(lengths))
    L = lengths[idx]
    processed = sum(len(c) * int(c.max()) for c in (L[i:i + batch] for i in range(0, len(L), batch)))
    return 100 * (1 - L.sum() / processed)

print("spread                     arrival order   length-sorted")
for sigma in (0.2, 0.6, 0.95, 1.3, 1.6):
    cv = (np.exp(sigma ** 2) - 1) ** 0.5          # coefficient of variation of a lognormal
    L = trace(sigma)
    print(f"sigma {sigma:4.2f}  (CV {cv:4.2f})     {waste(L):5.1f}%          {waste(L, order='sorted'):5.1f}%")
1
2
3
4
5
6
spread                     arrival order   length-sorted
sigma 0.20  (CV 0.20)      33.2%            0.4%
sigma 0.60  (CV 0.66)      67.3%            2.1%
sigma 0.95  (CV 1.21)      80.4%            3.8%
sigma 1.30  (CV 2.10)      86.0%            3.1%
sigma 1.60  (CV 3.45)      86.3%            2.6%

The sweep behaves the way the ratio predicts. At CV 0.20 the arrival-order policy wastes 33.2%, and at CV 3.45 it wastes 86.3%. Sorting holds the waste between 0.4% and 3.8% across the same range, and a thicker tail does not make its residual worse: at CV 3.45 it is 2.6%. What limits sorting is how many requests share each length band.

The contrast shows up in a real training run, not only in this harness. Hugging Face and IBM reported packing at 2x throughput on FLAN and 1.4x on OrcaMath, and their explanation is the spread argument: FLAN has short sequences with a large variance, so padded batches carry a lot of dead tokens, while OrcaMath has longer sequences with a lower variance and less to reclaim. Same feature, same code, two different payoffs, and the traces above reproduce the direction of the difference.

One long request poisons the batch

The extreme case is one request much longer than its neighbours. Thirty-one prompts of 25 tokens plus one of 1,500 tokens process 48,000 slots for 2,275 real tokens, which is 95.3% waste. That is the mechanism behind the 89% figure on GLUE-cola, and it is why a single long document in a support queue can visibly slow every short query behind it.

The obvious fix is to cap the width. The next block prices that, and the trade is worse than it looks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import numpy as np

# one long request arrives between short ones
mixed = np.array([25] * 31 + [1500])
processed = len(mixed) * mixed.max()
print(f"one 1,500-token request in 31 short ones: {processed:,} slots for {mixed.sum():,} real tokens, "
      f"{100 * (1 - mixed.sum() / processed):.1f}% wasted")

# capping the batch width is not free
rng = np.random.default_rng(7)
raw = np.clip(rng.lognormal(np.log(160), 0.95, 5000), 8, 4096).astype(int)
for cap in (256, 512):
    cut = np.minimum(raw, cap)
    padded = sum(len(c) * int(c.max()) for c in (cut[i:i + 32] for i in range(0, len(cut), 32)))
    print(f"cap at {cap}: {(raw > cap).mean() * 100:4.1f}% of requests truncated, "
          f"{100 * (1 - cut.sum() / raw.sum()):4.1f}% of tokens lost, "
          f"padding waste {100 * (1 - cut.sum() / padded):4.1f}%")
1
2
3
one 1,500-token request in 31 short ones: 48,000 slots for 2,275 real tokens, 95.3% wasted
cap at 256: 30.1% of requests truncated, 35.2% of tokens lost, padding waste 38.0%
cap at 512: 10.2% of requests truncated, 16.1% of tokens lost, padding waste 59.8%

Capping at 512 cuts padding from 80.4% to 59.8%, and in exchange it silently truncates 10.2% of requests, which hold 16.1% of all tokens. Capping at 256 truncates nearly a third of traffic and still leaves 38.0% padding. A truncation rate is a correctness number, so it belongs on a dashboard next to the latency graph, not buried in a config file. If an answer depends on the end of a 900-token document and the cap is 512, no amount of throughput tuning recovers it.

Sorting only pays when the queue is deep

Length-sorted batching looks like the free version of the fix: same padding logic, better grouping, no kernel changes. The catch is that sorting only creates tight bands when many requests are queued at once. With four requests in the queue, a sorted batch of four still spans a large slice of the distribution.

This grid runs the chat trace at four queue depths and three batch sizes. Each cell is the padding waste for that combination.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np

rng = np.random.default_rng(7)
raw = np.clip(rng.lognormal(np.log(160), 0.95, 5000), 8, 4096).astype(int)

def slots(L, batch):
    return sum(len(c) * int(c.max()) for c in (L[i:i + batch] for i in range(0, len(L), batch)))

def waste(L, batch, ordered):
    return 100 * (1 - L.sum() / slots(np.sort(L) if ordered else L, batch))

print("queued   batch   arrival   sorted")
for pool in (64, 256, 1000, 5000):
    L = raw[:pool]
    for batch in (4, 16, 32):
        print(f"{pool:6d}   {batch:5d}  {waste(L, batch, False):6.1f}%  {waste(L, batch, True):6.1f}%")
1
2
3
4
5
6
7
8
9
10
11
12
13
queued   batch   arrival   sorted
    64       4    49.8%    15.7%
    64      16    70.1%    51.0%
    64      32    77.9%    70.1%
   256       4    50.8%     4.2%
   256      16    71.2%    21.4%
   256      32    77.9%    37.2%
  1000       4    51.3%     1.2%
  1000      16    73.0%     5.7%
  1000      32    79.3%    10.5%
  5000       4    53.2%     0.6%
  5000      16    74.7%     2.3%
  5000      32    80.4%     3.8%

Two results matter. First, deep queues and small batches are where sorting shines: 5,000 queued at 4 per batch reaches 0.6% waste. Second, with a shallow queue sorting barely helps: 64 queued at 32 per batch moves 77.9% to 70.1%, which is not worth the reordering machinery. If a service sees a trickle of requests, sorting is a latency cost with no throughput return, because holding requests to form bands is what batching already does, only for longer.

The batch-size column is worth reading on its own. Larger batches raise arrival-order waste from 53.2% at 4 to 80.4% at 32 on the deep queue, since a bigger batch has more chances to contain an outlier. Batching harder is not free, which is the opposite of what a throughput chart usually suggests.

Sorting also has a wait to pay for, and the arithmetic is the same one that prices batching in the first place. To fill a batch of $B$ requests arriving at a steady $\lambda$ per second takes $B/\lambda$ seconds, so the mean request waits half that long, $B/(2\lambda)$. At 10 requests per second and 32 per batch, a full batch takes 3.2 seconds to assemble and the mean wait is 1.6 seconds before any inference starts. Sorting does not change that number, but it does require the queue to be deep enough to sort, which pushes in the same direction: the deeper the buffer that makes sorting work, the longer each request sits in it. Sorting does not remove that wait. It adds a reason to hold requests longer, which is how a throughput win turns into a latency complaint.

Packing removes the padding, not the constraints

The structural fix is to stop building a rectangular tensor. Packing concatenates whole requests into a flat token buffer and hands the kernel the boundaries, so a batch holds exactly the tokens that exist. Bin packing with a 4,096-token ceiling over the same trace:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np

rng = np.random.default_rng(7)
raw = np.clip(rng.lognormal(np.log(160), 0.95, 5000), 8, 4096).astype(int)
CAP = 4096

# first-fit decreasing: each micro-batch holds whole requests until it runs out of room
room, per_bin, members = [], [], []
for n in np.sort(raw)[::-1]:
    for i, r in enumerate(room):
        if r >= n:
            room[i] -= n
            members[i].append(n)
            break
    else:
        room.append(CAP - n)
        members.append([n])
bins, used = len(room), len(room) * CAP
print(f"packed: {bins} micro-batches of {CAP}, fill {(1 - sum(room) / used) * 100:.1f}%, "
      f"{100 * (1 - raw.sum() / used):.1f}% of capacity unused")
print(f"requests per micro-batch: mean {len(raw) / bins:.1f}, "
      f"{sum(1 for m in members if len(m) == 1)} bin(s) hold a single request")

padded = sum(len(c) * int(c.max()) for c in (raw[i:i + 32] for i in range(0, len(raw), 32)))
print(f"padded baseline, 32 per batch in arrival order: {padded:,} slots for {raw.sum():,} real tokens")
print(f"packing processes {padded / raw.sum():.2f}x fewer tokens and puts "
      f"{raw.sum() / bins:,.0f} real tokens in each micro-batch")
1
2
3
4
packed: 299 micro-batches of 4096, fill 99.9%, 0.1% of capacity unused
requests per micro-batch: mean 16.7, 1 bin(s) hold a single request
padded baseline, 32 per batch in arrival order: 6,238,680 slots for 1,223,960 real tokens
packing processes 5.10x fewer tokens and puts 4,094 real tokens in each micro-batch

Packing reaches 99.9% fill with 0.1% of capacity unused, and 299 micro-batches is the theoretical floor, $\lceil 1{,}223{,}960 / 4096 \rceil$. The 5.10x fewer slots is the saving the sorted policy found on a deep queue, except it holds at any queue depth. One caveat is visible in the output: a single 4,096-token request takes a whole micro-batch on its own, because nothing else fits beside it. The ceiling, not the packer, sets a floor on waste.

Packing is not a collator flag to flip without thought. The model has to know where each request ends, or attention mixes tokens across documents and you train on fiction. Krell et al. frame the work around exactly that: their packing gains a 2x BERT pre-training speedup while proving the packed model is mathematically equivalent to the padded one, and the equivalence depends on blocking attention at the boundaries. Hugging Face ships it as DataCollatorWithFlattening, which returns input_ids, labels and position_ids with the boundaries precomputed for flash_attn_varlen_func. Their guide is explicit that inferring boundaries from position_ids at runtime is the less preferred path and does not work for linear-attention models such as Qwen3-Next, which ignore position ids and need the collator’s boundary information.

Serving stacks make the same move under a different name. TensorRT-LLM’s in-flight batching requires packed input tensors with padding removed, and the docs give the reason in a footnote: padding single-token generation steps out to the maximum input length is an inefficient use of the machine.

The bookkeeping is small. Three requests of 40, 60 and 30 tokens become one 130-token buffer, and the kernel receives cumulative lengths of [0, 40, 100, 130]; attention is blocked between those marks, so token 41 cannot see token 39. The padded alternative would have been three rows of 60, or 180 slots for the same 130 real tokens.

RequestTokensStarts atEnds at
a40040
b6040100
c30100130

The second bill is seats that idle while the batch drains

Padding is the prefill half of the invoice. The decode half has a different shape: a static batch runs until its longest generation finishes, and every request that finished earlier leaves a seat empty for the rest of the run. The simulator below counts one seat-step per active request per decoding step, which is deliberately simple: it ignores prefill time and KV memory limits, and it charges every seat the same. The comparison it makes is still the one that matters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np

rng = np.random.default_rng(3)
SEATS = 32
first = np.clip(rng.lognormal(np.log(120), 0.8, SEATS), 1, 1024).astype(int)
queue = np.clip(rng.lognormal(np.log(120), 0.8, 400), 1, 1024).astype(int)

def static_batch(outputs):
    steps = int(outputs.max())          # the batch runs until its longest request finishes
    return steps * len(outputs), int(outputs.sum())

def continuous(first, queue):
    active, pending, steps, busy = list(first), list(queue), 0, 0
    while active or pending:
        while pending and len(active) < SEATS:
            active.append(pending.pop(0))
        busy += len(active)
        steps += 1
        active = [r - 1 for r in active if r - 1 > 0]
    return steps * SEATS, busy

for label, (capacity, busy) in (("static batch", static_batch(first)),
                                ("continuous", continuous(first, queue))):
    print(f"{label:12s} {capacity:8,d} seat-steps for {busy:,} real steps, "
          f"idle {100 * (1 - busy / capacity):5.1f}%")
print(f"static batch steps {first.max()}, mean output length {first.mean():.0f}, "
      f"longest to shortest {first.max() / first.min():.0f}x")
print(f"three longest requests need {[int(x) for x in sorted(first)[-3:]]}")
1
2
3
4
static batch   32,768 seat-steps for 5,698 real steps, idle  82.6%
continuous     85,088 seat-steps for 73,903 real steps, idle  13.1%
static batch steps 1024, mean output length 178, longest to shortest 68x
three longest requests need [564, 614, 1024]

In a static batch of 32, the longest generation needs 1,024 steps against a mean of 178, so the batch runs 1,024 steps and 82.6% of its seats are empty on average. The three longest requests need 564, 614 and 1,024 steps, so removing one outlier would not help much: the tail is a tail, not a typo. Refilling finished seats from a queue drops the idle share to 13.1%, and the residual is the drain at the end of a finite queue rather than the steady state of a busy service.

Two bills, one cause: a fixed shape. Padding waste comes from making every row as long as the longest row, and seat waste comes from making every row run as long as the longest row. Sorting and packing address the first, and per-iteration scheduling addresses the second. Fixing one leaves the other untouched, which is why a stack that only sorts its batches still looks inefficient in a utilisation chart.

What to measure in your own serving log

Three numbers, all cheap, all from data you already have:

  1. Slots under your real policy. Log prompt_tokens per request, replay the batching rule you actually run, and compute $\sumb\cdot \max(b)$ against the true total. Compare that ratio to the invoice, not to a benchmark.
  2. Truncation rate before any cap. Share of requests above the cap, and share of tokens lost. When the second number is larger than the first, the long documents are the ones paying.
  3. Queue depth against spread. Compute p99 over median of your prompt lengths. A ratio above 5 with a shallow queue is the case where sorting will not save you and packing will.

Keep the saving honest. Slots are not seconds: padded positions still hit memory bandwidth and the masked-attention path, so measured packing gains land at 1.4x to 2x, not at the 5.10x slot ratio. Treat the slot number as a ceiling on what the fix can buy, then measure throughput before quoting it internally.

One caveat before anyone rewrites a pipeline. At batch size 1 there is no padding, because there is no second request to pad against, and a low-traffic service may be running at batch 1 most of the day. Measure the batch-size distribution first. If most of your traffic is single requests, the padding bill is zero and the seat bill is the only one worth chasing.

FixWhat it removesWhat it costs
Sort by lengthMost of the padding, if the queue is deepLonger holds, and no benefit at shallow queues
Cap the widthPadding up to the capSilent truncation, which is a correctness change
Pack sequencesPadding entirelyBoundary-aware attention, varlen kernels, per-request position ids
Per-iteration schedulingIdle seatsScheduler complexity, preemption under memory pressure

Key takeaways

QuestionWhat the harness shows
How much does arrival-order batching waste?80.4% of slots on a heavy-tailed chat trace, 21.5% on narrow document traffic
Does sorting fix it?Only with a deep queue: 0.6% at 5,000 queued and 4 per batch, 70.1% at 64 queued and 32 per batch
Does capping the width fix it?It trades correctness for a partial win: 59.8% waste at cap 512, with 10.2% of requests truncated
What removes the padding?Packing, at 99.9% fill and 5.10x fewer slots, provided the attention boundaries are right
Is the slot ratio a speedup?No. Measured packing gains are 1.4x to 2x, so quote throughput, not slots
What does the decode side waste?82.6% of seats idle in a static batch whose longest generation sets the duration, against 13.1% with per-iteration refill

References

  • Krell, Kosec, Perez and Fitzgibbon, Efficient Sequence Packing without Cross-contamination (arXiv:2107.02027) — up to 50% padding in common datasets, 89% on GLUE-cola at width 128, 2x BERT phase-2 speedup — https://arxiv.org/abs/2107.02027
  • Hugging Face, Padding-free training — DataCollatorWithFlattening, boundary handling and the linear-attention caveat — https://huggingface.co/docs/transformers/en/padding_free
  • Lee et al., Improving Hugging Face Training Efficiency Through Packing with Flash Attention 2 — 2x on FLAN, 1.4x on OrcaMath, measured over 8 A100-80 GPUs — https://huggingface.co/blog/packing-with-FA2
  • Kundu et al., Enhancing Training Efficiency Using Packing with Flash Attention (arXiv:2407.09105) — dynamic padding versus packing, with ablations over batch size and sample selection — https://arxiv.org/html/2407.09105v4
  • NVIDIA, Paged Attention, IFB, and Request Scheduling — in-flight batching requires packed tensors, plus the padding footnote — https://nvidia.github.io/TensorRT-LLM/latest/features/paged-attention-ifb-scheduler.html
This post is licensed under CC BY 4.0 by the author.