Skip to content

Commit ba7429b

Browse files
committed
fix(refit): refit INT4 weights
Refitting an engine that holds INT4 weights failed, for ModelOpt and for TorchAO INT4 weight-only models alike: TensorRT refused the new weight for ..._int4_weight CONSTANT: the engine holds 524288 DataType.INT4, the new weight is 262144 DataType.INT8 The converter records an INT4 constant as packed bytes, two values per byte, and refit passed those bytes to TensorRT as INT8. Reusing a cached engine refits it, so with the engine cache on, the first compile stored an engine that every later compile then failed to load. Refit now passes the packed bytes as INT4 when the engine's weight is INT4. Tests refit a ModelOpt INT4 engine, and an engine with a TorchAO-style INT4 dequantize, with new weights and check the output. The second test needs neither ModelOpt nor TorchAO. The guides, the TorchAO examples README and the INT4 examples no longer say that INT4 engines cannot be refit, or that immutable_weights=True is what keeps the constants INT4. They still ask for immutable_weights=True, because only then does TensorRT fuse the INT4 dequantize into the matmul. The troubleshooting guide also says that the engine cache needs a refittable engine. Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
1 parent 4f1939e commit ba7429b

9 files changed

Lines changed: 99 additions & 32 deletions

File tree

‎docsrc/debugging/troubleshooting.rst‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,9 @@ Accuracy / Performance Issues
228228
size is a multiple of the block size (128). ModelOpt pads other weights, and
229229
their engine dequantizes a full 16-bit copy of the weight into scratch memory.
230230

231-
Refit does not support INT4 weights yet, so keep the default
232-
``immutable_weights=True``. A refittable engine still builds, but TensorRT does
233-
not fuse its INT4 dequantize into the matmul, and refitting it fails with an
234-
error. Reusing a cached engine fails the same way, because it refits the engine.
231+
Keep the default ``immutable_weights=True``. A refittable engine, which the
232+
engine cache needs, builds and can be refit, but TensorRT does not fuse its INT4
233+
dequantize into the matmul.
235234

236235
With TensorRT 11.4, some deeper networks with INT4 weights fail with an illegal
237236
memory access when the engine runs in the process that built it. The same engine
@@ -255,7 +254,8 @@ Accuracy / Performance Issues
255254
For **INT4 weight-only** quantization with TorchAO, see
256255
:ref:`quantize_linear_int4_woq`, :ref:`torch_export_flux_int4_woq`, and
257256
:ref:`torch_export_qwen3_int4_woq`. Use symmetric INT4 (zero zero-point)
258-
and ``immutable_weights=True`` so engine constants stay ``Datatype: Int4``.
257+
and ``immutable_weights=True``, so TensorRT can fuse the INT4 dequantize into the
258+
matmul.
259259

260260
For **NVFP4 weight-only** quantization with TorchAO, see
261261
:ref:`quantize_linear_nvfp4_woq` and :ref:`torch_export_flux_nvfp4_woq`.

‎docsrc/user_guide/shapes_precision/quantization.rst‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -218,9 +218,9 @@ int8 qdata into ``trt.DataType.INT4``. With BF16 scales, as in the example,
218218
the weights are dequantized straight to BF16, so TensorRT can fuse the
219219
dequantize into the matmul.
220220

221-
Compile with ``immutable_weights=True``. The converter packs INT4 at build
222-
time; engine refit would push the graph's int8 qdata at an INT4 prototype
223-
(``refit weights data type Int8 must equal to weights prototype Int4``).
221+
Compile with ``immutable_weights=True``. A refittable engine can be refit, but
222+
it dequantizes INT4 weights in FP32, and TensorRT does not fuse that into the
223+
matmul.
224224

225225
.. code-block:: python
226226
@@ -474,7 +474,9 @@ Troubleshooting
474474
The graph must keep ``dequantize_affine`` (same preprocess / constant-fold
475475
exclusion as FP8 WOQ). Group-wise INT4 also requires the INT4 pack path in
476476
the converter; per-channel INT8-style DQ will not emit ``Datatype: Int4``.
477-
Use symmetric quantization (zero zero-point) and ``immutable_weights=True``.
477+
Use symmetric quantization (zero zero-point). ``immutable_weights=True`` is
478+
not needed for INT4 constants, but it lets TensorRT fuse the INT4 dequantize
479+
into the matmul.
478480

479481
**"IDequantizeLayer rejects nonzero zero_point" / INT4 compile fails**
480482
TorchAO's default INT4 config is asymmetric. Use

‎examples/dynamo/torchao/README.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ so TensorRT can fuse Q/DQ into FP8 GEMMs.
1515

1616
Weight-only INT4 is the same DQ pattern with packed 4-bit integer weights.
1717
Use **symmetric** group-wise INT4 (zero zero-point) and compile with
18-
``immutable_weights=True`` so engine constants stay ``Datatype: Int4``.
18+
``immutable_weights=True`` so TensorRT can fuse the INT4 dequantize into the matmul.
1919

2020
Weight-only NVFP4 stores packed FP4 E2M1 weights with FP8 block scales.
2121
Export emits ``dequantize_nvfp4``, which Torch-TensorRT maps to two-level

‎examples/dynamo/torchao/quantize_linear_int4_woq.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,8 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
7272
# ^^^^^^^^^^^^^^^^^^
7373
# Wrap export in exclude_dq_from_constant_folding so inductor does not fold
7474
# dequantize_affine before Torch-TensorRT lowering. Use
75-
# immutable_weights=True: the converter re-packs int8 qdata into an INT4
76-
# constant at build time, and engine refit would push unpacked int8 at an INT4
77-
# prototype.
75+
# immutable_weights=True, so TensorRT can fuse the INT4 dequantize into the
76+
# matmul.
7877

7978
with exclude_dq_from_constant_folding():
8079
exp_program = torch.export.export(processed_model, (example_input,), strict=True)

‎examples/dynamo/torchao/torch_export_flux_int4_woq.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
1717
You need access to FLUX.1-dev on Hugging Face. Quantization is done
1818
layer-by-layer on GPU so the rest of the pipeline can stay on CPU. Compile with
19-
immutable_weights=True (INT4 constants cannot be refit from int8 graph
20-
weights). On 32GB cards, park the text encoders during compile and generate
19+
immutable_weights=True, so TensorRT can fuse the INT4 dequantize into the
20+
matmul. On 32GB cards, park the text encoders during compile and generate
2121
from precomputed prompt embeddings so T5 and the TRT execution context are not
2222
resident together.
2323
@@ -132,8 +132,8 @@
132132
# ---------------------------
133133
# .. note::
134134
# Compilation of the 12B transformer takes on the order of 20–30 minutes.
135-
# immutable_weights=True is required: the converter packs int8 qdata into
136-
# INT4 at build time, and refit would push Int8 weights at an Int4 prototype.
135+
# immutable_weights=True lets TensorRT fuse the INT4 dequantize into the
136+
# matmul. A refittable engine dequantizes in FP32 instead.
137137

138138
trt_gm = torch_tensorrt.dynamo.compile(
139139
exp_program,

‎examples/dynamo/torchao/torch_export_qwen3_int4_woq.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def greedy_generate(
259259
# Export and compile
260260
# ------------------
261261
# strict=False matches other Torch-TensorRT LLM examples (aotautograd).
262-
# immutable_weights=True is required for INT4 packed constants.
262+
# immutable_weights=True lets TensorRT fuse the INT4 dequantize into the matmul.
263263

264264
processed = pre_process_model_for_export(wrapper)
265265
with exclude_dq_from_constant_folding():

‎py/torch_tensorrt/dynamo/_refit.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,11 @@ def _refit_single_trt_engine_with_gm(
109109
# Use Tensor to create weights
110110
weight = mapping[layer_name]
111111
trt_dtype = dtype._from(weight.dtype).to(trt.DataType)
112-
trt_wt_tensor = trt.Weights(
113-
trt_dtype, weight.data_ptr(), torch.numel(weight)
114-
)
112+
count = torch.numel(weight)
113+
if refitter.get_weights_prototype(layer_name).dtype == trt.DataType.INT4:
114+
# INT4 weights are recorded packed, two values per byte.
115+
trt_dtype, count = trt.DataType.INT4, 2 * count
116+
trt_wt_tensor = trt.Weights(trt_dtype, weight.data_ptr(), count)
115117
if not refitter.set_named_weights(
116118
layer_name, trt_wt_tensor, trt_wt_location
117119
):

‎tests/py/dynamo/conversion/test_quantize_scale.py‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22
# SPDX-License-Identifier: BSD-3-Clause
33

44
import unittest
5+
from unittest import mock
56

67
import numpy as np
78
import tensorrt as trt
89
import torch
910
from torch.testing._internal.common_utils import TestCase, run_tests
10-
from torch_tensorrt import _enums
11+
from torch_tensorrt import ENABLED_FEATURES, _enums
12+
from torch_tensorrt.dynamo import _refit
1113
from torch_tensorrt.dynamo._settings import CompilationSettings
1214
from torch_tensorrt.dynamo.conversion import aten_ops_converters, impl
1315
from torch_tensorrt.dynamo.conversion._ConversionContext import ConversionContext
@@ -289,9 +291,19 @@ def dequantize(*values):
289291
dequantize(-8, 7)
290292

291293
def _int4_matmul(
292-
self, qdata, scale, x, dtype, runtime_scale=False, refittable=False
294+
self,
295+
qdata,
296+
scale,
297+
x,
298+
dtype,
299+
runtime_scale=False,
300+
refittable=False,
301+
refit_qdata=None,
293302
):
294-
"""Build and run x @ dequantize_affine(qdata, scale).T, the scale optionally an input."""
303+
"""Build and run x @ dequantize_affine(qdata, scale).T, the scale optionally an input.
304+
305+
With refit_qdata, the engine is refit with those weights before it runs.
306+
"""
295307
skip_if_trt_rtx_turing(self, "INT4 dequantize into a matmul")
296308
builder = trt.Builder(trt.Logger(trt.Logger.ERROR))
297309
network = builder.create_network(
@@ -328,6 +340,30 @@ def _int4_matmul(
328340
plan = builder.build_serialized_network(network, config)
329341
self.assertIsNotNone(plan)
330342
engine = trt.Runtime(trt.Logger(trt.Logger.ERROR)).deserialize_cuda_engine(plan)
343+
if refit_qdata is not None:
344+
new_ctx = ConversionContext(
345+
builder.create_network(
346+
1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)
347+
),
348+
ctx.compilation_settings,
349+
)
350+
impl.quantize.dequantize_affine(
351+
new_ctx,
352+
torch.ops.aten.mul.Tensor,
353+
None,
354+
"dq",
355+
refit_qdata,
356+
[1, 128],
357+
scale,
358+
dtype,
359+
)
360+
with mock.patch.object(
361+
_refit,
362+
"construct_refit_mapping",
363+
return_value=new_ctx.weight_refit_map,
364+
):
365+
_refit._refit_single_trt_engine_with_gm(None, engine, [])
366+
qdata = refit_qdata
331367
context = engine.create_execution_context()
332368
buffers = {"x": x.to("cuda", dtype), "scale": scale.cuda()}
333369
out = torch.empty(x.shape[0], qdata.shape[0], device="cuda", dtype=dtype)
@@ -366,6 +402,18 @@ def test_int4_dequantize_in_a_refittable_engine(self):
366402
)
367403
torch.testing.assert_close(out, expected, rtol=2e-2, atol=1.0)
368404

405+
@unittest.skipIf(not ENABLED_FEATURES.refit, "Refit is not available")
406+
def test_int4_dequantize_refits_new_weights(self):
407+
# Refit, which a cached engine also goes through, loads the INT4 weights.
408+
qdata = torch.randint(-8, 8, (512, 1024), dtype=torch.int8)
409+
new_qdata = torch.randint(-8, 8, (512, 1024), dtype=torch.int8)
410+
scale = torch.rand(512, 8, dtype=torch.bfloat16) + 0.5
411+
x = torch.randn(4, 1024)
412+
out, expected = self._int4_matmul(
413+
qdata, scale, x, torch.bfloat16, refittable=True, refit_qdata=new_qdata
414+
)
415+
torch.testing.assert_close(out, expected, rtol=2e-2, atol=1.0)
416+
369417
def test_int4_dequantize_in_the_scale_dtype_adds_no_cast(self):
370418
# A cast between the DQ and its matmul stops TensorRT from fusing them.
371419
skip_if_trt_rtx_turing(self, "INT4 dequantize into a matmul")

‎tests/py/dynamo/models/test_models_export.py‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -795,16 +795,21 @@ def test_int4_blockwise_weight_only(ir, dtype, in_features):
795795
def test_int4_blockwise_weight_only_refittable(ir):
796796
import modelopt.torch.quantization as mtq
797797
from modelopt.torch.quantization.utils import export_torch_mode
798+
from torch_tensorrt.dynamo import refit_module_weights
798799

799-
model = torch.nn.Linear(2048, 2048).eval().cuda().to(torch.bfloat16)
800-
input_tensor = torch.randn(8, 2048, dtype=torch.bfloat16).cuda()
801-
mtq.quantize(
802-
model,
803-
mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFG,
804-
forward_loop=lambda model: model(input_tensor),
805-
)
806-
output_pyt = model(input_tensor)
800+
input_tensor = torch.randn(4, 1024, dtype=torch.bfloat16).cuda()
801+
802+
def quantized_linear():
803+
model = torch.nn.Linear(1024, 512).eval().cuda().to(torch.bfloat16)
804+
mtq.quantize(
805+
model,
806+
mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFG,
807+
forward_loop=lambda model: model(input_tensor),
808+
)
809+
return model
807810

811+
model = quantized_linear()
812+
output_pyt = model(input_tensor)
808813
with torch.no_grad(), export_torch_mode():
809814
exp_program = torch.export.export(model, (input_tensor,), strict=False)
810815
trt_model = torchtrt.dynamo.compile(
@@ -818,6 +823,17 @@ def test_int4_blockwise_weight_only_refittable(ir):
818823
outputs_trt = trt_model(input_tensor)
819824
assert torch.allclose(output_pyt, outputs_trt, rtol=5e-3, atol=5e-2)
820825

826+
# Refit, which a cached engine also goes through, loads new INT4 weights.
827+
model = quantized_linear()
828+
output_pyt = model(input_tensor)
829+
with torch.no_grad(), export_torch_mode():
830+
exp_program = torch.export.export(model, (input_tensor,), strict=False)
831+
trt_model = refit_module_weights(
832+
trt_model, exp_program, arg_inputs=(input_tensor,)
833+
)
834+
outputs_trt = trt_model(input_tensor)
835+
assert torch.allclose(output_pyt, outputs_trt, rtol=5e-3, atol=5e-2)
836+
821837

822838
@pytest.mark.unit
823839
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)