Skip to content

[functionalization] Regenerate one output of a multi-output view without replaying the op - #194037

Closed
anijain2305 wants to merge 15 commits into
gh/anijain2305/1320/basefrom
gh/anijain2305/1320/head
Closed

anijain2305 wants to merge 15 commits into
gh/anijain2305/1320/basefrom
gh/anijain2305/1320/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Functionalization records a ViewMeta per view so it can rebuild that view after
its base is mutated. For a multi-output view the recorded replay is the whole
operation plus an index, so one output of unbind is rebuilt as
at::unbind(base, dim)[i]. Rebuilding all N outputs of one base allocates NN
tensors, and under torch.compile N
N fake tensors and proxies, leaving one
redundant split node in the post-AOT graph per regeneration.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each output is exactly one slice or select of the base. Codegen now emits
forward for those three to build that view directly, leaving a single split
node whatever N is.

The one thing replaying the operation provided that a select does not is
autograd's refusal to let you mutate an output of a multi-output view. That
restriction is keyed off CreationMeta, not off the grad_fn, so
apply_view_meta_sequence restores it directly by marking each regenerated
multi-output view MULTI_OUTPUT_NODE. Only DEFAULT is overwritten, since a view
created under no-grad or inference mode already carries a more specific reason
to reject the mutation. ATen cannot reach CreationMeta directly, because the
internal build splits aten from torch/csrc, hence the new
VariableHooksInterface method.

The cost is that a regenerated view reports SelectBackward0 where eager reports
UnbindBackward0, and the error message loses the output index. The gradient is
unchanged: select_backward scatters into the slice unbind_backward would have.
Two tests asserted on the grad_fn name and now assert the mutation error, which
is what the name stood for.

Measured against the parent, cold compile, fresh inductor cache, median of 3.
The repro mutates N split() views of one tensor and reads them back:

def f(x):
    outs = list(x.split(1))
    for i, o in enumerate(outs):
        o.add_(i)
    return torch.cat([o.clone() for o in outs])

N=128:  32.4s -> 14.9s
N=275: 109.8s -> 40.1s

The post-AOT graph goes from 32 split nodes to 1 at N=16. Without the fix the
cost grows faster than N (2.15x the views, 3.4x the time); with it, 2.7x.

Test Plan:

python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py test/inductor/test_auto_functionalize.py
# 875 passed, 8 skipped, 14 xfailed

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py
# 2884 passed, 819 skipped, 55 xfailed
# (1 pre-existing failure needing LAPACK, unrelated)

The changed goldens are all regeneration sites, where a split or unbind plus its
dead getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).

cc @ezyang @gchanan @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit ab37839 with merge base 37c9975 (image):

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

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

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 24, 2026
…out replaying the op

Functionalization records a ViewMeta for every view so it can rebuild that view
after its base is mutated. For a multi-output view the recorded replay is the
whole operation plus an index: one output of unbind is rebuilt as
`at::unbind(base, dim)[i]`. Rebuilding all N outputs of one base therefore
allocates N*N tensors.

Under torch.compile that is quadratic in the worst way. Each replay creates N
fake tensors and N proxies, and the traced graph keeps N identical view nodes
that every later pass walks again. On an internal optimizer that divides 491
split() views of one tensor in place, the graph carried 490 redundant split
nodes and AOT tracing them was about 47s of the compile.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each of their outputs is exactly one slice or select of the base. Add
ViewMeta::forward_single_output, overridden through codegen for those three to
build that one view directly.

The cheap replay is opt-in, and must stay that way. It is only valid where the
result never reaches autograd: an unbind output rebuilt as a select carries
SelectBackward instead of UnbindBackward, and so silently loses the error
autograd raises when you mutate one output of a multi-output view. Only
FunctionalTensorWrapper::sync_, which refreshes a wrapper's own value, opts in.
Every path that hands the tensor to user code replays the real op -
torch.func.functionalize via _unwrap_functional_tensor, AOTAutograd via
_functionalize_apply_view_metas. Do not pass single_output_replay=true from a
path whose result is user visible; nothing in C++ enforces this.

_unwrap_functional_tensor now also does the sync itself, so the torch._sync call
ahead of it in _maybe_unwrap_functional_tensor is removed. Left in, it runs the
cheap replay first and that discarded select is still traced, leaving a dead node
beside the exact regeneration.

Measured cold with autotuning disabled:

    491 views:  123.4s -> 38.8s
    275 views:   72.7s -> 34.0s

Test Plan:

```
python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py
# 829 passed

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py
# 2840 passed, 1 pre-existing failure (needs LAPACK)

python -m pytest -q -p no:randomly test/inductor/test_torchinductor.py
# failure set identical to baseline, test by test
```

test_multioutput_view_preserves_autograd_metadata covers the autograd rule above
and fails without the fix with SelectBackward0. The test_functionalization
goldens change only at regeneration sites, where a split or unbind plus its dead
getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).

ghstack-source-id: e54cd5a
Pull-Request: #194037
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 24, 2026
…out replaying the op

Functionalization records a ViewMeta for every view so it can rebuild that view
after its base is mutated. For a multi-output view the recorded replay is the
whole operation plus an index: one output of unbind is rebuilt as
`at::unbind(base, dim)[i]`. Rebuilding all N outputs of one base therefore
allocates N*N tensors.

Under torch.compile that is quadratic in the worst way. Each replay creates N
fake tensors and N proxies, and the traced graph keeps N identical view nodes
that every later pass walks again. Mutating N split() views of one tensor and
reading them back leaves N+1 split nodes in the post-AOT graph: 17 at N=16.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each of their outputs is exactly one slice or select of the base. Add
ViewMeta::forward_single_output, overridden through codegen for those three to
build that one view directly. The same graph then holds a single split node
whatever N is.

The cheap replay is opt-in, and must stay that way. It is only valid where the
result never reaches autograd: an unbind output rebuilt as a select carries
SelectBackward instead of UnbindBackward, and so silently loses the error
autograd raises when you mutate one output of a multi-output view. Only
FunctionalTensorWrapper::sync_, which refreshes a wrapper's own value, opts in.
Every path that hands the tensor to user code replays the real op -
torch.func.functionalize via _unwrap_functional_tensor, AOTAutograd via
_functionalize_apply_view_metas. Do not pass single_output_replay=true from a
path whose result is user visible; nothing in C++ enforces this.

Measured against the parent commit with a synthetic repro of the pattern that
motivated this - N split() views of one tensor divided in place, then read back -
cold compile, autotuning off, median of three:

    N=128:  38.2s -> 20.9s
    N=275: 125.3s -> 46.2s

Without the fix the cost grows faster than N (2.15x the views, 3.3x the time);
with it, roughly linearly (2.2x).

Test Plan:

```
python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py
# 829 passed

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py
# 2840 passed, 1 pre-existing failure (needs LAPACK)

python -m pytest -q -p no:randomly test/inductor/test_torchinductor.py
# failure set identical to baseline, test by test
```

test_multioutput_view_preserves_autograd_metadata covers the autograd rule above
and fails without the fix with SelectBackward0. The test_functionalization
goldens change only at regeneration sites, where a split or unbind plus its dead
getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).

ghstack-source-id: 5af0681
Pull-Request: #194037
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Aug 24, 2026
…out replaying the op

Functionalization records a ViewMeta for every view so it can rebuild that view
after its base is mutated. For a multi-output view the recorded replay is the
whole operation plus an index: one output of unbind is rebuilt as
`at::unbind(base, dim)[i]`. Rebuilding all N outputs of one base therefore
allocates N*N tensors.

Under torch.compile that is quadratic in the worst way. Each replay creates N
fake tensors and N proxies, and the traced graph keeps N identical view nodes
that every later pass walks again. Mutating N split() views of one tensor and
reading them back leaves N+1 split nodes in the post-AOT graph: 17 at N=16.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each of their outputs is exactly one slice or select of the base. Add
ViewMeta::forward_single_output, overridden through codegen for those three to
build that one view directly. The same graph then holds a single split node
whatever N is.

The cheap replay is opt-in, and must stay that way. It is only valid where the
result never reaches autograd: an unbind output rebuilt as a select carries
SelectBackward instead of UnbindBackward, and so silently loses the error
autograd raises when you mutate one output of a multi-output view. Only
FunctionalTensorWrapper::sync_, which refreshes a wrapper's own value, opts in.
Every path that hands the tensor to user code replays the real op -
torch.func.functionalize via _unwrap_functional_tensor, AOTAutograd via
_functionalize_apply_view_metas. Do not pass single_output_replay=true from a
path whose result is user visible; nothing in C++ enforces this.

Measured against the parent commit with a synthetic repro of the pattern that
motivated this - N split() views of one tensor divided in place, then read back -
cold compile, autotuning off, median of three:

    N=128:  38.2s -> 20.9s
    N=275: 125.3s -> 46.2s

Without the fix the cost grows faster than N (2.15x the views, 3.3x the time);
with it, roughly linearly (2.2x).

Test Plan:

```
python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py

python -m pytest -q -p no:randomly test/inductor/test_torchinductor.py
```

test_multioutput_view_preserves_autograd_metadata covers the autograd rule above
and fails without the fix with SelectBackward0. The test_functionalization
goldens change only at regeneration sites, where a split or unbind plus its dead
getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).

