Skip to content

[Inductor][HOP] Handle unbacked FlexAttention predicates - #183838

Closed
sanketpurandare wants to merge 1 commit into
mainfrom
sanketpurandare/stack/12
Closed

sanketpurandare wants to merge 1 commit into
mainfrom
sanketpurandare/stack/12

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

EP-overlap graph chunking traces FlexAttention with unbacked symbolic batch and sequence dimensions. These are valid runtime sizes, but several FlexAttention predicate and lowering sites forced trace-time decisions that should either fall back to the general kernel or remain represented as symbolic assertions.

Flex decoding remains an optional optimized implementation. Its predicates use guard_or_false because they are kernel eligibility checks, not user-visible invariants: when ShapeEnv can prove eligibility, decode can be selected; when an unbacked predicate is not provable, the general FlexAttention kernel is used. Failing to prove an optimization must not impose a runtime shape contract on user inputs.

Backward fake propagation preserves the accepted KV-batch-broadcast metadata contract. It reduces grad_key and grad_value back to key/value batch when key/value batch is one and query batch is known to satisfy the eager broadcast precondition; otherwise it records the non-broadcast invariant with torch._check(Bq == Bkv).

Public BlockMask length validation is expressed as symbolic torch._check predicates. Concrete mismatches still fail with the existing guidance, while unbacked symbolic lengths become deferred runtime assertions instead of forcing Python to branch on an unbacked expression.

The FlexAttention lowering keeps scalar shape captures as subgraph inputs for dependency tracking and codegen, but autotuning only receives tensor-valued IR inputs because benchmarking materializes real tensors. Captured Python ints and SymInts are realized as scalar IR, including in backward lowering, so realize_inputs also avoids applying tensor stride constraints to non-tensor scalar IR. This preserves the existing algorithm-selector contract instead of teaching global autotune to key or benchmark scalar captures.

This PR was authored with assistance from an AI assistant.

Test Plan:

python -m pytest test/inductor/test_flex_attention.py -q -s -k "unbacked_flex_decoding_eligibility_falls_back or backward_fake_symbolic_query_key_batch_metadata or direct_backward_inductor_batch_broadcast_matches_eager or direct_backward_inductor_supports_scalar_mask_mod_buffers or block_mask_vs_sequence_lengths"
python -m pytest test/inductor/test_flex_attention.py -q -s -k "direct_backward"
python -m pytest test/inductor/test_flex_attention.py -q -s -k "flex_decoding"
python -m pytest test/inductor/test_flex_attention.py -q -s -k "direct_backward_preserves_explicit_buffers or direct_backward_supports_symint_score_mod_buffers or captured_scalar_grad or symbol_closure_in_score_mod or mask_mod_handles_symint_addition or mask_mod_handles_derived_symint_closure"
python test/inductor/test_select_algorithm.py TestAlgorithmSelectorChoiceTypes
python test/inductor/test_dependencies.py TestDependencies.test_extern_kernel_nested_ir_args_are_dependencies
python test/inductor/test_mkldnn_pattern_matcher.py TestPatternMatcher.test_linear_add_bias TestPatternMatcher.test_linear_add_bias_float_constant
lintrunner -a

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98

@sanketpurandare
sanketpurandare requested a review from drisspg as a code owner May 15, 2026 02:54
@pytorch-bot

pytorch-bot Bot commented May 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/183838

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 5 Unrelated Failures, 1 Unclassified Failure

As of commit 50304b4 with merge base 820ea17 (image):

NEW FAILURE - The following job has failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/12 branch from 3d1e6c3 to deec133 Compare May 15, 2026 02:54
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/11 branch from 9533492 to 123bb3f Compare May 15, 2026 02:54
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 15, 2026
Add the scheduling layer for graph_trainer's public ep_overlap pass. The graph and eager chunking producers create correctness-preserving chunked graphs; this commit consumes their shared chunk metadata after FSDP bucketing and reorders EP dispatch/combine phases so paired chunk all-to-all launches can run before their delayed wait suffixes.

The scheduling logic lives in ep_overlap_pass.py and is intentionally separate from chunking. Its input contract is an already chunked graph with exactly two chunks per selected region, chunk body nodes tagged with chunk_id and chunked_region metadata, and MoE dispatcher regions annotated with custom EP metadata for dispatch and combine. The scheduler validates the chunk metadata, uses the last all-to-all in each EP phase as the overlap boundary, annotates delayed wait suffixes with EP_wait=True, and applies a priority topological sort. It does not duplicate nodes, delete nodes, split tensors, concatenate tensors, or otherwise change tensor values.

For forward dispatch, the overlap boundary is deliberately the final token-exchange all-to-all, not the earlier split-size exchange. Forward regions schedule dispatch then combine. Backward autograd sees combine gradients before dispatch gradients, so the scheduler derives the observed EP phase chunk order instead of imposing a hardcoded chunk order.

Wire the public ep_overlap pipeline as two stages: chunking runs before memory/offload/remat and bucketing, while scheduling runs after downstream FSDP bucketing/reordering. This lets distributed bucketing place shared full-value waits first, then lets the EP scheduler establish the final EP launch/wait order.

Add focused scheduler tests and H100 full-Inductor integration coverage for graph chunking and eager chunking across SDPA and FlexAttention debug-model variants. The distributed bitwise numerics tests introduced with graph chunking cover this composed public ep_overlap path because scheduling is value-preserving.

This pass stack relies on pending PyTorch support for hinted unbacked symbolic dimensions in the tracing and distributed compiler paths:
- FakeTensor folded matmul: pytorch/pytorch#183397
- ProxyTensor SDPA tracing: pytorch/pytorch#183398
- Inductor bucketing trace isolation from ambient unbacked symbols: pytorch/pytorch#183495
- Inductor collective bucketing with hinted unbacked SymInts: pytorch/pytorch#183544
- DTensor sharding padding for hinted even unbacked shards: pytorch/pytorch#183545
- HOP fake traces with discarded unbacked symbols: pytorch/pytorch#183837
- FlexAttention chunked unbacked input extents: pytorch/pytorch#183838
- FakeTensor trace metadata for hinted symbolic storage: pytorch/pytorch#183839
- Inductor symbolic stride ordering with unbacked hints: pytorch/pytorch#183840

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
  - 84 passed, 1 skipped, 14 warnings, 5 subtests passed
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
  - all 8 H100 integration tests passed

stack-info: PR: #3328, branch: sanketpurandare/stack/14
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 15, 2026
Add the scheduling layer for graph_trainer's public ep_overlap pass. The graph and eager chunking producers create correctness-preserving chunked graphs; this commit consumes their shared chunk metadata after FSDP bucketing and reorders EP dispatch/combine phases so paired chunk all-to-all launches can run before their delayed wait suffixes.

The scheduling logic lives in ep_overlap_pass.py and is intentionally separate from chunking. Its input contract is an already chunked graph with exactly two chunks per selected region, chunk body nodes tagged with chunk_id and chunked_region metadata, and MoE dispatcher regions annotated with custom EP metadata for dispatch and combine. The scheduler validates the chunk metadata, uses the last all-to-all in each EP phase as the overlap boundary, annotates delayed wait suffixes with EP_wait=True, and applies a priority topological sort. It does not duplicate nodes, delete nodes, split tensors, concatenate tensors, or otherwise change tensor values.

For forward dispatch, the overlap boundary is deliberately the final token-exchange all-to-all, not the earlier split-size exchange. Forward regions schedule dispatch then combine. Backward autograd sees combine gradients before dispatch gradients, so the scheduler derives the observed EP phase chunk order instead of imposing a hardcoded chunk order.

Wire the public ep_overlap pipeline as two stages: chunking runs before memory/offload/remat and bucketing, while scheduling runs after downstream FSDP bucketing/reordering. This lets distributed bucketing place shared full-value waits first, then lets the EP scheduler establish the final EP launch/wait order.

Add focused scheduler tests and H100 full-Inductor integration coverage for graph chunking and eager chunking across SDPA and FlexAttention debug-model variants. The distributed bitwise numerics tests introduced with graph chunking cover this composed public ep_overlap path because scheduling is value-preserving.

This pass stack relies on pending PyTorch support for hinted unbacked symbolic dimensions in the tracing and distributed compiler paths:
- FakeTensor folded matmul: pytorch/pytorch#183397
- ProxyTensor SDPA tracing: pytorch/pytorch#183398
- Inductor bucketing trace isolation from ambient unbacked symbols: pytorch/pytorch#183495
- Inductor collective bucketing with hinted unbacked SymInts: pytorch/pytorch#183544
- DTensor sharding padding for hinted even unbacked shards: pytorch/pytorch#183545
- HOP fake traces with discarded unbacked symbols: pytorch/pytorch#183837
- FlexAttention chunked unbacked input extents: pytorch/pytorch#183838
- FakeTensor trace metadata for hinted symbolic storage: pytorch/pytorch#183839
- Inductor symbolic stride ordering with unbacked hints: pytorch/pytorch#183840

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
  - 84 passed, 1 skipped, 14 warnings, 5 subtests passed
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
  - all 8 H100 integration tests passed

stack-info: PR: #3328, branch: sanketpurandare/stack/14
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 15, 2026
Add the scheduling layer for graph_trainer's public ep_overlap pass. The graph and eager chunking producers create correctness-preserving chunked graphs; this commit consumes their shared chunk metadata after FSDP bucketing and reorders EP dispatch/combine phases so paired chunk all-to-all launches can run before their delayed wait suffixes.

The scheduling logic lives in ep_overlap_pass.py and is intentionally separate from chunking. Its input contract is an already chunked graph with exactly two chunks per selected region, chunk body nodes tagged with chunk_id and chunked_region metadata, and MoE dispatcher regions annotated with custom EP metadata for dispatch and combine. The scheduler validates the chunk metadata, uses the last all-to-all in each EP phase as the overlap boundary, annotates delayed wait suffixes with EP_wait=True, and applies a priority topological sort. It does not duplicate nodes, delete nodes, split tensors, concatenate tensors, or otherwise change tensor values.

For forward dispatch, the overlap boundary is deliberately the final token-exchange all-to-all, not the earlier split-size exchange. Forward regions schedule dispatch then combine. Backward autograd sees combine gradients before dispatch gradients, so the scheduler derives the observed EP phase chunk order instead of imposing a hardcoded chunk order.

Wire the public ep_overlap pipeline as two stages: chunking runs before memory/offload/remat and bucketing, while scheduling runs after downstream FSDP bucketing/reordering. This lets distributed bucketing place shared full-value waits first, then lets the EP scheduler establish the final EP launch/wait order.

Add focused scheduler tests and H100 full-Inductor integration coverage for graph chunking and eager chunking across SDPA and FlexAttention debug-model variants. The distributed bitwise numerics tests introduced with graph chunking cover this composed public ep_overlap path because scheduling is value-preserving.

This pass stack relies on pending PyTorch support for hinted unbacked symbolic dimensions in the tracing and distributed compiler paths:
- FakeTensor folded matmul: pytorch/pytorch#183397
- ProxyTensor SDPA tracing: pytorch/pytorch#183398
- Inductor bucketing trace isolation from ambient unbacked symbols: pytorch/pytorch#183495
- Inductor collective bucketing with hinted unbacked SymInts: pytorch/pytorch#183544
- DTensor sharding padding for hinted even unbacked shards: pytorch/pytorch#183545
- HOP fake traces with discarded unbacked symbols: pytorch/pytorch#183837
- FlexAttention chunked unbacked input extents: pytorch/pytorch#183838
- FakeTensor trace metadata for hinted symbolic storage: pytorch/pytorch#183839
- Inductor symbolic stride ordering with unbacked hints: pytorch/pytorch#183840

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
  - 84 passed, 1 skipped, 14 warnings, 5 subtests passed
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
  - all 8 H100 integration tests passed

stack-info: PR: #3328, branch: sanketpurandare/stack/14
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 15, 2026
Add the scheduling layer for graph_trainer's public ep_overlap pass. The graph and eager chunking producers create correctness-preserving chunked graphs; this commit consumes their shared chunk metadata after FSDP bucketing and reorders EP dispatch/combine phases so paired chunk all-to-all launches can run before their delayed wait suffixes.

The scheduling logic lives in ep_overlap_pass.py and is intentionally separate from chunking. Its input contract is an already chunked graph with exactly two chunks per selected region, chunk body nodes tagged with chunk_id and chunked_region metadata, and MoE dispatcher regions annotated with custom EP metadata for dispatch and combine. The scheduler validates the chunk metadata, uses the last all-to-all in each EP phase as the overlap boundary, annotates delayed wait suffixes with EP_wait=True, and applies a priority topological sort. It does not duplicate nodes, delete nodes, split tensors, concatenate tensors, or otherwise change tensor values.

For forward dispatch, the overlap boundary is deliberately the final token-exchange all-to-all, not the earlier split-size exchange. Forward regions schedule dispatch then combine. Backward autograd sees combine gradients before dispatch gradients, so the scheduler derives the observed EP phase chunk order instead of imposing a hardcoded chunk order.

Wire the public ep_overlap pipeline as two stages: chunking runs before memory/offload/remat and bucketing, while scheduling runs after downstream FSDP bucketing/reordering. This lets distributed bucketing place shared full-value waits first, then lets the EP scheduler establish the final EP launch/wait order.

Add focused scheduler tests and H100 full-Inductor integration coverage for graph chunking and eager chunking across SDPA and FlexAttention debug-model variants. The distributed bitwise numerics tests introduced with graph chunking cover this composed public ep_overlap path because scheduling is value-preserving.

This pass stack relies on pending PyTorch support for hinted unbacked symbolic dimensions in the tracing and distributed compiler paths:
- FakeTensor folded matmul: pytorch/pytorch#183397
- ProxyTensor SDPA tracing: pytorch/pytorch#183398
- Inductor bucketing trace isolation from ambient unbacked symbols: pytorch/pytorch#183495
- Inductor collective bucketing with hinted unbacked SymInts: pytorch/pytorch#183544
- DTensor sharding padding for hinted even unbacked shards: pytorch/pytorch#183545
- HOP fake traces with discarded unbacked symbols: pytorch/pytorch#183837
- FlexAttention chunked unbacked input extents: pytorch/pytorch#183838
- FakeTensor trace metadata for hinted symbolic storage: pytorch/pytorch#183839
- Inductor symbolic stride ordering with unbacked hints: pytorch/pytorch#183840

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
  - 84 passed, 1 skipped, 14 warnings, 5 subtests passed
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_moe_seq --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_sdpa_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py /tmp/torchtitan_ep_overlap_integration_20260514_174529 --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8
  - all 8 H100 integration tests passed

stack-info: PR: #3328, branch: sanketpurandare/stack/14
@sanketpurandare
sanketpurandare marked this pull request as draft May 22, 2026 17:31
@sanketpurandare
sanketpurandare changed the base branch from sanketpurandare/stack/11 to main May 22, 2026 17:31
@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests release notes: fx release notes category release notes: distributed (dtensor) release notes category labels May 22, 2026
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/12 branch from deec133 to 3720258 Compare May 22, 2026 17:31
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/11 May 22, 2026 17:32
@sanketpurandare
sanketpurandare marked this pull request as ready for review May 22, 2026 17:32
Comment thread torch/nn/attention/flex_attention.py Outdated
Comment on lines 2371 to 2399
# These checks reject invalid block masks. With symbolic lengths, only
# raise when the invalid relation is provable at trace time.
block_mask_q_len = block_mask.shape[-2]
block_mask_kv_len = block_mask.shape[-1]
if query.size(-2) > block_mask_q_len or key.size(-2) > block_mask_kv_len:
if guard_or_false(query.size(-2) > block_mask_q_len) or guard_or_false(
key.size(-2) > block_mask_kv_len
):
raise ValueError(
f"block_mask was created for block_mask.shape={block_mask.shape} but got q_len={query.size(-2)} and kv_len={key.size(-2)}. "
"As the block mask was created for a smaller length than you're using it for, you likely need to create a new block mask."
)
elif (
query.size(-2) < block_mask_q_len and key.size(-2) <= block_mask_kv_len
) or (query.size(-2) <= block_mask_q_len and key.size(-2) < block_mask_kv_len):
guard_or_false(query.size(-2) < block_mask_q_len)
and guard_or_false(key.size(-2) <= block_mask_kv_len)
) or (
guard_or_false(query.size(-2) <= block_mask_q_len)
and guard_or_false(key.size(-2) < block_mask_kv_len)
):
raise ValueError(
f"block_mask was created for block_mask.shape={block_mask.shape} but got q_len={query.size(-2)} and kv_len={key.size(-2)}. "
"As the block mask was created for a larger length than you're using it for, you can either 1. create a new block mask with the correct length, or 2. 'adjust' the existing block mask to the correct length by calling block_mask._adjust(q_len, kv_len). This essentially 'crops' the block mask to the upper left corner, which does not work for all mask_mods!"
)
if query.size(-2) != block_mask_q_len:
if guard_or_false(query.size(-2) != block_mask_q_len):
raise AssertionError(
f"query.size(-2) ({query.size(-2)}) != block_mask_q_len ({block_mask_q_len})"
)
if key.size(-2) != block_mask_kv_len:
if guard_or_false(key.size(-2) != block_mask_kv_len):
raise AssertionError(
f"key.size(-2) ({key.size(-2)}) != block_mask_kv_len ({block_mask_kv_len})"

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.

AFAIk we dont use guard_or_false for runtime checks and things that if we choose wrongly will end up causing us to execute bad code. I think that this should be torch._check right?

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.

Done!

Comment thread torch/nn/attention/flex_attention.py Resolved
Comment thread torch/_inductor/codegen/wrapper.py Resolved

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

I approve of the guarding in flex

Comment thread torch/_inductor/codegen/wrapper.py Resolved
Comment thread torch/_inductor/codegen/wrapper.py Resolved
Comment thread torch/_inductor/codegen/wrapper.py Resolved
Comment thread torch/_inductor/codegen/wrapper.py Resolved
Comment thread torch/_inductor/codegen/wrapper.py Resolved
Comment thread torch/_inductor/codegen/wrapper.py Resolved
Comment thread torch/_inductor/lowering.py Resolved
Comment thread torch/_inductor/select_algorithm.py Resolved
Comment thread torch/nn/attention/flex_attention.py Resolved
Comment thread torch/nn/attention/flex_attention.py Resolved

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

cc @laithsakka feels like there is an api gap here with unbacked shapes/ runtime conditions

Comment thread torch/nn/attention/flex_attention.py Outdated
Comment on lines +2374 to +2376
if guard_or_false(query.size(-2) > block_mask_q_len) or guard_or_false(
key.size(-2) > block_mask_kv_len
):

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 feels to me like an API issue. This should not translate to False if we can't guard here. It should just translate to a runtime assertion, ideally with the error message preserved.

cc @laithsakka

Comment thread torch/nn/attention/flex_attention.py Outdated
Comment on lines +2382 to +2386
guard_or_false(query.size(-2) < block_mask_q_len)
and guard_or_false(key.size(-2) <= block_mask_kv_len)
) or (
guard_or_false(query.size(-2) <= block_mask_q_len)
and guard_or_false(key.size(-2) < block_mask_kv_len)

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.

same comments

# The fake kernel must choose one metadata shape during tracing. Reduce to
# key/value batch only when key/value is provably batch-broadcast; otherwise
# keep the non-broadcast metadata and record its equality precondition.
if guard_or_false(Bkv == 1) and guard_or_true(Bq != 1):

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 should guard on the conjunction, so we don't add a guard on one without being able to prove the other

Comment thread torch/nn/attention/flex_attention.py Outdated
# Keep concrete/hinted mismatches on the existing ValueError branches.
# Truly unbacked comparisons fall through to deferred equality checks.
if guard_or_false(query.size(-2) > block_mask_q_len) or guard_or_false(
key.size(-2) > block_mask_kv_len

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.

cond = sym_or((q_len > block_mask_q_len, kv_len > block_mask_kv_len)

torch._check(cond!=False, ...)
cond3 = not cond1 and cond2
torch._check(cond3!=False, ...)

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@huydhn

huydhn commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot revert -m 'Sorry for reverting your change but one of the new tests is failing internally' -c ghfirst

From D108817148

buck test @fbcode//mode/opt fbcode//caffe2/test/inductor:flex_attention -- --exact 'fbcode//caffe2/test/inductor:flex_attention - test_direct_backward_inductor_supports_scalar_score_mod_buffers_cuda (caffe2.test.inductor.test_flex_attention.TestFlexAttentionCUDA)'

Test was added in target revision (886e71e7b531ab481bbeaf02f899b48e798e9271) hence is not present in base rev (ca152aaa67728880e77e3af731ae83f8c6569a51)
monitoring.obc.py.OBCClient:13: ThriftPyDeprecatedWarning: Uses thrift-py-deprecated. Migrate to thrift-python. See https://fburl.com/thrift-python and https://fburl.com/wiki/jihy02dr. Future automatic thrift-py-deprecated code generation may stop for non-migrated targets: https://fburl.com/workplace/wer48s4m.
/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_utils_internal.py:283: NCCL_DEBUG env var is set to None
/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_utils_internal.py:292: NCCL_DEBUG is INFO from /etc/nccl.conf
2026-06-17 02:40:42,280 - tritonparse.structured_logging - INFO - TritonTraceHandler: disabled because /logs does not exist
/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/triton/fb/triton_util.py:163: ===========[FB_TRITON]=========== Triton Version: 3.5.0+fb
WARNING: Logging before InitGoogleLogging() is written to STDERR
I0617 02:40:47.225841 341530 RuntimeEnvironment.cpp:741] ModelTypeName from C2Online Trainer Env Var: MISSING_MODEL_TYPE_NAME
W0617 02:40:47.253901 341530 LoggerTransport.h:148] Tracing payload for Mock should not be called
W0617 02:40:47.253963 341530 LoggerTransport.h:281] Tracing payload for Mock should not be called: pt2_compile_chromium_events
INFO:2026-06-17 02:40:48 341530:341530 CuptiCallbackApi.cpp:69] Callback: domain = 3, cbid = 1
INFO:2026-06-17 02:40:48 341530:341530 CuptiActivityProfiler.cpp:96] CUDA versions. CUPTI: 22; Runtime: 12040; Driver: 13000
test_direct_backward_inductor_supports_scalar_score_mod_buffers_cuda (caffe2.test.inductor.test_flex_attention.TestFlexAttentionCUDA) ... ERROR

======================================================================
ERROR: test_direct_backward_inductor_supports_scalar_score_mod_buffers_cuda (caffe2.test.inductor.test_flex_attention.TestFlexAttentionCUDA)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/testing/_internal/common_utils.py", line 3591, in wrapper
    method(*args, **kwargs)
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/testing/_internal/common_device_type.py", line 571, in instantiated_test
    raise rte
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/testing/_internal/common_device_type.py", line 551, in instantiated_test
    result = test(self, **param_kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/testing/_internal/common_device_type.py", line 1599, in dep_fn
    return fn(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/testing/_internal/common_device_type.py", line 1448, in dep_fn
    return fn(slf, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/caffe2/test/inductor/test_flex_attention.py", line 215, in wrapper
    return test_func(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/caffe2/test/inductor/test_flex_attention.py", line 5888, in test_direct_backward_inductor_supports_scalar_score_mod_buffers
    dq, dk, dv, _ = compiled_bw(
                    ^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_dynamo/eval_frame.py", line 1183, in compile_wrapper
    raise e.remove_dynamo_frames() from None  # see TORCHDYNAMO_VERBOSE=1
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/compile_fx.py", line 1114, in _compile_fx_inner
    raise InductorError(e, currentframe()).with_traceback(
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/compile_fx.py", line 1091, in _compile_fx_inner
    mb_compiled_graph = fx_codegen_and_compile(
                        ^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/compile_fx.py", line 1903, in fx_codegen_and_compile
    return scheme.codegen_and_compile(gm, example_inputs, inputs_to_check, graph_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/compile_fx.py", line 1426, in codegen_and_compile
    _recursive_post_grad_passes(gm, is_inference=is_inference)
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/compile_fx.py", line 587, in _recursive_post_grad_passes
    post_grad_passes(gm, is_inference)
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/fx_passes/post_grad.py", line 275, in post_grad_passes
    fake_tensor_updater.incremental_update()
  File "/re_cwd/buck-out/v2/art/fbcode/3188ee4cd5d26d8a/caffe2/test/inductor/__flex_attention__/flex_attention#link-tree/torch/_inductor/fx_utils.py", line 593, in incremental_update
    raise AssertionError(
torch._inductor.exc.InductorError: AssertionError: A subgraph argument other than striding has been modified; FakeTensorUpdater cannot update this argument!

Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"


----------------------------------------------------------------------
Ran 1 test in 3.685s

FAILED (errors=1)
W0617 02:40:53.728988 344787 RouterZeroClient.cpp:36] Skipping Router Zero connection setup in unit test. ODS3 data will not be sent to Router Zero.

It's easier to revert and reland I think

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@sanketpurandare your PR has been successfully reverted.

EP-overlap graph chunking traces FlexAttention with unbacked symbolic batch and sequence dimensions. These are valid runtime sizes, but several FlexAttention predicate and lowering sites forced trace-time decisions that should either fall back to the general kernel or remain represented as symbolic assertions.

Flex decoding remains an optional optimized implementation. Its predicates use guard_or_false because they are kernel eligibility checks, not user-visible invariants: when ShapeEnv can prove eligibility, decode can be selected; when an unbacked predicate is not provable, the general FlexAttention kernel is used. Failing to prove an optimization must not impose a runtime shape contract on user inputs.

Backward fake propagation preserves the accepted KV-batch-broadcast metadata contract. It reduces grad_key and grad_value back to key/value batch when key/value batch is one and query batch is known to satisfy the eager broadcast precondition; otherwise it records the non-broadcast invariant with torch._check(Bq == Bkv).

Public BlockMask length validation is expressed as symbolic torch._check predicates. Concrete mismatches still fail with the existing guidance, while unbacked symbolic lengths become deferred runtime assertions instead of forcing Python to branch on an unbacked expression.

The FlexAttention lowering keeps scalar shape captures as subgraph inputs for dependency tracking and codegen, but autotuning only receives tensor-valued IR inputs because benchmarking materializes real tensors. Captured Python ints and SymInts are realized as scalar IR, including in backward lowering, so realize_inputs also avoids applying tensor stride constraints to non-tensor scalar IR. This preserves the existing algorithm-selector contract instead of teaching global autotune to key or benchmark scalar captures.

This PR was authored with assistance from an AI assistant.

Test Plan:

```bash
python -m pytest test/inductor/test_flex_attention.py -q -s -k "unbacked_flex_decoding_eligibility_falls_back or backward_fake_symbolic_query_key_batch_metadata or direct_backward_inductor_batch_broadcast_matches_eager or direct_backward_inductor_supports_scalar_mask_mod_buffers or block_mask_vs_sequence_lengths"
```

```bash
python -m pytest test/inductor/test_flex_attention.py -q -s -k "direct_backward"
```

```bash
python -m pytest test/inductor/test_flex_attention.py -q -s -k "flex_decoding"
```

```bash
python -m pytest test/inductor/test_flex_attention.py -q -s -k "direct_backward_preserves_explicit_buffers or direct_backward_supports_symint_score_mod_buffers or captured_scalar_grad or symbol_closure_in_score_mod or mask_mod_handles_symint_addition or mask_mod_handles_derived_symint_closure"
```

```bash
python test/inductor/test_select_algorithm.py TestAlgorithmSelectorChoiceTypes
```

```bash
python test/inductor/test_dependencies.py TestDependencies.test_extern_kernel_nested_ir_args_are_dependencies
```

```bash
python test/inductor/test_mkldnn_pattern_matcher.py TestPatternMatcher.test_linear_add_bias TestPatternMatcher.test_linear_add_bias_float_constant
```

```bash
lintrunner -a
```

stack-info: PR: #183838, branch: sanketpurandare/stack/12
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/b200 ciflow/dtensor Run DTensor specific tests ciflow/h100 ciflow/inductor ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo module: inductor release notes: distributed (dtensor) release notes category release notes: fx release notes category release notes: inductor (aoti) Reverted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Inductor][HOP] FlexAttention should bind derived unbacked tensor input extents from runtime metadata

6 participants