-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrunner.py
More file actions
2166 lines (1823 loc) · 84.1 KB
/
Copy pathrunner.py
File metadata and controls
2166 lines (1823 loc) · 84.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
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 2025-2026 Fujitsu Ltd.
Author: Keiji Kimura
"""
# pylint: disable=too-many-arguments, too-many-positional-arguments
import copy
import math
import gc
import json
import os
from typing import Optional
import time
from logging import getLogger
from pathlib import Path
import torch
from .__version__ import __version__
from .calibration import CalibrationConfig, prepare_calibration_dataset
from .model_config import ModelConfig
from .qep import QEPConfig
from .lpcd import LPCDConfig
from .quantizer import GPTQ, Quantizer
from .quantizer.autobit import AutoBitQuantizer
from .utils import calculate_accuracy as calc_accuracy
from .utils import calculate_perplexity as calc_perplexity
from .utils.quantization_progress import QuantizationProgressTracker
from .log import setup_logger
class Runner:
"""Runner class for model quantization
Runner class for executing quantization.
Supports quantization using calibration data and parallel quantization on multiple GPUs.
Examples:
Single GPU quantization (default):
>>> from onecomp import Runner, ModelConfig
>>> from onecomp.quantizer.gptq import GPTQ
>>> model_config = ModelConfig(model_id_or_path="meta-llama/Llama-2-7b-hf")
>>> quantizer = GPTQ(wbits=4, groupsize=128)
>>> runner = Runner(
... model_config=model_config,
... quantizer=quantizer,
... )
>>> runner.run()
Multi-GPU quantization (layer-wise parallel):
>>> from onecomp.quantizer.jointq import JointQ
>>> quantizer = JointQ(bits=4, group_size=128)
>>> # Use all available GPUs
>>> runner = Runner(
... model_config=model_config,
... quantizer=quantizer,
... multi_gpu=True,
... )
>>> runner.run()
>>> # Use specific GPUs (e.g., GPU 0, 2, 3)
>>> runner = Runner(
... model_config=model_config,
... quantizer=quantizer,
... multi_gpu=True,
... gpu_ids=[0, 2, 3],
... )
>>> runner.run()
"""
def __init__(
self,
model_config=None,
quantizer=None,
quantizers=None,
calibration_config=None,
qep=False,
qep_config=None,
lpcd=False,
lpcd_config=None,
multi_gpu=False,
gpu_ids=None,
post_processes=None,
report_progress=True,
):
"""__init__ method
Args:
model_config (ModelConfig):
Model configuration. Required.
quantizer (Quantizer):
The quantizer to use. Specify either ``quantizer`` or
``quantizers``, not both. At least one must be given.
quantizers (list[Quantizer]):
Specify multiple quantizers. When used with
``calibration_config.batch_size``, the X^T X accumulation
is shared, reducing the forward pass to a single execution.
Specify either ``quantizer`` or ``quantizers``, not both.
Currently, this is only available when
``calibration_config.batch_size`` is set and ``qep=False``.
calibration_config (CalibrationConfig or None):
Calibration data configuration. When ``None`` (default),
a :class:`CalibrationConfig` with default values is
created automatically.
See :class:`CalibrationConfig` for available fields.
qep (bool):
Whether to use QEP.
qep_config (QEPConfig or None):
Configuration for QEP. If None and ``qep=True``,
a default ``QEPConfig()`` is used.
lpcd (bool):
Whether to use LPCD.
lpcd_config (LPCDConfig or None):
Configuration for LPCD. If None and ``lpcd=True``,
a default ``LPCDConfig()`` is used.
multi_gpu (bool):
Whether to use multi-GPU for layer-wise parallel quantization.
Default is False.
gpu_ids (list[int]):
List of GPU IDs to use for multi-GPU quantization.
If None and multi_gpu is True, all available GPUs will be used.
post_processes (list[PostQuantizationProcess] or None):
Optional list of post-quantization processes to execute
after the main quantization step. Each process receives
a quantized model on CPU (built via
``create_quantized_model``) and may modify it in-place.
Processes are executed in order. Default is None.
report_progress (bool):
When ``True`` (default), emit ``[progress]`` log lines with
completed steps, elapsed time, and a linear ETA estimate
during long quantization (calibration, chunked, multi-GPU,
QEP). Set to ``False`` for quiet runs (e.g. CI).
Note:
For zero-config quantization (VRAM auto-estimation +
AutoBitQuantizer + QEP), use the class method
:meth:`auto_run` instead.
Examples:
Chunked calibration with GPTQ (large-scale calibration data):
>>> from onecomp import Runner, ModelConfig, CalibrationConfig
>>> from onecomp.quantizer.gptq import GPTQ
>>> model_config = ModelConfig(
... model_id_or_path="meta-llama/Llama-2-7b-hf"
... )
>>> quantizer = GPTQ(wbits=4, groupsize=128)
>>> calib_config = CalibrationConfig(
... max_length=2048,
... num_calibration_samples=1024,
... batch_size=128,
... )
>>> runner = Runner(
... model_config=model_config,
... quantizer=quantizer,
... calibration_config=calib_config,
... )
>>> runner.run()
With custom num_layers_per_group:
>>> calib_config = CalibrationConfig(
... max_length=2048,
... num_calibration_samples=1024,
... batch_size=128,
... num_layers_per_group=14,
... )
>>> runner = Runner(
... model_config=model_config,
... quantizer=quantizer,
... calibration_config=calib_config,
... )
>>> runner.run()
Multiple quantizers (benchmark comparison):
>>> from onecomp.quantizer.gptq import GPTQ
>>> from onecomp.quantizer.jointq import JointQ
>>> gptq = GPTQ(wbits=4, groupsize=128, calc_quant_error=True)
>>> jointq = JointQ(bits=4, group_size=128, calc_quant_error=True,
... device=torch.device(0))
>>> calib_config = CalibrationConfig(
... max_length=2048,
... num_calibration_samples=1024,
... batch_size=128,
... )
>>> runner = Runner(
... model_config=model_config,
... quantizers=[gptq, jointq],
... calibration_config=calib_config,
... )
>>> runner.run()
>>> # Results are stored in gptq.results and jointq.results respectively
"""
self.model_config = model_config
self.logger = getLogger(__name__)
self.quantizer = quantizer
self.quantizers = quantizers
if calibration_config is None:
calibration_config = CalibrationConfig()
self.calibration_config = calibration_config
self.qep = qep
self.multi_gpu = multi_gpu
self.gpu_ids = gpu_ids
self.post_processes = post_processes or []
self.quantized_model = None
self.qep_config = None
if qep:
self.qep_config = qep_config if qep_config is not None else QEPConfig()
self.lpcd_config = None
if lpcd:
self.lpcd_config = lpcd_config if lpcd_config is not None else LPCDConfig()
self.report_progress = report_progress
def check(self):
"""Check the settings
Performs the following checks:
1. ``model_config`` is a ``ModelConfig`` instance
2. Mutual exclusion check for ``quantizer`` and ``quantizers`` (cannot specify both)
3. Type check for ``quantizer`` / ``quantizers`` (must be ``Quantizer`` instances)
4. At least one of them must be specified
5. Parameter combination consistency check (see table below)
6. When ``multi_gpu=True``, ``quantizer.flag_calibration=True`` must hold
Valid parameter combinations:
=========== ==== ========== ================================
quantizers qep multi_gpu calibration_config.batch_size
=========== ==== ========== ================================
Specified False False Specified
None True False None
None False True None
None False False Specified
None False False None
=========== ==== ========== ================================
Note:
``multi_gpu=True`` requires a quantizer with ``flag_calibration=True``.
Raises:
TypeError: Invalid type for ``model_config``, ``quantizer``, or ``quantizers``
ValueError: Invalid parameter combination
"""
if not isinstance(self.model_config, ModelConfig):
raise TypeError("`model_config` is not a `ModelConfig` object")
# Type check for quantizer / quantizers
if self.quantizer is not None and self.quantizers is not None:
raise ValueError(
"Cannot specify both 'quantizer' and 'quantizers'. Use one or the other."
)
if self.quantizers is not None:
for i, q in enumerate(self.quantizers):
if not isinstance(q, Quantizer):
raise TypeError(f"`quantizers[{i}]` is not a `Quantizer` object")
elif self.quantizer is not None:
if not isinstance(self.quantizer, Quantizer):
raise TypeError("`quantizer` is not a `Quantizer` object")
else:
raise ValueError("Either 'quantizer' or 'quantizers' must be specified.")
# Parameter combination check
batch_size = self.calibration_config.batch_size
if self.quantizers is not None:
# quantizers mode: qep=False, multi_gpu=False, batch_size required
if self.qep:
raise ValueError("'quantizers' cannot be used with qep=True.")
if self.multi_gpu:
raise ValueError("'quantizers' cannot be used with multi_gpu=True.")
if batch_size is None:
raise ValueError(
"'quantizers' requires 'calibration_config.batch_size' to be set."
)
else:
# Single quantizer mode: combination check
if self.qep and self.multi_gpu:
raise ValueError("'qep' and 'multi_gpu' cannot be used together.")
if self.qep and batch_size is not None:
raise ValueError("'qep' cannot be used with 'calibration_config.batch_size'.")
if self.multi_gpu and batch_size is not None:
raise ValueError(
"'multi_gpu' cannot be used with 'calibration_config.batch_size'."
)
if self.multi_gpu and not self.quantizer.flag_calibration:
raise ValueError("'multi_gpu' requires a quantizer with flag_calibration=True.")
if self.qep and not self.quantizer.flag_qep_supported:
raise ValueError(
f"Quantizer '{type(self.quantizer).__name__}' "
f"(or one of its candidate quantizers) does not support "
f"QEP (Quantization Error Propagation). "
f"Set qep=False, or use a QEP-compatible quantizer "
f"(e.g., GPTQ, DBF, AutoBitQuantizer with "
f"QEP-compatible candidates)."
)
# Cross-validate calibration_dataset when AutoBitQuantizer is used
quantizer = self.quantizer or (self.quantizers[0] if self.quantizers else None)
if isinstance(quantizer, AutoBitQuantizer) and quantizer.calibration_config is not None:
runner_ds = self.calibration_config.calibration_dataset
quantizer_ds = quantizer.calibration_config.calibration_dataset
if runner_ds != quantizer_ds:
raise ValueError(
f"Calibration dataset mismatch: Runner uses "
f"{runner_ds!r} but quantizer uses {quantizer_ds!r}. "
f"Set the same calibration_dataset in both "
f"CalibrationConfig objects."
)
def _exclude_moe_router_if_needed(self):
"""Exclude MoE router layers from quantization.
vLLM's GateLinear (used for MoE routing) hardcodes
quant_config=None, so router weights must stay unquantized.
"""
config = self.model_config.load_config()
num_experts = (
getattr(config, "num_experts", 0)
or getattr(getattr(config, "text_config", None), "num_experts", 0)
or 0
)
if num_experts == 0:
return
keyword = "router"
target_quantizers = self.quantizers if self.quantizers is not None else [self.quantizer]
for q in target_quantizers:
if q.exclude_layer_keywords is None:
q.exclude_layer_keywords = [keyword]
elif keyword not in q.exclude_layer_keywords:
q.exclude_layer_keywords = list(q.exclude_layer_keywords) + [keyword]
self.logger.info(
"MoE model (num_experts=%d): excluding '%s' layers from "
"quantization (vLLM GateLinear does not support quantization)",
num_experts,
keyword,
)
def run(self):
"""Execute quantization (and related) processing"""
start_time = time.time()
logger = self.logger
logger.info("OneComp version: %s", __version__)
logger.info("Model: %s", self.model_config.get_model_id_or_path())
logger.info("Start the run method of Runner class")
logger.info("Checking the settings...")
self.check()
self._exclude_moe_router_if_needed()
if self.lpcd_config is not None:
logger.info("Start quantization with LPCD")
self.quantize_with_lpcd()
elif self.qep:
logger.info("Start quantization with error propagation (QEP)")
self.quantize_with_qep()
else:
logger.info("Start quantization")
self.quantize()
if self.post_processes:
self.run_post_processes()
elapsed_time = time.time() - start_time
logger.info(
"Finished the run method of Runner class (elapsed time: %.2f seconds)",
elapsed_time,
)
# Calculate total and average from per-layer quantization times and log them
target_quantizers = self.quantizers if self.quantizers is not None else [self.quantizer]
for q in target_quantizers:
quant_times = [
result.quantization_time
for result in q.results.values()
if result.quantization_time is not None
]
if quant_times:
total_quant_time = sum(quant_times)
avg_quant_time = total_quant_time / len(quant_times)
logger.info(
"[%s] Quantization time: total=%.2f seconds, "
"average=%.2f seconds/layer (%d layers)",
q.name,
total_quant_time,
avg_quant_time,
len(quant_times),
)
@classmethod
def auto_run(
cls,
model_id: str,
wbits: Optional[float] = None,
total_vram_gb: Optional[float] = None,
groupsize: int = 128,
device: str = "cuda:0",
qep: bool = True,
evaluate: bool = True,
eval_original_model: bool = False,
save_dir: str = "auto",
check_env: bool = False,
**kwargs,
):
"""One-liner quantization with sensible defaults.
Sets up ModelConfig, AutoBitQuantizer (ILP-based mixed-precision),
and QEP, then runs quantization. When ``wbits`` is ``None``,
the target bitwidth is estimated automatically from available VRAM.
Optionally evaluates perplexity and accuracy, and saves the
quantized model.
Args:
model_id (str): Hugging Face model ID or local path.
wbits (float or None): Target quantization bitwidth.
When ``None`` (default), estimated from VRAM via
``estimate_wbits_from_vram``.
total_vram_gb (float or None): Total VRAM budget in GB for
bitwidth estimation. Only used when ``wbits`` is ``None``.
When ``None``, the installed GPU VRAM is detected
automatically.
groupsize (int): GPTQ group size (default: 128).
Use -1 to disable grouping.
device (str): Device to place the model on (default: "cuda:0").
qep (bool): Whether to use QEP (default: True).
evaluate (bool): Whether to calculate perplexity and
accuracy after quantization (default: True).
eval_original_model (bool): Whether to also evaluate the
original (unquantized) model (default: False).
save_dir (str or None): Directory to save the quantized model.
``"auto"`` (default) derives the path from model_id
(e.g., ``"TinyLlama-1.1B-...-autobit-3.5bit"``).
Set to ``None`` to skip saving.
**kwargs: Additional keyword arguments forwarded to the
``GPTQ`` constructor (e.g., ``actorder``, ``sym``).
Returns:
Runner: The configured Runner instance (with quantization
results accessible via ``runner.quantizer.results``).
Examples:
Minimal usage (QEP + GPTQ 4-bit, groupsize=128, auto-save):
>>> from onecomp import Runner
>>> runner = Runner.auto_run(
... model_id="TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T"
... )
Custom save directory:
>>> runner = Runner.auto_run(
... model_id="TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T",
... save_dir="./my_quantized_model",
... )
Skip saving:
>>> runner = Runner.auto_run(
... model_id="TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T",
... save_dir=None,
... )
Evaluate both original and quantized models:
>>> runner = Runner.auto_run(
... model_id="TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T",
... eval_original_model=True,
... )
"""
setup_logger()
logger = getLogger(__name__)
if check_env:
from .utils.vram_estimator import ( # pylint: disable=import-outside-toplevel
check_environment,
print_env_report,
)
env_result = check_environment(
model_id,
total_vram_gb=total_vram_gb,
group_size=groupsize,
save_dir=save_dir if isinstance(save_dir, str) and save_dir != "auto" else None,
)
print_env_report(env_result, total_vram_gb_override=total_vram_gb)
if env_result.risk == "danger":
raise RuntimeError(
f"Environment check failed (OOM risk=danger): {env_result.risk_detail}"
)
candidate_bits = (2, 3, 4, 8)
if wbits is None:
from .utils import estimate_wbits_from_vram
result = estimate_wbits_from_vram(
model_id,
total_vram_gb=total_vram_gb,
group_size=groupsize,
logger=logger,
)
wbits = math.floor(result.target_bitwidth * 100) / 100
logger.info(
"VRAM estimation → target wbits=%.2f (%.2f GB total, ratio=80%%)",
wbits,
result.total_vram_gb,
)
_id_lower = model_id.lower()
is_gemma4 = any(key in _id_lower for key in ("gemma-4", "gemma4", "gemma_4"))
model_config = ModelConfig(model_id=model_id, device=device)
if is_gemma4:
valid_wbits = [b for b in candidate_bits if b <= wbits]
if not valid_wbits:
raise ValueError(
f"target wbits={wbits:.2f} is below all candidate "
f"bit-widths {candidate_bits}; cannot select a "
f"uniform GPTQ configuration for Gemma 4"
)
uniform_bit = max(valid_wbits)
if save_dir == "auto":
model_name = model_id.rstrip("/").split("/")[-1]
save_dir = f"{model_name}-gptq-{uniform_bit}bit"
logger.warning(
"Gemma 4 detected → falling back to uniform GPTQ %d-bit " "(target wbits=%.2f)",
uniform_bit,
wbits,
)
quantizer = GPTQ(wbits=uniform_bit, groupsize=groupsize, **kwargs)
else:
if save_dir == "auto":
model_name = model_id.rstrip("/").split("/")[-1]
save_dir = f"{model_name}-autobit-{wbits}bit"
from .quantizer.autobit import AutoBitQuantizer
candidate_quantizers = [
GPTQ(wbits=b, groupsize=groupsize, **kwargs) for b in candidate_bits
]
quantizer = AutoBitQuantizer(
assignment_strategy="activation_aware",
quantizers=candidate_quantizers,
target_bit=wbits,
save_path=save_dir if save_dir is not None else None,
enable_fused_groups=True,
)
runner = cls(model_config=model_config, quantizer=quantizer, qep=qep)
runner.run()
if evaluate:
original_ppl, _, quantized_ppl = runner.calculate_perplexity(
original_model=eval_original_model,
)
if eval_original_model:
logger.info("Original model perplexity: %s", original_ppl)
logger.info("Quantized model perplexity: %s", quantized_ppl)
original_acc, _, quantized_acc = runner.calculate_accuracy(
original_model=eval_original_model,
)
if eval_original_model:
logger.info("Original model accuracy: %s", original_acc)
logger.info("Quantized model accuracy: %s", quantized_acc)
if save_dir is not None:
runner.save_quantized_model(save_dir)
return runner
def quantize(self):
"""Quantize the model
Assumes that parameter combinations have been validated by check().
"""
if self.quantizers is not None:
# Multiple quantizers mode (chunked quantization)
self.quantize_with_calibration_chunked()
elif self.multi_gpu:
# Multi-GPU quantization (flag_calibration=True is guaranteed by check())
self.quantize_with_calibration_on_multi_gpu()
elif self.calibration_config.batch_size is not None:
# Chunked quantization (single quantizer)
self.quantize_with_calibration_chunked()
elif self.quantizer.flag_calibration:
# Standard calibration-based quantization
self.quantize_with_calibration()
else:
# Quantization without calibration
self.quantize_without_calibration()
def quantize_with_calibration(self):
"""Quantize the model with calibration"""
model = self.model_config.load_model()
logger = self.logger
input_device = next(model.parameters()).device
inputs = self.prepare_calibration_dataset(input_device, model=model)
# Setup the quantizer
self.quantizer.setup(model)
# Register hooks to all linear layers
handles = []
progress = None
if self.report_progress:
progress = QuantizationProgressTracker(
logger,
len(self.quantizer.module_to_name),
"Quantization",
)
if progress:
quantize_bound = self.quantizer.quantize
def _quantize_hook(module, input, output): # pylint: disable=redefined-builtin
quantize_bound(module, input, output)
progress.step_complete(self.quantizer.module_to_name[module])
hook_fn = _quantize_hook
else:
hook_fn = self.quantizer.quantize
for module in self.quantizer.module_to_name.keys():
handle = module.register_forward_hook(hook_fn)
handles.append(handle)
logger.info("Quantizing the model using %s", self.quantizer.name)
with torch.no_grad():
model(**inputs)
# Remove all hooks
for handle in handles:
handle.remove()
self.quantizer.execute_post_processing()
def quantize_with_calibration_chunked(self):
"""Quantize the model with calibration using chunked forward passes
Designed for large-scale calibration data.
Splits calibration data into chunks of calibration_batch_size and
accumulates information needed for quantization across multiple forward passes.
Processing flow:
1. Prepare calibration data on CPU
2. Load model and set up quantizer
3. Divide layers into groups and for each group:
a. Execute forward passes per chunk and accumulate X^T X in FP64
b. Quantize each layer using X^T X
Note:
- X^T X is accumulated in FP64 (for reuse in error computation)
- Cast to quantizer.hessian_dtype during quantization
- CPU/GPU memory usage can be adjusted by controlling the number of layer groups
"""
# Lazy import: load submodule only when needed
# pylint: disable-next=import-outside-toplevel
from .runner_methods.chunked_quantization import run_chunked_quantization
run_chunked_quantization(
model_config=self.model_config,
quantizers=self.quantizers if self.quantizers is not None else [self.quantizer],
calibration_config=self.calibration_config,
report_progress=self.report_progress,
)
def quantize_with_calibration_on_multi_gpu(self):
"""Quantize the model with calibration using multiple GPUs
Quantizes each linear layer in parallel across multiple GPUs.
Processing flow:
1. Load the model and prepare calibration data
2. Capture input activations for all layers and save to CPU
3. Distribute layers to each GPU and execute quantization in parallel
4. Aggregate results
Note:
- Called from quantize() when multi_gpu=True
- Uses all available GPUs when gpu_ids is None
"""
# Lazy import: load submodule only when needed
# pylint: disable-next=import-outside-toplevel
from .runner_methods.multi_gpu_quantization import run_multi_gpu_quantization
# Execute multi-GPU quantization
result = run_multi_gpu_quantization(
model_config=self.model_config,
quantizer=self.quantizer,
calibration_config=self.calibration_config,
gpu_ids=self.gpu_ids,
report_progress=self.report_progress,
)
# Store results in quantizer.results
self.quantizer.results = result["results"]
# Post-processing
self.quantizer.execute_post_processing()
def quantize_without_calibration(self):
"""Quantize the model without calibration
Quantize each layer in the form ||W - hat_W||_F^2.
"""
model = self.model_config.load_model()
logger = self.logger
# Setup the quantizer
self.quantizer.setup(model)
# Quantize each layer
logger.info(
"Quantizing the model without calibration using %s",
self.quantizer.name,
)
progress = None
if self.report_progress:
progress = QuantizationProgressTracker(
logger,
len(self.quantizer.module_to_name),
"Quantization without calibration (layers)",
)
for module in self.quantizer.module_to_name.keys():
self.quantizer.quantize(module, None, None)
if progress:
progress.step_complete(self.quantizer.module_to_name[module])
self.quantizer.execute_post_processing()
def quantize_with_qep(self):
"""Quantize the model with QEP
Dispatches to either the generic or architecture-aware
implementation based on ``qep_config.general``.
- ``general=True``: Generic implementation independent
of model architecture. Captures input activations per layer.
- ``general=False`` (default): Architecture-aware implementation that
exploits shared activations (e.g., QKV in Llama).
"""
kwargs = dict(
model_config=self.model_config,
quantizer=self.quantizer,
qep_config=self.qep_config,
calibration_config=self.calibration_config,
report_progress=self.report_progress,
)
if self.qep_config.general:
# Lazy import: load submodule only when needed
# pylint: disable-next=import-outside-toplevel
from .qep._quantize_with_qep import run_quantize_with_qep
run_quantize_with_qep(**kwargs)
else:
# Lazy import: load submodule only when needed
# pylint: disable-next=import-outside-toplevel
from .qep._quantize_with_qep_arch import run_quantize_with_qep_arch
run_quantize_with_qep_arch(**kwargs)
def quantize_with_lpcd(self):
"""Quantize the model with LPCD"""
# Lazy import: load submodule only when needed
# pylint: disable-next=import-outside-toplevel
from .lpcd._lpcd_runner import run_quantize_with_lpcd
run_quantize_with_lpcd(
model_config=self.model_config,
quantizer=self.quantizer,
qep_config=self.qep_config,
lpcd_config=self.lpcd_config,
calibration_config=self.calibration_config,
)
def quantize_with_jointq_error_propagation(
self,
max_layers=None,
skip_threshold_increase=0.01,
skip_threshold_error=0.01,
skip_threshold_amplification=5.0,
device=None,
batch_size=None,
variation_scale=0.1,
variation_cap=0.05,
degradation_threshold=0.1,
max_iter=10,
log_level=0,
exclude_layer_keywords=None,
):
"""Quantize the model with JointQ error propagation
A generic implementation independent of model architecture.
Consumes extra CPU memory and incurs unnecessary forward passes.
Could be faster by leveraging model structure to avoid redundant forward passes.
Current procedure:
1. Save input activations of the original model to CPU
2. For each target layer l, perform the following sequentially:
2-1. Save input activations of layer l in the quantized model to CPU
2-2. Quantize the weights of layer l in the quantized model
2-3. Update the weights of layer l in the quantized model
TODO: Implement quantization that leverages model structure.
Args:
max_layers: Maximum number of layers to process (None for all layers; for testing)
skip_threshold_increase: Skip threshold for error increase rate (default: 0.01)
skip_threshold_error: Skip threshold for relative cumulative error (default: 0.01)
skip_threshold_amplification (float): Skip threshold for error amplification rate.
Re-quantize when amplification exceeds this value even if g_relative is small
(default: 5.0)
device: Device to use for computation (None uses each layer's device)
batch_size (int): Batch size (default: None, solves the optimization problem all at once)
variation_scale (float): Scaling coefficient from degradation rate to variation rate (default: 0.1)
variation_cap (float): Upper limit for maximum variation rate (default: 0.05)
degradation_threshold (float): Degradation rate threshold; variation rate is 0 below this (default: 0.1)
max_iter (int): Maximum number of iterations for quantize_advanced (default: 10)
log_level (int): Log level for quantize_advanced (default: 0)
exclude_layer_keywords (list[str]): List of keywords for layers to exclude from Step 2.
If a layer name contains any of these keywords, it is excluded from
re-quantization in Step 2 (Step 1 results are used as-is).
None targets all layers (default: None)
"""
# Lazy import: load submodule only when needed
# pylint: disable-next=import-outside-toplevel
from .runner_methods.jointq_error_propagation import run_jointq_error_propagation
model = self.model_config.load_model()
logger = self.logger
input_device = next(model.parameters()).device
inputs = self.prepare_calibration_dataset(input_device, model=model)
run_jointq_error_propagation(
model=model,
inputs=inputs,
current_results=self.quantizer.results,
logger=logger,
max_layers=max_layers,
skip_threshold_increase=skip_threshold_increase,
skip_threshold_error=skip_threshold_error,
skip_threshold_amplification=skip_threshold_amplification,
device=device,
batch_size=batch_size,
variation_scale=variation_scale,
variation_cap=variation_cap,
degradation_threshold=degradation_threshold,
max_iter=max_iter,
log_level=log_level,
exclude_layer_keywords=exclude_layer_keywords,
)
def run_post_processes(self):
"""Execute post-quantization processes.
Builds a quantized model on CPU from ``quantizer.results`` and
passes it to each :class:`PostQuantizationProcess` in order.
Raises:
ValueError: If ``self.quantizer`` is ``None``
(``quantizers`` mode is not yet supported).
"""
logger = self.logger
if self.quantizer is None:
raise ValueError(
"post_processes requires a single 'quantizer'. "
"'quantizers' (multiple) is not yet supported with post_processes."
)
logger.info("Building quantized model for post-quantization processes...")
# use_gemlite=False: GemLite uses fp16-only Triton kernels that break when
# LoRA SFT runs with bfloat16 autocast. Plain buffers (qweight/scales) are
# needed so training can call base_layer.forward() without dtype mismatch.
quantized_model, _ = self.create_quantized_model(
pack_weights=False,
use_gemlite=False,
)
for process in self.post_processes:
logger.info("Start post-quantization process: %s", process.name)
process.run(quantized_model, self.model_config)
logger.info("Finished post-quantization process: %s", process.name)
self.quantized_model = quantized_model
def prepare_calibration_dataset(self, device, model=None):
"""Prepare calibration data for quantization methods such as GPTQ.
See calibration.calibration_data_loader.prepare_calibration_dataset for details.
Args:
device (torch.device): Device to place tensors on (CPU or GPU)
model: Model instance (optional). Add model-specific fields
(e.g. mm_token_type_ids for Gemma 4).
Returns:
dict: Input dictionary for the model
- "input_ids": tensor of shape (num_chunks, max_length)
- "attention_mask": tensor of shape (num_chunks, max_length)
"""
tokenizer = self.model_config.load_tokenizer()
return prepare_calibration_dataset(
tokenizer=tokenizer,
device=device,
calibration_config=self.calibration_config,
logger=self.logger,
model=model,
)
def print_quantization_results(self, quantizer=None):
"""Log quantization results.
Formats and logs the quantizer results.
The following information is output for each layer:
- Quantization time (seconds)
- Output squared error (only if value exists)
- Mean output squared error (only if value exists)
- Weight squared error (only if value exists)
- Mean weight squared error (only if value exists)
Args:
quantizer (Quantizer, optional):
The quantizer. Uses self.quantizer if None.
Specify explicitly when using quantizers mode.
Examples:
Single quantizer mode:
>>> runner.print_quantization_results()
Multiple quantizers mode:
>>> runner.print_quantization_results(quantizer=gptq)
"""
logger = self.logger
if quantizer is None:
quantizer = self.quantizer
if quantizer is None:
logger.warning(
"print_quantization_results: 'quantizer' is None. "
"Please specify a quantizer explicitly."
)
return
logger.info("Quantization results for %s:", quantizer.name)
for name, result in quantizer.results.items():
logger.info("%s:", name)
logger.info(
" Quantization time: %s seconds",
f"{result.quantization_time:.2f}",
)
logger.info(
" Output squared error: %s",
f"{result.output_squared_error:.2e}",
)
logger.info(
" Mean output squared error: %s",
f"{result.mean_output_squared_error:.2e}",
)
logger.info(
" Weight squared error: %s",
f"{result.weight_squared_error:.2e}",
)
logger.info(
" Mean weight squared error: %s",
f"{result.mean_weight_squared_error:.2e}",
)
if result.relative_output_squared_error is not None:
logger.info(
" Relative output squared error: %s",