Skip to content

[WIP] DP load balancing - #4849

Draft
jinsooihm wants to merge 4 commits into
pytorch:mainfrom
jinsooihm:dp-dataload-balance
Draft

jinsooihm wants to merge 4 commits into
pytorch:mainfrom
jinsooihm:dp-dataload-balance

Conversation

@jinsooihm

@jinsooihm jinsooihm commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

An attempt to implement a load balancer at dataloader level.

Problem

The attention workload depends quadratically with respect to the individual document lengths within a sequence.
So, even if all DP ranks get the same length sequences, their total workload may differ, leading to imbalance and stragglers.

Constraint

Ideally, we should not change which samples are used for a single optimization step.
This limits how much you can balance.
Consider the example, DP = 4, and the input microbatches have the following workload

step 1 step 2 step 3 step 4
rank 0 10 10 10 10
rank 1 1 1 1 1
rank 2 1 1 1 1
rank 3 1 1 1 1

It is impossible to achieve load balance, rank 0 will be the straggler and the total time would be approximately 40.

Another problem is with respect to packing.
Suppose DP = 2 and seq_len = 10.
Rank 0 gets documents a, b with lengths 6, 4.
Rank 1 gets documents c, d with lengths 9, 1.
It may not be possible with rearrange the documents across the microbatches because there may be no other way to pack.

Lastly, we may not be able to balance within the whole DP group when DP degree becomes large.

Solution

We set a DP balance group size that we try to balance among the whole optimization step microbatches.
For example, if PP = 4, grad acc = 2, DP balance group size = 8, we shuffle the 4 * 8 * 2 many microbatches around.

Example with PP = 1 grad acc = 2, DP = 2

Microbatch Ordinary location Document lengths Cost
A rank 0, accumulation 0 [8] 64
B rank 0, accumulation 1 [4, 4] 32
C rank 1, accumulation 0 [2, 2, 2, 2] 16
D rank 1, accumulation 1 eight [1] documents 8
ordinary:
  accumulation 0: rank 0 = A:64, rank 1 = C:16 -> 64
  accumulation 1: rank 0 = B:32, rank 1 = D: 8 -> 32
  synchronized cost = 96

balanced:
  accumulation 0: rank 0 = A:64, rank 1 = B:32 -> 64
  accumulation 1: rank 0 = D: 8, rank 1 = C:16 -> 16
  synchronized cost = 80

Let G = grad acc steps, D = DP balance group size, P = PP degree
Algorithm goes by:

  1. sort the G * D * P microbatches from high to low workload
  2. for i from 1 to G
    1. LPT assign D * P many next microbatches to the DP ranks to minimize the total PP work

See also #3938 for RL side load balancing.

There are some choices to be made in the implementation.

  • Currently, all the DP ranks in the group read the same whole G * D * P microbatches from the dataloader.
    But one may also consider each DP rank reading G * P, communicating metadata, make a balancing plan, and communicate the inputs.
  • Different cost model
  • Different algorithm
  • Shuffling of individual documents, not just the microbatches

Implementation

To be extensible, I took inspiration from MoE routed experts, where there the token_dispatcher does dispatch and combine while the inner_experts does the computation.

Components and responsibilities

Component Role Why it is separate
LoadBalancingDataLoader Orchestrates one optimizer-step window and records metrics. Keeps the trainer-facing dataloader API independent of coordination and planning strategies.
InputCoordinator Decides which input streams each process reads, exposes a candidate window, and delivers the assigned local payloads. It also owns child-loader state and cleanup. Input ownership and data movement differ fundamentally between replicated reads and a future collective-based implementation.
TokenizedTextPackingAdapter Inspects concrete text tensors and produces small, tensor-independent metadata. The planner should not know about positions, padding masks, labels, or model kwargs. A different input format can supply another adapter.
QuadraticAttentionCost Converts packing metadata into an estimated amount of work. Cost estimation can evolve independently of input parsing and assignment.
WholeMicrobatchBalancer Assigns abstract items to output bins using only IDs, costs, sizes, and execution coordinates. Planning remains deterministic and independent of tensor storage or communication.

The coordinator abstraction is needed because it owns both sides of routing:
which payloads are visible before planning and how planned assignments become
local payloads afterward. The loader cannot own those details without assuming
a particular input topology.

Data flow

Trainer requests microbatches for one optimizer step
                         |
                         v
             LoadBalancingDataLoader
                         |
                         v
              coordinator.collect()
              - read candidate payloads
              - assign stable IDs
                         |
             itemize callback for each payload
                         |
          +--------------+---------------+
          | packing adapter              |
          | concrete tensors -> metadata |
          +--------------+---------------+
                         |
          +--------------+---------------+
          | cost model                   |
          | metadata -> estimated work   |
          +--------------+---------------+
                         |
         CoordinatedWindow(items, bins, payloads)
                         |
                         v
                balancer.plan()
                - metadata only
                - choose assignments
                         |
                         v
             coordinator.distribute()
             - realize assignments
             - return local execution order
                         |
                         v
            Trainer executes the full step

collect() receives the itemization callback because the coordinator owns the
input reads, while the loader owns the adapter and cost model. This arrangement
also fits a future coordinator that first inspects local payloads, exchanges
only metadata, and later exchanges reassigned tensors.

Limitations

The prefetch does not include load balancing, so if it takes long, it may not be hidden in the computation.

Summary:
- add optimizer-step batch grouping and trainer consumption
- add deterministic whole-microbatch planning for packed text
- add replicated input coordination, metrics, and checkpointing
- document the final design

Test Plan:
- 112 focused CPU tests passed
- two-rank DCP and torch_checkpointing round trips passed
- 10-step two-GPU balance run passed
- pre-commit passed except unavailable pyrefly executable
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 23, 2026
@fegin

fegin commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

We discussed the design offline. But I have a few meta questions:

  1. Do you do reshuffle on a single rank or do you do reshuffle within a small group of DP ranks? We agree it is probably not feasible to do reshuffling among the entire global batch, it is too expensive.

  2. Have you measure that this algorithm's effect on CP? Some analysis will be helpful.

@jinsooihm

jinsooihm commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@fegin

  1. Reshuffle within small group of DP ranks.
  2. Since we are not changing the content of each microbatch, my intuition is that this is orthogonal to CP load balancing. If we also want to take into account of CP load balancing effect in this load balancing, we can change the cost function from the C1(mb) = sum of squares of document lengths in the microbatch to something like C2(mb) = max cp rank workload for the microbatch.
    Ideally, we should have C1(mb) ~ C2(mb) * CP degree if the CP balancer is good, but this is not guaranteed.
    The problem can become more complicated if we allow shuffling the individual documents as well.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl 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.

2 participants