Skip to content

[RL] First-fit flat-token packing across DP ranks - #3938

Merged
wwwjn merged 9 commits into
mainfrom
better-dataloader
Sep 27, 2026
Merged

wwwjn merged 9 commits into
mainfrom
better-dataloader

Conversation

@wwwjn

@wwwjn wwwjn commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

What

Pack RL samples across the full token capacity of each DP-rank input instead of filling context-length rows first. FFD determines how many inputs are needed; padding-aware LPT tries to balance their attention work without increasing that count.

Let T be token capacity per DP-rank input, S the maximum context length, D the DP degree, and M the number of PP microbatches per scheduling step. FFD produces B bins, and G = ceil(B / (M * D)) gives a complete [G][M][D] grid. The RL trainer currently uses M=1; M>1 is exercised by CPU scheduling tests.

For each training batch:

  1. Sort samples by effective packed length and use FFD to find B bins, respecting both token capacity and max_num_documents. Retain the bins as a fallback.
  2. Round up to G * M * D grid slots; this fixes the padding budget for both packing paths.
  3. Try longest-first LPT over those slots. Place each sample in the feasible bin with the highest current padding-aware work, breaking ties by fewer packed tokens.
  4. If LPT cannot place a sample, discard its partial packing and use the retained FFD bins, splitting bins into extra slots only when doing so lowers their maximum estimated cost.
  5. Estimate each bin's document and tail-padding attention work as W = sum(L^2) + q * S^2 + r^2, where q, r = divmod(T - sum(L), S). The existing padding segments and fixed-size varlen metadata are unchanged.
  6. Sort bins by descending W and group adjacent bins into D-wide rows consumed concurrently.
  7. For each G step, assign heavier bins in each row to DP ranks with lower accumulated W; reset rank totals at the next step. M=1 retains the original alternating rank order. This is a heuristic, not an optimality or zig-zag dominance guarantee.

LPT and its FFD fallback have the same grid size, hence the same padding fraction. The full-attention cost estimate does not model EP imbalance, PP stage-specific work, or pipeline bubbles. Per-sample alignment and rank-tail padding remain marked in padding_mask; tail positions wrap at S without adding padding documents.

Batcher-only replay

Replay 20 steps of recorded Qwen3-4B DAPO Math prompt/completion token IDs and logprobs from hamishivi/DAPO-Math-17k-Processed_filtered through the production TrainingSampleBuilder (drop_zero_std_reward_groups=false) and the batcher. The recorder retained only the two extreme-reward siblings of eight per prompt, so this subset is not a representative complete rollout batch. The captured run (pr4356_native_3407a0c_run2) used S=T=10,240, four groups per step, and DP=1; DP=2 and DP=4 below are batcher-only simulations, not RL training or GPU throughput. This is a different recorded run from the one used for earlier PR measurements; all numbers below were recomputed together after rebasing on main (07b97cbfb).

Replay shape Weighted padding (before -> after) Mean DP-row W gap (before -> after) M=1 critical path, sum_g max_d W (before -> after) LPT fallback (after)
DP=2, S=T=10,240, 4 groups/step; 160 recorded samples 64.02% -> 64.02% 80.89% -> 2.31% 2,036,257,250 -> 971,884,990 0/20
DP=4, S=T=4,096, 8 groups/step, 32-document cap; 320 recorded samples 39.67% -> 30.73% 49.38% -> 17.73% 333,944,518 -> 169,762,998 1/20

"Before" is the actual rebased main next-fit batcher; "after" is this PR. Weighted padding counts real tokens and allocated slots across all 20 steps. For both policies, W is the sum of squared attention-segment lengths derived from the emitted positions (including padding segments); the mean row gap averages (max_d W - min_d W) / max_d W over DP rows. The critical-path proxy sums each row's maximum across all steps. Each emitted current-bin W also matches the scheduler's cost model. Of the padding-fraction metrics, only train_batch/padding_frac remains logged; the old online baseline metric and packing path have been removed.

On the newly packed bins in a separate M=3 CPU scheduling simulation, accumulated-cost greedy assignment beats zig-zag in 10/20 steps (10 ties) and 17/20 steps (3 ties), respectively. These examples have no regressions, but greedy does not dominate zig-zag in general. Median batcher-only CPU timings were 16.38 -> 15.84 ms/step and 16.93 -> 16.90 ms/step across three repetitions; the ranges overlap, so these timings do not establish a speedup. The replay script is local and is not committed.

Tests

  • python -m pytest tests/unit_tests/rl/test_batcher.py tests/unit_tests/rl/test_bin_scheduler.py tests/unit_tests/rl/test_async_controller.py tests/unit_tests/cpu/test_varlen_attention.py -q (51 passed; local vLLM CUDA library path resolved).
  • File-scoped pre-commit checks passed. Project-wide Pyrefly was skipped because of unrelated local errors; a full pre-commit --all-files run was not completed.

@wwwjn
wwwjn requested a review from tianyu-l July 17, 2026 02:43
@wwwjn
wwwjn requested review from felipemello1 and removed request for tianyu-l July 17, 2026 02:43
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 17, 2026
@wwwjn
wwwjn requested a review from tianyu-l July 17, 2026 02:43
@felipemello1

felipemello1 commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

the numbers would be much higher for thinking=True. Right now, our average response is ~40, so we cant really tell


def _cost_imbalance(self, packed_rows: list[dict]) -> float:
"""Mean over microbatches of (max rank cost / mean rank cost), where a rank's cost is the
block-diagonal attention cost sum(seq_len**2) of its rows.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC this PR only cares about DP ranks load balancedness, but not across PP ranks?

After #3856 (comment) and the PR, we should do microbatching in torchtitan when PP is enabled. In fact, we should think if it's possible to share batcher / utils between RL and supervised training.

Also check #3926 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current load balance is done in each row: We pack as balance as possible between each row. When split into microbatchs, you could directly chunk all packed rows without thinking about load balance again. The chunk happens in _build_microbatch_grid

Now the batcher sits on controller, and has the global view of the data packing and microbatch split. If PP is enabled, we can also split the packed_rows in _build_microbatch_grid() into microbatches of local_batch_size * dp_degree * pp_degree

In fact, we should think if it's possible to share batcher / utils between RL and supervised training

Agreed, we can start by sharing utils. And discussed with @felipemello1 , he pointed out the trainer dataloader is SPMD-ed, while the RL's batcher sit with global view and handles the load balancing, so they are naturally different

best = 0 # fresh microbatch: every row empty, row 0 is lowest-cost
rows[best].append(training_sample)
row_len[best] += length
row_cost[best] += length * length

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is assuming quadratic full attention, but we are seeing

  • linear attention
  • sliding window attention, interleaved with full attention (but I guess this is fine because the sliding window layers shouldn't affect batching decision too much)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is true, the assumption is based on full attention. We should let user set the cost model given a seq_length.

Comment on lines +63 to +70
local_batch_size: int = 8
"""Per-DP-rank microbatch size (rows per forward pass). If the number of tokens in the
rollouts exceed the number of rows*seq_len, a new microbatch is started.
If it is less, the remaining rows are padded to this size."""
"""Number of max-length sequences in each DP rank's token budget.

The model input is flat with shape ``[local_batch_size * seq_len]``.
"""

seq_len: int = 2048
"""Tokens per row (packed sequence length)."""
"""Maximum length of one packed sequence."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@acisseJZhong pending refactor to remove BatchConfig

for microbatch_assignments in assignments:
rank_costs = [
sum(
self._sequence_costs(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't read too careful -- this function is called once during _assign_training_samples_to_microbatches, do we need to run it again for metrics logging?

@tianyu-l
tianyu-l requested a review from acisseJZhong August 24, 2026 20:06
@wwwjn wwwjn changed the title [rl] Cost-aware batch packing: greedy longest-first with flush-on-overflow [RL] Balance flat-token batches across DP ranks Sep 15, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without considering attention load balancing across DP / CP, this sounds exactly the classic bin-packing problem. See https://en.wikipedia.org/wiki/Bin_packing_problem

Previously it was using

  • Next Fit (NF): Try to put an item in your current active bag. If it does not fit, close that bag and start a new one.

This PR is changing it to

  • First Fit Decreasing (FFD): Sort your items from largest to smallest. Place each item into the first available bag that has enough room. This method is fast and usually very close to the true minimum.

There's other simple heuristic like

  • Best Fit (BF): Place the item in the bag that leaves the least amount of empty space leftover.

The problem itself is NP-hard, but could you do a brief survey and see what makes sense as a default good heuristic here? To clarify, I don't think we should spend too much energy on this version, because with load balancing concerns it sounds a more complex optimization problem.
cc @acisseJZhong @jinsooihm

@tianyu-l tianyu-l Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry for the back-and-forth. Thought more about the problem.

There are two optimizations for the batcher: to not waste compute and to reduce load imbalance among microbatches (which helps when different DP ranks run different data, or when different PP microbatches are pipelined).

Reduce padding would help both, but that's only part of the picture.

Another (bigger) part is still load imbalance caused by attention layers. Here I'm not considering EP imbalance.

For attention, today's mixture would almost always be 1 full quadratic attention : ~3 sliding-window attention / linear attention. In this case, I'd assume

  • claim/assumption 1: The imbalance of linear / sliding window doesn't seem to matter much compared with full quadratic, because of n^2 vs. 3n assuming documents are long.
  • assumption 2: The load imbalance across CP currently is handled independently (@fegin has CP load balancer that works with fixed DP microbatches; linear attention CP seems scaling linearly without issue according to @drisspg).

Assuming intra-microbatch load balance is solved (which is strong assumption, but can be improved later), then to solve inter-microbatch load balance, we mostly only need to look at the full quadratic attention cost -- this is suggesting your initial direction should be what we pursue, namely the joint optimization

  • reduce padding as much as possible
  • use full quadratic attention as cost function (assuming CP's time is mostly spent on computation, and communication is not exposed much).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the bin-packing problem: Yes this a bin-packing problem and we set the cost model = length of the sequence. And in bin-packing problem (RL batcher), the number of bins is not fixed (in RL batcher, the number of microbatches is decided by how many rows we packed into). We want to minimize the number of bins because we want to minimize the padding.

  • We don't have fixed number of bins because we define number of samples need to be consumed per RL train step, instead of define per RL step by consuming a global batch in trainer
  • So RL is NOT only solving "inter-microbatch" load balancing problem

But in a "load balancing problem" not necessary need "non-fixed bin numbers". eg, the intra-microbatch load balancing problem usually given the microbatch_size so we fixed the number of bins, but try to balance sum_over_sequences(cost_function(sequence_length)): https://en.wikipedia.org/wiki/Largest_differencing_method

Thanks for make this super-crystal clear, I agree the batcher here have a mixed purpose of both now. And I don't know if I could make it jointly optimized for both goal at the same time, so I think using a reasonable (not optimal) algorithm is fine. Prime-RL and slime they converged to the same algorithm (so let's use this too)

  1. FFD packing: decide the total number of bins
  2. Round the bin count up to a multiple of the DP degree
  3. Estimate the workload of each packed bin = Sum(L^2)
  4. Karmarkar-Karp assign bins to different DP ranks, load balancing cross DP ranks

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's discuss tomorrow

@wwwjn wwwjn Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What we need load balance:

  • DP / PP / CP
  • DP: all the concurrent running DP microbatch need to be load-balanced, nothing do to with spmd gradient accumlation (outer)
    • Microbatch is direct goal to balance
  • PP: need to handle inner gradient acc
  • CP: Given DP split, Split in CP

@wwwjn wwwjn Sep 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you say more -- are you trying to make bucket 1, bucket 2, bucket 3, ... balanced compared with each other in terms of sum(bucket workload), or are you trying to make rows with in each bucket balanced?

The former one. Yes this is not enough.. Let me update it and give another try:

The grid is updated to be: [number_of_outer_microbatchs(G)][PP_microbatchs(M)][DP_degree(D)]

The optimization goal is: We have total (GMD) rows already assigned,

  • First and top goal: balance between intra-D group (all the rows with in the same D group)
  • Second: balance between intra-M group
  • Intra-G balance is not a goal

The updated algorithm is:

  1. FFD to pack into flattened rows: each row have length Sum(L) <= T (L denotes each sequence's length)

  2. Decide G for RL by G = ceil(num_rows / (D * M)), then round the total number of rows to a multiple of D*M by padding empty rows. So num_rows = G * D * M after padding.

  3. Move some sequence from the row with largest workload to the padded empty row. <- This is heuristic

  4. Recalculate each row’s workload:

    W(row) = Σ L²

  5. Sort all rows by workload in descending order.

  6. Reshape directly into:[G][M][D]

    with D as the innermost dimension:

    grid[g][m][d] = sorted_rows[(g × M + m) × D + d]

    Therefore:

    • Adjacent D rows execute concurrently across DP replicas and have similar workloads.
    • Adjacent M DP groups form one PP schedule and have similar workloads, reducing pipeline bubbles.
    • Workload is not balanced across G; heavy outer groups and light outer groups execute sequentially.
  7. Optionally rotate assignments within each D group so the same DP rank does not always receive the slightly heavier row.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense.

In 6, maybe another possible heuristic is to zig zag assign?
Like if G, M = 2 and we had rows 10, 8, 6, 4, it would be better to do
10, 4 on rank 0 and 8, 6 on rank 1 than 10, 6 on rank 0 and 8, 4 on rank 1.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wwwjn regarding your 6

  • intra D you are doing round-robin. It makes sense as you probably couldn't do any better because row has the most granular unit
  • intra M it's still round-robin so you are not exploiting the inter-row freedom?

Assuming DP4, PP2 (2 microbatches), let's say there are 8 microbatches and the workload could be look like 0 -> 7.

Yours produces:
0, 1, 2, 3
4, 5, 6, 7

Jin Soo suggests we may do
0, 1, 2, 3
7, 6, 5, 4

The benefit is that sum(PP0 + PP1) across DP ranks can be reduced from 10 to 7. This is assuming reshard_after_forward=False.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, thank you both for pointing out! Round-robin in both D and M dim doesn't make sense.

Jin Soo suggests we may do
0, 1, 2, 3
7, 6, 5, 4

I was thinking the load needs to be balanced cross PP microbatches, otherwise there are more PP bubbles. Eg in the above case, DP rank0 has PP microbatches 0 and 7, which means DP rank0 has huge PP bubbles

But I also agree the end-to-end step time of sum(PP0 + PP1) is smaller across all DP ranks, which is more important than bubbles

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I update the original step6 to be following:

  • Sort all bins by workload in descending order.
  • Partition the sorted bins into consecutive D-wide groups, so the D inputs executed concurrently have similar workloads.
  • Reverse every other D-wide group. In a [G][M][D] layout, this zig-zag pairs heavier and lighter PP microbatches on each replica.

@wwwjn wwwjn changed the title [RL] Balance flat-token batches across DP ranks [WIP] [RL] Balance flat-token batches across DP ranks Sep 15, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 15, 2026
@wwwjn wwwjn changed the title [WIP] [RL] Balance flat-token batches across DP ranks [WIP] [RL] First-fit flat-token packing across DP ranks Sep 15, 2026
@wwwjn wwwjn changed the title [WIP] [RL] First-fit flat-token packing across DP ranks [RL] First-fit flat-token packing across DP ranks Sep 21, 2026
@wwwjn
wwwjn requested review from jinsooihm and tianyu-l September 21, 2026 18:36

# Step 3: prefer balanced LPT splits over fully padded bins.
self._expand_bins_by_splitting(bins, target_num_bins=target_num_bins)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not have a solution in mind for now, but just a note:
If we have bins

bin 1 bin 2 bin 3
10, 10, 10, 10 10, 10, 10, 10 10, 10, 10, 10

and target_num_bins=4,

this will result in

bin 1 bin 2 bin 3 bin 4
10, 10, 10, 10 10, 10, 10, 10 10, 10 10, 10

but a better balance can be achieved by

bin 1 bin 2 bin 3 bin 4
10, 10, 10 10, 10, 10 10, 10, 10 10, 10, 10

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So there could be some choice to be made on splitting by considering only max candidate or some top candidates.

Other heuristic could be after we figure out target_num_bins from FFD, we do LPT on target_num_bins many empty bins?

@wwwjn wwwjn Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah _expand_bins_by_splitting this is heuristic

Other heuristic could be after we figure out target_num_bins from FFD, we do LPT on target_num_bins many empty bins

I was thinking the same, but one caveat that I'm worried about is if do LPT again, we need to make sure all the items can still be packed into target_num_bins. Sometime if would failed when we re-pack using LPT into target_num_bins. A better alternative is we can always try to LPT into target_num_bins; if there's samples can not fit, we can fallback to this "split-heaviest-bin" idea.

eg, items = eight 3s and nine 2s

FFD uses 7 bins:

4 bins: [3, 3]
3 bins: [2, 2, 2]

Suppose DP rounding gives target_num_bins = 8. LPT across eight bins does:

[3], [3], [3], [3], [3], [3], [3], [3]

Then distributes eight 2s evenly:

[3,2], [3,2], [3,2], [3,2],
[3,2], [3,2], [3,2], [3,2]

Every bin now has only one token left, so the ninth 2 cannot fit, even though FFD packed everything into only seven bins.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh nice example.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of splitting the single heaviest bin each time, you could do

  • while you still need new bins to be filled
    • create a new bin
    • while the new bin is not full
      • put a document from current heaviest bin into it (unless the current heaviest bin only had 1 document thus would be emptied)

You can use a heap to maintain this structure so dynamically taking current heaviest is cheap.

Caveat: be careful not to introduce dead loop.

assert not cell.padding_mask[cell.loss_mask].any()


def test_batcher_uses_flat_rank_capacity_and_reports_padding_reduction() -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some of the tests should go to rl/test_batcher.py


# Step 3: prefer balanced LPT splits over fully padded bins.
self._expand_bins_by_splitting(bins, target_num_bins=target_num_bins)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of splitting the single heaviest bin each time, you could do

  • while you still need new bins to be filled
    • create a new bin
    • while the new bin is not full
      • put a document from current heaviest bin into it (unless the current heaviest bin only had 1 document thus would be emptied)

You can use a heap to maintain this structure so dynamically taking current heaviest is cheap.

Caveat: be careful not to introduce dead loop.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

  • explain the algorithm from the actual code you read, not from comments / reviewer discussions
  • evaluate if it makes sense, or if there are obvious improvement opportunity

@claude

claude Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 21s —— View job


Review: first-fit flat-token packing across DP ranks

  • Read the diff and batcher code
  • Check how varlen/flex attention treats tail padding
  • Explain the algorithm from the code
  • Evaluate it and look for improvements

I couldn't run Python in this job because the tool permissions didn't allow it, so no tests or simulations ran. The numbers below are worked out by hand from the code.


What the code actually does

Entry point: _pack_one_training_batch → _assign_training_samples_to_microbatches (batcher.py:291). The terms used below:

  • T = _num_rows_per_microbatch * seq_len, the flat token budget for one rank.
  • S = seq_len, which is max_context_length.
  • D = dp_degree.
  • L = num_tokens_to_pack(sample): len(token_ids) - 1, rounded up to per_sample_pad_multiple.
  1. First-fit decreasing (FFD) into flat bins of size T.
    • Samples are sorted by L, longest first.
    • Each sample goes into the first existing bin with tokens + L <= T and len(bin) < max_num_documents. If none fits, a new bin is opened.
    • The row boundaries are gone. A document can now cross an old S-sized row boundary. This is fine because each doc is ≤ S (add_training_samples drops longer ones), and positions reset per doc.
  2. Round up (:347): target = ceil(B / D) * D.
  3. Fill the extra slots (_expand_bins_by_splitting, :372).
    • A max-heap holds every bin with more than one sample, keyed by W = sum(L^2).
    • For each missing bin, the code repeatedly pops the heaviest donor and looks at that donor's shortest sample.
    • It moves the sample if the new bin has token room and L^2 < W_donor - W_new, i.e. the move shrinks the gap between donor and new bin. Otherwise the donor is set aside for the rest of this new bin.
    • The inner loop stops when the heap is empty or the document cap is reached.
    • The loop is guaranteed to terminate. Each iteration either moves a sample or permanently skips a donor for this bin; that skip stays valid because W_new and the new bin's token count only grow.
    • If a new bin ends up with no samples, the remaining slots become empty bins.
    • On Jin Soo's 3 × [10,10,10,10] → 4 example this yields 4 × [10,10,10], so that concern is addressed.
  4. Sort bins by W descending (:353) and cut them into consecutive groups of D. Group g is outer accumulation step g, and bin d in it goes to DP rank d.
  5. Zig-zag (:363): every odd group is reversed.
  6. Baseline for the metric only: _assign_with_row_packing re-runs the old next-fit-rows policy every step so that padding_frac_before_load_balance can be emitted.

Does it make sense?

The parts that are right:

  • FFD for the bin count. For a flat budget it is a good default. Best-fit decreasing is usually no better than FFD at this scale, so I wouldn't spend time switching.
  • Sort, then chunk into D-groups. For M=1 the step time is sum_g max_d W[g][d]. Given a fixed multiset of bins, sorting and cutting into consecutive groups of D is provably optimal for that sum. Nothing to improve there.
  • Zig-zag. As the PR says, it does nothing for M=1.

The two real gaps are further up the pipeline.

1. (Major) The cost model ignores tail padding, and tail padding is quadratic attention too

_pack_training_samples fills the tail with positions index % seq_len (:628). Both create_varlen_metadata_for_document (attention.py:631-639) and the flex document mask treat each padding reset as a document start. So the tail becomes pseudo-documents of length S, each with full causal attention. With T ≫ mean L, this is not small.

Worked example with S=10240 and T=61440 (the PR's multi-row shape), cost measured in L^2:

bin modeled W tail padding true attention cost
6 × 8k docs 403M 12,288 → 105M + 4M 512M
20 × 1k docs 21M 40,960 → 4 × 105M 440M
empty bin 0 6 × 105M 629M (heaviest in the batch)
  • What the scheduler sees: a 19× imbalance between the first two bins, and it treats empty bins as the lightest (they sort last).
  • What the kernel does: the two bins are within about 15%, and any empty bin is the straggler.
  • Effect on step 3: the stopping rule (:421) stops filling a new bin as soon as its W gap to the donors closes. That usually leaves the new bin mostly padding, and therefore expensive in reality.

Options:

  • (a) Cheap, local fix: add the padding segments to _attention_workload. For q, r = divmod(T - sum(L), S), add q * S**2 + r**2. This makes steps 3–4 optimize what the kernel actually runs.
  • (b) Better, as a follow-up in core: shorten the tail padding segments, e.g. reset positions every 128 tokens instead of every S. Padding attention then becomes about linear, and sum(L^2) becomes an accurate model.
    • This needs max_num_padding_segments in attention.py:647 to reserve ceil(T / pad_segment_len) slots.
    • The trade-off is slightly larger fixed metadata under CUDA graphs.
    • It also removes wasted attention FLOPs in every padded step, RL or not.

Fix (a) →

2. FFD bins are very skewed, and only D-1 bins at most get rebalanced

  • Why FFD bins are skewed: because FFD is decreasing first-fit, bin 0 takes the longest docs, bin 1 the next longest, and so on. W falls steeply across bins.
  • Why that matters: the cost only depends on imbalance inside a D-group, and adjacent sorted FFD bins can still differ a lot.
  • Why step 3 doesn't fix it: it only touches the heaviest donors, only to fill the target - B (< D) new slots, and it never moves work between existing bins.

Once target is fixed, the obvious improvement is:

  • Re-pack with capacity-constrained LPT: longest first, into the lowest-cost bin that still has token and document room, over exactly target bins.
  • Fall back to FFD + split if any sample doesn't fit. This covers @wwwjn's eight-3s / nine-2s counterexample, where LPT needs one more bin than FFD.
  • A cheaper variant only re-balances inside each D-group: pool the group's samples and LPT them into D bins with capacity T. If that fails, keep the original group. This keeps G unchanged and targets exactly the max_d term.
  • An earlier revision of this PR (lowest-cost fitting row) was essentially this without the fallback.
  • Do this together with (a); otherwise it balances the wrong quantity.

3. Smaller points

  • _expand_bins_by_splitting always moves the donor's shortest sample (:411).
    • Shortest moves the least L^2 per move, so it takes the most moves.
    • With max_num_documents set, the new bin can hit the document cap on tiny docs before the heavy donors come down much.
    • Suggested fix: move the largest sample with L^2 < W_donor - W_new that still fits. That closes the gap fastest and uses fewer document slots. The termination argument is unchanged.
  • Zig-zag only generalizes to M=2. Reversing every other D-group gives the right pairing for M=2. For M≥3, forward/reverse/forward gives rank 0 the heaviest row twice.
    • When PP lands, assign each g's M×D rows to ranks by greedy LPT on sum_m W (M rows per rank) instead.
    • For now it's harmless but speculative. Keeping it until PP exists is fine, but consider a TODO that notes the M=2 assumption.
  • The baseline policy runs every step only for a metric (:208, _assign_with_row_packing, _fill_empty_rank_assignments, _assign_training_samples_to_rows).
    • This keeps about 80 lines of the old next-fit policy alive in the hot path. Tianyu raised this earlier.
    • I'd keep it only as long as needed to validate, then delete it.
    • The metric name padding_frac_before_load_balance is also inaccurate: it measures the old next-fit packer, not "before load balance". padding_frac_next_fit_baseline would be clearer.
  • _padding_fraction counts real tokens as len(token_ids) - 1. So per_sample_pad_multiple alignment padding counts as padding, the same as the old ~padding_mask count. That's consistent, just noting it's intended.
  • Tests: as Tianyu noted, the batcher tests belong in rl/tests/test_batcher.py. Two tests would lock in the tricky cases:
    • Jin Soo's [10×4]×3 → 4 case.
    • A case where the document cap is hit during splitting.

Summary

  • Keep: FFD for the bin count, and sort + chunk + zig-zag for placement. Placement is optimal for M=1 given the bins.
  • Change before tuning further: the cost model. With tail padding split into S-length pseudo-docs, padding attention is often as large as the real sum(L^2), and empty bins are the most expensive rather than the cheapest. Fix (a) in this PR, or (b) as a follow-up.
  • Next-biggest win: capacity-constrained LPT over the fixed target bin count, with an FFD fallback. Today at most D-1 bins get rebalanced.
  • For the end-to-end numbers the PR still owes: measure per-rank step time, not just padding fraction.

@tianyu-l

Copy link
Copy Markdown
Contributor

@wwwjn claude's points sound valid to me.

  • would we consider running FFD for getting bin count only, and do LPT for actual packing, because FFD naturally biases toward imbalance?
  • consider the cost of padding -- we can't turn all padding into seq-length-1 elements for attention, because our attention backend has a max_num_documents limitation.
  • verify / improve zig-zag when M > 2.
  • do some (at least elementary) benchmarking to confirm if there really is improvement

@wwwjn

wwwjn commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

@wwwjn claude's points sound valid to me.

  • would we consider running FFD for getting bin count only, and do LPT for actual packing, because FFD naturally biases toward imbalance?
  • consider the cost of padding -- we can't turn all padding into seq-length-1 elements for attention, because our attention backend has a max_num_documents limitation.
  • verify / improve zig-zag when M > 2.
  • do some (at least elementary) benchmarking to confirm if there really is improvement

@claude review this code again. I've addressed @tianyu-l 's concern:

  1. Consider running FFD first then LPT for packing: Now the packing will first run LPT, if in some corner case can not fit, then fall back to FFD
  2. Cost of padding is also added into considerration
  3. Zig-zag doesn't work when M>2: Using a cost based greedy algorithm instead of zig-zag, to make the total cost across G steps of each DP rank close to each other. both zig-zag and this greedy are heuristic, greedy is not strictly better than zig-zag, but it's more general for M>2.
  4. Benchmarking using historical rollout from DAPO has been added in PR description

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 4m 34s —— View job


Re-review: LPT + padding-aware cost + greedy rank assignment

  • Read the updated diff (batcher.py, test_batcher.py, test_bin_scheduler.py)
  • Check LPT + FFD fallback
  • Check padding-aware cost
  • Check greedy rank assignment vs zig-zag
  • Post review

I couldn't run Python in this job (the tool permissions didn't allow it), so no tests or simulations ran. The examples below are worked out by hand from the code.


What the code does now (from _assign_training_samples_to_microbatches, batcher.py:341)

  1. FFD (:373-401) packs the samples into B bins and keeps them as the fallback.
  2. Round up: target = ceil(B / (M*D)) * M*D (:404-408).
  3. LPT (_pack_with_lpt, :453) runs over target empty bins.
    • Samples go longest first. Each one lands in the feasible bin with the smallest document-only sum(L^2).
    • If any sample doesn't fit anywhere, it returns None. The code then uses the FFD bins plus _expand_bins_by_splitting, which now uses the padding-aware cost for both the heap key and the accept test.
  4. Sort the bins by the padding-aware W = sum(L^2) + q*S^2 + r^2 (:417, :430).
  5. Assign to ranks with assign_sorted_bins_to_dp_ranks (:48).
    • Each G step is split into M consecutive D-wide rows.
    • In each row, the heaviest bin goes to the rank with the smallest running total, then the next heaviest to the next rank, and so on.
    • Totals reset at every G step.
    • When M=1, all ranks start each row at 0, so the only thing deciding the order is the tie-break. That makes it alternating zig-zag, which has no effect on step time when M=1.

Overall this addresses the three algorithm points from last round:

  • The same grid is used for LPT and FFD, so padding is identical.
  • Padding is now in the cost used for sorting and rank assignment.
  • The zig-zag problem at M≥3 is replaced by a cumulative-cost greedy.

The tests cover the tricky cases: the fallback (8×3 + 9×2), the document cap, M=3, the greedy-loses-to-zig-zag counterexample, and a randomized conservation/capacity sweep. Good work.


1. (Main issue) LPT balances sum(L^2), but the scheduler scores bins with padding-aware W

_pack_with_lpt places samples by document-only work (:483). Its docstring says padding-aware work "can decrease when a bin receives samples, so it is not an LPT placement key."

That's true for a min key, but it means LPT is balancing a different quantity from the one steps 4-5 and the PR's own metrics measure. The gap is widest exactly where RL data is common: documents truncated at S.

An L = S document costs S^2 under sum(L^2). Under W it costs zero extra, because it just replaces one S-length padding segment. So LPT treats bins holding truncated documents as "heavy" and stops filling them. Those bins end up mostly padding, which makes them the heaviest under W.

Worked example: T = 6S, D=2, with 3 documents of length S and 16 of length S/4. FFD gives B=2, and LPT succeeds.

bin 0 bin 1 max W
This PR's LPT (sum(L^2) key) [S, S], 2S tokens → W = 2S² + 4S² = 6S² [S, 16×S/4], 5S tokens → W = S² + S² + S² = 3S² 6S²
Balanced by W [S, S, 8×S/4] → 2S² + 0.5S² + 2S² = 4.5S² [S, 8×S/4] → S² + 0.5S² + 3S² = 4.5S² 4.5S²
  • That is a 25% lower critical path with the same grid and the same padding.
  • In this case the PR's LPT gives bin 0 the same cost as an empty bin (6S²).
  • Smaller version: S=10, T=20, samples [10, 5, 5, 5, 5]. LPT gives [10] | [5,5,5,5], so W = 200 | 100. FFD alone gives [10,5,5] | [5,5], so W = 150 | 150. Here the LPT path is worse than the FFD path it replaced.

Suggested fix: keep LPT, but key it on padding-aware W and place each sample in the feasible bin with the highest current W.

  • Adding a document never increases W. With padding P = qS + r, adding a document of length L changes W by 2(L-S)(L-r) ≤ 0 when L > r, and by 2L(L-r) ≤ 0 when L ≤ r.
  • So this is standard LPT for jobs that reduce cost: the bin currently in the worst state gets the next reduction.
  • Break ties by fewer tokens. Otherwise the all-empty start (every bin at k·S²) and each L = S placement (Δ=0) will pile everything onto bin 0.
  • On the first example above, a hand trace of this gives 4.5S² | 4.5S². On the second it gives 150 | 100, so the max of 150 matches FFD instead of 200.
  • It needs about four changed lines in _pack_with_lpt. The FFD fallback is unchanged.
  • Please A/B it on your DAPO replay: report the within-row (max W - min W) / max W, the LPT fallback rate, and the sum_g max_d W critical path.

Fix this →

2. Greedy vs zig-zag: take the better of the two

assign_sorted_bins_to_dp_ranks documents correctly that greedy can lose to zig-zag (the 192 vs 191 test).

  • Both cost O(M·D) per G step, so you can compute both assignments and keep the one with the lower max_d sum_m W.
  • That result is never worse than either heuristic, and it removes the "not strictly better" caveat from the docstring.
  • It's cheap and optional. It only matters once PP passes num_pp_microbatches > 1; production uses the default M=1 today.

3. Baseline code kept only for the metric (same point as last round, still open)

_pack_one_training_batch (:258) runs the whole old policy every step: _assign_with_row_packing, _assign_training_samples_to_rows, and _fill_empty_rank_assignments, roughly 100 lines (:589-691).

  • It isn't quite the pre-PR policy. Main's _build_document_limited_microbatch_grid moved a whole row from the first multi-row cell (donor.pop()). _fill_empty_rank_assignments moves the shortest sample from the cell with the most tokens. So padding_frac_before_load_balance compares against a slightly improved baseline, not exactly what main shipped. This is minor for padding, but worth knowing when quoting "before" numbers.
  • The _assign_training_samples_to_rows docstring says "for comparison and fallback" (:613), but it is never used as a fallback.
  • The metric name is still padding_frac_before_load_balance (:816). It measures the next-fit packer, so a name like padding_frac_next_fit_baseline would be clearer.
  • I'd delete all of it once the replay numbers are in the PR, which they now are. If you want to keep one comparison signal, a cheap train_batch/lpt_fallback counter (0 or 1) is more useful going forward. It tells you how often the FFD+split path actually runs.

4. Smaller points

  • _expand_bins_by_splitting (:495) is correct and terminates. Each successful move transfers one sample into the new bin, which is not in the heap while it is being filled, and skipped donors are only retried after a move.
    • It is O(len(donor)^2) per pop, because of the slice plus _attention_workload.
    • It also re-pushes every skipped donor after each move.
    • That's fine at the current scale (hundreds of samples, fallback path only). Just don't reuse it on a hot path.
  • _attention_workload runs twice per bin (:417 and :421). Compute the list once and sort indices. This is trivial.
  • The num_pp_microbatches keyword exists only for tests right now. That's reasonable prep for PP. Just make sure the trainer's consumer of [G*M][D] gets the matching reshape when PP lands.
  • The cost model still assumes all-full-attention layers, as discussed with Tianyu. That's acceptable. A one-line TODO near _attention_workload about hybrid SWA/linear models would help future readers.

Summary

  • Merge-worthy structure: FFD for the bin count, then LPT on the same grid with an FFD fallback, padding-aware sort, and per-row rank assignment.
  • One substantive change I'd make before landing: key LPT on padding-aware W, placing each sample in the highest-W feasible bin with a fewest-tokens tie-break. As written, LPT optimizes a different objective from the one used to sort and assign bins. It can leave bins holding truncated L = S documents as expensive as empty bins, and can even do worse than plain FFD ([10,5,5,5,5] example).
  • Nice to have: best-of greedy/zig-zag for M>1, delete the baseline path, and add an LPT-fallback counter.

Pack variable-length training samples directly into each DP rank token budget using longest-first token-count balancing. Remove the architecture-specific cost-model concept, preserve padding masks and document limits, and report padding before and after load balancing.
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude
regarding padding, we need to take this code into account
torchtitan/models/common/attention.py#L646 (https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/attention.py#L646), where we cut the padding into subsequences of lengths <= max_context_length.

Of course, this is assuming varlen attention kernel being used, but I think it's the correct default.

@claude

claude Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 48s —— View job


Padding cost vs. the varlen padding split in attention.py:646

  • Read create_varlen_metadata_for_document (torchtitan/models/common/attention.py:597-697)
  • Read the batcher's tail padding (batcher.py:668-674) and _attention_workload (batcher.py:437-459)
  • Check that the cost model matches what the kernel runs
  • Look for improvements that stay within the metadata limit

I couldn't run Python in this job (tool permissions), so the numbers below are worked out by hand.


1. The current cost model matches varlen exactly

This is what create_varlen_metadata_for_document does with padding_mask:

  • A position reset inside padding_mask counts as a padding segment, not a real document (:635-638).
  • Padding segments get their own budget of ceil(T / S) slots (:646-650), on top of max_num_documents. Both limits are checked with _assert_async (:667-669).
  • max_seqlen = S (:671), so every segment must have length <= S.
  • Unused slots are filled with num_tokens (:659-661). That makes them zero-length segments, so they cost nothing.

This is what the batcher emits:

  • Alignment padding (per_sample_pad_multiple) continues the document's range(sample_len) (:663-665). It never resets positions, so it uses no padding slot. It adds to the document's own L, and num_tokens_to_pack already counts it.
  • Tail padding of length P = T - sum(L) uses index % S (:673). That gives q = P // S full segments plus one segment of length r. This is q + (r > 0) resets, always <= ceil(T/S), so it fits the budget.

So the kernel sees documents L_i, then q segments of length S, then one of length r. W = sum(L^2) + q*S^2 + r^2 models exactly that. The flex document mask (get_document_mask_mod) splits on the same position resets and has no slot limit, so the model also holds there.

Earlier I suggested splitting padding into many short segments (e.g. 128 tokens). You're right that this is blocked: it would need more than ceil(T/S) padding slots, which means changing core metadata.

2. A free improvement within the same budget: split the tail into equal segments

The batcher always reserves k = ceil(T/S) padding slots, but it only uses ceil(P/S) of them. Spreading the tail across all k slots in near-equal pieces stays within every constraint:

  • Each piece is at most ceil(P/k) <= ceil(T/k) <= S.
  • The number of resets is at most k.
  • attention.py needs no change.

The padding cost becomes pad(P) = a*(c+1)^2 + (k-a)*c^2, where c, a = divmod(P, k). That is the smallest possible sum of squares for splitting P into <= k parts, so it is never worse than today's q*S^2 + r^2.

Example with S=10, T=60, k=6:

tail P today (% S) equal split
60 (empty bin) 600 600
45 425 339
30 300 150
20 200 68
5 25 5

A mostly-full bin's padding drops from O(S^2) to roughly P^2/k. That wasted attention compute is removed on every step. Real tokens should be unaffected, because padding only attends to padding and is excluded from the loss. That still needs checking: with --debug.seed=42 --debug.deterministic, loss and grad_norm should be bit-identical.

The change is local to the batcher:

  • In _pack_training_samples, replace index % self.seq_len with resets at the equal-split boundaries.
  • Update _attention_workload to the new pad(P).
  • Update the positions example in the docstring ([0,1,0,1,0,1,2,3] stays the same when k=1).

Fix this →

3. This change breaks an assumption in the current LPT key

_pack_with_lpt places each sample in the feasible bin with the highest current W (:482-493). That rule is only safe when adding a document never increases W. This holds for today's % S layout, because a document just replaces part of a padding segment.

Under the equal-split model it no longer holds. Take S=10, k=6, tail P=20, and add a document with L=10:

  • New cost: 100 + pad(10) - pad(20) = 100 + 18 - 68 = +50.
  • So W goes up.

The general rule is place the sample in the feasible bin with the smallest W after placement (break ties by fewer tokens). This works whether W goes up or down, and it reduces to classic LPT when the change in W is the same for every bin. The per-candidate cost is O(1) if you track sum(L^2) and tokens for each bin. If you keep today's % S padding, the current key is fine.

Summary

  • Nothing is wrong today. _attention_workload already matches the varlen split at attention.py:646: padding segments of at most S, a reserved budget of ceil(T/S) slots, and alignment padding folded into each document.
  • Suggested improvement (optional): split the tail evenly across all ceil(T/S) reserved slots.
    • It needs no change to core metadata and only lowers padding attention cost.
    • It does require updating _attention_workload and switching LPT to a min-post-placement key.
    • It could land in this PR or as a small follow-up, with a loss-equality check.
  • Varlen as the default cost model is fine: flex document masking splits on the same position resets, so the same estimate applies.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stamp to unblock, but see if you'd like to include some more improvements suggested by claude

The new batcher groups samples into different microbatches than the
row-based next-fit packing, which changes fp32 reduction order in the loss
and gradient accumulation. Per-token trainer logprobs are unchanged
(bit_wise/logprob_diff/max stays 0), so step 1 differs only in the last
bits and later on-policy steps diverge from the resulting ulp-level
weight difference. Values are taken from the A10G CI run on eb18cc2.
@wwwjn
wwwjn merged commit 51bf359 into main Sep 27, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants