Repository navigation
Qwen 3.5 Varlen Attention - #3801
Conversation
Thread per-document cu_seqlens through the GatedDeltaNet path so packed multi-document batches run the FLA variable-length kernels instead of falling back to padded full attention: - VarlenMetadata carries host-side cu_seq_q offsets (opt-in via include_host_offsets) and the GatedDeltaNet builds a CPU cu_seqlens tensor once, so the FLA chunked / fused-recurrent kernels and the causal conv avoid per-call device-to-host syncs. - GatedDeltaNet / GatedDeltaKernel / the causal conv accept cu_seqlens, cu_seqlens_host, and cu_seqlens_cpu and flatten the batch to a single packed sequence for the kernels. - Add a torch_native varlen reference path for numerical testing. - Integration coverage (FSDP and TP varlen + per-op SAC) and unit tests that compare the varlen forward against independent per-document forwards on the torch_native reference and on both FLA kernels (chunked and fused-recurrent) to verify document isolation. - Fix the qwen3_5 requirements include to use "-r" so the shared VLM requirements (flash-linear-attention) are actually installed. Tensor names follow the existing Qwen3.5 convention here; adopting the shape-suffix names is a separate follow-up commit.
Rename Qwen3.5 model tensors to the Noam Shazeer shape-suffix convention (e.g. x -> x_BLD, q/k/v -> xq_BLNK/xk_BLNK/xv_BLNV, g -> g_BLN) across the model and update the matching local_map sharding keys. Pure no-op refactor: no logic changes. Also switches the new varlen comments/docstrings to ASCII per the repo style rule.
|
|
| "v": _kernel_plc, | ||
| "g": _kernel_plc, | ||
| "beta": _kernel_plc, | ||
| "xq_BLNK": _kernel_plc, |
There was a problem hiding this comment.
while I am a fan of this naming style, is this okay in titan @tianyu-l ?
There was a problem hiding this comment.
This is already done in attention and MoE. Not sure why qwen3.5 missed that
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/attention.py#L113
| def create_varlen_metadata_for_document( | ||
| positions: torch.Tensor, | ||
| *, | ||
| include_host_offsets: bool = False, |
| "v": _kernel_plc, | ||
| "g": _kernel_plc, | ||
| "beta": _kernel_plc, | ||
| "xq_BLNK": _kernel_plc, |
There was a problem hiding this comment.
This is already done in attention and MoE. Not sure why qwen3.5 missed that
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/attention.py#L113
| cu_seqlens = attention_masks.cu_seq_q | ||
| cu_seqlens_host = _require_cu_seqlens_host(attention_masks.cu_seq_q_host) | ||
| if x_BLD.is_cuda: | ||
| cu_seqlens_cpu = _cu_seqlens_host_to_cpu_tensor( |
There was a problem hiding this comment.
why do u need both cu_seqlens_cpu and cu_seqlens_host?
There was a problem hiding this comment.
Good point. I changed this so we no longer store both in VarlenMetadata. The metadata now stores host offsets as a Python tuple (cu_seq_q_host) because passing a CPU int tensor through the checkpointed input structure caused a SelectiveAC recompute failure in the 8-GPU smoke.
cu_seqlens_cpu is now only a local adapter tensor built once inside GatedDeltaNet.forward, because FLA’s API expects that form. This avoids the CUDA-to-CPU sync while keeping checkpoint metadata tensor-free.
| cu_seqlens_host: tuple[int, ...], | ||
| cu_seqlens_cpu: torch.Tensor | None = None, | ||
| ) -> torch.Tensor: | ||
| if x_BTD.is_cuda: |
There was a problem hiding this comment.
match on backend instead?
| return list(cu_seqlens_host) | ||
|
|
||
|
|
||
| def _require_cu_seqlens_host( |
There was a problem hiding this comment.
maybe can just inline this?
There was a problem hiding this comment.
Yes, good call. Will do.
| packed_cu_seqlens_host = ( | ||
| tuple(packed_cu_seqlens.tolist()) if include_host_offsets else None | ||
| ) | ||
|
|
There was a problem hiding this comment.
when include_host_offsets=true can u remove the .item() call so that theres only one sync
|
Addressed the comments & revalidated with an 8xH100 smoke test (dp_shard=4 and tp=2) for 10 steps. I also tried storing the CPU tensor directly in I’ll be OOO until July 20, so I may be slower to respond, but I’ll address any remaining feedback when I’m back. |
| return out_BLNV.to(dtype) | ||
|
|
||
|
|
||
| def _torch_native_gated_delta_varlen( |
There was a problem hiding this comment.
i have some confusion on this torch native implementation. this function is serially processing each document, but i think fla is processing chunks in parallel, can we also provide a parallel processing version, should be faster i guess.
There was a problem hiding this comment.
Yeah valid critique.
I created the torch native implementation mostly to serve as a correctness reference against the flash linear attention implementation of varlen attention. I went for simplicity with the serial processing of each document.
My conception is that a performance inclined user would be using flash linear attention for the accelerated kernels + parallel processing. I am inclined to keep this simpler, please let me know if you feel differently.
There was a problem hiding this comment.
fair point. i used the debug model with seq len 512 for some simple test, which shows that neither the pre-existing _torch_native_gated_delta(batched) and the _torch_native_gated_delta_varlen is practical. If they are for numerical correctness test purpose only, maybe we should move all the (too slow) native backends into tests. what do you think?
cc: @tianyu-l
There was a problem hiding this comment.
Yeah I think that's very reasonable. I'm traveling & away from my computer the next 2 weeks, but could make that change once I return
There was a problem hiding this comment.
# Conflicts: # torchtitan/models/qwen3_5/model.py
Review feedback: the pure-torch gated delta implementations are far too slow for training (serial over documents and sequence steps), so they do not belong in the model as a runtime backend. Move them into test_qwen3_5_deltanet.py as the numerical baseline for the FLA kernels, injected through the GatedDeltaKernel module boundary, and drop "torch_native" from GatedDeltaBackend. The per-document conv fallback stays in the model as the non-CUDA path (FLA's causal conv is a triton kernel).
|
Merged main & migrated the torch native linear attention implementations into the test file. Then I reran an 8xH100 smoke test with dp_shard=4, tp=2 for 10 steps Can I get a re-review please @shuhuayu ? |
| "--module qwen3_5 --config qwen35_debugmodel_varlen_attn", | ||
| "--parallelism.data_parallel_shard_degree=4", | ||
| "--training.steps 10", | ||
| "--comm.train_timeout_seconds 600", |
There was a problem hiding this comment.
We were consistently getting timeouts for FLA / TileLang kernel compile + varlen autotune for the default 100s train timeout.
I was running a 4xH100 setup with FSDP and would reliably hit an all-gather NCCL timeout after step 1 with the default, but this would pass consistently with 600s.
I added a comment explaining the timeout, and have removed the training.steps 10 since that is in the default config.
| [ | ||
| [ | ||
| "--module qwen3_5 --config qwen35_debugmodel_varlen_attn", | ||
| "--parallelism.tensor_parallel_degree 2", |
There was a problem hiding this comment.
can we merge the two into one, testing FSDP and TP together?
There was a problem hiding this comment.
Then I reran an 8xH100 smoke test with dp_shard=4, tp=2 for 10 steps
Have you tested it with spmd_types backend and debug.spmd_typechecking on? Let's make sure it works, because we are deprecating other two backends (default, full_dtensor)
Actually the migration is being done in #3895, so don't have to happen in this PR.
There was a problem hiding this comment.
can we merge the two into one, testing FSDP and TP together?
Done, now we do dp=2, tp=2 on 4 GPUs.
Have you tested it with spmd_types backend and debug.spmd_typechecking on? Let's make sure it works, because we are deprecating other two backends (default, full_dtensor)
Actually the migration is being done in #3895, so don't have to happen in this PR.
I actually started working on the SPMD on a separate branch (with heavy Claude assistance), before you made your comment edit. It appears #3895 is authored by a Meta employee and will take priority, but I had some design variations & will go add some feedback from my experiments on that PR.
There was a problem hiding this comment.
Ok sounds good, thank you for the reviews!
| v: torch.Tensor, | ||
| g: torch.Tensor, | ||
| beta: torch.Tensor, | ||
| def _torch_native_causal_conv1d_varlen( |
There was a problem hiding this comment.
if you put _torch_native_gated_delta_varlen into test, why keeping torch native impl for conv1d here?
There was a problem hiding this comment.
Good call, I've moved that.
| ): | ||
| return create_varlen_metadata_for_document( | ||
| positions, | ||
| include_host_offsets=True, |
There was a problem hiding this comment.
maybe noob question, why for quadratic attention we didn't need to include_host_offsets?
There was a problem hiding this comment.
All good!
It's the asymmetry that motivated the opt-in flag. torch.nn.attention.varlen consumes cu_seqlens as device tensors directly (only max_q/max_k need host values, one .item() sync). FLA's gated-delta kernels and varlen conv additionally require cu_seqlens as a CPU tensor to size their kernel launches. We store the host offsets as Python ints rather than a CPU int tensor because a tensor there becomes part of the SelectiveAC checkpoint input structure and fails recompute with Autograd not support dtype: Int. I added a comment explaining this at get_attention_masks in cdfddbb.
- Merge the two varlen CI entries into one FSDP+TP (dp_shard=2, tp=2) entry, drop the redundant --training.steps flag (debug config already defaults to 10), and document why the 600s train timeout is needed (first-run FLA/TileLang compile exceeds the 100s default). - Move the per-document torch conv reference into the unit test next to the other reference implementations; the model conv path is now FLA-only and the CPU test patches the reference in. - Document why GatedDeltaNet needs host offsets while quadratic varlen attention does not (FLA kernels take cu_seqlens as a CPU tensor; torch.nn.attention.varlen consumes the device tensor).
| # Keep host metadata as Python values in VarlenMetadata so | ||
| # SelectiveAC does not treat integer CPU tensors as checkpoint | ||
| # inputs; build the FLA API tensor at the DeltaNet boundary. |
| ): | ||
| return create_varlen_metadata_for_document( | ||
| positions, | ||
| include_host_offsets=True, |
shuhuayu
left a comment
There was a problem hiding this comment.
Thanks for the update! Can you mainly check whether the flex attention code path also has sample packing fixed?
| B, L, _ = x_BLD.shape | ||
| cu_seqlens = None | ||
| cu_seqlens_cpu = None | ||
| if isinstance(attention_masks, VarlenMetadata): |
There was a problem hiding this comment.
do we miss something here? if one uses flex attention, which produces BlockMask, then the doc partition info cu_seqlens = None all the time, then we do not have sample packing for that code path.
There was a problem hiding this comment.
Yeah, good catch. There was a pre-existing bug with flex attention not consuming BlockMask. I'm working on a commit to address flex attention too.
Co-authored-by: Shuhua Yu <[email protected]>
The applied GitHub suggestion landed the backend comments at column 0; ufmt re-indents them into the Config body. Place the Conv1d dispatch TODO at the local_map conv callsite as suggested (wrapped to fit the line limit) and drop the blank line the docstring deletion left behind.
is this addressed? |
No, I'm working on it now though. FlexAttention has a pre-existing bug on main. The full quadratic attention layers (every fourth) correctly mask between documents. The gated delta net layers do not, so we have context bleeding between documents. I am working on a fix for flex attention too. Do you want me to include that in this PR, or put it into a separate PR? It re-uses some of the machinery of this PR (the |
Is the issue that
If that's the case, we can fix Flex in another PR |
Yes, that's correct. I just made a fix for flex, but I'll leave that out of scope for this PR and open a new PR to follow up. Edit: See #3984 for the flex attention fix |
tianyu-l
left a comment
There was a problem hiding this comment.
This PR seems caused numerics change, although it's not clear to me why, because I think the loss test is with Flex, but this PR only touches Varlen.
Could you investigate?
The failing job is flex attention for llama3, and the only non Qwen3.5 specific code this PR touches is varlen only structures (VarlenMetadata and create_varlen_metadata_for_document in common/attention.py), which is not used in the llama3 flex attention path. Additionally, that CI job was green on this PR branch previously, and the only changes since that are comment only (following @shuhuaya 's guidance) The failure is also reproducible on main (commit 4c64811). The root cause appears to be using an unpinned version of pytorch nightly. |
|
thx for the clarification. i reran the test and it passed, so i guess this is related to some changes from pytorch nightly side. |
|
Great, are we good to merge once @tianyu-l removes the request for changes? |
… attention (#3984) Follow-up to #3801 (merged), split out per @tianyu-l's review there. ## Summary Under the flex attention backend, the `BlockMask` document-isolates only the quadratic full-attention layers (1 in 4). `GatedDeltaNet` is a recurrence, so it needs document *offsets* rather than a mask. It previously received no document info at all, meaning its conv and recurrent state ran across packed-document boundaries as one continuous stream. This was pre-existing behavior on main (surfaced by @shuhuayu's review on #3801). Per review, `Qwen35Model.get_attention_masks` returns a flat mask dict (the gpt_oss pattern): `{"quadratic_attention": BlockMask (flex) or VarlenMetadata (varlen), "deltanet": VarlenMetadata}`; each transformer block picks its entry by `attn_mask_key` set at init, so `GatedDeltaNet` and `Qwen35Attention` keep their natural signatures with no per-module mask dispatch. `AttentionMasksType`'s mapping arm widens to `Mapping[str, BlockMask | VarlenMetadata | None]` (`Mapping` keeps value types covariant so gpt_oss's `dict[str, BlockMask]` still typechecks, and a `None` value marks an unused mask), which removes the `bad-override` suppression. For configs with no full-attention layer the dict fills `quadratic_attention: None`; a maskless (`None`) GatedDeltaNet forward stays legal: the TitanRL inference wrapper's forward calls every layer with `attention_masks=None` (`experiments/rl/models/vllm_wrapper.py`), and #3957's Qwen3.5 unified RL path builds hybrid Qwen3.5 on it -- request boundaries there are tracked by its vLLM paged-state GDN adapter, not by varlen offsets. Context-parallel mask sharding raises a clear error on non-BlockMask values (CP+varlen was already unsupported, now loud). Pipeline safety comes from #3856: the trainer pre-splits microbatches and builds the mask dict per microbatch. `GatedDeltaNet.forward` also clones `cu_seq_q` once per invocation. FLA's `tensor_cache` is keyed by tensor identity and holds only a few entries (one in fla 0.5.0, a 4-entry deque in 0.5.1+); under pipeline parallelism another microbatch's forward evicts the entry between a microbatch's forward and its selective-AC recompute, so the recompute runs the varlen index helpers that the original forward skipped as cache hits. Selective AC pairs saved-op invocations by index, and the shifted ledger fails hard: ``` RuntimeError: aten.slice.Tensor invocation index 4 encountered during backward but not found in storage. ``` A fresh tensor per forward keeps forward and recompute on the same cache-miss path. Without PP the divergence is benign (a recompute can only hit where its forward missed), which is why the non-PP varlen SAC CI entry never tripped this. Note for reviewers: this intentionally changes flex-path numerics for packed data. DeltaNet state now resets at document boundaries where it previously bled across them. Known limitation (pre-existing, documented TODO): a model config with no full-attention layers gets no masks, so no DeltaNet resets (the trainer only builds masks when `model_config.first_attention` is Flex/Varlen). ## Testing - CPU unit tests: the flex composite carries the BlockMask plus the packed document offsets (plain `VarlenMetadata` under varlen); GatedDeltaNet under the composite matches stitched per-document forwards; and a cache-key invariant test (fresh `cu_seqlens` per DeltaNet forward) that is red without the clone. Deltanet suite: 6 passed on one H100. - 8x H100 red/green for the clone on the `qwen3_5_moe_fsdp+tp+ep+pp` CI entry shape (pp2 / dp_shard2 / tp2 / ep4, selective AC), on the post-#3856 pre-split flow with `torch==2.14.0.dev20260731+cu130`: without the clone, step-1 backward fails with the ledger error above; with it, 10/10 steps complete. - 4x H100, flex backend, dp_shard=2 / tp=2, selective AC, 10 steps: green. - 4x H100 regression: the `qwen3_5_fsdp+tp+varlen_attn+per_op_sac` CI entry still passes 10 steps. - New with #3856: varlen + PP + SAC (pp2 / dp_shard2 / tp2) completes 10/10 steps on 8x H100 -- the first pipelined run of the GatedDeltaNet varlen path (previously hard-blocked by the PP+Varlen guard). - Note on torch versions: the pre-split `step(arg_mbs=...)` API that #3856 relies on landed in `torch==2.14.0.dev20260731+cu130`, but plain `pip install --pre torch torchvision` currently resolves torch back to `dev20260729` (torchvision `dev20260731` pins it), which fails all PP entries with `Expecting N arg_mbs but got 1` -- the current main 8-GPU CI failure. The PP runs above force the July 31 torch wheel.
Summary
Adds varlen attention support to the Qwen3.5 GatedDeltaNet (linear-attention) path. Packed multi-document batches now run the FLA variable-length kernels with per-document
cu_seqlens, so each document is processed independently within a packed sequence instead of padding out to full attention.I've added this for in house work at my job, where we have quite varied sequence lengths on training data (in a way that packing is insufficient). I think this would also benefit efforts to add Qwen3.5 to TorchTitan RL (where I believe Qwen3 uses varlen by default).
How to Review
The branch is organized as two commits for review:
a. No-op rename of the Qwen3.5 model tensors to the shape-suffix convention (
x -> x_BLD,q/k/v -> xq_BLNK/xk_BLNK/xv_BLNV, ...)b. I have seen PR's landing in torchtitan the last couple weeks making this change. If this is unwanted, I'm happy to remove this from the PR.
Details
VarlenMetadatacarries host-sidecu_seq_qoffsets (opt-in viainclude_host_offsets);GatedDeltaNetbuilds a CPUcu_seqlenstensor onceper forward, so the FLA chunked / fused-recurrent kernels and the causal conv
avoid per-call device-to-host syncs.
GatedDeltaNet/GatedDeltaKernel/ the causal conv threadcu_seqlens,cu_seqlens_host, andcu_seqlens_cpu, flattening the batch to a singlepacked sequence for the kernels.
Testing
Integration
I ran the following tests on an H100 node for 10 steps each:
qwen3_5_tp+varlen_attn+per_op_sacqwen3_5_fsdp+varlen_attn+per_op_sacdp_shard=4,tp=2(note this had a long first-step Triton compile)New Unit Tests
I added new unit tests to
tests/unit_tests/test_qwen3_5_deltanet.pythat assert that the varlenforward is asserted equal to running each document independently and stitching
the outputs back. Covered on the
torch_nativereference (CPU, exact, atol 1e-6) and on both productionFLA kernels (
fla_chunked,fla_fused_recurrent) on GPU:Notes / follow-ups
torch_nativevarlen reference path was added for numerical testing.-rso the shared VLM requirements (flash-linear-attention) are actually installed.cu_seqlens is not None; the non-varlenpath is a no-op refactor (the extracted
_local_map_convreproduces theprevious inline
local_map, same placements/grad placements), so existingnon-varlen Qwen3.5 behavior is unchanged. Note: Left to CI to confirm.
full_dtensor,because
qwen3_5/parallelize.pyraisesNotImplementedErrorunderfull_dtensor(TODO to lift the exclusion once supported).equivalence tests are what assert numerical correctness of the varlen path.