Skip to content

Commit 192b92f

Browse files
committed
Add AffineQuantizedTensor based workflow doc and examples
Summary: att Test Plan: . Reviewers: Subscribers: Tasks: Tags:
1 parent 42c2376 commit 192b92f

File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed

torchao/quantization/README.md

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,120 @@ model = torch.compile(model, mode='max-autotune')
164164
model(input)
165165
```
166166

167+
## Affine Quantization
168+
Affine quantization refers to the type of quantization that maps from floating point numbers to quantized numbers (typically integer) with an affine transformation, i.e.: `quantized_val = float_val / scale + zero_point` where `scale` and `zero_point` are quantization parameters for some granularity and based on some data.
169+
170+
### Quantization Primitives
171+
We used to have different quantize and dequantize operators for quantization with different granularities. But in the end these can all be expressed with a `block_size` argument with different settings, so we unified existing quant primitives to `choose_qparams_affine`, `quantize_affine` and `dequantize_affine` that can represent symmetric/asymmetric per tensor/channel/token/channel_group quantization, this can be used to implement the unified quantized tensor subclass.
172+
173+
### Quantized Tensor Subclass
174+
We also have a unified quantized tensor subclass that implements how to get a quantized tensor from floating point tensor and what does it mean to call linear ops on an instance of the tensor, e.g. `F.linear` and `aten.addmm`, with this we could dispatch to different operators (e.g. `int4mm` op) based on device (cpu, cuda) and quantization settings (`int4`, `int8`) and also packing formats (e.g. format optimized for cpu int4 mm kernel)
175+
176+
### Quantization Flow
177+
What we need to do afterwards is roughly the following
178+
179+
```
180+
from torchao.dtypes.aqt import to_aq
181+
def apply_int8wo_quant(weight):
182+
mapping_type = MappingType.SYMMETRIC
183+
target_dtype = torch.int8
184+
eps = torch.finfo(torch.float32).eps
185+
zero_point_dtype = torch.int64
186+
block_size = (1, weight.shape[1])
187+
return to_aq(weight, mapping_type, block_size, target_dtype, eps=eps, zero_point_dtype=zero_point_dtype)
188+
189+
for n, m in model.named_modules():
190+
# or use some filter_fn
191+
if isinstance(m, torch.nn.Linear):
192+
# optional filtering for module name, shape etc.
193+
m.weight = nn.Parameter(apply_int8wo_quant(m.weight))
194+
# note: quantization for activation need to be applied after the weight quantization
195+
# quantization activation (needed by dynamic quantization)
196+
# input_quant_func = apply_int8wo_quant # specify how input activation is quantized
197+
# m.weight = nn.Parameter(to_laq(m.weight, input_quant_func))
198+
```
199+
The model/tensor subclass should also be compatible with AOTI and torch.export, currently we can support
200+
`torch.export.export` and `torch.aot_compile` with the following workaround:
201+
```
202+
from torchao.quantization.utils import unwrap_tensor_subclass
203+
m_unwrapped = unwrap_tensor_subclass(m)
204+
205+
206+
# export
207+
m = torch.export.export(m_unwrapped, example_inputs).module()
208+
209+
# aot_compile
210+
torch._export.aot_compile(m_unwrapped, example_inputs)
211+
```
212+
213+
But we expect this will be integrated into the export path by default in the future.
214+
215+
216+
### Example
217+
Let's use int4 weight only quantization that's targeting tinygemm int4 weight only quantized matmul
218+
as an example:
219+
```python
220+
import torch
221+
from torchao.quantization.quant_primitives import MappingType, ZeroPointDomain
222+
from torchao.dtypes import to_aq
223+
from torch._inductor.runtime.runtime_utils import do_bench_gpu
224+
import copy
225+
from torchao.quantization.quant_api import (
226+
quantize,
227+
get_apply_int4wo_quant,
228+
)
229+
230+
class ToyLinearModel(torch.nn.Module):
231+
def __init__(self, m=64, n=32, k=64):
232+
super().__init__()
233+
self.linear1 = torch.nn.Linear(m, n, bias=False)
234+
self.linear2 = torch.nn.Linear(n, k, bias=False)
235+
236+
def example_inputs(self, batch_size=1, dtype=torch.float32, device="cpu"):
237+
return (torch.randn(batch_size, self.linear1.in_features, dtype=dtype, device=device),)
238+
239+
def forward(self, x):
240+
x = self.linear1(x)
241+
x = self.linear2(x)
242+
return x
243+
244+
# weight settings
245+
groupsize = 32
246+
247+
dtype = torch.bfloat16
248+
m = ToyLinearModel(1024, 1024, 1024).eval().to(dtype).to("cuda")
249+
m_bf16 = copy.deepcopy(m)
250+
example_inputs = m.example_inputs(dtype=dtype, device="cuda")
251+
252+
m_bf16 = torch.compile(m_bf16, mode='max-autotune')
253+
# apply int4 weight only quant (compatible with tinygemm int4 weight only quant mm kernel in torchao)
254+
m = quantize(m, get_apply_int4wo_quant(groupsize=groupsize))
255+
256+
torch._inductor.config.force_fuse_int_mm_with_mul = True
257+
torch._inductor.config.use_mixed_mm = True
258+
259+
# temporary workaround for tensor subclass + torch.compile
260+
from torchao.quantization.utils import unwrap_tensor_subclass
261+
m = unwrap_tensor_subclass(m)
262+
# compile the model to improve performance
263+
m = torch.compile(m, mode='max-autotune')
264+
265+
# benchmark to see the speedup
266+
from torchao.utils import benchmark_model
267+
268+
num_runs = 100
269+
torch._dynamo.reset()
270+
bf16_time = benchmark_model(m_bf16, num_runs, example_inputs[0])
271+
print(f"bf16 mean time: {bf16_time}")
272+
int4_time = benchmark_model(m, num_runs, example_inputs[0])
273+
print(f"int4 weight only quantized mean time: {int4_time}")
274+
print(f"speedup: {bf16_time / int4_time}")
275+
276+
# output (1xA100 GPU machine)
277+
bf16 mean time: 71.457685546875
278+
int4 weight only quantized mean time: 31.4580908203125
279+
speedup: 2.2715200981216173
280+
```
167281

168282
## Notes
169283

0 commit comments

Comments
 (0)