Repository navigation
Description
Bug description
Compiling a module that contains a tensor-parallel nn.Linear (ColwiseParallel or
RowwiseParallel from torch.distributed.tensor.parallel) with dynamic=True fails on the first
forward call. Inductor raises BackendCompilerFailed: RecursionError: maximum recursion depth exceeded. The same module compiles and runs with dynamic=False. backend='aot_eager' fails the
same way, so the failure is in AOTAutograd, not Inductor. A forward-only compile (no_grad) works,
so it needs the backward to be traced. Automatic dynamic (dynamic=None) hits it as soon as a
dimension changes and the graph is recompiled with a symbolic size. It needs a 3D input (the
linear's view -> mm -> _unsafe_view decomposition) and a non-scalar graph output: a 2D
(num_tokens, dim) input, or a graph that returns a scalar, compiles fine (see "What triggers it").
The failure happens while AOTAutograd traces the joint forward / backward graph (make_fx ->
torch.autograd.grad -> DTensor dispatch). A SymInt proxy thunk is forced, and forcing it recurses
through _compute_proxy -> get_proxy_slot(...).force() -> _compute_proxy without end.
Raising sys.setrecursionlimit to 100000 does not help (tested on a module with a colwise and a
rowwise linear), so the proxies appear to form a cycle rather than a long chain.
Repro
2 GPUs, plain torch only. The second case (ColwiseParallel, dynamic=True, inductor) is the
minimal failing one; the others show the scope.
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 02:53:23 2026
@author: Shahir
torch.compile with dynamic shapes on a ColwiseParallel / RowwiseParallel nn.Linear fails with
RecursionError in AOTAutograd's joint graph trace. dynamic=False and forward-only compiles work.
torchrun --nproc_per_node=2 dtensor_compile_dynamic_repro.py
"""
import os
import traceback
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel, parallelize_module
DIM = 256
def run(
mesh: DeviceMesh,
device: torch.device,
style: str,
dynamic: bool | None,
backend: str,
backward: bool
) -> str:
torch.compiler.reset()
linear = nn.Linear(DIM, DIM, bias=False, device=device)
parallelize_module(linear, mesh, ColwiseParallel() if style == 'colwise' else RowwiseParallel())
compiled = torch.compile(linear, backend=backend, dynamic=dynamic) # type: ignore
# RowwiseParallel takes the local shard of the input features
input_dim = DIM // mesh.size() if style == 'rowwise' else DIM
try:
# Two sequence lengths, so dynamic=None also ends up compiling a dynamic graph
for seq_len in (64, 96):
x = torch.randn(2, seq_len, input_dim, device=device, requires_grad=backward)
if backward:
compiled(x).sum().backward()
else:
with torch.no_grad():
compiled(x)
return "ok"
except Exception as error:
last_line = traceback.format_exception_only(type(error), error)[-1].strip()
return f"FAILED ({type(error).__name__}): {last_line[-200:]}"
def main() -> None:
device = torch.device('cuda', int(os.environ['LOCAL_RANK']))
torch.cuda.set_device(device)
dist.init_process_group(backend='nccl')
mesh = init_device_mesh('cuda', (dist.get_world_size(),))
# (style, dynamic, backend, backward)
cases: list[tuple[str, bool | None, str, bool]] = [
('colwise', False, 'inductor', True),
('colwise', True, 'inductor', True), # minimal failing case
('rowwise', True, 'inductor', True),
('colwise', True, 'aot_eager', True),
('colwise', True, 'inductor', False),
('colwise', None, 'inductor', True)
]
for style, dynamic, backend, backward in cases:
outcome = run(mesh, device, style, dynamic, backend, backward)
if dist.get_rank() == 0:
mode = "forward + backward" if backward else "forward only (no_grad)"
print(f"{style:8s} dynamic={str(dynamic):5s} backend={backend:9s} {mode:22s} {outcome}", flush=True)
dist.destroy_process_group()
if __name__ == '__main__':
main()torchrun --nproc_per_node=2 dtensor_compile_dynamic_repro.pyOutput (rank 0):
| style | dynamic | backend | mode | result |
|---|---|---|---|---|
| ColwiseParallel | False | inductor | forward + backward | ok |
| ColwiseParallel | True | inductor | forward + backward | RecursionError |
| RowwiseParallel | True | inductor | forward + backward | RecursionError |
| ColwiseParallel | True | aot_eager | forward + backward | RecursionError |
| ColwiseParallel | True | inductor | forward only (no_grad) |
ok |
| ColwiseParallel | None (automatic dynamic, two sequence lengths) | inductor | forward + backward | RecursionError |
What triggers it
Same setup (ColwiseParallel, dynamic=True unless noted, forward + backward, two sequence
lengths), with the linear inside a module whose forward returns different things; the caller
always runs compiled(x).sum().backward():
class Block(nn.Module):
def __init__(self, output: str) -> None:
super().__init__()
self.output = output
self.linear = nn.Linear(256, 256, bias=False) # parallelize_module(..., ColwiseParallel())
def forward(self, x: torch.Tensor) -> torch.Tensor: # x: (2, seq_len, 256)
if self.output == 'flattened_input':
return self.linear(x.view(-1, 256))
y = self.linear(x)
if self.output == 'scalar':
return y.sum()
if self.output == 'linear_output':
return y
if self.output == 'clone':
return y.clone()
if self.output == 'multiplied':
return y * 2
if self.output == 'graph_break':
torch._dynamo.graph_break()
return y * 2
raise ValueError(self.output)forward returns |
dynamic | result |
|---|---|---|
y.sum() (scalar) |
True | ok |
y |
True | BackendCompilerFailed |
y.clone() |
True | BackendCompilerFailed |
y * 2 |
True | BackendCompilerFailed |
y * 2 after torch._dynamo.graph_break() |
True | BackendCompilerFailed |
self.linear(x.view(-1, 256)) (2D input) |
True | ok |
y |
None (automatic dynamic) | BackendCompilerFailed |
So it is not about the output aliasing the DTensor's local tensor (clone and y * 2 fail too):
it needs the linear's input to be 3D and a backward that starts from a tangent with the symbolic
output shape. Flattening the tokens to 2D before a TP linear avoids it.
Error
torch._dynamo.exc.BackendCompilerFailed: backend='inductor' raised:
RecursionError: maximum recursion depth exceeded
Abbreviated stack, from the outermost frame:
torch/_functorch/_aot_autograd/graph_capture.py, line 130, in _create_graph
torch/fx/experimental/proxy_tensor.py, line 3060, in wrapped
...
torch/_functorch/_aot_autograd/graph_capture_wrappers.py, line 453, in inner_fn
backward_out = torch.autograd.grad(
torch/autograd/graph.py, line 979, in _engine_run_backward
torch/distributed/tensor/_dispatch.py, line 440, in _dispatch_get_local_results_slow_path
local_results = op_call(
torch/_subclasses/functional_tensor.py, line 625, in __torch_dispatch__
torch/fx/experimental/proxy_tensor.py, line 2007, in __torch_dispatch__
torch/fx/experimental/proxy_tensor.py, line 1211, in proxy_call
torch/fx/experimental/proxy_tensor.py, line 1146, in _fetch_proxies_and_all_constant_flag
torch/fx/experimental/proxy_tensor.py, line 1041, in inner
return get_proxy_slot(e, tracer).force()
torch/utils/_thunk.py, line 27, in force
torch/fx/experimental/proxy_tensor.py, line 2103, in _compute_proxy
torch/fx/experimental/proxy_tensor.py, line 2105, in <genexpr>
torch/utils/_thunk.py, line 27, in force
torch/fx/experimental/proxy_tensor.py, line 2103, in _compute_proxy
torch/fx/experimental/proxy_tensor.py, line 2105, in <genexpr>
... (the last three frames repeat until the recursion limit)
torch/_library/opaque_object.py, line 318, in is_opaque_type
Anomaly mode, enabled by AOTAutograd during the joint trace, points at the linear's
UnsafeViewBackward0 (the 3D input linear's mm + _unsafe_view).
Possible cause (unverified)
set_proxy_slot keeps the first proxy registered for a SymInt ("Never clobber pre-existing proxy").
The comment next to it notes that a tensor subclass's outer sizes are not passed to make_fx and are
untracked until AOTAutograd's unflatten. A 2D input works, so the cycle seems to involve the
flattened size the 3D linear creates (batch * seq for the mm, then _unsafe_view back to
(batch, seq, out)), with the tangent's symbolic sizes. If one SymInt's slot is first set from a
thunk computed from another, and the other's slot is then set from the first, the two thunks
reference each other and force() never terminates.
Expected behavior
dynamic=True compiles like dynamic=False, or it fails with an explicit unsupported error.
Versions
- torch 2.13.0, CUDA 12.9
- triton 3.7.1
- Python 3.13.16
Activity
[-]# [DTensor][compile] Dynamic shapes + backward on a `ColwiseParallel` / `RowwiseParallel` `nn.Linear` fail with `RecursionError` in the AOTAutograd joint graph trace[/-][+][DTensor][compile] Dynamic shapes + backward on a `ColwiseParallel` / `RowwiseParallel` `nn.Linear` fail with `RecursionError` in the AOTAutograd joint graph trace[/+]Fix make_fx rebuild of untracked SymInts from DTensor sharding prop
Fix make_fx rebuild of untracked SymInts from DTensor sharding prop (p…
Fix make_fx rebuild of untracked SymInts from DTensor sharding prop (p…
Fix make_fx rebuild of untracked SymInts from DTensor sharding prop (p…