Skip to content

Enable Fused qkv by default and enable fused gate_up in RL - #3714

Merged
wwwjn merged 13 commits into
mainfrom
fused-qkv-new
Jun 24, 2026
Merged

wwwjn merged 13 commits into
mainfrom
fused-qkv-new

Conversation

@wwwjn

@wwwjn wwwjn commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor
  • For Qwen3 / llama3 / gpt-oss, use fused_qkv by default. This is expected to change loss curve
  • In RL, introduce the same override registry mechanism in trainer / generator for fused gate_up
    • introduce separate override config for trainer and generator

Test

  • Run 8GPU model test locally (currently being blocked by GPT-oss failure on main)
  • Run 8GPU features test by CI

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 18, 2026
@wwwjn
wwwjn force-pushed the fused-qkv-new branch 2 times, most recently from daf6ca8 to 8bf09fc Compare June 22, 2026 00:44
@wwwjn wwwjn changed the title [WIP] Enable Fused qkv by default and enable fused gate_up in RL Enable Fused qkv by default and enable fused gate_up in RL Jun 22, 2026
Comment thread torchtitan/models/common/attention.py Outdated
# 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()

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.

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();

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.

Do you still need this if using the existing implementation, modulo the mixed tensor/dtensor regression?

Comment thread torchtitan/models/common/attention.py Outdated
Comment on lines +695 to +698
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.

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.

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

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

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.

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

Comment thread tests/assets/losses/llama3_cuda.txt Outdated
97 2.7786905765533447
98 2.734128475189209
99 2.7802340984344482
100 2.773043394088745

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.

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.

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.

oh yes let me update it to use a customized param_init. Init the huge metrics together brings worse perf...

Comment on lines +333 to +334
if override is not None and override.imports:
apply_overrides(override, model_spec.model)

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.

No this should happen at config time, in rl trainer, because one can override more than model code.

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 see, I changed to override at RLTrainer (controller's) config tree, not per-actor, so it can override more compononts other than model

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.

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()

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.

similar

Comment thread torchtitan/experiments/rl/generate.py Outdated
initial_load_in_hf=True,
initial_load_path=model_path,
),
override=config.override,

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.

similar

rope: RoPE.Config,
n_kv_heads: int | None = None,
fuse_qkv: bool = False,
fuse_qkv: bool = True,

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.

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.

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.

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:

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.

good to keep a reverse test for non-fused

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.

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

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 saw the issue closed. Can we just delete this patch?

Comment thread torchtitan/models/common/attention.py Outdated
Comment on lines +695 to +698
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.

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

Comment thread torchtitan/models/common/attention.py Outdated
# 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()

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.

Do you still need this if using the existing implementation, modulo the mixed tensor/dtensor regression?

wwwjn added 7 commits June 23, 2026 08:47
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.
@wwwjn
wwwjn force-pushed the fused-qkv-new branch 2 times, most recently from fe5f35a to c4ee563 Compare June 23, 2026 17:10
@wwwjn wwwjn changed the title Enable Fused qkv by default and enable fused gate_up in RL [WIP] Enable Fused qkv by default and enable fused gate_up in RL Jun 23, 2026
98 2.7335124015808105
99 2.7795348167419434
100 2.7722811698913574
2 7.751150131225586

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.

The loss are much closer to non-fused version after properly init the weights

Comment thread torchtitan/models/common/attention.py Outdated
Comment on lines +695 to +698
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.

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.

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):

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.

This logic can be merged into a for name in ("weights", "bias")

Comment on lines +333 to +334
if override is not None and override.imports:
apply_overrides(override, model_spec.model)

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.

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.

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.

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"]),

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.

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"]),

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.

Only override in 30B-A3B model 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.

I think it's better to keep original 30B, and create a dedicated entry for good perf, with swiglu and helion rope

@wwwjn wwwjn changed the title [WIP] Enable Fused qkv by default and enable fused gate_up in RL Enable Fused qkv by default and enable fused gate_up in RL Jun 24, 2026

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

pls address comments

batch=BatchConfig(local_batch_size=2, global_batch_size=8, seq_len=2048),
),
trainer=PolicyTrainer.Config(
override=OverrideConfig(imports=["torchtitan.overrides.fused_swiglu"]),

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 think it's better to keep original 30B, and create a dedicated entry for good perf, with swiglu and helion rope

Comment on lines +102 to +107
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)

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.

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.
@wwwjn wwwjn added ciflow/h100.8 Trigger H100.8 CI ciflow/graph-trainer Run GraphTrainer CI labels Jun 24, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 24, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/graph-trainer.
Currently recognized labels are

  • ciflow/8gpu
  • ciflow/h100.8
  • ciflow/rl

Please add the new label to .github/pytorch-probot.yml

@wwwjn

wwwjn commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

8 GPU model CI failure is the same as main branch failure.

@wwwjn
wwwjn merged commit 3396a4b into main Jun 24, 2026
19 of 24 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 25, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 25, 2026
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.
felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request Jun 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 26, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 28, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/graph-trainer Run GraphTrainer CI ciflow/h100.8 Trigger H100.8 CI 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.

2 participants