Skip to content

[RL] - RFC chunked CE loss for RL - #3477

Closed
felipemello1 wants to merge 2 commits into
pytorch:mainfrom
felipemello1:chunked_rl_loss_rfc
Closed

felipemello1 wants to merge 2 commits into
pytorch:mainfrom
felipemello1:chunked_rl_loss_rfc

Conversation

@felipemello1

@felipemello1 felipemello1 commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

The RFC's intent is to align on a general mindset on how to do it, but not the final implementation.

I wrote it after @DamianSzwichtenberg expressed interest in helping us with it in #3314.

Damian, please feel free to take it from here! This is just what was in my mind. See it as a starter, but please challenge the APIs, names, logic, etc.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 1, 2026
@felipemello1 felipemello1 changed the title [RL] - RFC chunked CE loss [RL] - RFC chunked CE loss for RL Jun 1, 2026
- Fix correctness errors: ratio formula (exp(train_logprobs - generator_logprobs)),
  logprob sign (-cross_entropy), unused loss_mask, missing global_valid_tokens arg
- Fix rendering: close unterminated code fence, drop stray fence, renumber sections 1-11
- Standardize naming to match loss.py (global_valid_tokens, label_chunk, cross_entropy)
- Unify vocab on train_logprobs and a single cross_entropy primitive (drop selected/policy)
- Typos and grammar throughout
@felipemello1
felipemello1 force-pushed the chunked_rl_loss_rfc branch from 3ab89f5 to 58a7f81 Compare June 1, 2026 16:57
## 5. GRPO point of view

```python
class GRPOLoss(BaseLoss):

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.

High level sounds good, but the concrete wrapping relationship could be improved.

E.g. a better organization I'd hope for may look like

RL: ChunkedLossWrapper.Config(loss_fn = GRPOLoss.Config())
SFT: ChunkedLossWrapper.Config(loss_fn = CELoss.Config())

which means we could decouple and use GRPOLoss directly without ChunkedLoss. (I'm not sure how important that is, but sounds doable.)

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 agree with that. Chunking is a reusable memory mechanism, not an objective, so I think the wrapper should own a pluggable loss rather than the loss owning/calling the wrapper via from_chunk_loss_fn. Concretely, the trainer configures the wrapper and the loss is injected by config:

ChunkedLoss.Config(loss_fn=GRPOLoss.Config())              # token-wise
CheckpointedChunkedLoss.Config(loss_fn=GSPOLoss.Config())  # sequence-wise

Note the grid isn't fully dense: token-wise losses (CE, GRPO) work under either wrapper, while sequence-wise GSPO needs the full [B, L] logprobs and so only works under CheckpointedChunkedLoss.

Comment on lines +553 to +555
We could opt to not support `_CheckpointedChunkedCE` and, therefore, sequence-wise losses.
This would simplify RL enablement for now. In the future, if sequence-wise losses become more popular,
a path forward is described in this RFC.

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.

Haven't really understood the design, but seems complicated.
I agree with this -- let's not worry too much about sequence-wise loss for now.

@felipemello1 felipemello1 Jun 1, 2026 •

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.

  1. the expensive memory is logits=[B,L,V]. We don't want to save these intermediate activations. We do only the forward, with no_grad
  2. So we compute it per chunk and get logprobs=[B, L/N]. These are checkpointed. In the forward, we concatenate them and get [B,L]
  3. in the backward, we recompute logits [B, L/N, V] when the gradients are needed (gradient checkpointing)

So, its the same as chunked CE, but with gradient checkpointing.

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.

But i agree that the code is bad, and we can just skip sequence-wise loss for now

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.

oh I see, something like?

  • 1st pass getting the per-sequence advantage
  • 2nd pass do the actual gradient computation

@felipemello1 felipemello1 Jun 1, 2026 •

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 guess this diagram helps with the understanding:

Forward, per chunk (under torch.no_grad):
    h_chunk [B, chunk, H]
        |
        v
    lm_head ----> logits [B, chunk, V]          <-- alive briefly -- its recomputed in backward
        |             |
        v             v
    token logprobs    [B, chunk]                <-- kept for backward -- cheap, no "V" dim
                      |
                      v
              torch.cat -> [B, L]              <-- returned -- given as input to sequence-wise loss

Backward, per chunk (under torch.enable_grad):
    grad_train_logprobs[:, slice]    h_chunk requires_grad
            \                /
             \              /
              v            v
              lm_head + token_logprobs       <-- re-materialized [B, chunk, V]  
                       |
                       v
              h_chunk.grad accumulated into [B, L, H]

1st pass getting the per-sequence advantage

per-sequence logprobs, which will be used by the loss.

2nd pass do the actual gradient computation

yes, for the cross entropy portion, that has [B, L/N, V] shape

train_logprobs_chunks: list[torch.Tensor] = []
with torch.no_grad():
for h_chunk, label_chunk in zip(h_chunks, label_chunks):
logits = lm_head(h_chunk)

@wwwjn wwwjn Jun 3, 2026 •

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.

previous: fwd - bwd - fwd - bwd - fwd - bwd - ....
now: fwd - fwd - fwd - fwd - ... - bwd - bwd - bwd - ...

The question is: do you still want to keep an option of "previous" behavior?Eg, separate pretrain ChunkedCELoss and RL's _checkpointedCELoss in two difference class? This behavior has low GPU memory usage and might needed for some pretrain users

@felipemello1 felipemello1 Jun 3, 2026 •

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.

option "(a) Execute RL loss on chunk" is the fastest/most memory efficient.
Option "(b) Checkpoint on chunks" is only really necessary, afaik, if we need the full logprob -- but i think that we we would opt to not add option B for now unless the community requested it

option (a) and (b) would have to be 2 different classes, but they could share some common utilities for the boilerplate around resharding, fsdp hooks, etc.

I am not sure if i answered your question though

This behavior has low GPU memory usage and might needed for some pretrain users

can you share a bit more?

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 see, now I understand
So option (a) is the same as current ChunkedCELoss (fwd - bwd - fwd - bwd - fwd - bwd - ....) , with flexibilty of plug in different losses. This is used for per-token level loss

and we decided deprioritize (b), which is more for per-sequence level loss

@felipemello1

Copy link
Copy Markdown
Contributor Author

@DamianSzwichtenberg, it sees that sequence-wise loss is more common and necessary than i was expecting. I think we should support it, but not make it a p0. Lets try to get the token-wise landed first, since its simpler, and have a follow up for sequence-wise?

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor

@DamianSzwichtenberg, it sees that sequence-wise loss is more common and necessary than i was expecting. I think we should support it, but not make it a p0. Lets try to get the token-wise landed first, since its simpler, and have a follow up for sequence-wise?

Sounds reasonable, I'll work on that early next week.

@felipemello1

Copy link
Copy Markdown
Contributor Author

hey @DamianSzwichtenberg , no pressure, just wanted to know if you are still working on this for us to adjust our plans. Thanks!!

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor

Hey @felipemello1 - yes, still on it! Almost ready. Just need to rebase onto main and run the end-to-end integration tests, then I'll push. Should have it up shortly. Thanks for your patience!

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

Labels

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.

4 participants