Skip to content

Skip installing large aliased constant-folded weights - #4531

Merged
micwill755 merged 2 commits into
mainfrom
skip-aliased-fold-install
Oct 13, 2026
Merged

micwill755 merged 2 commits into
mainfrom
skip-aliased-fold-install

Conversation

@micwill755

Copy link
Copy Markdown
Collaborator

Summary

  • Skip installing large constant-folded tensors that only alias existing module weights, avoiding expensive cpu().contiguous() copies under offload_module_to_cpu.

PR 2 of 3 in a compile-startup stack; based on #4530.

Test plan

  • Flux NVFP4 cold compile still succeeds with offload_module_to_cpu=True
  • Large weight permutes remain in-graph (not installed as frozen params)
  • VLA still folds materialized embedding constants and compiles (int32 indices)

@meta-cla meta-cla Bot added the cla signed label Aug 19, 2026
@github-actions github-actions Bot added 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 19, 2026
@github-actions
github-actions Bot requested a review from cehongwang August 19, 2026 21:56
@narendasan

Copy link
Copy Markdown
Collaborator

Can you explain more about what is happening here? What situation are we avoiding by skipping constant folding?

@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from 486fc5b to 443a31e Compare September 1, 2026 18:29
@micwill755

Copy link
Copy Markdown
Collaborator Author

Can you explain more about what is happening here? What situation are we avoiding by skipping constant folding?

We are not skipping constant folding, ConstantFolder still runs and we still fold, but we skip install when the result is >1 MiB and still aliases a module weight, e.g. a Flux aten.permute on self.weight. That avoids copying hundreds of MiB of weights we already have, e.g on Klein ~372 MiB / ~0.34s which leaves the permute in FX so TRT can fold it as a shuffle at engine build.

@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from 443a31e to bdba9b4 Compare September 16, 2026 23:22
Base automatically changed from partition-short-circuit to main September 16, 2026 23:23
@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from bdba9b4 to 45046a5 Compare September 16, 2026 23:23
@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from 45046a5 to 10b11d9 Compare September 29, 2026 17:44
@micwill755 micwill755 added this to the v2.15.0 milestone Sep 29, 2026
gm,
node,
torch.nn.Parameter(constant.cpu().contiguous(), requires_grad=False),
constant.cpu().contiguous(),

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.

We probably need detach? Can you check whether the grad_fn can be there?

replace_node_with_constant(
gm, node, torch.nn.Parameter(constant, requires_grad=False)
)
replace_node_with_constant(gm, node, constant)

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.

and here

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.

Agreed. Fixed in d02ac12 by restoring nn.Parameter wrapper in both offload paths. I added coverage asserting requires_grad=False, grad_fn is None, and successful copy.deepcopy() with offloading both enabled and disabled.


# Needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning
gm.register_parameter(qualname, constant)
gm.register_buffer(qualname, constant)

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 do we change it from parameter to buffer?

AI says:

Switching from register_parameter to register_buffer breaks copy.deepcopy and torch_tensorrt.save(retrace=False) for any folded weight that feeds a Torch fallback block.

nn.Parameter(x, requires_grad=False) was the only thing detaching folded tensors. constant_fold runs under _disable_current_modes() but not under torch.no_grad(), so the raw constant keeps its grad_fn. I measured this on the previous revision, and the code is unchanged:

The crash is raised from _exporter.py:113 (gm = copy.deepcopy(gm)), and _refit.py:152 does the same deepcopy. The PR adds no tests.

The simplest fix is to keep the Parameter wrapper. If you want buffers, detach instead, but note that _exporter.py:193 then treats _frozen_paramN as InputKind.BUFFER without a persistent flag, so that needs handling too:

    gm.register_buffer(qualname, constant.detach())

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.

Restored register_parameter() and added the deepcopy regression test described above.

Comment on lines 1 to 222
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause

import logging
from typing import Any, Set

import torch
from torch_tensorrt._utils import sanitized_torch_version
from torch_tensorrt.dynamo._settings import CompilationSettings
from torch_tensorrt.dynamo.lowering.constant_fold_exclusions import (
CONSTANT_FOLD_EXCLUSION_META_KEY,
)
from torch_tensorrt.dynamo.lowering.passes.pass_utils import (
clean_up_graph_after_modifications,
)

from packaging import version

# Modify import location of utilities based on Torch version
if version.parse(sanitized_torch_version()) < version.parse("2.1.1"):
from torch._inductor.freezing import ConstantFolder
else:
from torch._inductor.constant_folding import ConstantFolder

logger = logging.getLogger(__name__)

# Skip installing large folded tensors that already share storage with an
# existing module attribute (typically weight permutes/views). On Flux NVFP4
# those dominate replace cost via cpu().contiguous() under offload_module_to_cpu.
# Do NOT skip materialized folds (e.g. VLA position embedding outputs) — those
# can be required for TRT legality (int64 indices never reach the converter).
_MAX_CONSTANT_FOLD_BYTES = 1 << 20 # 1 MiB


def _tensor_reuses_module_storage(
gm: torch.fx.GraphModule, constant: torch.Tensor
) -> bool:
try:
ptr = constant.untyped_storage().data_ptr()
except Exception:
return False
for tensor in gm.state_dict().values():
if isinstance(tensor, torch.Tensor):
try:
if tensor.untyped_storage().data_ptr() == ptr:
return True
except Exception:
continue
return False


@torch.utils._python_dispatch._disable_current_modes() # type: ignore
def constant_fold(
gm: torch.fx.GraphModule, settings: CompilationSettings
) -> torch.fx.GraphModule:
"""Adapted from:
https://github.com/pytorch/pytorch/blob/3a79621c9dce17f77fbddc06aab21f6bc477f313/torch/_inductor/freezing.py#L178-L197

Folds constants in the graph module, not skipping constructors

Modifies the graph in-place and replaces node with constants
"""
cf = _TorchTensorRTConstantFolder(gm, skip_constructors=False)
cf.run()

# The constants are created on CPU to save GPU memory for TensorRT compilation.
# For TRT INetwork construction the constants are moved to CPU in get_attr call.
skipped_alias = 0
for node, constant in cf.node_replacements.items():
if isinstance(constant, torch.Tensor):
nbytes = int(constant.numel() * constant.element_size())
if nbytes > _MAX_CONSTANT_FOLD_BYTES and _tensor_reuses_module_storage(
gm, constant
):
skipped_alias += 1
logger.debug(
"Skipping constant-fold install for aliased %s (%d bytes > %d)",
node.name,
nbytes,
_MAX_CONSTANT_FOLD_BYTES,
)
continue
# Register folded values as plain tensors (buffers), matching Inductor.
if settings.offload_module_to_cpu:
replace_node_with_constant(
gm,
node,
torch.nn.Parameter(constant.cpu().contiguous(), requires_grad=False),
constant.cpu().contiguous(),
)
else:
replace_node_with_constant(
gm, node, torch.nn.Parameter(constant, requires_grad=False)
)
replace_node_with_constant(gm, node, constant)

if skipped_alias:
logger.info(
"Skipped installing %d large aliased folded constant(s) (>%d bytes); "
"leaving original view/permute ops in the graph",
skipped_alias,
_MAX_CONSTANT_FOLD_BYTES,
)

erased_params = []
for node in gm.graph.nodes:
# If get_attr node has no users, mark it for deletion
if node.op == "get_attr" and len(node.users) == 0:
erased_params.append(node)

# Remove unused nodes from the graph
for node in erased_params:
gm.graph.erase_node(node)

gm = clean_up_graph_after_modifications(gm)
# Delete the constant folder instance which holds GPU memory
del cf

logger.debug(f"Graph after constant folding:\n{gm.graph}")
return gm


