Skip to content

[DTensor] Reduce sharded any/all locally instead of all-gathering - #204895

Closed
aditvenk wants to merge 1 commit into
mainfrom
fix/dtensor-bool-reductions-204864
Closed

aditvenk wants to merge 1 commit into
mainfrom
fix/dtensor-bool-reductions-204864

Conversation

@aditvenk

@aditvenk aditvenk commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue or supporting maintainer

Fixes #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.

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.

@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (dtensor) release notes category labels Nov 14, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - 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.

Findings (7):

[minor] torch/distributed/tensor/_sharding_prop.py:747
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.

[minor] test/distributed/tensor/test_math_ops.py:408
(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.

[minor] torch/distributed/tensor/_ops/_math_ops.py:375
(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.

[minor] torch/distributed/tensor/_sharding_prop.py:532
(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.

[minor] torch/distributed/tensor/_sharding_prop.py:747
(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.

(2 more not shown, see the review run)

Reviewed commit: 93d848c (NOT the current head 81f28c0)

Review run

🐛 Report a bad review

🔗 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 Failures

As of commit 81f28c0 with merge base a35fc9b (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 14, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 14, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

out_tensor_meta = self._propagate_tensor_meta_non_cached(op_schema)

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.


@skip_if_lt_x_gpu(4, allow_cpu=True)

(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() &lt; 2, ...). Using skipGPUIf(torch.accelerator.device_count() &lt; 4, ...) would keep CPU coverage. Check whether the _min_gpus_required stamp is still needed for distributed_4gpu test selection.


# all/any are listed here because the remaining reduction helpers share this map,

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


# data dependent ops can't be used for fake propagation

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


out_tensor_meta = self._propagate_tensor_meta_non_cached(op_schema)

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


@register_single_dim_strategy(aten._assert_async.msg)

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


partial = Partial(reduction_op)

(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

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 14, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

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 .item() / bool() / _assert_async, so my recommendation is Needs Discussion.

Full review

Summary

The PR lets DTensor any/all on a sharded reduce dim reduce locally into Partial("max")/Partial("min"). It also removes the _local_scalar_dense / _assert_async.msg bypass in ShardingPropagator, so both ops now require a Replicate input.

I checked the following and found no defects:

  • Bool MAX/MIN collectives on NCCL (sent as uint8) and gloo.
  • Bool P(max) → S reduce-scatter.
  • Empty and uneven shards: the any/all identities match max/min.
  • out= rule layout and cache key: out is never redistributed, and candidates are filtered to out's current placement.
  • The numeric-partial filter's input spec.
  • The 0-output path through expand_to_full_mesh_op_strategy and wrap.

All points below are non-blocking. Nothing was executed in this job; this is a static review.

Backward Compatibility

  • The .item() / bool() / assert change needs its own BC note (torch/distributed/tensor/_sharding_prop.py:744-755).
    • What changed: the dormant Replicate-only local_scalar_dense_single_dim_strategy (_ops/_tensor_ops.py:532) now takes effect for every non-Replicate DTensor, not just any/all results. These calls used to run on the local shard with no communication. They now redistribute first, which issues a collective.
    • Correctness: this fixes a real bug. Before, .item() on Partial silently returned the rank-local value.
    • Hang risk: rank-conditional calls like if rank == 0: print(loss.item()) will now deadlock. ExplicitRedistributionContext(strict=True) will also start raising on them.
    • Description: the "BC-breaking?" section only mentions any/all now returning P instead of R. That change also means x.isnan().any().to_local() silently becomes rank-local. Please describe both changes there and in the release notes.

Testing

  • Stale filter to try removing (non-blocking). test/distributed/tensor/test_dtensor_ops.py:626 filters out num_classes=-1 because of "a bug with dtensor.max().item()". That bug was the bypass this PR removes. Please drop the filter and confirm run_one_hot passes, which would also be a real regression test for the .item() fix.
  • Stale docstring (non-blocking). test/distributed/tensor/test_decompositions.py:206-217 (test_assert_async) still explains the removed early return. It now passes for a different reason: all gives a Partial, which is all-reduced before the assert.
  • CPU variants are skipped or spawn extra pools (non-blocking).
    • skip_if_lt_x_gpu(4, allow_cpu=True) at test_math_ops.py:408 and :473 skips the CPU/gloo variant on any 1–3 GPU host. skipGPUIf(torch.accelerator.device_count() < 4, ...) matches the sibling class.
    • instantiate_device_type_tests(...) at test_math_ops.py:2664-2665 has no only_for. On GPU runners this spawns extra MultiProcContinuousTest pools. test_dtensor_ops.py:1211-1225 passes only_for=(DEVICE_TYPE,).
    • DTensorContinuousTestBase._init_pg binds devices from _get_device_type(world_size), not cls.device_type, so the CPU variant only really runs on CPU-only CI anyway.
  • Test helper is too complex for what it protects (non-blocking). _AssertAsyncTensorCaptureMode plus the dual capture/real-execution path in test_bool_reduction_assert_async is the most fragile part of the 334 added test lines. A CPU-only failing-assert check plus a passing-assert comm count on the accelerator would cover the same contract.

Code Quality

  • Inconsistent overload coverage (non-blocking).
    • Only any.out is registered, not all.out, {any,all}.dims_out or {any,all}.all_out.
    • Only _assert_async.msg gets the Replicate strategy, not _assert_async.default. torch._assert_async(dt) without a message still raises "no sharding strategy".
    • Both gaps predate the PR, but the PR makes the overloads behave differently for the same predicate.
  • Stale and misleading comments (non-blocking).
    • _math_ops.py:375-376 says all/any sit in LINEAR_REDUCTION_OP_MAP only because helpers share the map. They are now read to pick the Partial reduce op.
    • NON_LINEAR_BOOL_REDUCTION_OPS no longer describes ops that produce Partials.
    • _sharding_prop.py:532 labels _assert_async.msg "data dependent". It is skipped because it has no outputs.
  • The filter's protection is incomplete (non-blocking, follow-up).
    • The numeric-partial guard is applied only in expand_to_full_mesh_op_strategy. The Dijkstra / PreparedSingleDimStrategy.try_propagate path ignores full_mesh_strategy_filter; the mean and argmax filters have the same gap.
    • The same bool(max(-1, 0)) != max(bool(-1), bool(0)) hazard already exists in aten.to.dtype (_pointwise_ops.py:401-406), which keeps P(max)/P(min) through float→bool casts. That one is pre-existing.

Recommendation

Needs Discussion

The implementation looks correct. The remaining question is whether maintainers accept that .item(), bool() and _assert_async on any non-Replicate DTensor now issue a collective. That change is correct but can hang rank-conditional code. Please document it as a BC note before landing.

@pianpwk pianpwk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks! we could also implement this with a custom op handler, just to be explicit, but nbd

self._custom_op_handlers = {
aten.is_same_size.default: is_same_size_handler,
aten.is_pinned.default: is_pinned_handler,
aten.convolution.default: convolution_handler,
aten.convolution_backward.default: convolution_backward_handler,
aten._amp_foreach_non_finite_check_and_unscale_.default: found_inf_reduce_handler,
aten.as_strided.default: as_strided_handler,
aten.argmin.default: argminmax_handler,
aten.argmax.default: argminmax_handler,
}

@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 15, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@aditvenk

Copy link
Copy Markdown
Contributor Author

@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

@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

@aditvenk your PR has been successfully reverted.

pytorchmergebot added a commit that referenced this pull request Nov 17, 2026
…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)))
@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@pytorch-auto-revert

Copy link
Copy Markdown

@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 Can you please read this revert comment, follow the links and read the errors, to then give a brief diagnostics on the cause of the error? If you judge the error to be legitimate reason for a revert, please provide brief guidance on how the author could fix it.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @pytorch-auto-revert[bot]'s task in 45s —— View job


The revert is legitimate: it's a land race, and the _infer_reduction_dims call this PR adds doesn't match the signature now on main. Besides failing pyrefly, it would raise a TypeError at runtime.

Diagnosis and fix

Error

lintrunner-pyrefly-all / lint fails with:

>>> Lint for torch/distributed/tensor/_nonlinear_redux.py:
  Error (PYREFLY) missing-argument
    Missing argument `op` in function
    `torch.distributed.tensor._ops._math_ops._infer_reduction_dims`

    343  |    reduced_dims = _infer_reduction_dims(dim, input_spec.ndim)

Cause

_infer_reduction_dims on main now takes a third op argument (torch/distributed/tensor/_ops/_math_ops.py:135-151). The function uses it to decide what an empty dim list means. For any/all (NON_LINEAR_BOOL_REDUCTION_OPS) and prims reductions, dim=[] means no dims are reduced; for other ops it means all dims. Every other caller on main already passes op. The PR's new call in _bool_reduction_plan (torch/distributed/tensor/_nonlinear_redux.py:343) was written against the older two-argument signature. The PR's CI ran before that change reached the merge base, so it was green.

This is more than a typing nit. At runtime the call raises TypeError: missing 1 required positional argument: 'op' whenever any/all needs a redistribution. That covers most sharded any/all calls, so reverting was the right call.

Fix

Rebase onto current main and pass the op:

reduced_dims = _infer_reduction_dims(dim, input_spec.ndim, op_call)

Passing op_call also keeps the handler consistent with the strategy: any.dims / all.dims with dim=[] reduce nothing, so no mesh dim should be reduced locally. It's worth adding a test for an empty dims list (for example dt.any(dim=[]) on a Shard(0) input).

Before re-landing, run locally:

lintrunner -m origin/main
python test/distributed/tensor/test_math_ops.py DTensorBoolReductionTestCPU DTensorBoolReduction2DMeshTestCPU

This is a static diagnosis from the job log and the current source. I did not run the lint or the tests here.

@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

@aditvenk your PR has been successfully reverted.

pytorchmergebot added a commit that referenced this pull request Nov 25, 2026
…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.
@aditvenk
aditvenk force-pushed the fix/dtensor-bool-reductions-204864 branch from 60c4f21 to 81f28c0 Compare November 25, 2026 21:09
@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@aditvenk

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 26, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triage-error 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 GL/human GreenLight marked as needing human review GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (dtensor) release notes category Reverted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[DTensor] any/all on sharded reduction dim all-gathers full tensor (trunc_normal_ init gathers every param)

5 participants