Skip to content

[rl] Compile all of DAPOLoss.__call__ in the loss region - #5923

Merged
felipemello1 merged 3 commits into
mainfrom
felipemello1/rl-loss/2-dapo-loss-region
Nov 9, 2026
Merged

felipemello1 merged 3 commits into
mainfrom
felipemello1/rl-loss/2-dapo-loss-region

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: One decorator puts all of DAPOLoss.__call__ in the loss region. Before, only compute_logprobs was compiled, and the clip, surrogate and 7 metrics after it ran as ~80 small eager kernels per chunk. Qwen3-4B output stage, 10240 tokens, at the recipe's TP=2 without CUDA graphs: 22.2 -> 17.1 ms per microbatch (-23%).

main:     compute_logprobs (compiled) -> mask, ratio, clip, surrogate, normalize, 7 metrics (eager, + backward)
this PR:  DAPOLoss.__call__ (one compiled graph; compute_logprobs is inlined)
          kernels per output stage (8 chunks, fwd+bwd): 822 -> 158

Problem

  1. Only compute_logprobs is in the loss region.
  2. The rest of DAPOLoss.__call__ is [T] work: one tiny kernel per op, forward and backward, in each of the 8 chunks.
  3. Cost: ~6 ms of the 23 ms TP=2 output stage.

Solution

  1. @local_compile("loss", batch_invariant=False) on DAPOLoss.__call__. GRPOLoss inherits it.
  2. loss now turns on 5 functions: cross_entropy_loss, cross_entropy_and_logsumexp, mse_loss, compute_logprobs and DAPOLoss.__call__. DAPO's graph inlines compute_logprobs, so the DAPO loss compiles one graph, not two.
  3. Unchanged: batch-invariant mode can't enable the loss region, so it runs main's eager code.

Results

Numerics: not bitwise vs eager (Inductor fuses the [T] sums in another order). 8 DAPO/GRPO clip settings in one
process, the trainer's inputs (1-D int64 token count, NaN generator logprobs), GB300: all match eager; loss and
7 metrics max abs diff 9.5e-7, logits grad rel L2 <= 2.9e-7.

Qwen3-4B output stage: final norm + fp32 LM head + DAPO loss, 8 chunks, fwd+bwd, GB300, ms.
Same inputs as the trainer: DAPO-Math's packed loss mask (86% loss tokens), 1-D int64 count, NaN logprobs.
                                           base (#5921)   free function for the tail   this PR
TP=2, no CUDA graphs (the recipe's)
  fastest of 15 iterations, slowest rank   22.2           17.5                         17.1     -23%
  median                                   23.1           17.6                         17.2     -26%
TP=1, CUDA graphs (GPU time only)          30.7           29.6                         29.5     -3.9%
kernels / compiled graphs                  822 / 2        166 / 3                      158 / 2
Peak memory: equal. All arms in one exclusive lock; base ran first and last, and the table shows the last run
(the first was noisy: median 34.0, fastest 23.4).

End to end: the trainer spends 0.87 s of forward/backward per 10240-token microbatch (Qwen3-4B DAPO, 2 GB300, TP=2). GPU time saved: 1.2 ms (0.14%). Without CUDA graphs: 5-6 ms (0.6-0.7%), mostly CPU launch time, which the trainer hides if its CPU runs ahead of the GPU.

You may ask:

  • Why not a free function for the code after compute_logprobs? Measured (table): it ties at TP=1 and is 0.4 ms slower at TP=2. It also moves ~60 lines.
  • Several clip settings in one process? New clip pairs add graphs until the clip floats turn dynamic, and GRPOLoss adds one: 4 graphs for 8 instances, all correct on today's torch. A run builds one loss: 1 graph.

NOTE:

  • Overlap: the open draft #5474 rewrites DAPOLoss.__call__ and adds DPPOLoss. The decorator moves with __call__, and each loss with its own __call__ needs one decorator line.
  • Not run: a full RL run.

Test plan

  • No new test. CI's RL Integration Tests already run the compiled loss region on GPU: rl_grpo_fsdp2_gen_tp2_compile trains GRPO with Qwen3's default regions, which include loss.
  • Numerics vs eager: the GPU probe in Results.
  • pytest tests/rl/unit_tests/cpu/test_losses.py: 2 passed.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 7, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 10s —— View job


Approve -- please address the items below before merging. Review

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

Verdict: Approve -- please address the items below before merging. A one-line decorator takes the DAPO/GRPO tail out of eager mode. It is measured (-23% on the TP=2 output stage) and limited to the RL loss.

What this PR does. Puts @local_compile("loss", batch_invariant=False) on DAPOLoss.__call__, which GRPOLoss inherits. Before, only compute_logprobs was compiled. Now the whole loss is one graph, and Dynamo inlines compute_logprobs into it. Batch-invariant runs are unchanged: the loss region already raises there, and the alphabet_sort recipes set regions = []. So the rl_grpo_cuda.txt golden, which comes from a batch-invariant config, is unaffected.

Example. One chunk of a [T=1280, V] output stage, with regions=["loss"]:

before: compute_logprobs (Inductor) -> isfinite, where, clamp, exp, clamp, min, mul, sum, 7 metric sums  (~80 eager kernels fwd+bwd)
after:  DAPOLoss.__call__ (one Inductor graph, fwd+bwd)                                                  (~20 kernels)
numerics: not bitwise vs eager (reduction order); loss/metrics within 1e-6

Must fix

  1. PR description: "Summary (human-written)" is empty. The author needs to write it; agents leave it blank.
  2. tests/rl/unit_tests/cpu/test_losses.py:99-100 -- the decorator-presence check imports a private Dynamo helper (_debug_get_cache_entry_list) and reaches into decorator internals. Drop it, along with the import on line 9 (see inline comment).

Should consider

  • tests/rl/unit_tests/cpu/test_losses.py:81-83 -- four clip pairs mostly test Dynamo's automatic-dynamic floats, and each pair adds a CPU Inductor compile. One asymmetric pair covers what the trainer runs (see inline comment).
Details
  • Gate: the problem is real and measured (822 -> 158 kernels; 5-6 ms per microbatch without CUDA graphs). Two lines of logic; the decorator is the right layer, and methods are already decorated this way (kimi_k3/model.py:72, muse_spark/model.py). It doesn't touch core or shared code.
  • Region registration: apply() runs at model build (models/base/model.py:167). Recipes import DAPOLoss to build their config before the model is built, so the new callback is registered in time.
  • Recompiles: a run builds one loss. global_loss_token_counts being None, 0-D, or 1-D is a static branch in _normalize, and grad mode is a guard. Each of these adds at most one graph per kind of call site.
  • No new host syncs: max() and the sums stay on device.
  • Overlap with draft #5474 is noted in the description: each loss __call__ needs its own decorator line.

Not verified: fullgraph tracing of spmd_mesh_group("tp") (threading.local) inside the region and behavior under config.debug.spmd_typechecking=True. The author's TP=2 numbers cover the first, and RL GPU integration CI will exercise both. I couldn't run the new CPU test here. This touches RL trainer code, so a maintainer still needs to review.

Comment thread tests/rl/unit_tests/cpu/test_losses.py Outdated
Comment on lines +99 to +100
# The region compiled DAPOLoss.__call__ itself, not only compute_logprobs inside it.
assert _debug_get_cache_entry_list(DAPOLoss.__call__.__wrapped__.__code__)

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 check imports a private Dynamo helper (torch._dynamo.eval_frame._debug_get_cache_entry_list, line 9) and reaches into the decorator's internals through __wrapped__.__code__. CLAUDE.md says not to import another module's _private names. It also only confirms the decorator line is there. If someone removes the decorator, we lose some speed, but numerics stay the same, so nothing goes wrong silently. The invariant that actually needs guarding is "compiled __call__ matches eager", and the assert_close above already covers it. I'd delete these two lines and the import on line 9.

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.

Reply from claude: Done in 600d065. The cache-entry check and the private import are gone; the test now guards only that the compiled loss matches eager.

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.

Reply from claude: Follow-up in 99a58ba. A reviewer asked to keep a check that fails if the decorator is removed. It now uses public APIs only, which addresses the private-import point: the test records what torch.compile receives (as test_loss_functions_use_local_compile does) and asserts DAPOLoss.__call__ is among them. It fails with the decorator deleted. The fixture uses torch.compiler.reset().

Comment thread tests/rl/unit_tests/cpu/test_losses.py Outdated
Comment on lines +81 to +83
# Four clip pairs: from the third on, both bounds are dynamic floats in one reused graph,
# and each pair must still match eager.
for low, high in [(0.2, 0.2), (0.2, 0.28), (0.1, 0.4), (0.05, 0.5)]:

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.

With four clip pairs, the test mostly checks Dynamo's automatic-dynamic float behavior ("from the third on, both bounds are dynamic floats"). That is a torch internal, and this comment goes stale when it changes. A real run builds one loss and gets one graph (see the PR description), so the multi-pair path isn't what training runs. Each extra pair also costs another CPU Inductor fwd+bwd compile in the CPU RL suite. One asymmetric pair covers what the trainer runs: both bounds active, the NaN drop, and the 1-D int64 count.

Suggested change
# Four clip pairs: from the third on, both bounds are dynamic floats in one reused graph,
# and each pair must still match eager.
for low, high in [(0.2, 0.2), (0.2, 0.28), (0.1, 0.4), (0.05, 0.5)]:
# Asymmetric clip-higher bounds, so both clamp ends change the loss.
for low, high in [(0.2, 0.28)]:

(Or remove the loop altogether.)

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.

Reply from claude: Done in 600d065. One pair, (0.2, 0.28), and no loop. It keeps the NaN generator logprob and the 1-D int64 count.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 50s —— View job


Approve -- please address the item below before merging (only remaining item: the human-written summary is empty). Review

self.ratio_clip_high = config.ratio_clip_high
self.global_vocab_size = config.global_vocab_size

@local_compile("loss", batch_invariant=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 think we have multiple regions named loss. Is that ok? also, why only here and not grpo as well? Does this work fine with all the metrics?

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.

Reply from claude:

  1. Several functions under one name is supported: "loss" already turns on 4 (cross_entropy_loss, cross_entropy_and_logsumexp, mse_loss, compute_logprobs). Each gets its own binder (local_compile.py:98), so its own torch.compile wrapper, cache and recompile budget. compute_logprobs, called inside the compiled __call__, is inlined into the same graph: 2 graphs per process (this loss + the bf16 split), 158 kernels.
  2. GRPO is covered: GRPOLoss(DAPOLoss) only defines Config and __init__, so it inherits the decorated __call__. A future loss with its own __call__ adds one decorator line.
  3. Metrics are in the same graph, under torch.no_grad(), returned as 0-d tensors with no .item(). Compiled vs eager on GPU: 8 of 8 clip settings match, max metric difference 9.5e-7, grad rel L2 <= 2.9e-7. The max and the "> 1e-6" counts are exactly equal; sums differ in the last bits. Batch-invariant mode can't enable the loss region, so it runs eager as before.

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

Verdict: Approve -- please address the item below before merging. 600d065 fixes both test findings from the last review. The code change is still the single decorator line that was approved before.

What changed since the last review. Only the test changed (600d065). The decorator on DAPOLoss.__call__ (torchtitan/rl/trainer/losses/dapo.py:74) is unchanged.

Example. The test at HEAD:

loss_fn = DAPOLoss(ratio_clip_low=0.2, ratio_clip_high=0.28)
regions=[]       -> eager loss, 7 metrics, logits.grad
regions=["loss"] -> compiled loss, 7 metrics, logits.grad
assert_close(compiled, eager)   # with a NaN generator logprob and a 1-D int64 count

Earlier items

  • Resolved: the private _debug_get_cache_entry_list import and the cache-entry check are gone (tests/rl/unit_tests/cpu/test_losses.py).
  • Resolved: the test now uses one asymmetric clip pair (0.2, 0.28) with no loop. It doesn't depend on Dynamo's automatic-dynamic floats, and it pays for one CPU Inductor compile.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave it blank.
Details
  • The new commit adds no new problems. The fixture (LocalCompileConfig().apply() + torch._dynamo.reset()) follows the same pattern as tests/unit_tests/cpu/models/deepseek_v3/test_deepseek_v3_mla_compile.py:16.
  • Nested regions: compute_logprobs (torchtitan/components/loss.py) has its own @local_compile("loss", ...). Dynamo inlines it into the outer DAPOLoss.__call__ graph, which is where the 822 -> 158 kernel drop in the description comes from.
  • Batch-invariant runs: unchanged (batch_invariant=False). The rl_grpo_cuda.txt golden is unaffected.

Not verified: spmd_mesh_group("tp") inside the fullgraph region with config.debug.spmd_typechecking=True. RL GPU CI will cover it. This touches RL trainer code, so a maintainer still needs to review.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 54s —— View job


Approve -- please address the item below before merging (the only remaining item: the human-written summary is still empty). Review

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

Verdict: Approve -- please address the item below before merging. 99a58ba brings back a check that the decorator is present, this time using public APIs only. That addresses the earlier objection to the private Dynamo import. The code change is still the single decorator line that was approved before.

What changed since the last review. Only tests/rl/unit_tests/cpu/test_losses.py. The test now monkeypatches torch.compile with a recorder that passes calls through to the real torch.compile, so the compiled-vs-eager comparison still runs through Inductor. It then asserts that "DAPOLoss.__call__" is among the recorded qualnames. The fixture now uses the public torch.compiler.reset().

Example.

LocalCompileConfig(regions=["loss"]).apply()
  -> bind_local_compile -> config._compile -> torch.compile (recorded) -> real torch.compile
compiled_names ⊇ {"compute_logprobs", "DAPOLoss.__call__", ...}
decorator deleted -> "DAPOLoss.__call__" missing -> test fails

Earlier items

  • Resolved: no private torch._dynamo imports remain. The presence check uses the same monkeypatch.setattr(torch, "compile", ...) pattern as tests/unit_tests/cpu/config/test_compile_config.py:128.
  • Resolved: one asymmetric clip pair (0.2, 0.28), one CPU Inductor compile.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave it blank.
Details
  • Recorder correctness: LocalCompileConfig._compile looks up torch.compile when it is called (torchtitan/distributed/local_compile.py:37), so the monkeypatch catches it. functools.wraps copies __qualname__, so DAPOLoss.__call__.__qualname__ == "DAPOLoss.__call__" matches the qualname of the reference passed to torch.compile. Always-compiled helpers (create_block_mask, flex_attention) are plain functions with __qualname__, so recording them doesn't raise.
  • Fixture teardown order: monkeypatch is requested after reset_local_compile, so it is undone first. The final LocalCompileConfig().apply() then runs against the real torch.compile.
  • Placement: the presence check stays in tests/rl/, not in the core test_compile_config.py, which keeps core tests from importing RL code. Fine as is.
  • Your questions on dapo.py:74 (several functions sharing the loss name, GRPO inheriting the decorator, metrics in the graph) are answered in the thread and match the code: GRPOLoss (torchtitan/rl/trainer/losses/grpo.py) defines no __call__, and each local_compile decoration registers its own binder.

Not verified: spmd_mesh_group("tp") inside the fullgraph region with config.debug.spmd_typechecking=True. RL GPU CI covers it. I didn't run the CPU test here. This touches RL trainer code, so a maintainer still needs to review.

Only compute_logprobs was compiled; the mask, ratio, clip, surrogate, normalize and 7
metrics after it ran as about 80 small eager kernels per chunk, forward and backward.
One decorator on DAPOLoss.__call__ puts the whole loss in one compiled graph
(compute_logprobs is inlined). GRPOLoss inherits it.

The test compiles the region on CPU and checks loss, metrics and logits grad against
eager, with clip-higher bounds, a NaN generator logprob and the trainer's 1-D int64
count. It records what torch.compile receives and fails if DAPOLoss.__call__ is missing.
@felipemello1
felipemello1 force-pushed the felipemello1/rl-loss/2-dapo-loss-region branch from 99a58ba to 49eb330 Compare November 7, 2026 06:08
@felipemello1
felipemello1 changed the base branch from felipemello1/rl-loss/1-temperature-in-loss-region to main November 7, 2026 06:08
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: #5921 merged, so this PR is now one commit (49eb330) on main with the same diff as before (decorator + test). @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 48s —— View job


Approve -- please address the item below before merging (the only remaining item: the human-written summary is still empty). Review

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

Verdict: Approve -- please address the item below before merging. The diff is the same as the 99a58ba version I approved last time. It is now one commit (49eb330) on top of main, which includes #5921, and the base change doesn't interact with it.

What this PR does. Adds @local_compile("loss", batch_invariant=False) to DAPOLoss.__call__ (torchtitan/rl/trainer/losses/dapo.py:74), so with regions=["loss"] the whole DAPO/GRPO loss compiles into one graph that inlines compute_logprobs. It also adds a CPU test checking that the compiled loss matches eager, and that DAPOLoss.__call__ reaches torch.compile.

Example.

regions=["loss"], one [T, V] chunk
before: compute_logprobs (compiled) -> clip, surrogate, normalize, 7 metrics (eager, ~80 kernels fwd+bwd)
after:  DAPOLoss.__call__ (one compiled graph)
regions=[] or batch-invariant: unchanged eager path

Earlier items

  • Resolved (still true at HEAD): no private torch._dynamo imports. The presence check records what goes through the public torch.compile, and the fixture calls torch.compiler.reset().
  • Resolved (still true at HEAD): one asymmetric clip pair (0.2, 0.28) and no loop.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave it blank.
Details
  • Rebase check: at HEAD, local_compile (torchtitan/distributed/local_compile.py:58) still registers one binder per decorated function under the loss name. bind_local_compile passes reference to config._compile -> torch.compile, so the test's monkeypatched recorder still sees DAPOLoss.__call__.
  • Batch-invariant RL recipes (torchtitan_recipes/rl/alphabet_sort.py) set regions = [], so the rl_grpo_cuda.txt golden is unaffected.
  • The vLLM generator imports torchtitan.components.loss only to register the loss region (torchtitan/rl/generator/vllm/model_wrapper.py:34), and it never builds a loss. Whether or not dapo.py is imported there, generator behavior doesn't change.

Not verified: spmd_mesh_group("tp") inside the fullgraph region with config.debug.spmd_typechecking=True (RL GPU CI covers it). I didn't run the CPU test. This touches RL trainer code, so a maintainer still needs to review.

@felipemello1
felipemello1 marked this pull request as ready for review November 8, 2026 04:41
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 8, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 8, 2026 04:42
scalar tensors pre-normalized for SUM reduction across DP ranks.
"""
# Score tokens under the distribution vLLM sampled from.
trainer_logprobs, token_entropy = compute_logprobs(

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 will cause nested local_compile https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/loss.py#L495

It's mentioned that

Dynamo inlines it into the outer DAPOLoss.call graph, which is where the 822 -> 158 kernel drop in the description comes from.

but I'd like @anijain2305 to advise.

Also, with this PR can we remove the compile on comput_logprobs? The other occurrence is https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/generator/vllm/batch_invariance.py#L56 which can be decorated separately?

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.

Reply from claude:

  1. Nested local_compile works. When Dynamo traces the compiled DAPOLoss.__call__ and reaches the compiled compute_logprobs, it inlines the original function into the outer graph and skips the inner wrapper (torch/_dynamo/eval_frame.py, _torchdynamo_inline: "hooks to properly handle inlining"). The table in the description shows it: 2 graphs with this PR, vs 3 when the code after compute_logprobs is a separate compiled function.
    One catch: inside the outer graph, the inner decorator's compile kwargs are ignored. Today both decorators are ("loss", batch_invariant=False) with no extra kwargs, so nothing is lost.
  2. We'd rather keep the decorator on compute_logprobs. It is a public op, and code that calls it on its own (outside a compiled loss) should still get the compiled version.
    The batch_invariance.py call needs no change. It runs only in batch-invariant mode, where enabling the loss region raises (local_compile.py), so it is eager either way.

@felipemello1
felipemello1 merged commit 2805bd6 into main Nov 9, 2026
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 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.

3 participants