test_fake_quantization.py 2.47 KB
Newer Older
aiss's avatar
aiss committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'''Copyright The Microsoft DeepSpeed Team'''

import torch
import pytest
from deepspeed.accelerator import get_accelerator
from deepspeed.ops import op_builder

quantizer_cuda_module = None


def allclose(x, y):
    assert x.dtype == y.dtype
    rtol, atol = {torch.float32: (2e-2, 5e-3), torch.float16: (2e-2, 5e-3)}[x.dtype]
    return torch.allclose(x, y, rtol=rtol, atol=atol)


def quantize_dequantize_ref(inputs, bit, num_groups=1):
    # quantize
    q_range = 2**bit
    input_flat = inputs.float().reshape(num_groups, -1).contiguous()
    input_flat = torch.nan_to_num(input_flat, nan=0.0)
    input_min = input_flat.amin(-1, keepdim=True)
    input_max = input_flat.amax(-1, keepdim=True)

    scale = q_range / (2 * torch.max(input_min.abs(), input_max.abs() + 1e-5))
    input_flat = (input_flat * scale).round().clamp(-q_range // 2, q_range // 2 - 1)
    # dequantize
    dequant_flat = torch.t(input_flat.to(torch.int8)) / scale.view(-1).to(torch.float16)
    return torch.t(dequant_flat).reshape(inputs.shape)


def run_quant_dequant(inputs, groups, bits):
    global quantizer_cuda_module

    if quantizer_cuda_module is None:
        quantizer_cuda_module = op_builder.QuantizerBuilder().load()
    return quantizer_cuda_module.ds_quantize_fp16(inputs, groups, bits)


@pytest.mark.inference_ops
@pytest.mark.parametrize("tensor_shape", [(16, 4096), (128, 256)])
# Test with two tensor shapes as (16, 4096) and (128, 256).
@pytest.mark.parametrize("groups", [1, 16])
# Test with number of quant groups as 1 and 16.
# Note that we have an explicit boundary for groups as ((size / groups) - 1) / 4096 + 1) <= MAX_REG.
def test_fake_quant_dequant(tensor_shape, groups):

    input_tensor = torch.rand((tensor_shape),
                              dtype=torch.float16).to(get_accelerator().device_name())

    # 8-bit quantization.
    ref_input_8bit = input_tensor.clone().detach()
    ds_input_8bit = input_tensor.clone().detach()
    ref_out_8bit = quantize_dequantize_ref(ref_input_8bit, 8, groups)
    # run_quant_dequant will do quantize then dequantize, and return the dequantized value.
    ds_out_8bit = run_quant_dequant(ds_input_8bit, groups, 8)
    assert (allclose(ds_out_8bit, ref_out_8bit))

    # 4-bit quantization.
    ref_input_4bit = input_tensor.clone().detach()
    ds_input_4bit = input_tensor.clone().detach()
    ref_out_4bit = quantize_dequantize_ref(ref_input_4bit, 4, groups)
    ds_out_4bit = run_quant_dequant(ds_input_4bit, groups, 4)
    assert (allclose(ds_out_4bit, ref_out_4bit))