Skip to content

[rl] Add optional chunked logprobs to reduce peak memory - #3314

Closed
DamianSzwichtenberg wants to merge 3 commits into
pytorch:mainfrom
DamianSzwichtenberg:dev/RL-reduce-mem-usage
Closed

DamianSzwichtenberg wants to merge 3 commits into
pytorch:mainfrom
DamianSzwichtenberg:dev/RL-reduce-mem-usage

Conversation

@DamianSzwichtenberg

@DamianSzwichtenberg DamianSzwichtenberg commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

compute_logprobs now uses F.cross_entropy(reduction="none")] (replacing the previous log_softmax + gather), following the same pattern as forge's compute_logprobs. It can optionally process in chunks along the sequence dimension, reducing the peak float32 intermediate from O(B * S * V) to O(B * chunk_size * V). Opt-in via the logprobs_chunk_size config field (default: None = no chunking).

The chunked path is bit-for-bit identical to the non-chunked path because cross-entropy reduces over vocab independently per position — chunking along the sequence axis does not change the computation. Loss, reward, and logprob diffs are identical across all 10 training steps + pre/post validation, with and without chunking.

Usage: set logprobs_chunk_size in PolicyTrainer.Config:

trainer=PolicyTrainer.Config(
    logprobs_chunk_size=256,
    ...
)

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 11, 2026
@pytorch-bot

pytorch-bot Bot commented May 11, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/8gpu
  • ciflow/rl

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

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

Thanks, this is a nice optimization

torchtitan/experiments/rl/tests/test_bitwise_parity.py -v

# Run compute_logprobs unit tests (CPU-only, no torchrun needed)
python -m pytest \

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 yaml file is for GPU test, I think it's worth adding an separate CPU unit test yaml file to run RL CPU unit tests

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.

Done.

for start in range(0, seq_len, chunk_size):
end = min(start + chunk_size, seq_len)
chunk_logits = shift_logits[:, start:end, :].float()
chunk_lp = F.log_softmax(chunk_logits, dim=-1)

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.

Chunking might be problematic when loss_parallel is enabled and logits are shard on vocab dimension, calling log_softmax might issue one collective per chunk. In RL, now we don't enable loss_parallel which is good, and we can probably adding a guard asserting if logits are DTensor, it has Replicate() placement?

@DamianSzwichtenberg DamianSzwichtenberg May 12, 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.

Good catch! Added a placement guard (just for chunking path).

@DamianSzwichtenberg
DamianSzwichtenberg force-pushed the dev/RL-reduce-mem-usage branch 2 times, most recently from 30d9578 to 9d23434 Compare May 12, 2026 11:20
if dtensor_placements is not None:
from torch.distributed.tensor.placement_types import Replicate

if not all(isinstance(p, Replicate) for p in dtensor_placements):

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.

nit: you can use p.is_replicate() or p.is_shard() instead, which is simpler and clearer

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.

Fixed.

Comment thread .github/workflows/unit_test_cpu_rl.yaml Outdated

on:
push:
branches: [ main ]

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.

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.

Done.

Comment thread .github/workflows/unit_test_cpu_rl.yaml Outdated

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.

cc @felipemello1 about RL CPU tests, we can put it here

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

two high level notes, please see if you guys agree:

  1. I think that we should leverage the same CrossEntropy loss used in Torchtitan. We probably just need to pass reduce=None, to get per token logprobs, instead of reduce="sum".

  2. For the CI, it seems that for every new unit test file, we have to append it to the yaml. Is that true? Cant we just run it on all tests under /tests instead, and maybe have a special folder for GPU/integration tests or a decorator for GPU tests?

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

two high level notes, please see if you guys agree:

  1. I think that we should leverage the same CrossEntropy loss used in Torchtitan. We probably just need to pass reduce=None, to get per token logprobs, instead of reduce="sum".
  2. For the CI, it seems that for every new unit test file, we have to append it to the yaml. Is that true? Cant we just run it on all tests under /tests instead, and maybe have a special folder for GPU/integration tests or a decorator for GPU tests?
  1. Good point! In my opinion, cross_entropys flattened [batch*seq, vocab] shape requirements would make sequence-based chunking more complex and less intuitive compared to the current log_softmax approach on [batch, seq, vocab].
  2. You're absolutely right - we currently have to add each test file explicitly. I followed the pattern from unit_test_cpu_torchft.yaml which lists specific files. There's an alternative approach used in the main repo: unit_test_cpu.yaml runs the full unit_tests directory, and GPU tests self-filter using @unittest.skipUnless(torch.cuda.is_available()) (example: test_compile_moe.py#L45).

@felipemello1

felipemello1 commented May 13, 2026 •

Copy link
Copy Markdown
Contributor
  1. Check how i did it in forge
    compute_logprobs basically calls cross_entropy: https://github.com/meta-pytorch/torchforge/blob/main/src/forge/rl/loss/ops.py#L79-L112

and then the loss calls it: https://github.com/meta-pytorch/torchforge/blob/main/src/forge/rl/loss/grpo.py#L78

You should NOT have to refactor the entire loss to look like forge's, but the point is: we can and should call cross_entropy directly, because its highly optimized when compiled

There's an alternative approach used in the main repo: unit_test_cpu.yaml runs the full unit_tests directory, and GPU tests self-filter using @unittest.skipUnless(torch.cuda.is_available()) (example: test_compile_moe.py#L45).

This sounds good, i think we can create a decorator so this check is shorter, e.g. @gpu_test(n) that are used for tests that need gpu. Check torchtune: https://github.com/meta-pytorch/torchtune/blob/bd2a0fc7c31430972728494fa01aaeeb0ebf1ba1/tests/recipes/test_eleuther_eval.py#L58

Thats probably better, since most tests do NOT need gpu


Let me know if you feel comfortable tackling them as separate PRs -- unit tests first would be better

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author
  1. Check how i did it in forge
    compute_logprobs basically calls cross_entropy: https://github.com/meta-pytorch/torchforge/blob/main/src/forge/rl/loss/ops.py#L79-L112

and then the loss calls it: https://github.com/meta-pytorch/torchforge/blob/main/src/forge/rl/loss/grpo.py#L78

You should NOT have to refactor the entire loss to look like forge's, but the point is: we can and should call cross_entropy directly, because its highly optimized when compiled

There's an alternative approach used in the main repo: unit_test_cpu.yaml runs the full unit_tests directory, and GPU tests self-filter using @unittest.skipUnless(torch.cuda.is_available()) (example: test_compile_moe.py#L45).

This sounds good, i think we can create a decorator so this check is shorter, e.g. @gpu_test(n) that are used for tests that need gpu. Check torchtune: https://github.com/meta-pytorch/torchtune/blob/bd2a0fc7c31430972728494fa01aaeeb0ebf1ba1/tests/recipes/test_eleuther_eval.py#L58

Thats probably better, since most tests do NOT need gpu

Let me know if you feel comfortable tackling them as separate PRs -- unit tests first would be better

@felipemello1 Thanks for the feedback! Just to clarify the scope:

Should I:

  • include test improvements in this PR - Add the @gpu_test decorator and auto-discovery to the workflow alongside the chunked logprobs feature, then tackle cross_entropy in a follow-up PR?
  • split into separate PRs - First PR just adds test infrastructure improvements to existing RL tests, then this chunked logprobs with cross_entropy (with my new tests) benefits from that infrastructure?

Happy to work on this either way.

@felipemello1

felipemello1 commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

@DamianSzwichtenberg , i will open a PR today to address the unit test infrastructure. You should not have to touch any yaml after that. Do you want to focus on the chunked CE portion?

To summarize, we would need to delete our "compute_logprobs" and leverage ChunkedCrossEntropy in torchtitan with reduce=None to get per-token logprobs

Let me know if that makes sense / you agree.

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

@felipemello1 Got it, will implement chunked CE. Thanks 😉

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

I've updated compute_logprobs to use F.cross_entropy(reduction="none") directly, following the same pattern as forge's compute_logprobs.

I investigated reusing ChunkedCELoss, in my opinion it does not fit here; it takes hidden states (not logits), returns a scalar loss (not per-token logprobs), and its per-chunk backward + custom autograd reconnection assume the loss is computed inside the chunk loop — while the RL loss pipeline extracts variable-length response slices before computing the loss, making per-chunk backward non-trivial to align. Adapting it would require a new code path sharing no logic with the existing one beyond the cross_entropy call.

Waiting on the PR that fixes RL tests.

@wwwjn

wwwjn commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

For the tests, I agree we should add GPU unit tests for core and RL. In experiement folder we have some examples:

- 'torchtitan/experiments/graph_trainer/**'
, looking for the refactor. cc @felipemello1

For ChunkedCELoss, I think this overall idea is the same, but need more refactor of PolicyTrainer, Concretely:

it takes hidden states (not logits), returns a scalar loss (not per-token logprobs)

]._skip_lm_head = True # pyrefly: ignore[bad-argument-type]
We should set the skip_lm_head in PolicyTrainer.model, which will make

Then remove compute_logits() and replace it with ChunkedCELoss to only compute logits (which is not doable today), and then call GRPOLoss.

while the RL loss pipeline extracts variable-length response slices before computing the loss,

This is avoidable. We need this "slicing" because we used seq_lens, prompt_lens, response_lens in our dataflow, and we use the "length" to slicing out the response. Alternatively we can use reponse_masks which contains the same information.

The real difficulty I think is CE loss is baked into ChunkedCELoss today, and it will call forward then backward per chunk. We don't want to backward using CEloss in RL, but we want to use the chunked mechanism + GRPOloss. We'll need to either make ChunkedCELoss more flexible, or have a ChunkedGRPOLoss

compute_logprobs can now process log_softmax in chunks along the
sequence dimension, avoiding materializing the full [batch, seq, vocab]
fp32 intermediate. This is opt-in via the logprobs_chunk_size config
field (default: None = no chunking).

The chunked path is bit-for-bit identical to the non-chunked path
because log_softmax(dim=-1) reduces over vocab independently per
position — chunking along the sequence axis does not change the
computation.

Measured on Qwen3-0.6B (vocab=151936, TP=2),
chunk_size=256 reduces compute_logprobs peak memory delta from ~12.2 GB
to ~6.2 GB per GPU — a ~49% reduction (~5.9 GB saved). Loss, reward,
and logprob diffs are identical across all 10 steps with and without
chunking, both with and without full activation checkpointing.

Usage: set logprobs_chunk_size in PolicyTrainer.Config:

    trainer=PolicyTrainer.Config(
        logprobs_chunk_size=256,
        ...
    )
- Use CE
- Remove github workflow (tests will get automatically discovered)
@DamianSzwichtenberg
DamianSzwichtenberg force-pushed the dev/RL-reduce-mem-usage branch from 9582b34 to 0d57b27 Compare May 15, 2026 07:25
@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

@wwwjn Thanks for the feedback on ChunkedCELoss—I’ll definitely dig into that extension.

Since the current PR is already validated and self-contained, I’d like to merge this first to keep the changes atomic and avoid further scope creep.

Regarding the ChunkedCELoss follow-up, would you prefer I start with an RFC to align on the design, or should I go straight to an implementation PR for discussion?"

@tianyu-l

Copy link
Copy Markdown
Contributor

The real difficulty I think is CE loss is baked into ChunkedCELoss today, and it will call forward then backward per chunk. We don't want to backward using CEloss in RL, but we want to use the chunked mechanism + GRPOloss.

@wwwjn it should already work with requires_grad=False. I didn't follow closely how backward is done in current RL loop, but maybe we could call compute_logprobs in torch.no_grad mode?

https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/loss.py#L288

@wwwjn

wwwjn commented May 15, 2026

