-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlinear.py
More file actions
2440 lines (2113 loc) · 94.6 KB
/
Copy pathlinear.py
File metadata and controls
2440 lines (2113 loc) · 94.6 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright The FMS Model Optimizer Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Quantization linear modules"""
# pylint: disable=arguments-renamed
# Standard
import json
import logging
# Third Party
from torch import nn
import numpy as np
import torch
import torch.nn.functional as F
# Local
from fms_mo.custom_ext_kernels.utils import pack_vectorized
from fms_mo.quant.quantizers import (
SAWB,
HardPrune,
Qbypass,
Qdynamic,
get_activation_quantizer,
get_weight_quantizer,
mask_fc_kij,
)
from fms_mo.quant.rotation import RotQuantWrapper
from fms_mo.utils.import_utils import available_packages
if available_packages["triton"]:
# Local
from fms_mo.custom_ext_kernels.triton_kernels import (
tl_matmul_chunk_truncate as tl_matmul,
)
logger = logging.getLogger(__name__)
class QLinear(nn.Linear):
"""docstring for QLinear_pact.
A wrapper for the quantization of linear (aka. affine or fc) layers
Layer weights and input activation can be quantized to low-precision integers through popular
quantization methods. Bias is not quantized.
Supports both non-negtive activations (after relu) and symmetric/nonsymmetric 2-sided
activations (after sum, swish, silu ..)
Attributes:
num_bits_feature : precision for activations
num_bits_weight : precision for weights
qa_mode : quantizers for activation quantization. Options:PACT, CGPACT, PACT+,
LSQ+, DoReFa.
qw_mode : quantizers for weight quantization. Options: SAWB, OlDSAWB, PACT,
CGPACT, PACT+, LSQ+, DoReFa.
act_clip_init_val : initialization value for activation clip_val on positive side
act_clip_init_valn : initialization value for activation clip_val on negative side
w_clip_init_val : initialization value for weight clip_val on positive side
(None for SAWB)
w_clip_init_valn : initialization value for weight clip_val on negative side
(None for SAWB)
non_neg : if True, call one-side activation quantizer
align_zero : if True, preserve zero, i.e align zero to an integer level
"""
def __init__(
self,
in_features,
out_features,
bias=True,
num_bits_feature=32,
qa_mode=None,
num_bits_weight=32,
qw_mode=None,
**kwargs,
):
"""
Initializes the quantized linear layer.
Args:
in_features (int): Number of input features.
out_features (int): Number of output features.
bias (bool, optional): Whether to include a bias term. Defaults to True.
num_bits_feature (int, optional): Number of bits for feature quantization.
Defaults to 32.
qa_mode (str, optional): Quantization mode for feature. Defaults to None.
num_bits_weight (int, optional): Number of bits for weight quantization.
Defaults to 32.
qw_mode (str, optional): Quantization mode for weight. Defaults to None.
**kwargs (dict): Additional keyword arguments.
Note:
scales could be of higher precision than x or W, need to make sure qinput.dtype after
Qa(x/scale) are consistent with x. Same for W
"""
super().__init__(
in_features, out_features, bias, device=kwargs.get("device", "cuda")
)
qcfg = kwargs.pop("qcfg")
self.num_bits_feature = num_bits_feature
self.num_bits_weight = num_bits_weight
self.qa_mode = qa_mode
self.qw_mode = qw_mode
self.qa_mode_calib = kwargs.get(
"qa_mode_calib",
qcfg.get("qa_mode_calib", "max" if num_bits_feature == 8 else "percentile"),
)
self.qw_mode_calib = kwargs.get(
"qw_mode_calib",
qcfg.get("qw_mode_calib", "max" if num_bits_feature == 8 else "percentile"),
)
self.act_clip_init_val = kwargs.get(
"act_clip_init_val", qcfg.get("act_clip_init_val", 8.0)
)
self.act_clip_init_valn = kwargs.get(
"act_clip_init_valn", qcfg.get("act_clip_init_valn", -8.0)
)
self.w_clip_init_val = kwargs.get(
"w_clip_init_val", qcfg.get("w_clip_init_val", 1.0)
)
self.w_clip_init_valn = kwargs.get(
"w_clip_init_valn", qcfg.get("w_clip_init_valn", -1.0)
)
self.non_neg = kwargs.get("non_neg", qcfg.get("non_neg", False))
self.align_zero = kwargs.get("align_zero", qcfg.get("align_zero", True))
self.extend_act_range = kwargs.get(
"extend_act_range", qcfg.get("extend_act_range", False)
)
self.fp8_use_subnormal = kwargs.get(
"fp8_use_subnormal", qcfg.get("fp8_use_subnormal", False)
)
self.register_buffer(
"calib_counter", torch.tensor(qcfg.get("qmodel_calibration_new", 0))
) # Counters has to be buffer in case DP is used.
self.register_buffer(
"num_module_called", torch.tensor(0)
) # A counter to record how many times this module has been called
self.ptqmode = "qout" # ['fp32_out', 'qout', None]
self.W_fp = None
self.use_PT_native_Qfunc = kwargs.get(
"use_PT_native_Qfunc", qcfg.get("use_PT_native_Qfunc", False)
)
self.perGp = kwargs.get("qgroup", qcfg.get("qgroup", None))
self.qcfg = qcfg
self.calib_iterator = []
# To simplify update of clipvals in forward()
quantA_default = Qbypass() if "rot_" not in self.qa_mode else RotQuantWrapper()
quantW_default = Qbypass() if "rot_" not in self.qw_mode else RotQuantWrapper()
self.quantize_feature = quantA_default
self.quantize_calib_feature = quantA_default
if self.num_bits_feature not in [32, 16]:
self.quantize_feature = get_activation_quantizer(
self.qa_mode,
nbits=self.num_bits_feature,
clip_val=self.act_clip_init_val,
clip_valn=self.act_clip_init_valn,
non_neg=self.non_neg,
align_zero=self.align_zero,
extend_act_range=bool(self.extend_act_range),
use_PT_native_Qfunc=self.use_PT_native_Qfunc,
use_subnormal=self.fp8_use_subnormal,
)
if self.calib_counter > 0:
qa_mode_calib = (
self.qa_mode_calib + "sym"
if self.qa_mode.endswith("sym")
else self.qa_mode_calib
)
self.quantize_calib_feature = Qdynamic(
self.num_bits_feature,
qcfg,
non_neg=self.non_neg,
align_zero=self.align_zero,
qmode=qa_mode_calib,
quantizer2sync=self.quantize_feature,
)
self.quantize_weight = quantW_default
self.quantize_calib_weight = quantW_default
if self.num_bits_weight not in [32, 16]:
self.quantize_weight = get_weight_quantizer(
self.qw_mode,
nbits=self.num_bits_weight,
clip_val=self.w_clip_init_val,
clip_valn=self.w_clip_init_valn,
align_zero=self.align_zero,
w_shape=self.weight.shape,
perGp=self.perGp,
use_subnormal=self.fp8_use_subnormal,
)
if self.calib_counter > 0:
self.quantize_calib_weight = (
self.quantize_weight
if any(m in self.qw_mode for m in ["sawb", "max", "adaround"])
else Qdynamic(
self.num_bits_weight,
qcfg,
non_neg=False,
align_zero=True,
qmode=self.qw_mode_calib,
symmetric=True,
quantizer2sync=self.quantize_weight,
)
)
self.mask = None
self.mask_type = qcfg.get("mask_type", "kij")
self.update_type = qcfg.get("update_type", "hard")
self.prune_group = qcfg.get("prune_group", 4)
self.prune_ratio = qcfg.get("prune_ratio", 0.0)
self.prune_mix = qcfg.get("prune_mix", False)
self.in_threshold = qcfg.get("in_threshold", 128)
w_size = self.weight.shape
if (
self.prune_mix
and self.prune_ratio == 0.75
and w_size[1] <= self.in_threshold
):
self.prune_ratio = 0.50
self.p_inplace = qcfg.get("p_inplace", False)
# For non-learnable quantizers, use the real quantizer as the calib quantizer directly
if self.qw_mode == "oldsawb":
logger.info(
"Please consider using new SAWB quantizer. 'oldsawb' mode is not supported anymore."
)
self.smoothq = qcfg.get("smoothq", False)
if self.smoothq:
self.register_buffer("smoothq_act_scale", torch.zeros(w_size[1]))
self.register_buffer(
"smoothq_alpha",
torch.tensor([qcfg.get("smoothq_alpha", 0.5)], dtype=torch.float32),
)
def forward(self, x):
"""
Forward pass of the layer.
Args:
x (Tensor): Input tensor of shape (batch_size, in_features).
Returns:
Tensor: Output tensor of shape (batch_size, out_features).
"""
if self.smoothq:
scale = self.get_smoothq_scale(x)
else:
scale = torch.tensor([1.0]).to(x.dtype).to(x.device)
# pylint: disable = access-member-before-definition
if self.calib_counter > 0:
with torch.no_grad():
qinput = self.quantize_calib_feature(x / scale)
qweight = self.quantize_calib_weight(self.weight * scale)
self.calib_counter -= 1
if self.calib_counter == 0:
self.quantize_calib_feature = None
self.quantize_calib_weight = None
elif self.ptqmode == "fp32_out":
if self.W_fp is None:
# i.e., 1st time this module is run, clone the FP32 weights, assuming weight is
# initialized by fp32 already
# pylint: disable=not-callable
self.W_fp = self.weight.detach().clone()
self.weight.requires_grad = (
True # Some models prefer to set requires_grad to False by default
)
# pylint: disable=not-callable
return F.linear(x, self.W_fp, self.bias)
else:
qinput = self.quantize_feature(x / scale).to(x.dtype)
# Default self.update_type == 'hard' pruning.
if self.mask is not None:
pweight = HardPrune.apply(
self.weight, self.mask.to(self.weight.device), self.p_inplace
)
qweight = self.quantize_weight(pweight)
else:
qweight = self.quantize_weight(self.weight * scale).to(
self.weight.dtype
)
qbias = self.bias
# pylint: disable=not-callable
output = F.linear(qinput, qweight, qbias)
self.num_module_called += 1
return output
def get_mask(self):
"""
Gets the mask for the weight tensor.
By default, uses hard pruning. The mask is stored in the `mask` attribute.
Returns:
torch.Tensor: The mask tensor.
"""
if self.mask_type == "kij":
self.mask = mask_fc_kij(
self.weight, group=self.prune_group, prune_ratio=self.prune_ratio
)
else:
self.mask = None
def get_prune_ratio(self):
"""
Calculates the prune ratio of the mask.
Returns:
float: The prune ratio of the mask.
"""
mask = self.mask.reshape(-1)
return torch.sum(mask) * 1.0 / mask.shape[0]
def set_act_scale(self, act_scale):
"""Sets the activation scale for smooth quantization.
Args:
act_scale (torch.Tensor): The activation scale to be set.
It should have the same number of channels as the weight tensor.
"""
assert (
act_scale.shape[0] == self.weight.shape[1]
), "scale applies to per-channel"
self.smoothq_act_scale.copy_(act_scale)
def get_smoothq_scale(self, x):
"""
Calculate the smoothQ scale for a given input tensor x.
Args:
x: The input tensor for which to calculate the smoothQ scale.
Returns:
smoothq_scale: The calculated smoothQ scale for the input tensor x.
"""
if self.smoothq_act_scale.sum().item() == 0.0:
smoothq_scale = torch.tensor([1.0]).to(x.dtype).to(x.device)
else:
weight_scale = self.weight.abs().max(dim=0, keepdim=True)[0].clamp(min=1e-5)
if isinstance(self.smoothq_alpha, torch.Tensor):
alpha = self.smoothq_alpha.item()
else:
alpha = self.smoothq_alpha
smoothq_scale = (
(self.smoothq_act_scale.pow(alpha) / weight_scale.pow(1.0 - alpha))
.clamp(min=1e-5)
.to(x.dtype)
)
return smoothq_scale
def __repr__(self):
"""
Returns a string representation of the quantized linear layer.
"""
str_quantizer = ",QntzerW,A="
str_quantizer += (
""
if self.num_bits_weight == 32
else f"{self.quantize_weight.__repr__().split('(')[0]},"
)
str_quantizer += (
""
if self.num_bits_feature == 32
else f"{self.quantize_feature.__repr__().split('(')[0]}"
)
str_quantizer += (
""
if self.mask is None
else f", p_rate={self.prune_ratio}, p_group={self.prune_group}, "
)
return (
f"{self.__class__.__name__}({self.in_features},{self.out_features}, "
f"Nbits_W,A={self.num_bits_weight},{self.num_bits_feature}{str_quantizer})"
)
# ------------------------------------------------------------------------------
# ----- The following wrappers are for torch FX CPU lowering only (FBGEMM) -----
# ----- NOTE: do not use them directly in QAT, backward is not defined -----
# ------------------------------------------------------------------------------
class QLinearFPout(torch.ao.nn.quantized.Linear):
"""
A new QLinear class for fbgemm lowering, not for generic QAT/PTQ use (no backward)
Original "torch.ao.nn.quantized.Linear" is designed to
find pattern Q->(dQ->ref Linear->Q)->dQ then
swap to Q-> QLinear ->dQ
which means 1) this QLinear takes INT8 as input AND output INT8
2) this QLinear needs to know output scale/zp, which is usually unavailable
from fms_mo models
Here we utilize another native backend function to
find pattern (Q->dQ->ref Linear)->
swap to QLinearFPout ->dQ
"""
@classmethod
def from_reference(cls, ref_qlinear, input_scale, input_zero_point):
r"""Creates a (fbgemm/qnnpack) quantized module from a reference quantized module
Args:
ref_qlinear (Module): a reference quantized linear module, either produced by
torch.ao.quantization utilities or provided by the user
input_scale (float): scale for input Tensor
input_zero_point (int): zero point for input Tensor
NOTE: scale/zp are from input node
"""
qlinear = cls(
ref_qlinear.in_features,
ref_qlinear.out_features,
)
qweight = ref_qlinear.get_quantized_weight()
# CPU/FBGEMM doesn't support perCh
if ref_qlinear.weight_qscheme in [
torch.per_channel_symmetric,
torch.per_channel_affine,
]:
qscale_perT = max(qweight.q_per_channel_scales())
qweight = torch.quantize_per_tensor(
qweight.dequantize(), qscale_perT, 0, torch.qint8
)
qlinear.set_weight_bias(qweight.cpu(), ref_qlinear.bias.cpu())
qlinear.scale = float(input_scale)
qlinear.zero_point = int(input_zero_point)
return qlinear
def _get_name(self):
"""
Returns the name of the QuantizedLinear_FPout as a string.
"""
return "QuantizedLinear_FPout"
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the layer.
Args:
x (Tensor): Input tensor of shape (batch_size, in_features).
Returns:
Tensor: Output tensor of shape (batch_size, out_features).
"""
return torch.ops.quantized.linear_with_input_q_dq_qweight_dq_output_fp32(
x, self.scale, self.zero_point, self._packed_params._packed_params
)
class QLinearDebug(nn.Linear):
"""
A new QLinear class for debugging lowering, no backward
Here we assume the graph has Q/dQ nodes already, and try to absorb those nodes into this QLinear
here we use FP32 native backend function, but external kernels can be used, too
find pattern (Q->dQ->ref Linear) ->
swap to (QLinearDebug ) ->
"""
@classmethod
def from_reference(cls, ref_qlinear, input_scale, input_zero_point):
r"""Creates a quantized linear module from a reference quantized module
Args:
ref_qlinear (Module): a reference quantized linear module, either produced by
torch.ao.quantization utilities or provided by the user
input_scale (float): scale for input Tensor
input_zero_point (int): zero point for input Tensor
NOTE: scale/zp are for input activation
"""
nnlinear = cls(ref_qlinear.in_features, ref_qlinear.out_features)
nnlinear.register_buffer("input_scale", input_scale)
nnlinear.register_buffer("input_zp", input_zero_point)
was_fp16 = False
if ref_qlinear.weight.dtype == torch.float16:
was_fp16 = True
ref_qlinear.float()
nnlinear.weight = nn.Parameter(
ref_qlinear.get_weight(), requires_grad=False
) # this is Q(w).dQ()
nnlinear.bias = nn.Parameter(ref_qlinear.bias, requires_grad=False)
if was_fp16:
ref_qlinear.half()
nnlinear.half()
return nnlinear
@classmethod
def from_fms_mo(cls, fms_mo_qlinear, **kwargs):
"""
Converts a QLinear module to QLinearDebug.
Args:
cls: The class of the QLinearModule to be created.
fms_mo_qlinear: The QLinear module to be converted.
kwargs: Additional keyword arguments.
Returns:
A QLinearDebug object initialized with the weights and biases from the
QLinear module.
"""
assert fms_mo_qlinear.num_bits_feature in [
4,
8,
] and fms_mo_qlinear.num_bits_weight in [4, 8], "Please check nbits setting!"
target_device = kwargs.get(
"target_device", next(fms_mo_qlinear.parameters()).device
)
qlinear_cublas = cls(fms_mo_qlinear.in_features, fms_mo_qlinear.out_features)
qlinear_cublas.input_dtype = (
torch.quint8
) # Assume input to fms_mo QLinear is always asym
with torch.no_grad():
Qa = fms_mo_qlinear.quantize_feature
input_scale = (Qa.clip_val - Qa.clip_valn) / (2**Qa.num_bits - 1)
input_zero_point = torch.round(-Qa.clip_valn / input_scale).to(torch.int)
qlinear_cublas.register_buffer("input_scale", input_scale)
qlinear_cublas.register_buffer("input_zp", input_zero_point)
Qw = fms_mo_qlinear.quantize_weight
w_scale = Qw.clip_val * 2 / (2**Qw.num_bits - 2)
w_zp = torch.zeros_like(w_scale, dtype=torch.int)
qlinear_cublas.register_buffer("w_scale", w_scale.float())
qlinear_cublas.register_buffer("w_zp", w_zp)
qlinear_cublas.weight = nn.Parameter(
Qw(fms_mo_qlinear.weight), requires_grad=False
)
qlinear_cublas.bias = nn.Parameter(fms_mo_qlinear.bias, requires_grad=False)
return qlinear_cublas.to(target_device)
def _get_name(self):
"""
Returns the name of the QLinear_Debug as a string.
"""
return "QuantizedLinear_Debug"
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the layer.
Args:
x (Tensor): Input tensor of shape (batch_size, in_features).
Returns:
Tensor: Output tensor of shape (batch_size, out_features).
"""
with torch.no_grad():
x = torch.clamp(
(x / self.input_scale + self.input_zp).round(), 0, 255
) # map to int
x = (x - self.input_zp) * self.input_scale # deQ
x = super().forward(x)
return x
class QLinearW4A32Debug(nn.Linear):
"""
Here we assume the graph does not have Q/dQ nodes, since A32,
so all we need is to dQ the W
"""
@classmethod
def from_reference(cls, ref_qlinear):
r"""Creates a quantized linear module from a reference quantized module
Args:
ref_qlinear (Module): a reference quantized linear module
"""
qlinear = cls(ref_qlinear.in_features, ref_qlinear.out_features)
org_dtype = ref_qlinear.weight.dtype
qlinear.weight = nn.Parameter(
ref_qlinear.float().get_weight().to(org_dtype), requires_grad=False
) # This is Q(w).dQ()
qlinear.bias = nn.Parameter(ref_qlinear.bias.to(org_dtype), requires_grad=False)
return qlinear
@classmethod
def from_fms_mo(cls, fms_mo_qlinear):
"""
Converts a QLinear module to QLinearW4A32Debug.
Args:
cls: The class of the QLinearModule to be created.
fms_mo_qlinear: The QLinear module to be converted.
Returns:
A QLinearW4A32Debug object initialized with the weights and biases from the
QLinear module.
"""
qlinear = cls(fms_mo_qlinear.in_features, fms_mo_qlinear.out_features)
# If your model is half(), ref_linear and PT native quant func won't work,
# need to convert to .float() first
org_dtype = fms_mo_qlinear.weight.dtype
fms_mo_qlinear.float()
qlinear.weight = nn.Parameter(
fms_mo_qlinear.quantize_weight(fms_mo_qlinear.weight).to(org_dtype),
requires_grad=False,
) # This is Q(w).dQ()
qlinear.bias = nn.Parameter(
fms_mo_qlinear.bias.to(org_dtype), requires_grad=False
)
return qlinear
def _get_name(self):
"""
Returns the name of the QLinearW4A32Debug as a string.
"""
return "QuantizedLinear_W4A32_Debug"
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the layer.
Args:
x (Tensor): Input tensor of shape (batch_size, in_features).
Returns:
Tensor: Output tensor of shape (batch_size, out_features).
"""
with torch.no_grad():
# Could use cublas fp16 kernel, but make sure it accept out_feat < 16 cases
x = super().forward(x)
return x
class NNLinearCublasDebug(nn.Linear):
"""
A Linear class for debugging FP32, no Quantization, simply swap nn.Linear with this,
which calls cublas gemm instead of F.linear
"""
@classmethod
def from_float(cls, nnlinear):
"""
Converts a floating point neural network layer to a cublas neural network layer.
Args:
cls (class): The class NNLinearCublasDebug.
nnlinear (nn.Linear): The floating point Linear layer to be converted.
Returns:
nnlinear_cu (cls): The converted NNLinearCublasDebug.
"""
nnlinear_cu = cls(nnlinear.in_features, nnlinear.out_features)
nnlinear_cu.weight = nn.Parameter(
nnlinear.weight.float(), requires_grad=False
) # force to use F32
nnlinear_cu.bias = nn.Parameter(nnlinear.bias.float(), requires_grad=False)
return nnlinear_cu
def _get_name(self):
"""
Returns the name of the NNLinearCublasDebug as a string.
"""
return "Linear_cublas_fp32"
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the layer.
Args:
x (Tensor): Input tensor of shape (batch_size, in_features).
Returns:
Tensor: Output tensor of shape (batch_size, out_features).
"""
# Check shape before GEMM
if len(x.shape) == 3 and len(self.weight.shape) == 2: # Batched input
re_shape = (-1, x.shape[2])
tar_shape = tuple(x.shape[:2]) + (self.weight.shape[0],) # W is transposed
x = x.reshape(re_shape)
elif len(x.shape) == len(self.iweight.shape) == 2: # 2D
tar_shape = (x.shape[0], self.weight.shape[0]) # W is transposed
else:
raise RuntimeError("Input dimension to Linear is not 2D or batched 2D")
with torch.no_grad():
x = torch.ops.mygemm.gemm_nt_f32(x, self.weight) # fp32 only
x = x.reshape(tar_shape) + self.bias
return x
class QLinearINT8Deploy(nn.Linear):
"""
A QLinear class for lowering test, no backward
weight is stored in torch.int8 (or could use int32 for gptq?)
also need to override forward to make it Q->Linear->dQ on the graph.
(as opposed to Q->dQ->Linear)
"""
@classmethod
def from_fms_mo(cls, fms_mo_qlinear, **kwargs):
"""
Converts a QLinear module to QLinearINT8Deploy.
Args:
cls: The class of the QLinearModule to be created.
fms_mo_qlinear: The QLinear module to be converted.
(experimental)
use_int_kernel: choose from ['cutlass', 'triton', False], "cutlass" kernel is faster,
"triton" supports chunky truncation, "False" fallbacks to torch.matmul
max_acc_bits: usually INT matmul accumulate in INT32, but some HW could have different
design, such as using INT24 accumulator, which will saturate at
(-2**(acc_bit-1) +1, 2**(acc_bit-1) )
truncate_lsb: some HW may apply truncation on least-significant bits (LSBs) of the
accumulated partial sum
chunk_size: some HW may have specific chunk size (BLOCK SIZE, especially in k-dim) for
the reason to avoid overflow/underflow problem. This can be simulated using
PyTorch (break a matmul into serial smaller matmuls, slow) or Triton kernel
useDynMaxQfunc: [-1, -2] indicates reduce_dim, 0< val <64 indicates artificial
zero-shift, False -> use normal static quantization.
Returns:
A QLinearINT8Deploy object initialized with the weights and biases from the
QLinear module.
"""
assert all(
getattr(fms_mo_qlinear, a_or_w) in [4, 8]
for a_or_w in ["num_bits_feature", "num_bits_weight"]
), "Please check nbits setting!"
tar_dev = kwargs.get(
"target_device",
kwargs.get("device", next(fms_mo_qlinear.parameters()).device),
)
fms_mo_w_dtype = fms_mo_qlinear.weight.dtype
qlin_int = cls(
fms_mo_qlinear.in_features,
fms_mo_qlinear.out_features,
bias=fms_mo_qlinear.bias is not None,
device="meta", # init on tar_dev is unnecessary
)
# Make sure to register an Op for integer matmul, could be real INT matmul or emulation
qcfg = getattr(fms_mo_qlinear, "qcfg", {})
qlin_int.use_int_kernel = kwargs.get(
"use_int_kernel", qcfg.get("use_int_kernel", "cutlass")
)
qlin_int.usePTnativeQfunc = kwargs.get("use_PT_native_Qfunc", False)
qlin_int.useDynMaxQfunc = kwargs.get("use_dynamic_max_act_Qfunc", False)
qlin_int.useSymAct = (
"sym" in fms_mo_qlinear.qa_mode
or fms_mo_qlinear.qa_mode in ["pertokenmax", "max"]
# these are the symmetric quantizers with no "sym" in their names
)
qlin_int.max_acc_bits = kwargs.get("max_acc_bits", 32)
qlin_int.accminmax = (
-(1 << (qlin_int.max_acc_bits - 1)),
(1 << (qlin_int.max_acc_bits - 1)) - 1,
)
qlin_int.truncate_lsb = kwargs.get("truncate_lsb", 0)
qlin_int.chunk_size = kwargs.get("chunk_size", 100000)
qlin_int.acc_dtype = torch.float16
qlin_int.nbits_a = fms_mo_qlinear.num_bits_feature # only support INT8 for now
qlin_int.nbits_w = fms_mo_qlinear.num_bits_weight
w_levels = 2**qlin_int.nbits_w - 2
a_levels = 2**qlin_int.nbits_a - 1 - qlin_int.useSymAct
with torch.no_grad():
Qa = fms_mo_qlinear.quantize_feature
Qw = fms_mo_qlinear.quantize_weight
# if no calibration has been run before swapping, clipvals stored in Qw will be the
# ones from ckpt or default. But if want to experiment with new quantizers different
# from the ckpt, need to run one quantizer.fwd() to update the clipvals.
# NOTE currently it will recalc by default, but user can choose to turn it off
if kwargs.get("recalc_clipvals", True):
Qw(fms_mo_qlinear.weight)
w_cv = Qw.clip_val
a_cv = getattr(Qa, "clip_val", torch.tensor(8.0, device=tar_dev))
a_cvn = getattr(Qa, "clip_valn", torch.tensor(-8.0, device=tar_dev))
# Store original cv_a and cv_w in python floats (instead of tensors) will be more
# accurate, but not compatible for per-ch and per-token.
qlin_int.cvs = [a_cv, a_cvn, w_cv] # TODO remove the need of this?
# prepare smoothQuant scale, = (smQ_a_scale ^ alpha)/(smQ_w_scale ^ (1-alpha) )
smoothq_scale = torch.tensor([1.0], device=tar_dev, dtype=fms_mo_w_dtype)
if getattr(fms_mo_qlinear, "smoothq", False):
smoothq_a_scale = fms_mo_qlinear.smoothq_act_scale
smoothq_w_scale = (
fms_mo_qlinear.weight.abs()
.max(dim=0, keepdim=True)[0]
.clamp(min=1e-5)
)
smoothq_alpha = fms_mo_qlinear.smoothq_alpha
if torch.all(smoothq_a_scale != 0).item():
smoothq_scale = (
(
smoothq_a_scale**smoothq_alpha
/ smoothq_w_scale ** (1.0 - smoothq_alpha)
)
.clamp(min=1e-5)
.to(smoothq_a_scale.dtype)
)
# could trigger Qw.clipval re-calc for SAWB here, if needed
input_scale = torch.tensor(1.0, device=tar_dev)
w_scale = w_cv * 2 / w_levels
qlin_int.use_fake_zero_shift = False
if qlin_int.useDynMaxQfunc in [-1, -2]:
input_zero_point = torch.tensor(
128 - qlin_int.useSymAct, device=tar_dev
)
elif 0 < qlin_int.useDynMaxQfunc < 65:
# introduce fake zero-shift, input_scale will be calc dynamically
qlin_int.use_fake_zero_shift = True
input_zero_point = torch.tensor(qlin_int.useDynMaxQfunc, device=tar_dev)
elif qlin_int.usePTnativeQfunc:
input_scale = torch.tensor([(a_cv - a_cvn) / a_levels], device=tar_dev)
input_zero_point = torch.round(-a_cvn / input_scale)
else:
# fms_mo formula is a bit different from conventional PT formula
quant_scale = a_levels / torch.tensor([a_cv - a_cvn], device=tar_dev)
quant_stepsize = 1.0 / quant_scale
quant_zero_point = torch.round(a_cvn * quant_scale)
input_scale = quant_stepsize
input_zero_point = -quant_zero_point
quant_w_scale = w_levels / (w_cv * 2)
w_scale = 1.0 / quant_w_scale
qlin_int.register_buffer("quant_scale", quant_scale)
qlin_int.register_buffer("quant_stepsize", quant_stepsize)
qlin_int.register_buffer("quant_zero_point", quant_zero_point)
w_zp = torch.zeros_like(w_scale, dtype=torch.int)
input_zero_point = input_zero_point.to(torch.int) # note 2 in pre-compute
qlin_int.register_buffer("input_scale", input_scale)
qlin_int.register_buffer("input_zp", input_zero_point)
qlin_int.register_buffer("w_scale", w_scale)
qlin_int.register_buffer("w_zp", w_zp)
qlin_int.register_buffer("smoothq_scale", smoothq_scale)
# NOTE:
# 1. Keep W transposed to prevent confusion, hence (W.t()/scale).t()
# 2. only a few quantizer have .dequantize working correctly, e.g. SAWB
# 3. smooth_quant factor is included in the W here, will also include it in the forward
if isinstance(Qw, SAWB):
Qw.dequantize = False
w_int8 = Qw(fms_mo_qlinear.weight.float() * smoothq_scale)
else:
w_int8 = (
torch.round((fms_mo_qlinear.weight * smoothq_scale).t() / w_scale)
.clamp(-w_levels / 2, w_levels / 2)
.t()
)
w_int8 = w_int8.to(
torch.int
) # stored as int32 as correction term needs sum()
qlin_int.weight = nn.Parameter(w_int8.to(torch.int8), requires_grad=False)
# Pre-compute the "correction term" for zero-shift for asym activation quantizers
# NOTE:
# 1. sym act should have corr_term=0, unless we want to introduce fake zero-shift
# 2. sum to reduce dim=1 because w_int is in [out,in], after sum shape=[out,], same as
# w_scale (per-Ch) and bias.
# 3. calc INT part, i.e. (zp-128)*w_int8.sum(dim=1), first in INT32. because it can be
# >> fp16.max (~65535 only) easily, make sure not to cast INT32 to FP16 during calc,
# simply cast scales to FP32
# 4. for the "fake zero-shift case", input_scale will be max/(127-fake_zero_shift)
# instead of max/127, see qa_dyn_max_fake_zero_shift()
# 5. Combine correction term into linear.bias for non-dynamic cases. For dyn quant,
# input_scale is a placehold for now and will be calc'ed on the fly later.
if qlin_int.useSymAct:
corr_term_int = 0
if qlin_int.use_fake_zero_shift:
# one exception, fake zero-shift
corr_term_int = input_zero_point * (w_int8.sum(dim=1))
else:
corr_term_int = (input_zero_point - 128) * (w_int8.sum(dim=1))
qlin_int.register_buffer(
"corr_term", corr_term_int * w_scale.float() * input_scale.float()
) # keep in FP32, cast at the end
qlin_int.org_model_has_bias = fms_mo_qlinear.bias is not None
# Combine correction term into linear.bias when possible. NOTE the magnitude of these 2
# terms could vary a lot. use fp32 in case of underflow and lose accuracy.
if qlin_int.org_model_has_bias:
new_bias = fms_mo_qlinear.bias.float() - qlin_int.corr_term
else:
new_bias = -qlin_int.corr_term
if qlin_int.use_fake_zero_shift:
# dyn sym act but with fake zp, remove corr_term from bias
new_bias += qlin_int.corr_term
delattr(qlin_int, "bias")
# sometimes reg_buffer() is unhappy about existing bias
qlin_int.register_buffer("bias", new_bias.to(fms_mo_w_dtype))
# redundant variables to be cleaned up
# qlin_int.register_buffer("Qa_clip_val", Qa.clip_val.detach())
# qlin_int.register_buffer("Qa_clip_valn", Qa.clip_valn.detach())
# qlin_int.register_buffer("Qw_clip_val", Qw.clip_val.detach())
qlin_int.set_matmul_op()
return qlin_int.to(tar_dev)
@classmethod
def from_torch_iW(cls, nnlin_iW, prec, a_cv, a_cvn, w_cv, zero_shift, **kwargs):
"""Converts a torch.nn.Linear module to a QLinearINT8Deploy.
Args:
cls (class): The class of the QLinearINT8Deploy to be created.
nnlin_iW (torch.nn.Linear): The original torch.nn.Linear module.
prec (str): The precision of the quantized weights, must be "int8".
a_cv (float): The activation CV of the input tensor.
a_cvn (float): The activation CV of the input tensor's negative part.
w_cv (float): The weight CV of the weights tensor.
zero_shift (float or str): The zero shift value. If a string,
it should be a JSON-formatted list of floats.
**kwargs: Additional keyword arguments.
Returns:
QLinearINT8Deploy: The converted QLinearINT8Deploy.
"""
assert prec == "int8", "Only support INT8 for now."
target_device = kwargs.get(
"target_device", kwargs.get("device", next(nnlin_iW.parameters()).device)
)
qlinear_iW = cls(
nnlin_iW.in_features,
nnlin_iW.out_features,
bias=nnlin_iW.bias is not None,
device=target_device,
)
qlinear_iW.nbits_a = 8 # Only support INT8 for now
qlinear_iW.nbits_w = 8
qlinear_iW.acc_dtype = kwargs.get("acc_dtype", torch.float)
qlinear_iW.usePTnativeQfunc = kwargs.get("use_PT_native_Qfunc", True)
qlinear_iW.use_int_kernel = kwargs.get(
"use_int_kernel", "triton" if available_packages["triton"] else False
)
qlinear_iW.weight = nn.Parameter(
nnlin_iW.weight.to(torch.int8), requires_grad=False
)
qlinear_iW.max_acc_bits = kwargs.get("max_acc_bits", 32)
qlinear_iW.accminmax = (
-(1 << (qlinear_iW.max_acc_bits - 1)),
(1 << (qlinear_iW.max_acc_bits - 1)) - 1,
)
qlinear_iW.truncate_lsb = kwargs.get("truncate_lsb", False)
qlinear_iW.chunk_size = kwargs.get("chunk_size", 100000)
with torch.no_grad():
if qlinear_iW.usePTnativeQfunc:
input_scale = torch.Tensor(
[(a_cv - a_cvn) / (2**qlinear_iW.nbits_a - 1)]
)
input_zero_point = torch.round(-a_cvn / input_scale).to(torch.int)
w_scale = torch.Tensor([w_cv * 2 / (2**qlinear_iW.nbits_w - 2)])
else:
# fms_mo formula is a bit different from conventional PT formula
quant_scale = (2**qlinear_iW.nbits_a - 1) / torch.Tensor([a_cv - a_cvn])
quant_stepsize = 1.0 / quant_scale
quant_zero_point = torch.round(a_cvn * quant_scale)
input_scale = quant_stepsize
input_zero_point = -quant_zero_point
quant_w_scale = (2**qlinear_iW.nbits_a - 2) / torch.Tensor([w_cv * 2])
w_scale = 1.0 / quant_w_scale
qlinear_iW.register_buffer("quant_scale", quant_scale)
qlinear_iW.register_buffer("quant_stepsize", quant_stepsize)
qlinear_iW.register_buffer("quant_zero_point", quant_zero_point)
w_zp = torch.zeros_like(w_scale, dtype=torch.int)
qlinear_iW.register_buffer("input_scale", input_scale)
qlinear_iW.register_buffer("input_zp", input_zero_point)
qlinear_iW.register_buffer("w_scale", w_scale)
qlinear_iW.register_buffer("w_zp", w_zp)
# Store original cv_a and cv_w (in python floats, not tensors), and sq scales
# for later verification