Skip to content

[fake tensor] Cache _unsafe_view dispatch - #193765

Closed
anijain2305 wants to merge 8 commits into
gh/anijain2305/1316/basefrom
gh/anijain2305/1316/head
Closed

anijain2305 wants to merge 8 commits into
gh/anijain2305/1316/basefrom
gh/anijain2305/1316/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

_unsafe_view has bypassed the fake tensor dispatch cache since the cache was
first added, with no stated reason. It is not a cheap op to bypass: on a
Qwen3-8B prefill trace it accounts for 325 of the 729 uncached dispatches, and an
uncached dispatch costs about 1.1ms against 220us for a cache hit.

The thing that makes it look unsafe is real, but it is not a reason to bypass the
cache - it is a reason to record what the op does. _unsafe_view's output shares
its input's storage, exactly like view; the "unsafe" part is only that it does
not record the view for autograd. The cache synthesizes an output from stored
metadata and gives it a fresh storage unless the entry names the input it aliases,
so caching this op without saying so would quietly drop the aliasing. Set
view_idx for it, as is already done for ops where is_view is true, and the output
handed back on a hit aliases its input the way the real op's does.

Along with that, the "don't derive size and stride twice" check now keys off
entry.view_idx rather than func.is_view, so it covers this op too rather than
paying for the derivation once in empty_strided and again in set_.

Dispatches that bypass the cache on that model drop from 344 to 19, and Dynamo
tracing goes from 5.01s to 4.73s.

Test plan:

python test/test_fake_tensor.py

459 tests; the 4 cudnn_rnn errors are pre-existing on this host and fail
identically with the change reverted.

The interesting check is aliasing, so it was verified two ways. Directly: an
_unsafe_view on a fake tensor with symbolic sizes shares storage with its input
on both the miss and the subsequent hit. And with
fake_tensor_cache_crosscheck_enabled, which re-runs every cached op uncached and
compares, a full Qwen3-8B trace passes.

This PR was authored with the assistance of an AI coding agent.

[ghstack-poisoned]
@anijain2305
anijain2305 requested a review from aorenste as a code owner August 17, 2026 05:47
@pytorch-bot

pytorch-bot Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 17, 2026
_unsafe_view has bypassed the fake tensor dispatch cache since the cache was
first added, with no stated reason. It is not a cheap op to bypass: on a
Qwen3-8B prefill trace it accounts for 325 of the 729 uncached dispatches, and an
uncached dispatch costs about 1.1ms against 220us for a cache hit.

The thing that makes it look unsafe is real, but it is not a reason to bypass the
cache - it is a reason to record what the op does. _unsafe_view's output shares
its input's storage, exactly like view; the "unsafe" part is only that it does
not record the view for autograd. The cache synthesizes an output from stored
metadata and gives it a fresh storage unless the entry names the input it aliases,
so caching this op without saying so would quietly drop the aliasing. Set
view_idx for it, as is already done for ops where is_view is true, and the output
handed back on a hit aliases its input the way the real op's does.

Along with that, the "don't derive size and stride twice" check now keys off
entry.view_idx rather than func.is_view, so it covers this op too rather than
paying for the derivation once in empty_strided and again in set_.

Dispatches that bypass the cache on that model drop from 344 to 19, and Dynamo
tracing goes from 5.01s to 4.73s.

Test plan:

```
python test/test_fake_tensor.py
```

459 tests; the 4 cudnn_rnn errors are pre-existing on this host and fail
identically with the change reverted.

The interesting check is aliasing, so it was verified two ways. Directly: an
_unsafe_view on a fake tensor with symbolic sizes shares storage with its input
on both the miss and the subsequent hit. And with
fake_tensor_cache_crosscheck_enabled, which re-runs every cached op uncached and
compares, a full Qwen3-8B trace passes.

This PR was authored with the assistance of an AI coding agent.