Copy link
Copy Markdown
Contributor

but maybe we could call compute_logprobs in torch.no_grad mode?

I think we can use the ChunkedCELoss class with torch.no_grad to achieve the same functionality as this PR (chunked forward ofcompute_logprobs())

However, I was worried about the the backward. Today's RL loss flow is:

  • log_probs = compute_logprobs(logits)
  • loss = GRPOLoss(log_probs)

If we pass hidden_states.requires_grad = False, then the log_probs will not have a proper gradient. Then the loss won't backprop properly?

@felipemello1

felipemello1 commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

If we pass hidden_states.requires_grad = False, then the log_probs will not have a proper gradient. Then the loss won't backprop properly?

thats my understanding as well

I think we would first need to understand why the backward is called within the loss. Is it because we need to release the memory after each chunk, or is it because of the fsdp hooks related to the lm_head?

If its because of the lm_head, maybe we can have ChunkedCE (without lm_head) and FusedChunkedCE.

If its because of the memory, then its more complicated. Perhaps do something like:

ChunkLoss(fn=my_lr_loss)

But i wonder if we reinventing the wheel and this is already a solved problem in other RL frameworks/Liger, and we can just take a look at how they do it, lol.

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

It seems to me that the GRPO loss for RL and cross-entropy loss for SFT both decompose into two steps: cross-entropy (reduction=None) -> reduction. They are different in that

Not surprisingly, this PR is trying to do chunked fwd on the cross-entropy without reduction, and is not doing bwd.

  • Not sure if there's a clean way to merge the implementation of ChunkedCELoss, which really focuses on the handling of both fwd and bwd. One way is to add if-else branching to omit the bwd part, but IMO it's not proper to call it a "Loss" any more.
  • If instead of seq-dim, we do chunking on the batch-dim, then I do see the implementation being much closer. However, for small local batch size (e.g. 1), there could be nothing to chunk.

There is room to improve this PR though.

  • Right now we still materialize the full logits (B, S, vocab_size).
  • I feel we can call model fwd with skip_lm_head=True and do the lm_head computation inside in chunked fashion, to save more peak memory.

I'm putting a hold on this PR for more discussions.

@felipemello1

Copy link
Copy Markdown
Contributor

I spent the day on it yesterday. My tested solution is to pass a chunk_loss_fn to the ChunkedCrossEntropy that
a) does the chunking (so it knows how to compute the masks, weights, normalization, etc)
b) call the loss on the chunk AFTER the CE and BEFORE the backwards.

chunked_token_loss(
    hidden_states,
    lm_head,
    labels,
    chunk_loss_fn,
) -> scalar

so something like:

class TitanCoreChunkedCELoss(..., chunk_loss_fn)
	chunks = chunk_loss_fn.get_chunks(inputs)
	for chunk in chunks:
		logprobs = do_CE_loss()
	    loss = chunk_loss_fn.loss_chunk(logprobs)
	    loss.backwards()

For the pure pre-training case, chunk_loss_fn.loss_chunk(logprobs) is a dummy sum.

That way, the titan CE loss stays the exact same, but it works with any RL loss.

I will have a PR to showcase it. Perf is the same, and the design is not intrusive.

@tianyu-l

Copy link
Copy Markdown
Contributor

@felipemello1

call the loss on the chunk AFTER the CE and BEFORE the backwards

Since we will do packing in the batch, and a single original sequence could be spanning multiple chunks, I'm not sure if you can always compute the sequence-wise GRPO loss within a chunk, per my comment

