nickfraser commited on
Commit
eb5a5f6
1 Parent(s): d67ece3

[math_model/test] Added "QOp" implementation and basic tests.

Browse files
Files changed (3) hide show
  1. math_model.py +69 -11
  2. test_quant_conv2d.py +34 -0
  3. test_quant_linear.py +31 -0
math_model.py CHANGED
@@ -14,11 +14,11 @@ def dequantize(tensor, scale, zero_point):
14
 
15
 
16
  class QuantLinear(nn.Module):
17
- def __init__(self, quant_param):
18
  super().__init__()
19
  mul_factor = torch.tensor(quant_param['smoothquant_mul']).view(quant_param['smoothquant_mul_shape'])
20
  self.register_buffer('mul_factor', mul_factor)
21
- self.linear = nn.Linear(128, 128)
22
  weight_scale = torch.tensor(quant_param['weight_scale']).view(quant_param['weight_scale_shape'])
23
  weight_zp = torch.tensor(quant_param['weight_zp']).view(quant_param['weight_zp_shape'])
24
  input_scale = torch.tensor(quant_param['input_scale']).view(quant_param['input_scale_shape'])
@@ -28,10 +28,9 @@ class QuantLinear(nn.Module):
28
  self.register_buffer('input_scale', input_scale)
29
  self.register_buffer('input_zp', input_zp)
30
 
31
- def forward(self, x):
 
32
  scaled_x = x * self.mul_factor
33
- # With an integer conv kernel, if the weight zero point is not zero,
34
- # it is required an extra input channel that is equal to the per-channel zero point of the weights
35
  quant_weight = quantize(self.linear.weight, self.weight_scale, self.weight_zp, is_asym=True)
36
  quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False)
37
  dequantized_weight = dequantize(quant_weight, self.weight_scale, self.weight_zp)
@@ -39,12 +38,37 @@ class QuantLinear(nn.Module):
39
  out = torch.nn.functional.linear(dequantized_input, dequantized_weight, self.linear.bias)
40
  return out
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  class QuantConv2d(nn.Module):
43
- def __init__(self, quant_param):
44
  super().__init__()
45
  mul_factor = torch.tensor(quant_param['smoothquant_mul']).view(quant_param['smoothquant_mul_shape'])
46
  self.register_buffer('mul_factor', mul_factor)
47
- self.conv2d = nn.Conv2d(128, 128, 3)
48
  weight_scale = torch.tensor(quant_param['weight_scale']).view(quant_param['weight_scale_shape'])
49
  weight_zp = torch.tensor(quant_param['weight_zp']).view(quant_param['weight_zp_shape'])
50
  input_scale = torch.tensor(quant_param['input_scale']).view(quant_param['input_scale_shape'])
@@ -54,13 +78,47 @@ class QuantConv2d(nn.Module):
54
  self.register_buffer('input_scale', input_scale)
55
  self.register_buffer('input_zp', input_zp)
56
 
57
- def forward(self, x):
 
58
  scaled_x = x * self.mul_factor
59
- # With an integer conv kernel, if the weight zero point is not zero,
60
- # it is required an extra input channel that is equal to the per-channel zero point of the weights
61
- quant_weight = quantize(self.linear.weight, self.weight_scale, self.weight_zp, is_asym=True)
62
  quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False)
63
  dequantized_weight = dequantize(quant_weight, self.weight_scale, self.weight_zp)
64
  dequantized_input = dequantize(quant_input, self.input_scale, self.input_zp)
65
  out = torch.nn.functional.conv2d(dequantized_input, dequantized_weight, self.conv2d.bias)
66
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
 
16
  class QuantLinear(nn.Module):
17
+ def __init__(self, in_ch, out_ch, quant_param):
18
  super().__init__()
19
  mul_factor = torch.tensor(quant_param['smoothquant_mul']).view(quant_param['smoothquant_mul_shape'])
20
  self.register_buffer('mul_factor', mul_factor)
21
+ self.linear = nn.Linear(in_ch, out_ch)
22
  weight_scale = torch.tensor(quant_param['weight_scale']).view(quant_param['weight_scale_shape'])
23
  weight_zp = torch.tensor(quant_param['weight_zp']).view(quant_param['weight_zp_shape'])
24
  input_scale = torch.tensor(quant_param['input_scale']).view(quant_param['input_scale_shape'])
 
28
  self.register_buffer('input_scale', input_scale)
29
  self.register_buffer('input_zp', input_zp)
30
 
31
+ # I.e., "fake quantization"
32
+ def qdq_forward(self, x):
33
  scaled_x = x * self.mul_factor
 
 
34
  quant_weight = quantize(self.linear.weight, self.weight_scale, self.weight_zp, is_asym=True)
