Assign sequences to length buckets with searchsorted and count padding
Why it matters Length bucketing is used by training loaders and inference batchers to cut padding waste.
Bucketed batching groups sequences of similar length so each batch pads to its bucket size instead of the longest sequence overall. Finding each sequence's bucket is one np.searchsorted call.
Write bucketize(lengths, boundaries). boundaries is a sorted 1D int array b. Bucket k holds lengths L with b[k-1] < L <= b[k] (bucket 0 is L <= b[0]); bucket len(b) holds every L > b[-1]. Every sequence is padded to its bucket's boundary b[k], except in the overflow bucket, where sequences pad to the longest length in that bucket.
Return (bucket_ids, pad_tokens) where bucket_ids is an int array with one id per sequence and pad_tokens is the total number of padding tokens added over all sequences (an int).
def bucketize(lengths, boundaries)Example
bucketize([3, 8, 8, 20], [4, 8, 16]) gives bucket_ids [0, 1, 1, 3] and pad_tokens 1.
Understand the idea
np.searchsorted(b, v) finds where v would be inserted into the sorted array b to keep it sorted. side='left' puts v before equal values (returns the first index with b[k] >= v); side='right' puts it after them (first index with b[k] > v). That choice decides which bucket a boundary value falls in.
Worked example: boundaries [4, 8, 16]. Length 3: first boundary >= 3 is 4, index 0. Length 8: first boundary >= 8 is 8, index 1. Length 20: no boundary >= 20, index 3, the overflow bucket. Padding: 3 pads to 4 (1 token), the 8s pad to 8 (0), 20 is alone in overflow (0). Total 1.
Rule: bucket = searchsorted(b, L, side='left'), so b[k-1] < L <= b[k].
Bucketed data loaders for speech, translation and LLM fine-tuning use this to save compute on padding.
Shapes and data flow
lengths (N,), boundaries (K,) -> bucket_ids (N,), pad_tokens scalar