Skip to content

[rl] Update the RL loss guard golden for the new CUDA exponential_ transform - #5909

Merged
felipemello1 merged 2 commits into
pytorch:mainfrom
felipemello1:rl-loss-golden-torch-exponential
Nov 6, 2026
Merged

felipemello1 merged 2 commits into
pytorch:mainfrom
felipemello1:rl-loss-golden-torch-exponential

Conversation

@felipemello1

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Written with Claude Code.

TLDR: The RL loss guard fails on every run with the 2026-11-06 PyTorch nightly. The guard is a CI step on A10G: it runs 10 RL steps on Qwen3-0.6B and checks that each loss equals the saved value in tests/assets/losses/rl_grpo_cuda.txt (the golden). That nightly changes CUDA exponential_, which vLLM's sampler uses for its random noise, so the same seed now samples different tokens. This PR replaces the golden with the losses the guard now prints.

same seed, same raw random draw (u ~ 0.39904):
  nightly 11-05:  q = -log(u)      = 0.9187
  nightly 11-06:  q = -log(1 - u)  = 0.5092

Problem

  1. vLLM picks each token as argmax(probs / q), where q is float32 noise from q[i].exponential_(generator=g), one seeded generator per request. TorchTitan asks vLLM for processed logprobs, which its FlashInfer sampler cannot return, so vLLM always takes this PyTorch path.
  2. PyTorch main e946fc9997 ("Accurate exponential_ tails") changes CUDA exponential_ for float32, float16 and bfloat16 from -log(u) to -log(1 - u), on the same raw random bits. The distribution is the same. The value for a given seed is not.
  3. Different noise gives different tokens, then different rewards. The step-1 loss on A10G moves from -0.003584 to -0.003829, and loss_compare.py --assert-equal fails.

Solution

  1. Replace the golden with the "Actual losses" that the guard printed on A10G with the 11-06 nightly.
  2. This is the only golden from an RL run. The other files in tests/assets/losses/ come from pretraining runs, which do not sample.
  3. Stacked on the import fix: its commit b6b87b152 is the first commit here, so please review only the second. Without it, the guard crashes before step 1. No code changes.

Results

The exponential_ change is the whole cause. Putting the old formula back on the 11-06 nightly gives the 11-05 losses bit for bit:

loss guard config at e06b11eaa, 4 GB300 (trainer TP=2 + 1 generator TP=2), 10 steps
                                           step-1 loss               all 10 steps vs 11-05
  nightly 11-05                            -0.0026281552854925394    (baseline)
  nightly 11-06                            -0.00481081660836935      all differ
  nightly 11-05, old formula patched in    -0.0026281552854925394    bitwise equal
  nightly 11-06, old formula patched in    -0.0026281552854925394    bitwise equal
nightly = torch, torchvision and vLLM from that day; every other package identical.
patch: Tensor.exponential_ replaced by -log(torch.rand(...)); torch.rand is identical on both nightlies.
GPU and TP differ from CI (no A10G here), so these losses match neither golden. Only the A/B comparison matters.

This A/B ran FA4 (GB300). A10G runs FA2, which it does not cover. No torch commit between the two nightlies touches attention.

The CI history points to the same nightly:

RL Integration Tests (A10G), jobs started 11-05 12:06 to 11-06 19:39 UTC:
  nightly 11-02 or 11-05:  76 runs, all "All losses match"
  nightly 11-06:           24 runs reach the check; all print the same 10 losses (this golden)
                           22 more crash with the NameError that the import fix repairs
  same commit f782e30c1:   13:08 pass (11-05 nightly), 16:09 fail (11-06 nightly)
Installed packages, last pass vs first fail: only torch and vllm differ.
vLLM 11-05 and 11-06 nightlies: both built from vLLM commit 9f03b510c, each against its own torch.

You may ask:

  • Why not pin the torch nightly? The PyTorch change is an intended fix: the old kernel under-sampled tokens with probability below ~1e-7. Pinning only delays this update.
  • Why not draw the noise in float64 (vLLM's sampler option use_fp64_gumbel)? float64 noise also differs from the old float32 noise, so the golden changes anyway.
  • Is the new loss curve worse? A step-by-step comparison means nothing, because the rollouts are different samples. Both curves stay below |loss| = 4e-3.

NOTE: I copied the values from the CI log, because I have no A10G to run --export-result. The log prints each loss with repr(), so the copy is exact. Those runs used main up to e06b11eaa. On the 4 later main commits the guard crashed with the NameError or has not run yet, so CI on this PR is the first check on current main. I expect no loss change:

  • c50b0aeae (use attn-gym mla decode kernel): moves the FlashAttention pick into a helper; A10G still gets FA2. Its attn-gym bump (0.0.17 -> 0.0.18) rebuilds the CI image, so other image packages may differ too.
  • 6d9a92994 (MoE router scores before W2): MoE only. Qwen3-0.6B is dense.
  • b54ff76f3 (reject dtype changes to materialized buffers): adds an error check, no math change.
  • 80e28952b (fake backend for size-1 mesh axes): this config's size-1 dp_shard axis now gets the fake backend. One rank has nothing to send, so the math is unchanged.

Test plan

  • RL Integration Tests (A10G) on this PR (ciflow/rl).
  • The A/B above: the guard config with TP=2, launched with and without a sitecustomize.py on PYTHONPATH that sets torch.Tensor.exponential_ to fill -torch.rand(shape, generator=generator).log() / lambd. In the patched runs, the patched calls come from 2 processes (the generator's 2 ranks), with noise of shape (151936,): one vocabulary row per request, vLLM's per-request sampling path.

Felipe Mello added 2 commits November 6, 2026 11:30
…ention backend

The attn-gym MLA decode change removed get_cuda_flash_attention_impl from the
torchtitan.tools.utils import, but _FA4PageSize.get_supported_kernel_block_sizes
still calls it. Every vLLM generator then fails at engine init with
NameError: name 'get_cuda_flash_attention_impl' is not defined.
…ansform

The PyTorch nightly of 2026-11-06 changes CUDA exponential_ for float32,
float16 and bfloat16 from -log(u) to -log(1 - u) on the same Philox draw.
vLLM's sampler draws its noise with exponential_, so with the same seed the
generator samples different tokens and the loss guard's step losses change.
Putting the old formula back on the 11-06 nightly reproduces the 11-05 losses
bit for bit. The new values are the "Actual losses" printed by the A10G loss
guard on that nightly, identical across 24 CI runs.
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 6, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 6, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 57s —— View job


Approve (one must-fix item: fill in the human-written summary) -- 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 -- the golden refresh has a clear cause: the A/B shows that patching the old exponential_ formula back in brings back the 11-05 losses bit for bit. No code changes beyond the stacked import fix.

What this PR does. It replaces the 10 losses in tests/assets/losses/rl_grpo_cuda.txt, the A10G RL loss guard golden. The 11-06 PyTorch nightly changed CUDA exponential_ from -log(u) to -log(1-u). vLLM's per-request sampler uses that noise, so the same seed now samples different tokens and gives different rewards. The first commit (b6b87b1) is the same as #5908: it restores the missing get_cuda_flash_attention_impl import that attention.py:69 uses.

Example.

loss guard, A10G, seed 42, Qwen3-0.6B, 10 steps
  nightly 11-05: step-1 loss -0.0035842829383909702  (old golden) -> pass
  nightly 11-06: step-1 loss -0.003829071531072259   -> --assert-equal fails on main
  this PR:       golden = the 11-06 values             -> pass (expected, CI on this PR is the check)

Must fix

  1. PR description -- "Summary (human-written)" is empty. CONTRIBUTING.md says the author fills it in. Add one or two sentences.

Questions

  • .github/workflows/validate_release_gpu.yml (validate-rl) runs the same golden with --assert-equal against TORCH_VERSION="2.15.0". If 2.15.0 was cut before e946fc9997, that guard keeps the old -log(u) noise and can't match this golden. Only one torch version can match the golden at a time. Today this only matters if the 0.2.x release branch is revalidated from main's golden: assets/version.txt is 0.2.2, not an RC, so the workflow won't run on main. Is that expected, or should the release branch keep its own golden?
Details
  • Gate: the problem is real on main (every RL A10G run on the 11-06 nightly fails the guard). Root cause: an intended upstream change in PyTorch (e946fc9997). Refreshing the golden is the right fix. Pinning the nightly would only put off the same update, and use_fp64_gumbel would change the golden anyway, as the description says.
  • The golden values match the description (step 1 -0.003829...). They are repr() values, the same format as the old file.
  • The stacked commit is identical to #5908. Whichever PR merges first, the other one's attention.py hunk becomes a no-op on rebase.
  • The A/B ran 1 generator with TP=2 on GB300, while CI runs the recipe's 3 generators with TP=2 on A10G. That's fine for the attribution, since only the old-vs-new formula comparison matters.
  • .github/workflows/integration_test_8gpu_rl.yaml:87-88 says the guard overrides to TP=4 ("the golden is from TP=4"). The command passes no override, and the recipe uses TP=2. This comment was stale before this PR. It belongs in a separate cleanup, not here.

Not verified: whether torch 2.15.0 includes e946fc9997. Whether the guard passes on current main HEAD; this PR's ciflow/rl run is the first check.

@felipemello1
felipemello1 marked this pull request as ready for review November 6, 2026 20:02
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 6, 2026

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

seems from @drisspg pytorch/pytorch#202464 so I'm not worried

@felipemello1
felipemello1 merged commit 28ea4ba into pytorch:main Nov 6, 2026
shuhuayu added a commit that referenced this pull request Nov 10, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

this pr is to add `deterministic ` option to gdn backend (an existing
bug) so gdn has reproducible numerics.

## Why

Independent prerequisite based on `main`. Merge this before #5782; the
model stack is based on this branch.

`torch.use_deterministic_algorithms(True)` does not reach Attention
Gym's GDN L2 normalization policy. Its forward schedule is fixed, but
backward autotuning benchmarks different tile schedules. Two
strict-deterministic runs can therefore choose different backward
schedules and train differently.

**Example.** The eight-GB300 Flash-Next first-step diagnostic observes a
difference in `kda_l2norm_bwd` before the PLE output gradient or any
lookup-gradient exchange. Hash IDs and selected vectors are identical.
Disabling normalization autotuning under PyTorch's existing
deterministic flag pins the schedule.

```python
autotune = not torch.are_deterministic_algorithms_enabled()
normalized_q = l2norm(q, cu_seqlens=cu_seqlens, autotune=autotune)
```

## What changed

Pass that policy through all shared GDN normalization callsites:
ordinary chunk/recurrent forward, recurrent backward's chunk-gradient
recomputation, and CP GDN. Nondeterministic runs retain autotuning. No
model flag or alternate kernel is added.

## User-facing changes

| Before | After |
| --- | --- |
| Strict determinism still allows GDN backward normalization autotuning
| The existing PyTorch deterministic flag selects a fixed schedule. |

## Numerics and testing

- The CUDA regression checks that deterministic backward bypasses the L2
autotuner and produces finite, nonzero gradients in ordinary and
batch-invariant GDN modes. It does not assert how many times upstream
internals run in nondeterministic mode.
- The shared GDN computation in this PR is unchanged by the PLE storage
refactor. Both native DTensor and plain-owned-row qualification sources
include this same committed policy.
- Two-GB300 controlled A/B runs match first-step logits and 190 gradient
shards per rank, all twenty ten-step loss/norm values, and all 763 final
model/optimizer tensors bitwise. Full remat and checkpoint resume
preserve the result.
- The restacked TP2/SP/EP2 registered GB300 regression matches all
twenty unchanged golden values bitwise. Runtime: PyTorch
`2.16.0.dev20261030+cu132`, revision
`bf270c3251d8e84723cedbf5b60eaa60cacaa3f2`; seed 42 and strict
determinism. No production kernel or runtime patch is used.
- Existing GDN integration coverage exercises the default path; all-file
lint/typechecking pass.

```bash
python -m pytest -q tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py
```

The fix intentionally chooses a fixed backward schedule in deterministic
mode; it does not claim bitwise equivalence to every autotuned schedule.
#5785 carries the registered strict numerical integration. EP remains in
#5782 and TP/SP in #5783.

## Rebase validation

Rebased onto `main` at `c62c6a7552137d10d4fc3927aa20dcd69925aaf2`. This
includes #5909's upstream RL golden-reference fix. All ten losses from
the old failing RL job exactly match that corrected reference; this PR
does not edit the RL golden.

- Runtime: PyTorch `2.16.0.dev20261108+cu132`, revision
`1392e1f8e4903657d4391f3bd8fcc9ca8a74b758`; Attention Gym
`0.0.19.dev10+g26beb363c`, pinned revision
`26beb363c6d1328851bfc5c9c8691fa2066bd1fa`.
- The retained
`test_deterministic_backward_bypasses_normalization_autotuner` passes on
a GB300, covering ordinary and batch-invariant GDN forward/backward with
finite, nonzero gradients.
- All-file pre-commit, including typechecking, passes on this PR and the
complete rebased stack. Typechecking uses this runtime and isolated
stubs for optional dependencies.
- The complete stack's targeted CPU suite passes 123 tests.

The earlier multi-GPU model qualification results above apply to their
recorded pre-rebase sources and October 30 runtime. They have not been
repeated after this rebase. GitHub CI for the new head is pending.

## Stack

Prerequisite: #5784, shared GDN deterministic normalization,
independently based on `main`. Merge it first.

1. #5782: Flash-Next model, native DTensor PLE, FSDP and EP, based on
the prerequisite.
2. #5783: TP/SP and PLE feature-column sharding, based on #5782.
3. #5785: PP, remat and registered numerical integration, based on
#5783.

Local all-file hooks pass; Pyrefly uses the pinned validation runtime
and isolated optional-dependency stubs. GitHub CI is pending.
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.

2 participants