35
  quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False)
36
  dequantized_weight = dequantize(quant_weight, self.weight_scale, self.weight_zp)
 
38
  out = torch.nn.functional.linear(dequantized_input, dequantized_weight, self.linear.bias)
39
  return out
40
 
41
+ # Accelerated version
42
+ def qop_forward(self, x):
43
+ # With an integer linear kernel, if the weight zero point is not zero,
44
+ # A correction term must be calculated to correct the output.
45
+ # The correction term calculated as follows:
46
+ # - sum the input tensor across the dot-product dimentions: (e.g., `torch.sum(quant_input, dim=-1)`)
47
+ # - multiply this sum with every weight zero-point (e.g., `torch.sum(quant_input, dim=-1) * self.weight_zp`
48
+ # - Subtract from previous output (e.g., `quant_output -= torch.sum(quant_input, dim=-1) * self.weight_zp`)
49
+ # - All other code is just to make sure the broadcasting semantics work correctly
50
+ scaled_x = x * self.mul_factor
51
+ quant_weight = quantize(self.linear.weight, self.weight_scale, self.weight_zp, is_asym=True).to(torch.uint8)
52
+ quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False).to(torch.int8)
53
+ quant_output = torch.nn.functional.linear(quant_input.to(torch.float32), quant_weight.to(torch.float32), None).to(torch.int32) # Convert inputs to FP32 to avoid F.linear quantizing the output to int8
54
+ correction = torch.sum(quant_input, dim=-1).to(torch.int32).unsqueeze(-1) * (-self.weight_zp).to(torch.uint8).view([1]*(quant_input.ndim-1) + [self.weight_zp.nelement()]) # Correct for weight zero-point
55
+ quant_output = quant_output + correction
56
+ output = dequantize(quant_output, (self.weight_scale * self.input_scale).view([1]*(quant_output.ndim-1) + [(self.weight_scale * self.input_scale).nelement()]), 0.0)
57
+ output += self.linear.bias
58
+ return output
59
+
60
+ def forward(self, x, qop=False):
61
+ if qop:
62
+ return self.qop_forward(x)
63
+ else:
64
+ return self.qdq_forward(x)
65
+
66
  class QuantConv2d(nn.Module):
67
+ def __init__(self, in_ch, out_ch, kernel_size, quant_param):
68
  super().__init__()
69
  mul_factor = torch.tensor(quant_param['smoothquant_mul']).view(quant_param['smoothquant_mul_shape'])
70
  self.register_buffer('mul_factor', mul_factor)
71
+ self.conv2d = nn.Conv2d(in_ch, out_ch, kernel_size)
72
  weight_scale = torch.tensor(quant_param['weight_scale']).view(quant_param['weight_scale_shape'])
73
  weight_zp = torch.tensor(quant_param['weight_zp']).view(quant_param['weight_zp_shape'])
74
  input_scale = torch.tensor(quant_param['input_scale']).view(quant_param['input_scale_shape'])
 
78
  self.register_buffer('input_scale', input_scale)
79
  self.register_buffer('input_zp', input_zp)
80
 
81
+ # I.e., "fake quantization"
82
+ def qdq_forward(self, x):
83
  scaled_x = x * self.mul_factor
84
+ quant_weight = quantize(self.conv2d.weight, self.weight_scale, self.weight_zp, is_asym=True)
 
 
85
  quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False)
86
  dequantized_weight = dequantize(quant_weight, self.weight_scale, self.weight_zp)
87
  dequantized_input = dequantize(quant_input, self.input_scale, self.input_zp)
88
  out = torch.nn.functional.conv2d(dequantized_input, dequantized_weight, self.conv2d.bias)
89
  return out
90
+
91
+ # Accelerated version
92
+ def qop_forward(self, x):
93
+ # With an integer conv2d kernel, if the weight zero point is not zero,
94
+ # A correction term must be calculated to correct the output.
95
+ # Conceptually, it's identical to the linear case except that it's difficult
96
+ # to reduce the input across the dot-product dimension. This leaves us with two obvious options:
97
+ # 1. Manually compute the reduction via Im2Col -> `torch.sum`
98
+ # 2. Add an extra _output channel_ to the convolution with a kernel made from all ones (e.g., `torch.ones()`)
99
+ # In this example, I've used option #2.
100
+ # The correction term is then calculated as follows:
101
+ # - Add an extra output channel to the weight tensor with all values equal to 1 to calculate the sum (e.g., `torch.cat((quant_weight, torch.ones(shape)), dim=0)`)
102
+ # - Extract the sum from the output tensor (e.g., `sum = quant_output[:,-1,:,:]`)
103
+ # - multiply this sum with every weight zero-point (e.g., `sum * self.weight_zp`
104
+ # - Subtract from previous output (e.g., `quant_output -= sum * self.weight_zp`)
105
+ # - All other code is just to make sure the broadcasting semantics work correctly
106
+ scaled_x = x * self.mul_factor
107
+ quant_weight = quantize(self.conv2d.weight, self.weight_scale, self.weight_zp, is_asym=True).to(torch.uint8)
108
+ b_shape = list(quant_weight.shape) # Used for weight zero-point correction
109
+ b_shape[0] = 1 # Used for weight zero-point correction
110
+ weight_cat = torch.ones((1,1,1,1)).broadcast_to(b_shape).to(torch.uint8) # Used for weight zero-point correction
111
+ quant_weight = torch.cat((quant_weight,weight_cat),dim=0).to(torch.uint8) # Create extra output channel, used for weight zero-point correction
112
+ quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False).to(torch.int8)
113
+ quant_output = torch.nn.functional.conv2d(quant_input.to(torch.float32), quant_weight.to(torch.float32), None).to(torch.int32) # Convert inputs to FP32 to avoid F.conv2d quantizing the output to int8
114
+ correction = quant_output[:,-1,:,:] * (-self.weight_zp).to(torch.uint8).view([1, self.weight_zp.nelement()] + [1]*(quant_output.ndim-2)) # Correct zero-point for weight
115
+ quant_output = quant_output[:,:-1,:,:] + correction
116
+ output = dequantize(quant_output, (self.weight_scale * self.input_scale).view([1, (self.weight_scale * self.input_scale).nelement()] + [1]*(quant_output.ndim-2)), 0.0)
117
+ output += self.conv2d.bias.view([1, self.conv2d.bias.nelement()] + [1]*(quant_output.ndim-2))
118
+ return output
119
+
120
+ def forward(self, x, qop=False):
121
+ if qop:
122
+ return self.qop_forward(x)
123
+ else:
124
+ return self.qdq_forward(x)
test_quant_conv2d.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from math_model import QuantConv2d
3
+
4
+ torch.manual_seed(0)
5
+
6
+ batch_size = 1
7
+ out_ch = 8
8
+ in_ch = 4
9
+ k = 3
10
+ h = 5
11
+ w = 5
12
+
13
+ quant_params = {
14
+ 'smoothquant_mul': torch.rand((in_ch,)),
15
+ 'smoothquant_mul_shape': (1,in_ch,1,1),
16
+ 'weight_scale': torch.rand((out_ch,)),
17
+ 'weight_scale_shape': (out_ch,1,1,1),
18
+ 'weight_zp': torch.randint(-255, 0, (out_ch,)),
19
+ 'weight_zp_shape': (out_ch,1,1,1),
20
+ 'input_scale': torch.rand((1,)),
21
+ 'input_scale_shape': (1,),
22
+ 'input_zp': torch.zeros((1,)),
23
+ 'input_zp_shape': (1,),
24
+ }
25
+
26
+ print(quant_params)
27
+
28
+ l = QuantConv2d(in_ch, out_ch, k, quant_params)
29
+ i = torch.rand((batch_size,in_ch,h,w))
30
+ o_qdq = l(i)
31
+ o_qop = l(i, qop=True)
32
+ print(o_qdq.shape)
33
+ print(o_qop.shape)
34
+ print(o_qdq - o_qop)
test_quant_linear.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from math_model import QuantLinear
3
+
4
+ torch.manual_seed(0)
5
+
6
+ batch_size = 1
7
+ out_ch = 128
8
+ in_ch = 64
9
+
10
+ quant_params = {
11
+ 'smoothquant_mul': torch.rand((in_ch,)),
12
+ 'smoothquant_mul_shape': (in_ch,),
13
+ 'weight_scale': torch.rand((out_ch,)),
14
+ 'weight_scale_shape': (out_ch,1),
15
+ 'weight_zp': torch.randint(-255, 0, (out_ch,)),
16
+ 'weight_zp_shape': (out_ch,1),
17
+ 'input_scale': torch.rand((1,)),
18
+ 'input_scale_shape': (1,),
19
+ 'input_zp': torch.zeros((1,)),
20
+ 'input_zp_shape': (1,),
21
+ }
22
+
23
+ print(quant_params)
24
+
25
+ l = QuantLinear(in_ch, out_ch, quant_params)
26
+ i = torch.rand((batch_size,in_ch))
27
+ o_qdq = l(i)
28
+ o_qop = l(i, qop=True)
29
+ print(o_qdq.shape)
30
+ print(o_qop.shape)
31
+ print(o_qdq - o_qop)