Skip to content

[Dynamic Shapes] Rebind unbacked symbols to derived expressions - #183837

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

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

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

rebind_unbacked already records equivalences when a retraced binding site maps
an unbacked symbol to another symbol or to a constant. The same invariant applies
when the new value is a derived symbolic expression such as (u1 + 1) // 2: the
old symbol still has a concrete binding relationship and should be eliminated in
favor of that expression.

The previous assertion assumed any non-symbol replacement with free symbols was
invalid. That is too strong for legitimate derived unbacked shapes and makes the
binding logic reject a value it can represent with the existing ShapeEnv
replacement mechanism. Record the replacement with _eliminate_unbacked, which
is the existing path for replacing an unbacked symbol by a non-symbol expression.

This intentionally does not restore the reverted broad HOP fake-trace
suppression. The FlexAttention/HOP reproducer for #183677 now passes on current
main without that suppression, and the broad suppression was the source of the
internal cond, AOTInductor, Executorch, and FlexAttention regressions.

This change was authored with assistance from an AI assistant.

Test Plan:

python test/test_dynamic_shapes.py TestUnbacked.test_rebind_unbacked_to_symbolic_expression -v
python test/dynamo/test_misc.py MiscTests.test_cond_runtime_assert_generation -v
python test/functorch/test_control_flow.py TestControlFlowTraced.test_cond_functionalized_nested -v
python test/inductor/test_aot_inductor.py -k cond_non_tensor_predicates_dynamic_True_cpu -v
python - <<'PY'
import torch
from torch.nn.attention.flex_attention import create_block_mask, flex_attention

if not torch.cuda.is_available():
    raise RuntimeError('CUDA unavailable')

device = 'cuda'
dtype = torch.float16

def score_mod(score, batch, head, q_idx, kv_idx):
    return score

compiled_create_block_mask = torch.compile(create_block_mask, dynamic=True, fullgraph=True)

def create_dynamic_block_mask(q_batch, kv_batch):
    q_len = q_batch.size(0)
    kv_len = kv_batch.size(0)
    def mask_mod(batch, head, q_idx, kv_idx):
        q_group = q_batch[q_idx]
        kv_group = kv_batch[kv_idx]
        return (q_group == kv_group) & (q_group != -1) & (kv_group != -1)
    return compiled_create_block_mask(mask_mod, B=None, H=None, Q_LEN=q_len, KV_LEN=kv_len, device=device, BLOCK_SIZE=128)

groups = torch.zeros(128, dtype=torch.int64, device=device)
block_mask = create_dynamic_block_mask(groups, groups)
q = torch.randn(1, 1, 128, 64, device=device, dtype=dtype, requires_grad=True)
k = torch.randn(1, 1, 128, 64, device=device, dtype=dtype, requires_grad=True)
v = torch.randn(1, 1, 128, 64, device=device, dtype=dtype, requires_grad=True)
compiled_flex_attention = torch.compile(flex_attention, fullgraph=True, dynamic=True, backend='aot_eager')
out = compiled_flex_attention(q, k, v, score_mod=score_mod, block_mask=block_mask)
out.sum().backward()
torch.cuda.synchronize()
print('ok', out.shape)
PY
lintrunner -a

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

@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/183837

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit a866a80 with merge base 083e261 (image):

BROKEN TRUNK - The following jobs failed but were 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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor release notes: fx release notes category labels May 15, 2026
@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
sanketpurandare requested review from drisspg and xmfan May 15, 2026 03:45
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/10 to main May 22, 2026 17:31
@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/torchtitan Run TorchTitan integration tests module: inductor release notes: distributed (dtensor) release notes category labels May 22, 2026
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/11 branch from 123bb3f to 5a662c0 Compare May 22, 2026 17:31
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/10 May 22, 2026 17:32
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/11 branch from c6b2bb3 to 1c5e150 Compare May 27, 2026 04:34
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/15 May 27, 2026 04:34
@sanketpurandare
sanketpurandare marked this pull request as ready for review May 27, 2026 04:34
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 27, 2026
Introduce the public graph_trainer EP-overlap configuration surface and the eager chunking producer for its chunk metadata contract. The new compile options select the logical chunk dimension, the chunking strategy, and one supported module-root pattern: all transformer blocks or all MoE blocks. Sequence chunking is limited to MoE block roots because attention needs full K/V context.

Keep EP overlap validation in configs.py next to the other graph_trainer compile config validation. The eager producer wraps selected module forwards during model parallelization, splits tensor inputs into two chunks, calls the original forward once per chunk, and materializes tensor outputs with cat. It emits the same chunk metadata that graph chunking will emit, so the later scheduling pass can consume either producer through one contract.

Add shared MoE EP region annotations for dispatcher dispatch/combine bodies, config fingerprinting for the new options, and a generic trace-input-preparation hook in GraphTrainer. This commit does not add graph chunking or communication-overlap scheduling.

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:
- Covered by the full graph_trainer pass, numerics, and H100 integration test runs after the stacked graph chunking and scheduling commits.

stack-info: PR: #3363, branch: sanketpurandare/stack/17
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 27, 2026
Add the graph-level chunking transform used by graph_trainer's EP overlap pipeline. The public opt-in remains --compile.passes ep_overlap, but this commit intentionally only introduces the correctness-preserving chunked dataflow. It does not implement EP communication-overlap scheduling.

The chunking pass lives in ep_chunk_pass.py with shared metadata and symbolic-shape helpers in ep_pass_utils.py. It uses the unbacked SymInt introduced by the trace-input dynamic-shape preparation as the source of truth for chunk influence. The pass plans selected forward/backward module regions, splits live-ins whose fake shapes carry the selected symbol, rewrites one chunk body in place, copies the peer chunk body, and materializes escaping full values. Tensor live-outs carrying the selected dimension are concatenated. Backward parameter-gradient live-outs can be accumulated before grad communication as a performance optimization; --compile.ep_overlap_disable_early_grad_accumulation disables that optimization for strict eager-chunk bitwise comparisons.

The pass runs after memory policy, CPU offload, and SAC/rematerialization, and before FSDP bucketing. It does not special-case offload or remat nodes; those interactions are represented as ordinary dataflow through live-ins and live-outs. Forward buffer mutations are preserved as chunk-local mutation chains so MoE accounting such as tokens-per-expert remains semantically visible. Chunk-derived symbolic shapes are kept through scheduling and then concretized by concretize_ep_chunk_symbolic_shapes_pass before backend codegen.

The eager wrapper remains the numerical reference: selected modules are split into two chunks, the original module forward runs once per chunk, and outputs are combined back. Graph chunking is expected to be bitwise equivalent to eager chunking when early grad accumulation is disabled, including model state such as MoE expert-bias buffers.

This pass stack relies on 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
- Inductor TP slice/cat collective fusion: pytorch/pytorch#184833

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- python torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py TestDSv3BitwiseDeterministic.test_ep_overlap_graph_matches_eager_chunking

stack-info: PR: #3325, branch: sanketpurandare/stack/12
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 27, 2026
Add the scheduling layer for graph_trainer's public ep_overlap pass. Graph and eager chunking producers create correctness-preserving chunked graphs; this commit consumes their shared chunk metadata after FSDP bucketing and reorders EP token-exchange regions to expose communication/compute overlap without changing tensor values.

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 true EP token-exchange markers on _c10d_functional.all_to_all_single.default nodes via custom[EP_token_exchange]. Generic MoE dispatch/combine traceback annotations are sanitized and are not scheduling markers.

The scheduler validates that both chunks have the same token-exchange signature, annotates each token-exchange wait with EP_token_exchange_wait, and emits a wait-gated schedule. For each token-exchange pair it emits the launch dependency closure in chunk order, then emits ready non-wait filler work that can run while the previous token exchange is outstanding, and only then allows the required wait/tail work. Forward uses chunk order 0 then 1; backward uses chunk order 1 then 0. All nodes are emitted exactly once through a global topological emitter, and the pass does not duplicate, delete, split, concatenate, or otherwise compute tensor values.

Wire the public ep_overlap pipeline as graph/eager chunking, FSDP process-group isolation and bucketing, EP scheduling, chunk-symbol concretization, optional async TP fusion, and DTensor metadata cleanup. Add focused scheduler tests and H100 integration coverage for graph 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 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
- Inductor TP slice/cat collective fusion: pytorch/pytorch#184833

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8

stack-info: PR: #3328, branch: sanketpurandare/stack/14
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request May 27, 2026
Add the scheduling layer for graph_trainer's public ep_overlap pass. Graph and eager chunking producers create correctness-preserving chunked graphs; this commit consumes their shared chunk metadata after FSDP bucketing and reorders EP token-exchange regions to expose communication/compute overlap without changing tensor values.

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 true EP token-exchange markers on _c10d_functional.all_to_all_single.default nodes via custom[EP_token_exchange]. Generic MoE dispatch/combine traceback annotations are sanitized and are not scheduling markers.

The scheduler validates that both chunks have the same token-exchange signature, annotates each token-exchange wait with EP_token_exchange_wait, and emits a wait-gated schedule. For each token-exchange pair it emits the launch dependency closure in chunk order, then emits ready non-wait filler work that can run while the previous token exchange is outstanding, and only then allows the required wait/tail work. Forward uses chunk order 0 then 1; backward uses chunk order 1 then 0. All nodes are emitted exactly once through a global topological emitter, and the pass does not duplicate, delete, split, concatenate, or otherwise compute tensor values.

Wire the public ep_overlap pipeline as graph/eager chunking, FSDP process-group isolation and bucketing, EP scheduling, chunk-symbol concretization, optional async TP fusion, and DTensor metadata cleanup. Add focused scheduler tests and H100 integration coverage for graph 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 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
- Inductor TP slice/cat collective fusion: pytorch/pytorch#184833

Test Plan:
- pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py
- pytest -q torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap
- PYTHONPATH=$PWD python torchtitan/experiments/graph_trainer/tests/integration_tests.py <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --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 <out_dir> --test_suite graph_trainer_h100 --test_name aot_fx_trace_deepseek_v3_flexattn_full_inductor_ep_overlap_eager_transformer_batch --ngpu 8

stack-info: PR: #3328, branch: sanketpurandare/stack/14
@zou3519
zou3519 removed their request for review May 28, 2026 21:04
@sanketpurandare
sanketpurandare marked this pull request as draft June 4, 2026 19:00
@sanketpurandare
sanketpurandare changed the base branch from sanketpurandare/stack/15 to main June 4, 2026 19:00
@sanketpurandare
sanketpurandare force-pushed the sanketpurandare/stack/11 branch from 1c5e150 to 8719709 Compare June 4, 2026 19:00
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/15 June 4, 2026 19:01
@sanketpurandare
sanketpurandare marked this pull request as ready for review June 4, 2026 19:01
@sanketpurandare
sanketpurandare marked this pull request as draft June 4, 2026 19:06
@sanketpurandare
sanketpurandare changed the base branch from sanketpurandare/stack/15 to main June 4, 2026 19:06
@sanketpurandare
sanketpurandare changed the base branch from main to sanketpurandare/stack/15 June 4, 2026 19:07
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: inductor / unit-test / inductor-cpu-test / test-osdc (inductor_amx, 2, 2, mt-l-x86iamx-8-64)

Details for Dev Infra team Raised by workflow job

@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -f "Unrelated failures already present on trunk"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@wdvr

wdvr commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

@pytorchmergebot revert -m "failing some executorch / other tests on the HOP / control-flow / FlexAttention surface I believe" -c ghfirst

claude analysis:

