Repository navigation
Skip installing large aliased constant-folded weights - #4531
Conversation
|
Can you explain more about what is happening here? What situation are we avoiding by skipping constant folding? |
486fc5b to
443a31e
Compare
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. |
443a31e to
bdba9b4
Compare
bdba9b4 to
45046a5
Compare
45046a5 to
10b11d9
Compare
| gm, | ||
| node, | ||
| torch.nn.Parameter(constant.cpu().contiguous(), requires_grad=False), | ||
| constant.cpu().contiguous(), |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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())
There was a problem hiding this comment.
Restored register_parameter() and added the deepcopy regression test described above.
| # 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)) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
nvm just saw #4597. Would be good to verify it solves all these ops.
98441b1 to
d02ac12
Compare
micwill755
left a comment
There was a problem hiding this comment.
Addressed all comments.
d02ac12 to
0b02f46
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: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)0b02f46 to
1681cc8
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: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)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 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)|
Can you fix the lint? |
Avoid cpu().contiguous() copies of folded tensors that already share storage with module weights under offload_module_to_cpu, while still installing materialized folds.
1681cc8 to
4d7742f
Compare
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'.
Summary
cpu().contiguous()copies underoffload_module_to_cpu.PR 2 of 3 in a compile-startup stack; based on #4530.
Test plan
offload_module_to_cpu=True