Skip to content

Jagged Arbitrary Masked Self Attention support - #339

Merged
shijieliu merged 14 commits into
NVIDIA:mainfrom
z52527:fea-JaggedTransformerBlock
May 8, 2026
Merged

shijieliu merged 14 commits into
NVIDIA:mainfrom
z52527:fea-JaggedTransformerBlock

Conversation

@z52527

@z52527 z52527 commented Mar 31, 2026 •

Copy link
Copy Markdown
Collaborator

Resolves #276

Summary

Replace Megatron-Core's TransformerBlock (padded dense + DotProductAttention) with a JaggedTransformerBlock that flattens all batch sequences into a single sequence (B=1) and uses jiayus's Flash Attention with arbitrary_func mask encoding. Zero padding, block sparsity skips cross-batch blocks.

Both backends are preserved via use_jagged_flash_attn flag; mask / arbitrary_func is caller-provided, not built inside the model.

Architecture

Caller builds arbitrary_func (or attention_mask)
         │
         ▼
SIDGRModel.forward / generate
         │
         ▼
decoder_step ── routes by use_jagged_flash_attn ──┐
         │                                         │
    FA path                                   mcore path
         │                                         │
JaggedTransformerBlock                    TransformerBlock
  unsqueeze(0) → [1,T,D]                pad → [S,B,D]
  flash_attn_func(arbitrary=True)        DotProductAttention
  squeeze(0) → [T,D]                    unpad → jagged

Changed Files

File What Changed
model/jagged_flash_attn_block.py New. JaggedGPTLayer (FA kernel per layer), JaggedFlashAttnBlock (layer stack), JaggedTransformerBlock (wrapper: unsqueeze→FA→squeeze)
model/attention_mask.py New functions. dense_mask_to_arbitrary_func (per-batch dense→interval encoding), build_jagged_causal_arbitrary_func (vectorized, offsets→flattened causal arbitrary_func)
model/gpt_model.py SIDGRDecoder: use_jagged_flash_attn flag selects JaggedTransformerBlock or mcore TransformerBlock. decoder_step: pure routing, zero mask construction. forward/generate: caller passes arbitrary_func or attention_mask
model/__init__.py get_sid_gr_model: propagate use_jagged_flash_attn flag
tests/test_jagged_flash_attn_block.py New. Smoke / correctness / backward tests for JaggedGPTLayer; FA-vs-reference comparison for JaggedTransformerBlock; batch isolation test
tests/test_dense_mask_to_arbitrary_func.py New. Roundtrip tests for dense_mask_to_arbitrary_func; flattened jagged causal / target-grouped tests; dense_mask_to_jagged_arbitrary_func as test utility

Test Plan

  • pytest examples/sid_gr/tests/test_dense_mask_to_arbitrary_func.py — arbitrary_func encoding roundtrip
  • pytest examples/sid_gr/tests/test_jagged_flash_attn_block.py — FA layer correctness, JaggedTransformerBlock vs padded reference, batch isolation
  • mypy examples/sid_gr/model/gpt_model.py — type check clean

@z52527
z52527 requested a review from JacoCheung March 31, 2026 09:28
@greptile-apps

greptile-apps Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces JaggedTransformerBlock as an alternative decoder backend that flattens all batch sequences into a single B=1 sequence and applies Flash Attention with an interval-based arbitrary_func mask, replacing Megatron-Core's padded DotProductAttention. Both backends are preserved and selected via a use_jagged_flash_attn flag.

  • New JaggedFlashAttnBlock / JaggedGPTLayer (jagged_flash_attn_block.py): self-contained pre-norm GPT stack with per-layer FA kernel, block-sparsity construction, and dtype auto-cast for fp16/bf16 compliance.
  • New mask utilities (attention_mask.py): dense_mask_to_arbitrary_func converts a dense bool mask to FA interval encoding; build_jagged_causal_arbitrary_func efficiently builds the flattened causal mask in a fully vectorized manner.
  • Dual-backend routing (gpt_model.py): decoder_step now owns mask-construction fallback for both paths; forward and generate accept pre-built masks from callers.

Confidence Score: 3/5

The core routing logic in decoder_step has a gap: when attention_mask is provided to an FA-configured model, the fallback is bypassed and a bare AssertionError fires, making the documented contract incorrect.

The decoder_step routing has a gap where providing attention_mask to an FA-configured model bypasses the fallback and crashes with an uninformative assertion. Combined with unresolved issues from prior rounds (random weights in lazy-init, per-step mask rebuild in generation, beam-branch isolation, unpinned Dockerfile dependency), the change is not ready to merge without targeted fixes.

examples/sid_gr/model/gpt_model.py (decoder_step routing), examples/sid_gr/model/attention_mask.py (dead code / missing seqlen assertion), docker/Dockerfile (unpinned branch)

Important Files Changed

Filename Overview
examples/sid_gr/model/gpt_model.py Major refactor of SIDGRDecoder to support dual-backend (JaggedFA / mcore) routing via decoder_step; contains a P1 footgun where providing attention_mask to an FA-configured model bypasses the fallback and crashes with a bare AssertionError.
examples/sid_gr/model/attention_mask.py Adds dense_mask_to_arbitrary_func and build_jagged_causal_arbitrary_func; has dead-code first n_func block (previously flagged), an unreachable parity check in surviving code, and missing seqlen/N consistency assertion.
examples/sid_gr/model/jagged_flash_attn_block.py New self-contained GPT transformer block using jiayus Flash Attention; deferred flash_attn import inside forward (previously flagged); block-sparsity construction and per-layer pre-norm architecture look correct.
docker/Dockerfile Adds flash-attention clone from unpinned arbitrary_mask branch; non-reproducible builds flagged in a previous thread.
examples/sid_gr/model/init.py Propagates use_jagged_flash_attn flag (default False) through get_sid_gr_model; straightforward plumbing change.
examples/sid_gr/tests/test_jagged_flash_attn_block.py New tests covering smoke, causal correctness vs PyTorch SDPA reference, backward pass, and batch isolation; guarded by HAS_FLASH_ATTN to skip gracefully without the dependency.
examples/sid_gr/tests/test_dense_mask_to_arbitrary_func.py New roundtrip tests for dense_mask_to_arbitrary_func and build_jagged_causal_arbitrary_func; test utility dense_mask_to_jagged_arbitrary_func uses a simpler all-pairs encoding that intentionally differs from the production function.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant SIDGRModel
    participant decoder_step
    participant SIDGRDecoder
    participant JaggedTransformerBlock
    participant TransformerBlock

    Caller->>SIDGRModel: "forward(batch, arbitrary_func=None, attention_mask=None)"
    SIDGRModel->>decoder_step: "input_hidden_states, input_offsets, arbitrary_func=None"
    alt both masks None
        decoder_step->>decoder_step: build_jagged_causal_arbitrary_func(offsets) [FA path]
        decoder_step->>decoder_step: padded_causal_mask_with_optional_bos(offsets) [mcore path]
    else "attention_mask provided but arbitrary_func=None on FA path"
        decoder_step->>decoder_step: assert arbitrary_func is not None fires
    end
    alt "use_jagged_flash_attn=True"
        decoder_step->>SIDGRDecoder: forward(hidden_states, arbitrary_func)
        SIDGRDecoder->>JaggedTransformerBlock: forward([total_tokens,D], arbitrary_func)
        JaggedTransformerBlock->>JaggedTransformerBlock: unsqueeze(0) to [1,T,D]
        JaggedTransformerBlock->>JaggedTransformerBlock: "flash_attn_func(arbitrary=True)"
        JaggedTransformerBlock->>JaggedTransformerBlock: squeeze(0) to [T,D]
        JaggedTransformerBlock-->>SIDGRDecoder: [total_tokens, D]
    else "use_jagged_flash_attn=False"
        decoder_step->>SIDGRDecoder: forward(hidden_states, attention_mask, offsets, max_seqlen)
        SIDGRDecoder->>SIDGRDecoder: jagged to dense [S,B,D]
        SIDGRDecoder->>TransformerBlock: forward(padded, attention_mask)
        TransformerBlock-->>SIDGRDecoder: padded output
        SIDGRDecoder->>SIDGRDecoder: dense to jagged [total_tokens,D]
    end
    decoder_step-->>SIDGRModel: jagged output hidden states
Loading

Reviews (11): Last reviewed commit: "Merge branch 'main' into fea-JaggedTrans..." | Re-trigger Greptile

Comment thread examples/sid_gr/model/gpt_model.py Resolved
Comment thread examples/sid_gr/model/attention_mask.py Resolved
Comment thread examples/sid_gr/model/gpt_model.py Resolved
Comment thread examples/sid_gr/model/gpt_model.py Resolved
Comment thread examples/sid_gr/model/gpt_model.py Resolved
Comment thread examples/sid_gr/model/attention_mask.py Resolved
@shijieliu

Copy link
Copy Markdown
Collaborator

update arbitary mask FA in 3rd party module

Comment thread examples/sid_gr/model/gpt_model.py Resolved
Comment thread docker/Dockerfile Resolved
@shijieliu

Copy link
Copy Markdown
Collaborator

/build

1 similar comment
@JacoCheung

Copy link
Copy Markdown
Collaborator

/build

@JacoCheung

JacoCheung commented Apr 28, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #49662233 -- failed

Job Status Log
pre_check ❌ failed view
train_build ✅ success view
inference_build ✅ success view
tritonserver_build ✅ success view
build_whl ❌ failed view
dynamicemb_test_fwd_bwd_8gpus ❌ failed view
dynamicemb_test_load_dump_8gpus ✅ success view
unit_test_1gpu_a100 ✅ success view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ❌ failed view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ✅ success view
inference_test_1gpu ✅ success view

Result: 9/14 jobs passed

View full pipeline

@z52527

z52527 commented Apr 28, 2026

Copy link
Copy Markdown
Collaborator Author

track CI here

@shijieliu
shijieliu merged commit ec052b4 into NVIDIA:main May 8, 2026
Comment on lines +554 to 578
if attention_mask is None and arbitrary_func is None:
if self.decoder.use_jagged_flash_attn:
total_tokens = int(input_offsets[-1].item())
arbitrary_func = build_jagged_causal_arbitrary_func(
input_offsets, total_tokens
)
else:
add_bos = (
self.add_bos_to_history_for_training
if default_mask_add_bos_to_history is None
else default_mask_add_bos_to_history
)
attention_mask = padded_causal_mask_with_optional_bos(
input_offsets,
input_max_seqlen,
add_bos_to_history=add_bos_to_history,
add_bos_to_history=add_bos,
bos_interval=self._num_hierarchies,
)
else:
# THD still needs batch dimension
# we need to unsqueeze the hidden states to [T, 1, hidden_size] and unsqueeze back after decoder
assert input_hidden_states.dim() == 2, "input_hidden_states should be 2D"
decoder_input_hidden_states = input_hidden_states.unsqueeze(1)
attention_mask = None
packed_seq_params = to_packed_seq_params(
input_offsets,
input_max_seqlen,

if self.decoder.use_jagged_flash_attn:
assert arbitrary_func is not None
return self.decoder(
hidden_states=input_hidden_states,
arbitrary_func=arbitrary_func,
)

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.

P1 Wrong mask type silently skips fallback and crashes

When use_jagged_flash_attn=True and a caller passes attention_mask (without arbitrary_func), the guard at line 554 is not entered (because attention_mask is not None). No fallback is built, and the assert arbitrary_func is not None at line 574 fires as a bare AssertionError with no message. Any caller that was previously passing attention_mask to this function will silently get an opaque crash after switching to the FA backend, even though the docstring says "Pass either tensor to override." The condition should also handle the case where the wrong mask type is provided for the active backend, either by ignoring attention_mask gracefully on the FA path or by raising an explicit, informative error.

z52527 added a commit to z52527/recsys-examples that referenced this pull request May 11, 2026
Bring origin/main into the branch so the PR shows only the beam_decode
work as net new content (instead of double-counting the
fea-JaggedTransformerBlock changes that already landed via PR NVIDIA#339).

Conflicts resolved by keeping the beam_decode-side additions and
discarding the pre-NVIDIA#339 versions of shared text:

* docker/Dockerfile: keep the FA SHA pin (FLASH_ATTN_ARBITRARY_MASK_COMMIT).
* examples/sid_gr/beam_search/beam_search.py: keep parent_indices list
  (used by build_beam_topk_indices).
* examples/sid_gr/model/attention_mask.py: keep the n_func single-
  assignment cleanup; keep build_jagged_target_aware_arbitrary_func
  and dense_mask_to_jagged_arbitrary_func.
* examples/sid_gr/model/gpt_model.py: keep
  get_jagged_flash_attn_block(), the beam-isolating mask construction
  in generate(), the dense->jagged arbitrary_func adapter in
  decoder_step(), and the updated docstring wording. Re-add the
  padded_target_aware_causal_mask import that generate() needs.
* examples/sid_gr/model/jagged_flash_attn_block.py: keep the
  beam_decode_attn resolver, _beam_decode_attn_reference fallback,
  build_block_sparsity helper, JaggedGPTLayer decode_beam method,
  JaggedFlashAttnBlock prefill/decode_beam methods, plus the updated
  doc tone ("arbitrary-mask FlashAttention" / inference-only scope).
* examples/sid_gr/training/README.md: keep the corrected beam-search
  limitation paragraph and the de-personified FA dependency label.

Validation: 44/44 tests in test_beam_decode_generate.py and 37/37
tests in test_jagged_flash_attn_block.py + test_dense_mask_to_arbitrary_func.py
pass after the merge.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Runchu Zhao <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEA] Jagged Arbitrary Masked Self Attention support

3 participants