def replace_node_with_constant(
gm: torch.fx.GraphModule, node: torch.fx.Node, constant: torch.Tensor
) -> None:
"""Adapted from:
https://github.com/pytorch/pytorch/blob/bcf35c6ae62bb6560befa3550e37a8283944e5f4/torch/_inductor/constant_folding.py#L17-L43

Modified to register parameters, instead of buffers for frozen constants
Registers frozen constants as buffers (same as Inductor), not Parameters.
"""
g = gm.graph

if not hasattr(gm, "_frozen_param_count"):
gm._frozen_param_count = 0

i = gm._frozen_param_count

while True:
qualname = f"_frozen_param{i}"
if not hasattr(gm, qualname):
break
i += 1

gm._frozen_param_count = i + 1

with g.inserting_before(node):
new_input_node = g.create_node("get_attr", qualname, (), {})
node.replace_all_uses_with(new_input_node)
new_input_node.meta.update(node.meta)
g.erase_node(node)

# Needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning
gm.register_parameter(qualname, constant)
gm.register_buffer(qualname, constant)
setattr(gm, qualname, constant)


# TODO: Delete this class when the following code is fixed in nightly:
# https://github.com/pytorch/pytorch/blob/4b881b0da390c1290bb12850ef9daad6f6eb2cb6/torch/_inductor/constant_folding.py#L53-L63
class _TorchTensorRTConstantFolder(ConstantFolder): # type: ignore[misc]
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
# Quantization ops excluded from constant folding so TRT sees QDQ
# (ModelOpt tensorrt.quantize_op, TorchAO dequantize_affine, TorchAO
# NVFP4 dequantize_nvfp4, and TorchAO MXFP4 dequantize_mxfp4 when
# those custom ops are registered).
self.quantization_ops: Set[torch._ops.OpOverload] = set()
try:
# modelopt import ensures torch.ops.tensorrt.quantize_op.default is registered
import modelopt.torch.quantization as mtq # noqa: F401

assert torch.ops.tensorrt.quantize_op.default
assert torch.ops.tensorrt.dynamic_block_quantize_op.default
self.quantization_ops.add(torch.ops.tensorrt.quantize_op.default)
self.quantization_ops.add(
torch.ops.tensorrt.dynamic_block_quantize_op.default
)
except Exception as e:
pass

try:
import torchao # noqa: F401

assert torch.ops.torchao.dequantize_affine.default
self.quantization_ops.add(torch.ops.torchao.dequantize_affine.default)
except Exception:
pass

try:
from torchao.quantization.quant_primitives import ( # noqa: F401
_dequantize_affine_float8_non_decomposed,
_quantize_affine_float8_non_decomposed,
)

self.quantization_ops.add(
torch.ops.torchao.quantize_affine_float8_non_decomposed.default
)
self.quantization_ops.add(
torch.ops.torchao.dequantize_affine_float8_non_decomposed.default
)
except Exception:
pass

try:
from torch_tensorrt.dynamo.conversion import nvfp4_custom_op # noqa: F401

assert torch.ops.torchao_trt.dequantize_nvfp4.default
self.quantization_ops.add(torch.ops.torchao_trt.dequantize_nvfp4.default)
except Exception:
pass

try:
from torch_tensorrt.dynamo.conversion import mxfp4_custom_op # noqa: F401

assert torch.ops.torchao_trt.dequantize_mxfp4.default
self.quantization_ops.add(torch.ops.torchao_trt.dequantize_mxfp4.default)
except Exception:
pass

# TODO: Update this function when quantization is added
def is_impure(self, node: torch.fx.node.Node) -> bool:

if node.target in self.quantization_ops:
return True
# The meta value holds the IDs of the rules that marked this node; it is
# empty once every rule that claimed it has been disabled.
return bool(node.meta.get(CONSTANT_FOLD_EXCLUSION_META_KEY))

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.

