Skip to content

Cache post-lowering ATen graphs to skip decomp on warm compiles. - #4540

Open
micwill755 wants to merge 4 commits into
mainfrom
early-lowering-cache
Open

micwill755 wants to merge 4 commits into
mainfrom
early-lowering-cache

Conversation

@micwill755

@micwill755 micwill755 commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add a disk cache for the post-lowering ATen GraphModule, keyed from the exported program before decomposition.
  • On a hit, skip run_decompositions and post_lowering and rebuild the FX graph from a node list + state_dict (torch.save), not torch.export.save or FX __reduce__ retrace.
  • Conservative: full compilation + fast partition only; bypass if the graph cannot be encoded.

Test plan

  • tests/py/dynamo/models/test_lowering_cache.py
  • Flux2 Klein 4B NVFP4 warm compile + inference (engine cache hits after the engine is built from the reconstructed graph)

@meta-cla meta-cla Bot added the cla signed label Aug 20, 2026
@github-actions github-actions Bot added component: tests Issues re: Tests 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 20, 2026
@github-actions
github-actions Bot requested a review from zewenli98 August 20, 2026 22:40
@lanluo-nvidia lanluo-nvidia modified the milestones: v2.14.0, v2.15.0 Aug 20, 2026

@narendasan narendasan left a comment

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.

Here can we use the same caching interface as engine caching? In theory users could provide their own implementation for things like remote cache or mem cache. We should use the same cache object for both engine and graph cache if possible

@micwill755
micwill755 force-pushed the batch-defer-fx-cleanup branch from b287f3a to af86293 Compare September 1, 2026 18:29
@micwill755
micwill755 force-pushed the early-lowering-cache branch 2 times, most recently from 8da3124 to a6ec762 Compare September 2, 2026 07:06
@micwill755

Copy link
Copy Markdown
Collaborator Author

Here can we use the same caching interface as engine caching? In theory users could provide their own implementation for things like remote cache or mem cache. We should use the same cache object for both engine and graph cache if possible

Done, lowered graphs now use BaseEngineCache.save/load as bytes, and custom_engine_cache is reused for both engines and graphs. Let me know if you want any further changes.

@micwill755
micwill755 force-pushed the batch-defer-fx-cleanup branch from 579e79f to 64a6f93 Compare September 16, 2026 23:22
@micwill755
micwill755 force-pushed the batch-defer-fx-cleanup branch from 64a6f93 to 7e0b391 Compare September 16, 2026 23:23
@micwill755
micwill755 marked this pull request as ready for review September 29, 2026 17:20
@micwill755
micwill755 force-pushed the batch-defer-fx-cleanup branch from 7e0b391 to d9e1735 Compare September 29, 2026 17:44
@cehongwang

Copy link
Copy Markdown
Collaborator

@zewenli98 Can you review this?

@micwill755
micwill755 force-pushed the batch-defer-fx-cleanup branch from d9e1735 to 622fcd6 Compare October 6, 2026 19:18
@micwill755
micwill755 force-pushed the early-lowering-cache branch from 666c1b1 to d2be6d3 Compare October 6, 2026 19:18
@micwill755 micwill755 closed this Oct 6, 2026
@micwill755 micwill755 reopened this Oct 6, 2026
@micwill755
micwill755 force-pushed the early-lowering-cache branch from e9ada9a to 149d075 Compare October 6, 2026 20:18
@micwill755
micwill755 force-pushed the batch-defer-fx-cleanup branch 2 times, most recently from a2c9200 to 9c130ab Compare October 6, 2026 21:34
@micwill755
micwill755 force-pushed the early-lowering-cache branch from 149d075 to b3608de 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:49.970188+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/impl/moe.py	2026-10-06 21:35:19.290872+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:49.968083+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py	2026-10-06 21:35:23.569487+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 batch-defer-fx-cleanup branch from 9c130ab to 148fd1e Compare October 13, 2026 18:40
@micwill755
micwill755 force-pushed the early-lowering-cache branch from b3608de to 37b8702 Compare October 13, 2026 18:43
Comment on lines +498 to +500
cache_lowered_graphs: bool = _defaults.CACHE_LOWERED_GRAPHS,
reuse_cached_lowered_graphs: bool = _defaults.REUSE_CACHED_LOWERED_GRAPHS,
lowering_cache_dir: str = _defaults.LOWERING_CACHE_DIR,

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.

Do we need to add the same args in cross_compile_for_windows?


logger = logging.getLogger(__name__)

_CACHE_FORMAT_VERSION = 5

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.

Why does it start from 5?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Updated and set to 1, let me know if you want further changes here.

Comment on lines +40 to +48
_NON_SEMANTIC_SETTINGS = {
"cache_built_engines",
"reuse_cached_engines",
"cache_lowered_graphs",
"reuse_cached_lowered_graphs",
"dryrun",
"lazy_engine_init",
"timing_cache_path",
}

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.

Is it same as

_SETTINGS_TO_BE_ENGINE_INVARIANT = {
"max_aux_streams",
"version_compatible",
"optimization_level",
"disable_tf32",
"sparse_weights",
"engine_capability",
"hardware_compatible",
"target_compute_capabilities",
"refit_identical_engine_weights",
"immutable_weights",
"enable_weight_streaming",
"tiling_optimization_level",
"l2_limit_for_tiling",
"enable_autocast",
"autocast_low_precision_type",
"autocast_excluded_nodes",
"autocast_excluded_ops",
"autocast_max_output_threshold",
"autocast_max_depth_of_reduction",
"autocast_calibration_dataloader",
"decompose_attention",
"disabled_constant_fold_exclusions",
"attn_bias_is_causal",
"build_route",
}
?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No. The engine cache list covers settings that change the TensorRT engine. This cache stores the graph before the engine is built, so it must also include settings that change decomposition and lowering. Only settings that cannot change that graph are excluded.

Comment on lines +462 to +463
def _canonical_graph(gm: torch.fx.GraphModule) -> Tuple[str, ...]:
return tuple(node.format_node() for node in gm.graph.nodes)

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.

Can this method promise isomorphism? In engine caching, I did something like

def canonicalize_graph(graph: torch.fx.Graph) -> str:
"""Canonicalize the graph to a string for isomorphic graph comparison
Args:
graph (torch.fx.Graph): graph to canonicalize
Returns:
str: canonicalized graph string
"""
canonical_nodes = []
input_counter = 0
for node in graph.nodes:
if node.op == "placeholder":
canonical_nodes.append(f"placeholder_input_{input_counter}")
input_counter += 1
else:
canonical_nodes.append(f"{node.op}_{node.target}")
return " ".join(canonical_nodes)

The idea here is that if two graphs are isomorphic (with the same structure but different names), they should reuse the same cache.

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.

Also, do you think if we can put the common util methods into utils.py instead of repeat?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, the old key included the node names a renamed export would miss. Each node is now numbered in order, and each operation records the numbers it reads, so add_1(x, y) and add_7(input, bias) produce the same key. An add of a different pair does not. The engine-cache helper only numbers the inputs and drops those connections, so I kept this key separate.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Also, do you think if we can put the common util methods into utils.py instead of repeat?

Good idea, moved canonicalize_setting_value into dynamo/utils.py, updated both the engine cache and lowering cache to use it, and existing tests import the shared function.

@micwill755
micwill755 force-pushed the early-lowering-cache branch from 37b8702 to 2aa0679 Compare October 13, 2026 22:08
Base automatically changed from batch-defer-fx-cleanup to main October 13, 2026 22:09
@micwill755
micwill755 force-pushed the early-lowering-cache branch 2 times, most recently from 76e7c24 to 8820d25 Compare October 13, 2026 23:12
@github-actions github-actions Bot added the component: lowering Issues re: The lowering / preprocessing passes label Oct 13, 2026
@micwill755
micwill755 force-pushed the early-lowering-cache branch from 8820d25 to ada13a8 Compare October 13, 2026 23:24
Serialize the live FX node list and state_dict with torch.save so a hit can skip decomposition and post_lowering without retracing generated Python.
Reuse save/load so custom engine caches can hold post-lowering GraphModules without a separate disk format.
A re-export that only renames nodes was a cache miss. Number every node in order and keep its arguments, so renamed graphs match and swapped inputs do not.
@micwill755
micwill755 force-pushed the early-lowering-cache branch from ada13a8 to 7b0b8db Compare October 13, 2026 23:41
@micwill755
micwill755 removed this pull request from stack #4533 October 13, 2026 23:52

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: tests Issues re: Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants