RuntimeError: Argument 'primals_out' of Node 'results' was used before it has been defined! Please check that Nodes in the graph are topologically ordered
- Dominant language
- Python
- Stars
- 103k
- Forks
- 29.5k
- PR merge metrics
- PR metrics pending
Description
### 🐛 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:
```python
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
Full MWE with eager / compile
```python
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)
```
### Error logs
compiling forward only
```
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,)
```
compiling backward
```
torch._dynamo.exc.InternalTorchDynamoError: RuntimeError: Tried to erase Node primals_out but it still had 1 users in the graph: {results: None}!
```
compile forward/backward + config.compiled_autograd
```
NotImplementedError: Cannot access storage of TensorWrapper
```
### 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 @Chillee @samdow @kshitij12345
Contributor guide
Assessment
This issue has not been assessed yet.