Skip to content

Remove coordinate cache in LocalDeviceMesh - #184534

Closed
Flamefire wants to merge 1 commit into
pytorch:mainfrom
Flamefire:remove-id-cache
Closed

Flamefire wants to merge 1 commit into
pytorch:mainfrom
Flamefire:remove-id-cache

Conversation

@Flamefire

@Flamefire Flamefire commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

The cache uses 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.

Mostly a revert of #173836

Fixes #184526

@pytorch-bot

pytorch-bot Bot commented May 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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:

✅ No Failures

As of commit e01c529 with merge base cd1956a (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 the ciflow/torchtitan Run TorchTitan integration tests label May 20, 2026
@Flamefire Flamefire added topic: not user facing topic category release notes: DeviceMesh and removed ciflow/torchtitan Run TorchTitan integration tests topic: not user facing topic category labels May 20, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label May 20, 2026
@Flamefire
Flamefire requested a review from wconstab May 21, 2026 10:54
…lTensorMode (pytorch#173836)"

Remove coordinate cache in LocalDeviceMesh

The cache uses 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.

Fixes pytorch#184526

This reverts commit 8e65dfa.
@aditvenk

Copy link
Copy Markdown
Contributor

@claude

@claude

claude Bot commented May 21, 2026 •

Copy link
Copy Markdown

Claude finished @aditvenk's task in 4m 25s —— View job


Reviewing PR #184534

  • Gather context and read the changed file
  • Analyze the change and provide review feedback

LGTM - This is a correct and well-motivated fix.

The bug is clear: id(self) returns the CPython memory address of the _LocalDeviceMesh object, and Python is free to reuse that address once the object is garbage collected. In the example from the issue description:

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 temporary submesh from mesh_2d["dim0"] can be destroyed before mesh_2d["dim1"] is created, and the new submesh may receive the same id(). This causes the cache to silently return wrong coordinates — a correctness bug that would be extremely difficult to debug in practice since it's non-deterministic.

The removal is clean:

  • The cache (_coordinate_cache) and its lock (_coordinate_cache_lock) are fully removed from LocalTensorMode.__init__
  • The double-checked locking pattern in get_coordinate is replaced with the straightforward computation
  • The threading import is still needed by other code in the file, so no stale imports

No concerns with this change. The original caching was a performance optimization, but correctness must come first. If caching is needed in the future, it would need a key that's tied to the mesh's identity/content rather than its memory address (e.g., using weakref with a destructor callback to evict entries, or keying on mesh content/shape).


@aditvenk

Copy link
Copy Markdown
Contributor

@claude suggest a way to fix the correctness issue but retain the performance benefits of the caching approach.

@claude

claude Bot commented May 21, 2026 •

Copy link
Copy Markdown

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


Suggesting a Correct Caching Approach for LocalDeviceMesh


The root problem with the removed cache was using id(self) as the key. Python's id() returns the object's memory address, which can be reused after the object is garbage collected. Since submeshes are temporaries (e.g. mesh_2d["dim0"]), they get destroyed immediately and a subsequent mesh_2d["dim1"] may receive the same address, causing incorrect cache hits.

Here are three approaches to retain caching correctly, ordered by my preference:


Option 1: Use the mesh itself as the dict key (simplest, recommended)

DeviceMesh already implements __hash__ and __eq__ (see device_mesh.py:675-693) based on its content (_flatten_rank_map, _layout, _device_type, _mesh_dim_names, _thread_id). This means you can use the mesh object directly as a dictionary key:

# In LocalTensorMode.__init__:
self._coordinate_cache: dict[DeviceMesh, list[SymInt]] = {}

# In _LocalDeviceMesh.get_coordinate:
if self in lm._coordinate_cache:
    return lm._coordinate_cache[self]

# ... compute coords ...
lm._coordinate_cache[self] = out
return out

Pros:

  • Content-based equality — two structurally identical meshes share cache entries
  • No id() reuse bug since it keys on value equality
  • Simple, no extra infrastructure

Cons:

  • Hashing cost on each lookup (though DeviceMesh lazily caches its hash)
  • Cache entries are never evicted (mesh objects are held alive by the dict) — but this is bounded by the number of distinct mesh shapes used, which is typically very small

Option 2: Use weakref with the mesh object to auto-evict

Use a WeakValueDictionary or manually attach the cache entry to the mesh object itself via a side table with weak references:

import weakref

# In LocalTensorMode.__init__:
self._coordinate_cache: dict[int, tuple[weakref.ref[DeviceMesh], list[SymInt]]] = {}

# In _LocalDeviceMesh.get_coordinate:
mesh_id = id(self)
if mesh_id in lm._coordinate_cache:
    ref, coords = lm._coordinate_cache[mesh_id]
    if ref() is self:  # Verify the object is still alive and the same
        return coords
    # Stale entry — remove it
    del lm._coordinate_cache[mesh_id]

# ... compute coords ...
lm._coordinate_cache[mesh_id] = (weakref.ref(self), out)
return out

Pros:

  • O(1) lookup (integer key)
  • Correctly handles id() reuse by verifying the weakref still points to the same object
  • Cache entries become stale (but are lazily cleaned) when the mesh is GC'd

Cons:

  • Slightly more complex
  • weakref.ref(self) keeps a weak reference; if the mesh is collected between id() lookup and ref() check, the entry is simply treated as a miss (safe)
  • DeviceMesh would need to support weak references (it may already if it doesn't define __slots__ tightly — worth checking)

Option 3: Cache directly on the mesh object (_cached_local_coordinates attribute)

Store the computed coordinates directly on the DeviceMesh instance:

# In _LocalDeviceMesh.get_coordinate:
cache_attr = "_local_tensor_coordinates"
cached = getattr(self, cache_attr, None)
if cached is not None:
    return cached

# ... compute coords ...
object.__setattr__(self, cache_attr, out)
return out

Pros:

  • Zero extra data structures on LocalTensorMode
  • Naturally evicted when the mesh is GC'd
  • No id() reuse issue — the cache lives on the object itself

Cons:

  • Pollutes the DeviceMesh instance with attributes from a different subsystem
  • If the same mesh is used under different LocalTensorMode instances with different rank sets, the cached coordinates from one mode would be incorrectly returned for another. You'd need to include lm.ranks in the cache key or attribute name.
  • Thread safety concerns if multiple modes share a mesh

My Recommendation

Option 1 is the cleanest and most Pythonic. The hash is already cached on DeviceMesh (lazy self._hash), so repeated lookups are effectively O(1) after the first call. The number of distinct meshes in a typical program is small (often single digits), so the cache will never grow large. And because it uses value equality, it avoids the entire class of identity-vs-equality bugs.

If profiling shows the __hash__/__eq__ overhead matters (unlikely given the _hash cache), Option 2 provides an id()-based fast path that is still correct by validating via weakref.


@Flamefire

Copy link
Copy Markdown
Collaborator Author

I was thinking about using Option 3 already: The coordinates is a property of the mesh, so why not store it there instead of in the LocalTensor context?
The weakref approach is viable but IMO overly complicated

@wconstab

Copy link
Copy Markdown
Contributor

What's wrong with option 1?

@Flamefire

Flamefire commented May 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

LocalTensorMode is (likely?) a long-living object. So when adding the Mesh as a dict key to it it will keep it alive for potentially a long time. Especially as each mesh['sub'] creates a new (short-lived) instance this might be wasteful.

Besides of that: Why cache a class instance methods result in another class instead of in the same class? Isn't that non-locality an issue?
I'd usually do something like:

def __init__(self):
  self._prop = None

@property
def prop(self):
  if self._prop is None:
    self._prop = # Calculation
  return self._prop

That looks much cleaner to me than having a cache in a class that need to be retrieved first, which may even fail.

@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 26, 2026
@wconstab

Copy link
Copy Markdown
Contributor

I think it does make sense to move some of this logic to a cached property on DeviceMesh, with caveats:

  • we support serialization of DeviceMesh- i would probably keep the cache data out of the serialized artifact, and also keep it out of the hash and eq scope

I feel like this API probably still could use some discussion as far as efficiency. Do we really want to create a fully-enumerated rank mapping dict here? If we can avoid that and do cute algebra to get the local value directly it seems worth it.

cc @fegin

@Flamefire

Copy link
Copy Markdown
Collaborator Author

Storing of the coordinates was done as an optimization. So I'd say it is fine to have this as an implementation detail of would be fine.
Are the serialization, hash and eq methods using some magic so we'd need code to explicitly ignore that cache value or would it just work to not include it there?

@fegin

fegin commented May 29, 2026

Copy link
Copy Markdown
Contributor

I think it does make sense to move some of this logic to a cached property on DeviceMesh, with caveats:

Why do we want a cached property on DeviceMesh? I thought we want to move away from that idea -- killing the flatten DeivceMesh being recorded in the global data. In the real workload, we want to ask users to explicitly cache the DeviceMesh rather than relying on DeviceMesh itself do the work.

@wconstab

wconstab commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

After discussing offline with @fegin, I want to propose we keep the cache in LocalTensor but we change the cache key from id() to some function of DeviceMesh's rank_tensor and layout.

The proposal to move the cache into DeviceMesh was rejected on the basis that DeviceMesh shouldn't itself know about or cache rank mappings of the non-local rank. LocalTensor itself is the place where non-local ranks (all world ranks) need to be brought together in one process

@Flamefire would you be open to doing it this way?

In any case, I am approving this PR to land now, to unblock others. We can take the perf regression on LocalTensor in the mean time. The caching was added to speed up DTensor sharding validator, and I don't think the regression would be an absolute blocker. cc @pianpwk @anshul-si

@Flamefire

Copy link
Copy Markdown
Collaborator Author

Why do we want a cached property on DeviceMesh? I thought we want to move away from that idea -- killing the flatten DeivceMesh being recorded in the global data. In the real workload, we want to ask users to explicitly cache the DeviceMesh rather than relying on DeviceMesh itself do the work.

Sorry, I don't fully understand the reasoning.
What is meant by "flatten DeivceMesh being recorded in the global data"?
How are users supposed to cache DeviceMesh in a way that helps for this issue?
If DeviceMesh stores the result of the calculation (inside itself) and users cache DeviceMesh they'll get the cached values too

Here we have a property-like method that depends mostly on properties of the class it belongs to: self._rank_map and self._layout.
It does depend on ranks of the active local-tensor-mode to select elements though, but does that really make it a property of LocalTensor? If so why is it called on the Mesh?

Is it possible that enabled_local_tensor_mode might be different for multiple calls to get_coordinate? It looks like it might.

In that case I assume replacing the original id(self) key by (self._rank_map, self._layout)-tuple would be the best solution if we don't want to make the cache inside DeviceMesh indexed by the ranks, although that would be faster.

Semi-related: for performance, self._layout.remap_to_tensor(rank_map) looks like it shouldn't be called for each rank and can be moved out of the loop. But I'm not sure if that actually works given the comment about "torch.inference_mode()"

@fegin

fegin commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

@Flamefire

My previous comment was targeting something different. Sorry for the confusion. But one main idea is the same, the fix shouldn't go to DeviceMesh but should keep in LocalMesh. DeviceMesh already cache coordinates. It is LocalMesh, which performs something differently, so any optimization should be done in LocalMesh.

@Flamefire

Copy link
Copy Markdown
Collaborator Author

Ah, so not in LocalTensorMode but LocalDeviceMesh.

Can you take a look at #187021 if that is what you imagined? I documented an alternative there too.

@Flamefire

Copy link
Copy Markdown
Collaborator Author

Looks like the reason for caching in LocalTensorMode was that at some point a deepcopy of LocalDeviceMesh is done which doesn't support those LocalTensors (semi-replicated values) and fails, see CI of #187021
So I'd say we need to keep the cache in LocalTensorMode but with a proper key: #187052

@fegin

fegin commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

@Flamefire May I ask which one is the final proposal, there seem to be several open PRs now.

@Flamefire

Copy link
Copy Markdown
Collaborator Author

I guess the last one is the way to go

@Flamefire
Flamefire deleted the remove-id-cache branch July 10, 2026 10:51
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
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 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