Skip to content

[fx] Skip the record_shapeenv_event prologue when nothing is recorded - #193161

Closed
anijain2305 wants to merge 13 commits into
gh/anijain2305/1306/basefrom
gh/anijain2305/1306/head
Closed

anijain2305 wants to merge 13 commits into
gh/anijain2305/1306/basefrom
gh/anijain2305/1306/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

record_shapeenv_event wraps the mutating ShapeEnv methods, so it runs a few
hundred thousand times per compile (366k in one model's cold compile). Event
recording is only on under translation validation, but the wrapper paid for it
on every call regardless: an import of symbolic_shapes, an isinstance
assertion, a debug log, bumping the NEST counter, building the retlog closure,
and a second call through it to log the return value.

Check for "not recording, and the trace log is off" first and call the wrapped
function directly. The isinstance check moves to the slow path; the decorator
already verifies at decoration time that it is wrapping a method whose first
argument is self, and the fast path would raise AttributeError immediately on
anything without should_record_events.

On one model's cold compile with dynamic=True, total compile time as the union
of top-level chromium events:

pair 1: baseline 48.12s changed 47.70s
pair 2: baseline 47.76s changed 46.75s
pair 3: baseline 47.57s changed 46.18s

i.e. 47.82s -> 46.88s, -2.0%.

Test plan:

python test/test_dynamic_shapes.py
python test/dynamo/test_misc.py

Both give failure sets identical to a run with the change stashed (this host
has pre-existing aarch64 CPU codegen failures). Recording itself is exercised
by a ShapeEnv(should_record_events=True) that traces a few fake-tensor ops and
replays its events; the recorded event names and the replayed ShapeEnv are
unchanged.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit d9be74b with merge base 411c2b5 (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/inductor release notes: fx release notes category labels Aug 12, 2026
anijain2305 added a commit that referenced this pull request Aug 12, 2026
record_shapeenv_event wraps the mutating ShapeEnv methods, so it runs a few
hundred thousand times per compile (366k in a UMA cold compile). Event
recording is only on under translation validation, but the wrapper paid for it
on every call regardless: an import of symbolic_shapes, an isinstance
assertion, a debug log, bumping the NEST counter, building the retlog closure,
and a second call through it to log the return value.

Check for "not recording, and the trace log is off" first and call the wrapped
function directly. The isinstance check moves to the slow path; the decorator
already verifies at decoration time that it is wrapping a method whose first
argument is self, and the fast path would raise AttributeError immediately on
anything without should_record_events.

On a UMA cold compile (fairchem uma-s-1p2, 1000 atoms, dynamic=True), total
compile time as the union of top-level chromium events:

  pair 1:  baseline 48.12s   changed 47.70s
  pair 2:  baseline 47.76s   changed 46.75s
  pair 3:  baseline 47.57s   changed 46.18s

i.e. 47.82s -> 46.88s, -2.0%.

Test plan:

```
python test/test_dynamic_shapes.py
python test/dynamo/test_misc.py
```

Both give failure sets identical to a run with the change stashed (this host
has pre-existing aarch64 CPU codegen failures). Recording itself is exercised
by a ShapeEnv(should_record_events=True) that traces a few fake-tensor ops and
replays its events; the recorded event names and the replayed ShapeEnv are
unchanged.

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


ghstack-source-id: d6ae86a
Pull-Request: #193161
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 14, 2026
record_shapeenv_event wraps the mutating ShapeEnv methods, so it runs a few
hundred thousand times per compile (366k in one model's cold compile). Event
recording is only on under translation validation, but the wrapper paid for it
on every call regardless: an import of symbolic_shapes, an isinstance
assertion, a debug log, bumping the NEST counter, building the retlog closure,
and a second call through it to log the return value.

Check for "not recording, and the trace log is off" first and call the wrapped
function directly. The isinstance check moves to the slow path; the decorator
already verifies at decoration time that it is wrapping a method whose first
argument is self, and the fast path would raise AttributeError immediately on
anything without should_record_events.

On one model's cold compile with dynamic=True, total compile time as the union
of top-level chromium events:

  pair 1:  baseline 48.12s   changed 47.70s
  pair 2:  baseline 47.76s   changed 46.75s
  pair 3:  baseline 47.57s   changed 46.18s

i.e. 47.82s -> 46.88s, -2.0%.

Test plan:

```
python test/test_dynamic_shapes.py
python test/dynamo/test_misc.py
```

Both give failure sets identical to a run with the change stashed (this host
has pre-existing aarch64 CPU codegen failures). Recording itself is exercised
by a ShapeEnv(should_record_events=True) that traces a few fake-tensor ops and
replays its events; the recorded event names and the replayed ShapeEnv are
unchanged.

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

ghstack-source-id: c9b12b4
Pull-Request: #193161
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torch/fx/experimental/recording.py Outdated

if not isinstance(args[0], ShapeEnv):
raise AssertionError(f"Expected ShapeEnv, got {type(args[0])}")
# Narrow shape_env itself, not args[0]: the fast path above binds

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.

comment is not needed? no?

Comment thread torch/fx/experimental/recording.py Outdated

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.

nit: not shape_env.should_record_events or shape_env.is_recording is evaluated three times per call. Bind it once at the top and reuse in the inner if / except?

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

avoid inlining (not shape_env.should_record_events or shape_env.is_recording) threetimes else looks good.

[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305 anijain2305 added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 15, 2026
@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

pytorchmergebot pushed a commit that referenced this pull request Aug 16, 2026
…lready knows (#193416)

Every FunctionalTensor wraps an inner tensor by calling
_make_wrapper_subclass with the inner tensor's sizes and strides. When the
caller does not supply storage_size, that helper computes it with
computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a
sub, a mul and an add per dimension - to size a storage that exists only to
track aliasing between subclasses; the data pointer is not even valid.

The inner tensor already knows its storage size, so pass it. This is the same
thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes
storage_size=values.untyped_storage().size()), and mirroring elem is if anything
the more faithful value: the wrapper is meant to shadow elem, whereas the
recomputed number describes only the extent the sizes and strides reach.

On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold
compile with dynamic=True, across 4268 wrapper creations, time in
FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic
operations disappear from the compile. End to end, as the union of top-level
chromium events, over interleaved pairs:

  pair 1:  baseline 40.26s   with storage_size 39.78s
  pair 2:  baseline 40.05s   with storage_size 38.16s
  pair 3:  baseline 39.49s   with storage_size 38.07s

39.93s -> 38.67s, -3.2%.

Sparse inners keep the old path, as they already do for strides and
storage_offset.

Test plan:

```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/test_functionalization.py
```

Failure sets identical to a run with the change reverted (this aarch64 host has
pre-existing failures).

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

Pull Request resolved: #193416
Approved by: https://github.com/Skylion007, https://github.com/zou3519
ghstack dependencies: #193159, #193161
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…pytorch#193161)

record_shapeenv_event wraps the mutating ShapeEnv methods, so it runs a few
hundred thousand times per compile (366k in one model's cold compile). Event
recording is only on under translation validation, but the wrapper paid for it
on every call regardless: an import of symbolic_shapes, an isinstance
assertion, a debug log, bumping the NEST counter, building the retlog closure,
and a second call through it to log the return value.

Check for "not recording, and the trace log is off" first and call the wrapped
function directly. The isinstance check moves to the slow path; the decorator
already verifies at decoration time that it is wrapping a method whose first
argument is self, and the fast path would raise AttributeError immediately on
anything without should_record_events.

On one model's cold compile with dynamic=True, total compile time as the union
of top-level chromium events:

  pair 1:  baseline 48.12s   changed 47.70s
  pair 2:  baseline 47.76s   changed 46.75s
  pair 3:  baseline 47.57s   changed 46.18s

i.e. 47.82s -> 46.88s, -2.0%.

Test plan:

```
python test/test_dynamic_shapes.py
python test/dynamo/test_misc.py
```

Both give failure sets identical to a run with the change stashed (this host
has pre-existing aarch64 CPU codegen failures). Recording itself is exercised
by a ShapeEnv(should_record_events=True) that traces a few fake-tensor ops and
replays its events; the recorded event names and the replayed ShapeEnv are
unchanged.

This PR was authored with the assistance of an AI coding agent.
Pull Request resolved: pytorch#193161
Approved by: https://github.com/laithsakka
ghstack dependencies: pytorch#193159
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…lready knows (pytorch#193416)

Every FunctionalTensor wraps an inner tensor by calling
_make_wrapper_subclass with the inner tensor's sizes and strides. When the
caller does not supply storage_size, that helper computes it with
computeStorageNbytes, which walks the dimensions doing symbolic arithmetic - a
sub, a mul and an add per dimension - to size a storage that exists only to
track aliasing between subclasses; the data pointer is not even valid.

The inner tensor already knows its storage size, so pass it. This is the same
thing NestedTensor does (torch/nested/_internal/nested_tensor.py passes
storage_size=values.untyped_storage().size()), and mirroring elem is if anything
the more faithful value: the wrapper is meant to shadow elem, whereas the
recomputed number describes only the extent the sizes and strides reach.

On a 4d symbolic tensor the call goes from 144us to 21us. Over one model's cold
compile with dynamic=True, across 4268 wrapper creations, time in
FunctionalTensor.__new__ drops from 1.04s to 0.11s, and about 30k symbolic
operations disappear from the compile. End to end, as the union of top-level
chromium events, over interleaved pairs:

  pair 1:  baseline 40.26s   with storage_size 39.78s
  pair 2:  baseline 40.05s   with storage_size 38.16s
  pair 3:  baseline 39.49s   with storage_size 38.07s

39.93s -> 38.67s, -3.2%.

Sparse inners keep the old path, as they already do for strides and
storage_offset.

Test plan:

```
python test/inductor/test_torchinductor_dynamic_shapes.py -k cuda
python test/test_functionalization.py
```

Failure sets identical to a run with the change reverted (this aarch64 host has
pre-existing failures).

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

Pull Request resolved: pytorch#193416
Approved by: https://github.com/Skylion007, https://github.com/zou3519
ghstack dependencies: pytorch#193159, pytorch#193161
@github-actions
github-actions Bot deleted the gh/anijain2305/1306/head branch November 5, 2026 01:46
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 release notes: fx release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants