Repository navigation
[rl] Add optional chunked logprobs to reduce peak memory - #3314
DamianSzwichtenberg wants to merge 3 commits into
Conversation
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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
left a comment
There was a problem hiding this comment.
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 \ |
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Good catch! Added a placement guard (just for chunking path).
30d9578 to
9d23434
Compare
| 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): |
There was a problem hiding this comment.
nit: you can use p.is_replicate() or p.is_shard() instead, which is simpler and clearer
|
|
||
| on: | ||
| push: | ||
| branches: [ main ] |
There was a problem hiding this comment.
8599818#diff-5352d6248ca962635fea389024f074b8c3b06dc252ff809fcb841ae9f34477c4R10-R38 Can you switch to triggered by rl label here?
There was a problem hiding this comment.
cc @felipemello1 about RL CPU tests, we can put it here
felipemello1
left a comment
There was a problem hiding this comment.
two high level notes, please see if you guys agree:
-
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".
-
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?
9d23434 to
32a02f0
Compare
|
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
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:
Happy to work on this either way. |
|
@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. |
|
@felipemello1 Got it, will implement chunked CE. Thanks 😉 |
|
I've updated I investigated reusing Waiting on the PR that fixes RL tests. |
|
For the tests, I agree we should add GPU unit tests for core and RL. In experiement folder we have some examples: , looking for the refactor. cc @felipemello1For ChunkedCELoss, I think this overall idea is the same, but need more refactor of PolicyTrainer, Concretely:
Then remove compute_logits() and replace it with ChunkedCELoss to only compute logits (which is not doable today), and then call GRPOLoss.
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 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)
9582b34 to
0d57b27
Compare
|
@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?" |
@wwwjn it should already work with |
I think we can use the ChunkedCELoss class with torch.no_grad to achieve the same functionality as this PR (chunked forward of However, I was worried about the the backward. Today's RL loss flow is:
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 If its because of the If its because of the memory, then its more complicated. Perhaps do something like:
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
left a comment
There was a problem hiding this comment.
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
- In SFT loss, we can do sequence-dim chunked forward+backward, because the reduction step is independent across sequence dimension.
- 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)
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
modelfwd withskip_lm_head=Trueand do thelm_headcomputation inside in chunked fashion, to save more peak memory.
I'm putting a hold on this PR for more discussions.
|
I spent the day on it yesterday. My tested solution is to pass a so something like: For the pure pre-training case, 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. |
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
|
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:
On caveat today: in torchtitan RL today, we are not using sequence 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 |
|
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 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? |
|
@DamianSzwichtenberg , thanks for helping us with this!! i let claude/opus do some work and i have a couple of versions: 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:
Would you feel comfortable with that? |
|
@felipemello1 Sounds good, happy to help. Let me know when it's ready for review. |
|
@felipemello1 Any updates 😉 ? |
|
here it is: #3477 I am sorry for the delay, and thanks for staying interested in it! |
compute_logprobsnow usesF.cross_entropy(reduction="none")] (replacing the previouslog_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 fromO(B * S * V)toO(B * chunk_size * V). Opt-in via thelogprobs_chunk_sizeconfig 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_sizein PolicyTrainer.Config: