-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathmode.py
More file actions
504 lines (395 loc) · 17.1 KB
/
mode.py
File metadata and controls
504 lines (395 loc) · 17.1 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
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
"""This module contains the mode descriptor for the quantization mode."""
from abc import abstractmethod
from collections.abc import Callable
from modelopt.torch.opt.config import ModeloptBaseConfig
from modelopt.torch.opt.conversion import ModelLikeModule
from modelopt.torch.opt.mode import (
ConvertEntrypoint,
ConvertReturnType,
ModeConfigList,
ModeDescriptor,
RestoreEntrypoint,
UpdateEntrypoint,
_ModeRegistryCls,
)
from modelopt.torch.opt.searcher import ForwardLoop
from .compress import compress_convert, compress_restore, update_compress_metadata
from .config import (
AWQClipCalibConfig,
AWQFullCalibConfig,
AWQLiteCalibConfig,
CompressConfig,
GPTQLiteConfig,
LocalHessianCalibConfig,
MaxCalibConfig,
MseCalibConfig,
QuantizeAlgoCfgType,
QuantizeAlgorithmConfig,
QuantizeConfig,
SmoothQuantCalibConfig,
SVDQuantConfig,
_QuantizeExportConfig,
)
from .conversion import (
convert_to_quantized_model,
export_quantized_model,
restore_export_quantized_model,
restore_quantized_model,
restore_quantizer_state,
restore_svdquant_model,
update_quantize_metadata,
)
from .model_calib import (
awq,
gptq_lite,
local_hessian_calibrate,
max_calibrate,
mse_calibrate,
sequential_calibrate,
smoothquant,
svdquant,
)
__all__ = ["BaseCalibrateModeDescriptor"]
QuantizeModeRegistry = _ModeRegistryCls("quantization")
# TODO: OMNIML-717 Reuse search infra for quantization calibration algorithms
@QuantizeModeRegistry.register_mode
class QuantizeModeDescriptor(ModeDescriptor):
"""Class to describe the ``"quant"`` mode.
The properties of this mode can be inspected via the source code.
"""
@property
def name(self) -> str:
"""Returns the value (str representation) of the mode."""
return "quantize"
@property
def config_class(self) -> type[ModeloptBaseConfig]:
"""Specifies the config class for the mode."""
return QuantizeConfig
@property
def next_prohibited_modes(self) -> set[str] | None:
"""Modes that should not be applied after this mode."""
return {"sparsity", "autonas", "fastnas", "gradnas"}
@property
def export_mode(self) -> str | None:
"""The mode that corresponds to the export mode of this mode."""
return "export_quantize"
@property
def convert(self) -> ConvertEntrypoint:
"""The mode's entrypoint for converting a model."""
return convert_to_quantized_model
@property
def restore(self) -> RestoreEntrypoint:
"""The mode's entrypoint for restoring a model."""
return restore_quantized_model
@property
def update_for_save(self) -> UpdateEntrypoint:
"""The mode's entrypoint for updating the models state before saving."""
return update_quantize_metadata
@property
def update_for_new_mode(self) -> UpdateEntrypoint:
"""The mode's entrypoint for updating the models state before new mode."""
return update_quantize_metadata
@QuantizeModeRegistry.register_mode
class QuantizeExportModeDescriptor(ModeDescriptor):
"""Class to describe the export of quantization mode.
Note that this mode is just a placeholder to throw an error since we don't support exporting
quantized models right now. It is used to properly indicate that the ``quantize`` mode does
require an export mode if we ever wanted to do chaining/stacking of modes with it.
"""
@property
def name(self) -> str:
"""Returns the value (str representation) of the mode."""
return "quantize_export"
@property
def config_class(self) -> type[ModeloptBaseConfig]:
"""Specifies the config class for the mode."""
return _QuantizeExportConfig
@property
def is_export_mode(self) -> bool:
"""Specifies whether the mode is an export mode."""
return True
@property
def convert(self) -> ConvertEntrypoint:
"""The mode's entrypoint for converting a model."""
return export_quantized_model
@property
def restore(self) -> RestoreEntrypoint:
"""The mode's entrypoint for restoring a model."""
return restore_export_quantized_model
@QuantizeModeRegistry.register_mode
class RealQuantizeModeDescriptor(ModeDescriptor):
"""Mode for real quantization."""
@property
def name(self) -> str:
"""Returns the value (str representation) of the mode."""
return "real_quantize"
@property
def next_modes(self) -> set[str] | None:
"""Real quantization should be the last mode in the chain."""
# TODO: update this to support QLoRA
return {"max_calibrate", "eagle"}
@property
def config_class(self) -> type[ModeloptBaseConfig]:
"""Specifies the config class for the mode."""
return CompressConfig
@property
def convert(self) -> ConvertEntrypoint:
"""The mode's entrypoint for converting a model."""
return compress_convert
@property
def restore(self) -> RestoreEntrypoint:
"""The mode's entrypoint for restoring a model."""
return compress_restore
@property
def update_for_save(self) -> UpdateEntrypoint:
"""The mode's entrypoint for updating the models state before saving."""
return update_compress_metadata
@property
def update_for_new_mode(self) -> UpdateEntrypoint:
"""The mode's entrypoint for updating the models state before new mode."""
return update_compress_metadata
@QuantizeModeRegistry.register_mode
class AutoQuantizeModeDescriptor(QuantizeModeDescriptor):
"""Mode for autoquantize."""
@property
def name(self) -> str:
"""Returns the value (str representation) of the mode."""
return "auto_quantize"
def wrapped_calib_func(
model: ModelLikeModule,
config: QuantizeAlgorithmConfig,
forward_loop: ForwardLoop | None = None,
func: Callable | None = None,
) -> ConvertReturnType:
"""Wrap the calibration function to be compatible with the ModelOpt convert entrypoint.
The calibration algorithms in ..model_calib.py are designed to be called directly with the model,
forward_loop and the relevant kwargs and are independent of the ModelOpt framework.
So lets wrap them to be compatible with the ModelOpt convert entrypoint.
"""
kwargs = config.model_dump()
method = kwargs.pop("method")
sequential = kwargs.pop("use_sequential", False)
if method is not None and "awq" in method:
# For backward compatibility
kwargs["algorithm"] = method
moe_calib_experts_ratio = kwargs.pop("moe_calib_experts_ratio", None)
if moe_calib_experts_ratio is not None:
assert (
isinstance(moe_calib_experts_ratio, (int, float)) and 0 < moe_calib_experts_ratio <= 1
), f"Invalid moe_calib_experts_ratio {moe_calib_experts_ratio!r}"
for module in model.modules():
if hasattr(module, "_moe_calib_experts_ratio"):
module._moe_calib_experts_ratio = moe_calib_experts_ratio
if func is not None:
if sequential:
if forward_loop is None:
raise ValueError("forward_loop is required for calibration but got None.")
assert method in ["max"], (
f"Sequential calibration currently only supports max calibration, got {method}"
)
# Wrap with sequential processing
sequential_calibrate(
model,
forward_loop=forward_loop,
calib_func=func,
**kwargs,
)
else:
# Direct calibration (existing behavior)
func(model, forward_loop=forward_loop, **kwargs)
# Lets get the latest metadata for the quantizer states
metadata = {}
update_quantize_metadata(model, config, metadata)
return model, metadata
class BaseCalibrateModeDescriptor(ModeDescriptor):
"""Base class for quantization calibration algorithm modes.
All calibration algorithm modes must be derived from this base class.
In addition, the `config_class` for the mode must return a subclass of :class:`QuantizeAlgorithmConfig`.
This base class also provides some convenient wrappers/utilities for calibration algorithms to be
translated into ModelOpt mode.
It includes:
1. A utility to convert the algorithm name to a mode name. This is useful since many algorithm names
are trivial and not a good fit as a mode name. For example, ``"max"`` or ``None``.
2. Conversion of the ``algorithm`` and ``kwargs`` arguments of
:meth:`calibrate <modelopt.torch.quantization.model_quant.calibrate>` API to a mode config
list compatible with :meth:`apply_mode <modelopt.torch.opt.conversion.apply_mode>`.
3. Wrapper for the calibration functions in :mod:`modelopt.torch.quantization.model_calib` to be
compatible with the ModelOpt convert entrypoint.
"""
_calib_func: Callable | None
def __init__(self, *args, **kwargs):
"""Initialize Base calibrate mode descriptor."""
assert issubclass(self.config_class, QuantizeAlgorithmConfig), (
f"`config_class` of {self.__class__} must be a subclass of `QuantizeAlgorithmConfig`!, "
f"got {self.config_class}!"
)
super().__init__(*args, **kwargs)
@classmethod
def _get_mode_name(cls, algo_name: str | None = None, check: bool = False) -> str:
mode_name = algo_name + "_calibrate" if algo_name else "_no_calibrate"
if check:
assert mode_name in CalibrateModeRegistry, (
f"Algorithm {algo_name} not found in CalibrateModeRegistry!"
)
return mode_name
@property
def name(self) -> str:
"""Returns the value (str representation) of the mode."""
return self._get_mode_name(self.config_class().method)
@property
@abstractmethod
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
@property
def convert(self) -> ConvertEntrypoint:
"""The calibrate algorithm mode's entrypoint for converting a model.
This method is called by the ModelOpt framework when applying this calibration mode to a model.
See :meth:`wrapped_calib_func` for more details on the logic.
Note: Subclasses must specify the `_calib_func` class attribute with the appropriate
calibration function to be used or override this method.
"""
assert hasattr(self.__class__, "_calib_func"), (
f"Calibration function '_calib_func' not defined for {self.__class__}, "
"either define it or override the `convert` method!"
)
def wrapped_func(model, config, forward_loop=None):
# Access _calib_func as a class attribute to avoid binding
# Check if _calib_func is defined as a class attribute
return wrapped_calib_func(model, config, forward_loop, func=self.__class__._calib_func)
return wrapped_func
@property
def restore(self) -> RestoreEntrypoint:
"""The mode's entrypoint for restoring a model."""
return restore_quantizer_state
@property
def update_for_save(self) -> UpdateEntrypoint:
"""The mode's entrypoint for updating the models state before saving."""
return update_quantize_metadata
@property
def update_for_new_mode(self) -> UpdateEntrypoint:
"""The mode's entrypoint for updating the models state before new mode."""
return update_quantize_metadata
def get_modelike_from_algo_cfg(algo_cfg: QuantizeAlgoCfgType) -> ModeConfigList:
"""Get the mode like from the algorithm config."""
if isinstance(algo_cfg, list):
assert not any(isinstance(c, list) for c in algo_cfg), (
f"Nested lists received as config! config: {algo_cfg}"
)
return [get_modelike_from_algo_cfg(c)[0] for c in algo_cfg]
if algo_cfg is None or isinstance(algo_cfg, str):
algo_name, algo_cfg = algo_cfg, {}
elif isinstance(algo_cfg, dict):
algo_name = algo_cfg["method"]
else:
raise ValueError(f"Invalid config type: {type(algo_cfg)}")
return [(BaseCalibrateModeDescriptor._get_mode_name(algo_name, check=True), algo_cfg)]
class _CalibrateModeRegistryCls(_ModeRegistryCls):
def register_mode(self, cls_descriptor: type[_ModeRegistryCls.T]) -> type[_ModeRegistryCls.T]:
"""Register a new mode with the given descriptor."""
assert issubclass(cls_descriptor, BaseCalibrateModeDescriptor), (
f"Mode descriptor for `_CalibrateModeRegistryCls` must be a subclass of `BaseCalibrateModeDescriptor`! "
f"Got: {cls_descriptor}"
)
return super().register_mode(cls_descriptor)
CalibrateModeRegistry = _CalibrateModeRegistryCls("calibrate_algos")
@CalibrateModeRegistry.register_mode
class NoneCalibrateModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for no calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return QuantizeAlgorithmConfig
_calib_func = None
@CalibrateModeRegistry.register_mode
class MaxCalibrateModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for max calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return MaxCalibConfig
_calib_func = max_calibrate
@CalibrateModeRegistry.register_mode
class MseCalibrateModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for mse calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return MseCalibConfig
_calib_func = mse_calibrate
@CalibrateModeRegistry.register_mode
class LocalHessianModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for local Hessian-weighted MSE calibration algorithm.
This algorithm uses activation information to optimize per-block scales for weight
quantization by minimizing output reconstruction error instead of weight reconstruction error.
"""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return LocalHessianCalibConfig
_calib_func = local_hessian_calibrate
@CalibrateModeRegistry.register_mode
class SmoothQuantModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for smoothquant calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return SmoothQuantCalibConfig
_calib_func = smoothquant
@CalibrateModeRegistry.register_mode
class AWQLiteModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for AWQ lite calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return AWQLiteCalibConfig
_calib_func = awq
@CalibrateModeRegistry.register_mode
class AWQClipModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for AWQ clip calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return AWQClipCalibConfig
_calib_func = awq
@CalibrateModeRegistry.register_mode
class AWQFullModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for AWQ full calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return AWQFullCalibConfig
_calib_func = awq
@CalibrateModeRegistry.register_mode
class SVDQuantModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for SVDQuant calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return SVDQuantConfig
_calib_func = svdquant
@property
def restore(self) -> RestoreEntrypoint:
"""The mode's entrypoint for restoring a model."""
return restore_svdquant_model
@CalibrateModeRegistry.register_mode
class GPTQLiteModeDescriptor(BaseCalibrateModeDescriptor):
"""Mode for GPTQ calibration algorithm."""
@property
def config_class(self) -> type[QuantizeAlgorithmConfig]:
"""Specifies the config class for the mode."""
return GPTQLiteConfig
_calib_func = gptq_lite