Repository navigation
Apply Torch-TRT decomps during dynamo.trace so compile skips a second AOT retrace. - #4596
micwill755 wants to merge 6 commits into
Conversation
ea5e700 to
8da3124
Compare
a41ed2f to
20b8bcd
Compare
8da3124 to
a6ec762
Compare
20b8bcd to
d48152c
Compare
d48152c to
6f91a46
Compare
|
Please change MutableTorchTensorRT.py as well |
|
This skips decomposition of nodes added in pre_export_lowering and thus caused errors in tests: /home/verify-et-runtime/TensorRT-2.14/tests/py/dynamo/models/test_autocast.py |
when enable_autocast=True we no longer skip run_decompositions, so the casts inserted in pre_export_lowering still get decomposed |
MutableTorchTensorRTModule now uses export_with_tensorrt_decomps on the default path so it gets the same one-shot decomp as dynamo.trace. |
ee681ee to
fe0fb9c
Compare
70b20cf to
488038d
Compare
fe0fb9c to
c9aee71
Compare
c9aee71 to
cd041e7
Compare
488038d to
666c1b1
Compare
| use_fp32_acc, | ||
| ) | ||
| if enable_autocast: | ||
| logger.info( |
There was a problem hiding this comment.
This should be a more of a warning than info
6e5e81f to
9ae4895
Compare
There was a problem hiding this comment.
There are some changes that do not conform to Python style guidelines:
--- /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/impl/moe.py 2026-10-06 21:34:57.449454+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/impl/moe.py 2026-10-06 21:35:24.339350+00:00
@@ -94,11 +94,13 @@
ctx, offs, torch.int32, f"{name}_offs_i32", target, source_ir
)
offs_row = impl.shuffle.reshape(
ctx, target, source_ir, f"{name}_offs_row", offs_i32, (1, -1)
)
- passed = impl.elementwise.le(ctx, target, source_ir, f"{name}_passed", offs_row, rows)
+ passed = impl.elementwise.le(
+ ctx, target, source_ir, f"{name}_passed", offs_row, rows
+ )
group = impl.reduce.sum(
ctx,
target,
source_ir,
f"{name}_group",
--- /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py 2026-10-06 21:34:57.447603+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py 2026-10-06 21:35:27.307516+00:00
@@ -4640,13 +4640,11 @@
if key in kwargs and kwargs[key] is not None:
return kwargs[key]
return args_bounds_check(args, index, default)
-def histc_validator(
- node: Node, settings: Optional[CompilationSettings] = None
-) -> bool:
+def histc_validator(node: Node, settings: Optional[CompilationSettings] = None) -> bool:
bins = _arg_or_kwarg(node.args, node.kwargs, 1, "bins", 100)
lo = _arg_or_kwarg(node.args, node.kwargs, 2, "min", 0)
hi = _arg_or_kwarg(node.args, node.kwargs, 3, "max", 0)
if not all(
isinstance(v, (int, float)) and not isinstance(v, bool) for v in (bins, lo, hi)b3608de to
37b8702
Compare
b8d07aa to
fb39431
Compare
76e7c24 to
8820d25
Compare
fb39431 to
7c47c8b
Compare
ada13a8 to
7b0b8db
Compare
7c47c8b to
e99b651
Compare
…ort. Autocast inserts cast nodes in pre_export_lowering, so a one-shot decomp stamp from trace would leave those ops undecomposed. Keep the skip on the default path; run a single run_decompositions after lowering when enable_autocast is set. Apply Torch-TRT decomps during Mutable module export.
e99b651 to
8923268
Compare
…uessing it After the rule-based autocast pass casts the inputs of a node, it assumes the node now returns the new dtype and writes `meta["val"].to(dtype)`. That guess is wrong in several common cases: - Ops with several outputs, such as max_pool2d with indices or split. Their meta is a tuple or a list, so the pass crashes: `AttributeError: 'tuple' object has no attribute 'to'`. - Ops whose output dtype is fixed by an argument, such as `to(dtype)` or `cumsum(dtype=...)`. The meta says float16 but the op still returns float32. The next node then skips the cast it needs, and decomposition fails with `Input type (float) and bias type (c10::Half) should be the same`. - Ops with integer or bool outputs, such as argmax or a comparison. The meta wrongly turns them into floats. - Graphs with dynamic shapes, where sym_size nodes return a SymInt: `AttributeError: 'SymInt' object has no attribute 'to'`. This change runs each retyped node on the fake values of its new inputs, in the graph's fake mode, and takes the output dtypes from that run. The traced shapes are kept, so data-dependent sizes, such as the output of nonzero or a boolean mask, keep their symbols. Outputs are matched by position, because a program loaded with torch.export.load keeps the outputs of ops such as split and chunk in a tuple, while the op itself returns a list. The getitem users of a node with several outputs are updated too. PR pytorch#4596 by Michael Williams handles the tuple and SymInt cases by casting every tensor inside the meta. That stops the crash, but still marks fixed-dtype and integer outputs as float16. Both changes edit the same lines. Added tests with max_pool2d (with indices) and split, with a conv fed by `cumsum(dtype=torch.float32)`, with an argmax feeding an embedding kept in float32, with a dynamic batch, and with chunk and unbind in a program saved and loaded with torch.export. Each fails without the change and passes with it. The dynamic batch test also takes a boolean mask, whose data-dependent size must keep working.
…uessing it
After the rule-based autocast pass casts the inputs of a node, it assumes
the node now returns the new dtype and writes `meta["val"].to(dtype)`.
That guess is wrong in several common cases:
- Ops with several outputs, such as max_pool2d with indices or split.
Their meta is a tuple or a list, so the pass crashes:
`AttributeError: 'tuple' object has no attribute 'to'`.
- Ops whose output dtype is fixed by an argument, such as `to(dtype)` or
`cumsum(dtype=...)`. The meta says float16 but the op still returns
float32. The next node then skips the cast it needs, and decomposition
fails with `Input type (float) and bias type (c10::Half) should be the
same`.
- Ops with integer or bool outputs, such as argmax or a comparison. The
meta wrongly turns them into floats.
- Graphs with dynamic shapes, where sym_size nodes return a SymInt:
`AttributeError: 'SymInt' object has no attribute 'to'`.
This change runs each retyped node on the fake values of its new inputs,
in the graph's fake mode, and takes the output dtypes from that run. The
traced shapes are kept, so data-dependent sizes, such as the output of
nonzero or a boolean mask, keep their symbols. Outputs are matched by
position, because a program loaded with torch.export.load keeps the
outputs of ops such as split and chunk in a tuple, while the op itself
returns a list. The getitem users of a node with several outputs are
updated too.
Getting the output dtypes right has one side effect. A model can cast to
float32 on purpose, as RMSNorm does before it squares its input:
h = h.to(torch.float32)
h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + eps)
With the old guess, the nodes after such a cast saw a float16 meta, got
no cast, and ran in float32 by accident. With the true dtype, the pass
would cast them back to float16, and pow overflows for values above 256,
so the norm returns zeros with no error. So the pass now keeps the nodes
after an explicit float32 cast of a floating-point tensor in float32,
until a cast to another dtype. That is how they run without autocast,
and how they ran before at run time. Where that path used to reach a
layer with weights and fail to build, such as a Linear after the norm,
the layer now runs in float32 too. In a float32 model, x.to(x.dtype) is
also such a cast, so this can keep most of a model in float32. A warning
says how many nodes stay in float32, and the next commit adds a setting
to turn this off.
Running an op on fake values can also switch grad mode or vmap on and
off, for example for a torch.no_grad() block or a torch.vmap call in the
model. If the pass fails part way, it now switches them back, so the rest
of the process keeps the state it had.
PR pytorch#4596 by Michael Williams handles the tuple and SymInt cases by
casting every tensor inside the meta. That stops the crash, but still
marks fixed-dtype and integer outputs as float16. Both changes edit the
same lines.
Added tests with max_pool2d (with indices) and split, with a conv fed by
`cumsum(dtype=torch.float32)`, with an argmax feeding an embedding kept in
float32, with a dynamic batch, and with chunk and unbind in a program
saved and loaded with torch.export. Each fails without the change and
passes with it. The dynamic batch test also takes a boolean mask, whose
data-dependent size must keep working. The argmax test uses inputs with a
clear winner, so float16 rounding cannot change which row it picks.
Also added a test with RMSNorm on values of about 400, followed by a
Linear, which fails without the float32 rule, and a test that a failed
compile of a torch.no_grad() or torch.vmap region leaves grad mode on and
vmap off, which fails without the state restore.
…uessing it
After the rule-based autocast pass casts the inputs of a node, it assumes
the node now returns the new dtype and writes `meta["val"].to(dtype)`.
That guess is wrong in several common cases:
- Ops with several outputs, such as max_pool2d with indices or split.
Their meta is a tuple or a list, so the pass crashes:
`AttributeError: 'tuple' object has no attribute 'to'`.
- Ops whose output dtype is fixed by an argument, such as `to(dtype)` or
`cumsum(dtype=...)`. The meta says float16 but the op still returns
float32. The next node then skips the cast it needs, and decomposition
fails with `Input type (float) and bias type (c10::Half) should be the
same`.
- Ops with integer or bool outputs, such as argmax or a comparison. The
meta wrongly turns them into floats.
- Graphs with dynamic shapes, where sym_size nodes return a SymInt:
`AttributeError: 'SymInt' object has no attribute 'to'`.
This change runs each retyped node on the fake values of its new inputs,
in the graph's fake mode, and takes the output dtypes from that run. The
traced shapes are kept, so data-dependent sizes, such as the output of
nonzero or a boolean mask, keep their symbols. Outputs are matched by
position, because a program loaded with torch.export.load keeps the
outputs of ops such as split and chunk in a tuple, while the op itself
returns a list. The getitem users of a node with several outputs are
updated too.
Getting the output dtypes right has one side effect. A model can cast to
float32 on purpose, as RMSNorm does before it squares its input:
h = h.to(torch.float32)
h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + eps)
With the old guess, the nodes after such a cast saw a float16 meta, got
no cast, and ran in float32 by accident. With the true dtype, the pass
would cast them back to float16, and pow overflows for values above 256,
so the norm returns zeros with no error. So the pass now keeps the nodes
after an explicit float32 cast of a floating-point tensor in float32,
until a cast to another dtype. That is how they run without autocast,
and how they ran before at run time. Where that path used to reach a
layer with weights and fail to build, such as a Linear after the norm,
the layer now runs in float32 too. In a float32 model, x.to(x.dtype) is
also such a cast, so this can keep most of a model in float32. A warning
says how many nodes stay in float32, and the next commit adds a setting
to turn this off.
Running an op on fake values can also switch grad mode or vmap on and
off, for example for a torch.no_grad() block or a torch.vmap call in the
model. If the pass fails part way, it now switches them back, so the rest
of the process keeps the state it had.
PR pytorch#4596 by Michael Williams handles the tuple and SymInt cases by
casting every tensor inside the meta. That stops the crash, but still
marks fixed-dtype and integer outputs as float16. Both changes edit the
same lines.
Added tests with max_pool2d (with indices) and split, with a conv fed by
`cumsum(dtype=torch.float32)`, with an argmax feeding an embedding kept in
float32, with a dynamic batch, and with chunk and unbind in a program
saved and loaded with torch.export. Each fails without the change and
passes with it. The dynamic batch test also takes a boolean mask, whose
data-dependent size must keep working. The argmax test uses inputs with a
clear winner, so float16 rounding cannot change which row it picks.
Also added a test with RMSNorm on values of about 400, followed by a
Linear, which fails without the float32 rule, and a test that a failed
compile of a torch.no_grad() or torch.vmap region leaves grad mode on and
vmap off, which fails without the state restore.
# Conflicts: # py/torch_tensorrt/dynamo/lowering/passes/rule_based_autocast.py
filter_decomposition_table (from main) keeps scatter_add intact when its index extent is symbolic, since the decomposition loops over that extent. One-shot export in dynamo.trace runs before the graph exists, so it applied the unfiltered table and dynamic scatter_add failed to export with a constraint violation. Export now leaves SHAPE_DEPENDENT_DECOMPOSITIONS out of the table and records them in the stamp. maybe_run_decompositions applies the filter again and runs run_decompositions only when the graph still has a deferred op that the filter would decompose. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ions. (#5066) Signed-off-by: Bryce Ferenczi <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
dynamo.trace()(the pathtorch_tensorrt.compile(nn.Module)already uses) so AOT Autograd runs once, matching Inductor /torch.compile(backend="torch_tensorrt").dynamo.compile()skipsExportedProgram.run_decompositionswhen the exported program stamp matches the current settings. Stocktorch.exportEPs, or a settings mismatch, still decompose.export_for_tensorrt,export_and_compile,skip_decompositions).PR 5 of the compile-startup stack; based on #4540.
Test plan
tests/py/dynamo/models/test_one_shot_decomp.py(stamp match, skip when stamped, stock export still decomps, settings mismatch re-decomps, inplaceadd_decomposed during export,trace()stamps)run_decompositions2.59s → skip; compile phase 33.7s → 28.8s; steady-state unchangedStack created with GitHub Stacks CLI • Give Feedback 💬