pytorch - 💡(How to fix) Fix RuntimeError: Argument 'primals_out' of Node 'results' was used before it has been defined! Please check that Nodes in the graph are topologically ordered [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

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#179510Fetched 2026-04-08 03:00:41
View on GitHub
Comments
0
Participants
1
Timeline
5
Reactions
0
Participants
Timeline (top)
mentioned ×2subscribed ×2labeled ×1

Error Message

import torch from torch import Tensor, nn

@torch.no_grad() def _fixpoint_iteration(fn, x: Tensor) -> Tensor: for _ in range(5): x = fn(x) return x

def fixpoint_solve_old(fn, x0: Tensor, *extra_args: Tensor) -> Tensor: with torch.no_grad(): x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

x_star1 = fn(x_star, *extra_args)
x_star = x_star1.clone().detach().requires_grad_()
x_star2 = fn(x_star, *extra_args)

def backward_solve(g: Tensor) -> Tensor:
    return _fixpoint_iteration(
        lambda u: g + torch.autograd.grad(x_star2, x_star, u, retain_graph=True)[0],
        g,
    )

x_star1.register_hook(backward_solve)
return x_star1

def fixpoint_solve_new(fn, x0: Tensor, *extra_args: Tensor) -> Tensor: with torch.no_grad(): x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

x_star, vjp_fn, *_ = torch.func.vjp(
    lambda z: fn(z, *extra_args),
    x_star,
)

def backward_solve(g: Tensor) -> Tensor:
    return _fixpoint_iteration(lambda u: g + vjp_fn(u)[0], g)

x_star.register_hook(backward_solve)
return x_star

def check_eager(solver): y = torch.randn(5, 3) W = nn.Parameter(torch.randn(3, 3)) b = nn.Parameter(torch.randn(3)) y_star = solver(lambda z: z @ W.mH + b, y) loss = y_star.square().sum() loss.backward() assert W.grad is not None

def check_compiled_forward(solver): torch._dynamo.reset() y = torch.randn(5, 3) W = nn.Parameter(torch.randn(3, 3)) b = nn.Parameter(torch.randn(3))

@torch.compile
def forward(y0) -> Tensor:
    y_star = solver(lambda z: z @ W.mH + b, y0)
    return y_star.square().sum()

loss = forward(y)
loss.backward()
assert W.grad is not None

def check_compiled_backward(solver): torch._dynamo.reset() y = torch.randn(5, 3) W = nn.Parameter(torch.randn(3, 3)) b = nn.Parameter(torch.randn(3))

@torch.compile
def backward(y0) -> Tensor:
    y_star = solver(lambda z: z @ W.mH + b, y0)
    loss = y_star.square().sum()
    loss.backward()

backward(y)
assert W.grad is not None

def test(solver): checks = { "eager": check_eager, "compiled_forward": check_compiled_forward, "compiled_backward": check_compiled_backward, } excs = {}

for name, check in checks.items():
    try:
        check(solver)
    except Exception as exc:
        excs[name] = exc
    else:
        excs[name] = None

print(
    f"{solver.__name__}:\n"
    + "\n".join(
        f"  {name}: {'OK' if exc is None else 'FAIL'}" for name, exc in excs.items()
    )
)
for name, exc in excs.items():
    if exc is not None:
        print(f"{name}: {exc}")

if name == "main": # torch._dynamo.config.compiled_autograd = True test(fixpoint_solve_old) test(fixpoint_solve_new) # check_compiled_forward(fixpoint_solve_new) # check_compiled_backward(fixpoint_solve_new)

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 16 On-line CPU(s) list: 0-15 Vendor ID: GenuineIntel Model name: 11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz CPU family: 6 Model: 141 Thread(s) per core: 2 Core(s) per socket: 8 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 58% CPU max MHz: 4800.0000 CPU min MHz: 800.0000 BogoMIPS: 4992.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 384 KiB (8 instances) L1i cache: 256 KiB (8 instances) L2 cache: 10 MiB (8 instances) L3 cache: 24 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-15 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Indirect target selection: Vulnerable Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

Code Example

def fixpoint_solve_old(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star1 = fn(x_star, *extra_args)
    x_star = x_star1.clone().detach().requires_grad_()
    x_star2 = fn(x_star, *extra_args)

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(
            lambda u: g + torch.autograd.grad(x_star2, x_star, u, retain_graph=True)[0],
            g,
        )

    x_star1.register_hook(backward_solve)
    return x_star1

def fixpoint_solve_new(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star, vjp_fn, *_ = torch.func.vjp(
        lambda z: fn(z, *extra_args),
        x_star,
    )

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(lambda u: g + vjp_fn(u)[0], g)

    x_star.register_hook(backward_solve)
    return x_star

---

import torch
from torch import Tensor, nn


@torch.no_grad()
def _fixpoint_iteration(fn, x: Tensor) -> Tensor:
    for _ in range(5):
        x = fn(x)
    return x


def fixpoint_solve_old(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star1 = fn(x_star, *extra_args)
    x_star = x_star1.clone().detach().requires_grad_()
    x_star2 = fn(x_star, *extra_args)

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(
            lambda u: g + torch.autograd.grad(x_star2, x_star, u, retain_graph=True)[0],
            g,
        )

    x_star1.register_hook(backward_solve)
    return x_star1


def fixpoint_solve_new(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star, vjp_fn, *_ = torch.func.vjp(
        lambda z: fn(z, *extra_args),
        x_star,
    )

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(lambda u: g + vjp_fn(u)[0], g)

    x_star.register_hook(backward_solve)
    return x_star


def check_eager(solver):
    y = torch.randn(5, 3)
    W = nn.Parameter(torch.randn(3, 3))
    b = nn.Parameter(torch.randn(3))
    y_star = solver(lambda z: z @ W.mH + b, y)
    loss = y_star.square().sum()
    loss.backward()
    assert W.grad is not None


def check_compiled_forward(solver):
    torch._dynamo.reset()
    y = torch.randn(5, 3)
    W = nn.Parameter(torch.randn(3, 3))
    b = nn.Parameter(torch.randn(3))

    @torch.compile
    def forward(y0) -> Tensor:
        y_star = solver(lambda z: z @ W.mH + b, y0)
        return y_star.square().sum()

    loss = forward(y)
    loss.backward()
    assert W.grad is not None


def check_compiled_backward(solver):
    torch._dynamo.reset()
    y = torch.randn(5, 3)
    W = nn.Parameter(torch.randn(3, 3))
    b = nn.Parameter(torch.randn(3))

    @torch.compile
    def backward(y0) -> Tensor:
        y_star = solver(lambda z: z @ W.mH + b, y0)
        loss = y_star.square().sum()
        loss.backward()

    backward(y)
    assert W.grad is not None


def test(solver):
    checks = {
        "eager": check_eager,
        "compiled_forward": check_compiled_forward,
        "compiled_backward": check_compiled_backward,
    }
    excs = {}

    for name, check in checks.items():
        try:
            check(solver)
        except Exception as exc:
            excs[name] = exc
        else:
            excs[name] = None

    print(
        f"{solver.__name__}:\n"
        + "\n".join(
            f"  {name}: {'OK' if exc is None else 'FAIL'}" for name, exc in excs.items()
        )
    )
    for name, exc in excs.items():
        if exc is not None:
            print(f"{name}: {exc}")


if __name__ == "__main__":
    # torch._dynamo.config.compiled_autograd = True
    test(fixpoint_solve_old)
    test(fixpoint_solve_new)
    # check_compiled_forward(fixpoint_solve_new)
    # check_compiled_backward(fixpoint_solve_new)

---

RuntimeError: Argument 'primals_out' of Node 'results' was used before it has been defined! Please check that Nodes in the graph are topologically ordered
graph():
    %_saved_tensors_hooks_disable : [num_users=0] = call_function[target=torch._C._autograd._saved_tensors_hooks_disable](args = (torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case.,), kwargs = {})
    %_grad_increment_nesting : [num_users=0] = call_function[target=torch._C._functorch._grad_increment_nesting](args = (), kwargs = {})
    %set_inplace_requires_grad_allowed : [num_users=0] = call_function[target=torch._C._functorch.set_inplace_requires_grad_allowed](args = (True,), kwargs = {})
    %set_inplace_requires_grad_allowed_1 : [num_users=0] = call_function[target=torch._C._functorch.set_inplace_requires_grad_allowed](args = (False,), kwargs = {})
    %results : [num_users=1] = call_function[target=torch._C._functorch._unwrap_for_grad](args = (%primals_out, 1), kwargs = {})
    %fwd_body_0 : [num_users=1] = get_attr[target=fwd_body_0]
    %bwd_body_0 : [num_users=1] = get_attr[target=bwd_body_0]
    %l_y0_ : torch.Tensor [num_users=1] = placeholder[target=L_y0_]
    %l_w_ : torch.nn.parameter.Parameter [num_users=6] = placeholder[target=L_W_]
    %getattr_1 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul : [num_users=1] = call_function[target=operator.matmul](args = (%l_y0_, %getattr_1), kwargs = {})
    %l_b_ : torch.nn.parameter.Parameter [num_users=6] = placeholder[target=L_b_]
    %x : [num_users=1] = call_function[target=operator.add](args = (%matmul, %l_b_), kwargs = {})
    %getattr_2 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_1 : [num_users=1] = call_function[target=operator.matmul](args = (%x, %getattr_2), kwargs = {})
    %x_1 : [num_users=1] = call_function[target=operator.add](args = (%matmul_1, %l_b_), kwargs = {})
    %getattr_3 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_2 : [num_users=1] = call_function[target=operator.matmul](args = (%x_1, %getattr_3), kwargs = {})
    %x_2 : [num_users=1] = call_function[target=operator.add](args = (%matmul_2, %l_b_), kwargs = {})
    %getattr_4 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_3 : [num_users=1] = call_function[target=operator.matmul](args = (%x_2, %getattr_4), kwargs = {})
    %x_3 : [num_users=1] = call_function[target=operator.add](args = (%matmul_3, %l_b_), kwargs = {})
    %getattr_5 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_4 : [num_users=1] = call_function[target=operator.matmul](args = (%x_3, %getattr_5), kwargs = {})
    %x_4 : [num_users=1] = call_function[target=operator.add](args = (%matmul_4, %l_b_), kwargs = {})
    %_wrap_for_grad : [num_users=2] = call_function[target=torch._C._functorch._wrap_for_grad](args = (%x_4, 1), kwargs = {})
    %getattr_6 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_5 : [num_users=1] = call_function[target=operator.matmul](args = (%_wrap_for_grad, %getattr_6), kwargs = {})
    %primals_out : [num_users=2] = call_function[target=operator.add](args = (%matmul_5, %l_b_), kwargs = {})
    %child : [num_users=1] = call_function[target=torch._functorch.eager_transforms._set_tensor_requires_grad](args = (%_wrap_for_grad,), kwargs = {})
    %autograd_function_apply : [num_users=1] = call_function[target=torch.ops.higher_order.autograd_function_apply](args = (%fwd_body_0, %bwd_body_0, %results, %primals_out, %child), kwargs = {non_differentiable_idx: [], saved_for_backward_idx: []})
    %getitem : [num_users=1] = call_function[target=operator.getitem](args = (%autograd_function_apply, 0), kwargs = {})
    %_grad_decrement_nesting : [num_users=0] = call_function[target=torch._C._functorch._grad_decrement_nesting](args = (), kwargs = {})
    %_saved_tensors_hooks_enable : [num_users=0] = call_function[target=torch._C._autograd._saved_tensors_hooks_enable](args = (), kwargs = {})
    %square : [num_users=1] = call_method[target=square](args = (%getitem,), kwargs = {})
    %sum_1 : [num_users=1] = call_method[target=sum](args = (%square,), kwargs = {})
    return (sum_1,)

---

torch._dynamo.exc.InternalTorchDynamoError: RuntimeError: Tried to erase Node primals_out but it still had 1 users in the graph: {results: None}!

---

NotImplementedError: Cannot access storage of TensorWrapper
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

I am trying to simplify this old fixpoint solver code (xref https://implicit-layers-tutorial.org/deep_equilibrium_models/) towards the new torch.func API:

def fixpoint_solve_old(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star1 = fn(x_star, *extra_args)
    x_star = x_star1.clone().detach().requires_grad_()
    x_star2 = fn(x_star, *extra_args)

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(
            lambda u: g + torch.autograd.grad(x_star2, x_star, u, retain_graph=True)[0],
            g,
        )

    x_star1.register_hook(backward_solve)
    return x_star1

def fixpoint_solve_new(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star, vjp_fn, *_ = torch.func.vjp(
        lambda z: fn(z, *extra_args),
        x_star,
    )

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(lambda u: g + vjp_fn(u)[0], g)

    x_star.register_hook(backward_solve)
    return x_star

Both of these work fine in eager mode, however, when using torch.func.vjp, I get this error with torch.compile:

RuntimeError: Argument 'primals_out' of Node 'results' was used before it has been defined! Please check that Nodes in the graph are topologically ordered

I tried using torch._dynamo.config.compiled_autograd = True which yields a different error message:

NotImplementedError: Cannot access storage of TensorWrapper

Possibly related: #172026

<details> <summary> Full MWE with eager / compile </summary>
import torch
from torch import Tensor, nn


@torch.no_grad()
def _fixpoint_iteration(fn, x: Tensor) -> Tensor:
    for _ in range(5):
        x = fn(x)
    return x


def fixpoint_solve_old(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star1 = fn(x_star, *extra_args)
    x_star = x_star1.clone().detach().requires_grad_()
    x_star2 = fn(x_star, *extra_args)

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(
            lambda u: g + torch.autograd.grad(x_star2, x_star, u, retain_graph=True)[0],
            g,
        )

    x_star1.register_hook(backward_solve)
    return x_star1


def fixpoint_solve_new(fn, x0: Tensor, *extra_args: Tensor) -> Tensor:
    with torch.no_grad():
        x_star = _fixpoint_iteration(lambda z: fn(z, *extra_args), x0)

    x_star, vjp_fn, *_ = torch.func.vjp(
        lambda z: fn(z, *extra_args),
        x_star,
    )

    def backward_solve(g: Tensor) -> Tensor:
        return _fixpoint_iteration(lambda u: g + vjp_fn(u)[0], g)

    x_star.register_hook(backward_solve)
    return x_star


def check_eager(solver):
    y = torch.randn(5, 3)
    W = nn.Parameter(torch.randn(3, 3))
    b = nn.Parameter(torch.randn(3))
    y_star = solver(lambda z: z @ W.mH + b, y)
    loss = y_star.square().sum()
    loss.backward()
    assert W.grad is not None


def check_compiled_forward(solver):
    torch._dynamo.reset()
    y = torch.randn(5, 3)
    W = nn.Parameter(torch.randn(3, 3))
    b = nn.Parameter(torch.randn(3))

    @torch.compile
    def forward(y0) -> Tensor:
        y_star = solver(lambda z: z @ W.mH + b, y0)
        return y_star.square().sum()

    loss = forward(y)
    loss.backward()
    assert W.grad is not None


def check_compiled_backward(solver):
    torch._dynamo.reset()
    y = torch.randn(5, 3)
    W = nn.Parameter(torch.randn(3, 3))
    b = nn.Parameter(torch.randn(3))

    @torch.compile
    def backward(y0) -> Tensor:
        y_star = solver(lambda z: z @ W.mH + b, y0)
        loss = y_star.square().sum()
        loss.backward()

    backward(y)
    assert W.grad is not None


def test(solver):
    checks = {
        "eager": check_eager,
        "compiled_forward": check_compiled_forward,
        "compiled_backward": check_compiled_backward,
    }
    excs = {}

    for name, check in checks.items():
        try:
            check(solver)
        except Exception as exc:
            excs[name] = exc
        else:
            excs[name] = None

    print(
        f"{solver.__name__}:\n"
        + "\n".join(
            f"  {name}: {'OK' if exc is None else 'FAIL'}" for name, exc in excs.items()
        )
    )
    for name, exc in excs.items():
        if exc is not None:
            print(f"{name}: {exc}")


if __name__ == "__main__":
    # torch._dynamo.config.compiled_autograd = True
    test(fixpoint_solve_old)
    test(fixpoint_solve_new)
    # check_compiled_forward(fixpoint_solve_new)
    # check_compiled_backward(fixpoint_solve_new)
</details>

Error logs

<details><summary>compiling forward only </summary>
RuntimeError: Argument 'primals_out' of Node 'results' was used before it has been defined! Please check that Nodes in the graph are topologically ordered
graph():
    %_saved_tensors_hooks_disable : [num_users=0] = call_function[target=torch._C._autograd._saved_tensors_hooks_disable](args = (torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case.,), kwargs = {})
    %_grad_increment_nesting : [num_users=0] = call_function[target=torch._C._functorch._grad_increment_nesting](args = (), kwargs = {})
    %set_inplace_requires_grad_allowed : [num_users=0] = call_function[target=torch._C._functorch.set_inplace_requires_grad_allowed](args = (True,), kwargs = {})
    %set_inplace_requires_grad_allowed_1 : [num_users=0] = call_function[target=torch._C._functorch.set_inplace_requires_grad_allowed](args = (False,), kwargs = {})
    %results : [num_users=1] = call_function[target=torch._C._functorch._unwrap_for_grad](args = (%primals_out, 1), kwargs = {})
    %fwd_body_0 : [num_users=1] = get_attr[target=fwd_body_0]
    %bwd_body_0 : [num_users=1] = get_attr[target=bwd_body_0]
    %l_y0_ : torch.Tensor [num_users=1] = placeholder[target=L_y0_]
    %l_w_ : torch.nn.parameter.Parameter [num_users=6] = placeholder[target=L_W_]
    %getattr_1 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul : [num_users=1] = call_function[target=operator.matmul](args = (%l_y0_, %getattr_1), kwargs = {})
    %l_b_ : torch.nn.parameter.Parameter [num_users=6] = placeholder[target=L_b_]
    %x : [num_users=1] = call_function[target=operator.add](args = (%matmul, %l_b_), kwargs = {})
    %getattr_2 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_1 : [num_users=1] = call_function[target=operator.matmul](args = (%x, %getattr_2), kwargs = {})
    %x_1 : [num_users=1] = call_function[target=operator.add](args = (%matmul_1, %l_b_), kwargs = {})
    %getattr_3 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_2 : [num_users=1] = call_function[target=operator.matmul](args = (%x_1, %getattr_3), kwargs = {})
    %x_2 : [num_users=1] = call_function[target=operator.add](args = (%matmul_2, %l_b_), kwargs = {})
    %getattr_4 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_3 : [num_users=1] = call_function[target=operator.matmul](args = (%x_2, %getattr_4), kwargs = {})
    %x_3 : [num_users=1] = call_function[target=operator.add](args = (%matmul_3, %l_b_), kwargs = {})
    %getattr_5 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_4 : [num_users=1] = call_function[target=operator.matmul](args = (%x_3, %getattr_5), kwargs = {})
    %x_4 : [num_users=1] = call_function[target=operator.add](args = (%matmul_4, %l_b_), kwargs = {})
    %_wrap_for_grad : [num_users=2] = call_function[target=torch._C._functorch._wrap_for_grad](args = (%x_4, 1), kwargs = {})
    %getattr_6 : [num_users=1] = call_function[target=builtins.getattr](args = (%l_w_, mH), kwargs = {})
    %matmul_5 : [num_users=1] = call_function[target=operator.matmul](args = (%_wrap_for_grad, %getattr_6), kwargs = {})
    %primals_out : [num_users=2] = call_function[target=operator.add](args = (%matmul_5, %l_b_), kwargs = {})
    %child : [num_users=1] = call_function[target=torch._functorch.eager_transforms._set_tensor_requires_grad](args = (%_wrap_for_grad,), kwargs = {})
    %autograd_function_apply : [num_users=1] = call_function[target=torch.ops.higher_order.autograd_function_apply](args = (%fwd_body_0, %bwd_body_0, %results, %primals_out, %child), kwargs = {non_differentiable_idx: [], saved_for_backward_idx: []})
    %getitem : [num_users=1] = call_function[target=operator.getitem](args = (%autograd_function_apply, 0), kwargs = {})
    %_grad_decrement_nesting : [num_users=0] = call_function[target=torch._C._functorch._grad_decrement_nesting](args = (), kwargs = {})
    %_saved_tensors_hooks_enable : [num_users=0] = call_function[target=torch._C._autograd._saved_tensors_hooks_enable](args = (), kwargs = {})
    %square : [num_users=1] = call_method[target=square](args = (%getitem,), kwargs = {})
    %sum_1 : [num_users=1] = call_method[target=sum](args = (%square,), kwargs = {})
    return (sum_1,)
</details> <details><summary> compiling backward </summary>
torch._dynamo.exc.InternalTorchDynamoError: RuntimeError: Tried to erase Node primals_out but it still had 1 users in the graph: {results: None}!
</details> <details><summary> compile forward/backward + config.compiled_autograd </summary>
NotImplementedError: Cannot access storage of TensorWrapper
</details>

Versions

Collecting environment information... PyTorch version: 2.11.0+cu130 Is debug build: False CUDA used to build PyTorch: 13.0 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.4 LTS (x86_64) GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 Clang version: 18.1.3 (1ubuntu1) CMake version: version 4.3.1 Libc version: glibc-2.39

Python version: 3.14.3 (main, Mar 24 2026, 22:50:36) [Clang 22.1.1 ] (64-bit runtime) Python platform: Linux-6.8.0-101-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: 13.0.88 CUDA_MODULE_LOADING set to: N/A GPU models and configuration: Could not collect Nvidia driver version: Could not collect cuDNN version: Probably one of the following: /usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.20.0 /usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7 Is XPU available: False HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True Caching allocator config: N/A

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 16 On-line CPU(s) list: 0-15 Vendor ID: GenuineIntel Model name: 11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz CPU family: 6 Model: 141 Thread(s) per core: 2 Core(s) per socket: 8 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 58% CPU max MHz: 4800.0000 CPU min MHz: 800.0000 BogoMIPS: 4992.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 384 KiB (8 instances) L1i cache: 256 KiB (8 instances) L2 cache: 10 MiB (8 instances) L3 cache: 24 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-15 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Indirect target selection: Vulnerable Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

Versions of relevant libraries: [pip3] Could not collect [conda] Could not collect

cc @chauhang @penguinwu

extent analysis

TL;DR

The issue is likely due to incorrect usage of torch.func.vjp with torch.compile, and a workaround could be to modify the fixpoint_solve_new function to properly handle the compiled mode.

Guidance

  1. Check the usage of torch.func.vjp: Verify that torch.func.vjp is used correctly, especially when combined with torch.compile. The error message suggests that there might be an issue with the topological ordering of nodes in the graph.
  2. Modify fixpoint_solve_new for compiled mode: Consider modifying the fixpoint_solve_new function to handle the compiled mode separately, potentially by using a different approach for computing the Jacobian or by using a different autograd function.
  3. Test with a simpler example: Try to reproduce the issue with a simpler example to isolate the problem and understand the root cause.
  4. Check the PyTorch version and updates: Ensure that the PyTorch version is up-to-date, as the issue might be related to a known bug that has been fixed in a later version.

Example

# Simplified example to test torch.func.vjp with torch.compile
import torch

@torch.compile
def test_vjp(x):
    y, vjp_fn = torch.func.vjp(lambda x: x**2, x)
    return vjp_fn(torch.ones_like(x))

# Test the function
x = torch.randn(5)
result = test_vjp(x)

Notes

  • The issue seems to be related to the interaction between torch.func.vjp and torch.compile, which might require a specific usage or configuration.
  • The error messages suggest that there might be an issue with the graph construction or the autograd functionality.
  • Further investigation and debugging are needed to determine the root cause of the issue.

Recommendation

Apply a workaround by modifying the fixpoint_solve_new function to handle the compiled mode separately, and test the modified function with a simpler example to verify the 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