Skip to content

Commit bb603c4

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 guides now also say that INT4 engines that refit or use the engine cache, which needs a refittable engine, are slower. On an A100, a bf16 gated MLP (4096 to 14336 to 4096) took 0.76 ms for one token with a refittable INT4 engine, 0.27 ms with an immutable one, and 0.24 ms in bf16. Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
1 parent 33a8cf1 commit bb603c4

9 files changed

Lines changed: 103 additions & 32 deletions

File tree

‎docsrc/debugging/troubleshooting.rst‎

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

232-
Refit does not support INT4 weights yet, so keep the default
233-
``immutable_weights=True``. A refittable engine still builds, but TensorRT does
234-
not fuse its INT4 dequantize into the matmul, and refitting it fails with an
235-
error. Reusing a cached engine fails the same way, because it refits the engine.
232+
Keep the default ``immutable_weights=True``. A refittable engine, which the
233+
engine cache needs, builds and can be refit, but TensorRT does not fuse its INT4
234+
dequantize into the matmul, so INT4 engines that refit or use the engine cache
235+
are slower. They dequantize every weight into scratch memory on each run. For a
236+
BF16 gated MLP (4096 to 14336 to 4096) on an A100, one token took 0.76 ms with a
237+
refittable INT4 engine, 0.27 ms with an immutable one, and 0.24 ms in BF16.
236238

237239
With TensorRT 11.4, some deeper networks with INT4 weights fail with an illegal
238240
memory access when the engine runs in the process that built it. The same engine
@@ -256,7 +258,8 @@ Accuracy / Performance Issues
256258
For **INT4 weight-only** quantization with TorchAO, see
257259
:ref:`quantize_linear_int4_woq`, :ref:`torch_export_flux_int4_woq`, and
258260
:ref:`torch_export_qwen3_int4_woq`. Use symmetric INT4 (zero zero-point)
259-
and ``immutable_weights=True`` so engine constants stay ``Datatype: Int4``.
261+
and ``immutable_weights=True``, so TensorRT can fuse the INT4 dequantize into the
262+
matmul.
260263

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

‎docsrc/user_guide/shapes_precision/quantization.rst‎

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

222-
Compile with ``immutable_weights=True``. The converter packs INT4 at build
223-
time; engine refit would push the graph's int8 qdata at an INT4 prototype
224-
(``refit weights data type Int8 must equal to weights prototype Int4``).
222+
Compile with ``immutable_weights=True``. A refittable engine can be refit, but
223+
it dequantizes INT4 weights in FP32, and TensorRT does not fuse that into the
224+
matmul. So INT4 engines that refit or use the engine cache, which needs refittable
225+
engines, are slower: 2 to 3 times in a measured BF16 MLP.
225226

226227
.. code-block:: python
227228
@@ -490,7 +491,9 @@ Troubleshooting
490491
The graph must keep ``dequantize_affine`` (same preprocess / constant-fold
491492
exclusion as FP8 WOQ). Group-wise INT4 also requires the INT4 pack path in
492493
the converter; per-channel INT8-style DQ will not emit ``Datatype: Int4``.
493-
Use symmetric quantization (zero zero-point) and ``immutable_weights=True``.
494+
Use symmetric quantization (zero zero-point). ``immutable_weights=True`` is
495+
not needed for INT4 constants, but it lets TensorRT fuse the INT4 dequantize
496+
into the matmul.
494497

495498
**"IDequantizeLayer rejects nonzero zero_point" / INT4 compile fails**
496499
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
@@ -283,9 +285,19 @@ def supported(*values, block_size=(1, 16)):
283285
self.assertTrue(supported(-128, 127, block_size=(1, 256)))
284286

