Skip to content

fix(dynamo): INT4 weight-only as 4-bit constants (ModelOpt, TorchAO), INT4 refit, wide group-wise int8 runs in PyTorch - #5061

Open
shoumikhin wants to merge 5 commits into
pytorch:mainfrom
shoumikhin:modelopt-int4-weight-only
Open

shoumikhin wants to merge 5 commits into
pytorch:mainfrom
shoumikhin:modelopt-int4-weight-only

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

INT4 weight-only quantization stores weights in 4 bits and keeps activations in bf16 or fp16.

  • ModelOpt: a model quantized with mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFG fails to compile. The quantize converter accepts only 8-bit.
  • TorchAO: the INT4 dequantize always outputs float32. A bf16 graph fails to build.
  • Group-wise int8 weights with the full int8 range are silently packed into 4 bits.
  • Refit and the engine cache fail for INT4 engines.

What this change does

TensorRT fuses an INT4 dequantize into the matmul only when its scale and output have the activation type and the weight has the matmul's shape.

  • ModelOpt: a constant weight is quantized to INT4 at build time, rounding like ModelOpt. Conv weights, unsigned quantizers, weights with an odd last dim and non-constant weights (torch.compile) stay in PyTorch.
  • TorchAO: the dequantize runs in the promoted type of the scale and output, like torchao, so it fuses when the scales have the activation type.
  • Wide group-wise int8: a dequantize whose group-wise int8 weights hold values outside -8..7 runs in PyTorch.
  • Refittable engines dequantize in float32, because TensorRT fails to build many of them with a 16-bit INT4 dequantize. That does not fuse, so INT4 engines that refit or use the engine cache are slower.
  • Refit now loads INT4 weights, so refit and the engine cache work.
  • PT2E dequantize by keyword (as torch.fx.symbolic_trace leaves it) crashed the hierarchical partitioner. It now runs in PyTorch.
  • The guides recommend INT4 for weight-only quantization and note a TensorRT 11.4 issue.

A100, bf16 gated MLP (4096 to 14336 to 4096), TorchAO INT4, group 128:

tokens bf16 INT4 before INT4 after
1 0.24 ms 0.78 ms 0.27 ms
128 0.30 ms 0.88 ms 0.42 to 0.75 ms

ModelOpt INT4 builds the same fused layers and runs as fast.

Tests

Local runs on A100, TensorRT 11.4, torch 2.15, ModelOpt 0.48, torchao 0.18. On the current torch nightly ModelOpt fails to import, so its tests skip.

  • Model tests compile ModelOpt INT4 (fp16, bf16, padded K), match ModelOpt, check that the quantize runs in TensorRT and the engine shrinks, and that conv and unsigned cases run in PyTorch. A refittable engine is refit. A TorchAO test checks that a wide group-wise int8 dequantize runs in PyTorch.
  • Unit tests cover rounding, zero scales, narrow range, the validators, the dequantize types TensorRT needs to fuse, INT4 refit, and the keyword dequantize. Each fails without its fix, except keep-working cases.

Not run: other GPUs, TensorRT-RTX, Windows.

@meta-cla meta-cla Bot added the cla signed label Nov 16, 2026
@github-actions github-actions Bot added documentation Improvements or additions to documentation component: tests Issues re: Tests component: conversion Issues re: Conversion stage component: core Issues re: The core compiler component: converters Issues re: Specific op converters component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths labels Nov 16, 2026
@github-actions
github-actions Bot requested a review from apbose November 16, 2026 15:23
@narendasan
narendasan requested review from micwill755 and zewenli98 and removed request for apbose November 17, 2026 19:42
@shoumikhin
shoumikhin force-pushed the modelopt-int4-weight-only branch from 948e371 to 1848444 Compare November 18, 2026 19:15
@shoumikhin shoumikhin changed the title fix(dynamo): compile ModelOpt INT4 weight-only weights as 4-bit constants fix(dynamo): compile INT4 weight-only weights as fused 4-bit constants (ModelOpt and TorchAO) Nov 18, 2026
@shoumikhin
shoumikhin force-pushed the modelopt-int4-weight-only branch 3 times, most recently from a46025b to ba7429b Compare November 23, 2026 10:25
@shoumikhin shoumikhin changed the title fix(dynamo): compile INT4 weight-only weights as fused 4-bit constants (ModelOpt and TorchAO) fix(dynamo): INT4 weight-only as 4-bit constants (ModelOpt, TorchAO), INT4 refit, error on wide group-wise int8 Nov 23, 2026
@shoumikhin
shoumikhin marked this pull request as draft November 23, 2026 21:54

