quant_utils.py 6.82 KB
Newer Older
helloyongyang's avatar
helloyongyang committed
1
2
3
4
5
6
7
8
9
10
import torch
from qtorch.quant import float_quantize


class BaseQuantizer(object):
    def __init__(self, bit, symmetric, granularity, **kwargs):
        self.bit = bit
        self.sym = symmetric
        self.granularity = granularity
        self.kwargs = kwargs
Dongz's avatar
Dongz committed
11
12
13
        if self.granularity == "per_group":
            self.group_size = self.kwargs["group_size"]
        self.calib_algo = self.kwargs.get("calib_algo", "minmax")
helloyongyang's avatar
helloyongyang committed
14
15

    def get_tensor_range(self, tensor):
Dongz's avatar
Dongz committed
16
        if self.calib_algo == "minmax":
helloyongyang's avatar
helloyongyang committed
17
            return self.get_minmax_range(tensor)
Dongz's avatar
Dongz committed
18
        elif self.calib_algo == "mse":
helloyongyang's avatar
helloyongyang committed
19
20
            return self.get_mse_range(tensor)
        else:
Dongz's avatar
Dongz committed
21
            raise ValueError(f"Unsupported calibration algorithm: {self.calib_algo}")
helloyongyang's avatar
helloyongyang committed
22
23

    def get_minmax_range(self, tensor):
Dongz's avatar
Dongz committed
24
        if self.granularity == "per_tensor":
helloyongyang's avatar
helloyongyang committed
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
            max_val = torch.max(tensor)
            min_val = torch.min(tensor)
        else:
            max_val = tensor.amax(dim=-1, keepdim=True)
            min_val = tensor.amin(dim=-1, keepdim=True)
        return (min_val, max_val)

    def get_mse_range(self, tensor):
        raise NotImplementedError

    def get_qparams(self, tensor_range, device):
        min_val, max_val = tensor_range[0], tensor_range[1]
        qmin = self.qmin.to(device)
        qmax = self.qmax.to(device)
        if self.sym:
            abs_max = torch.max(max_val.abs(), min_val.abs())
            abs_max = abs_max.clamp(min=1e-5)
            scales = abs_max / qmax
            zeros = torch.tensor(0.0)
        else:
            scales = (max_val - min_val).clamp(min=1e-5) / (qmax - qmin)
            zeros = (qmin - torch.round(min_val / scales)).clamp(qmin, qmax)
        return scales, zeros, qmax, qmin

    def reshape_tensor(self, tensor, allow_padding=False):
Dongz's avatar
Dongz committed
50
        if self.granularity == "per_group":
helloyongyang's avatar
helloyongyang committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
            t = tensor.reshape(-1, self.group_size)
        else:
            t = tensor
        return t

    def restore_tensor(self, tensor, shape):
        if tensor.shape == shape:
            t = tensor
        else:
            t = tensor.reshape(shape)
        return t

    def get_tensor_qparams(self, tensor):
        tensor = self.reshape_tensor(tensor)
        tensor_range = self.get_tensor_range(tensor)
        scales, zeros, qmax, qmin = self.get_qparams(tensor_range, tensor.device)
        return tensor, scales, zeros, qmax, qmin

    def fake_quant_tensor(self, tensor):
        org_shape = tensor.shape
        org_dtype = tensor.dtype
        tensor, scales, zeros, qmax, qmin = self.get_tensor_qparams(tensor)
        tensor = self.quant_dequant(tensor, scales, zeros, qmax, qmin)
        tensor = self.restore_tensor(tensor, org_shape).to(org_dtype)
        return tensor

    def real_quant_tensor(self, tensor):
        org_shape = tensor.shape
        tensor, scales, zeros, qmax, qmin = self.get_tensor_qparams(tensor)
        tensor = self.quant(tensor, scales, zeros, qmax, qmin)
        tensor = self.restore_tensor(tensor, org_shape)
Dongz's avatar
Dongz committed
82
        if self.sym:
helloyongyang's avatar
helloyongyang committed
83
84
85
86
87
88
89
            zeros = None
        return tensor, scales, zeros


class IntegerQuantizer(BaseQuantizer):
    def __init__(self, bit, symmetric, granularity, **kwargs):
        super().__init__(bit, symmetric, granularity, **kwargs)
Dongz's avatar
Dongz committed
90
91
92
        if "int_range" in self.kwargs:
            self.qmin = self.kwargs["int_range"][0]
            self.qmax = self.kwargs["int_range"][1]
helloyongyang's avatar
helloyongyang committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        else:
            if self.sym:
                self.qmin = -(2 ** (self.bit - 1))
                self.qmax = 2 ** (self.bit - 1) - 1
            else:
                self.qmin = 0.0
                self.qmax = 2**self.bit - 1

        self.qmin = torch.tensor(self.qmin)
        self.qmax = torch.tensor(self.qmax)
        self.dst_nbins = 2**bit

    def quant(self, tensor, scales, zeros, qmax, qmin):
        tensor = torch.clamp(torch.round(tensor / scales) + zeros, qmin, qmax)
        return tensor

    def dequant(self, tensor, scales, zeros):
        tensor = (tensor - zeros) * scales
        return tensor

Dongz's avatar
Dongz committed
113
114
115
116
117
118
119
120
    def quant_dequant(
        self,
        tensor,
        scales,
        zeros,
        qmax,
        qmin,
    ):
helloyongyang's avatar
helloyongyang committed
121
122
123
124
125
126
127
128
        tensor = self.quant(tensor, scales, zeros, qmax, qmin)
        tensor = self.dequant(tensor, scales, zeros)
        return tensor


class FloatQuantizer(BaseQuantizer):
    def __init__(self, bit, symmetric, granularity, **kwargs):
        super().__init__(bit, symmetric, granularity, **kwargs)
Dongz's avatar
Dongz committed
129
130
131
132
        assert self.bit in ["e4m3", "e5m2"], f"Unsupported bit configuration: {self.bit}"
        assert self.sym

        if self.bit == "e4m3":
helloyongyang's avatar
helloyongyang committed
133
134
135
            self.e_bits = 4
            self.m_bits = 3
            self.fp_dtype = torch.float8_e4m3fn
Dongz's avatar
Dongz committed
136
        elif self.bit == "e5m2":
helloyongyang's avatar
helloyongyang committed
137
138
139
140
            self.e_bits = 5
            self.m_bits = 2
            self.fp_dtype = torch.float8_e5m2
        else:
Dongz's avatar
Dongz committed
141
            raise ValueError(f"Unsupported bit configuration: {self.bit}")
helloyongyang's avatar
helloyongyang committed
142
143
144
145
146
147
148
149
150

        finfo = torch.finfo(self.fp_dtype)
        self.qmin, self.qmax = finfo.min, finfo.max

        self.qmax = torch.tensor(self.qmax)
        self.qmin = torch.tensor(self.qmin)

    def quant(self, tensor, scales, zeros, qmax, qmin):
        scaled_tensor = tensor / scales + zeros
Dongz's avatar
Dongz committed
151
        scaled_tensor = torch.clip(scaled_tensor, self.qmin.cuda(), self.qmax.cuda())
helloyongyang's avatar
helloyongyang committed
152
        org_dtype = scaled_tensor.dtype
Dongz's avatar
Dongz committed
153
        q_tensor = float_quantize(scaled_tensor.float(), self.e_bits, self.m_bits, rounding="nearest")
helloyongyang's avatar
helloyongyang committed
154
155
156
157
158
159
160
161
162
163
164
165
166
        q_tensor.to(org_dtype)
        return q_tensor

    def dequant(self, tensor, scales, zeros):
        tensor = (tensor - zeros) * scales
        return tensor

    def quant_dequant(self, tensor, scales, zeros, qmax, qmin):
        tensor = self.quant(tensor, scales, zeros, qmax, qmin)
        tensor = self.dequant(tensor, scales, zeros)
        return tensor


Dongz's avatar
Dongz committed
167
if __name__ == "__main__":
helloyongyang's avatar
helloyongyang committed
168
    weight = torch.randn(4096, 4096, dtype=torch.bfloat16).cuda()
Dongz's avatar
Dongz committed
169
    quantizer = IntegerQuantizer(4, False, "per_group", group_size=128)
helloyongyang's avatar
helloyongyang committed
170
171
172
173
    q_weight = quantizer.fake_quant_tensor(weight)
    print(weight)
    print(q_weight)
    print(f"cosine = {torch.cosine_similarity(weight.view(1, -1).to(torch.float64), q_weight.view(1, -1).to(torch.float64))}")
Dongz's avatar
Dongz committed
174

helloyongyang's avatar
helloyongyang committed
175
176
177
178
179
180
    realq_weight, scales, zeros = quantizer.real_quant_tensor(weight)
    print(f"realq_weight = {realq_weight}, {realq_weight.shape}")
    print(f"scales = {scales}, {scales.shape}")
    print(f"zeros = {zeros}, {zeros.shape}")

    weight = torch.randn(8192, 4096, dtype=torch.bfloat16).cuda()
Dongz's avatar
Dongz committed
181
    quantizer = FloatQuantizer("e4m3", True, "per_channel")
helloyongyang's avatar
helloyongyang committed
182
183
184
185
186
187
188
189
190
    q_weight = quantizer.fake_quant_tensor(weight)
    print(weight)
    print(q_weight)
    print(f"cosine = {torch.cosine_similarity(weight.view(1, -1).to(torch.float64), q_weight.view(1, -1).to(torch.float64))}")

    realq_weight, scales, zeros = quantizer.real_quant_tensor(weight)
    print(f"realq_weight = {realq_weight}, {realq_weight.shape}")
    print(f"scales = {scales}, {scales.shape}")
    print(f"zeros = {zeros}")