|
| 1 | +import paddle |
| 2 | +import paddle.nn as nn |
| 3 | +from paddleslim.lc.quantizers import NF4Quantizer |
| 4 | +from .linear import WeightQuantizationLinear |
| 5 | + |
| 6 | + |
| 7 | +class NF4Linear(WeightQuantizationLinear): |
| 8 | + quant_dtype = "int4" |
| 9 | + weight_dtype = "int8" |
| 10 | + |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + linear: nn.Linear, |
| 14 | + block_size=64, |
| 15 | + double_quant=False, ): |
| 16 | + super(NF4Linear, self).__init__(linear) |
| 17 | + self.block_size = block_size |
| 18 | + self.double_quant = double_quant |
| 19 | + self.quantizer = NF4Quantizer(block_size, double_quant) |
| 20 | + # PaddlePaddle dosen't support Int4 data type, one Int8 data represents two Int4 data. |
| 21 | + self.quant_weight = self.create_parameter( |
| 22 | + shape=[self.out_features // 2, self.in_features], |
| 23 | + attr=paddle.ParamAttr(self.quant_weight_name), |
| 24 | + dtype=NF4Linear.weight_dtype, |
| 25 | + is_bias=False, ) |
| 26 | + |
| 27 | + self.quant_scale_name = ".".join([self.weight_name, "quant_scale"]) |
| 28 | + self.quant_scale = self.create_parameter( |
| 29 | + shape=[self.out_features], |
| 30 | + attr=paddle.ParamAttr(self.quant_scale_name), |
| 31 | + dtype="float32", # to be fixed |
| 32 | + is_bias=False, ) |
| 33 | + if self.double_quant: |
| 34 | + self.double_quant_scale_name = ".".join( |
| 35 | + [self.weight_name, "double_quant_scale"]) |
| 36 | + self.double_quant_scale = self.create_parameter( |
| 37 | + shape=[self.out_features], |
| 38 | + attr=paddle.ParamAttr(self.double_quant_scale_name), |
| 39 | + dtype="float32", |
| 40 | + is_bias=False, ) |
| 41 | + |
| 42 | + def quantize(self, weight): |
| 43 | + quantized_weight = self.quantizer.quantize(weight) |
| 44 | + #self.set_state_dict({self.quant_weight_name: quantized_weight}) |
| 45 | + self.quant_weight.set_value(quantized_weight) |
| 46 | + #self.set_state_dict({self.quant_scale_name: self.quantizer.quant_scale}) |
| 47 | + self.quant_scale.set_value(self.quantizer.quant_scale) |
| 48 | + if self.double_quant: |
| 49 | + #self.set_state_dict({self.double_quant_scale_name: self.quantizer.double_quant_scale}) |
| 50 | + self.double_quant_scale.set_value(self.quantizer.double_quant_scale) |
| 51 | + return quantized_weight |
| 52 | + |
| 53 | + def forward(self, x): |
| 54 | + self.quantizer.quant_scale = self.state_dict[self.quant_scale_name] |
| 55 | + self.quantizer.double_quant_scale = self.state_dict[ |
| 56 | + self.double_quant_scale_name] |
| 57 | + return self.quantizer.matmul(x, self.quant_weight) |
0 commit comments