Repository navigation
[rl] Compile all of DAPOLoss.__call__ in the loss region - #5923
Conversation
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 3m 10s —— View job Approve -- please address the items below before merging. Review |
There was a problem hiding this comment.
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
- PR description: "Summary (human-written)" is empty. The author needs to write it; agents leave it blank.
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 importDAPOLossto 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_countsbeingNone, 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.
| # The region compiled DAPOLoss.__call__ itself, not only compute_logprobs inside it. | ||
| assert _debug_get_cache_entry_list(DAPOLoss.__call__.__wrapped__.__code__) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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().
| # 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)]: |
There was a problem hiding this comment.
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.
| # 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.)
There was a problem hiding this comment.
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.
|
Reply from claude: @claude review |
|
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) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Reply from claude:
- 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 owntorch.compilewrapper, 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. - GRPO is covered:
GRPOLoss(DAPOLoss)only definesConfigand__init__, so it inherits the decorated__call__. A future loss with its own__call__adds one decorator line. - 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.
There was a problem hiding this comment.
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_listimport 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
- 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 astests/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 outerDAPOLoss.__call__graph, which is where the 822 -> 158 kernel drop in the description comes from. - Batch-invariant runs: unchanged (
batch_invariant=False). Therl_grpo_cuda.txtgolden 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.
|
Reply from claude: @claude review |
|
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 |
There was a problem hiding this comment.
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._dynamoimports remain. The presence check uses the samemonkeypatch.setattr(torch, "compile", ...)pattern astests/unit_tests/cpu/config/test_compile_config.py:128. - Resolved: one asymmetric clip pair (0.2, 0.28), one CPU Inductor compile.
Must fix
- PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave it blank.
Details
- Recorder correctness:
LocalCompileConfig._compilelooks uptorch.compilewhen it is called (torchtitan/distributed/local_compile.py:37), so the monkeypatch catches it.functools.wrapscopies__qualname__, soDAPOLoss.__call__.__qualname__ == "DAPOLoss.__call__"matches the qualname of the reference passed totorch.compile. Always-compiled helpers (create_block_mask,flex_attention) are plain functions with__qualname__, so recording them doesn't raise. - Fixture teardown order:
monkeypatchis requested afterreset_local_compile, so it is undone first. The finalLocalCompileConfig().apply()then runs against the realtorch.compile. - Placement: the presence check stays in
tests/rl/, not in the coretest_compile_config.py, which keeps core tests from importing RL code. Fine as is. - Your questions on
dapo.py:74(several functions sharing thelossname, 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 eachlocal_compiledecoration 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.
99a58ba to
49eb330
Compare
|
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 |
There was a problem hiding this comment.
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._dynamoimports. The presence check records what goes through the publictorch.compile, and the fixture callstorch.compiler.reset(). - Resolved (still true at HEAD): one asymmetric clip pair (0.2, 0.28) and no loop.
Must fix
- 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 thelossname.bind_local_compilepassesreferencetoconfig._compile->torch.compile, so the test's monkeypatched recorder still seesDAPOLoss.__call__. - Batch-invariant RL recipes (
torchtitan_recipes/rl/alphabet_sort.py) setregions = [], so therl_grpo_cuda.txtgolden is unaffected. - The vLLM generator imports
torchtitan.components.lossonly to register thelossregion (torchtitan/rl/generator/vllm/model_wrapper.py:34), and it never builds a loss. Whether or notdapo.pyis 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.
…s the loss region
| scalar tensors pre-normalized for SUM reduction across DP ranks. | ||
| """ | ||
| # Score tokens under the distribution vLLM sampled from. | ||
| trainer_logprobs, token_entropy = compute_logprobs( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Reply from claude:
- Nested
local_compileworks. When Dynamo traces the compiledDAPOLoss.__call__and reaches the compiledcompute_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 aftercompute_logprobsis 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. - 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.
Thebatch_invariance.pycall needs no change. It runs only in batch-invariant mode, where enabling thelossregion raises (local_compile.py), so it is eager either way.
Summary (human-written)
Agent details
TLDR: One decorator puts all of
DAPOLoss.__call__in thelossregion. Before, onlycompute_logprobswas 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%).Problem
compute_logprobsis in thelossregion.DAPOLoss.__call__is[T]work: one tiny kernel per op, forward and backward, in each of the 8 chunks.Solution
@local_compile("loss", batch_invariant=False)onDAPOLoss.__call__.GRPOLossinherits it.lossnow turns on 5 functions:cross_entropy_loss,cross_entropy_and_logsumexp,mse_loss,compute_logprobsandDAPOLoss.__call__. DAPO's graph inlinescompute_logprobs, so the DAPO loss compiles one graph, not two.lossregion, so it runs main's eager code.Results
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:
compute_logprobs? Measured (table): it ties at TP=1 and is 0.4 ms slower at TP=2. It also moves ~60 lines.GRPOLossadds one: 4 graphs for 8 instances, all correct on today's torch. A run builds one loss: 1 graph.NOTE:
#5474rewritesDAPOLoss.__call__and addsDPPOLoss. The decorator moves with__call__, and each loss with its own__call__needs one decorator line.Test plan
lossregion on GPU:rl_grpo_fsdp2_gen_tp2_compiletrains GRPO with Qwen3's default regions, which includeloss.pytest tests/rl/unit_tests/cpu/test_losses.py: 2 passed.