Repository navigation
Enable Fused qkv by default and enable fused gate_up in RL - #3714
Conversation
daf6ca8 to
8bf09fc
Compare
| # PyTorch ops respect strides, but downstream consumers that read raw | ||
| # memory (e.g. vLLM attention/KV-cache kernels) assume contiguous | ||
| # head-major layout, so materialize all three contiguously here. | ||
| xq = xq.reshape(bs, seqlen, -1, self.head_dim).contiguous() |
There was a problem hiding this comment.
Inference path (vLLM): after the QKV projection, the wrapper hands q/k/v to vLLM's attention backend, which does two things with custom CUDA/Triton kernels (FlashAttention/FlashInfer + reshape_and_cache):
a. copies K/V into the paged KV cache, and
b. runs attention.
Those kernels take the tensor's raw base pointer (.data_ptr()) and index it with hand-computed offsets assuming a fixed contiguous, head-major layout — roughly addr = base + token*(n_headshead_dim) + headhead_dim + d. They do not consult .stride();
There was a problem hiding this comment.
Do you still need this if using the existing implementation, modulo the mixed tensor/dtensor regression?
| xq = qkv[:, :, :, :hpk, :] | ||
| xk = qkv[:, :, :, hpk : hpk + 1, :] | ||
| xv = qkv[:, :, :, hpk + 1 :, :] | ||
| # Slicing the R dim leaves K/V as strided views into the fused buffer. |
There was a problem hiding this comment.
We have to use slice instead of torchs.split() because CP +PP +Fused_qkv causing the mixed DTensor / plain tensor issue for cat(). cat() is the backward of split().
Two asymmetries land on q vs k vs v between the split and the attention:
- RoPE touches Q,K but not V.
- CP all-gathers K,V across the context-parallel sequence dim but leaves Q alone.
PP runs _backward_metadata_inference, a synthetic torch.autograd.grad pass to discover grad shapes/placements. In that pass, those asymmetric paths hand back grads with inconsistent types: the Q grad arrives as a DTensor, while the K/V grads come back as plain torch.Tensor (they cross the CP collective / to_local boundary).
Solve by using slice (the backward of slice is scatter_add). The bug is always there but didn't hit by CI
There was a problem hiding this comment.
I'm not comfortable with the change.
- I'm not sure what's the overhead this workaround has over the previous one
- The code definitely looks more ugly
It feels full_dtensor or spmd_types can work around all these. Have you tried?
If so can we temporarily add a local_map somewhere to unblock the default backend.
There was a problem hiding this comment.
The failing test is from 8 GPU features CI test, which is using "full_dtensor mode" i think.
So the actual failure is because of "fused_qkv split + full_dtensor + CP + PP" causing mixed DTensor and plain tensor. The plain tensor comes from CP all-gather (from claude) which I didn't find a clean way to wrap it back to DTensor @fegin
So here I still use a local map to make it clean and easy to read. Let me also create a issue to track the composibility issue
| 97 2.7786905765533447 | ||
| 98 2.734128475189209 | ||
| 99 2.7802340984344482 | ||
| 100 2.773043394088745 |
There was a problem hiding this comment.
The new loss seems consistently worse.
If we use identical init, do we expect the loss to be identical? If so could you try that? The swiglu override shows how you could get the same param init.
There was a problem hiding this comment.
oh yes let me update it to use a customized param_init. Init the huge metrics together brings worse perf...
| if override is not None and override.imports: | ||
| apply_overrides(override, model_spec.model) |
There was a problem hiding this comment.
No this should happen at config time, in rl trainer, because one can override more than model code.
There was a problem hiding this comment.
I see, I changed to override at RLTrainer (controller's) config tree, not per-actor, so it can override more compononts other than model
There was a problem hiding this comment.
Update: I tried applying config time in RLTrainer, however, it's impossible to manipulate the config in RLTrainer, and also put the apply_override after update_from_config, to apply the model sharding config correctly. This would cause fused_swiglu (which need to override shardingConfig) calling the default dense ffn sharding which is wrong.
Manipulating each actor's config is easier, after calling update_from_config()
| initial_load_in_hf=True, | ||
| initial_load_path=model_path, | ||
| ), | ||
| override=config.override, |
| rope: RoPE.Config, | ||
| n_kv_heads: int | None = None, | ||
| fuse_qkv: bool = False, | ||
| fuse_qkv: bool = True, |
There was a problem hiding this comment.
If this is global migration, we don't need this flag any more, do we? I think it'd be good to keep non-fused version reversely tested, maybe only in some qwen config.
There was a problem hiding this comment.
Yeah let's keep the flag and add non-fused test too, because we still have non-fused qkv code in the repo
| ) | ||
|
|
||
|
|
||
| def qwen3_debugmodel_fused_qkv() -> Trainer.Config: |
There was a problem hiding this comment.
good to keep a reverse test for non-fused
There was a problem hiding this comment.
Added the non-fused test back
| @@ -63,7 +69,11 @@ def _dtensor_safe_weak_ref_tensor(tensor): | |||
|
|
|||
| # TODO: Followup with core vLLM fix | |||
| # https://github.com/pytorch/torchtitan/issues/3067 | |||
There was a problem hiding this comment.
I saw the issue closed. Can we just delete this patch?
| xq = qkv[:, :, :, :hpk, :] | ||
| xk = qkv[:, :, :, hpk : hpk + 1, :] | ||
| xv = qkv[:, :, :, hpk + 1 :, :] | ||
| # Slicing the R dim leaves K/V as strided views into the fused buffer. |
There was a problem hiding this comment.
I'm not comfortable with the change.
- I'm not sure what's the overhead this workaround has over the previous one
- The code definitely looks more ugly
It feels full_dtensor or spmd_types can work around all these. Have you tried?
If so can we temporarily add a local_map somewhere to unblock the default backend.
| # PyTorch ops respect strides, but downstream consumers that read raw | ||
| # memory (e.g. vLLM attention/KV-cache kernels) assume contiguous | ||
| # head-major layout, so materialize all three contiguously here. | ||
| xq = xq.reshape(bs, seqlen, -1, self.head_dim).contiguous() |
There was a problem hiding this comment.
Do you still need this if using the existing implementation, modulo the mixed tensor/dtensor regression?
FusedQKVLinear.forward: split along the R dim leaves xk/xv as strided views into the fused buffer. PyTorch ops respect strides, but vLLM attention/KV-cache kernels read raw memory assuming contiguous head-major layout, so materialize q/k/v contiguously. Deduplicate _split_qkv_on_save / _merge_qkv_on_load into a loop over (weight, bias) x (wq, wk, wv) (per review feedback). Behavior is identical: bias just drops the trailing in_features dim. vllm_registry: read the FFN hidden dim from `hidden_dim` when present (fused gate+up FusedSwiGLU config) and fall back to `w1.out_features` for the stock FeedForward, since the fused config has no `w1`. vllm_wrapper: accept *args in the _node_ref patch; newer vLLM passes extra positional args at the FAP piecewise codegen callsite.
…non-fused test, remove #3067 patch
fe5f35a to
c4ee563
Compare
| 98 2.7335124015808105 | ||
| 99 2.7795348167419434 | ||
| 100 2.7722811698913574 | ||
| 2 7.751150131225586 |
There was a problem hiding this comment.
The loss are much closer to non-fused version after properly init the weights
| xq = qkv[:, :, :, :hpk, :] | ||
| xk = qkv[:, :, :, hpk : hpk + 1, :] | ||
| xv = qkv[:, :, :, hpk + 1 :, :] | ||
| # Slicing the R dim leaves K/V as strided views into the fused buffer. |
There was a problem hiding this comment.
The failing test is from 8 GPU features CI test, which is using "full_dtensor mode" i think.
So the actual failure is because of "fused_qkv split + full_dtensor + CP + PP" causing mixed DTensor and plain tensor. The plain tensor comes from CP all-gather (from claude) which I didn't find a clean way to wrap it back to DTensor @fegin
So here I still use a local map to make it clean and easy to read. Let me also create a issue to track the composibility issue
| weight_init = base_param_init.get("weight") | ||
| if weight_init is not None: | ||
|
|
||
| def _init_weight(t): |
There was a problem hiding this comment.
This logic can be merged into a for name in ("weights", "bias")
| if override is not None and override.imports: | ||
| apply_overrides(override, model_spec.model) |
There was a problem hiding this comment.
Update: I tried applying config time in RLTrainer, however, it's impossible to manipulate the config in RLTrainer, and also put the apply_override after update_from_config, to apply the model sharding config correctly. This would cause fused_swiglu (which need to override shardingConfig) calling the default dense ffn sharding which is wrong.
Manipulating each actor's config is easier, after calling update_from_config()
| enable_sp: bool, | ||
| ) -> None: | ||
| """Standard dense FFN (``w1``/``w2``/``w3``) TP sharding. | ||
| """Standard dense FFN TP sharding. |
There was a problem hiding this comment.
This should be removed.
This is needed here because the apply_override is called before set_sharding_config, which is wrong
| group_size = 8 | ||
| return RLTrainer.Config( | ||
| model_spec=_qwen3_rl_model_registry("0.6B", attn_backend="flex"), | ||
| override=OverrideConfig(imports=["torchtitan.overrides.fused_swiglu"]), |
There was a problem hiding this comment.
Only override one speed run config
| batch=BatchConfig(local_batch_size=2, global_batch_size=8, seq_len=2048), | ||
| ), | ||
| trainer=PolicyTrainer.Config( | ||
| override=OverrideConfig(imports=["torchtitan.overrides.fused_swiglu"]), |
There was a problem hiding this comment.
Only override in 30B-A3B model now
There was a problem hiding this comment.
I think it's better to keep original 30B, and create a dedicated entry for good perf, with swiglu and helion rope
| batch=BatchConfig(local_batch_size=2, global_batch_size=8, seq_len=2048), | ||
| ), | ||
| trainer=PolicyTrainer.Config( | ||
| override=OverrideConfig(imports=["torchtitan.overrides.fused_swiglu"]), |
There was a problem hiding this comment.
I think it's better to keep original 30B, and create a dedicated entry for good perf, with swiglu and helion rope
| q = t.new_empty(n_heads * head_dim, *tail) | ||
| k = t.new_empty(n_kv_heads * head_dim, *tail) | ||
| v = t.new_empty(n_kv_heads * head_dim, *tail) | ||
| base_init(q) | ||
| base_init(k) | ||
| base_init(v) |
There was a problem hiding this comment.
my feeling is that
- t is sharded dtensor
- q, k, v will be Replicate dtensor, and init is done as on single-device
- fused is Replicate
copy_(fused)correctly copies Replicate into sharded t
So I think this code is doing
- init on single device
- shard
Whereas previously it should be
- shard
- init already distributed tensors (handled by DTensor)
My assessment (without verifying above) is that this PR makes it more correct, and aligns with our long-term goal of parallelism-agnostic RNG, so I'm approving. The loss curves seems OK, too.
Please add comments.
…used-qkv init docs - Update qwen3 MoE loss files (CUDA + ROCm) for fused-QKV init parity: step-1 bit-identical to non-fused; FP-noise compounding after (max ~4e-3). - Add rl_grpo_qwen3_30b_a3b_varlen_perf (fused_swiglu + helion_rope overrides; base 30B left matching main). - Make register_to_vllm / VLLMModelWrapper 'override' required (never None); update test_bitwise_parity callsite. - Rewrite _fused_qkv_param_init docstring: parallelism-agnostic RNG (init replicated then shard) + device-dependent stride note.
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
8 GPU model CI failure is the same as main branch failure. |
Clean merge, no conflicts, no code replays. Fused-QKV-by-default (pytorch#3714) flows via common/ but ezpz/agpt keeps fuse_qkv=False (zero checkpoint risk to 2B/80B chains); LoRA/protocol convert() change (pytorch#3456) benign for ezpz (moe quant builds OK); varlen+PP assert (pytorch#3777) and SPMD Partial size-1 fix (pytorch#3762) are no-op/free-win. Config-build smoke passed for agpt_2b/2b_real/80b + moe_10b_2b/sdpa.
sync_smoke.sh VERDICT: ok -- agpt TP=1, agpt TP=2 (local_map surface), and moe all train clean through the merged code. Confirms the fused-QKV common/attention.py refactor (pytorch#3714) is safe on the ezpz non-fused path under TP>1, and the moe convert()/SPMD-Partial paths work.
…ervability TODOs pytorch#3714 made fused qkv the qwen3 default; loading the non-fused HF checkpoint into the fused wqkv yields garbage (repetition -> 0 reward -> training stalls). _qwen3_rl_model_registry now rebuilds fused qkv as separate q/k/v for every RL config (warns when it does), until the HF->fused weight load is fixed. TODOs added: resume restores model/optimizer/policy_version but not the rollout buffer or dataset position; the zero-std group drop can silently stall (no train step -> no metrics) if every group is zero-variance.
…lback + verification The umbrella clone-sync advanced the 3 prod clones past pytorch#3714 (fused qkv/ optimizer by default), breaking DCP resume from pre-fused checkpoints (Missing key: optimizer...weight.fused). Documents the cause, the per-clone rollback to 1263e5a + infra re-apply, and the hardware verification (8570407: loaded 2B-256N step-86200 in 32.6s, exit 0, chain untouched). Adds the planned checkpoint-compat shim to open items.
… optim-statedict format migration The clone-pull ckpt-resume break was mis-attributed in-session first to pytorch#3714 (fused-qkv-by-default) and then to the optimizer implementation="fused" flag. Both ruled out by direct evidence: - implementation defaulted to "fused" in BOTH 1263e5a (pinned/working) and HEAD - FusedQKVLinear hooks touch only MODEL state, never tok_embeddings optim state Verified cause: optimizer state-dict FORMAT migration. 1263e5a uses get/set_optimizer_state_dict (nested); HEAD uses get_flat_optim_state_dict/ load_flat_optim_state_dict (flat) via pytorch#3623 (772dd1b) + pytorch#3269 (632f67f), both ancestors of HEAD but not 1263e5a. The .fused-suffixed keys are the new flat layout applied to all params. Decision: do NOT build a compat shim (nested->flat migration is hard and can silently load wrong Adam momentum). Clones stay pinned pre-pytorch#3623 -- they resume cleanly (2B-256N chain advanced 86200->86674). New known-bug doc + corrected incident report.
Test