forked from PaddlePaddle/PaddleNLP
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquant.py
More file actions
Latest commit
294 lines (267 loc) Β· 10.8 KB
/
Copy pathquant.py
File metadata and controls
294 lines (267 loc) Β· 10.8 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
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
importjson
importos
importpaddle
frompaddleimportnn
frompaddle.distributed.fleet.meta_parallelimport (
ColumnParallelLinear,
RowParallelLinear,
)
frompaddle.quantizationimportPTQ, QAT, QuantConfig
frompaddleslim.quant.advancedimport (
GPTQ,
AutoClip,
AWQSearch,
EMASampler,
MultiStepSampler,
PieceWiseSearch,
Shift,
Smooth,
)
frompaddleslim.quant.advanced.utilsimportfind_parent_layer_and_sub_name
frompaddleslim.quant.layersimport (
QuantizedColumnParallelLinear,
QuantizedRowParallelLinear,
)
frompaddleslim.quant.observersimport (
AbsMaxChannelWiseWeightObserver,
AVGObserver,
GroupWiseWeightObserver,
)
frompaddleslim.quant.observers.abs_max_weightimport (
AbsMaxChannelWiseWeightObserverLayer,
)
frompaddleslim.quant.observers.avgimportAVGObserverLayer
frompaddleslim.quant.observers.groupwiseimportGroupWiseWeightObserverLayer
frompaddlenlp.peftimportPrefixModelForCausalLM
frompaddlenlp.peft.loraimport (
ColumnParallelLoRALinear,
LoRALinear,
RowParallelLoRALinear,
)
frompaddlenlp.peft.lora.lora_quant_layersimport (
ColumnParallelQuantedLoRALinear,
QuantedLoRALinear,
RowParallelQuantedLoRALinear,
)
frompaddlenlp.utils.logimportlogger
defcreate_qat_model(quant_args, model, dtype):
frompaddle.quantization.quantersimportFakeQuanterWithAbsMaxObserver
frompaddleslim.quant.quantersimport (
FakeQuanterChannelWiseAbsMaxObserver,
PACTQuanter,
)
q_config=QuantConfig(activation=None, weight=None)
q_config.add_qat_layer_mapping(LoRALinear, QuantedLoRALinear)
q_config.add_qat_layer_mapping(RowParallelLoRALinear, RowParallelQuantedLoRALinear)
q_config.add_qat_layer_mapping(ColumnParallelLoRALinear, ColumnParallelQuantedLoRALinear)
ifquant_args.quant_type=="a8w8":
activation=PACTQuanter(quanter=FakeQuanterWithAbsMaxObserver(), init_value=20.0, dtype=dtype)
weight=FakeQuanterChannelWiseAbsMaxObserver(bit_length=8, dtype="float32")
elifquant_args.quant_type=="weight_only_int4":
activation=None
weight=FakeQuanterChannelWiseAbsMaxObserver(bit_length=4, dtype="float32")
elifquant_args.quant_type=="weight_only_int8":
activation=None
weight=FakeQuanterChannelWiseAbsMaxObserver(bit_length=8, dtype="float32")
else:
raiseValueError("quant_type should be one of ['a8w8', 'weight_only_int4', 'weight_only_int8']")
q_config.add_type_config(RowParallelLoRALinear, weight=weight, activation=activation)
q_config.add_type_config(ColumnParallelLoRALinear, weight=weight, activation=activation)
q_config.add_type_config(LoRALinear, weight=weight, activation=activation)
q_config.add_type_config(nn.Linear, weight=weight, activation=activation)
qat=QAT(q_config)
model=qat.quantize(model, inplace=True)
returnmodel
defapply_shift(quant_args, trainer, ptq_dataloader, ptq_model_config):
logger.info("***** Running Shift *****")
shift_sampler=EMASampler() ifquant_args.shift_sampler=="ema"elseNone
shift=Shift(
model=trainer.model,
model_config=ptq_model_config,
sample_function=shift_sampler,
shift_all_linears=quant_args.shift_all_linears,
)
withpaddle.no_grad():
trainer.ptq_loop(
ptq_dataloader,
description="Shift",
max_eval_iters=quant_args.shift_step,
)
shift.update_weight()
delshift, shift_sampler
logger.info("***** Shift done *****")
defapply_smooth(quant_args, trainer, ptq_dataloader, ptq_model_config):
ifquant_args.do_awq:
logger.info("***** Running AWQ *****")
else:
logger.info("***** Running Smooth *****")
smooth_sampler=MultiStepSampler() ifquant_args.smooth_sampler=="multi_step"elseNone
ifquant_args.smooth_piecewise_search:
search_func=PieceWiseSearch(
k_piece=quant_args.smooth_k_piece,
bits_length=8,
search_piece=quant_args.smooth_search_piece,
search_alpha_min=0.2,
search_alpha_max=0.8,
search_scale_min=1.0,
search_scale_max=5.0,
weight_quant_method="abs_max_channel_wise",
act_quant_method="avg",
)
elifquant_args.do_awq:
search_func=AWQSearch(
n_grid=20,
bits_length=4,
weight_quant_method=quant_args.weight_quant_method,
)
else:
search_func=None
smooth=Smooth(
trainer.model,
ptq_model_config,
alpha=0.5,
smooth_all_linears=quant_args.smooth_all_linears,
sample_function=smooth_sampler,
search_function=search_func,
smooth_method="awq"ifquant_args.do_awqelse"smoothquant",
)
withpaddle.no_grad():
trainer.ptq_loop(
ptq_dataloader,
description="Smooth",
max_eval_iters=quant_args.smooth_step,
)
smooth.update_weight()
delsmooth, smooth_sampler, search_func
logger.info("***** Smooth done *****")
defapply_autoclip(quant_args, trainer, ptq_dataloader):
"""
AutoClip
"""
print("-------------------Start AutoClip------------------")
sampler=MultiStepSampler()
auto_clip=AutoClip(
trainer.model,
weight_bits=4,
weight_quant_method=quant_args.weight_quant_method,
sample_function=sampler,
n_grid=20,
max_shrink=0.5,
)
withpaddle.no_grad():
trainer.ptq_loop(
ptq_dataloader,
description="AutoClip",
max_eval_iters=quant_args.autoclip_step,
)
auto_clip.auto_clip()
delsampler, auto_clip
logger.info("***** AutoClip done *****")
defapply_ptq(quant_args, trainer, ptq_dataloader):
logger.info("***** Running PTQ *****")
q_config=QuantConfig(activation=None, weight=None)
ifquant_args.weight_quant_method=="abs_max_channel_wise":
weight_observer=AbsMaxChannelWiseWeightObserver
elifquant_args.weight_quant_method=="groupwise":
weight_observer=GroupWiseWeightObserver
else:
raiseValueError("weight_quant_method should be one of ['abs_max_channel_wise', 'groupwise']")
ifquant_args.quant_type=="a8w8":
activation=AVGObserver(quant_bits=8)
weight=weight_observer(quant_bits=8)
elifquant_args.quant_type=="weight_only_int4":
activation=None
weight=weight_observer(quant_bits=4)
elifquant_args.quant_type=="weight_only_int8":
activation=None
weight=weight_observer(quant_bits=8)
else:
raiseValueError("quant_type should be one of ['a8w8', 'weight_only_int4', 'weight_only_int8']")
q_config.add_qat_layer_mapping(ColumnParallelLinear, QuantizedColumnParallelLinear)
q_config.add_qat_layer_mapping(RowParallelLinear, QuantizedRowParallelLinear)
q_config.add_type_config(
[paddle.nn.Linear, ColumnParallelLinear, RowParallelLinear, QuantedLoRALinear],
activation=activation,
weight=weight,
)
ptq=PTQ(q_config)
trainer.model=ptq.quantize(trainer.model, inplace=True)
trainer.ptq_loop(
ptq_dataloader,
description="PTQ",
max_eval_iters=quant_args.ptq_step,
)
weight_scales= {}
act_scales= {}
forcur_name, cur_layerintrainer.model.named_sublayers():
ifisinstance(cur_layer, AbsMaxChannelWiseWeightObserverLayer):
if"_observer"notincur_name:
weight_scales[cur_name] =cur_layer.scales().numpy().tolist()
ifisinstance(cur_layer, GroupWiseWeightObserverLayer):
if"_observer"notincur_name:
weight_scales[cur_name] =cur_layer.scales().numpy().tolist()
ifisinstance(cur_layer, AVGObserverLayer):
if"_observer"notincur_name:
act_scales[cur_name] =cur_layer.scales().numpy().tolist()
weight_scales_path=os.path.join(trainer.args.output_dir, "weight_scales.json")
withopen(weight_scales_path, "w") asf:
json.dump(weight_scales, f)
logger.info(f"Weight scales saved in {weight_scales_path}.")
act_scales_path=os.path.join(trainer.args.output_dir, "act_scales.json")
withopen(act_scales_path, "w") asf:
json.dump(act_scales, f)
logger.info(f"Activation scales saved in {act_scales_path}.")
trainer.model=ptq.convert(trainer.model, inplace=True)
logger.info("***** PTQ done *****")
defapply_gptq(quant_args, trainer, ptq_dataloader):
logger.info("***** Running GPTQ *****")
num_layer=0
model=trainer.model
forcur_name, cur_layerinmodel.named_sublayers():
iftype(cur_layer) in [paddle.nn.Linear, ColumnParallelLinear, RowParallelLinear]:
num_layer+=1
logger.info(f"GPTQ layer: {num_layer}, {cur_name}")
parent_layer, sub_name=find_parent_layer_and_sub_name(model, cur_name)
cur_quant_layer=GPTQ(cur_layer)
setattr(parent_layer, sub_name, cur_quant_layer)
withpaddle.no_grad():
trainer.ptq_loop(
ptq_dataloader,
description="GPTQ",
max_eval_iters=quant_args.gptq_step,
)
cur_quant_layer.fasterquant(percdamp=0.1, groupsize=-1, actorder=True)
delcur_quant_layer
setattr(parent_layer, sub_name, cur_layer)
logger.info("***** GPTQ done *****")
defget_ptq_model_config(model):
ifisinstance(model, PrefixModelForCausalLM):
base_model_prefix=model.model.base_model_prefix
else:
base_model_prefix=model.base_model_prefix
ifbase_model_prefixin ["chatglm"]:
raiseNotImplementedError(f"{model} does not support Shift or Smooth.")
elifbase_model_prefix=="chatglm_v2":
model_config= {"fused_qkv": False, "parallel_ffn": False, "skip_norm_list": ["rms_norm_56"]}
elifbase_model_prefix=="bloom":
model_config= {"fused_qkv": True, "parallel_ffn": False}
elifbase_model_prefix=="llama":
model_config= {"fused_qkv": False, "parallel_ffn": True}
else:
raiseValueError(
f"Unknown base_model_prefix: {model.base_model_prefix}. Supported base_model_prefix list: chatglm_V2, bloom, llama."
)
returnmodel_config