Introduction to torch.compile
intermediate/torch_compile_tutorial
torch.compile
graph break
torch.compile is available in PyTorch 2.0 and later.
This introduction covers basic torch.compile usage
and demonstrates the advantages of torch.compile over
our previous PyTorch compiler solution,
TorchScript.
Required pip dependencies for this tutorial
System requirements
- A C++ compiler, such as g++
- Python development package (python-devel/python-dev)
Graph Breaks
The graph break is one of the most fundamental concepts within torch.compile.
It allows torch.compile to handle arbitrary Python code by interrupting
compilation, running the unsupported code, then resuming compilation.
The term “graph break” comes from the fact that torch.compile attempts
to capture and optimize the PyTorch operation graph. When unsupported Python code is encountered,
then this graph must be “broken”.
Graph breaks result in lost optimization opportunities, which may still be undesirable,
but this is better than silent incorrectness or a hard crash.
Let’s look at a data-dependent control flow example to better see how graph breaks work.
TRACED GRAPH
===== __compiled_fn_20_a963597d_f789_4ae8_a3cf_15dba8e0fa1c =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_a_: "f32[10][1]cpu", L_b_: "f32[10][1]cpu"):
l_a_ = L_a_
l_b_ = L_b_
The first time we run bar, we see that torch.compile traced 2 graphs
corresponding to the following code (noting that b.sum() < 0 is False):
x = a / (torch.abs(a) + 1); b.sum()
return x * b
The second time we run bar, we take the other branch of the if statement
and we get 1 traced graph corresponding to the code b = b * -1; return x * b.
We do not see a graph of x = a / (torch.abs(a) + 1); b.sum() outputted the second time
since torch.compile cached this graph from the first run and re-used it.
Let’s investigate by example how TorchDynamo would step through bar.
If b.sum() < 0, then TorchDynamo would run graph 1, let
Python determine the result of the conditional, then run
graph 2. On the other hand, if not b.sum() < 0, then TorchDynamo
would run graph 1, let Python determine the result of the conditional, then
run graph 3.
We can see all graph breaks by using torch._logging.set_logs(graph_breaks=True).
TRACED GRAPH
===== __compiled_fn_28_86798bfa_6a69_4c85_8c52_da8df0ee5d88 =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_a_: "f32[10][1]cpu", L_b_: "f32[10][1]cpu"):
l_a_ = L_a_
l_b_ = L_b_
In order to maximize speedup, graph breaks should be limited.
We can force TorchDynamo to raise an error upon the first graph
break encountered by using fullgraph=True:
Traceback (most recent call last):
File "/__w/tutorials/tutorials/pytorch/tutorials/intermediate_source/torch_compile_tutorial.py", line 360, in <module>
opt_bar_fullgraph(torch.randn(10), torch.randn(10))
File "/usr/local/lib/python3.12/dist-packages/torch/_dynamo/eval_frame.py", line 1276, in compile_wrapper
raise e.with_traceback(
torch._dynamo.exc.Unsupported: Data-dependent branching
In our example above, we can work around this graph break by replacing
the if statement with a torch.cond:
from functorch.experimental.control_flow import cond
@torch.compile(fullgraph=True)
def bar_fixed(a, b):
x = a / (torch.abs(a) +
TRACED GRAPH
===== __compiled_fn_37_474d821e_6f52_4ed4_af4d_7320f7b101cb =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_a_: "f32[10][1]cpu", L_b_: "f32[10][1]cpu"):
l_a_ = L_a_
l_b_ = L_b_
In order to serialize graphs or to run graphs on different (i.e. Python-less)
environments, consider using torch.export instead (from PyTorch 2.1+).
One important restriction is that torch.export does not support graph breaks. Please check
the torch.export tutorial
for more details on torch.export.
Check out our section on graph breaks in the torch.compile programming model
for tips on how to work around graph breaks.
foo
)
print
(
opt_foo1
(
(
3
,
3
),
(
3
,
3
)))
@torch
.
compile
def
opt_foo2
(
x
,
y
):
a
=
(
x
)
b
=
(
y
)
return
a
+
b
print
(
opt_foo2
(
(
3
,
3
),
(
3
,
3
)))
a: "f32[3, 3][3, 1]cpu" = torch.sin(l_x_); l_x_ = None
b: "f32[3, 3][3, 1]cpu" = torch.cos(l_y_); l_y_ = None
add: "f32[3, 3][3, 1]cpu" = a + b; a = b = None
return (add,)
/usr/local/lib/python3.12/dist-packages/triton/knobs.py:504: UserWarning: TRITON_DEFAULT_FP_FUSION is unset: defaulting to FP fusion ENABLED for backward compatibility in Triton 3.9. The default will change to DISABLED in Triton 3.10; set TRITON_DEFAULT_FP_FUSION=1 to keep fusion enabled or =0 to adopt the new default early and silence this warning.
warn_once(FP_FUSION_DEFAULT_WARNING)
tensor([[ 0.8198, 0.7071, 0.5760],
[ 0.1990, -0.7729, 0.2355],
[ 0.4543, 0.5683, 0.0037]])
TRACED GRAPH
===== __compiled_fn_3_1b683bb6_8d16_4cf7_834e_6214b567bac6 =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3][3, 1]cpu", L_y_: "f32[3, 3][3, 1]cpu"):
l_x_ = L_x_
l_y_ = L_y_
a: "f32[3, 3][3, 1]cpu" = torch.sin(l_x_); l_x_ = None
b: "f32[3, 3][3, 1]cpu" = torch.cos(l_y_); l_y_ = None
add: "f32[3, 3][3, 1]cpu" = a + b; a = b = None
return (add,)
tensor([[ 1.0256, 0.6622, 1.2293],
[ 1.1146, 1.7289, 1.1825],
[ 0.7528, -0.8261, -0.1917]])
torch
.
cos
(
y
)
return
a
+
b
print
(
outer
(
(
3
,
3
),
(
3
,
3
)))
a: "f32[3, 3][3, 1]cpu" = torch.sin(l_x_); l_x_ = None
b: "f32[3, 3][3, 1]cpu" = torch.cos(l_y_); l_y_ = None
add: "f32[3, 3][3, 1]cpu" = a + b; a = b = None
return (add,)
tensor([[ 1.5961, 0.9128, -0.8261],
[-0.5093, -0.0217, -0.2431],
[ 0.1975, -1.5779, 0.5385]])
__init__
()
self
.
lin
=
(
3
,
3
)
def
forward
(
self
,
x
):
return
(
self
.
lin
(
x
))
mod1
=
()
()
print
(
mod1
(
(
3
,
3
)))
mod2
=
()
mod2
=
(
mod2
)
print
(
mod2
(
(
3
,
3
)))
l_self_modules_lin_parameters_bias_ = L_self_modules_lin_parameters_bias_
l_x_ = L_x_
linear: "f32[3, 3][3, 1]cpu" = torch._C._nn.linear(l_x_, l_self_modules_lin_parameters_weight_, l_self_modules_lin_parameters_bias_); l_x_ = l_self_modules_lin_parameters_weight_ = l_self_modules_lin_parameters_bias_ = None
relu: "f32[3, 3][3, 1]cpu" = torch.nn.functional.relu(linear); linear = None
return (relu,)
tensor([[0.3617, 0.2013, 0.3791],
[0.9668, 0.5713, 0.0000],
[0.1447, 0.0000, 0.0000]], grad_fn=<CompiledFunctionBackward>)
tensor([[0.0000, 0.0000, 0.0000],
[0.5763, 0.7793, 0.0000],
[1.0176, 0.2081, 0.0000]], grad_fn=<CompiledFunctionBackward>)
=
None
z: "f32[4096, 4096][4096, 1]cuda:0" = torch.nn.functional.relu(y); y = None
u: "f32[4096, 4096][4096, 1]cuda:0" = z * 2; z = None
return (u,)
compile: 0.4534583435058594
eager: 0.042147838592529296
foo3
(
))
eager_times
.
append
(
eager_time
)
print
(
f
"eager time
{
i
}
:
{
eager_time
}
"
)
print
(
"~"
*
10
)
compile_times
=
[]
for
i
in
range
(
10
):
,
compile_time
=
timed
(
lambda
:
opt_foo3
(
))
compile_times
.
append
(
compile_time
)
print
(
f
"compile time
{
i
}
:
{
compile_time
}
"
)
print
(
"~"
*
10
)
import
numpy
as
np
eager_med
=
np
.
median
(
eager_times
)
compile_med
=
np
.
median
(
compile_times
)
speedup
=
eager_med
/
compile_med
assert
speedup
>
1
print
(
f
"(eval) eager median:
{
eager_med
}
, compile median:
{
compile_med
}
, speedup:
{
speedup
}
x"
)
print
(
"~"
*
10
)
.
We
Python
,
as
in
.
This
not
!
if x.sum() < 0:
traced 1, 1: True
traced 1, 2: False
compile 1, 1: True
compile 1, 2: True
~~~~~~~~~~
torch
.
randn
(
5
,
5
)
=
3
script_f2
=
torch
.
jit
.
script
(
f2
)
try
:
script_f2
(
,
)
except
:
tb
.
print_exc
()
compile_f2
=
(
f2
)
print
(
"compile 2:"
,
test_fns
(
f2
,
compile_f2
,
(
,
)))
print
(
"~"
*
10
)
,
)
RuntimeError: f2() Expected a value of type 'Tensor (inferred)' for argument 'y' but instead found type 'int'.
Inferred 'y' to be of type 'Tensor' because it was not annotated with an explicit type.
Position: 1
Value: 3
Declaration: f2(Tensor x, Tensor y) -> Tensor
Cast error details: Unable to cast 3 to Tensor
TRACED GRAPH
===== __compiled_fn_18_d63ce27a_5501_4d9f_ac92_282002e603aa =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_x_: "f32[5, 5][5, 1]cpu"):
l_x_ = L_x_
add: "f32[5, 5][5, 1]cpu" = l_x_ + 3; l_x_ = None
return (add,)
compile 2: True
~~~~~~~~~~
abs_1: "f32[10][1]cpu" = torch.abs(l_a_)
add: "f32[10][1]cpu" = abs_1 + 1; abs_1 = None
x: "f32[10][1]cpu" = l_a_ / add; l_a_ = add = None
sum_1: "f32[][]cpu" = l_b_.sum(); l_b_ = None
lt: "b8[][]cpu" = sum_1 < 0; sum_1 = None
return (lt, x)
TRACED GRAPH
===== __compiled_fn_24_33756430_4cc1_43a7_b5b1_e49e3b8c3657 =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_x_: "f32[10][1]cpu", L_b_: "f32[10][1]cpu"):
l_x_ = L_x_
l_b_ = L_b_
mul: "f32[10][1]cpu" = l_x_ * l_b_; l_x_ = l_b_ = None
return (mul,)
TRACED GRAPH
===== __compiled_fn_26_2ddd2da3_618d_443e_9732_08ce14b8c069 =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_b_: "f32[10][1]cpu", L_x_: "f32[10][1]cpu"):
l_b_ = L_b_
l_x_ = L_x_
b: "f32[10][1]cpu" = l_b_ * -1; l_b_ = None
mul_1: "f32[10][1]cpu" = l_x_ * b; l_x_ = b = None
return (mul_1,)
tensor([0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000,
0.5000])
abs_1: "f32[10][1]cpu" = torch.abs(l_a_)
add: "f32[10][1]cpu" = abs_1 + 1; abs_1 = None
x: "f32[10][1]cpu" = l_a_ / add; l_a_ = add = None
sum_1: "f32[][]cpu" = l_b_.sum(); l_b_ = None
lt: "b8[][]cpu" = sum_1 < 0; sum_1 = None
return (lt, x)
TRACED GRAPH
===== __compiled_fn_32_bd8e4af2_04c8_4308_8c29_642572ea87d3 =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_x_: "f32[10][1]cpu", L_b_: "f32[10][1]cpu"):
l_x_ = L_x_
l_b_ = L_b_
mul: "f32[10][1]cpu" = l_x_ * l_b_; l_x_ = l_b_ = None
return (mul,)
TRACED GRAPH
===== __compiled_fn_34_4aec2aea_25fd_4a58_b666_b46ef24067bd =====
/usr/local/lib/python3.12/dist-packages/torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_b_: "f32[10][1]cpu", L_x_: "f32[10][1]cpu"):
l_b_ = L_b_
l_x_ = L_x_
b: "f32[10][1]cpu" = l_b_ * -1; l_b_ = None
mul_1: "f32[10][1]cpu" = l_x_ * b; l_x_ = b = None
return (mul_1,)
tensor([0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000,
0.5000])
torch
.
randn
(
10
))
except
:
tb
.
print_exc
()
Explanation: Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.
The branch condition involves a tensor computed as follows:
lt = lt(sum_1, 0)
Hint: For the common pattern `if tensor_cond: x = transform(x)` (e.g. clamping inf/nan values), consider making the code branchless by always applying the transform. Operations like torch.clamp, torch.nan_to_num, and torch.where are typically no-ops on well-behaved inputs and compile without graph breaks.
Hint: This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround.
Hint: Use `torch.cond` to express dynamic control flow.
Developer debug context: attempted to jump with TensorVariable()
For more details about this graph break, please visit: https://meta-pytorch.github.io/compile-graph-break-site/gb/gb0170.html
from user code:
File "/__w/tutorials/tutorials/pytorch/tutorials/intermediate_source/torch_compile_tutorial.py", line 313, in bar
if b.sum() < 0:
^^^^^^^^^^^
Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"
1
)
def
true_branch
(
y
):
return
y
*
-
1
def
false_branch
(
y
):
return
y
.
clone
()
b
=
cond
(
b
.
sum
()
<
0
,
true_branch
,
false_branch
,
(
b
,))
return
x
*
b
bar_fixed
(
,
)
bar_fixed
(
,
-
)
abs_1: "f32[10][1]cpu" = torch.abs(l_a_)
add: "f32[10][1]cpu" = abs_1 + 1; abs_1 = None
x: "f32[10][1]cpu" = l_a_ / add; l_a_ = add = None
sum_1: "f32[][]cpu" = l_b_.sum()
lt: "b8[][]cpu" = sum_1 < 0; sum_1 = None
cond_true_0 = self.cond_true_0
cond_false_0 = self.cond_false_0
cond = torch.ops.higher_order.cond(lt, cond_true_0, cond_false_0, (l_b_,)); lt = cond_true_0 = cond_false_0 = l_b_ = None
b: "f32[10][1]cpu" = cond[0]; cond = None
mul: "f32[10][1]cpu" = x * b; x = b = None
return (mul,)
class cond_true_0(torch.nn.Module):
def forward(self, l_b_: "f32[10][1]cpu"):
l_b__1 = l_b_
mul: "f32[10][1]cpu" = l_b__1 * -1; l_b__1 = None
return (mul,)
class cond_false_0(torch.nn.Module):
def forward(self, l_b_: "f32[10][1]cpu"):
l_b__1 = l_b_
clone: "f32[10][1]cpu" = l_b__1.clone(); l_b__1 = None
return (clone,)
tensor([0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000,
0.5000])