Batching and Right-Padding Variable-Length Sequences
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Training or running inference on sequence models requires turning ragged, uneven-length feature vectors into rectangular 2D mini-batches. Implement batch_and_pad to group an ordered list of floating-point sequences into batches and right-pad shorter rows within each batch:
def batch_and_pad(
sequences: list[list[float]],
batch_size: int,
pad_value: float = 0.0,
drop_last: bool = False,
) -> list[list[list[float]]]:
...
Rules
- Sequential Grouping: Preserve input order and split
sequencesinto consecutive chunks containingbatch_sizesequences each (except possibly the final chunk whenlen(sequences)is not divisible bybatch_size). - Trailing Partial Chunk (
drop_last): Whendrop_lastisTrueand the last chunk has strictly fewer thanbatch_sizesequences, omit that chunk from the result. Otherwise (whendrop_lastisFalse, or when the last chunk already hasbatch_sizesequences), keep it. - Per-Batch Right Padding: Independently for each retained chunk, let
max_lenequal the length of the longest sequence inside that chunk. Extend every shorter sequence in that chunk on the right using copies ofpad_valueso all rows in the chunk share lengthmax_len. Do not mutate the caller's input lists. - Zero-Length Sequences: An empty list
[]is a valid sequence of length0. If every sequence inside a retained chunk is[], itsmax_lenis0and each row in that chunk stays[]. Ifsequencesitself is empty, return[].
Examples
Example 1
sequences = [[2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5]]
batch_size = 3
pad_value = 0.0
drop_last = False
batch_and_pad(sequences, batch_size, pad_value, drop_last)
# Output:
# [
# [[2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0]],
# [[8.0, 6.0], [9.5, 0.0]]
# ]
Walk-through:
- The first chunk holds [[2.5], [4.0, 1.5, 3.0], []] with lengths 1, 3, and 0. Its local width is 3, so [2.5] gains two trailing 0.0 entries and [] gains three.
- The second chunk holds [[8.0, 6.0], [9.5]] (2 sequences < 3), which is retained because drop_last=False and padded to its own local width of 2 (unaffected by width 3 from the first chunk).
Example 2
sequences = [[10.0, 20.0], [30.0, 40.0, 50.0], [], [], [70.0]]
batch_size = 2
pad_value = -9.0
drop_last = True
batch_and_pad(sequences, batch_size, pad_value, drop_last)
# Output:
# [
# [[10.0, 20.0, -9.0], [30.0, 40.0, 50.0]],
# [[], []]
# ]
Walk-through:
- Chunk 1 ([[10.0, 20.0], [30.0, 40.0, 50.0]]) has local width 3, so [10.0, 20.0] is right-padded with -9.0.
- Chunk 2 ([[], []]) contains only empty sequences, so its local width is 0 and both rows stay [].
- Chunk 3 ([[70.0]]) has only 1 sequence (< batch_size), so drop_last=True discards it.
Constraints
0 <= len(sequences) <= 10^50 <= len(seq) <= 5,000for everyseqinsequences- Total count of numbers across all input sequences does not exceed
10^6 1 <= batch_size <= 10^4pad_valueis a finitefloat
Step-by-step walkthrough
Understand the goal and input/output shapes
Deep learning frameworks process examples in rectangular arrays called tensors, where every row inside a mini-batch must have the exact same width. Because raw feature sequences arrive with different lengths, we need a preprocessing step that groups consecutive sequences into batches and extends shorter rows on the right.
Given
sequences,batch_size,pad_value, anddrop_last,batch_and_padreturns a 3D listbatchesin which each item is one rectangular 2D batch:Input sequences: [ [2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5] ] |---------- batch 0 ----------| |---- batch 1 ----| batch_size = 3, pad_value = 0.0, drop_last = False: batch 0: lengths [1, 3, 0] -> width = 3 -> [ [2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0] ] batch 1: lengths [2, 1] -> width = 2 -> [ [8.0, 6.0], [9.5, 0.0] ] (dropped if drop_last=True)Four invariants govern the output: - Order stays intact: indices
0 .. batch_size - 1form batch 0, the nextbatch_sizeform batch 1, and so on. - Strictly undersized final chunk:drop_last=Truediscards the trailing chunk only when its length is strictly belowbatch_size(<, never<=). - Per-batch width: each batch pads solely to the widest sequence inside that batch, unaffected by wider sequences elsewhere. - Zero-length sequences remain valid:[]has length0. When every sequence in a batch is[], its target width is0and every row remains[].Why batch-local two-pass processing is optimal
A naive implementation might compute the maximum sequence length once across the entire input list and pad every batch to that global width. If a single outlier sequence has length
5,000while all other sequences have length4, global padding inflates every batch by over1,000x. Findingmax_lenseparately inside each batch avoids any cross-batch bloat.Can we beat scanning each sequence reference and writing each output float once? No — every element in the returned 3D list must be allocated and filled at least once. With
ninput sequences andPtotal floats across all returned batches (real entries plus filler),O(n + P)time is the theoretical floor, provided we avoid quadratic operations or mutating the caller's lists.Partition sequences into fixed-count chunks
Python's
range(0, len(sequences), batch_size)yields the starting offsetstart_idxof each chunk:0,batch_size,2 * batch_size, and so forth. Slicingsequences[start_idx : start_idx + batch_size]clamps cleanly atlen(sequences)without raising anIndexErroron a short trailing chunk.len(sequences) = 5, batch_size = 3: start_idx = 0 -> sequences[0:3] -> 3 items (full) start_idx = 3 -> sequences[3:6] -> 2 items (short: len < batch_size)Only the very last slice can ever satisfy
len(raw_batch) < batch_size. Consequently, whendrop_lastisTrueandlen(raw_batch) < batch_size, we canbreakimmediately. We also validatebatch_size >= 1up front with a clearValueError.def batch_and_pad( sequences: List[List[float]], batch_size: int, pad_value: float = 0.0, drop_last: bool = False, ) -> List[List[List[float]]]: if batch_size < 1: raise ValueError("batch_size must be at least 1") # batches: 3D list of padded 2D batches, shape [num_batches][rows_in_batch][L_max_of_batch] batches = [] # Step through `sequences` in contiguous chunks of size `batch_size`. for start_idx in range(0, len(sequences), batch_size): raw_batch = sequences[start_idx : start_idx + batch_size] # Only the final slice can have strictly fewer than `batch_size` sequences; # a full final batch has len(raw_batch) == batch_size and is kept even when drop_last=True. if drop_last and len(raw_batch) < batch_size: break batches.append(pad_batch(raw_batch, pad_value)) return batchesRight-pad a single batch without mutating inputs
Inside
pad_batch(batch, pad_value), we run two simple loops overbatch:- Compute
max_len: Initializemax_len = 0and raise it wheneverlen(seq) > max_len. Starting at0naturally leavesmax_len = 0for an all-empty batch ([[], []]) with no extra branching. - Construct each padded row: Set
missing_count = max_len - len(seq), copy the original row vialist(seq), and concatenate[pad_value] * missing_counton the right.
Why call
list(seq)even whenmissing_count == 0? - Mutatingseqin place with.extend(...)would corrupt the caller'ssequencesargument. - Reusingseqdirectly without copying creates an alias (two variables referencing the exact same list object in memory), so any later edit to the output batch would silently alter the caller's input.def pad_batch(batch: List[List[float]], pad_value: float) -> List[List[float]]: """Right-pad every sequence in a single batch up to that batch's maximum length.""" # Phase 1: Find L_max across this batch only (starts at 0 so all-empty batches get 0). max_len = 0 for seq in batch: if len(seq) > max_len: max_len = len(seq) # Phase 2: Build a fresh padded row for every sequence without mutating the caller's lists. # padded_batch: 2D list of shape [len(batch)][max_len] padded_batch = [] for seq in batch: missing_count = max_len - len(seq) # Always copy `seq` with `list(seq)` even when missing_count == 0, so mutating # the returned batch later can never mutate the original input sequence. padded_row = list(seq) + [pad_value] * missing_count padded_batch.append(padded_row) return padded_batch- Compute
Walk through Examples 1 and 2
First trace Example 1 (
sequences = [[2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5]],batch_size = 3,pad_value = 0.0,drop_last = False):start_idx = 0 -> raw_batch = [[2.5], [4.0, 1.5, 3.0], []] max_len = max(1, 3, 0) = 3 seq [2.5] -> missing 2 -> [2.5, 0.0, 0.0] seq [4.0, 1.5, 3.0] -> missing 0 -> [4.0, 1.5, 3.0] seq [] -> missing 3 -> [0.0, 0.0, 0.0] start_idx = 3 -> raw_batch = [[8.0, 6.0], [9.5]] len(raw_batch) == 2 < 3, drop_last is False -> keep! max_len = max(2, 1) = 2 seq [8.0, 6.0] -> missing 0 -> [8.0, 6.0] seq [9.5] -> missing 1 -> [9.5, 0.0] Result: [ [[2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0]], [[8.0, 6.0], [9.5, 0.0]] ]Now trace Example 2 (
sequences = [[10.0, 20.0], [30.0, 40.0, 50.0], [], [], [70.0]],batch_size = 2,pad_value = -9.0,drop_last = True): -start_idx = 0:[[10.0, 20.0], [30.0, 40.0, 50.0]]pads to width3->[[10.0, 20.0, -9.0], [30.0, 40.0, 50.0]]. -start_idx = 2:[[], []]hasmax_len = 0->[[], []]. -start_idx = 4:[[70.0]]has length1 < 2withdrop_last=True, triggeringbreakand omitting the trailing chunk.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def pad_batch(batch: List[List[float]], pad_value: float) -> List[List[float]]: """Right-pad every sequence in a single batch up to that batch's maximum length.""" # Phase 1: Find L_max across this batch only (starts at 0 so all-empty batches get 0). max_len = 0 for seq in batch: if len(seq) > max_len: max_len = len(seq) # Phase 2: Build a fresh padded row for every sequence without mutating the caller's lists. # padded_batch: 2D list of shape [len(batch)][max_len] padded_batch = [] for seq in batch: missing_count = max_len - len(seq) # Always copy `seq` with `list(seq)` even when missing_count == 0, so mutating # the returned batch later can never mutate the original input sequence. padded_row = list(seq) + [pad_value] * missing_count padded_batch.append(padded_row) return padded_batch def batch_and_pad( sequences: List[List[float]], batch_size: int, pad_value: float = 0.0, drop_last: bool = False, ) -> List[List[List[float]]]: if batch_size < 1: raise ValueError("batch_size must be at least 1") # batches: 3D list of padded 2D batches, shape [num_batches][rows_in_batch][L_max_of_batch] batches = [] # Step through `sequences` in contiguous chunks of size `batch_size`. for start_idx in range(0, len(sequences), batch_size): raw_batch = sequences[start_idx : start_idx + batch_size] # Only the final slice can have strictly fewer than `batch_size` sequences; # a full final batch has len(raw_batch) == batch_size and is kept even when drop_last=True. if drop_last and len(raw_batch) < batch_size: break batches.append(pad_batch(raw_batch, pad_value)) return batches✅ Submit now — all tests should pass.
Intuition & how it works
Imagine packing wooden planks of uneven lengths into rectangular shipping crates that each hold batch_size planks. A crate does not need to be as long as the longest plank in the entire warehouse — it only needs to match the longest plank placed inside that specific crate (max_len). For any shorter plank in that crate, you fill the empty space on its right end with foam spacers (pad_value) so nothing slides around, and if the very last crate is only partially full, drop_last=True tells you to set that incomplete crate aside instead of shipping it. In machine learning pipelines, grouping examples into fixed-count chunks is called batching (processing several inputs together in parallel on hardware accelerators), and extending shorter rows at the end to form a rectangle is called right padding.
Why do simpler shortcuts go wrong? If you pad every sequence to the global maximum length across the whole dataset, a single 5,000-step sequence forces thousands of tiny 3-step sequences in completely unrelated batches to expand to length 5,000, wasting huge amounts of memory and compute. On the other hand, if you append pad_value directly onto the input lists using .extend(), you permanently corrupt the caller's dataset so it can never be reused in a second training epoch.
Let's trace Example 1 (sequences = [[2.5], [4.0, 1.5, 3.0], [], [8.0, 6.0], [9.5]], batch_size = 3, pad_value = 0.0, drop_last = False):
Chunk 1 (indices 0..2): [[2.5], [4.0, 1.5, 3.0], []]
-> lengths are 1, 3, and 0 -> max_len = 3
-> right-pad to 3: [[2.5, 0.0, 0.0], [4.0, 1.5, 3.0], [0.0, 0.0, 0.0]]
Chunk 2 (indices 3..4): [[8.0, 6.0], [9.5]]
-> 2 sequences (< batch_size 3), kept because drop_last is False
-> lengths are 2 and 1 -> max_len = 2
-> right-pad to 2: [[8.0, 6.0], [9.5, 0.0]]
Complexity
Let n be len(sequences) and P be the total number of floats across all returned batches (original values plus appended pad_value entries).
- Time:
O(n + P). Stepping acrosssequencesin chunks ofbatch_sizeand checkinglen(seq)visits each of thensequence references a constant number of times, and constructing the copied + padded rows writes each of thePoutput floats once (plus at mostO(n)skipped sequence references ifdrop_last=Truediscards the trailing chunk, which is absorbed intoO(n)). - Space:
O(P)for the output (O(batch_size)auxiliary space). Aside from the returned 3Dbatcheslist holdingPfloats,raw_batchholds at mostbatch_sizelist references at a time.
Notice why we express time and memory in terms of P rather than total input elements alone: P depends on how lengths are distributed inside each batch. Under the constraints (n = 10^5, batch_size = 10^4, max sequence length 5,000, total input elements <= 10^6), 10 batches each containing one length-5,000 sequence and 9,999 empty sequences have only 5 * 10^4 input floats yet require 10 * 10^4 * 5,000 = 5 * 10^8 output floats! That gap is inherent to rectangular batching and motivates lazy streaming and length bucketing in the follow-ups.
Edge cases
- Empty
sequences([]):range(0, 0, batch_size)runs zero iterations, returning[]whetherdrop_lastisTrueorFalse. - Fewer sequences than
batch_size(0 < n < batch_size): Produces a single short batch whendrop_last=False, or[]whendrop_last=True. - Exact multiple (
n % batch_size == 0): Every slice has lengthbatch_size, solen(raw_batch) < batch_sizeis never true anddrop_last=Truediscards nothing. batch_size == 1: Every sequence forms its own full 1-row batch withmax_len = len(seq), so zero padding is added and nothing is dropped.- Batch of only empty sequences (
[[], []]in Example 2):max_lenstarts at0and stays0, returning[[], []]with zeropad_valueelements appended. - Empty sequence paired with non-empty sequences (
[[2.5], [4.0, 1.5, 3.0], []]):[]has length0and expands cleanly into[pad_value, pad_value, pad_value]. - Invalid
batch_size < 1: Raises a descriptiveValueErrorinstead of lettingrange(..., 0)fail with a step-size error or letting negative steps return[]silently.
Common mistakes
- Dropping the final batch unconditionally when
drop_last=True: Writingif drop_last: batches.pop()throws away a completely full last batch wheneverlen(sequences)is an exact multiple ofbatch_size. Always checklen(raw_batch) < batch_size. - Padding to the global maximum length: Computing
max_lenonce across all ofsequencesinstead of inside each batch gives wrong widths on batches whose local maximum is smaller, failing Example 1 ([[8.0, 6.0], [9.5, 0.0]]has width2, not3). - Mutating or aliasing input sequences: Using
seq.extend(...)mutates the caller's input in place, and appendingseqdirectly whenlen(seq) == max_lenaliases the caller's list so later in-place edits to the output also change the input. Always copy withlist(seq). - Calling
max(len(s) for s in batch)withoutdefault=0in reusable helpers: While stride slicing never handspad_batchan empty batch, reusable helpers in streaming pipelines can encounter empty chunks; startingmax_len = 0(or passingdefault=0) avoidsValueError: max() arg is an empty sequence. - Left-padding instead of right-padding: Writing
[pad_value] * missing_count + list(seq)shifts every original element's index to the right, breaking positional alignment.
Follow-up questions
- How can you convert this function into a lazy iterator so arbitrarily large sequence streams can be batched in bounded memory? Turn the function into a generator (a Python function that uses
yieldto produce one batch on demand rather than materializing every batch in RAM at once) and pull chunks ofbatch_sizeitems fromiter(sequences)viaitertools.islice. That allowssequencesto be an unbounded disk or network stream and lowers peak memory fromO(P)across the entire dataset toO(batch_size * max_len)for the single batch currently yielded.
```python from itertools import islice
def stream_batches(sequences, batch_size, pad_value=0.0, drop_last=False): if batch_size < 1: raise ValueError("batch_size must be at least 1") iterator = iter(sequences) while True: raw_batch = list(islice(iterator, batch_size)) if not raw_batch or (drop_last and len(raw_batch) < batch_size): return yield pad_batch(raw_batch, pad_value) ```
- What changes are required to emit a companion attention mask alongside each batch distinguishing original entries from appended filler values? Alongside each
padded_row, construct[1] * len(seq) + [0] * missing_countas an attention mask (a binary indicator matrix telling downstream layers which positions carry real observations versus synthetic padding). This is crucial wheneverpad_value(such as0.0) can also occur naturally inside real input vectors, because a model cannot tell real0.0measurements apart from padded0.0slots without an explicit mask.
python
def pad_batch_with_mask(batch, pad_value=0.0):
max_len = max((len(seq) for seq in batch), default=0)
padded_batch = []
mask_batch = []
for seq in batch:
missing_count = max_len - len(seq)
padded_batch.append(list(seq) + [pad_value] * missing_count)
mask_batch.append([1] * len(seq) + [0] * missing_count)
return padded_batch, mask_batch
- When a dataset mixes very short sequences with occasional multi-thousand-step outliers, how can length bucketing cut down padding overhead without sacrificing training randomness? Apply pooled length bucketing (grouping sequences of similar lengths prior to batching so each batch's local
max_lenstays close to its members' true lengths). At the start of each epoch, shuffle the dataset, partition it into medium-sized windows (such as50 * batch_sizesequences per window), sort within each window bylen(seq)with small random tie-breaking jitter, slice each window intobatch_sizemini-batches, and shuffle the mini-batch order before training. Long outliers get packed together into one or two wide batches rather than stretching dozens of short batches, while cross-epoch shuffling keeps stochastic gradient updates unbiased.
Follow-up questions
- How can you convert this function into a lazy iterator so arbitrarily large sequence streams can be batched in bounded memory?
- What changes are required to emit a companion attention mask alongside each batch distinguishing original entries from appended filler values?
- When a dataset mixes very short sequences with occasional multi-thousand-step outliers, how can length bucketing cut down padding overhead without sacrificing training randomness?
Similar questions
- Siemens Technical Program Manager Behavioral Loop
- GRPO vs. PPO and Reward Granularity for Reasoning LLMs
- Model Post-Training Scenarios: End-to-End Delivery, Alignment Regressions, and Empirical Debate
- SFT, DPO, PPO, and KL Regularization in LLM Post-Training
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger