Repository navigation
[DTensor] Use explicit hints for unbacked sharding - #183545
sanketpurandare wants to merge 1 commit into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/183545
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 2 Unrelated FailuresAs of commit 16fcc86 with merge base b343105 ( NEW FAILURE - The following job has failed:
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. |
d010cda to
791a147
Compare
DTensor sharding assumes the uneven-padding path when a shard size is unbacked because the divisibility predicate cannot be evaluated as a Python bool. That is conservative for arbitrary symbolic sizes, but it is too conservative for tracing paths that provide optimization hints and know the sharded dimension is evenly divisible. Use optimization hints only for the padding policy decision. If a hinted symbolic size proves divisibility by the mesh chunk count, emit a symbolic torch._check for the divisibility relation and take the no-padding branch. Tensor shapes, split sizes, and local tensor sizes remain symbolic; the hint is not used to specialize graph shapes. Apply the helper to reduce-scatter padding, local padding, and local unpadding so evenly sharded hinted unbacked dimensions avoid constructing symbolic pad sizes that lower to operators requiring concrete padding lists. Test Plan: python test/distributed/tensor/test_placement_types.py PlacementTypesTestCase.test_hinted_unbacked_even_shard_skips_padding -v lintrunner --config=.lintrunner.toml torch/_subclasses/fake_impls.py test/test_fake_tensor.py torch/distributed/tensor/placement_types.py test/distributed/tensor/test_placement_types.py stack-info: PR: #183545, branch: sanketpurandare/stack/10
208f80b to
47e4d8f
Compare
DTensor sharding assumes the uneven-padding path when a shard size is unbacked because the divisibility predicate cannot be evaluated as a Python bool. That is conservative for arbitrary symbolic sizes, but it is too conservative for tracing paths that explicitly override optimization hints and know the sharded dimension is evenly divisible. Only trust explicit optimization hint overrides for this padding policy decision. Ordinary first-example hints are non-guarding runtime hints and cannot justify a no-padding branch, because a compiled graph may be reused on later uneven inputs. When an explicit override proves divisibility by the mesh chunk count, emit a symbolic torch._check for the divisibility relation and take the no-padding branch. Tensor shapes, split sizes, and local tensor sizes remain symbolic; the hint is not used to specialize graph shapes. Apply the helper to reduce-scatter padding, local padding, and local unpadding so evenly sharded explicitly hinted unbacked dimensions avoid constructing symbolic pad sizes that lower to operators requiring concrete padding lists. Authored with Codex. Test Plan: pip install -e . -v --no-build-isolation --no-deps python test/distributed/tensor/test_placement_types.py PlacementTypesTestCase.test_hinted_unbacked_even_shard_skips_padding PlacementTypesTestCase.test_unbacked_even_fallback_hint_requires_override -v python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_dtensor_unbacked_matmuls -v lintrunner -a stack-info: PR: #183545, branch: sanketpurandare/stack/10
47e4d8f to
27e027f
Compare
Add the scheduling layer for graph_trainer's public ep_overlap pass. The previous commit creates the correctness-preserving chunked graph; this commit consumes that chunked graph 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 canonical chunk order, extracts dispatch/combine phases, 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. Wire the public ep_overlap pipeline as two stages: chunking runs after CPU offload and SAC/rematerialization, while scheduling runs after downstream FSDP bucketing/reordering. This keeps chunk planning aligned with the final recompute graph and lets bucketing place shared full waits before the overlap scheduler establishes the final EP launch/wait order. The distributed DSV3 bitwise numerics tests introduced in the previous commit now cover this composed public ep_overlap path as well. Since this scheduling pass is value-preserving, those tests validate that adding the scheduler on top of graph chunking does not change the eager-chunk-equivalent loss/gradient behavior. Existing tlparse validation artifacts show the intended rank-code order: dispatch chunk0 launch, dispatch chunk1 launch, delayed dispatch waits, combine chunk0 launch, combine chunk1 launch, and delayed combine waits annotated with EP_wait=True. 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 Test Plan: - pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -k 'ep_overlap or chunk' -q - 8 passed, 73 deselected, 2 subtests passed - pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py -k ep_overlap -q - 3 passed, 20 deselected stack-info: PR: #3328, branch: sanketpurandare/stack/14
|
|
||
| # Padding decisions require a Python branch. Only explicit hint overrides | ||
| # can justify skipping padding for otherwise data-dependent sharding. | ||
| torch._check(size % num_chunks == 0) |
There was a problem hiding this comment.
I think this part leaks the hint outside of optimizations; now the information can be used for general tracing, and I don't think we should do it (just go through this process again in a later optimization). Other than that looks good, you might be able to simplify away some of the False branches.
cc @laithsakka
There was a problem hiding this comment.
Thanks, I think the important distinction here is that the hint is not being baked into the graph as a concrete shape value. The hint only chooses the no-padding policy branch during tracing; the emitted check is still on the symbolic condition itself:
torch._check(size % num_chunks == 0)So if the hint is 8, a later runtime size of 16 still passes because it satisfies the symbolic divisibility condition, while a runtime size of 10 fails closed instead of silently skipping required padding. The graph is not specialized to 8; it records the actual DTensor sharding precondition.
That check is why this remains safe. Without it, tracing the no-padding branch from the hint would make odd runtime sizes unsafe. With it, the hint is only used to select the branch, and the graph carries the symbolic condition needed to justify that branch.
I also simplified the helper's false branches as suggested.
There was a problem hiding this comment.
hmm then maybe there is an argument that the frontend should specify torch._check(size % num_chunks == 0) instead of optimization_hint for safety, but I am not sure about your use case
There was a problem hiding this comment.
I agree that if a higher-level frontend already owns the invariant, emitting torch._check(size % num_chunks == 0) there would be the cleanest contract.
In this case DTensor still has to choose a padding policy locally. For unbacked SymInts, guard_or_false(size % num_chunks == 0) cannot prove the divisibility predicate, so without an explicit hint we must conservatively take the padding path. That is semantically conservative, but it is not representable for this use case today: even when the runtime size would be evenly divisible and the actual padding amount would be zero, the traced padding path still constructs symbolic pad sizes from the unbacked SymInt, and those flow into padding/unpadding helpers that require concrete Python padding values.
The hint is only used to choose the trace-time no-padding policy branch. It is not used as a runtime guard, and the graph is not specialized to the hinted value. The no-padding branch emits the actual symbolic precondition:
torch._check(size % num_chunks == 0)So runtime values that satisfy divisibility continue to work, while values that do not satisfy it fail closed instead of silently skipping required padding.
Given the current padding path cannot handle symbolic pad sizes, I do not see a way around using the explicit hint to select the no-padding branch, with the symbolic _check preserving correctness.
Stacked PRs: * #183545 * #183544 * #183495 * #183398 * __->__#183397 --- --- --- ### [ATen][FakeTensor] Handle unbacked dims in folded matmul The folded matmul path used for ND @ 1D/2D tensors was still forcing concrete sizes in two places: the empty-tensor check used numel(), and the fold/view path built concrete DimVector shapes from sizes(). With unbacked input dimensions, both paths can require specializing a data-dependent symbol even though the operation can be represented symbolically. Keep the folded path symbolic by using sym_numel(), sym_sizes(), sym_strides(), reshape_symint(), _unsafe_view_symint(), and symbolic output resize. The contiguity predicate now uses symbolic equality guarded through TORCH_GUARD_OR_FALSE instead of forcing concrete stride/shape integers. Also let fake view metadata recover from hinted unbacked contiguity relations by emitting symbolic equality checks for stride relations that are true at the traced hint. This handles shapes such as 2 * (u0 // 2) with a stride expressed through u0 without specializing u0 to a concrete value. Add fake tensor regression tests for rank-3 linear with an unbacked batch dimension and hinted unbacked view contiguity. Test Plan: python test/test_fake_tensor.py FakeTensorTest.test_linear_rank3_unbacked_batch_dim FakeTensorTest.test_view_unbacked_contiguous_relation_from_hints -v lintrunner --config=.lintrunner.toml aten/src/ATen/native/LinearAlgebra.cpp torch/_decomp/decompositions.py torch/_subclasses/fake_impls.py test/test_fake_tensor.py Fixes pytorch/torchtitan#3322 Pull Request resolved: #183397 Approved by: https://github.com/laithsakka
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
aa4268f to
191dc5a
Compare
…ked SymInts (#183544) Stacked PRs: * #184911 * #183840 * #183839 * #183838 * #183837 * #183545 * __->__#183544 --- --- --- ### [Inductor][Bucketing] Make collective bucketing tolerate hinted unbacked SymInts Collective bucketing uses tensor metadata for two distinct purposes. The bucket merge graph needs symbolic tensor shapes to remain symbolic, while bucket sizing and foreach grouping need concrete values only as optimization-policy estimates. Contract: - Semantic tensor shape paths must stay symbolic. Expressions such as x.numel(), x.shape[0] // group_size, split sizes, torch.empty symbolic extents, narrow offsets/lengths, and reshape shapes describe runtime tensor semantics and must not be specialized from hints. - Optimization-policy paths may use concrete hints. Bucket byte-size accounting and foreach grouping are policy decisions, so hinted unbacked SymInts are supported there, but unhinted unbacked SymInts fail fast with a clear bucketing error. - Hints are not a promise to specialize graph shapes. They are used only for sizing/grouping decisions where a Python integer is required to choose an optimization policy. - The supported symbolic policy values are concrete ints, backed SymInts, unbacked SymInts with optimization hints, and derived expressions from those hinted symbols such as u0 // 2 and hidden * (u0 // 2). Replace the policy uses of concrete shape extraction with local hint helpers that evaluate concrete ints, direct SymInt hints, and ShapeEnv optimization hint overrides. If a symbolic policy value cannot be resolved from hints, fail with a clear bucketing error instead of falling back to unbacked-symbol heuristics or forcing a guarding specialization. Leave semantic merge-function sizes symbolic: numel(), split sizes, empty sizes, narrow extents, and reshape shapes continue to flow into the traced bucket graph as symbolic expressions. This lets hinted unbacked chunk expressions such as u0 // 2 survive through all-gather and reduce-scatter bucketing. Add trace-only coverage for hinted unbacked chunked fake tensors in all-gather and reduce-scatter bucket traces, plus a no-hint failure case for optimization-policy grouping. Also make compute-estimation artifact logging tolerate scalar symbolic metadata on FX node arguments; those symbols are valid metadata, but they are not tensor-like values with dtype/shape. Fixes #183676 Test Plan: python test/distributed/test_inductor_collectives.py -k TestBucketingTrace -v python test/distributed/test_inductor_collectives.py TestCollectivesInductor.test_all_gather_bucket_bucket_mode_custom_ops TestCollectivesInductor.test_reduce_scatter_bucket_bucket_mode_custom_ops -v python test/distributed/test_overlap_bucketing_unit.py TestNodeRuntimeEstimationUnit.test_compute_estimation_logging_handles_symbolic_scalar_meta -v lintrunner --config=.lintrunner.toml torch/_inductor/fx_passes/bucketing.py torch/_inductor/fx_passes/node_runtime_estimation.py test/distributed/test_inductor_collectives.py test/distributed/test_overlap_bucketing_unit.py pytest torchtitan/experiments/graph_trainer/tests/test_passes.py::TestChunkPasses::test_chunk_pass_guardrails_and_pipeline_order -q pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py::TestGraphTrainerNumerics::test_moe_dsv3_ep_overlap_aot_fx_trace_vs_eager_chunked -q Pull Request resolved: #183544 Approved by: https://github.com/IvanKobzarev
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
191dc5a to
cf06a7f
Compare
|
@pytorchbot merge -f "One unrelated failure wrt torchtitan and one unexpected Success which for test/distributed/tensor/test_dtensor_ops.py::TestUnbackedDTensorOpsCPU::test_unbacked_dtensor_op_db_nn_functional_pixel_shuffle_cpu_float32. So this PR actually fixed it so we can enable it in future" |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
@pytorchbot revert -m "Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable" -c autorevert This PR is attributed to have caused regression in:
Note: This revert was accelerated by the AI advisor: AI advisor: revert (confidence=0.90); AI advisor: revert (confidence=0.92); AI advisor: revert (confidence=0.92) Please investigate and fix the issues. |
|
Claude finished @pytorch-auto-revert[bot]'s task in 6m 6s —— View job Revert Diagnostics
DiagnosisThe revert is legitimate. The PR introduced a regression in view sharding propagation that caused previously-passing compiled DTensor tests to fail. Root CauseFrom the CI log (job 79780857310), there are two distinct effects from this PR: 1. "Unexpected success" in The PR's explicit hint mechanism allowed 2. Regression in compiled DTensor tests ( The PR added a new early-exit check in cmd = self.rule[tgt_shard_dim]
if isinstance(cmd, Split) and isinstance(cmd.input_dim, Flatten):
first_dim = cmd.input_dim.input_dims[0]
if isinstance(first_dim, InputDim) and p.dim != first_dim.input_dim:
raise RuntimeError(
f"Shard(dim={p.dim}) through Split(Flatten(...), {cmd.group_shape}) "
f"is not supported yet for non-first flatten dims."
)The error traceback (lines 40066-40078) shows the propagation path: This check raises for The ops Guidance for the Fix
|
|
@pytorchbot successfully started a revert job. Check the current status here. |
|
@sanketpurandare your PR has been successfully reverted. |
DTensor sharding falls back to conservative behavior when a shard size is unbacked because divisibility and sharding metadata often require Python decisions. That is correct for arbitrary symbolic sizes, but it is too conservative for tracing paths that explicitly override optimization hints and know that a sharded dimension or strict-view split factor is stable. This change only trusts explicit optimization hint overrides for those Python decisions. When a hint selects a no-padding or shardable branch, the traced graph still emits the symbolic torch._check for the correctness predicate, so runtime values that satisfy the predicate continue to work and values that violate it fail closed. The hint chooses the trace-time policy branch; it is not baked in as a concrete tensor extent. For _StridedShard, view propagation now preserves a symbolic split_factor when the split factor came from symbolic shape propagation. The C++ placement still needs an int64_t unroll count for list-based lowering, so the Python wrapper stores the symbolic split factor separately and uses the explicit hint only as a guarded unroll count. The equality assertion is deferred instead of directly calling torch._check(symbol == hint), because the direct check immediately refines the ShapeEnv replacement and destroys the symbolic split_factor metadata we need to preserve. A post-merge revert found additional gaps. First, strict view propagation could raise for Shard on a non-first flattened input dim through a combined Split(Flatten(...)) rule. That combined rewrite cannot preserve the exact intermediate _StridedShard placement, so it now falls back to input replication for that mesh dim instead of crashing. During compiled DTensor tracing, the same redistribution path can create temporary local fake symbols while computing per-rank shard offsets; those symbols are implementation details because DTensor returns the global output contract through the output spec, so they are ignored while tracing local redistribution and local compute. Second, the ignore-fresh-symbol helper must live in this commit, not in a later stack commit, because PR 183545 CI runs this commit independently. Third, stale xfails are removed only where the behavior now genuinely works: eager/multithreaded view and reshape, unbacked view_copy, and unbacked pixel_shuffle/pixel_unshuffle. Compiled view and reshape remain xfailed because AOTAutograd alias replay still reaches DTensor as_strided. The view fallback test is also updated to distinguish comm-free representable cases from deliberate Replicate fallback cases, and the _StridedShard utility test now mocks the all_gather_single path that the code actually calls. Assisted by Codex. Fixes #183678 Test Plan: ```bash pip install -e . -v --no-build-isolation --no-deps ``` ```bash PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=3 python test/distributed/tensor/test_dtensor_ops.py TestCompiledDTensorOpsCPU.test_compiled_dtensor_op_db_take_along_dim_cpu_float32 -v PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=2 python test/distributed/tensor/test_dtensor_ops.py TestCompiledDTensorOpsCPU.test_compiled_dtensor_op_db_linalg_tensorsolve_cpu_float32 -v PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=0 python test/distributed/tensor/test_dtensor_ops.py TestCompiledDTensorOpsCPU.test_compiled_dtensor_op_db_nn_functional_instance_norm_cpu_float32 -v python test/distributed/tensor/test_view_ops.py TestViewOps.test_split_flatten_non_first_shard_falls_back_to_replicate -v python test/distributed/tensor/test_dtensor_ops.py -k test_unbacked_dtensor_op_db_view_copy_cpu_float32 -v python test/distributed/tensor/test_dtensor_ops.py -k test_unbacked_dtensor_op_db_nn_functional_pixel_shuffle_cpu_float32 -v ``` ```bash python -m pytest test/distributed/tensor/test_dtensor_ops.py -q -k 'test_compiled_dtensor_op_db_reshape_cpu_float32 or test_dtensor_op_db_reshape_cpu_float32 or test_dtensor_op_db_view_cpu_float32 or test_unbacked_dtensor_op_db_nn_functional_pixel_unshuffle_cpu_float32' python -m pytest test/distributed/tensor/test_dtensor_ops.py -q -k 'test_compiled_dtensor_op_db_view_cpu_float32 or test_dtensor_op_db_view_cpu_float32' python test/distributed/tensor/test_view_ops.py TestViewOps.test_dtensor_flatten_split_multi_mesh -v python test/distributed/tensor/test_utils.py LocalTest.test_strided_shard_to_replicate_preserves_even_unbacked_shape -v python test/distributed/tensor/test_dtensor_compile.py TestDTensorCompile.test_dtensor_different_gradient_placement -v python test/distributed/tensor/test_compile_on_one_rank.py TestCompileOnOneRank.test_compiled_dtensor_rng_op_graph_consistency -v python test/distributed/tensor/debug/test_debug_mode.py TestDTensorDebugMode.test_debug_mode_mm -v python test/inductor/test_compiled_autograd.py TestCompiledAutograd.test_dtensor_backward_symints_do_not_reuse_native_sharding_cache -v python test/dynamo/test_fx_graph_runnable.py FxGraphRunnableTest.test_dtensor_compile_redistribute -v lintrunner -a ``` ```bash python -m pytest -q test/distributed/tensor/test_placement_types.py test/distributed/tensor/test_view_ops.py::TestViewOps::test_view_groups_unbacked_sharding_propagation ``` ```bash lintrunner --config=.lintrunner.toml torch/distributed/tensor/placement_types.py torch/distributed/tensor/_ops/_view_ops.py torch/distributed/tensor/_ops/utils.py test/distributed/tensor/test_placement_types.py test/distributed/tensor/test_view_ops.py ``` stack-info: PR: #183545, branch: sanketpurandare/stack/10
|
@pytorchbot merge -f "Unrelated failures, 2 from broken trunk and 1 unrelated optimizer test that is not affected by this PR" |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Stacked PRs:
[DTensor] Use explicit hints for unbacked sharding
DTensor sharding falls back to conservative behavior when a shard size is
unbacked because divisibility and sharding metadata often require Python
decisions. That is correct for arbitrary symbolic sizes, but it is too
conservative for tracing paths that explicitly override optimization hints and
know that a sharded dimension or strict-view split factor is stable.
This change only trusts explicit optimization hint overrides for those Python
decisions. When a hint selects a no-padding or shardable branch, the traced graph
still emits the symbolic torch._check for the correctness predicate, so runtime
values that satisfy the predicate continue to work and values that violate it
fail closed. The hint chooses the trace-time policy branch; it is not baked in as
a concrete tensor extent.
For _StridedShard, view propagation now preserves a symbolic split_factor when
the split factor came from symbolic shape propagation. The C++ placement still
needs an int64_t unroll count for list-based lowering, so the Python wrapper
stores the symbolic split factor separately and uses the explicit hint only as a
guarded unroll count. The equality assertion is deferred instead of directly
calling torch._check(symbol == hint), because the direct check immediately
refines the ShapeEnv replacement and destroys the symbolic split_factor
metadata we need to preserve.
A post-merge revert found additional gaps. First, strict view propagation could
raise for Shard on a non-first flattened input dim through a combined
Split(Flatten(...)) rule. That combined rewrite cannot preserve the exact
intermediate _StridedShard placement, so it now falls back to input replication
for that mesh dim instead of crashing. During compiled DTensor tracing, the same
redistribution path can create temporary local fake symbols while computing
per-rank shard offsets; those symbols are implementation details because DTensor
returns the global output contract through the output spec, so they are ignored
while tracing local redistribution and local compute.
Second, the ignore-fresh-symbol helper must live in this commit, not in a later
stack commit, because PR 183545 CI runs this commit independently. Third, stale
xfails are removed only where the behavior now genuinely works: eager/multithreaded
view and reshape, unbacked view_copy, and unbacked pixel_shuffle/pixel_unshuffle.
Compiled view and reshape remain xfailed because AOTAutograd alias replay still
reaches DTensor as_strided. The view fallback test is also updated to distinguish
comm-free representable cases from deliberate Replicate fallback cases, and the
_StridedShard utility test now mocks the all_gather_single path that the code
actually calls.
Assisted by Codex.
Fixes #183678
Test Plan:
pip install -e . -v --no-build-isolation --no-depscc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo