Skip to content

[qwen3_5] Reset GatedDeltaNet state at document boundaries under flex attention - #3984

Merged
tianyu-l merged 7 commits into
pytorch:mainfrom
Jeremalloch:jm/qwen35-flex-gdn-packing
Aug 13, 2026
Merged

tianyu-l merged 7 commits into
pytorch:mainfrom
Jeremalloch:jm/qwen35-flex-gdn-packing

Conversation

@Jeremalloch

@Jeremalloch Jeremalloch commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

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-Always Pre-Split Microbatches for PP #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 Always Pre-Split Microbatches for PP #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 Always Pre-Split Microbatches for PP #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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 25, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

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

@Jeremalloch Jeremalloch changed the title [qwen3_5] Reset GatedDeltaNet state at document boundaries under flex attention [DO NOT REVIEW] [qwen3_5] Reset GatedDeltaNet state at document boundaries under flex attention Jul 25, 2026
@tianyu-l
tianyu-l requested a review from shuhuayu July 25, 2026 00:26
@Jeremalloch
Jeremalloch force-pushed the jm/qwen35-flex-gdn-packing branch from 4cd69e4 to 305be8d Compare July 27, 2026 15:24
@Jeremalloch
Jeremalloch marked this pull request as ready for review July 27, 2026 15:24
@Jeremalloch Jeremalloch changed the title [DO NOT REVIEW] [qwen3_5] Reset GatedDeltaNet state at document boundaries under flex attention [qwen3_5] Reset GatedDeltaNet state at document boundaries under flex attention Jul 27, 2026
@Jeremalloch

Copy link
Copy Markdown
Contributor Author

@shuhuayu Do you mind giving this a look now? It's ready for review

@shuhuayu

Copy link
Copy Markdown
Contributor

@shuhuayu Do you mind giving this a look now? It's ready for review

thanks. I will do my review by the end of tomorrow.

@tianyu-l
tianyu-l requested a review from jinsooihm July 30, 2026 01:01

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

the varlen backend under PP still carries the full batch's VarlenMetadata through microbatch splitting.

PP is going to be supported in #3856

Comment thread torchtitan/models/qwen3_5/model.py Outdated
attention_masks = Qwen35AttentionMasks(
full_attention=attention_masks.full_attention,
deltanet=create_varlen_metadata_for_document(
attention_masks.deltanet_positions,

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.

positions is available in the args of this function -- why would you need to separately pass it in?

@Jeremalloch Jeremalloch Jul 31, 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.

Fair, but moot point now that #3856 will supercede this part of the code. After it lands, get_attention_masks builds the VarlenMetadata directly, so nothing will be converted in forward anymore.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
if isinstance(attention_masks, Qwen35AttentionMaskInputs):
attention_masks = Qwen35AttentionMasks(
full_attention=attention_masks.full_attention,
deltanet=create_varlen_metadata_for_document(

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 not create from outside the model? I thought we are doing that when flex is not used. Can we just pass both in, when flex is used?

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.

Isn't the problem that constructing VarlenMetadata outside does not behave nicely with PP microbatching? I think after #3856 , you can just make get_attention_masks to always return VarlenMetadata and optionally BlockMask if the backend is flex.

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.

traditional attention models (e.g. the ancient llama3) doesn't need varlen metadata when Flex is used?

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 was referring to the get_attention_masks in qwen35.

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, @jinsooihm is correct, constructing VarlenMetadata in get_attention_masks didn't survive the schedule-side microbatch split.

Since #3856 moves the split to the trainer and builds masks per microbatch, I'll switch the qwen3.5 override to return the BlockMask paired with the VarlenMetadata directly and removed the indirection.

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.

with #3856, we still need to pass a mask with two fields, the blockmask for full attention, and varlenmetadata for gdn, but the creation of this attetion_mask is moved to get_attention_masks.

i think after that we can remove type checks like if isinstance(attention_masks, Qwen35AttentionMasks):, let get_attention_masks return Qwen35AttentionMasks.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
GatedDeltaBackend = Literal["fla_chunked", "fla_fused_recurrent"]


class Qwen35AttentionMaskInputs(NamedTuple):

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 don't think we need this

Comment thread torchtitan/models/qwen3_5/model.py Outdated
class Qwen35AttentionMasks(NamedTuple):
"""Per-consumer masks resolved for one model-forward microbatch."""

full_attention: AttentionMasksType

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.

you mean quadratic_attention?

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 was mimicking convention elsewhere in the repo, but since Qwen3.5 has linear + quadratic attention, I think you're right about naming convention.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
)
return super().get_attention_masks(positions)
full_attention_masks = super().get_attention_masks(positions)
if full_attention_masks is 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.

It seems to me that you may as well not have this if check and just always return Qwen35AttentionMaskInputs with possibly `full_attention=None.

Is the problem here that get_attention_masks gets never called in the trainer if the model does not have full attention layers?

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, exactly, the trainer only builds masks when model_config.first_attention is Flex/Varlen, so for a config with no full-attention layers get_attention_masks is never called and this branch is effectively dead code.

I'm refactoring now with the PP PR in mind.

@Jeremalloch

Jeremalloch commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you all for your reviews.

I'll wait for #3856 to land, and then rebase on top of that to incorporate it's improvements.

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

is this the case #3856 makes mask-building happen after the microbatch split, then we can remove this type check, and the one above.

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.

Yup, I'm in alignment. I was unaware of #3856 but I'll wait for it to land, before rebasing & fixing things up.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
self,
positions: torch.Tensor,
) -> AttentionMasksType | None:
) -> AttentionMasksType | Qwen35AttentionMasks | 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.

Maybe I am missing something, but why can't we just always return Qwen35AttentionMasks instead of having an option of returning AttentionMasksType?

@tianyu-l tianyu-l Aug 1, 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.

no matter which one we do, I feel typing would complain (due to inheritance)? Proper fix should be making this return type generic

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.

@jinsooihm fair call, I did that in the latestt commit (cf5d4c9)

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.

no matter which one we do, I feel typing would complain (due to inheritance)? Proper fix should be making this return type generic

Yeah, that's fair. I'm going to leave it out of scope here since it touches the common Decoder class though.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
Comment on lines +372 to +378
if attention_masks is not None:
varlen_metadata = attention_masks.deltanet
# FLA caches varlen index helpers by tensor identity. A fresh
# tensor ensures forward and activation-checkpoint recompute both
# execute the helpers instead of taking different cache paths.
cu_seqlens = varlen_metadata.cu_seq_q.clone()
cu_seqlens_host = varlen_metadata.cu_seq_q_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.

is this problem only showing up with interleaving pp? i am quite confused with how fla's tensor_cache.

@Jeremalloch Jeremalloch Aug 7, 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.

This happens to every pipeline schedule, as they all run some other microbatch's forward between microbatch i's forward and its backward (even 1F1B, which does F_i, B_j, F_k, ..., B_i).

The failure appears when more distinct microbatch cu_seqlens objects are first-touched between a microbatch's forward and its SAC recompute than FLA's cache holds (and the cache size is set to 4)

More Detailed Explanation

FLA wraps its varlen index helpers (prepare_lens, prepare_chunk_indices) in tensor_cache, which is a single-entry cache (in FLA 0.5.0) a deque bounded with length 4 (in FLA >= 0.5.1), keyed by argument object identity (a is b see here).

Within one microbatch's forward, all DeltaNet layers share one cu_seq_q object, so the first layer computes the helpers and the rest are cache hits dispatching zero ops. Selective AC pairs saved-op invocations by index between forward and recompute, so both must take the same hit/miss path. Without PP nothing runs in between and the entry survives (a recompute hitting more than its forward is tolerated). With PP, once the in-flight microbatches exceed the cache capacity, microbatch A's entry is evicted before its recompute, the recompute dispatches ops the forward skipped, and the ledger misaligns:

RuntimeError: aten.slice.Tensor invocation index 4 encountered during backward but not found in storage.

A Couple Solution Approaches

The tensor clone makes forward and recompute take the cache miss path unconditionally. This has the cost of re-running a tiny per-document index computation per layer.

Alternatives would be FLA_DISABLE_TENSOR_CACHE=1 (which accomplishes the same thing as this clone using a global env config) or an upstream FLA change to key the cache on value rather than identity.
I could make more than 4 microbatches + varlen unsupported behaviour for Qwen 3.5 and drop the clone?
The issue is that torchtitan has a great deal of PP schedule flexibility, safe bound depends on the schedule (not just the number of microbatches), and on FLA internals, which have already changed once.

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 the .clone() suffices to solve the problem here, let's not bother alter the behavior of fla internal.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
Comment on lines +747 to +749
# TODO: DeltaNet state then runs across document boundaries in
# pure GatedDeltaNet models under both flex and varlen backends.
return 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.

this causes numerical bug, right?

Comment thread torchtitan/models/qwen3_5/model.py Outdated
self.spatial_merge_size = config.vision_encoder.spatial_merge_size

def get_attention_masks(
def get_attention_masks( # pyrefly: ignore [bad-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.

this looks a bandaid solution, I think at least we could

Comment thread torchtitan/models/qwen3_5/model.py Outdated
Comment on lines +727 to +728
attn_config = self.config.first_attention
if attn_config is not None and isinstance(
attn_config.inner_attention, VarlenAttention.Config
):
# Host offsets are a GatedDeltaNet-only need: the FLA varlen
# kernels take cu_seqlens as a CPU tensor to size their launches,
# whereas quadratic attention (torch.nn.attention.varlen) consumes
# the device tensor directly. They are stored as Python ints so
# SelectiveAC checkpoint metadata stays tensor-free.
return create_varlen_metadata_for_document(
positions,
include_host_offsets=True,
)
return super().get_attention_masks(positions)
assert attn_config is not None # enforced in __init__

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 don't think we need this

Comment thread torchtitan/models/qwen3_5/model.py Outdated
Comment on lines +742 to +748
if isinstance(attn_config.inner_attention, VarlenAttention.Config):
# Under varlen both consumers read the same document offsets.
masks["quadratic_attention"] = deltanet_metadata
else:
quadratic_masks = super().get_attention_masks(positions)
assert isinstance(quadratic_masks, BlockMask)
masks["quadratic_attention"] = quadratic_masks

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 there's no full attention module, just fill None?

Comment thread torchtitan/models/qwen3_5/model.py Outdated
attention_masks: AttentionMasksType | None,
positions: torch.Tensor | None = None,
) -> torch.Tensor:
if isinstance(attention_masks, dict):

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.

it should always be a dict

cu_seqlens_cpu = None
if isinstance(attention_masks, VarlenMetadata):
cu_seqlens = attention_masks.cu_seq_q
if attention_masks is not 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.

assert not None?

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.

None is a legal value here, not an error case. It is the documented "no packing boundaries" case: the recurrence runs each batch row as one continuous stream.

The RL inference path uses this contract. The TitanRL vLLM wrapper calls every layer with attention_masks=None. #3957 builds hybrid Qwen3.5 on that path. Its GDN adapter tracks request boundaries with vLLM paged state, not with varlen offsets. The fla_fused_recurrent inference backend exists for the same path. The per-document reference forwards in the CPU unit tests also use the None default.

Training cannot pass None for packed data, because get_attention_masks always fills the "deltanet" entry. An assert here fires only on the legitimate inference path.

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 would suggest update the comment here to be direct with the reason to use .clone(). The bug only shows up when pp + sac, but the current comments only mentions ac.

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.

merging as didn't want to wait for longer, let's address this later

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.

Thank's for merging @tianyu-l sorry for the delay in responding to the penultimate round of feedback

@tianyu-l

Copy link
Copy Markdown
Contributor

Hey @Jeremalloch, could you rebase and address final comments so that we can merge this PR? It's blocking several others. Thanks!

A BlockMask only document-isolates the quadratic full-attention layers
(1 in 4); GatedDeltaNet is a recurrence and needs document offsets, so
under the flex backend its conv and recurrent state previously ran
across packing boundaries as one continuous stream (pre-existing on
main -- DeltaNet took no mask argument at all).

Qwen35Model.get_attention_masks now pairs the flex BlockMask with the
same VarlenMetadata the varlen backend uses, in a Qwen35AttentionMasks
NamedTuple; each attention module picks its slice in forward. The
varlen backend path is unchanged. Note this intentionally changes flex
numerics for packed data: DeltaNet state now resets where it previously
bled across documents.

Pipeline stages holding only GatedDeltaNet blocks still get no masks
(pre-existing, now documented with a TODO).

New CPU unit tests cover the composite construction/routing and that
DeltaNet under the composite matches stitched per-document forwards.
BlockMask is core torch and always importable, so move it out of the
try/except; the guard exists only because torchtitan.models.qwen3_5
imports the triton/CUDA-only FLA kernels at module scope. Add a comment
saying so.
Under pipeline parallelism the schedule splits kwargs into microbatches
along the batch axis. The flex-backend composite mask carried a prebuilt
VarlenMetadata whose flattened cu_seqlens (and Python-tuple host
offsets) cannot be split that way, so every microbatch would see the
full batch's offsets. get_attention_masks now returns
Qwen35AttentionMaskInputs holding the BlockMask and the batch-aligned
(B, L) document positions; the scheduler splits both on dim 0 and
Qwen35Model.forward builds each microbatch's VarlenMetadata after the
split.

GatedDeltaNet.forward also clones cu_seq_q once per invocation. FLA's
tensor_cache is a single-entry cache keyed by tensor identity; under
pipeline parallelism another microbatch's forward replaces the entry
between a microbatch's forward and its selective-AC recompute, so the
recompute runs the varlen index helpers (fla prepare_lens et al.) that
the original forward skipped as cache hits. Selective AC pairs saved-op
invocations by index, and the extra ops shift the ledger:

  RuntimeError: aten.slice.Tensor invocation index 4 encountered during
  backward but not found in storage.

A fresh tensor per forward gives forward and recompute the same
cache-miss path. Without PP the divergence is benign (a recompute can
only hit where its forward missed), which is why non-PP varlen SAC
never tripped this.

Also rewords the no-masks comment: pipeline stages keep the whole-model
config (_split_module deep-copies and only prunes modules), so the None
branch is about model configs without full-attention layers, not about
which layers a stage holds.

Validated on H100: deltanet unit suite 7 passed (including a CPU test
pinning the fresh-cache-key invariant, red without the clone, and a
pipeline-splitting test driving
torch.distributed.pipelining.microbatch.split_args_kwargs_into_chunks);
flex dp2/tp2 + SAC and varlen dp2/tp2 + SAC 10-step smokes green; the
qwen3_5_moe_fsdp+tp+ep+pp CI entry on 8 GPUs fails step-1 backward with
the ledger error above without the clone and completes 10/10 steps
with it.
Per review: drop Qwen35AttentionMaskInputs and the in-forward
conversion. Qwen35Model.get_attention_masks now returns the flex
BlockMask paired directly with the VarlenMetadata, built in place, and
the composite field is renamed full_attention -> quadratic_attention.

This relies on pytorch#3856 (the trainer pre-splits pipeline microbatches and
builds masks per microbatch): before it lands, a prebuilt
VarlenMetadata does not survive the schedule-side kwarg split, so this
must land after pytorch#3856. The cu_seq_q clone in GatedDeltaNet.forward
stays load-bearing either way: microbatches still interleave under
1F1B, so FLA's single-entry identity cache is still evicted between a
microbatch's forward and its selective-AC recompute.
Per review (shuhuayu, jinsooihm): Qwen35Model.get_attention_masks now
returns Qwen35AttentionMasks under both backends -- under varlen both
fields share one VarlenMetadata -- so the attention modules take
Qwen35AttentionMasks | None directly and the isinstance dispatch in
GatedDeltaNet.forward and Qwen35Attention.forward goes away.

The get_attention_masks return-type override still needs a pyrefly
bad-override ignore; making Decoder's mask type generic is the proper
fix (tianyu-l) and is left as a follow-up.
Per review: replace the Qwen35AttentionMasks NamedTuple with the
gpt_oss-style flat mask dict. Qwen35Model.get_attention_masks returns
{"quadratic_attention": BlockMask (flex) or VarlenMetadata (varlen),
"deltanet": VarlenMetadata}; each transformer block picks its entry by
attn_mask_key at init, so GatedDeltaNet and Qwen35Attention keep their
natural signatures and no per-module mask dispatch remains.

AttentionMasksType's mapping arm widens to
Mapping[str, BlockMask | VarlenMetadata]: Mapping (not dict) keeps the
value type covariant so existing dict[str, BlockMask] producers
(gpt_oss) still typecheck, and the qwen3.5 override no longer needs a
bad-override suppression. Context-parallel mask sharding gains an
explicit ValueError for non-BlockMask mask-dict values (varlen document
metadata is not shardable; CP+varlen was already unsupported).

Qwen35Model now raises ValueError at construction for configs with no
full-attention layer: the trainer only builds masks when the config has
a quadratic attention layer, and without masks GatedDeltaNet would
silently run across packed-document boundaries (review question on the
old TODO branch).
Per review: Qwen35Model no longer raises at construction for configs
without a full-attention layer. get_attention_masks always emits both
keys, with quadratic_attention set to None when the config has no
quadratic layer, and AttentionMasksType's mapping values gain | None to
express unused masks. The transformer block indexes the mask dict
unconditionally (it is always a dict or None) via the
Qwen35AttentionMaskDict alias.

A maskless (None) GatedDeltaNet forward stays legal: the TitanRL
inference wrapper calls every layer with attention_masks=None on a
single continuous sequence (experiments/rl/models/vllm_wrapper.py), and
the per-document reference forwards in the unit tests rely on the same
contract. Training always receives document offsets because
get_attention_masks fills the deltanet entry unconditionally.

Also: context-parallel mask sharding error message no longer blames
varlen metadata when the offending value is something else; new unit
coverage for the deltanet-only mask dict.
@Jeremalloch
Jeremalloch force-pushed the jm/qwen35-flex-gdn-packing branch from 2801fc3 to 9366180 Compare August 13, 2026 04:41
@Jeremalloch

Copy link
Copy Markdown
Contributor Author

Hey @Jeremalloch, could you rebase and address final comments so that we can merge this PR? It's blocking several others. Thanks!

Addressed @tianyu-l

cu_seqlens_cpu = None
if isinstance(attention_masks, VarlenMetadata):
cu_seqlens = attention_masks.cu_seq_q
if attention_masks is not 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.

i would suggest update the comment here to be direct with the reason to use .clone(). The bug only shows up when pp + sac, but the current comments only mentions ac.

Comment thread torchtitan/models/qwen3_5/model.py Outdated
Comment on lines +372 to +378
if attention_masks is not None:
varlen_metadata = attention_masks.deltanet
# FLA caches varlen index helpers by tensor identity. A fresh
# tensor ensures forward and activation-checkpoint recompute both
# execute the helpers instead of taking different cache paths.
cu_seqlens = varlen_metadata.cu_seq_q.clone()
cu_seqlens_host = varlen_metadata.cu_seq_q_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.

i think the .clone() suffices to solve the problem here, let's not bother alter the behavior of fla internal.

@tianyu-l
tianyu-l merged commit f4e7818 into pytorch:main Aug 13, 2026
19 checks passed
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.

4 participants