Skip to content

[fake tensor] Don't derive a view's size and stride twice on a dispatch cache hit - #192821

Closed
anijain2305 wants to merge 5 commits into
gh/anijain2305/1301/basefrom
gh/anijain2305/1301/head
Closed

anijain2305 wants to merge 5 commits into
gh/anijain2305/1301/basefrom
gh/anijain2305/1301/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

empty_strided in the cache hit path 192us/call, 3.19s total
set_ in the cache hit path 283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

python test/test_fake_tensor.py

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."

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 10, 2026 17:49
@pytorch-bot

pytorch-bot Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit be908cd with merge base 2760264 (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 10, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 7895de1
Pull-Request: #192821
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 10, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 5241fd2
Pull-Request: #192821
anijain2305 added a commit that referenced this pull request Aug 10, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 5241fd2
Pull-Request: #192821
anijain2305 added a commit that referenced this pull request Aug 11, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 5241fd2
Pull-Request: #192821
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR and explain how it reduces the compile time

@claude

claude Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Claude finished @anijain2305's task in 29m 44s —— View job


Reviewed — LGTM. The change removes a redundant symbolic-shape derivation on the view cache-hit path; my only ask is a regression test that actually covers view synthesis under a ShapeEnv.

Full review: how this saves compile time, correctness analysis, and suggestions

How it reduces compile time

The cache-hit path for a view op synthesizes the output in two steps (torch/_subclasses/fake_tensor.py:2369 and :2390):

empty = torch.empty_strided(shape, stride, ..., device="meta")   # step 1
...
empty.set_(storage, storage_offset, shape, stride)               # step 2

Step 2 fully overwrites what step 1 established. Tracing both into ATen:

empty_strided (meta) → at::detail::_empty_strided_generic (aten/src/ATen/EmptyTensor.cpp:232-252):

  • check_size_nonnegative(size) — one TORCH_SYM_CHECK(x.sym_ge(0)) per dim (EmptyTensor.h:17)
  • computeStorageNbytes(sizes, strides, itemsize) (EmptyTensor.cpp:146-176) — per dim: a TORCH_GUARD_OR_FALSE(sizes[i].sym_eq(0)) plus strides[i] * (sizes[i] - 1) accumulation, then a final itemsize * (offset + size)
  • set_sizes_and_strides(size, stride) — clone_symvec + invalidate numel/contiguity

set_ (meta) → set_storage_meta__symint (aten/src/ATen/native/TensorShape.cpp:399-469):

  • checkSetStorage(...) with TORCH_GUARD_OR_TRUE(sym_ge(storage_offset, 0))
  • set_sizes_and_strides(size, stride, storage_offset) — this is where the placeholder's sizes/strides/offset are replaced (c10/core/TensorImpl.cpp:920-960)
  • result.sym_numel() (TensorShape.cpp:435) — forces the numel product over symbolic sizes
  • result.is_contiguous() (:456) — forces compute_contiguous, which is per-dim sym_eq/sym_ne comparisons (c10/core/Contiguity.h:45-75)
  • computeStorageNbytes{,Contiguous} again (:456-460)
  • finally set_storage_keep_dtype swaps in the base's storage (Resize.h:181-194)

So on symbolic shapes both calls independently do the same class of work: an O(ndim) walk building SymInt products/sums plus a handful of symbolic comparisons. Every one of those SymInt ops is a PyInterpreter round trip into Python (SymInt::operator* falls off the maybe_as_int() fast path at c10/core/SymInt.h:187-194 and into the slow path → Python → sympy). That's what makes each call cost ~200us rather than ~200ns, and it's why the derivation — not the TensorImpl allocation — dominates both calls.

Passing () collapses step 1 to nothing measurable: zero dims means check_size_nonnegative is an empty loop, computeStorageNbytes returns the concrete itemsize * (0 + 1), and set_sizes_and_strides takes the concrete IntArrayRef fast path (TensorImpl.cpp:926-934, which requires !has_symbolic_sizes_strides_ — true for a freshly built 0-dim placeholder). set_ then installs the real sizes/strides/offset/storage exactly as before, paying the symbolic derivation once instead of twice.

The reported numbers are self-consistent, which is a good sign the profile is measuring the right thing:

  • 3.19s / 192us ≈ 16.6k — matches all 16551 cache hits, so empty_strided was on every hit
  • 2.06s / 283us ≈ 7.3k — matches the 7288 view hits, so set_ is view-only
  • expected saving = view fraction of the empty_strided time = 7288 × 192us ≈ 1.40s, versus the observed 53.93s → 52.43s = 1.50s

Non-view hits are untouched (they keep the real shape/stride), and static-shape compiles see no change either way since the concrete path was already cheap.

Correctness

The thing I wanted to be sure about is whether step 1 had any observable side effect on the ShapeEnv that is now being dropped, since the sizes/strides/storage it computed were always thrown away. Two candidates, both benign:

  1. check_size_nonnegative no longer runs for view outputs. For backed symints this is a guard_or_...-style evaluation; for unbacked it becomes a deferred runtime assert. But both of these sites are gated on not self._suppress_guards_tls() (symbolic_shapes.py:8900, :9053, and symbol_guard_counter at :8937), and the whole block runs under maybe_suppress() = shape_env.suppress_guards() (fake_tensor.py:2360-2361, 2368). So no guard, no deferred assert, and no symbol_guard_counter increment was ever recorded from it. It was pure overhead. Also, these sizes came from a dispatch that already succeeded when the entry was made, so they cannot be negative.

  2. The placeholder's storage nbytes shrinks (1 element instead of numel). Harmless: the placeholder's StorageImpl is unconditionally discarded by set_storage_keep_dtype (the fresh storage is never an alias of the base's, so the !is_alias_of branch at Resize.h:181 always fires), and the set_nbytes growth check at TensorShape.cpp:453-466 reads result's post-set_ metadata against the base's storage, not the placeholder's. Also this is meta, so nothing is actually allocated.

Other things I checked and found fine:

  • is_view ⟹ view_idx is not None: view_idx is populated exactly when func.is_view at fake_tensor.py:2144-2151, so the cast(int, entry.view_idx) at :2385 is as safe as before. Entries where metadata is None (constants, in-place) return early at :2323/:2329 and never reach the new code.
  • Hoisting func.is_view above the with block costs nothing — it's a plain attribute assigned in OpOverload.__init__ (torch/_ops.py:884), not a cached_property.
  • Keeping the isinstance(func, torch._ops.OpOverload) guard is correct despite the func: OpOverload annotation, since HOPs reach this function too.
  • Ordering is unchanged: _set_conj/_set_neg still land before set_.
  • Genuinely 0-dim view outputs (e.g. select to a scalar) are unaffected — () if is_view else shape is the same value.

Suggestions

1. Add a regression test for the symbolic view cache-hit path. This is the only substantive gap. Today's coverage of the branch you changed is thinner than it looks:

  • test_cache_view_op (test/test_fake_tensor.py:3781) does not exercise this code. It uses y2.mul_(2), and mul_ is in-place, so _make_cache_entry_for_output takes the inplace_idx branch at :2137-2141 and _get_output_tensor_from_cache_entry returns the aliased arg at :2329 — it never reaches empty_strided/set_. The test asserts on _is_view() propagation, not on view synthesis.
  • test_cache_tuple_outputs (:3987) does reach it via torch.split, and with fake_tensor_cache_crosscheck_enabled = True set globally at :97, assert_metadata_eq validates shape/stride/storage_offset/_is_view/base (torch/_subclasses/meta_utils.py:180-189). But that's static shapes only — precisely the configuration where this diff changes nothing.

Since the behavior that moved is symbolic, something like this would pin it down:

def test_cache_view_op_dynamic(self):
    shape_env = ShapeEnv()
    mode = FakeTensorMode(shape_env=shape_env)
    x = mode.from_tensor(torch.randn(4, 8))
    y = mode.from_tensor(torch.randn(4, 8))
    with mode:
        FakeTensorMode.cache_clear()
        ref = x.view(-1)
        self.assertHitsMisses(0, 1)
        res = y.view(-1)
        self.assertHitsMisses(1, 1)
        self.assertEqual(ref.shape, res.shape)
        self.assertEqual(ref.stride(), res.stride())
        self.assertEqual(ref.storage_offset(), res.storage_offset())
        self.assertTrue(res._is_view())
        self.assertEqual(res.untyped_storage()._cdata, y.untyped_storage()._cdata)

Worth @parametrize-ing over a couple of view ops with non-trivial strides (permute, x[1:], expand) so the stride/offset install is checked and not just the shape. The end-to-end torch.compile runs described in the test plan are good evidence, but they won't catch a future regression here. Fix this →

2. Optional nit. The duplicated conditional reads a little awkwardly; a single unpack is marginally tidier, though the current form is arguably more explicit and I'd not block on it:

placeholder_shape, placeholder_stride = ((), ()) if is_view else (shape, stride)

3. Not a blocker, just noting for the stack. The remaining set_ cost (283us/call, 2.06s) is now the whole bill for view synthesis, and a chunk of it is sym_numel() + is_contiguous() at TensorShape.cpp:435,456 re-deriving properties the cache entry could in principle carry. If you want more from this path later, caching the contiguity flags alongside metadata.shape/stride looks like the next lever.

Process note

Per CLAUDE.md / AI_POLICY.md: this review is AI-generated and is advisory only — please confirm the analysis before acting on it, and note that the test-plan verification below was not re-run by me. There is no built torch and no .venv in this checkout, so I could not execute python test/test_fake_tensor.py or reproduce the timings; the analysis above is from reading the Python and ATen sources.

· branch [`gh/anijain2305/1301/head`](https://github.com/pytorch/pytorch/tree/gh/anijain2305/1301/head)

[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 11, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 26842ad
Pull-Request: #192821
anijain2305 added a commit that referenced this pull request Aug 11, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 26842ad
Pull-Request: #192821
@anijain2305
anijain2305 requested a review from zou3519 August 11, 2026 14:43
@anijain2305 anijain2305 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Aug 11, 2026
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 11, 2026
…ch cache hit

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

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


ghstack-source-id: 4d5f387
Pull-Request: #192821
@anijain2305

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
…ch cache hit (pytorch#192821)

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

This PR was authored with the assistance of an AI coding agent.
Pull Request resolved: pytorch#192821
Approved by: https://github.com/zou3519
ghstack dependencies: pytorch#192817
gavinwang269 pushed a commit to gavinwang269/pytorch that referenced this pull request Aug 13, 2026
…ch cache hit (pytorch#192821)

When the fake tensor dispatch cache hits for a view op, the output is synthesized
by allocating a meta tensor with empty_strided and then calling set_ on it to
point at the input's storage. set_ overwrites the size, stride and storage that
empty_strided just established, so on symbolic shapes we pay twice for the part
that dominates both calls: deriving the storage size and the contiguity flags
from symbolic sizes and strides, which calls back into Python for every SymInt
add, mul and comparison.

Allocate the placeholder with an empty size and stride when the op is a view, and
let set_ install the real ones.

Measured on a FairChem UMA compile, where 7288 of 16551 cache hits are views:

  empty_strided in the cache hit path   192us/call, 3.19s total
  set_ in the cache hit path            283us/call, 2.06s total

Interleaved cold compile runs: 53.93s -> 52.43s.

Test Plan:

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

Failure set identical to baseline (4 pre-existing cudnn RNN errors). Also
exercised the view synthesis path end to end under both dynamic=True and
dynamic=False with view/permute/T/slice/expand/as_strided plus backward:

```
python -c "... torch.compile(f, dynamic=dyn) over view, permute, .T, x[1:], expand, as_strided ..."
```

This PR was authored with the assistance of an AI coding agent.
Pull Request resolved: pytorch#192821
Approved by: https://github.com/zou3519
ghstack dependencies: pytorch#192817
@github-actions
github-actions Bot deleted the gh/anijain2305/1301/head branch November 3, 2026 01:50
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