Skip to content

[DTensor] Fix index_put sharding strategy for None indices - #179217

Closed
aditvenk wants to merge 1 commit into
mainfrom
ps/rr/_dtensor__fix_index_put_sharding_strategy_for_none_indices_and_mid_tensor_indexing
Closed

aditvenk wants to merge 1 commit into
mainfrom
ps/rr/_dtensor__fix_index_put_sharding_strategy_for_none_indices_and_mid_tensor_indexing

Conversation

@aditvenk

@aditvenk aditvenk commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

The strategy computation for aten.index_put had two remaining issues blocking models like Falcon-7b that use list indexing (e.g. tensor[..., [-1], :]):

  1. aten.index_put_.default (in-place variant, generated by autograd in the backward of aten.index.Tensor) was not registered in the single-dim strategy system.

  2. _get_num_tensor_inputs counted None children in TupleStrategy, but args_strategy drops them, causing a count mismatch for ops with List[Optional[Tensor]] arguments.

The values-dim-to-self-dim mapping fix for consecutive indexed dims was already landed in #178350; this commit adds the missing op registration, the infra bug fix, updated docstrings, and additional test coverage for None indices, in-place index_put_, non-contiguous indexed dims, and mid-tensor indexing.

Authored with Claude.

Fixes meta-pytorch/autoparallel#348

@pytorch-bot

pytorch-bot Bot commented Apr 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 1 Pending

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

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

@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 Apr 3, 2026
@aditvenk

aditvenk commented Apr 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude Critically review this PR, especially correctness of the index_put_single_dim_strategy for corner cases

@claude

claude Bot commented Apr 3, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 28m 1s —— View job


Critical Review of index_put_single_dim_strategy

  • Read PR diff and changed files
  • Understand the existing index_single_dim_strategy (forward) logic
  • Analyze correctness of index_put_single_dim_strategy for corner cases
  • Review test coverage
  • Post review findings

Summary

This PR fixes three issues in DTensor's index_put sharding strategy: (1) missing aten.index_put_.default registration, (2) a _get_num_tensor_inputs count mismatch for None children in TupleStrategy, and (3) an incorrect values-dim-to-self-dim mapping when indexed dims are not at dim 0.

I traced the core index_put_single_dim_strategy logic through 7 corner cases. The implementation is correct for all realistic scenarios, with one minor edge case noted below.


Corner Case Analysis

I manually traced the values_to_self mapping and generated strategies for each case:

Case Description Result
1 Consecutive indexed at dim 0: self[4,8,16], indices=[idx,None,None] Correct — generates Shard(1) and Shard(2) strategies
2 Mid-dim indexing: self[16,8,4,16], indices=[None,None,idx] Correct — insert_dim=2 correctly maps self dims 0,1,3 to values dims 0,1,3
3 Non-contiguous: self[4,8,3,16], indices=[idx,None,idx] Correct — all_consecutive=False, broadcast dims go to front, self dims 1,3 map to values dims 1,2
4 Multiple consecutive mid: self[16,4,8,16], indices=[None,idx,idx,None] Correct — insert_dim=1, self dims 0,3 map to values dims 0,2
5 Values broadcast (fewer dims): self[4,8,16], indices=[idx], values shape (8,16) Correct — values_offset=1 right-aligns values dims
6 All-None indices: indices=[None,None] Crashes — sorted_indexed[0] on empty list (see below)
7 Single element index at dim 0: self[4,8], indices=[idx], idx shape (1,) Correct

Cases 2 and 4 validate the core fix in this PR — the old code would have incorrectly used insert_dim=0 for mid-tensor indexing.


Findings

1. Minor: IndexError on empty sorted_indexed (low severity)

_tensor_ops.py:1135:

insert_dim = sorted_indexed[0] if all_consecutive else 0

If n_indexed == 0 (all indices are None), sorted_indexed is empty, all_consecutive is True (since len([]) <= 1), and sorted_indexed[0] raises IndexError.

This is unlikely in practice — index_put with all-None indices is semantically useless and probably never produced by autograd or user code. But a defensive guard would be:

insert_dim = sorted_indexed[0] if (all_consecutive and sorted_indexed) else 0

Note: the forward index_single_dim_strategy at line 1021 has the same pattern (indexed_dims[0]), but there indexed_dims is guaranteed non-empty because broadcast_ndim = max(len(m.shape) for m in index_metas) would crash first on an empty index_metas. In the backward, broadcast_ndim uses if index_shapes else 0, so it doesn't crash there — but then hits the sorted_indexed[0] issue instead.

2. The _get_num_tensor_inputs change is defensive but not directly exercised by index_put

single_dim_strategy.py:200:

return sum(1 for child in obj.children if child is not None)

For index_put with needs_pytree=True, the indices tuple [DTensorSpec, None, DTensorSpec] flows through _wrap_with_op_strategy which keeps mixed lists as plain Python lists (not TupleStrategy) via line 619-623 of _sharding_prop.py. So _get_num_tensor_inputs hits the (list, tuple) branch and recursively counts — None returns 0 correctly regardless of the TupleStrategy fix.

The fix is still valid as a defensive improvement: if any code path (e.g., pytree manipulation) produces a TupleStrategy with None children, the count would be correct. But it doesn't directly fix a bug exercised by this PR's test cases.

3. Strategy correctness: the values_to_self mapping is sound

The mapping correctly mirrors PyTorch's advanced indexing output shape semantics:

  • Consecutive indexed dims at position k: output = (*self[:k], *broadcast, *self[k+n:])
  • Non-consecutive indexed dims: output = (*broadcast, *non_indexed_in_order)

The values_offset calculation (line 1160) correctly handles values broadcasting by right-aligning values dims to the output shape.

