|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD 3-Clause license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import unittest |
| 8 | + |
| 9 | +import torch |
| 10 | + |
| 11 | +from torchao.prototype.quantization.gguf import ( |
| 12 | + GGUFQuantizedTensor, |
| 13 | + GGUFWeightOnlyConfig, |
| 14 | +) |
| 15 | +from torchao.quantization import quantize_ |
| 16 | +from torchao.quantization.quant_primitives import choose_qparams_gguf |
| 17 | +from torchao.quantization.utils import compute_error |
| 18 | + |
| 19 | + |
| 20 | +class TestGGUFQuantization(unittest.TestCase): |
| 21 | + def setUp(self): |
| 22 | + torch.manual_seed(123) |
| 23 | + self.input = torch.randn(2, 256, dtype=torch.float32) |
| 24 | + self.n_blocks_per_superblock = 8 |
| 25 | + self.block_size = (1, 32) |
| 26 | + self.dtype = torch.uint4 |
| 27 | + |
| 28 | + def test_choose_qparams_gguf(self): |
| 29 | + ( |
| 30 | + super_block_scale_scale, |
| 31 | + super_block_min_scale, |
| 32 | + quantized_block_scale, |
| 33 | + quantized_block_min, |
| 34 | + ) = choose_qparams_gguf(self.input, self.block_size, self.dtype) |
| 35 | + |
| 36 | + assert super_block_scale_scale.shape, (2, 8) |
| 37 | + assert super_block_min_scale.shape, (2, 8) |
| 38 | + assert quantized_block_scale.shape, (2, 32) |
| 39 | + |
| 40 | + def test_gguf_quantized_tensor_from_float(self): |
| 41 | + gqt = GGUFQuantizedTensor.from_float( |
| 42 | + self.input, |
| 43 | + self.n_blocks_per_superblock, |
| 44 | + self.dtype, |
| 45 | + ) |
| 46 | + |
| 47 | + dequant = gqt.dequantize() |
| 48 | + |
| 49 | + sqnr = compute_error(dequant, self.input) |
| 50 | + self.assertGreater(sqnr, 30) |
| 51 | + |
| 52 | + def test_quantize_api(self): |
| 53 | + m = torch.nn.Sequential(torch.nn.Linear(256, 64)) |
| 54 | + quantize_(m, GGUFWeightOnlyConfig()) |
| 55 | + assert type(m[0].weight) == GGUFQuantizedTensor |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + unittest.main() |
0 commit comments