ghstack-source-id: 2ea7ca7
Pull-Request: #193765
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 17, 2026
_unsafe_view has bypassed the fake tensor dispatch cache since the cache was
first added, with no stated reason. It is not a cheap op to bypass: on a
Qwen3-8B prefill trace it accounts for 325 of the 729 uncached dispatches, and an
uncached dispatch costs about 1.1ms against 220us for a cache hit.

The thing that makes it look unsafe is real, but it is not a reason to bypass the
cache - it is a reason to record what the op does. _unsafe_view's output shares
its input's storage, exactly like view; the "unsafe" part is only that it does
not record the view for autograd. The cache synthesizes an output from stored
metadata and gives it a fresh storage unless the entry names the input it aliases,
so caching this op without saying so would quietly drop the aliasing. Set
view_idx for it, as is already done for ops where is_view is true, and the output
handed back on a hit aliases its input the way the real op's does.

Along with that, the "don't derive size and stride twice" check now keys off
entry.view_idx rather than func.is_view, so it covers this op too rather than
paying for the derivation once in empty_strided and again in set_.

Dispatches that bypass the cache on that model drop from 344 to 19, and Dynamo
tracing goes from 5.01s to 4.73s.

Test plan:

```
python test/test_fake_tensor.py
```

459 tests; the 4 cudnn_rnn errors are pre-existing on this host and fail
identically with the change reverted.

The interesting check is aliasing, so it was verified two ways. Directly: an
_unsafe_view on a fake tensor with symbolic sizes shares storage with its input
on both the miss and the subsequent hit. And with
fake_tensor_cache_crosscheck_enabled, which re-runs every cached op uncached and
compares, a full Qwen3-8B trace passes.

This PR was authored with the assistance of an AI coding agent.


ghstack-source-id: b5fa305
Pull-Request: #193765
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

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

(Reviewed by me, assisted by AI)

[cleanup] My agent says:

Worth adding a regression test for the aliasing. What makes it matter more than usual: the verification cited in the description won't catch a future regression. fake_tensor_cache_crosscheck_enabled compares via assert_metadata_eq (torch/_subclasses/meta_utils.py:149-189), which checks dtype/shape/stride/offset/_is_view()/_base but never storage identity - and _is_view() is False for both the real and the synthesized output, so it passes either way. extract_tensor_metadata, which the existing cache tests compare on, carries storage_bytes but no storage identity either. Nothing in test/test_fake_tensor.py currently mentions _unsafe_view.

Sketch for FakeTensorDispatchCache (not run here; the hit count is compared relatively because the Python fake impl re-dispatches internally, so the absolute miss count isn't 1):

def test_cache_unsafe_view(self):
    with FakeTensorMode():
        x = torch.randn(4, 4)
        y = torch.randn(4, 4)

        FakeTensorMode.cache_clear()
        ref = aten._unsafe_view.default(x, [16])
        self.assertEqual(ref.untyped_storage()._cdata, x.untyped_storage()._cdata)

        hits = FakeTensorMode.cache_info().hits
        res = aten._unsafe_view.default(y, [16])
        self.assertEqual(FakeTensorMode.cache_info().hits, hits + 1)
        self.assertEqual(res.untyped_storage()._cdata, y.untyped_storage()._cdata)
        self.assertNotEqual(res.untyped_storage()._cdata, x.untyped_storage()._cdata)
        self.assertEqual(extract_tensor_metadata(ref), extract_tensor_metadata(res))

# created here, so for a view op don't pay to derive them twice. On
# symbolic shapes that derivation is the bulk of the cost of both calls.
is_view = isinstance(func, torch._ops.OpOverload) and func.is_view
is_view = entry.view_idx is not None

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.

[cleanup] My agent says:

This was the last use of func in _get_output_tensor_from_cache_entry, so the parameter is now dead - as is the func that _output_from_cache_entry holds only to forward it. Both signatures and their four positional call sites can drop it.

[ghstack-poisoned]
@anijain2305 anijain2305 added the topic: not user facing topic category label Aug 22, 2026
@anijain2305

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 Aug 22, 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

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
_unsafe_view has bypassed the fake tensor dispatch cache since the cache was
first added, with no stated reason. It is not a cheap op to bypass: on a
Qwen3-8B prefill trace it accounts for 325 of the 729 uncached dispatches, and an
uncached dispatch costs about 1.1ms against 220us for a cache hit.

The thing that makes it look unsafe is real, but it is not a reason to bypass the
cache - it is a reason to record what the op does. _unsafe_view's output shares
its input's storage, exactly like view; the "unsafe" part is only that it does
not record the view for autograd. The cache synthesizes an output from stored
metadata and gives it a fresh storage unless the entry names the input it aliases,
so caching this op without saying so would quietly drop the aliasing. Set
view_idx for it, as is already done for ops where is_view is true, and the output
handed back on a hit aliases its input the way the real op's does.

Along with that, the "don't derive size and stride twice" check now keys off
entry.view_idx rather than func.is_view, so it covers this op too rather than
paying for the derivation once in empty_strided and again in set_.

Dispatches that bypass the cache on that model drop from 344 to 19, and Dynamo
tracing goes from 5.01s to 4.73s.

Test plan:

```
python test/test_fake_tensor.py
```

459 tests; the 4 cudnn_rnn errors are pre-existing on this host and fail
identically with the change reverted.

The interesting check is aliasing, so it was verified two ways. Directly: an
_unsafe_view on a fake tensor with symbolic sizes shares storage with its input
on both the miss and the subsequent hit. And with
fake_tensor_cache_crosscheck_enabled, which re-runs every cached op uncached and
compares, a full Qwen3-8B trace passes.

This PR was authored with the assistance of an AI coding agent.
Pull Request resolved: pytorch#193765
Approved by: https://github.com/aorenste
aeytkn pushed a commit to aeytkn/pytorch that referenced this pull request Sep 3, 2026
_unsafe_view has bypassed the fake tensor dispatch cache since the cache was
first added, with no stated reason. It is not a cheap op to bypass: on a
Qwen3-8B prefill trace it accounts for 325 of the 729 uncached dispatches, and an
uncached dispatch costs about 1.1ms against 220us for a cache hit.

The thing that makes it look unsafe is real, but it is not a reason to bypass the
cache - it is a reason to record what the op does. _unsafe_view's output shares
its input's storage, exactly like view; the "unsafe" part is only that it does
not record the view for autograd. The cache synthesizes an output from stored
metadata and gives it a fresh storage unless the entry names the input it aliases,
so caching this op without saying so would quietly drop the aliasing. Set
view_idx for it, as is already done for ops where is_view is true, and the output
handed back on a hit aliases its input the way the real op's does.

Along with that, the "don't derive size and stride twice" check now keys off
entry.view_idx rather than func.is_view, so it covers this op too rather than
paying for the derivation once in empty_strided and again in set_.

Dispatches that bypass the cache on that model drop from 344 to 19, and Dynamo
tracing goes from 5.01s to 4.73s.

Test plan:

```
python test/test_fake_tensor.py
```

459 tests; the 4 cudnn_rnn errors are pre-existing on this host and fail
identically with the change reverted.

The interesting check is aliasing, so it was verified two ways. Directly: an
_unsafe_view on a fake tensor with symbolic sizes shares storage with its input
on both the miss and the subsequent hit. And with
fake_tensor_cache_crosscheck_enabled, which re-runs every cached op uncached and
compares, a full Qwen3-8B trace passes.

This PR was authored with the assistance of an AI coding agent.
Pull Request resolved: pytorch#193765
Approved by: https://github.com/aorenste
@github-actions
github-actions Bot deleted the gh/anijain2305/1316/head branch November 8, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants