Skip to content

Apply Torch-TRT decomps during dynamo.trace so compile skips a second AOT retrace. - #4596

Open
micwill755 wants to merge 6 commits into
mainfrom
one-shot-decomp-in-trace
Open

micwill755 wants to merge 6 commits into
mainfrom
one-shot-decomp-in-trace

Conversation

@micwill755

@micwill755 micwill755 commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Apply Torch-TRT's decomp table during dynamo.trace() (the path torch_tensorrt.compile(nn.Module) already uses) so AOT Autograd runs once, matching Inductor / torch.compile(backend="torch_tensorrt").
  • dynamo.compile() skips ExportedProgram.run_decompositions when the exported program stamp matches the current settings. Stock torch.export EPs, or a settings mismatch, still decompose.
  • No new user-facing API (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, inplace add_ decomposed during export, trace() stamps)
  • Flux.1-dev transformer export+decomp only: second AOT 14.4s → 0s
  • Flux2 Klein 4B NVFP4 cold compile (Victor harness): run_decompositions 2.59s → skip; compile phase 33.7s → 28.8s; steady-state unchanged

Stack created with GitHub Stacks CLI • Give Feedback 💬

@meta-cla meta-cla Bot added the cla signed label Aug 26, 2026
@github-actions github-actions Bot added component: tests Issues re: Tests component: lowering Issues re: The lowering / preprocessing passes component: core Issues re: The core compiler component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths labels Aug 26, 2026
@github-actions
github-actions Bot requested a review from zewenli98 August 26, 2026 21:45
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from a41ed2f to 20b8bcd Compare September 1, 2026 18:30
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from 20b8bcd to d48152c Compare September 2, 2026 07:06
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from d48152c to 6f91a46 Compare September 9, 2026 22:54
@micwill755
micwill755 requested review from cehongwang and narendasan and removed request for zewenli98 September 10, 2026 17:20
@cehongwang

Copy link
Copy Markdown
Collaborator

Please change MutableTorchTensorRT.py as well

@cehongwang

Copy link
Copy Markdown
Collaborator

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

@micwill755

Copy link
Copy Markdown
Collaborator Author

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

@micwill755

Copy link
Copy Markdown
Collaborator Author

Please change MutableTorchTensorRT.py as well

MutableTorchTensorRTModule now uses export_with_tensorrt_decomps on the default path so it gets the same one-shot decomp as dynamo.trace.

@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from ee681ee to fe0fb9c Compare September 16, 2026 23:22
@micwill755
micwill755 force-pushed the early-lowering-cache branch 2 times, most recently from 70b20cf to 488038d Compare September 16, 2026 23:23
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from fe0fb9c to c9aee71 Compare September 16, 2026 23:23
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from c9aee71 to cd041e7 Compare September 29, 2026 17:44
@micwill755 micwill755 added this to the v2.15.0 milestone Sep 29, 2026
use_fp32_acc,
)
if enable_autocast:
logger.info(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be a more of a warning than info

@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from 6e5e81f to 9ae4895 Compare October 6, 2026 21:34

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

@lanluo-nvidia lanluo-nvidia modified the milestones: v2.15.0, v2.16.0 Oct 8, 2026
@micwill755
micwill755 force-pushed the early-lowering-cache branch from b3608de to 37b8702 Compare October 13, 2026 18:43
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch 3 times, most recently from b8d07aa to fb39431 Compare October 13, 2026 22:09
@micwill755
micwill755 force-pushed the early-lowering-cache branch from 76e7c24 to 8820d25 Compare October 13, 2026 23:12
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from fb39431 to 7c47c8b Compare October 13, 2026 23:12
@micwill755
micwill755 force-pushed the early-lowering-cache branch 2 times, most recently from ada13a8 to 7b0b8db Compare October 13, 2026 23:41
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from 7c47c8b to e99b651 Compare October 13, 2026 23:41
…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.
@micwill755
micwill755 force-pushed the one-shot-decomp-in-trace branch from e99b651 to 8923268 Compare October 13, 2026 23:51
@micwill755
micwill755 removed this pull request from stack #4533 October 13, 2026 23:52
@micwill755
micwill755 changed the base branch from early-lowering-cache to main October 13, 2026 23:52
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Nov 5, 2026
…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.
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Nov 5, 2026
…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.
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Nov 5, 2026
…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.
@5had3z
5had3z self-requested a review November 16, 2026 21:54
5had3z and others added 2 commits November 16, 2026 14:52
# 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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed component: api [Python] Issues re: Python API component: core Issues re: The core compiler component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: lowering Issues re: The lowering / preprocessing passes component: runtime component: tests Issues re: Tests component: torch_compile

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants