pytorch - ✅(Solved) Fix @custom_op aliasing check fires unconditionally, even under torch.no_grad() [1 pull requests, 1 participants]

Official PRs (…)
ON THIS PAGE

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#180620Fetched 2026-04-17 08:25:59
View on GitHub
Comments
0
Participants
1
Timeline
15
Reactions
0
Author
Participants
Timeline (top)
labeled ×5mentioned ×5subscribed ×5

Error Message

Error logs

PR fix notes

PR #180717: Skip custom_op aliasing check under no_grad / inference_mode

Description (problem / solution / changelog)

The aliasing check on custom op outputs is there to protect the autograd graph, but it fires unconditionally today, even when grad is disabled via torch.no_grad() or torch.inference_mode(). In those contexts there is no autograd graph being built, so returning a view of an input is perfectly fine. This fixes that by gating the check on torch.is_grad_enabled(). Fixes #180620.

Changed files

  • test/test_custom_ops.py (modified, +19/-0)
  • torch/_library/custom_ops.py (modified, +1/-1)

Code Example

"""Repro: @custom_op aliasing check fires even under no_grad.

The aliasing constraint (output must not alias input) is enforced
unconditionally, even when autograd is disabled and aliasing is safe.
"""
import torch


@torch.library.custom_op("mylib::bar", mutates_args=("buf",))
def bar(buf: torch.Tensor, n: int) -> torch.Tensor:
    buf[:n].fill_(1.0)
    return buf[:n]  # return a view into the mutated buffer


buf = torch.zeros(100, device="cuda")

# Fails even under no_grad
with torch.no_grad():
    result = bar(buf, 10)
    print("no_grad: OK")
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

IIUC, the input/output aliasing problem is tricky with autograd. But it shouldn't need to be upheld when no autograd is involved

"""Repro: @custom_op aliasing check fires even under no_grad.

The aliasing constraint (output must not alias input) is enforced
unconditionally, even when autograd is disabled and aliasing is safe.
"""
import torch


@torch.library.custom_op("mylib::bar", mutates_args=("buf",))
def bar(buf: torch.Tensor, n: int) -> torch.Tensor:
    buf[:n].fill_(1.0)
    return buf[:n]  # return a view into the mutated buffer


buf = torch.zeros(100, device="cuda")

# Fails even under no_grad
with torch.no_grad():
    result = bar(buf, 10)
    print("no_grad: OK")

Error logs

No response

Versions

main

cc @chauhang @penguinwu @bdhirsh @bobrenjc93 @aorenste

extent analysis

TL;DR

The issue can be worked around by re-examining the custom op's behavior when autograd is disabled.

Guidance

  • Review the @torch.library.custom_op decorator to ensure it correctly handles the no_grad context.
  • Consider modifying the bar function to create a new tensor instead of returning a view into the mutated buffer when autograd is disabled.
  • Investigate if there are any existing issues or discussions related to custom ops and autograd in the PyTorch library.
  • Verify if the issue persists when using a different device (e.g., CPU) instead of CUDA.

Example

@torch.library.custom_op("mylib::bar", mutates_args=("buf",))
def bar(buf: torch.Tensor, n: int) -> torch.Tensor:
    with torch.no_grad():
        new_buf = buf.clone()
        new_buf[:n].fill_(1.0)
        return new_buf[:n]

Notes

The provided code snippet and issue description suggest that the problem lies in the interaction between custom ops and autograd. However, without more information about the PyTorch version and the specific use case, it's difficult to provide a definitive solution.

Recommendation

Apply workaround: The example code snippet provides a possible workaround by creating a new tensor instead of returning a view into the mutated buffer when autograd is disabled. This approach may help mitigate the issue, but further investigation is needed to determine the root cause and a permanent fix.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

pytorch - ✅(Solved) Fix @custom_op aliasing check fires unconditionally, even under torch.no_grad() [1 pull requests, 1 participants]