Skip to content

[perf] custom DTensor strategy for reductions of .any and .all - #201840

Closed
francesco-bertolotti wants to merge 3 commits into
pytorch:mainfrom
francesco-bertolotti:f14-no-big-all-gathers-in-truc-normal
Closed

francesco-bertolotti wants to merge 3 commits into
pytorch:mainfrom
francesco-bertolotti:f14-no-big-all-gathers-in-truc-normal

Conversation

@francesco-bertolotti

Copy link
Copy Markdown

Linked issue or supporting maintainer

I don't think there's a reported issue for this.

BC-breaking?

No.

Summary (human written only)

I recently switched to trunc_normal_ for LLM weight initialization, and init time spiked to 10 minutes. After investigating, I found that trunc_normal_ internally calls .any() several times. On DTensor, this triggers expensive and unnecessary all-gathers.

The naive solution would be to iterate over each local shard independently. However, Claude gaslighted me into believing that it might be useful to have the RNG state of all ranks advance in sync. So this PR introduces a single boolean all-reduce to decide whether any rank needs to redraw samples, avoiding repeated all-gathers of the full mask.

This issue affects DeepSeek Initialization of TorchTitan

Agent details (if applicable)

nn.init.trunc_normal_ checks for rejected samples using mask.any() in its rejection loops. On a sharded DTensor, the any strategy only shards along non-reduction dimensions. A full reduction therefore redistributes the mask to Replicate, triggering an all-gather of a tensor-sized mask on every iteration.

This PR adds an _any helper that, for DTensor inputs, reduces the local shard and all-reduces a single integer flag using MAX across the sharded mesh dimensions. Plain tensors are unaffected and do not require importing torch.distributed.tensor.

Test plan:

python test/nn/test_init.py -k trunc_normal
python test/distributed/_composable/fsdp/test_fully_shard_extensions.py -k end_to_end -k monkey_patch
python test/distributed/tensor/test_random_ops.py -k trunc_normal

Authored with Claude Code.

@pytorch-bot

pytorch-bot Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

PR Status: missing actionable issue

Auto PR Triage did not find either of the following when it checked this PR:

  • a linked issue labeled actionable (Fixes #<issue> or Part of #<issue>); or
  • a maintainer named in the description who agreed to the change (Supported by @<maintainer>).

Such PRs are a low priority for maintainers to review and might not get a response given the very high volume of PRs we receive. Please focus on actionable issues to ensure a maintainer will be available to review your PR.

If one of these applies, add the matching line to the PR description. If there is no actionable issue for this change yet, you can open one (or comment on an existing one) and wait for a maintainer to label it actionable. Adding actionable to an already-linked issue automatically requests re-triage of open, non-draft PRs with missing actionable issue, unless automated triage is disabled. Adding a valid actionable-issue link or Supported by line to the description also requests re-triage automatically. Marking the PR ready, reopening it, or re-enabling automated triage rechecks existing links and support. If re-triage is still needed, comment @pytorchbot triage to run Auto PR Triage again.

🔗 Helpful Links

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

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

❌ 4 Awaiting Approval, 6 New Failures, 6 Unrelated Failures

As of commit f3a408d with merge base 1776b98 (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

NEW FAILURES - The following jobs have failed:

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 2, 7, mt-l-x86iamx-8-64) (gh)
    test/test_modules.py::TestJitReplaceSubmodule::test_jit_replace_submodule_empty_qualified_name

    AI verdict: AI verdict: not related

    The test itself PASSED on every attempt. The job went red because pytest's junitxml reporter crashed with an INTERNALERROR KeyError inside the repo's custom LogXMLReruns plugin in test/conftest.py, running under pytest 9.2.0. The suspect commit only changes DTensor reduction-op handling in torch/distributed/tensor/_ops/_math_ops.py, which cannot affect pytest's report bookkeeping.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 3, 7, mt-l-x86iamx-8-64) (gh)
    test/test_modules.py::TestJitReplaceSubmodule::test_jit_replace_submodule

    AI verdict: AI verdict: infra issue

    The test itself PASSED; pytest then crashed with an INTERNALERROR KeyError inside its junitxml reporter, called from test/conftest.py's pytest_runtest_logreport override. This hit every test, including skipped test_ops tests. The cause is the test-harness environment (old CI image with pytest 9.2.0, from a month-old merge base). The suspect's DTensor _math_ops.py change is not involved.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 6, 7, mt-l-x86iamx-8-64) (gh)
    test/test_ops.py::TestCommonCPU::test_compare_cpu___rxor___cpu_int64

    AI verdict: AI verdict: infra issue

    The failure is a pytest INTERNALERROR (KeyError in junitxml finalize via test/conftest.py pytest_runtest_logreport). It fires on a test that was SKIPPED and repeats on unrelated tests in other shards, so no real test outcome was produced. The suspect only modifies DTensor reduction strategy tables in torch/distributed/tensor/_ops/_math_ops.py, which this test never touches. The likely cause is the PR's month-old base conftest clashing with the current CI pytest 9.2.0 environment.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-test-cuda132 / test (inductor_cpp_wrapper, 2, 2, mt-l-x86aavx2-11-41-a10g) (gh)
    test/inductor/test_torchinductor_opinfo.py::TestInductorOpInfoCUDA::test_comprehensive_linalg_cross_cuda_float64

    AI verdict: AI verdict: not related

    The test passes, but pytest then crashes with an INTERNALERROR KeyError in junitxml finalize. The cause is the PR's month-old merge base: its test/conftest.py LogXMLReruns.node_reporter stores reporters under a plain (nodeid, workernode) key, while the newer pytest in the current CI image looks them up by NodeId objects. Trunk has already rewritten node_reporter to fix this. The suspect diff only touches DTensor reduction strategies and plays no part.

    Full reasoning on HUD →

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot missing actionable issue A PR without a linked actionable issue or maintainer sponsor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 23, 2026
@francesco-bertolotti

Copy link
Copy Markdown
Author

@pytorchbot label "release notes: distributed (dtensor)" "topic: performance"

@pytorch-bot pytorch-bot Bot added release notes: distributed (dtensor) release notes category topic: performance topic category labels Oct 23, 2026

@Skylion007 Skylion007 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I don't think this is the right way to handle this, a custom DTensor strategy used in the registry is.

@francesco-bertolotti

Copy link
Copy Markdown
Author

Hi @Skylion007,

Thanks for the quick review. I had considered changing how any is sharded, but held off because of this comment:

# all/any are NOT linear reductions: validation showed S(reduction_dim)->P(...)
# produces incorrect results. They only support sharding on non-reduction dims.

If I read it right, it concerns mapping any/all to the linear sum/product partials. Would a dedicated strategy for any/all that produces Partial("max")/Partial("min") on the reduced sharded dims be what you have in mind? If so, I'll try to rework the PR that way.

get Partial(max) for any and Partial(min) for all.
This avoids expensive all-gathers when calling any on huge masks.
Example:
Input Placement: (Shard(0), Shard(1)), Op: any()
Strat Placement: (Partial(max), Partial(max))
@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Oct 24, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@francesco-bertolotti

francesco-bertolotti commented Oct 24, 2026 •

Copy link
Copy Markdown
Author

Hi @Skylion007, thanks for the pointer. I reworked the PR along those lines: the change in torch/nn/init.py is gone, and the fix is now in the DTensor sharding rule for any/all (bool_reduction_single_dim_strategy).

A shard on a reduction dim now maps to Partial("max") for any and Partial("min") for all, which on the boolean outputs are OR and AND. Shards on kept dims are unchanged, and a Partial input is still not propagated.

With this, mask.any() in trunc_normal_'s rejection loop does one scalar all-reduce per iteration instead of all-gathering the mask.


f3a408d also registers aten.all.dims with the bool strategy (it was missing, unlike any.dims), and fixes _infer_reduction_dims so an int dim on a 0-d tensor is treated as no reduction dims; previously it emitted an unreachable S(0) -> P(max) rule that the validator flagged.

@francesco-bertolotti francesco-bertolotti changed the title avoid expensive all gather in trunc normal [perf] custom DTensor strategy for reductions of .any and .all Oct 24, 2026
aditvenk added a commit that referenced this pull request Nov 25, 2026
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 unchanged and no Partial leaves the op. aten.all.dims now gets
the bool reduction strategy like aten.any.dims.

#204895 instead returned Partial from any/all and made .item()/bool() reduce
Partial inputs: rank-asymmetric .item() callers hung, and the Partial rules
leaked 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 ~10 us of Python dispatch to calls that
need no collective.

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 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 added a commit that referenced this pull request Nov 25, 2026
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 unchanged and no Partial leaves the op. aten.all.dims now gets
the bool reduction strategy like aten.any.dims.

#204895 instead returned Partial from any/all and made .item()/bool() reduce
Partial inputs: rank-asymmetric .item() callers hung, and the Partial rules
leaked 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 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 added a commit that referenced this pull request Nov 25, 2026
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

Copy link
Copy Markdown
Contributor

@francesco-bertolotti -- We had an earlier attempt that tried to propagate Partial(max/min) for any/all, but that breaks subsequent bool()/.item() accesses on the DTensor which operate only on the local shards. Forcing a Replicate prior to those operators broke internal tests hence we had to revert.

I have reworked the PR to do the any/all on local shards and then reduce the scalar outputs #204895 ; this will preserve BC on these ops w.r.t output placements, but avoid the expensive AG collective.

Can you give this a spin if it works for your needs?

@francesco-bertolotti

Copy link
Copy Markdown
Author

Tested #204895 (applied to the 2026-11-23 nightly) on 4xGH200 with our FSDP2 trainer's init test, with and without CPUOffloadPolicy: both pass (replicas identical, shards distinct, values within the truncation bounds). trunc_normal_ now does 4 small all-reduces instead of 4 all-gathers, and bool(t.any()) agrees across ranks. With this PR's Partial(max) approach it did not: ranks returned [False, False, False, True].

So I am closing this PR.

aditvenk added a commit that referenced this pull request Nov 25, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests missing actionable issue A PR without a linked actionable issue or maintainer sponsor open source release notes: distributed (dtensor) release notes category topic: performance topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants