Skip to content

[rl] Support pipeline parallelism in trainer - #3980

Merged
wwwjn merged 2 commits into
mainfrom
rl-trainer-pp-cp-ci
Oct 19, 2026
Merged

wwwjn merged 2 commits into
mainfrom
rl-trainer-pp-cp-ci

Conversation

@wwwjn

@wwwjn wwwjn commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Depends on pytorch/pytorch#200238, which adds step(loss_kwarg_mbs=...) to pipeline schedules. Every PP run in TorchTitan now passes it, so CI will fail until that change reaches the torch nightly.

Why

The RL trainer rejected pipeline parallelism for two reasons:

  1. TorchStore could not publish a complete model from stage-local state dicts. The routing client from Add precomputed routing for weight sync #5061 fixes this: every stage publishes into the same key.
  2. The RL loss takes per-token arguments (advantages, generator logprobs, loss mask, temperature) that differ per microbatch, and pipeline schedules passed the same loss_kwargs to every microbatch. [pipelining] Add loss_kwarg_mbs for per-microbatch loss keyword arguments pytorch#200238 adds loss_kwarg_mbs for this, so TorchTitan no longer needs an RL-side workaround.

What changes

  • Engine (shared): under PP, the engine copies global_loss_token_counts into each microbatch's loss arguments and passes them to the schedule as loss_kwarg_mbs, instead of raising "not supported with pipeline parallelism yet". It also collects one loss metrics dict per microbatch: the schedule's scalar loss wrapper fills a per-microbatch loss_metrics dict, replacing it on each call because the schedule also calls the loss on microbatch 0 while inferring stage metadata. ForwardBackwardResult.loss_metrics is now nested like microbatch_groups (one list per group, one dict per microbatch). The pretraining trainers do not read these metrics.
  • GraphTrainer: its traced loss takes one shared set of loss arguments. It overrides _pp_forward_backward_microbatch_group to keep passing the shared loss_kwargs to its runtime, and its existing rejection of per-microbatch loss arguments now also covers its PP path.
  • RL trainer:
    • Lifts the PP restriction. Context parallelism still raises, because per-token loss arguments are not sharded along the sequence yet.
    • The batcher returns TrainerStepBatch.microbatch_groups ([num_groups][num_pp_microbatches][dp_degree]), so each group runs as one pipeline step. The controller sends each DP rank its grouped column; the Monarch actor system now slices the trainer ranks as (pp, dp, cp, tp) so a DP rank's slice spans every pipeline stage.
    • Ranks without the last stage return no metrics, and the controller takes the result from a rank that has it. V-style schedules (ZBV, DualPipeV) put the last stage on the first PP rank, so this does not assume a fixed rank.
    • RDMA microbatch transfer (async_loop.batcher.rdma_min_tensor_bytes, off by default) keeps the group structure, but is rejected together with PP for now: its prefetcher reads one microbatch per group.
    • Every stage publishes its partial state dict into the single model_state_dict key, so generators do not depend on the trainer PP layout.
  • CI: new 8-GPU integration test rl_grpo_pp2_interleaved1f1b_fsdp2_gen_tp2: Qwen3-0.6B, trainer PP=2 with Interleaved1F1B (two stages per rank) x FSDP=2, two TP=2 generators, untied embeddings.

Test plan

  • tests/unit_tests/cpu/test_trainer.py, tests/unit_tests/cpu/test_pipeline_parallel.py, and GraphTrainer's test_trace_module.py and test_graph_pp_runner.py pass on the 2026-10-07 CPU nightly with [pipelining] Add loss_kwarg_mbs for per-microbatch loss keyword arguments pytorch#200238 applied. One GraphPP test fails because the optional dist_moe package is not installed, which is unrelated.
  • RL CPU unit tests pass locally with vLLM stubbed out (no real vLLM on that host); the per-file failure set matches main. The tests that spawn Monarch processes (test_batcher_actor.py, the multi-rank RDMA test) time out on that host on main too, so CI covers them.
  • Not yet run on this version: the 8-GPU integration test. It needs vLLM plus the PyTorch change; CI covers it once #200238 is in the nightly.
  • An earlier version of this PR, which used an RL-side workaround instead of the PyTorch change, ran an 8-step deterministic batch-invariant run where PP=2 x FSDP=2 matched no-PP FSDP=2 bit for bit on loss, entropy, and reward, with logprob_diff/max = 0. grad_norm differed by 1 ULP at one step. This needs re-running on this version.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 24, 2026
@wwwjn wwwjn changed the title [RL] Support pipeline and context parallelism in trainer [WIP][rl] Support pipeline and context parallelism in trainer Jul 24, 2026
@wwwjn
wwwjn marked this pull request as draft July 24, 2026 18:36
@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch from e080230 to b4b3844 Compare October 2, 2026 02:34
@wwwjn wwwjn changed the title [WIP][rl] Support pipeline and context parallelism in trainer [WIP][rl] Support pipeline in trainer Oct 2, 2026
@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch from b4b3844 to 9dbf874 Compare October 5, 2026 22:24
@wwwjn wwwjn changed the title [WIP][rl] Support pipeline in trainer [rl] Support pipeline in trainer Oct 6, 2026
@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch 2 times, most recently from 264d271 to 1887031 Compare October 6, 2026 23:23
@tianyu-l tianyu-l closed this Oct 7, 2026
@wwwjn wwwjn reopened this Oct 8, 2026
@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch from 1887031 to 4002e49 Compare October 8, 2026 03:26
@wwwjn wwwjn changed the title [rl] Support pipeline in trainer [rl] Support pipeline parallelism in trainer Oct 8, 2026
@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch from 4002e49 to 8799f51 Compare October 8, 2026 04:44
@wwwjn
wwwjn marked this pull request as ready for review October 9, 2026 21:03
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 9, 2026
Comment thread torchtitan_recipes/tests/rl.py Outdated
# Tied embeddings cannot be split across pipeline stages.
config.model.enable_weight_tying = False # pyrefly: ignore[missing-attribute]
config.num_generators = 2
config.trainer.parallelism.pipeline_parallel_degree = 2

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.

could you test interleaved 1f1b schedule instead, which is more "non-trivial'

Comment thread torchtitan/rl/components/batcher.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/rl/trainer.py Outdated
# metrics so every stage returns the same values.
pp_degree = self.pp_mesh.size()
gathered_metrics: list[dict[str, float] | None] = [None] * pp_degree
torch.distributed.all_gather_object(

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 we should avoid using all_gather_object? @fegin

why do we need to have the same metrics on every PP rank anyway?

Comment thread torchtitan/rl/trainer/trainer.py Resolved
Comment thread torchtitan/rl/trainer.py Outdated
Comment on lines +246 to +250
[
rank_batches[self.dp_rank]
for rank_batches in training_data[start : start + group_size]
]
for start in range(0, len(training_data), group_size)

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 feel this logic belongs to batcher, as it's already getting PP info

Comment thread torchtitan/training_engine.py Outdated
Comment on lines +63 to +65
loss_metrics: list[dict[str, torch.Tensor]]
"""Loss metrics, one dict per microbatch. Under PP, they are empty on ranks
without the last stage."""

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.

we have microbatch_groups: list[list[TrainingMicrobatch]], so feels to me that this should match the nested list structure

pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Oct 15, 2026
…ents (#200238)

`step()` forwards the same `loss_kwargs` to the loss of every microbatch, so a loss cannot take inputs that differ per microbatch beyond the target. TorchTitan's RL trainer needs this under PP: its loss takes per-token advantages, generator logprobs, a loss mask, and temperature for each microbatch. Today it works around this by packing those tensors into the target (pytorch/torchtitan#3980).

This PR adds `loss_kwarg_mbs` to `step()`: one dict of loss keyword arguments per microbatch, mirroring `kwarg_mbs` for model inputs.

```python
schedule.step(
    arg_mbs=arg_mbs,
    target_mbs=target_mbs,
    loss_kwargs={"global_token_count": n},  # same for every microbatch
    loss_kwarg_mbs=[                        # one dict per microbatch
        {"advantages": advantages_mbs[i], "loss_mask": loss_mask_mbs[i]}
        for i in range(n_microbatches)
    ],
    losses=losses,
)
# Microbatch i computes:
#   loss_fn(output, target_mbs[i], **loss_kwargs, **loss_kwarg_mbs[i])
```

- `loss_kwargs` is passed unchanged to every microbatch; unlike `kwargs`, it is not split.
- `loss_kwarg_mbs` is a pre-split input, validated like the others: it must be a list of `n_microbatches` dicts, and it cannot be combined with whole-batch inputs or `target`, so per-token loss tensors and targets are always split by the caller in the same way.
- A key in both `loss_kwargs` and `loss_kwarg_mbs[i]` raises Python's usual "multiple values for keyword argument" `TypeError`.
- `loss_fn` still returns only the loss. Backward metadata inference uses the first microbatch's entry, as it already does for the target. The docs note that this extra `loss_fn` call means the loss must not accumulate into objects passed in `loss_kwarg_mbs`, such as a metrics dict.

The pipelining docs (`docs/source/distributed.pipelining.md`) now describe `loss_kwargs` and `loss_kwarg_mbs` next to the existing pre-split example.

Test plan:
- `test_schedule_with_loss_kwarg_mbs` covers Schedule1F1B, ScheduleGPipe, ScheduleInterleaved1F1B, ScheduleInterleavedZeroBubble, and ScheduleLoopedBFS. Each uses a shared `loss_kwargs` value plus a per-microbatch weight and metrics dict, and checks losses, metrics, and gradients against a reference.
- `test_schedule_pre_split_validation` adds the type, length, and whole-batch `target` error cases; `test_schedule_with_loss_kwarg_mbs` also checks the duplicate-key `TypeError`.
- Without this change, all 6 tests fail; with it, `pytest test/distributed/pipelining/` gives 210 passed and 112 skipped (GPU-only) on a CPU build.

Pull Request resolved: #200238
Approved by: https://github.com/sanketpurandare, https://github.com/tianyu-l
Comment thread torchtitan/training_engine.py Outdated
return torch.sum(torch.stack(detached_losses)).to(self.device), loss_metrics
return self._pp_loss_sentinel_on_non_last_stage, loss_metrics

def _pp_schedule_loss_kwargs(

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.

make this nested function? doesn't feel to me that's worth a separate private method

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.

not addressed, I feel we just need an inline variable, not even a function.

@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.

need to rebase, I'll need to take another look

@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch from 4aa78ec to 0781b1a Compare October 17, 2026 01:49

@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.

one comment

Comment thread torchtitan/training_engine.py Outdated
return torch.sum(torch.stack(detached_losses)).to(self.device), loss_metrics
return self._pp_loss_sentinel_on_non_last_stage, loss_metrics

def _pp_schedule_loss_kwargs(

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.

not addressed, I feel we just need an inline variable, not even a function.

wwwjn added 2 commits October 18, 2026 23:27
Depends on pytorch/pytorch#200238, which adds per-microbatch loss keyword
arguments (`loss_kwarg_mbs`) to pipeline schedules.

- Engine: under PP, copy `global_loss_token_counts` into each microbatch's
  loss arguments and pass one per-microbatch `loss_kwargs` list to
  `_pp_forward_backward_microbatch_group`, which returns the group loss and
  one loss metrics dict per microbatch. The schedule's scalar loss wrapper
  fills a per-microbatch `loss_metrics` dict and replaces it on each call,
  since the schedule also calls the loss on the first microbatch while
  inferring stage metadata. A `_pp_schedule_loss_kwargs` hook maps the
  per-microbatch arguments to the schedule's `step` arguments; GraphTrainer
  overrides it to keep passing the shared `loss_kwargs` its traced loss takes,
  and its rejection of per-microbatch loss arguments now covers its PP path.
- `ForwardBackwardResult.loss_metrics` is nested like `microbatch_groups`:
  one list per group, one dict per microbatch.
- Batcher: return `TrainerStepBatch.microbatch_groups`
  ([num_groups][num_pp_microbatches][dp_degree]); RDMA microbatches keep the
  group structure and number rows in training order.
- Controller: slice trainer ranks per DP rank as (pp, dp, cp, tp), send each
  DP rank its grouped column, and take the metrics from the first rank that
  returns them; reject RDMA microbatch transfer with PP for now.
- RL trainer: lift the PP restriction (context parallelism still raises),
  return no metrics on ranks without the last stage, and stage the merged
  state dicts of all local model parts so every stage publishes into the
  single "model_state_dict" TorchStore key.
- Add CPU unit tests and an 8-GPU PP=2 (Interleaved1F1B) x FSDP=2
  integration test.
Drop the _pp_schedule_loss_kwargs hook: _pp_forward_backward_microbatch_group
builds loss_kwarg_mbs inline. GraphTrainer, whose traced loss takes one
shared set of loss arguments, overrides _pp_forward_backward_microbatch_group
to pass them as loss_kwargs and reports no loss metrics.
@wwwjn
wwwjn force-pushed the rl-trainer-pp-cp-ci branch from 3d5f845 to 88f5003 Compare October 19, 2026 06:28
@wwwjn
wwwjn merged commit a4a62b3 into main Oct 19, 2026
wwwjn added a commit to wwwjn/torchtitan that referenced this pull request Oct 19, 2026
pytorch#3980 made PP preprocessing return (arg_mbs, kwarg_mbs, target_mbs,
loss_kwarg_mbs), but two callers still unpacked three values:

- TrainingEngine's prepare_for_capture (PP + CUDA graphs, from pytorch#5241)
  raised "too many values to unpack" in every PP integration test. It now
  passes the first microbatch's loss arguments to schedule initialization,
  which calls the loss on that microbatch, as the real step does.
- GraphTrainer PP reuses the core preprocessing, so its forward-backward
  loop failed the same way. Per-microbatch loss arguments are rejected
  there, so the PP branch drops the empty fourth element.

The CPU test for prepare_for_capture still fed the old 3-tuple, which hid
the mismatch; it now uses the PP layout and checks the loss arguments.
wwwjn added a commit that referenced this pull request Oct 19, 2026
…x per layer (#5547)

**TLDR:** Two CI fixes for the GraphTrainer and 8 GPU Integration jobs.
1. Fixes #5366. The Flex eager-vs-trace bitwise tests compiled flex once
per layer in the eager reference, and after 8 graphs Dynamo silently ran
unfused eager flex. The traced side was correct; the eager reference
changed. With this PR the eager reference compiles flex once, like the
core and RL trainers, and hitting the recompile limit raises instead of
falling back.
2. Fixes PP after #3980. #3980 made PP preprocessing return 4 values,
but two callers still unpacked 3, so every PP + CUDA graph integration
test and the GraphTrainer PP numerics test fail on main with
`ValueError: too many values to unpack (expected 3)`.

## 1. Flex bitwise tests compiled flex per layer (#5366)

**Problem**
1. **The eager reference was annotated.** `_run_steps` called
`annotate_graph_trainer_model` for both `Trainer` and `GraphTrainer`. It
wraps every submodule's forward with `annotate_fn({"module_fqn": fqn})`.
Only GraphTrainer's graph passes read these tags. The core and RL
trainers never set them.
2. **Dynamo now guards on the annotation.** pytorch/pytorch#198959
(October 10 nightly, the first failing one) adds an `FX_ANNOTATION`
guard. Each layer's `inner_attention` has a different `module_fqn`, so
the eager compiled flex compiles once per layer: 8 graphs for Qwen3
debugmodel_moe, all identical.
3. **The graphs carry over between tests.** Dynamo caches them on
`flex_attention`'s code object, which outlives the `torch.compile`
wrapper rebuilt in `setUp`. Llama3 Flex leaves 6. Qwen3 MoE Flex then
passes the limit of 8 at its third layer.
4. **Silent fallback.** Past the limit, Dynamo runs flex eagerly, which
is the unfused implementation, so the eager loss changes: `hit
config.recompile_limit (8)`, then `eager vs aot_fx_trace: loss
mismatch`.

**Solution**
1. **Annotate only GraphTrainer runs.** The eager reference stays
unannotated, like the core and RL trainers.
2. **`fullgraph=True` and `recompile_limit=16`** on the test's flex
compile, the same settings as #5442. Hitting the limit raises instead of
falling back.
3. **`torch._dynamo.reset()` in `setUp`.** Tests no longer share flex
graphs.
4. **Unchanged:** the GraphTrainer runs, their annotations, and every
assertion.

## 2. PP callers still unpacked 3 values after #3980

**Problem**
1. #3980 made `TrainingEngine._preprocess_microbatch_group` return
`(arg_mbs, kwarg_mbs, target_mbs, loss_kwarg_mbs)` under PP.
2. `prepare_for_capture` (PP + CUDA graphs, added by #5241 before #3980
landed) still unpacked 3 values. Every PP test in the 8 GPU features job
fails there: 3d, pp_1f1b, pp_dp_tp, pp_looped_zero_bubble, lora, and
others. On main, that job passes at #3980's parent `efdde5eda` and fails
at #3980 `a4a62b349`.
3. GraphTrainer PP reuses the core preprocessing, and its
forward-backward loop also unpacked 3 values, so
`test_dense_llama3_hsdp_graph_pp_vs_eager` fails. The GraphTrainer job
uses `set -eux`, so it stops there and never reaches
`test_bitwise_deterministic.py`.
4. The CPU test for `prepare_for_capture` still fed the old 3-tuple,
which hid the mismatch.

**Solution**
1. **`prepare_for_capture`** unpacks 4 values and passes the first
microbatch's loss arguments plus `global_loss_token_counts` to schedule
initialization. Initialization calls the loss on that microbatch, as the
real step does.
2. **GraphTrainer PP** drops the fourth element. GraphTrainer rejects
per-microbatch loss arguments earlier, so it is always empty, and both
paths now return `(arg_mbs, kwarg_mbs, target_mbs)`, as before #3980.
3. **The CPU test** feeds the PP layout with a per-microbatch loss
argument and checks the loss arguments passed to initialization. It
fails without the fix with the same `ValueError`.

## Results
```text
torch 2.16.0.dev20261019+cu132, GB200 (2 GPUs), flash-attn-4

1. Llama3 Flex -> Qwen3 MoE Flex test_aot_fx_trace_vs_eager, in one process
main:     "hit config.recompile_limit (8)", then
          eager vs aot_fx_trace: loss mismatch: 6.995096683502197 vs 6.995151519775391
this PR:  pass, 1 flex graph per test, eager == traced == 6.995151519775391

flex graphs after the Qwen3 MoE Flex eager run (test run alone)
annotated eager (main):  8 (one per layer)
unannotated eager:       1, same loss

Full test_bitwise_deterministic.py
main:     recompile limit hit once; on GB200 it breaks
          TestDSv3FlexAttnBitwiseDeterministic::test_aot_fx_trace_vs_eager and
          ::test_ep_chunk_matches_eager_chunking_bitwise
this PR:  16 passed (Varlen and Flex), 9 skipped, no recompile limit hit

2. PP
pp_1f1b integration test (2 GPUs, PP + CUDA graphs)
main:     ValueError in prepare_for_capture
this PR:  10 steps pass

GraphTrainer PP (the HSDP+PP numerics config reduced to PP=2, 2 GPUs)
main:     ValueError in GraphTrainer _forward_backward_body
this PR:  trains
```

You may ask: does the core trainer recompile flex per layer too? No.
Llama3 1B (16 layers) with flex on the core `Trainer` compiles flex once
and never recompiles. Only an annotated eager model recompiles per
layer.

NOTE: GraphTrainer's validator runs the annotated model eagerly, so Flex
validation on a model with more than 8 layers should hit the same
per-layer recompiles. Not covered here.
NOTE: `test_dense_llama3_hsdp_graph_pp_vs_eager` needs 8 GPUs, so I
could not run it locally. On the PP=2 reduction, eager PP vs GraphPP
misses its grad_norm tolerance (max 1.7e-4) both with this PR and at
#3980's parent, so that gap comes from the reduced config, not this PR.
The full 8 GPU test passed on main before #3980.

**Test plan**
- `pytest
torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py`:
16 passed, 9 skipped.
- The Llama3 Flex -> Qwen3 MoE Flex pair from #5366 passes in one
process.
- `python -m tests.integration_tests.run_tests <out> --test_suite
features --test_name pp_1f1b --ngpu 2`: passes; fails on main.
- `pytest tests/unit_tests/cpu/test_trainer.py
tests/unit_tests/cpu/distributed/test_cuda_graph.py
tests/unit_tests/cpu/components/test_validator.py
tests/unit_tests/cpu/distributed/test_pipeline_parallel.py`: 135 passed.
- CI: GraphTrainer 8 GPU and 8 GPU Integration (features) jobs.
wwwjn added a commit that referenced this pull request Oct 20, 2026
## Summary

Context parallelism (CP) in the RL trainer.

Under CP, `preprocess_inputs` shards the labels along the packed token
dimension, but the per-token loss arguments that the RL losses consume
(advantages, generator logprobs, loss mask, temperature) reached the
loss unsharded. CP > 1 therefore could not train.

- `shard_per_token_tensors` (in
`torchtitan/distributed/context_parallel.py`) keeps a CP rank's
contiguous token shard of each per-token tensor. This is the same layout
`shard_tensors` produces without a load-balancing permutation.
- `TrainingEngine` shards the loss arguments with it when CP is enabled.
It raises if a CP load balancer is configured, because the permutation
would reorder the labels but not the loss arguments. Ulysses CP, the CP
mode for varlen attention, already requires
`context_parallel_load_balancer=None`.

## Why the losses need no change

The GRPO and DAPO losses are masked per-token sums divided by a global
loss-token count. Each CP rank sums over its own tokens. FSDP shards on
`(dp_shard, cp)` with gradient division disabled, so summing gradients
over CP reproduces the full-sequence gradient. Loss metrics are summed
over the existing `dp x cp` loss mesh.

## Using it

A recipe sets `context_parallel_degree` on the trainer and converts the
trainer's attention to a CP kernel. Generators keep plain attention. The
new CI config shows the pattern:

```python
config.trainer.parallelism.context_parallel_degree = 2
config.trainer = apply_transforms(
    config.trainer,
    [ContextParallelTransform(
        inner_attention_map={VarlenInnerAttention: UlyssesCPVarlenInnerAttention})],
)
```

## Tests

- **New CPU tests**
(`tests/unit_tests/cpu/distributed/test_context_parallel_per_token.py`,
7 tests), all passing. They check:
  - shards match the CP token ranges and reassemble the full tensors;
  - masked sums over shards equal the unsharded sum;
  - non-tensor values pass through;
- mismatched or indivisible token counts and a configured load balancer
are rejected;
  - the engine shards with its CP mesh coordinates.
- **Existing CPU suites:** distributed, RL trainer, losses, batcher and
trainer loop pass (189). Two FSDP mixed-precision tests fail with and
without this change: the local torch build predates
`MixedPrecisionPolicy(param_dtype_override_fn=...)`.
- **New 8-GPU integration test** `rl_grpo_cp2_fsdp2_gen_tp2`:
Qwen3-0.6B, trainer FSDP=2 x Ulysses varlen CP=2, two generators at
TP=2. The config builds with Ulysses varlen attention in all 28 trainer
layers and plain varlen attention in the generators.
- **GPU numerics, CP=2 vs no CP.** One RL GRPO forward/backward plus
optimizer step on Qwen3-0.6B (random init), on 4 GB300 GPUs with a
2026-10-12 nightly. Both layouts use the same rank-local initial weights
and two fixed 4,096-token microbatches: packed documents, padding, and
per-token advantages, logprobs and masks. Deterministic mode is on.

| Metric | FSDP=2 x TP=2 | Repeat, relative diff | CP=2 x TP=2, relative
diff |
  |---|---|---|---|
  | loss | 0.3046408296 | 0 | 2.0e-7 |
  | grad norm | 2.045546532 | 0 | 2.1e-4 |
  | entropy | 11.72645378 | 0 | 8.1e-8 |
  | ratio clipped fraction, ratio mean, logprob diff | | 0 | 0 |

The no-CP repeat is bitwise identical. The CP differences are bf16
reduction-order noise; per-token loss arguments misaligned with the
labels would move the loss by O(1). Peak active memory per GPU: 4.47 GiB
without CP, 3.92 GiB with CP.

- **GPU end to end.** The integration config's CP path on one 4-GPU host
(trainer FSDP=1 x Ulysses varlen CP=2, one generator at TP=2), and the
same with FSDP=2 and no CP. Both run all 5 steps and exit cleanly.

| Step | CP=2 loss | CP=2 reward | CP=2 grad norm | No-CP loss | No-CP
reward | No-CP grad norm |
  |---|---|---|---|---|---|---|
  | 1 | -0.0039 | 0.67 | 2.41 | 2.4e-6 | 0.50 | 0.065 |
  | 2 | 0.00028 | 0.22 | 2.20 | -0.00012 | 0.29 | 0.22 |
  | 3 | 0.0017 | 0.27 | 1.32 | -0.0033 | 0.34 | 0.79 |
  | 4 | -0.0020 | 0.20 | 0.27 | -0.0028 | 0.17 | 0.39 |
  | 5 | -0.0010 | 0.36 | 1.06 | 0.0036 | 0.37 | 0.77 |

The two runs sample different rollouts, so their rows are not expected
to match. At this 1,024-token context, CP=2 trains about half as many
tokens per second as FSDP=2 on the same two GPUs. Both runs set
`VLLM_ALLREDUCE_USE_FLASHINFER=0` for the generator, because
FlashInfer's all-reduce JIT build failed in that environment.

## Relation to #3980

#3980 (pipeline parallelism in the RL trainer) adds a guard that rejects
CP until per-token loss arguments are sharded. This PR does that
sharding on the non-PP path. Whichever lands second should drop that
guard for the non-PP case. CP combined with PP still needs the sharded
loss arguments packed into the PP targets, which is out of scope here.
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.

2 participants