Repository navigation
fix(dynamo): INT4 weight-only as 4-bit constants (ModelOpt, TorchAO), INT4 refit, wide group-wise int8 runs in PyTorch - #5061
shoumikhin wants to merge 5 commits into
Conversation
948e371 to
1848444
Compare
a46025b to
ba7429b
Compare
micwill755
left a comment
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
Raising here fails the whole compile. Could this check go in the dequantize validator instead, so that op runs in PyTorch?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
ba7429b to
bb603c4
Compare
c465b15 to
662fe39
Compare
…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 the quantize has other users too, or reshapes to different shapes, the constant keeps the block-row shape, which gives the same values unfused. The validator runs again on each engine's part of the graph, where users outside the engine become its output. Since only a reshape whose shape is unknown or not a matmul weight's sends the quantize to PyTorch, a quantize that partitioning gives to TensorRT also converts there. 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. So does every INT4 quantize on TensorRT-RTX for Turing (SM 7.5), which cannot dequantize INT4 into a matmul. - 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. 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, which weights run in PyTorch, and that a quantize whose reshape is in another engine keeps the block-row shape. 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 <[email protected]>
…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. On TensorRT-RTX for Turing (SM 7.5), which cannot dequantize INT4 into a matmul, it sends every group-wise INT4 dequantize to PyTorch. A unit test checks the validator at the edges of -8..7, in fake mode and without TorchAO, and on TensorRT-RTX for Turing. A TorchAO test checks that such a dequantize runs in PyTorch and that the output matches. Signed-off-by: Anthony Shoumikhin <[email protected]>
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 <[email protected]>
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 <[email protected]>
…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, in the same block as its quantize. It raises
IndexError without this change.
Signed-off-by: Anthony Shoumikhin <[email protected]>
662fe39 to
c392e7b
Compare
What is wrong today
INT4 weight-only quantization keeps weights in 4 bits and activations in bf16 or fp16.
mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFGfails to compile. The quantize converter accepts only 8-bit.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.
torch.fx.symbolic_traceleaves it) crashed the hierarchical partitioner. It now runs in PyTorch.A100, bf16 gated MLP (4096 to 14336 to 4096), TorchAO INT4, group 128:
ModelOpt INT4 builds the same fused layers and runs as fast.
Tests
Run 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.
Not run: other GPUs, TensorRT-RTX, Windows.