On main, every constant view of a weight gets folded, so the view op disappears before conversion. With #4531, when a fold over 1 MiB shares storage with the weight, the PR continues. The view op and its weight constant stay in the graph, and that op's converter now has to handle a constant input. For squeeze.default there is no converter at all. This behaviour only exists because of the PR.

How often it happens. I exported small models through torch.export plus Torch-TensorRT's get_decompositions() to see which ops actually reach constant_fold from ordinary code:

User code on a large weight Op that survives
w.squeeze() aten.squeeze.default (affected)
w.squeeze(0) aten.squeeze.dim (fine)
torch.as_strided(w, ...) aten.as_strided.default (affected)
w[0] aten.select.int (fine in #4531)
w.transpose(1, 2) aten.permute.default (fine)

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.

Addressed in d02ac12. Skipping installation is now allowlisted only for aten.permute.default, whose converter supports constant inputs. squeeze.default, as_strided.default, and select.int retain the existing install behavior. Tests verify this and compile all four cases e2e

nbytes,
_MAX_CONSTANT_FOLD_BYTES,
)
continue

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.

On main, every constant view of a weight gets folded, so the view op disappears before conversion. With #4531, when a fold over 1 MiB shares storage with the weight, the PR continues. The view op and its weight constant stay in the graph, and that op's converter now has to handle a constant input. For squeeze.default there is no converter at all. This behaviour only exists because of the PR.

How often it happens. I exported small models through torch.export plus Torch-TensorRT's get_decompositions() to see which ops actually reach constant_fold from ordinary code:

User code on a large weight Op that survives
w.squeeze() aten.squeeze.default (affected)
w.squeeze(0) aten.squeeze.dim (fine)
torch.as_strided(w, ...) aten.as_strided.default (affected)
w[0] aten.select.int (fine in #4531)
w.transpose(1, 2) aten.permute.default (fine)

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.

nvm just saw #4597. Would be good to verify it solves all these ops.

@micwill755 micwill755 Oct 6, 2026 •

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.

PR no longer depends on #4597 to make unsupported view ops safe, only permute.default may remain in the graph. #4597 remains a separate optimization that avoids executing folds which this PR intentionally leaves uninstalled.

@micwill755 micwill755 left a comment

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.

Addressed all comments.

@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from d02ac12 to 0b02f46 Compare October 6, 2026 21:29

@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:29:53.491018+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/impl/moe.py	2026-10-06 21:30:25.197175+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:29:53.488953+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py	2026-10-06 21:30:29.562361+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)

@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from 0b02f46 to 1681cc8 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.863751+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/impl/moe.py	2026-10-06 21:35:23.821719+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.861631+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py	2026-10-06 21:35:28.467426+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)

@micwill755
micwill755 requested a review from cehongwang October 6, 2026 22:24

@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 22:24:34.506473+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/impl/moe.py	2026-10-06 22:25:07.796699+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 22:24:34.504386+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py	2026-10-06 22:25:12.116690+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)

@cehongwang

Copy link
Copy Markdown
Collaborator

Can you fix the lint?

@lanluo-nvidia lanluo-nvidia modified the milestones: v2.15.0, v2.16.0 Oct 8, 2026
Avoid cpu().contiguous() copies of folded tensors that already share storage with module weights under offload_module_to_cpu, while still installing materialized folds.
@micwill755
micwill755 force-pushed the skip-aliased-fold-install branch from 1681cc8 to 4d7742f Compare October 13, 2026 18:18
@micwill755
micwill755 merged commit eac7761 into main Oct 13, 2026
micwill755 added a commit that referenced this pull request Nov 10, 2026
TensorRT only accepts a quantized constant directly in front of a DQ
layer. Since #4531, a large permute of a module weight is left unfolded,
so TorchAO FP8 weight-only Linear (which transposes the FP8 qdata before
dequantize_affine) built FP8 const -> permute -> DQ and failed with
'Quantized constant ... is only allowed before DQ'.
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.

4 participants