@micwill755 micwill755 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.

I left a few comments, please resolve and move out of draft and it will be good to merge.

f"(got nonzero zero_point for '{name}')"
)
assert isinstance(qdata, torch.Tensor)
if qdata.numel() and (int(qdata.min()) < -8 or int(qdata.max()) > 7):

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.

Raising here fails the whole compile. Could this check go in the dequantize validator instead, so that op runs in PyTorch?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good idea, done. The check is now a capability validator on the torchao dequantize converter, so a dequantize whose group-wise int8 weights hold values outside -8..7 runs in PyTorch, and the rest of the model still compiles. I checked a small IntxWeightOnlyConfig int8 model: both dequantizes run in PyTorch and the output matches eager in bf16 and float32. The unit test now checks the validator, and a new TorchAO test checks that the op runs in PyTorch.

# it dequantizes in float32 and casts, which TensorRT does not fuse. It does the
# same when 7 times the rounded scale overflows, as for a weight near 65504 in fp16.
dq_dtype = (
weight.dtype if ctx.compilation_settings.immutable_weights else torch.float32

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.

Refittable engines, which the engine cache needs, always get the float32 dequantize, which TensorRT doesn't fuse. Could the docs say INT4 engines that refit or use the engine cache are slower?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, done. The troubleshooting guide and the TorchAO INT4 section now say that INT4 engines that refit or use the engine cache 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. At 128 tokens it was 0.87 ms against 0.43 ms.

output = cast_trt_tensor(
ctx, output, weight.dtype, f"{name}_cast_output", target, source_ir
)
return impl.shuffle.reshape(

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 the ModelOpt path, the dequantize is followed by this reshape and ModelOpt's reshape back before the matmul. Does TensorRT still fuse it? Timings like the TorchAO table would confirm.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, it still fuses. I built the same bf16 gated MLP (4096 to 14336 to 4096) with ModelOpt INT4 and with TorchAO INT4 on an A100. The engine inspector shows the same layers for both, with no shuffle layer left, and at one token each dequantize is part of its matmul kernel. The timings match too: 0.27 ms for both at one token, and 0.43 ms against 0.42 ms at 128 tokens. At 128 tokens TensorRT keeps the down projection's dequantize separate on both paths, so that is not caused by the reshape.

@shoumikhin
shoumikhin force-pushed the modelopt-int4-weight-only branch from ba7429b to bb603c4 Compare November 25, 2026 23:45
@shoumikhin shoumikhin changed the title fix(dynamo): INT4 weight-only as 4-bit constants (ModelOpt, TorchAO), INT4 refit, error on wide group-wise int8 fix(dynamo): INT4 weight-only as 4-bit constants (ModelOpt, TorchAO), INT4 refit, wide group-wise int8 runs in PyTorch Nov 25, 2026
@shoumikhin
shoumikhin marked this pull request as ready for review November 25, 2026 23:45
@shoumikhin
shoumikhin force-pushed the modelopt-int4-weight-only branch 2 times, most recently from 2655155 to e34222f Compare November 26, 2026 05:18
…ants

A Linear quantized with ModelOpt's INT4_BLOCKWISE_WEIGHT_ONLY_CFG failed to
compile: the quantize converter accepted only 8-bit quantization. TensorRT
has no INT4 quantize for activations; it keeps 4-bit weights only when they
arrive as an INT4 constant in front of an IDequantizeLayer.

When the input of an INT4 quantize is a constant weight, the converter now
quantizes it at conversion time and adds only a dequantize layer:

- The rounding follows ModelOpt's CUDA fake quantization: it multiplies
  the weight by the factor 7 / amax and rounds, so ties round the same way.
  Values past amax clamp to the INT4 range, and to -8 only without
  narrow_range, which the converter now passes on, given by position or by
  keyword. A block whose amax is 0, or whose scale amax / 7 rounds to 0 in
  the dequantize type, quantizes to 0 with a scale of 1.
- ModelOpt passes the weight as rows of one block each and reshapes the
  result back. The INT4 constant takes the shape of that reshape, with one
  scale per block along the last dim, because TensorRT fuses the dequantize
  into the matmul only when the constant has the matmul weight's shape. If
  the reshape is there but its shape cannot be read, the quantize runs in
  PyTorch instead of quietly building the slower block-row form. When ModelOpt
  pads the last dim to whole blocks, a slice follows the reshape, and
  TensorRT does not fuse the dequantize.
- The scale and the dequantize output use the weight's type. With a float32
  scale TensorRT dequantizes the whole weight into scratch memory first. The
  scale rounding puts results within one bf16 or fp16 step of ModelOpt's.
- TensorRT fails to build many refittable engines (immutable_weights=False)
  that have a 16-bit INT4 dequantize. In a refittable engine the converter
  dequantizes INT4 weights in float32 and casts to the weight's type, as the
  TorchAO INT4 path does. TensorRT does not fuse that dequantize into the
  matmul, and refit itself does not handle INT4 weights yet, so the
  troubleshooting guide asks for immutable_weights=True. A weight near the
  largest value of its type, where 7 times the rounded scale would be
  infinity, also dequantizes in float32.
- TensorRT INT4 is signed, so the quantize of an unsigned INT4 quantizer
  runs in PyTorch instead of being quantized as signed.
- Only matmul weights take this path. ModelOpt pads a conv kernel's last dim
  to a whole block, which would make a 3x3 conv weight many times larger, so
  their quantize runs in PyTorch and TensorRT gets the 16-bit weight. So does
  an amax that is not one value per block row, instead of scaling the wrong
  rows.
- An INT4 quantize of a weight that is not a constant, as under
  torch.compile, runs in PyTorch too.
- INT4 constants pack two values per byte along the last dim, so a weight
  with an odd last dim runs its quantize in PyTorch as well. A per-channel
  INT4 quantizer on a Linear with an odd in_features makes one.
- A capability validator on the quantize converter finds these cases when
  the graph is partitioned, so the rest of the model still compiles.
- The weight is quantized in one float32 copy, not two.

Unit tests check the rounding against ModelOpt's on normally distributed
weights, that a block with an amax below 2**-24 quantizes to 0 with a scale
of 1 while one just above it does not, that a refittable engine and a weight
near 65504 in fp16 get the float32 dequantize, that the converter reads
narrow_range given by position or by keyword, and which weights run in
PyTorch. ModelOpt model tests check that a Linear's quantize runs in
TensorRT, also in a refittable engine, and that its engine is smaller than
the engine of the unquantized layer by more than half the size of the 16-bit
weights. They check that a convolution and an unsigned quantizer run their
quantize in PyTorch and match ModelOpt.

The troubleshooting guide now recommends INT4 for weight-only quantization,
shows how to leave convolutions out of the config, says when TensorRT
does not fuse the INT4 dequantize, and says that INT8
weight-only quantization does not make the engine smaller: TensorRT keeps
INT8 weights only for a matmul whose activations are INT8 too. It also
notes a TensorRT 11.4 issue with INT4 weights in some deeper networks, and
how to avoid it. The dequantize_affine docstring said the opposite for INT8
and now agrees. Its TorchAO INT4 comments said TensorRT needs an FP32
dequantize output, which contradicts the bf16 output used for ModelOpt
weights; they now say what the code does, and the measured reason for FP32
there: a bf16 output fails to build in a refittable engine.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
…in PyTorch

The torchao dequantize_affine converter treats every group-wise int8 weight as
INT4 and packs it into 4-bit nibbles. A weight that uses the wider int8 range
is then silently changed. torchao makes such weights, for example with
IntxWeightOnlyConfig for int8 or int6 and a per-group granularity. On an A100
the output of such a layer has a cosine similarity close to 0 with PyTorch.
TensorRT's group-wise INT8 dequantize with a constant scale, which these
weights have, is no alternative either: it builds, but the output is wrong,
with huge values and some NaN.

The converter now has a capability validator. A dequantize_affine whose
group-wise int8 weights hold values outside -8..7 runs in PyTorch, and the
rest of the model still compiles. For a small torchao IntxWeightOnlyConfig
int8 model, both dequantizes now run in PyTorch, and the output matches
PyTorch in bf16 and float32.

The validator reads the weight's values outside fake mode, because
torch.compile partitions the graph in fake mode.

A unit test checks the validator at the edges of -8..7, in fake mode and
without TorchAO. A TorchAO test checks that such a dequantize runs in PyTorch
and that the output matches.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
The torchao dequantize_affine converter always gave the group-wise INT4
dequantize a float32 output, whatever output dtype the graph asked for. A graph
that asks for bfloat16 then fails to build, because the matmul that uses the
weight gets a bfloat16 input and a float32 weight:

    IMatrixMultiplyLayer must have same input types

The INT4 example avoided this by asking for float32 and casting back. That
works, but TensorRT then keeps a full high-precision copy of the weights in
activation memory instead of dequantizing inside the matmul.

The converter now dequantizes the way torchao does: it multiplies in the
promoted type of the scale dtype and the requested output dtype, then casts to
the output dtype. A float64 scale is used in float32, and a float64 output
stays float32, as before, since TensorRT has no float64. TensorRT builds a
blocked INT4 dequantize only with the scale in its output type, so the scale,
constant or run-time, is cast to that dtype too.

With bfloat16 scales and a bfloat16 output there is no cast left, and
TensorRT can fuse the dequantize into the matmul. A graph that asks for
float32 with a constant scale builds the same engine as before. A
refittable engine still dequantizes in float32 and casts, because TensorRT
fails to build many of them with a 16-bit INT4 dequantize. The INT4
example and the user guide now dequantize straight to the activation dtype.

Measured on an A100 with a bfloat16 gated MLP (4096 to 14336 to 4096), INT4
group size 128:

| tokens | bfloat16 weights | INT4 before | INT4 after |
|---|---|---|---|
| 1 | 0.24 ms | 0.78 ms | 0.27 ms |
| 128 | 0.30 ms | 0.88 ms | 0.42 to 0.75 ms |

At 128 tokens TensorRT sometimes keeps the dequantize out of the matmul,
which gives the slower end of the range. Activation memory drops from 336 MiB
to 0.1 MiB at 1 token. Outputs match PyTorch.
A run-time scale in bfloat16 or float16, and a model quantized with torchao's
own INT4 dequantize in bfloat16, now build too.

This change depends on the one that runs group-wise int8 weights outside
-8..7 in PyTorch. Without it, such weights in a 16-bit graph would now build
into a wrong engine instead of failing.

Most new tests fail without this change. Some cases also passed before and
check what must keep working: a float32 output (it built before too), and
NumPy scales.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
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>
…word

The partitioners keep a quantized_decomposed quantize together with the
dequantizes that read it. To find that quantize they read the dequantize's
first positional argument. A graph from torch.fx.symbolic_trace keeps
arguments the way the model passed them, so a dequantize called as

    dequantize_per_tensor(input=q, scale=0.1, zero_point=0, ...)

has no positional arguments. Reading the first one raised IndexError. The
hierarchical partitioner reads it for every node, so it failed on such a
graph.

The input is now read by position or by keyword. The dequantize's converter
still reads its arguments by position only, so its validator refuses this
node and it runs in PyTorch, as it did before quantize and dequantize
conversion was added.

A hierarchical partitioning test traces such a model with
torch.fx.symbolic_trace and checks that it partitions and that the
dequantize runs in PyTorch. It raises IndexError without this change.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
@shoumikhin
shoumikhin force-pushed the modelopt-int4-weight-only branch from e34222f to c465b15 Compare November 26, 2026 06:40

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: conversion Issues re: Conversion stage component: converters Issues re: Specific op converters component: core Issues re: The core compiler component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: tests Issues re: Tests documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants