Repository navigation
[RL] Changes to enable compilation for trainer - #2568
Lucaskabela merged 2 commits into
Conversation
There was a problem hiding this comment.
if we go with pytorch varlen, do we still need to worry about this file? cc @wwwjn
There was a problem hiding this comment.
This is post rebase - yes we do need these changes for the following reasons:
- Moving
torch.autograd.Functionout of the inner context - this is so compile can trace it _flash_attn_varlen_fwdcustom op - this is so torch can trace it; without custom op, we don't know how shape will propogate through this
There was a problem hiding this comment.
if ur going with pytorch varlen i think u can directly call varlen_attn (which is already a custom op) pytorch's varlen calls the upstream flash attention impl instead of vllm's flash attention
There was a problem hiding this comment.
Sorry I misunderstood this question (I thought this was related to the deletion of vllm_attention directory).
We will need to move the autograd.Function out but yes we won't need the custom op in that case
8a62589 to
be75f04
Compare
be75f04 to
520d314
Compare
b0e8401 to
d032ea8
Compare
d032ea8 to
76c42cc
Compare
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def parallelize_qwen3( |
There was a problem hiding this comment.
@wwwjn could you work with @sanketpurandare to land PP + DTensor so that we can remove this ad hoc function?
There was a problem hiding this comment.
Thanks! Do we have an estimated timeline on this? In the meanwhile I don't think this should be blocking here but it is good to be aware of to coordinate :)
There was a problem hiding this comment.
also wondering what is the timeline for the PP full dtensor PR? would also like to have that to unblock Verl integration. cc @sanketpurandare
There was a problem hiding this comment.
Thanks! Do we have an estimated timeline on this? In the meanwhile I don't think this should be blocking here but it is good to be aware of to coordinate :)
DTensors for PP Stack is ready (RFC):PR1, PR2, PR3
I think the main blocker now is these PR needs review, and might not have a good ETA for this to be landed now. Removing this function here should be a separate concern.
| return model | ||
|
|
||
|
|
||
| def apply_compile(model: nn.Module, compile_config: CompileConfig): |
There was a problem hiding this comment.
Similar comment here - we can switch to that definition once ready/as a follow up :) shouldn't be blocking (imo)
There was a problem hiding this comment.
can you put this function into the centralized compile.py introduced in https://github.com/pytorch/torchtitan/pull/2557/changes#diff-b369dd9c89f872a2eba30aff3ea51cabdcdcc84c2dfc2638080acaceec2f2954R1?
|
Converting to draft to rebase on the attention changes |
6b10848 to
2a05c1f
Compare
| with utils.set_default_dtype(TORCH_DTYPE_MAP[config.training.dtype]): | ||
| model = model_spec.model.build() | ||
|
|
||
| # Replace attention with vLLM compatible attention for RL training. |
There was a problem hiding this comment.
If we need to keep this definition around then we will need the custom op changes there to support the compilation
Additionally, deleting keeps us grounded on one source of truth to help avoid confusions so I think it best to just remove this code if we are switching to varlen
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def parallelize_qwen3( |
There was a problem hiding this comment.
Thanks! Do we have an estimated timeline on this? In the meanwhile I don't think this should be blocking here but it is good to be aware of to coordinate :)
| return model | ||
|
|
||
|
|
||
| def apply_compile(model: nn.Module, compile_config: CompileConfig): |
There was a problem hiding this comment.
Similar comment here - we can switch to that definition once ready/as a follow up :) shouldn't be blocking (imo)
2a05c1f to
1a8fb5c
Compare
4fa4dac to
2196a7d
Compare
acisseJZhong
left a comment
There was a problem hiding this comment.
Results in the same losses as on main - the timing is now like:
loss seems to differ based on your paste?
| return model | ||
|
|
||
|
|
||
| def apply_compile(model: nn.Module, compile_config: CompileConfig): |
There was a problem hiding this comment.
can you put this function into the centralized compile.py introduced in https://github.com/pytorch/torchtitan/pull/2557/changes#diff-b369dd9c89f872a2eba30aff3ea51cabdcdcc84c2dfc2638080acaceec2f2954R1?
| Follows the same pattern as torchtitan/models/llama3/parallelize.py. | ||
| """ | ||
| # NOTE: we MUST use `.compile()` instead of `torch.compile()` here, because | ||
| # compatibility with weight naming between this model and vLLM definition. |
There was a problem hiding this comment.
can you put more detail on why torch.compile() wouldn't work here?
also, can we all switch to model.compile() in this case?
There was a problem hiding this comment.
It's OK to not change all pretrain compile in this PR. But please create an issue to track.
There was a problem hiding this comment.
.compile() is the general guidance due to subtle interactions with nn.Module - I will investigate this more though but IIRC this is a known issue with compile
| tensor_parallel_degree=1, | ||
| data_parallel_replicate_degree=1, | ||
| ), | ||
| compile=CompileConfig(enable=True, backend="aot_eager"), |
There was a problem hiding this comment.
nit: can we also introduce the enable field to GeneratorCompileConfig just for symmetry? Or is that we by default turn on generator compile, but no default on for trainer?
There was a problem hiding this comment.
It is a bit more complicated than that unfortunately - the compile integration in generator is quite different than trainer, so there is not a simple "enable" flag - we need both a backend turned on and a cudagraph option.
There is an "enforce_eager" option that we can wire through to compile, but on the PR for enabling the GeneratorCompile I was discouraged from wiring this through as it adds complexity
tianyu-l
left a comment
There was a problem hiding this comment.
please address remaining comments
| # Explicit positions avoid dynamic rope_cache[0:seqlen] slice in RoPE, | ||
| # which breaks torch.compile with symbolic shapes. | ||
| seq_len = full_tensor.shape[1] | ||
| positions = torch.arange(seq_len, device=device).unsqueeze(0) |
There was a problem hiding this comment.
A separate question: It seems the full sequence here is always per episode, with batch size 1, and we have a for loop over all the episodes. Wouldn't this be very inefficient?
https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/actors/trainer.py#L296
There was a problem hiding this comment.
Yes absolutely - we can make a significant improvement by batching in the future but need to be careful about our logits
There was a problem hiding this comment.
We are missing a "batcher" concept in the main RL loop
| Follows the same pattern as torchtitan/models/llama3/parallelize.py. | ||
| """ | ||
| # NOTE: we MUST use `.compile()` instead of `torch.compile()` here, because | ||
| # compatibility with weight naming between this model and vLLM definition. |
There was a problem hiding this comment.
It's OK to not change all pretrain compile in this PR. But please create an issue to track.
Lucaskabela
left a comment
There was a problem hiding this comment.
Re logits changing: That is expected now, since this PR was rebased to change the backend (i.e removing the code in trainer). There is no impact on the loss between compile=False and True, but between main and this PR there will be
| # Explicit positions avoid dynamic rope_cache[0:seqlen] slice in RoPE, | ||
| # which breaks torch.compile with symbolic shapes. | ||
| seq_len = full_tensor.shape[1] | ||
| positions = torch.arange(seq_len, device=device).unsqueeze(0) |
There was a problem hiding this comment.
Yes absolutely - we can make a significant improvement by batching in the future but need to be careful about our logits
| tensor_parallel_degree=1, | ||
| data_parallel_replicate_degree=1, | ||
| ), | ||
| compile=CompileConfig(enable=True, backend="aot_eager"), |
There was a problem hiding this comment.
It is a bit more complicated than that unfortunately - the compile integration in generator is quite different than trainer, so there is not a simple "enable" flag - we need both a backend turned on and a cudagraph option.
There is an "enforce_eager" option that we can wire through to compile, but on the PR for enabling the GeneratorCompile I was discouraged from wiring this through as it adds complexity
2196a7d to
88e2191
Compare
Minor fix in #2568 to move apply_compile to distributed/compile caused a bug due to missing `.named_children()` in this integration. So, update to fix (avoid crashing) for compile on the trainer
## Summary In this PR, we enable naive, JIT style torch.compile for the RL policy trainer. This is the first step towards speeding up the trainer model. Changes are: 1. Wiring through compilation config: - Added TrainerCompileConfig dataclass with enable (bool) and backend (str, default "eager") fields - Added compile field to PolicyTrainer.Config with compile and aot_eager backend - Added apply_compile() method that calls .compile(backend=..., fullgraph=True, dynamic=True) on each transformer layer -> This is crticial, as `torch.compile()` results in weight name change which breaks the weight transfer and dynamism needed for seqlen 2. config_registry.py — Enable compile by default in configs - Both rl_grpo_qwen3_0_6b and rl_grpo_qwen3_debug configs now set compile=TrainerCompileConfig(enable=True, backend="aot_eager") 3. vllm_compat_attention.py — Deleted to consolidate on new attention backend ## Test Plan ```bash python torchtitan/experiments/rl/simple_grpo_sum_digits.py --module rl --config rl_grpo_qwen3_0_6b --hf_assets_path=torchtitan/experiments/rl/example_checkpoint/Qwen3-0.6B ``` Results in the same losses w/ and w/o compile, but different on main due to changing backend - the timing is now like: ### Main ```bash [actor=<root>] Step 9 | Loss: +0.0041 | Reward: +0.450 | Correct: 29/40 | Avg tokens: 100 | Logprob diff: mean=-1.1657e-01, max=1.1326e+01 | Time: 21.1s [actor=<root>] Timing: generate=2.98s grade=0.01s advantage=0.0003s train=15.02s sync=3.14s (push=0.13s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 219.2s, avg 21.92s/step): [actor=<root>] generate: 25.1s total, 2.51s avg, 11% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 155.9s total, 15.59s avg, 71% [actor=<root>] sync: 38.1s total, 3.81s avg, 17% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ ``` ### Changes ```bash [actor=<root>] Step 9 | Loss: -0.0072 | Reward: +0.300 | Correct: 26/40 | Avg tokens: 100 | Logprob diff: mean=-1.0181e-01, max=1.2256e+01 | Time: 12.9s [actor=<root>] Timing: generate=2.53s grade=0.01s advantage=0.0002s train=7.12s sync=3.24s (push=0.12s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 170.0s, avg 17.00s/step): [actor=<root>] generate: 24.0s total, 2.40s avg, 14% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 113.3s total, 11.33s avg, 67% [actor=<root>] sync: 32.7s total, 3.27s avg, 19% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=60% (12/20) Format=90% (18/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=60% (12/20) Format=90% (18/20)= (vllm) [[email protected] ~/torchtitan (lucaskabela/enable_trainer_compile_03_10)]$ pytho ``` So we save ~40s of runtime e2e via compilation in this manner without affecting our logits/accuracy
## Summary In this PR, we enable naive, JIT style torch.compile for the RL policy trainer. This is the first step towards speeding up the trainer model. Changes are: 1. Wiring through compilation config: - Added TrainerCompileConfig dataclass with enable (bool) and backend (str, default "eager") fields - Added compile field to PolicyTrainer.Config with compile and aot_eager backend - Added apply_compile() method that calls .compile(backend=..., fullgraph=True, dynamic=True) on each transformer layer -> This is crticial, as `torch.compile()` results in weight name change which breaks the weight transfer and dynamism needed for seqlen 2. config_registry.py — Enable compile by default in configs - Both rl_grpo_qwen3_0_6b and rl_grpo_qwen3_debug configs now set compile=TrainerCompileConfig(enable=True, backend="aot_eager") 3. vllm_compat_attention.py — Deleted to consolidate on new attention backend ## Test Plan ```bash python torchtitan/experiments/rl/simple_grpo_sum_digits.py --module rl --config rl_grpo_qwen3_0_6b --hf_assets_path=torchtitan/experiments/rl/example_checkpoint/Qwen3-0.6B ``` Results in the same losses w/ and w/o compile, but different on main due to changing backend - the timing is now like: ### Main ```bash [actor=<root>] Step 9 | Loss: +0.0041 | Reward: +0.450 | Correct: 29/40 | Avg tokens: 100 | Logprob diff: mean=-1.1657e-01, max=1.1326e+01 | Time: 21.1s [actor=<root>] Timing: generate=2.98s grade=0.01s advantage=0.0003s train=15.02s sync=3.14s (push=0.13s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 219.2s, avg 21.92s/step): [actor=<root>] generate: 25.1s total, 2.51s avg, 11% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 155.9s total, 15.59s avg, 71% [actor=<root>] sync: 38.1s total, 3.81s avg, 17% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ ``` ### Changes ```bash [actor=<root>] Step 9 | Loss: -0.0072 | Reward: +0.300 | Correct: 26/40 | Avg tokens: 100 | Logprob diff: mean=-1.0181e-01, max=1.2256e+01 | Time: 12.9s [actor=<root>] Timing: generate=2.53s grade=0.01s advantage=0.0002s train=7.12s sync=3.24s (push=0.12s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 170.0s, avg 17.00s/step): [actor=<root>] generate: 24.0s total, 2.40s avg, 14% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 113.3s total, 11.33s avg, 67% [actor=<root>] sync: 32.7s total, 3.27s avg, 19% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=60% (12/20) Format=90% (18/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=60% (12/20) Format=90% (18/20)= (vllm) [[email protected] ~/torchtitan (lucaskabela/enable_trainer_compile_03_10)]$ pytho ``` So we save ~40s of runtime e2e via compilation in this manner without affecting our logits/accuracy
Minor fix in #2568 to move apply_compile to distributed/compile caused a bug due to missing `.named_children()` in this integration. So, update to fix (avoid crashing) for compile on the trainer
## Summary In this PR, we enable naive, JIT style torch.compile for the RL policy trainer. This is the first step towards speeding up the trainer model. Changes are: 1. Wiring through compilation config: - Added TrainerCompileConfig dataclass with enable (bool) and backend (str, default "eager") fields - Added compile field to PolicyTrainer.Config with compile and aot_eager backend - Added apply_compile() method that calls .compile(backend=..., fullgraph=True, dynamic=True) on each transformer layer -> This is crticial, as `torch.compile()` results in weight name change which breaks the weight transfer and dynamism needed for seqlen 2. config_registry.py — Enable compile by default in configs - Both rl_grpo_qwen3_0_6b and rl_grpo_qwen3_debug configs now set compile=TrainerCompileConfig(enable=True, backend="aot_eager") 3. vllm_compat_attention.py — Deleted to consolidate on new attention backend ## Test Plan ```bash python torchtitan/experiments/rl/simple_grpo_sum_digits.py --module rl --config rl_grpo_qwen3_0_6b --hf_assets_path=torchtitan/experiments/rl/example_checkpoint/Qwen3-0.6B ``` Results in the same losses w/ and w/o compile, but different on main due to changing backend - the timing is now like: ### Main ```bash [actor=<root>] Step 9 | Loss: +0.0041 | Reward: +0.450 | Correct: 29/40 | Avg tokens: 100 | Logprob diff: mean=-1.1657e-01, max=1.1326e+01 | Time: 21.1s [actor=<root>] Timing: generate=2.98s grade=0.01s advantage=0.0003s train=15.02s sync=3.14s (push=0.13s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 219.2s, avg 21.92s/step): [actor=<root>] generate: 25.1s total, 2.51s avg, 11% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 155.9s total, 15.59s avg, 71% [actor=<root>] sync: 38.1s total, 3.81s avg, 17% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ ``` ### Changes ```bash [actor=<root>] Step 9 | Loss: -0.0072 | Reward: +0.300 | Correct: 26/40 | Avg tokens: 100 | Logprob diff: mean=-1.0181e-01, max=1.2256e+01 | Time: 12.9s [actor=<root>] Timing: generate=2.53s grade=0.01s advantage=0.0002s train=7.12s sync=3.24s (push=0.12s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 170.0s, avg 17.00s/step): [actor=<root>] generate: 24.0s total, 2.40s avg, 14% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 113.3s total, 11.33s avg, 67% [actor=<root>] sync: 32.7s total, 3.27s avg, 19% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=60% (12/20) Format=90% (18/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=60% (12/20) Format=90% (18/20)= (vllm) [[email protected] ~/torchtitan (lucaskabela/enable_trainer_compile_03_10)]$ pytho ``` So we save ~40s of runtime e2e via compilation in this manner without affecting our logits/accuracy
Minor fix in pytorch#2568 to move apply_compile to distributed/compile caused a bug due to missing `.named_children()` in this integration. So, update to fix (avoid crashing) for compile on the trainer
## Summary In this PR, we enable naive, JIT style torch.compile for the RL policy trainer. This is the first step towards speeding up the trainer model. Changes are: 1. Wiring through compilation config: - Added TrainerCompileConfig dataclass with enable (bool) and backend (str, default "eager") fields - Added compile field to PolicyTrainer.Config with compile and aot_eager backend - Added apply_compile() method that calls .compile(backend=..., fullgraph=True, dynamic=True) on each transformer layer -> This is crticial, as `torch.compile()` results in weight name change which breaks the weight transfer and dynamism needed for seqlen 2. config_registry.py — Enable compile by default in configs - Both rl_grpo_qwen3_0_6b and rl_grpo_qwen3_debug configs now set compile=TrainerCompileConfig(enable=True, backend="aot_eager") 3. vllm_compat_attention.py — Deleted to consolidate on new attention backend ## Test Plan ```bash python torchtitan/experiments/rl/simple_grpo_sum_digits.py --module rl --config rl_grpo_qwen3_0_6b --hf_assets_path=torchtitan/experiments/rl/example_checkpoint/Qwen3-0.6B ``` Results in the same losses w/ and w/o compile, but different on main due to changing backend - the timing is now like: ### Main ```bash [actor=<root>] Step 9 | Loss: +0.0041 | Reward: +0.450 | Correct: 29/40 | Avg tokens: 100 | Logprob diff: mean=-1.1657e-01, max=1.1326e+01 | Time: 21.1s [actor=<root>] Timing: generate=2.98s grade=0.01s advantage=0.0003s train=15.02s sync=3.14s (push=0.13s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 219.2s, avg 21.92s/step): [actor=<root>] generate: 25.1s total, 2.51s avg, 11% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 155.9s total, 15.59s avg, 71% [actor=<root>] sync: 38.1s total, 3.81s avg, 17% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=55% (11/20) Format=100% (20/20) [actor=<root>] ================================================================================ ``` ### Changes ```bash [actor=<root>] Step 9 | Loss: -0.0072 | Reward: +0.300 | Correct: 26/40 | Avg tokens: 100 | Logprob diff: mean=-1.0181e-01, max=1.2256e+01 | Time: 12.9s [actor=<root>] Timing: generate=2.53s grade=0.01s advantage=0.0002s train=7.12s sync=3.24s (push=0.12s) [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] Training timing (10 steps in 170.0s, avg 17.00s/step): [actor=<root>] generate: 24.0s total, 2.40s avg, 14% [actor=<root>] grade: 0.1s total, 0.01s avg, 0% [actor=<root>] train: 113.3s total, 11.33s avg, 67% [actor=<root>] sync: 32.7s total, 3.27s avg, 19% [actor=<root>] -------------------------------------------------------------------------------- [actor=<root>] RL Training complete [actor=<root>] Evaluating post-training performance... [actor=<root>] Eval: Accuracy=60% (12/20) Format=90% (18/20) [actor=<root>] ================================================================================ [actor=<root>] Pre-training: Accuracy=40% (8/20) Format=50% (10/20) [actor=<root>] Post-training: Accuracy=60% (12/20) Format=90% (18/20)= (vllm) [[email protected] ~/torchtitan (lucaskabela/enable_trainer_compile_03_10)]$ pytho ``` So we save ~40s of runtime e2e via compilation in this manner without affecting our logits/accuracy
Minor fix in pytorch#2568 to move apply_compile to distributed/compile caused a bug due to missing `.named_children()` in this integration. So, update to fix (avoid crashing) for compile on the trainer
Summary
In this PR, we enable naive, JIT style torch.compile for the RL policy trainer. This is the first step towards speeding up the trainer model. Changes are:
layer -> This is crticial, as
torch.compile()results in weight name change which breaks the weight transfer and dynamism needed for seqlencompile=TrainerCompileConfig(enable=True, backend="aot_eager")
Test Plan
Results in the same losses w/ and w/o compile, but different on main due to changing backend - the timing is now like:
Main
Changes
So we save ~40s of runtime e2e via compilation in this manner without affecting our logits/accuracy