Repository navigation
[qwen3_5] Reset GatedDeltaNet state at document boundaries under flex attention - #3984
Conversation
|
|
4cd69e4 to
305be8d
Compare
|
@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. |
| attention_masks = Qwen35AttentionMasks( | ||
| full_attention=attention_masks.full_attention, | ||
| deltanet=create_varlen_metadata_for_document( | ||
| attention_masks.deltanet_positions, |
There was a problem hiding this comment.
positions is available in the args of this function -- why would you need to separately pass it in?
There was a problem hiding this comment.
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.
| if isinstance(attention_masks, Qwen35AttentionMaskInputs): | ||
| attention_masks = Qwen35AttentionMasks( | ||
| full_attention=attention_masks.full_attention, | ||
| deltanet=create_varlen_metadata_for_document( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
traditional attention models (e.g. the ancient llama3) doesn't need varlen metadata when Flex is used?
There was a problem hiding this comment.
I was referring to the get_attention_masks in qwen35.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| GatedDeltaBackend = Literal["fla_chunked", "fla_fused_recurrent"] | ||
|
|
||
|
|
||
| class Qwen35AttentionMaskInputs(NamedTuple): |
There was a problem hiding this comment.
I don't think we need this
| class Qwen35AttentionMasks(NamedTuple): | ||
| """Per-consumer masks resolved for one model-forward microbatch.""" | ||
|
|
||
| full_attention: AttentionMasksType |
There was a problem hiding this comment.
you mean quadratic_attention?
There was a problem hiding this comment.
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.
| ) | ||
| return super().get_attention_masks(positions) | ||
| full_attention_masks = super().get_attention_masks(positions) | ||
| if full_attention_masks is None: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
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. |
| attention_masks = attention_masks.deltanet | ||
| cu_seqlens = None | ||
| cu_seqlens_cpu = None | ||
| if isinstance(attention_masks, VarlenMetadata): |
There was a problem hiding this comment.
is this the case #3856 makes mask-building happen after the microbatch split, then we can remove this type check, and the one above.
There was a problem hiding this comment.
Yup, I'm in alignment. I was unaware of #3856 but I'll wait for it to land, before rebasing & fixing things up.
| self, | ||
| positions: torch.Tensor, | ||
| ) -> AttentionMasksType | None: | ||
| ) -> AttentionMasksType | Qwen35AttentionMasks | None: |
There was a problem hiding this comment.
Maybe I am missing something, but why can't we just always return Qwen35AttentionMasks instead of having an option of returning AttentionMasksType?
There was a problem hiding this comment.
no matter which one we do, I feel typing would complain (due to inheritance)? Proper fix should be making this return type generic
There was a problem hiding this comment.
@jinsooihm fair call, I did that in the latestt commit (cf5d4c9)
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
is this problem only showing up with interleaving pp? i am quite confused with how fla's tensor_cache.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
i think the .clone() suffices to solve the problem here, let's not bother alter the behavior of fla internal.
| # TODO: DeltaNet state then runs across document boundaries in | ||
| # pure GatedDeltaNet models under both flex and varlen backends. | ||
| return None |
There was a problem hiding this comment.
this causes numerical bug, right?
| self.spatial_merge_size = config.vision_encoder.spatial_merge_size | ||
|
|
||
| def get_attention_masks( | ||
| def get_attention_masks( # pyrefly: ignore [bad-override] |
There was a problem hiding this comment.
this looks a bandaid solution, I think at least we could
- make the return type a flat dictionary, similar to https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/gpt_oss/model.py#L232
- fill in masks that we need, depending on if Flex/Varlen/Deltanet is in the model part.
| 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__ |
There was a problem hiding this comment.
I don't think we need this
| 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 |
There was a problem hiding this comment.
if there's no full attention module, just fill None?
| attention_masks: AttentionMasksType | None, | ||
| positions: torch.Tensor | None = None, | ||
| ) -> torch.Tensor: | ||
| if isinstance(attention_masks, dict): |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
merging as didn't want to wait for longer, let's address this later
There was a problem hiding this comment.
Thank's for merging @tianyu-l sorry for the delay in responding to the penultimate round of feedback
|
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.
2801fc3 to
9366180
Compare
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: |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
i think the .clone() suffices to solve the problem here, let's not bother alter the behavior of fla internal.
Follow-up to #3801 (merged), split out per @tianyu-l's review there.
Summary
Under the flex attention backend, the
BlockMaskdocument-isolates only the quadratic full-attention layers (1 in 4).GatedDeltaNetis 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_masksreturns a flat mask dict (the gpt_oss pattern):{"quadratic_attention": BlockMask (flex) or VarlenMetadata (varlen), "deltanet": VarlenMetadata}; each transformer block picks its entry byattn_mask_keyset at init, soGatedDeltaNetandQwen35Attentionkeep their natural signatures with no per-module mask dispatch.AttentionMasksType's mapping arm widens toMapping[str, BlockMask | VarlenMetadata | None](Mappingkeeps value types covariant so gpt_oss'sdict[str, BlockMask]still typechecks, and aNonevalue marks an unused mask), which removes thebad-overridesuppression. For configs with no full-attention layer the dict fillsquadratic_attention: None; a maskless (None) GatedDeltaNet forward stays legal: the TitanRL inference wrapper's forward calls every layer withattention_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.forwardalso clonescu_seq_qonce per invocation. FLA'stensor_cacheis 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: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_attentionis Flex/Varlen).Testing
VarlenMetadataunder varlen); GatedDeltaNet under the composite matches stitched per-document forwards; and a cache-key invariant test (freshcu_seqlensper DeltaNet forward) that is red without the clone. Deltanet suite: 6 passed on one H100.qwen3_5_moe_fsdp+tp+ep+ppCI entry shape (pp2 / dp_shard2 / tp2 / ep4, selective AC), on the post-Always Pre-Split Microbatches for PP #3856 pre-split flow withtorch==2.14.0.dev20260731+cu130: without the clone, step-1 backward fails with the ledger error above; with it, 10/10 steps complete.qwen3_5_fsdp+tp+varlen_attn+per_op_sacCI entry still passes 10 steps.step(arg_mbs=...)API that Always Pre-Split Microbatches for PP #3856 relies on landed intorch==2.14.0.dev20260731+cu130, but plainpip install --pre torch torchvisioncurrently resolves torch back todev20260729(torchvisiondev20260731pins it), which fails all PP entries withExpecting N arg_mbs but got 1-- the current main 8-GPU CI failure. The PP runs above force the July 31 torch wheel.