36 × pytorch/tritonbench/.../test_operator_accuracy[_beta[triton_beta]] - test_operator_accuracyflex_attention_accuracy (noop, causal, head_bias, sliding_window, document_mask, prefix_lm, softcap) — accuracy/listing failures across multiple error_clusters
-> Related (the diff explicitly names FlexAttention's score_mod alias check as the motivating fix path).

43 × caffe2/test/inductor:test_aot_inductor - test_cond_* / test_while_loop_* / test_custom_op_in_subgraph_* cpu+cuda — clusters 1017592810737058, 1161238703736894, 1267440348546219 -> testx Good Quality with 4 retries each;
-> Related (HOP cond/while_loop AOT inductor codegen path directly exercises the modified compute_unbacked_bindings and HOP alias/mutation helper).

9 × executorch/exir/tests:passes + executorch/exir/backend/test:test_backends_* + executorch/exir/tests:memory_planning / test_constant_prop_pass_for_control_flow, test_debug_handle_generator_pass_with_control_flow, test_spec_prop_pass_cond, test_alloc_node_spec, test_partition_with_control_flow, test_partition_with_map, test_multi_map, test, test_spec_prop_pass_scan
-> Related (executorch control-flow / map passes exercise the same HOP infrastructure).

7 × executorch/exir/emit/test:emit + executorch/extension/llm/custom_ops:test_update_cross_attn_cache + executorch/test/end2end:end2end_aten — test_emit_cond, test_emit_map, test_load_emit_map, test_emit_scan_add_mul, test_run_emit_scan_cumsum, test_run_emit_scan_dynamic_shape, test_update_cross_attn_cache_in_cond, test_ft_map_dynshape

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

`rebind_unbacked` already records equivalences when a retraced binding site maps
an unbacked symbol to another symbol or to a constant. The same invariant applies
when the new value is a derived symbolic expression such as `(u1 + 1) // 2`: the
old symbol still has a concrete binding relationship and should be eliminated in
favor of that expression.

The previous assertion assumed any non-symbol replacement with free symbols was
invalid. That is too strong for legitimate derived unbacked shapes and makes the
binding logic reject a value it can represent with the existing ShapeEnv
replacement mechanism. Record the replacement with `_eliminate_unbacked`, which
is the existing path for replacing an unbacked symbol by a non-symbol expression.

This intentionally does not restore the reverted broad HOP fake-trace
suppression. The FlexAttention/HOP reproducer for #183677 now passes on current
main without that suppression, and the broad suppression was the source of the
internal cond, AOTInductor, Executorch, and FlexAttention regressions.

This change was authored with assistance from an AI assistant.

Test Plan:

```bash
python test/test_dynamic_shapes.py TestUnbacked.test_rebind_unbacked_to_symbolic_expression -v
```

```bash
python test/dynamo/test_misc.py MiscTests.test_cond_runtime_assert_generation -v
```

```bash
python test/functorch/test_control_flow.py TestControlFlowTraced.test_cond_functionalized_nested -v
```

```bash
python test/inductor/test_aot_inductor.py -k cond_non_tensor_predicates_dynamic_True_cpu -v
```

```bash
python - <<'PY'
import torch
from torch.nn.attention.flex_attention import create_block_mask, flex_attention

if not torch.cuda.is_available():
    raise RuntimeError('CUDA unavailable')

device = 'cuda'
dtype = torch.float16

def score_mod(score, batch, head, q_idx, kv_idx):
    return score

compiled_create_block_mask = torch.compile(create_block_mask, dynamic=True, fullgraph=True)

def create_dynamic_block_mask(q_batch, kv_batch):
    q_len = q_batch.size(0)
    kv_len = kv_batch.size(0)
    def mask_mod(batch, head, q_idx, kv_idx):
        q_group = q_batch[q_idx]
        kv_group = kv_batch[kv_idx]
        return (q_group == kv_group) & (q_group != -1) & (kv_group != -1)
    return compiled_create_block_mask(mask_mod, B=None, H=None, Q_LEN=q_len, KV_LEN=kv_len, device=device, BLOCK_SIZE=128)

groups = torch.zeros(128, dtype=torch.int64, device=device)
block_mask = create_dynamic_block_mask(groups, groups)
q = torch.randn(1, 1, 128, 64, device=device, dtype=dtype, requires_grad=True)
k = torch.randn(1, 1, 128, 64, device=device, dtype=dtype, requires_grad=True)
v = torch.randn(1, 1, 128, 64, device=device, dtype=dtype, requires_grad=True)
compiled_flex_attention = torch.compile(flex_attention, fullgraph=True, dynamic=True, backend='aot_eager')
out = compiled_flex_attention(q, k, v, score_mod=score_mod, block_mask=block_mask)
out.sum().backward()
torch.cuda.synchronize()
print('ok', out.shape)
PY
```

```bash
lintrunner -a
```

stack-info: PR: #183837, branch: sanketpurandare/stack/11
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: torchtitan-test / torchtitan-x-pytorch-test / test-osdc (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8), torchtitan-test / torchtitan-x-pytorch-test / test-osdc (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

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/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[HOP] Alias/mutation fake traces should ignore discarded unbacked symbols

4 participants