Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (7): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/204895
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 81f28c0 with merge base a35fc9b ( 🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:
Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval. This comment was automatically generated by Dr. CI and updates every 15 minutes. |
There was a problem hiding this comment.
Automated review of 93d848c: nothing blocking; ready for human review.
The PR lets DTensor any/all reduce shards on the reduced dim locally into Partial("max")/Partial("min") instead of all-gathering them first, and stops skipping sharding propagation for _local_scalar_dense and _assert_async.msg, so both now require a Replicate input. Recommendation: Needs Discussion. The implementation looks correct, but maintainers need to acknowledge the user-visible behavior change, which the PR labels as not BC-breaking, and add release notes.
⚪ 7 non-blocking findings
BC: removing the early returns changes .item(), bool(), float() and torch._assert_async(t, msg) on every non-Replicate DTensor, not only on any/all results. Before, OutputSharding(None, op_schema) was returned and the op ran on the local shard with no communication. Now Shard/Partial inputs are redistributed to Replicate, which issues a collective. Effects: dt.sum().item() on Partial("sum") now returns the global value instead of the rank-local partial (a bug fix, but users will see it). Rank-conditional calls like if rank == 0: print(loss.item()) on a non-Replicate loss will now deadlock. any/all on an input sharded on a reduced dim now return Partial("max")/Partial("min") instead of Replicate() (_math_ops.py:613-615), so .to_local(), placement checks, or local_map/plain-Tensor code silently get a rank-local predicate. The newly registered aten.all.dims behaves the same way. Ask: fill in the "BC-breaking?" section. List the scalar-extraction/assert change as its own release-notes item, as a bug fix with the hang caveat. The title and release-note label currently describe only the any/all optimization.
(non-blocking) @ skip_if_lt_x_gpu(4, allow_cpu=True) (also at :473) ignores the device type and is evaluated at import time. It skips unless at_least_x_gpu(4) is true or no accelerator is present. On a 13 GPU host, including the standard 2-GPU distributed runner, it therefore also skips DTensorNumericPartialBoolReductionTestCPU, which only needs gloo. The sibling class uses the device-aware skipGPUIf(torch.accelerator.device_count() < 2, ...). Using skipGPUIf(torch.accelerator.device_count() < 4, ...) would keep CPU coverage. Check whether the _min_gpus_required stamp is still needed for distributed_4gpu test selection.
(non-blocking) Stale comment: it says all/any are in LINEAR_REDUCTION_OP_MAP "because the remaining reduction helpers share this map". Now the only reader of those entries is bool_reduction_single_dim_strategy (:605), which uses them to pick the Partial reduce op. The name NON_LINEAR_BOOL_REDUCTION_OPS is also misleading, since these ops now produce Partials on reduced dims.
(non-blocking) Misleading comment: _assert_async.msg is listed under "data dependent ops can't be used for fake propagation", but it has a meta kernel returning None (_meta_registrations.py:1195). It is skipped because it has no outputs.
(non-blocking) The removed rationale (asserts inside decompositions) is no longer explained anywhere, and test/distributed/tensor/test_decompositions.py:206-209 still describes that special case. Inside PlacementTrackingMode, a non-Replicate predicate now rejects the candidate with "Decomposition requires redistribution" (_decompositions.py:118-137, :224-227). BCE and one_hot end up with the same candidates as before, but the docstring's reasoning no longer matches the code.
(non-blocking) Only aten._assert_async.msg gets the Replicate-only strategy. aten._assert_async.default, which torch._assert_async(dt) without a message dispatches to, still has no strategy and raises "does not have a sharding strategy registered". This predates the PR, but the two overloads now behave differently for the same predicate. Consider registering both.
(non-blocking) The hand-written \[Partial(op), _ShardingPlaceholder(d)\] loop and the second reduce_dims computation (:606-615) duplicate what _reduction_single_dim_strategy already emits with reduction_linear=True (:343-352). The helper also adds an unconditional [P, P] rule, and extra_partial_rules can only append rules, not remove that one. A flag on the helper to suppress partial passthrough would remove the duplication.
This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review
|
@claude review this PR |
|
Claude finished @Skylion007's task in 1m 26s —— View job The any/all sharding logic looks correct and I found no blocking bugs. Maintainers do need to sign off on the user-visible change to Full reviewSummaryThe PR lets DTensor any/all on a sharded reduce dim reduce locally into I checked the following and found no defects:
All points below are non-blocking. Nothing was executed in this job; this is a static review. Backward Compatibility
Testing
Code Quality
RecommendationNeeds Discussion The implementation looks correct. The remaining question is whether maintainers accept that |
pianpwk
left a comment
There was a problem hiding this comment.
thanks! we could also implement this with a custom op handler, just to be explicit, but nbd
pytorch/torch/distributed/tensor/_dispatch.py
Lines 231 to 240 in dc82419
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
@pytorchbot revert -m "Breaks internal test test_moe_ep_multirank_gpu: .item() on a Partial DTensor now all-reduces, hanging rank-asymmetric callers" -c ghfirst |
|
@pytorchbot successfully started a revert job. Check the current status here. |
|
@aditvenk your PR has been successfully reverted. |
…204895)" This reverts commit 11b9713. Reverted #204895 on behalf of https://github.com/aditvenk due to Breaks internal test test_moe_ep_multirank_gpu: .item() on a Partial DTensor now all-reduces, hanging rank-asymmetric callers ([comment](#204895 (comment)))
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). 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:
Autorevert dashboard as of 2026-11-25 19:25:03 UTC Note: This revert was accelerated by the AI advisor: AI advisor: related (confidence=0.97) Please investigate and fix the issues. |
|
Claude finished @pytorch-auto-revert[bot]'s task in 45s —— View job The revert is legitimate: it's a land race, and the Diagnosis and fixError
Cause
This is more than a typing nit. At runtime the call raises FixRebase onto current main and pass the op: reduced_dims = _infer_reduction_dims(dim, input_spec.ndim, op_call)Passing Before re-landing, run locally: lintrunner -m origin/main
python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCPU DTensorBoolReduction2DMeshTestCPUThis is a static diagnosis from the job log and the current source. I did not run the lint or the tests here. |
|
@pytorchbot successfully started a revert job. Check the current status here. |
|
@aditvenk your PR has been successfully reverted. |
…ring (#204895)" This reverts commit 1c77017. Reverted #204895 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](#204895 (comment)))
any/all only shard non-reduction dims, so DTensor all-gathers an input sharded along a reduced dim just to compute a predicate. nn.init.trunc_normal_ calls mask.any() in its rejection loop, so initializing a sharded parameter all-gathers a full-size mask per iteration (#204864, #201840). bool_reduction_handler (next to argminmax_handler) runs the normal sharding propagation, but keeps the mesh dims it would redistribute that shard a reduced dim (and bool Partial inputs matching the op's max/min combine). The op reduces them locally and only the result is redistributed, from Partial("max"/"min") to the output placements propagation chose. Output placements are the ones propagation chose, and no Partial leaves the op. aten.all.dims now gets the bool reduction strategy like aten.any.dims, which changes some of its output placements. Returning Partial from any/all and making .item()/bool() reduce Partial inputs would hang rank-asymmetric .item() callers and leak the Partial into decomposition-derived strategies (isin, binary_cross_entropy). Returning the Partial without that (#201840) makes bool() rank-local, so trunc_normal_ ranks leave the loop at different iterations and their RNG offsets diverge. A strategy cannot express "reduce locally, then reduce the output", hence the handler; it adds ~8 us of Python dispatch per call. TorchTitan DeepSeekV3 init_weights on 8 B200s (FSDP, identical weights): | config | main | this PR | |---|---|---| | 671B, first 16 of 61 layers | 0.51 s | 0.24 s | | 16B, CPU offload (torchtitan#6161) | 66.5 s | 40.6 s | Test Plan: ``` python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCPU DTensorBoolReduction2DMeshTestCPU python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCUDA DTensorBoolReduction2DMeshTestCUDA python test/distributed/tensor/test_math_ops.py python -m pytest test/distributed/tensor/test_dtensor_ops.py -k "any or all_ or isin or binary_cross_entropy" python test/distributed/tensor/test_decompositions.py python test/distributed/tensor/test_utils.py ``` 128 bool-reduction tests pass on CPU/gloo and 128 on CUDA/NCCL; the other suites pass. Authored with an AI assistant.
60c4f21 to
81f28c0
Compare
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
@pytorchbot merge |
|
The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…torch#204895) ## Linked issue or supporting maintainer Fixes pytorch#204864 ## BC-breaking? No. > (AI-generated detail) For `aten.any.default`/`.dim`/`.dims` and `aten.all.default`/`.dim`, output placements and values are unchanged; only the collective differs. `aten.all.dims` now uses the bool-reduction strategy like `aten.any.dims` instead of a strategy derived from its decomposition, so some of its output placements change (they now match `aten.any.dims`). As with `aten.any.dims` and other ops with a single-dim strategy, a `register_sharding(aten.all.dims)` override is now ignored. Debug tooling sees any/all go through Python dispatch: `ExplicitRedistributionContext` messages always include the full op schema, and `mode="warn"` can warn twice when both the input and the output are redistributed; DebugMode prints `-> output:` for calls without a collective and shows the output collective as a `redistribute_input` record without an `[implicit]` header; cache hits count in the Python sharding-prop cache stats. ## Summary (human written only) any/all don't need to gather the entire input before applying the operation -- we can operate on the local shards. The first attempt at landing this PR propagated Partial(max/min) through these ops, which subsequently required us to force Replication on `bool()`, `.item()`, and `assert` operators. This unfortunately broke some internal tests. Hence, in take 2, we are retaining the BC for these ops w.r.t placements, but we avoid the expensive AG before the any/all, and instead do the operation on local shards and then reduce the smaller outputs. ## Agent details (if applicable) Authored with an AI assistant. **What the code does.** `bool_reduction_handler` in `torch/distributed/tensor/_nonlinear_redux.py` is registered in `_dispatch.py` for the six functional `any`/`all` overloads. For each call it: 1. runs the normal sharding propagation; 2. among the mesh dims propagation would redistribute, keeps the input placement of those that shard a reduced dim (`Shard` or `_StridedShard`) or hold a bool `Partial` matching the op's combine (`max` for any, `min` for all); 3. reduces locally; 4. redistributes the result from `Partial("max")`/`Partial("min")` to the output placements propagation chose: all-reduce for `Replicate`, reduce-scatter for `Shard`. The output placements are the ones propagation would give without the handler, and the op never returns a `Partial`. In `_ops/_math_ops.py`, `aten.all.dims` is registered with the bool-reduction strategy like `aten.any.dims`. The strategy itself still only shards non-reduction dims. If it emitted `Partial("max")`/`Partial("min")`, strategies derived from decompositions that call any/all (e.g. `torch.isin`) would inherit the `Partial`. **Why a handler.** - A sharding strategy can only redistribute inputs. It cannot express "reduce locally, then reduce the output". - Returning the `Partial` instead would make `bool()`/`.item()` rank-local, since they read the local tensor. For example, `nn.init.trunc_normal_` ranks would then leave the rejection loop at different iterations, and DTensor's RNG offsets would diverge. - Cost: any/all go through Python dispatch, about +8 us per call. A tiny sharded input that needs a collective costs about +30 us over main; from about 1M elements this PR is faster (see the per-call table). **Benchmarks.** TorchTitan DeepSeekV3 `init_weights`, timed on TorchTitan's own init path (meta → parallelize → `to_empty` → `init_weights`), FSDP on 8xB200. Both runs use the same 2026-11-24 nightly binaries; only torch's Python sources differ. With seed 1234 the parameter checksums match, so the weights are bit-identical. | config | main | this PR | |---|---|---| | 16B, GPU init | 0.22 s | 0.19 s | | 671B, first 16 of 61 layers (153B params), GPU init | 0.51 s | 0.24 s | | 16B, FSDP CPU offload (with torchtitan#6161) | 66.5 s | 40.6 s | | 671B, first 8 of 61 layers (61B params), FSDP CPU offload | 245 s | 162 s | - Full 671B doesn't fit in fp32 on one node, so the rows above use a prefix of its layers. Extrapolating: GPU init goes from about 2.2 s to 1.0 s; CPU-offload init goes from about 45 to 30 min, and the CPU random-number generation that remains is serial and dominates either way. - Peak GPU memory during init is 2.5 GiB lower. - Most DSv3 params use `trunc_normal_(std=0.02)` with the default bounds a/b=±2 (±100σ), so the loop rarely redraws. The saving is mostly the one full-mask all-gather per parameter; ±3σ bounds would make main's cost per parameter larger. `trunc_normal_` microbenchmark (std=0.02, a/b=±3σ, 8xB200, NCCL): | global shape, fp32, Shard(0) | main | this PR | |---|---|---| | (262144, 7168) | 20.7 ms, 4 all-gathers | 7.6 ms, 4 scalar all-reduces | Per call, 2 ranks on CUDA (`bool(...)` includes the sync, as in `if t.any():`): | call | main | this PR | |---|---|---| | 8x8 `R.any()` (no collective) | 11.2 us | 18.9 us | | 8x8 `S(0).any()` | 149.8 us | 181.8 us | | `bool(8x8 S(0).any())` | 186.4 us | 215.2 us | | `bool(1024x1024 S(0).any())` | 259.4 us | 221.2 us | **Test Plan.** ```bash python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCPU DTensorBoolReduction2DMeshTestCPU python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCUDA DTensorBoolReduction2DMeshTestCUDA python test/distributed/tensor/test_math_ops.py python -m pytest test/distributed/tensor/test_dtensor_ops.py -k "any or all_ or isin or binary_cross_entropy" python test/distributed/tensor/test_decompositions.py python test/distributed/tensor/test_single_dim_strategy.py python test/distributed/tensor/test_strategy_validation.py python test/distributed/tensor/test_utils.py python test/distributed/tensor/test_random_ops.py lintrunner --take PYFMT,RUFF,PYREFLY,CODESPELL,FLAKE8 -a ``` Results: - 128 bool-reduction tests pass on CPU/gloo and 128 on CUDA/NCCL. - `test_math_ops.py` (476) and the other suites pass. - Comparison with main over about 3000 any/all calls on 1-D and 2-D CPU meshes (Shard/_StridedShard/Partial/Replicate inputs, uneven/empty shards, bool/uint8/float with NaN): - values and placements are identical, apart from `all.dims`; - no all-gathers remain; - no call issues more collectives. - `test_trunc_normal_rejection_loop_stays_in_sync` checks that every rank runs the same number of rejection iterations. - `test_bool_reduction_in_decompositions` checks that `isin` and `binary_cross_entropy` get no `Partial` from any/all. Pull Request resolved: pytorch#204895 Approved by: https://github.com/pianpwk
Linked issue or supporting maintainer
Fixes #204864
BC-breaking?
No.
Summary (human written only)
any/all don't need to gather the entire input before applying the operation -- we can operate on the local shards.
The first attempt at landing this PR propagated Partial(max/min) through these ops, which subsequently required us to force Replication on
bool(),.item(), andassertoperators. This unfortunately broke some internal tests. Hence, in take 2, we are retaining the BC for these ops w.r.t placements, but we avoid the expensive AG before the any/all, and instead do the operation on local shards and then reduce the smaller outputs.Agent details (if applicable)
Authored with an AI assistant.
What the code does.
bool_reduction_handlerintorch/distributed/tensor/_nonlinear_redux.pyis registered in_dispatch.pyfor the six functionalany/alloverloads. For each call it:Shardor_StridedShard) or hold a boolPartialmatching the op's combine (maxfor any,minfor all);Partial("max")/Partial("min")to the output placements propagation chose: all-reduce forReplicate, reduce-scatter forShard.The output placements are the ones propagation would give without the handler, and the op never returns a
Partial.In
_ops/_math_ops.py,aten.all.dimsis registered with the bool-reduction strategy likeaten.any.dims. The strategy itself still only shards non-reduction dims. If it emittedPartial("max")/Partial("min"), strategies derived from decompositions that call any/all (e.g.torch.isin) would inherit thePartial.Why a handler.
Partialinstead would makebool()/.item()rank-local, since they read the local tensor. For example,nn.init.trunc_normal_ranks would then leave the rejection loop at different iterations, and DTensor's RNG offsets would diverge.Benchmarks.
TorchTitan DeepSeekV3
init_weights, timed on TorchTitan's own init path (meta → parallelize →to_empty→init_weights), FSDP on 8xB200. Both runs use the same 2026-11-24 nightly binaries; only torch's Python sources differ. With seed 1234 the parameter checksums match, so the weights are bit-identical.trunc_normal_(std=0.02)with the default bounds a/b=±2 (±100σ), so the loop rarely redraws. The saving is mostly the one full-mask all-gather per parameter; ±3σ bounds would make main's cost per parameter larger.trunc_normal_microbenchmark (std=0.02, a/b=±3σ, 8xB200, NCCL):Per call, 2 ranks on CUDA (
bool(...)includes the sync, as inif t.any():):R.any()(no collective)S(0).any()bool(8x8 S(0).any())bool(1024x1024 S(0).any())Test Plan.
python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCPU DTensorBoolReduction2DMeshTestCPU python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCUDA DTensorBoolReduction2DMeshTestCUDA python test/distributed/tensor/test_math_ops.py python -m pytest test/distributed/tensor/test_dtensor_ops.py -k "any or all_ or isin or binary_cross_entropy" python test/distributed/tensor/test_decompositions.py python test/distributed/tensor/test_single_dim_strategy.py python test/distributed/tensor/test_strategy_validation.py python test/distributed/tensor/test_utils.py python test/distributed/tensor/test_random_ops.py lintrunner --take PYFMT,RUFF,PYREFLY,CODESPELL,FLAKE8 -aResults:
test_math_ops.py(476) and the other suites pass.all.dims;test_trunc_normal_rejection_loop_stays_in_syncchecks that every rank runs the same number of rejection iterations.test_bool_reduction_in_decompositionschecks thatisinandbinary_cross_entropyget noPartialfrom any/all.