In GRPO, the reduction step has ratio computation which needs info across individual sequences (also seen in https://github.com/meta-pytorch/torchforge/blob/main/src/forge/rl/loss/ops.py#L193)

@wwwjn

wwwjn commented May 18, 2026

Copy link
Copy Markdown
Contributor

@felipemello1

call the loss on the chunk AFTER the CE and BEFORE the backwards

Since we will do packing in the batch, and a single original sequence could be spanning multiple chunks, I'm not sure if you can always compute the sequence-wise GRPO loss within a chunk, per my comment

In GRPO, the reduction step has ratio computation which needs info across individual sequences (also seen in https://github.com/meta-pytorch/torchforge/blob/main/src/forge/rl/loss/ops.py#L193)

The math makes sense to me, we will need the trainer's forward logprobs of the whole sequence. So it makes it even harder to reuse ChunkedCELoss code which assume the loss is calculated on per-token level. We should invent a new chunked loss class for these kind of Forward-only-chunk

The best chunk-style loss in RL I could think is:

  1. Run trainer model forward in chunked manner (chunked lm_head) to get per-token logprob
  2. Don't backward and just collect the per-token logprobs
  3. Sum per-sequence to get sequence level ratio R
  4. Compute the GRPO loss from R and advantage
  5. Then backward

On caveat today: in torchtitan RL today, we are not using sequence level ratio which is not strictly GRPO.

@tianyu-l

Copy link
Copy Markdown
Contributor

@wwwjn

On caveat today: in torchtitan RL today, we are not using sequence level ratio which is not strictly GRPO.

I think we are
https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/grpo.py#L106

@felipemello1

felipemello1 commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

nce level ratio which is not strictly GRPO.

This is wrong -.-`. We should be doing exp(trainer_logprobs - generator_logprobs), and if they are the same (on-policy -- which is our case), then we have exp(0)=1. But instead, we just do log(trainer_logprobs), which is something that is not 1 or a constant per tokens. But it will get fixed. Let me see if i can have a small-ish RFC/PR tomorrow to share for you guys to review

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

Based on your feedback, I think we all agree: the GRPO loss requires computing the mean over the full sequence, which means we cannot decompose the loss computation per chunk and call backward immediately. This is a fundamental difference from ChunkedCELoss.

In my experiments with ChunkedCELoss, moving backward outside of the chunked loop led to memory corruption (RuntimeError: storage of size 0). In my understanding, the implementation balances communication and memory usage as follows:

We disable resharding before the chunk loop, which reduces the number of forward all-gathers from N to 1
We call backward per chunk, which frees the intermediate logits immediately
After all chunks complete, we manually reshard the weights
The key issue is: if we move backward outside the loop and call reshard() before it, autograd will have a reference to tensors that were freed (due to resharding), causing the memory corruption error.
(I'm talking about this code)

For RL, I merged the LM head with logprob computation by checkpointing the LM head using torch.checkpoint.checkpoint(..., use_reentrant=False). This breaks the autograd graph's reference to freed storage, allowing us to reshard safely. The trade-off is that checkpointing costs N backward all-gathers during recomputation.

Any thoughts on the best path forward?

@felipemello1

felipemello1 commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

@DamianSzwichtenberg , thanks for helping us with this!!

i let claude/opus do some work and i have a couple of versions:
a) One that calls .backward on every chunk
b) One that concatenates chunks (like discussed), do RL loss, then run backwards

Most RL losses work with independent chunks, as they are averaged per token. GSPO averages per sequence and doesn't work with (a). For maximum perf, we would support both ways, but we could simplify and go just with (b).

The thing is: the code is ugly, but i know that it runs with multiple parallelisms and has parity with grad_norm, loss, tok/s.

I don't have bandwidth at the moment to go much deeper into it, so, if you are willing to help, I am thinking about these steps:

  1. I do a quick review myself and clean it up a bit
  2. Ask you to take a look, salvage the ideas that are good and work towards bringing us to a great PR

Would you feel comfortable with that?

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

@felipemello1 Sounds good, happy to help. Let me know when it's ready for review.

@DamianSzwichtenberg

Copy link
Copy Markdown
Contributor Author

@felipemello1 Any updates 😉 ?

@felipemello1

Copy link
Copy Markdown
Contributor

@DamianSzwichtenberg

here it is: #3477

I am sorry for the delay, and thanks for staying interested in it!

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

Labels

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.

4 participants