Stella Laurenzo commited on
Commit
82e06d6
1 Parent(s): 4241729

Initial add of unet/int8 model.

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ quant_param.json filter=lfs diff=lfs merge=lfs -text
37
+ quant_params.json filter=lfs diff=lfs merge=lfs -text
38
+ unet/int8/quant_params.json filter=lfs diff=lfs merge=lfs -text
unet/int8/config.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.19.0.dev0",
4
+ "act_fn": "silu",
5
+ "addition_embed_type": "text_time",
6
+ "addition_embed_type_num_heads": 64,
7
+ "addition_time_embed_dim": 256,
8
+ "attention_head_dim": [
9
+ 5,
10
+ 10,
11
+ 20
12
+ ],
13
+ "block_out_channels": [
14
+ 320,
15
+ 640,
16
+ 1280
17
+ ],
18
+ "center_input_sample": false,
19
+ "class_embed_type": null,
20
+ "class_embeddings_concat": false,
21
+ "conv_in_kernel": 3,
22
+ "conv_out_kernel": 3,
23
+ "cross_attention_dim": 2048,
24
+ "cross_attention_norm": null,
25
+ "down_block_types": [
26
+ "DownBlock2D",
27
+ "CrossAttnDownBlock2D",
28
+ "CrossAttnDownBlock2D"
29
+ ],
30
+ "downsample_padding": 1,
31
+ "dual_cross_attention": false,
32
+ "encoder_hid_dim": null,
33
+ "encoder_hid_dim_type": null,
34
+ "flip_sin_to_cos": true,
35
+ "freq_shift": 0,
36
+ "in_channels": 4,
37
+ "layers_per_block": 2,
38
+ "mid_block_only_cross_attention": null,
39
+ "mid_block_scale_factor": 1,
40
+ "mid_block_type": "UNetMidBlock2DCrossAttn",
41
+ "norm_eps": 1e-05,
42
+ "norm_num_groups": 32,
43
+ "num_attention_heads": null,
44
+ "num_class_embeds": null,
45
+ "only_cross_attention": false,
46
+ "out_channels": 4,
47
+ "projection_class_embeddings_input_dim": 2816,
48
+ "resnet_out_scale_factor": 1.0,
49
+ "resnet_skip_time_act": false,
50
+ "resnet_time_scale_shift": "default",
51
+ "sample_size": 128,
52
+ "time_cond_proj_dim": null,
53
+ "time_embedding_act_fn": null,
54
+ "time_embedding_dim": null,
55
+ "time_embedding_type": "positional",
56
+ "timestep_post_act": null,
57
+ "transformer_layers_per_block": [
58
+ 1,
59
+ 2,
60
+ 10
61
+ ],
62
+ "up_block_types": [
63
+ "CrossAttnUpBlock2D",
64
+ "CrossAttnUpBlock2D",
65
+ "UpBlock2D"
66
+ ],
67
+ "upcast_attention": null,
68
+ "use_linear_projection": true
69
+ }
unet/int8/params.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1047f8e694b0ce7d2fb0754b519b1d3aa7c316bfe74900474f69a261d0077fc7
3
+ size 5136204272
unet/int8/quant_params.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbc5f010261abb44cf5c149fc1471cb6cfc272d4c5e94cfdbfd80c9f9d52eb39
3
+ size 85103981
unet/int8/reference/math_model.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+
4
+ def quantize(tensor, scale, zero_point, is_asym=False):
5
+ if is_asym:
6
+ clamp_min, clamp_max = torch.tensor(0.), torch.tensor(255.)
7
+ else:
8
+ clamp_min, clamp_max = torch.tensor(-128.), torch.tensor(127.)
9
+ quant_tensor = torch.clamp(torch.round(tensor/scale + zero_point), clamp_min, clamp_max)
10
+ return quant_tensor
11
+
12
+ def dequantize(tensor, scale, zero_point):
13
+ return (tensor - zero_point) * scale
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'])
25
+ input_zp = torch.tensor(quant_param['input_zp']).view(quant_param['input_zp_shape'])
26
+ self.register_buffer('weight_scale', weight_scale)
27
+ self.register_buffer('weight_zp', weight_zp)
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)
37
+ dequantized_input = dequantize(quant_input, self.input_scale, self.input_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
+ weight_zp_int8 = (self.weight_zp - 128).to(torch.int8).to(torch.float32) # Conversion from uint8 -> int8, can be computed offline
51
+ quant_weight = quantize(self.linear.weight, self.weight_scale, weight_zp_int8, is_asym=False).to(torch.int8)
52
+ fused_input_scale = self.input_scale / self.mul_factor # Fuse SmoothQuant and input scales, can be computed offline
53
+ quant_input = quantize(x, fused_input_scale, self.input_zp, is_asym=False).to(torch.int8)
54
+ 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
55
+ correction = torch.sum(quant_input, dim=-1, keepdim=True).to(torch.int32) * weight_zp_int8.to(torch.int8).view([1]*(quant_input.ndim-1) + [self.weight_zp.nelement()]) # Correct for weight zero-point
56
+ quant_output = quant_output - correction
57
+ 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)
58
+ output += self.linear.bias
59
+ return output
60
+
61
+ def forward(self, x, qop=False):
62
+ if qop:
63
+ return self.qop_forward(x)
64
+ else:
65
+ return self.qdq_forward(x)
66
+
67
+ class QuantConv2d(nn.Module):
68
+ def __init__(self, in_ch, out_ch, kernel_size, quant_param):
69
+ super().__init__()
70
+ mul_factor = torch.tensor(quant_param['smoothquant_mul']).view(quant_param['smoothquant_mul_shape'])
71
+ self.register_buffer('mul_factor', mul_factor)
72
+ self.conv2d = nn.Conv2d(in_ch, out_ch, kernel_size)
73
+ weight_scale = torch.tensor(quant_param['weight_scale']).view(quant_param['weight_scale_shape'])
74
+ weight_zp = torch.tensor(quant_param['weight_zp']).view(quant_param['weight_zp_shape'])
75
+ input_scale = torch.tensor(quant_param['input_scale']).view(quant_param['input_scale_shape'])
76
+ input_zp = torch.tensor(quant_param['input_zp']).view(quant_param['input_zp_shape'])
77
+ self.register_buffer('weight_scale', weight_scale)
78
+ self.register_buffer('weight_zp', weight_zp)
79
+ self.register_buffer('input_scale', input_scale)
80
+ self.register_buffer('input_zp', input_zp)
81
+
82
+ # I.e., "fake quantization"
83
+ def qdq_forward(self, x):
84
+ scaled_x = x * self.mul_factor
85
+ quant_weight = quantize(self.conv2d.weight, self.weight_scale, self.weight_zp, is_asym=True)
86
+ quant_input = quantize(scaled_x, self.input_scale, self.input_zp, is_asym=False)
87
+ dequantized_weight = dequantize(quant_weight, self.weight_scale, self.weight_zp)
88
+ dequantized_input = dequantize(quant_input, self.input_scale, self.input_zp)
89
+ out = torch.nn.functional.conv2d(dequantized_input, dequantized_weight, self.conv2d.bias)
90
+ return out
91
+
92
+ # Accelerated version
93
+ def qop_forward(self, x):
94
+ # With an integer conv2d kernel, if the weight zero point is not zero,
95
+ # A correction term must be calculated to correct the output.
96
+ # Conceptually, it's identical to the linear case except that it's difficult
97
+ # to reduce the input across the dot-product dimension. This leaves us with two obvious options:
98
+ # 1. Manually compute the reduction via Im2Col -> `torch.sum`
99
+ # 2. Add an extra _output channel_ to the convolution with a kernel made from all ones (e.g., `torch.ones()`)
100
+ # In this example, I've used option #2.
101
+ # The correction term is then calculated as follows:
102
+ # - 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)`)
103
+ # - Extract the sum from the output tensor (e.g., `sum = quant_output[:,-1,:,:]`)
104
+ # - multiply this sum with every weight zero-point (e.g., `sum * self.weight_zp`
105
+ # - Subtract from previous output (e.g., `quant_output -= sum * self.weight_zp`)
106
+ # - All other code is just to make sure the broadcasting semantics work correctly
107
+ weight_zp_int8 = (self.weight_zp - 128).to(torch.int8).to(torch.float32) # Conversion from uint8 -> int8, can be computed offline
108
+ quant_weight = quantize(self.conv2d.weight, self.weight_scale, weight_zp_int8, is_asym=False).to(torch.int8)
109
+ b_shape = list(quant_weight.shape) # Used for weight zero-point correction
110
+ b_shape[0] = 1 # Used for weight zero-point correction
111
+ weight_cat = torch.ones((1,1,1,1)).broadcast_to(b_shape).to(torch.int8) # Used for weight zero-point correction
112
+ quant_weight = torch.cat((quant_weight,weight_cat),dim=0).to(torch.int8) # Create extra output channel, used for weight zero-point correction
113
+ fused_input_scale = self.input_scale / self.mul_factor # Fuse SmoothQuant and input scales, can be computed offline
114
+ quant_input = quantize(x, fused_input_scale, self.input_zp, is_asym=False).to(torch.int8)
115
+ 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
116
+ correction = quant_output[:,-1,:,:] * weight_zp_int8.to(torch.int8).view([1, self.weight_zp.nelement()] + [1]*(quant_output.ndim-2)) # Correct zero-point for weight
117
+ quant_output = quant_output[:,:-1,:,:] - correction
118
+ 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)
119
+ output += self.conv2d.bias.view([1, self.conv2d.bias.nelement()] + [1]*(quant_output.ndim-2))
120
+ return output
121
+
122
+ def forward(self, x, qop=False):
123
+ if qop:
124
+ return self.qop_forward(x)
125
+ else:
126
+ return self.qdq_forward(x)
unet/int8/reference/test_quant_conv2d.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from math_model import QuantConv2d
4
+
5
+ torch.manual_seed(0)
6
+
7
+ batch_size = 1
8
+ out_ch = 128
9
+ in_ch = 64
10
+ k = 3
11
+ h = 5
12
+ w = 5
13
+
14
+ i = 2*torch.rand((batch_size,in_ch,h,w)) - 1.
15
+ l = nn.Conv2d(in_ch, out_ch, k, bias=True)
16
+
17
+ quant_params = {
18
+ 'smoothquant_mul': torch.rand((in_ch,)),
19
+ 'smoothquant_mul_shape': (1,in_ch,1,1),
20
+ 'weight_scale': torch.rand((out_ch,)),
21
+ 'weight_scale': torch.max(torch.abs(torch.flatten(l.weight, start_dim=1)), dim=1).values / 128.,
22
+ 'weight_scale_shape': (out_ch,1,1,1),
23
+ 'weight_zp': torch.clamp(torch.round((torch.mean((l.weight), dim=(1,2,3))) * (128 / torch.max(torch.abs(torch.flatten(l.weight, start_dim=1)), dim=1).values)) + 128, 0, 255),
24
+ 'weight_zp_shape': (out_ch,1,1,1),
25
+ 'input_scale': torch.max(torch.abs(i)) / 128.,
26
+ 'input_scale_shape': tuple(),
27
+ 'input_zp': torch.zeros((1,)),
28
+ 'input_zp_shape': tuple(),
29
+ }
30
+
31
+ print(quant_params)
32
+
33
+ ql = QuantConv2d(in_ch, out_ch, k, quant_params)
34
+ ql.conv2d.load_state_dict(l.state_dict())
35
+ o_qdq = ql(i)
36
+ o_qop = ql(i, qop=True)
37
+ print(o_qdq.shape)
38
+ print(o_qop.shape)
39
+ print(o_qdq - o_qop)
unet/int8/reference/test_quant_linear.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from math_model import QuantLinear
4
+
5
+ torch.manual_seed(0)
6
+
7
+ batch_size = 1
8
+ out_ch = 128
9
+ in_ch = 64
10
+
11
+ i = 2*torch.rand((batch_size,in_ch)) - 1.
12
+ l = nn.Linear(in_ch, out_ch, bias=True)
13
+
14
+ quant_params = {
15
+ 'smoothquant_mul': torch.rand((in_ch,)),
16
+ 'smoothquant_mul_shape': (1,in_ch),
17
+ 'weight_scale': torch.max(torch.abs(l.weight), dim=1).values / 128.,
18
+ 'weight_scale_shape': (out_ch,1),
19
+ 'weight_zp': torch.clamp(torch.round((torch.mean((l.weight), dim=1)) * (128 / torch.max(torch.abs(l.weight), dim=1).values)) + 128, 0, 255),
20
+ 'weight_zp_shape': (out_ch,1),
21
+ 'input_scale': torch.max(torch.abs(i)) / 128.,
22
+ 'input_scale_shape': tuple(),
23
+ 'input_zp': torch.zeros((1,)),
24
+ 'input_zp_shape': tuple(),
25
+ }
26
+
27
+ print(quant_params)
28
+
29
+ ql = QuantLinear(in_ch, out_ch, quant_params)
30
+ ql.linear.load_state_dict(l.state_dict())
31
+ o_qdq = ql(i)
32
+ o_qop = ql(i, qop=True)
33
+ print(o_qdq.shape)
34
+ print(o_qop.shape)
35
+ print(o_qdq - o_qop)