Skip to content

Qwen 3.5 Varlen Attention - #3801

Merged
tianyu-l merged 11 commits into
pytorch:mainfrom
Jeremalloch:jm/qwen35-varlen-attn
Jul 27, 2026
Merged

tianyu-l merged 11 commits into
pytorch:mainfrom
Jeremalloch:jm/qwen35-varlen-attn

Conversation

@Jeremalloch

@Jeremalloch Jeremalloch commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. Add variable-length attention support to Qwen3.5 GatedDeltaNet
  2. Adopt Shazeer style shape-suffix tensor names in Qwen3.5
    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

  • VarlenMetadata carries host-side cu_seq_q offsets (opt-in via
    include_host_offsets); GatedDeltaNet builds a CPU cu_seqlens tensor once
    per forward, so the FLA chunked / fused-recurrent kernels and the causal conv
    avoid per-call device-to-host syncs.
  • GatedDeltaNet / GatedDeltaKernel / the causal conv thread cu_seqlens,
    cu_seqlens_host, and cu_seqlens_cpu, flattening the batch to a single
    packed sequence for the kernels.

Testing

Integration

I ran the following tests on an H100 node for 10 steps each:

  • 2-GPU: qwen3_5_tp+varlen_attn+per_op_sac
  • 4-GPU: qwen3_5_fsdp+varlen_attn+per_op_sac
  • 8-GPU combined smoke: Qwen3.5 varlen + SelectiveAC, dp_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.py that assert that the varlen
forward is asserted equal to running each document independently and stitching
the outputs back. Covered on the torch_native reference (CPU, exact, atol 1e-6) and on both production
FLA kernels (fla_chunked, fla_fused_recurrent) on GPU:

Notes / follow-ups

  • A torch_native varlen reference path was added for numerical testing.
  • The qwen3_5 requirements was updated to use -r so the shared VLM requirements (flash-linear-attention) are actually installed.
  • All varlen behavior is gated behind cu_seqlens is not None; the non-varlen
    path is a no-op refactor (the extracted _local_map_conv reproduces the
    previous inline local_map, same placements/grad placements), so existing
    non-varlen Qwen3.5 behavior is unchanged. Note: Left to CI to confirm.
  • The Qwen3.5 feature tests run on the default SPMD backend, not full_dtensor,
    because qwen3_5/parallelize.py raises NotImplementedError under
    full_dtensor (TODO to lift the exclusion once supported).
  • The integration harness asserts process completion (exit code); the unit
    equivalence tests are what assert numerical correctness of the varlen path.

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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 26, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@tianyu-l
tianyu-l requested review from liangel-02 and shuhuayu June 26, 2026 20:07
"v": _kernel_plc,
"g": _kernel_plc,
"beta": _kernel_plc,
"xq_BLNK": _kernel_plc,

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.

while I am a fan of this naming style, is this okay in titan @tianyu-l ?

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.

Comment thread tests/integration_tests/features.py Resolved
def create_varlen_metadata_for_document(
positions: torch.Tensor,
*,
include_host_offsets: bool = False,

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.

@drisspg @liangel-02 please help review

"v": _kernel_plc,
"g": _kernel_plc,
"beta": _kernel_plc,
"xq_BLNK": _kernel_plc,

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.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
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(

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.

why do u need both cu_seqlens_cpu and cu_seqlens_host?

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.

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.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
cu_seqlens_host: tuple[int, ...],
cu_seqlens_cpu: torch.Tensor | None = None,
) -> torch.Tensor:
if x_BTD.is_cuda:

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.

match on backend instead?

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.

Addressed

Comment thread torchtitan/models/qwen3_5/model.py Outdated
return list(cu_seqlens_host)


def _require_cu_seqlens_host(

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.

maybe can just inline this?

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.

Yes, good call. Will do.

packed_cu_seqlens_host = (
tuple(packed_cu_seqlens.tolist()) if include_host_offsets else None
)

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.

when include_host_offsets=true can u remove the .item() call so that theres only one sync

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.

Yes, will do.

@Jeremalloch

Jeremalloch commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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 VarlenMetadata, but that failed the 8-GPU SelectiveAC smoke with Autograd not support dtype: Int during recompute. The current version keeps checkpointed metadata as Python host offsets and only builds the FLA CPU tensor locally at the DeltaNet boundary.

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.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
return out_BLNV.to(dtype)


def _torch_native_gated_delta_varlen(

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

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

@shuhuayu shuhuayu Jul 2, 2026 •

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.

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?

image

cc: @tianyu-l

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

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.

@shuhuayu I made the change in commit 3af330b.

One thing I kept in the model: the per-document F.conv1d fallback in _causal_conv1d_varlen, now gated only on not x.is_cuda, since FLA's causal conv is triton-only. Happy to move that too if you'd rather the model be FLA-only.

# 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).
@tianyu-l
tianyu-l requested a review from shuhuayu July 21, 2026 19:35
@Jeremalloch

Copy link
Copy Markdown
Contributor Author

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 ?

Comment thread tests/integration_tests/models.py Outdated
"--module qwen3_5 --config qwen35_debugmodel_varlen_attn",
"--parallelism.data_parallel_shard_degree=4",
"--training.steps 10",
"--comm.train_timeout_seconds 600",

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.

why do we have this?

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

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.

can we merge the two into one, testing FSDP and TP together?

@tianyu-l tianyu-l Jul 23, 2026 •

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.

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.

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.

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.

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.

OK, posted review feedback on #3895 and put by Claude aided stab at Qwen3.5 SPMD up on #3973 (which I see you've already tagged some reviewers on).

How do you envision merge order? Qwen3.5 spmd first, and then varlen following?

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 thinking of merging this first, then wait until @pianpwk comes back from vacation to rebase #3895 or review #3973

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.

Ok sounds good, thank you for the reviews!

Comment thread torchtitan/models/qwen3_5/model.py Outdated
v: torch.Tensor,
g: torch.Tensor,
beta: torch.Tensor,
def _torch_native_causal_conv1d_varlen(

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 you put _torch_native_gated_delta_varlen into test, why keeping torch native impl for conv1d here?

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.

Good call, I've moved that.

):
return create_varlen_metadata_for_document(
positions,
include_host_offsets=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.

maybe noob question, why for quadratic attention we didn't need to include_host_offsets?

@Jeremalloch Jeremalloch Jul 23, 2026 •

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.

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.

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.

- 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).
Comment on lines +361 to +363
# 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.

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.

):
return create_varlen_metadata_for_document(
positions,
include_host_offsets=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.

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

Thanks for the update! Can you mainly check whether the flex attention code path also has sample packing fixed?

Comment thread torchtitan/models/qwen3_5/model.py Resolved
B, L, _ = x_BLD.shape
cu_seqlens = None
cu_seqlens_cpu = None
if isinstance(attention_masks, VarlenMetadata):

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

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

Comment thread torchtitan/models/qwen3_5/model.py Resolved
Comment thread torchtitan/models/qwen3_5/model.py Resolved
Jeremalloch and others added 2 commits July 24, 2026 11:33
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.
@tianyu-l

Copy link
Copy Markdown
Contributor

Can you mainly check whether the flex attention code path also has sample packing fixed?

is this addressed?

@Jeremalloch

Copy link
Copy Markdown
Contributor Author

Can you mainly check whether the flex attention code path also has sample packing fixed?

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 cu_seqlens since linear attention scan needs boundary offsets to reset state). So the flex attention fix would logically fit either in this PR, or in a follow up.

@tianyu-l

Copy link
Copy Markdown
Contributor

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.

Is the issue that

  • when varlen backend is used for quadratic, it reads cu_seqlen info; this PR makes sure the GDN module is also reading that info
  • but when flex is used for quadratic, the GDN module is not reading that info, thus doing wrong math similar how varlen path was behaving for GDN module before this PR

If that's the case, we can fix Flex in another PR

@Jeremalloch

Jeremalloch commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

Is the issue that

  • when varlen backend is used for quadratic, it reads cu_seqlen info; this PR makes sure the GDN module is also reading that info
  • but when flex is used for quadratic, the GDN module is not reading that info, thus doing wrong math similar how varlen path was behaving for GDN module before this PR

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

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

LGTM!

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

https://github.com/pytorch/torchtitan/actions/runs/30119302889/job/89620841191?pr=3801

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?

@Jeremalloch

Copy link
Copy Markdown
Contributor Author

https://github.com/pytorch/torchtitan/actions/runs/30119302889/job/89620841191?pr=3801

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).
https://github.com/pytorch/torchtitan/actions/runs/30117511153/job/89561745203#step:17:1623

The root cause appears to be using an unpinned version of pytorch nightly.
The last passing run for this job used dev20260723, but from July 24th onward the debug losses shift.

@shuhuayu

Copy link
Copy Markdown
Contributor

thx for the clarification. i reran the test and it passed, so i guess this is related to some changes from pytorch nightly side.

@Jeremalloch

Copy link
Copy Markdown
Contributor Author

Great, are we good to merge once @tianyu-l removes the request for changes?

@tianyu-l
tianyu-l merged commit d24ae40 into pytorch:main Jul 27, 2026
19 of 21 checks passed
tianyu-l pushed a commit that referenced this pull request Aug 13, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants