feat: speed up first_fit in sequence packing with a segment tree#15563
feat: speed up first_fit in sequence packing with a segment tree#15563fangwei123456 wants to merge 3 commits intoNVIDIA-NeMo:mainfrom
first_fit in sequence packing with a segment tree#15563Conversation
Signed-off-by: wei.fang <wei.fang@miromind.ai>
first_fit in sequence packing with a segment treefirst_fit in sequence packing with a segment tree
|
Which collection is this used in? |
|
@pzelasko This module ( |
|
Are you using this for speech / speech LLM models or something else? The repo was recently split and many collections (llm, vlm, diffusion) moved to their own repos in https://github.com/NVIDIA-NeMo org. Since these utilities are not used for any speech collection, my first thought is that it was on oversight to keep them when purging deprecated collection code. I don't think any of the speech models currently supports packed sequences (although we might add that support later). |
|
I use this packing technique to concatenate samples of different text types into long sequences for SFT training of the LLM. Thank you for your reply. If this method is not useful for speech processing, we can close this PR. |
Speed up
first_fitin sequence packing with a segment treeWhat does this PR do?
Replaces the O(n) linear scan in
find_first_bin_that_fitswith an O(log n) segment tree, reducing the overallfirst_fitpacking complexity from O(n^2) to O(n log n). This significantly speeds up sequence packing for large datasets.A
backendparameter is added tofirst_fitwith two options:"segment_tree"(default) — uses a segment tree for O(log n) per-query lookup"naive"— uses the original O(n) linear scanThe function signature and return type remain backward-compatible. Downstream callers (
first_fit_decreasing,first_fit_shuffle,create_packing_strategy,fill_packing_strategy) require no changes.This modification is particularly crucial for processing large datasets: in our own experiments, the time required to process 50GB of data was reduced from two and a half hours to just one minute.
Changes
nemo/utils/sequence_packing_utils.py_SegmentTreeclass: a 1-indexed flat-array segment tree that stores per-bin remaining capacity, with internal nodes tracking the max of their children. Supportsopen_bin,query(leftmost bin with capacity >= s), andupdatein O(log n).backendparameter ("segment_tree"|"naive") tofirst_fit._first_fit_naiveand_first_fit_segment_treeas the two backend implementations.find_first_bin_that_fitswith a deprecation note for backward compatibility.tests/utils/test_first_fit_backends.py(new)Performance
Benchmarked on 10,000 random sequences (lengths 1–500, pack_size=1024):
naivesegment_treeTests
All 16 tests pass, including correctness (both backends match) and performance (segment tree > 2x faster).
Signed-off-by: Wei Fang wei.fang@miromind.ai