285287
def _int4_matmul(
286-
self, qdata, scale, x, dtype, runtime_scale=False, refittable=False
288+
self,
289+
qdata,
290+
scale,
291+
x,
292+
dtype,
293+
runtime_scale=False,
294+
refittable=False,
295+
refit_qdata=None,
287296
):
288-
"""Build and run x @ dequantize_affine(qdata, scale).T, the scale optionally an input."""
297+
"""Build and run x @ dequantize_affine(qdata, scale).T, the scale optionally an input.
298+
299+
With refit_qdata, the engine is refit with those weights before it runs.
300+
"""
289301
skip_if_trt_rtx_turing(self, "INT4 dequantize into a matmul")
290302
builder = trt.Builder(trt.Logger(trt.Logger.ERROR))
291303
network = builder.create_network(
@@ -322,6 +334,30 @@ def _int4_matmul(
322334
plan = builder.build_serialized_network(network, config)
323335
self.assertIsNotNone(plan)
324336
engine = trt.Runtime(trt.Logger(trt.Logger.ERROR)).deserialize_cuda_engine(plan)
337+
if refit_qdata is not None:
338+
new_ctx = ConversionContext(
339+
builder.create_network(
340+
1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)
341+
),
342+
ctx.compilation_settings,
343+
)
344+
impl.quantize.dequantize_affine(
345+
new_ctx,
346+
torch.ops.aten.mul.Tensor,
347+
None,
348+
"dq",
349+
refit_qdata,
350+
[1, 128],
351+
scale,
352+
dtype,
353+
)
354+
with mock.patch.object(
355+
_refit,
356+
"construct_refit_mapping",
357+
return_value=new_ctx.weight_refit_map,
358+
):
359+
_refit._refit_single_trt_engine_with_gm(None, engine, [])
360+
qdata = refit_qdata
325361
context = engine.create_execution_context()
326362
buffers = {"x": x.to("cuda", dtype), "scale": scale.cuda()}
327363
out = torch.empty(x.shape[0], qdata.shape[0], device="cuda", dtype=dtype)
@@ -360,6 +396,18 @@ def test_int4_dequantize_in_a_refittable_engine(self):
360396
)
361397
torch.testing.assert_close(out, expected, rtol=2e-2, atol=1.0)
362398

399+
@unittest.skipIf(not ENABLED_FEATURES.refit, "Refit is not available")
400+
def test_int4_dequantize_refits_new_weights(self):
401+
# Refit, which a cached engine also goes through, loads the INT4 weights.
402+
qdata = torch.randint(-8, 8, (512, 1024), dtype=torch.int8)
403+
new_qdata = torch.randint(-8, 8, (512, 1024), dtype=torch.int8)
404+
scale = torch.rand(512, 8, dtype=torch.bfloat16) + 0.5
405+
x = torch.randn(4, 1024)
406+
out, expected = self._int4_matmul(
407+
qdata, scale, x, torch.bfloat16, refittable=True, refit_qdata=new_qdata
408+
)
409+
torch.testing.assert_close(out, expected, rtol=2e-2, atol=1.0)
410+
363411
def test_int4_dequantize_in_the_scale_dtype_adds_no_cast(self):
364412
# A cast between the DQ and its matmul stops TensorRT from fusing them.
365413
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
@@ -793,16 +793,21 @@ def test_int4_blockwise_weight_only(ir, dtype, in_features):
793793
def test_int4_blockwise_weight_only_refittable(ir):
794794
import modelopt.torch.quantization as mtq
795795
from modelopt.torch.quantization.utils import export_torch_mode
796+
from torch_tensorrt.dynamo import refit_module_weights
796797

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

809+
model = quantized_linear()
810+
output_pyt = model(input_tensor)
806811
with torch.no_grad(), export_torch_mode():
807812
exp_program = torch.export.export(model, (input_tensor,), strict=False)
808813
trt_model = torchtrt.dynamo.compile(
@@ -816,6 +821,17 @@ def test_int4_blockwise_weight_only_refittable(ir):
816821
outputs_trt = trt_model(input_tensor)
817822
assert torch.allclose(output_pyt, outputs_trt, rtol=5e-3, atol=5e-2)
818823

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

820836
@pytest.mark.unit
821837
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)