4. Missing strategy: sharding on broadcast dims of values

Unlike the forward index_single_dim_strategy which allows sharding on index broadcast dims (lines 1042-1061 of the forward), index_put_single_dim_strategy requires all indices to be Replicate. This is correct — in index_put, every rank must know the full set of write coordinates to produce correct results. (The forward can shard indices because each rank reads a disjoint subset.)

However, the strategy does not currently allow sharding self on indexed dims even when the values tensor and index tensors are all replicated. This is conservative (and documented as such in the docstring). It could be relaxed in the future since replicated indices mean every rank writes the same values to the same positions.

5. Test coverage is good for the fixed cases

The four new tests cover:

  • None indices with dim-0 indexing (test_index_put_none_indices)
  • In-place variant (test_index_put_inplace_none_indices)
  • Non-contiguous indexed dims (test_index_put_noncontiguous_indexed_dims)
  • Mid-dim consecutive indexing (test_index_put_mid_dim_indexed)

Missing test coverage (not blockers, just observations):

  • Multiple consecutive indexed dims not at dim 0 (Case 4 above)
  • Values with fewer dims than the output (broadcast case, Case 5)
  • Multi-dimensional index tensors (e.g., idx.shape = (2,3) giving broadcast_ndim=2)

Verdict

The PR is correct for all practical corner cases. The core values_to_self mapping logic is sound and properly mirrors PyTorch's advanced indexing semantics. The one theoretical crash (all-None indices) is negligible risk.

@aditvenk
aditvenk force-pushed the ps/rr/_dtensor__fix_index_put_sharding_strategy_for_none_indices_and_mid_tensor_indexing branch 2 times, most recently from e2d5ba3 to dc0f045 Compare April 3, 2026 17:08
@aditvenk
aditvenk requested review from anshul-si, fmassa and pianpwk April 3, 2026 17:11
@aditvenk

aditvenk commented Apr 3, 2026

Copy link
Copy Markdown
Contributor Author

Will rebase once @anshul-si 's #178350 goes in

@aditvenk
aditvenk force-pushed the ps/rr/_dtensor__fix_index_put_sharding_strategy_for_none_indices_and_mid_tensor_indexing branch from dc0f045 to e028891 Compare April 7, 2026 19:41
@aditvenk aditvenk changed the title [DTensor] Fix index_put sharding strategy for None indices and mid-te… [DTensor] Fix index_put sharding strategy for None indices Apr 7, 2026
The strategy computation for aten.index_put had two remaining issues
blocking models like Falcon-7b that use list indexing
(e.g. tensor[..., [-1], :]):

1. aten.index_put_.default (in-place variant, generated by autograd in the
   backward of aten.index.Tensor) was not registered in the single-dim
   strategy system.

2. _get_num_tensor_inputs counted None children in TupleStrategy, but
   args_strategy drops them, causing a count mismatch for ops with
   List[Optional[Tensor]] arguments.

The values-dim-to-self-dim mapping fix for consecutive indexed dims was
already landed in #178350; this commit adds the missing op registration,
the infra bug fix, updated docstrings, and additional test coverage for
None indices, in-place index_put_, non-contiguous indexed dims, and
mid-tensor indexing.

Authored with Claude.

Fixes meta-pytorch/autoparallel#348

<!-- ps-id: 3fc0ba49-8b82-4c1d-b532-2ba111099dc3 -->
@aditvenk
aditvenk force-pushed the ps/rr/_dtensor__fix_index_put_sharding_strategy_for_none_indices_and_mid_tensor_indexing branch from e028891 to 28e10a6 Compare April 8, 2026 16:27
@aditvenk

aditvenk commented Apr 8, 2026

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 Apr 8, 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

@github-actions
github-actions Bot deleted the ps/rr/_dtensor__fix_index_put_sharding_strategy_for_none_indices_and_mid_tensor_indexing branch May 9, 2026 02:26
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…79217)

The strategy computation for aten.index_put had two remaining issues blocking models like Falcon-7b that use list indexing (e.g. tensor[..., [-1], :]):

1. aten.index_put_.default (in-place variant, generated by autograd in the backward of aten.index.Tensor) was not registered in the single-dim strategy system.

2. _get_num_tensor_inputs counted None children in TupleStrategy, but args_strategy drops them, causing a count mismatch for ops with List[Optional[Tensor]] arguments.

The values-dim-to-self-dim mapping fix for consecutive indexed dims was already landed in pytorch#178350; this commit adds the missing op registration, the infra bug fix, updated docstrings, and additional test coverage for None indices, in-place index_put_, non-contiguous indexed dims, and mid-tensor indexing.

Authored with Claude.

Fixes meta-pytorch/autoparallel#348
Pull Request resolved: pytorch#179217
Approved by: https://github.com/pianpwk
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…79217)

The strategy computation for aten.index_put had two remaining issues blocking models like Falcon-7b that use list indexing (e.g. tensor[..., [-1], :]):

1. aten.index_put_.default (in-place variant, generated by autograd in the backward of aten.index.Tensor) was not registered in the single-dim strategy system.

2. _get_num_tensor_inputs counted None children in TupleStrategy, but args_strategy drops them, causing a count mismatch for ops with List[Optional[Tensor]] arguments.

The values-dim-to-self-dim mapping fix for consecutive indexed dims was already landed in pytorch#178350; this commit adds the missing op registration, the infra bug fix, updated docstrings, and additional test coverage for None indices, in-place index_put_, non-contiguous indexed dims, and mid-tensor indexing.

Authored with Claude.

Fixes meta-pytorch/autoparallel#348
Pull Request resolved: pytorch#179217
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

ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (dtensor) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

index_put with incompatible shardings on 2D mesh

3 participants