ghstack-source-id: 61d6eb7
Pull-Request: #194037
pytorchmergebot added a commit that referenced this pull request Sep 3, 2026
…iew without replaying the op (#194037)"

This reverts commit cdd9908.

Reverted #194037 on behalf of https://github.com/huydhn due to Check with Animesh, we will revert and reland this instead. There are some internal failures on D118506424 ([comment](#194037 (comment)))
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@anijain2305 your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Sep 3, 2026
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Sep 3, 2026
…out replaying the op

Functionalization records a ViewMeta per view so it can rebuild that view after
its base is mutated. For a multi-output view the recorded replay is the whole
operation plus an index, so one output of unbind is rebuilt as
`at::unbind(base, dim)[i]`. Rebuilding all N outputs of one base allocates N*N
tensors, and under torch.compile N*N fake tensors and proxies, leaving one
redundant split node in the post-AOT graph per regeneration.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each output is exactly one slice or select of the base. Codegen now emits
`forward` for those three to build that view directly, leaving a single split
node whatever N is.

The one thing replaying the operation provided that a select does not is
autograd's refusal to let you mutate an output of a multi-output view. That
restriction is keyed off CreationMeta, not off the grad_fn, so
apply_view_meta_sequence restores it directly by marking each regenerated
multi-output view MULTI_OUTPUT_NODE. Only DEFAULT is overwritten, since a view
created under no-grad or inference mode already carries a more specific reason
to reject the mutation. ATen cannot reach CreationMeta directly, because the
internal build splits aten from torch/csrc, so torch/csrc/autograd registers a
marker function that apply_view_meta_sequence calls.

An earlier version of this change put that marker on VariableHooksInterface,
and that is what got it reverted: torchdistx implements that interface out of
tree, so adding a pure virtual broke its build. A dedicated registration point
avoids that, and is safer than giving the interface method a default body would
have been - torchdistx installs a forwarding proxy as the process-wide hooks,
so a default it did not forward would have silently dropped the mutation
restriction instead of failing to build.

The cost is that a regenerated view reports SelectBackward0 where eager reports
UnbindBackward0, and the error message loses the output index. The gradient is
unchanged: select_backward scatters into the slice unbind_backward would have.
Two tests asserted on the grad_fn name and now assert the mutation error, which
is what the name stood for.

Measured against the parent, cold compile, fresh inductor cache, median of 3.
The repro mutates N split() views of one tensor and reads them back:

    def f(x):
        outs = list(x.split(1))
        for i, o in enumerate(outs):
            o.add_(i)
        return torch.cat([o.clone() for o in outs])

    N=128:  32.4s -> 14.9s
    N=275: 109.8s -> 40.1s

The post-AOT graph goes from 32 split nodes to 1 at N=16. Without the fix the
cost grows faster than N (2.15x the views, 3.4x the time); with it, 2.7x.

Test Plan:

```
python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py test/inductor/test_auto_functionalize.py
# 875 passed, 8 skipped, 14 xfailed

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py
# 2884 passed, 819 skipped, 55 xfailed
# (1 pre-existing failure needing LAPACK, unrelated)
```

The changed goldens are all regeneration sites, where a split or unbind plus its
dead getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).
ghstack-source-id: 5939fc2
Pull-Request: #194037
@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

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@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

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…out replaying the op (pytorch#194037)

Functionalization records a ViewMeta per view so it can rebuild that view after
its base is mutated. For a multi-output view the recorded replay is the whole
operation plus an index, so one output of unbind is rebuilt as
`at::unbind(base, dim)[i]`. Rebuilding all N outputs of one base allocates N*N
tensors, and under torch.compile N*N fake tensors and proxies, leaving one
redundant split node in the post-AOT graph per regeneration.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each output is exactly one slice or select of the base. Codegen now emits
`forward` for those three to build that view directly, leaving a single split
node whatever N is.

The one thing replaying the operation provided that a select does not is
autograd's refusal to let you mutate an output of a multi-output view. That
restriction is keyed off CreationMeta, not off the grad_fn, so
apply_view_meta_sequence restores it directly by marking each regenerated
multi-output view MULTI_OUTPUT_NODE. Only DEFAULT is overwritten, since a view
created under no-grad or inference mode already carries a more specific reason
to reject the mutation. ATen cannot reach CreationMeta directly, because the
internal build splits aten from torch/csrc, hence the new
VariableHooksInterface method.

The cost is that a regenerated view reports SelectBackward0 where eager reports
UnbindBackward0, and the error message loses the output index. The gradient is
unchanged: select_backward scatters into the slice unbind_backward would have.
Two tests asserted on the grad_fn name and now assert the mutation error, which
is what the name stood for.

Measured against the parent, cold compile, fresh inductor cache, median of 3.
The repro mutates N split() views of one tensor and reads them back:

    def f(x):
        outs = list(x.split(1))
        for i, o in enumerate(outs):
            o.add_(i)
        return torch.cat([o.clone() for o in outs])

    N=128:  32.4s -> 14.9s
    N=275: 109.8s -> 40.1s

The post-AOT graph goes from 32 split nodes to 1 at N=16. Without the fix the
cost grows faster than N (2.15x the views, 3.4x the time); with it, 2.7x.

Test Plan:

```
python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py test/inductor/test_auto_functionalize.py
# 875 passed, 8 skipped, 14 xfailed

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py
# 2884 passed, 819 skipped, 55 xfailed
# (1 pre-existing failure needing LAPACK, unrelated)
```

The changed goldens are all regeneration sites, where a split or unbind plus its
dead getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).

Pull Request resolved: pytorch#194037
Approved by: https://github.com/zou3519
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…iew without replaying the op (pytorch#194037)"

This reverts commit cdd9908.

Reverted pytorch#194037 on behalf of https://github.com/huydhn due to Check with Animesh, we will revert and reland this instead. There are some internal failures on D118506424 ([comment](pytorch#194037 (comment)))
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…out replaying the op (pytorch#194037)

Functionalization records a ViewMeta per view so it can rebuild that view after
its base is mutated. For a multi-output view the recorded replay is the whole
operation plus an index, so one output of unbind is rebuilt as
`at::unbind(base, dim)[i]`. Rebuilding all N outputs of one base allocates N*N
tensors, and under torch.compile N*N fake tensors and proxies, leaving one
redundant split node in the post-AOT graph per regeneration.

split.Tensor, split_with_sizes and unbind.int are the only multi-output views,
and each output is exactly one slice or select of the base. Codegen now emits
`forward` for those three to build that view directly, leaving a single split
node whatever N is.

The one thing replaying the operation provided that a select does not is
autograd's refusal to let you mutate an output of a multi-output view. That
restriction is keyed off CreationMeta, not off the grad_fn, so
apply_view_meta_sequence restores it directly by marking each regenerated
multi-output view MULTI_OUTPUT_NODE. Only DEFAULT is overwritten, since a view
created under no-grad or inference mode already carries a more specific reason
to reject the mutation. ATen cannot reach CreationMeta directly, because the
internal build splits aten from torch/csrc, hence the new
VariableHooksInterface method.

The cost is that a regenerated view reports SelectBackward0 where eager reports
UnbindBackward0, and the error message loses the output index. The gradient is
unchanged: select_backward scatters into the slice unbind_backward would have.
Two tests asserted on the grad_fn name and now assert the mutation error, which
is what the name stood for.

Measured against the parent, cold compile, fresh inductor cache, median of 3.
The repro mutates N split() views of one tensor and reads them back:

    def f(x):
        outs = list(x.split(1))
        for i, o in enumerate(outs):
            o.add_(i)
        return torch.cat([o.clone() for o in outs])

    N=128:  32.4s -> 14.9s
    N=275: 109.8s -> 40.1s

The post-AOT graph goes from 32 split nodes to 1 at N=16. Without the fix the
cost grows faster than N (2.15x the views, 3.4x the time); with it, 2.7x.

Test Plan:

```
python -m pytest -q -p no:randomly test/functorch/test_eager_transforms.py \
  test/test_functionalization.py test/inductor/test_auto_functionalize.py
# 875 passed, 8 skipped, 14 xfailed

python -m pytest -q -p no:randomly test/functorch/test_aotdispatch.py
# 2884 passed, 819 skipped, 55 xfailed
# (1 pre-existing failure needing LAPACK, unrelated)
```

The changed goldens are all regeneration sites, where a split or unbind plus its
dead getitems becomes a single slice or select.

This commit was authored with the assistance of an AI agent (Claude Code).

Pull Request resolved: pytorch#194037
Approved by: https://github.com/zou3519
@zou3519 zou3519 added the module: bc-breaking Related to a BC-breaking change label Sep 16, 2026
@zou3519

zou3519 commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

minor bc-break for changing the IR, but maybe that doesn't count

@anmyachev

Copy link
Copy Markdown
Collaborator

We also observe regression in timm_models due to this change: intel/intel-xpu-backend-for-triton#8077 (comment)

torchxpubot pushed a commit to intel/torch-xpu-ops that referenced this pull request Oct 9, 2026
…5579)

[pytorch#194037](pytorch/pytorch#194037)
regenerates each output of a multi-output view as a select/slice, so the
outputs now report SelectBackward instead of UnbindBackward. Upstream
updated the test to assert the multi-output view mutation error instead
of the grad_fn name; sync that change into the XPU copy.

Fixes: [#5258](#5258)
minmingzhu pushed a commit to minmingzhu/torch-xpu-ops that referenced this pull request Oct 28, 2026
…ntel#5579)

[pytorch#194037](pytorch/pytorch#194037)
regenerates each output of a multi-output view as a select/slice, so the
outputs now report SelectBackward instead of UnbindBackward. Upstream
updated the test to assert the multi-output view mutation error instead
of the grad_fn name; sync that change into the XPU copy.

Fixes: [intel#5258](intel#5258)
@github-actions
github-actions Bot deleted the gh/anijain2305/1320/head branch November 15, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged module: bc-breaking Related to a BC-breaking change module: inductor Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants