Skip to content

Fix coordinate cache in LocalDeviceMesh - #187052

Closed
Flamefire wants to merge 4 commits into
pytorch:mainfrom
Flamefire:fix-local-device-mesh-cache2
Closed

Flamefire wants to merge 4 commits into
pytorch:mainfrom
Flamefire:fix-local-device-mesh-cache2

Conversation

@Flamefire

Copy link
Copy Markdown
Collaborator

Alternative to #184534 after discussion and #187021.

The cache used the id of the Mesh as the key which is not unique over the lifetime of the LocalTensorMode instance:
When the mesh is destroyed its slot may be reused leading to silently wrong, indeterministic results.
E.g.:
mesh_dim0_local_rank = mesh_2d["dim0"].get_local_rank(mesh_dim=0)
mesh_dim1_local_rank = mesh_2d["dim1"].get_local_rank(mesh_dim=0)
The values for both might be the same as the 2nd could use the cached
coords from the first submesh, which is a temporary that gets
immediately destroyed.

Use the attributes used for the calculation as the cache key instead. Those are all tuples or data classes which works fine.

Fixes #184526
Fixes 8e65dfa.

Closes #184534
Closes #187021

@pytorch-bot

pytorch-bot Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ 1 Pending, 1 Unrelated Failure

As of commit 3ed8808 with merge base 9f132a8 (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Jun 11, 2026
@Flamefire Flamefire changed the title Fix local device mesh cache Fix coordinate cache in LocalDeviceMesh Jun 11, 2026
@Flamefire
Flamefire force-pushed the fix-local-device-mesh-cache2 branch from 9f72e27 to eaa429e Compare June 11, 2026 15:25
@janeyx99
janeyx99 requested a review from wconstab June 11, 2026 17:22
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 11, 2026
@Flamefire
Flamefire requested a review from fegin June 12, 2026 06:49
@fegin

fegin commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

This is better than the current logic, but not completely collision free, in rare cases, this can cause an issue. But I'm wondering if this is good enough. Let's say if we actually have a collision, can the later LocalTensor still reuse that cached one? It seems to be fine. cc., @wconstab

@wconstab

Copy link
Copy Markdown
Contributor

@claude review this PR

@wconstab

Copy link
Copy Markdown
Contributor

I think this logic looks fine. let's see what claude says and i'm also discussing with @fegin offline

@claude

claude Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Claude finished @wconstab's task in 1m 56s —— View job


PR Review: Fix coordinate cache in LocalDeviceMesh

  • Read the diff and surrounding code
  • Verify cache-key correctness and collision safety
  • Check for stale references / leftover state
  • Answer @fegin's collision question

Summary

This is a solid fix and I think the design is actually collision-safe, which also answers @fegin's question. The old code keyed the cache by id(mesh), which is unsafe because a destroyed mesh's id can be recycled by a later temporary submesh, returning stale coordinates. This PR replaces that with a key built from the inputs to the computation itself.

The key correctness argument

The cached value is computed in get_coordinate (torch/distributed/_local_tensor/__init__.py:1649-1661) from exactly these inputs:

  • self.ndim → in the key
  • self._rank_map (cloned) → captured via self._flatten_rank_map, which is tuple(self._rank_map.tolist()) (device_mesh.py:298), in the key
  • self._layout → in the key (frozen dataclass, hashable/comparable)
  • lm.ranks → constant for a given LocalTensorMode, and the cache now lives on lm, so it's implicitly scoped correctly

Because the key is precisely the set of inputs used by the computation, a key "collision" can only happen between two meshes that would compute identical coordinates. So to answer @fegin / @wconstab directly: yes — if two meshes hit the same cache entry, reuse is safe, because the cached result is by construction the same value the second mesh would have computed. The remaining attributes in DeviceMesh._hash_key (_device_type, _mesh_dim_names, _thread_id) don't feed into the coordinate math, so omitting them from the key is correct, not a latent bug.

That's a stronger guarantee than the PR description claims ("not completely collision free") — within this function's logic it effectively is collision-free.

Other checks

  • Lock + double-checked-locking pattern is preserved correctly (fast path at :1640, re-check under lock at :1646).
  • The old per-mesh self._local_coordinates_cache attribute is fully removed — no dangling references remain in the tree.
  • Cache now lives for the lifetime of the LocalTensorMode rather than per-mesh. This is the intended fix and memory is bounded by the number of distinct (ndim, rank_map, layout) meshes, so not a concern.

Minor nits (non-blocking)

  1. Stale comment at :1264:

    # Cache for get_coordinate results, keyed by mesh id

    It's no longer keyed by mesh id — it's keyed by the computation inputs. Suggest:

    # Cache for get_coordinate results, keyed by the inputs used to compute them
    # (ndim, flattened rank map, layout). Protected by _coordinate_cache_lock for
    # thread safety in MPMD contexts.
  2. Type annotation at :1266-1268 uses a bare tuple for the rank-map element; tuple[int, ...] would be more precise:

    self._coordinate_cache: dict[
        tuple[int, tuple[int, ...], torch.distributed._mesh_layout._MeshLayout], list[SymInt]
    ] = {}

The CI failure (torchtitan-x-pytorch-build / build-osdc) looks unrelated to this change.

LGTM modulo the comment fix.

@fegin fegin 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.

This PR should fix the original collision issue. Thanks for the fix.

@Flamefire

Copy link
Copy Markdown
Collaborator Author

Claudes comment on the key description makes sense to me, so updated that to avoid confusion in the future.

@fegin

fegin commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

Move coordinate cache to LocalDeviceMesh.

The cache used the `id` of the Mesh as the key which is not unique over
the lifetime of the `LocalTensorMode` instance:
When the mesh is destroyed its slot may be reused leading to silently wrong,
indeterministic results.
E.g.:
        mesh_dim0_local_rank = mesh_2d["dim0"].get_local_rank(mesh_dim=0)
        mesh_dim1_local_rank = mesh_2d["dim1"].get_local_rank(mesh_dim=0)
The values for both might be the same as the 2nd could use the cached
coords from the first submesh, which is a temporary that gets
immediately destroyed.

Caching the result directly in LocalDeviceMesh, as it is a property of
that, is safer.
It might be possible that during the lifetime of a LocalDeviceMesh the
LocalTensorMode is changed which affects the coordinate calculation
through the `ranks` value, so use that as a key of a dict instead of
storing the value directly in a property.

Fixes pytorch#184526
Fixes 8e65dfa.
`(Local)DeviceMesh` seems to get serialized including its attributes
which doesn't seem to work for the `LocalIntNode` contained.
Use a tuple of all attributes used for calculation as the cache key.
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased fix-local-device-mesh-cache2 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout fix-local-device-mesh-cache2 && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the fix-local-device-mesh-cache2 branch from 17c2a6c to 3ed8808 Compare June 23, 2026 18:19
@fegin

fegin commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -f "The failing test is not related"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

@Flamefire
Flamefire deleted the fix-local-device-mesh-cache2 branch June 24, 2026 17:08
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Alternative to pytorch#184534 after discussion and pytorch#187021.

The cache used the `id` of the Mesh as the key which is not unique over the lifetime of the `LocalTensorMode` instance:
When the mesh is destroyed its slot may be reused leading to silently wrong, indeterministic results.
E.g.:
        mesh_dim0_local_rank = mesh_2d["dim0"].get_local_rank(mesh_dim=0)
        mesh_dim1_local_rank = mesh_2d["dim1"].get_local_rank(mesh_dim=0)
The values for both might be the same as the 2nd could use the cached
coords from the first submesh, which is a temporary that gets
immediately destroyed.

Use the attributes used for the calculation as the cache key instead. Those are all tuples or data classes which works fine.

Fixes pytorch#184526
Fixes 8e65dfa.

Closes pytorch#184534
Closes pytorch#187021
Pull Request resolved: pytorch#187052
Approved by: https://github.com/fegin
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Alternative to pytorch#184534 after discussion and pytorch#187021.

The cache used the `id` of the Mesh as the key which is not unique over the lifetime of the `LocalTensorMode` instance:
When the mesh is destroyed its slot may be reused leading to silently wrong, indeterministic results.
E.g.:
        mesh_dim0_local_rank = mesh_2d["dim0"].get_local_rank(mesh_dim=0)
        mesh_dim1_local_rank = mesh_2d["dim1"].get_local_rank(mesh_dim=0)
The values for both might be the same as the 2nd could use the cached
coords from the first submesh, which is a temporary that gets
immediately destroyed.

Use the attributes used for the calculation as the cache key instead. Those are all tuples or data classes which works fine.

Fixes pytorch#184526
Fixes 8e65dfa.

Closes pytorch#184534
Closes pytorch#187021
Pull Request resolved: pytorch#187052
Approved by: https://github.com/fegin
pragupta pushed a commit to ROCm/pytorch that referenced this pull request Aug 4, 2026
) (#3537)

Cherry-pick of upstream commit 2314113
(pytorch#187052) onto release/2.11.

The LocalTensorMode coordinate cache was keyed by the mesh's Python
object id, which is not unique over the lifetime of the mode: when a
temporary submesh is destroyed, Python may reuse its id for the next
submesh, silently returning stale coordinates for a different mesh
dimension. This fixes the cache key to use the actual inputs to the
coordinate calculation (ndim, flattened rank map, layout) instead.

Fixes ROCM-28605, pytorch#184526.

Verified locally:
test/distributed/tensor/test_utils.py::TestStridedShardingWithLocalTensor:
{test_2d_mesh_strided_sharding,test_2d_mesh_2d_tensor_strided_sharding}
fail before this commit and pass after it.

Co-authored-by: Alexander Grund <[email protected]>
pragupta pushed a commit to ROCm/pytorch that referenced this pull request Aug 4, 2026
) (#3538)

Cherry-pick of upstream commit 2314113
(pytorch#187052) onto release/2.12.

The LocalTensorMode coordinate cache was keyed by the mesh's Python
object id, which is not unique over the lifetime of the mode: when a
temporary submesh is destroyed, Python may reuse its id for the next
submesh, silently returning stale coordinates for a different mesh
dimension. This fixes the cache key to use the actual inputs to the
coordinate calculation (ndim, flattened rank map, layout) instead.

Fixes ROCM-28605, pytorch#184526.

Verified locally:
test/distributed/tensor/test_utils.py::TestStridedShardingWithLocalTensor:
{test_2d_mesh_strided_sharding,test_2d_mesh_2d_tensor_strided_sharding}
fail before this commit and pass after it.

Co-authored-by: Alexander Grund <[email protected]>
pragupta pushed a commit to ROCm/pytorch that referenced this pull request Aug 4, 2026
) (#3539)

Cherry-pick of upstream commit 2314113
(pytorch#187052) onto release/2.13.

The LocalTensorMode coordinate cache was keyed by the mesh's Python
object id, which is not unique over the lifetime of the mode: when a
temporary submesh is destroyed, Python may reuse its id for the next
submesh, silently returning stale coordinates for a different mesh
dimension. This fixes the cache key to use the actual inputs to the
coordinate calculation (ndim, flattened rank map, layout) instead.

Fixes ROCM-28605, pytorch#184526.

Verified locally:
test/distributed/tensor/test_utils.py::TestStridedShardingWithLocalTensor:
{test_2d_mesh_strided_sharding,test_2d_mesh_2d_tensor_strided_sharding}
fail before this commit and pass after it.

Co-authored-by: Alexander Grund <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests Merged module: DeviceMesh open source release notes: DeviceMesh 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.

_LocalDeviceMesh coordinate cache unreliable leading to failures

6 participants