-
Notifications
You must be signed in to change notification settings - Fork 529
Expand file tree
/
Copy pathmodel_calib.py
More file actions
2047 lines (1749 loc) · 86.8 KB
/
Copy pathmodel_calib.py
File metadata and controls
2047 lines (1749 loc) · 86.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
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
# 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.
"""Calibration utilities."""
import fnmatch
import math
import time
import warnings
from collections.abc import Callable, Mapping, Sequence
from functools import partial
from typing import TypeAlias
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from modelopt.torch.opt.searcher import ForwardLoop
from modelopt.torch.quantization.utils.layerwise_calib import (
LayerActivationCollector,
_CheckpointState,
)
from modelopt.torch.utils import print_rank_0, warn_rank_0
from modelopt.torch.utils.distributed import DistributedProcessGroup, ParallelState
from modelopt.torch.utils.distributed import is_initialized as dist_is_initialized
from modelopt.torch.utils.distributed import size as dist_size
from modelopt.torch.utils.network import bind_forward_method, unpatch_forward_method
from .calib import MseCalibrator, NVFP4MSECalibrator, _Calibrator
from .conversion import create_and_replace_svdquant_linear_on_the_fly, set_quantizer_by_cfg_context
from .nn import NVFP4StaticQuantizer, QuantModule, SequentialQuantizer, TensorQuantizer
from .utils import (
SHARED_PATTERNS,
SharedWeightGlobalAmaxState,
disable_calib,
enable_fake_quant,
enable_quant,
enable_weight_access_and_writeback,
is_quantized_column_parallel_linear,
is_quantized_linear,
is_quantized_row_parallel_linear,
persistent_materialization,
promote_nvfp4_static_quantizers,
)
from .utils.calib_utils import _GPTQ_HELPER_REGISTRY, GPTQHelper
__all__ = [
"CalibratorFactory",
"awq",
"layerwise_calibrate",
"local_hessian_calibrate",
"max_calibrate",
"smoothquant",
"svdquant",
]
def _collect_weight_stats(quantizer: nn.Module, weight: torch.Tensor) -> None:
quantizer(weight)
def _is_calibrated_nvfp4_static(q) -> bool:
"""True iff ``q`` is an enabled NVFP4-static weight quantizer with ``_amax`` set."""
return (
isinstance(q, NVFP4StaticQuantizer)
and not q._disabled
and q.is_nvfp4_static
and getattr(q, "_amax", None) is not None
)
def _collect_grouped_linears(model: nn.Module) -> list[list[nn.Module]]:
"""Collect name-based sibling groups (Q/K/V, gate/up, w1/w3) of calibrated NVFP4-static linears."""
# Inline import: layer_utils -> quant_utils -> model_calib cycle.
from modelopt.torch.export.layer_utils import _GATE_UP_PAIRS
patterns: tuple[tuple[str, ...], ...] = (("q_proj", "k_proj", "v_proj"), *_GATE_UP_PAIRS)
groups: list[list[nn.Module]] = []
for parent in model.modules():
for sibling_names in patterns:
members = [
child
for child in (getattr(parent, n, None) for n in sibling_names)
if child is not None
and _is_calibrated_nvfp4_static(getattr(child, "weight_quantizer", None))
]
if len(members) >= 2:
groups.append(members)
return groups
@torch.no_grad()
def _check_grouped_weight_global_amax_synced(model: nn.Module) -> None:
"""Verify shared NVFP4 state unified each name-based fusible group's weight global_amax.
The default name-based grouping (Q/K/V, gate/up, w1/w3) is kept here as a *check*
rather than performed: after attach/populate/promote, the promoted static-NVFP4 weight
quantizers in each name group must already share one ``global_amax``. This catches the
SharedWeightGlobalAmaxState path failing to form or sync a group it should have (e.g. a
default-pattern regression, or an architecture the regexes miss)
before the MSE per-block search — computed against ``global_amax`` — bakes in the
inconsistency. Run only when the default patterns are in effect (custom
``shared_states`` may intentionally group differently). Members whose ``global_amax``
is not materialized (``None``/meta, e.g. an ``init_empty_weights`` model) are skipped.
"""
for group in _collect_grouped_linears(model):
amaxes = [m.weight_quantizer.global_amax for m in group]
amaxes = [a for a in amaxes if a is not None and not a.is_meta]
if len(amaxes) < 2:
continue
ref = amaxes[0]
assert all(torch.equal(a, ref) for a in amaxes), (
"A fusible sibling group (q/k/v or gate/up) was not unified to a shared weight "
"global_amax; SharedWeightGlobalAmaxState failed to sync it, so the per-block "
"MSE scales would be inconsistent across the group."
)
def _finalize_with_shared_state(model: nn.Module, weight_patterns: list[str]) -> None:
"""Finalize quantization from the attached shared state: aggregate, promote, verify.
Aggregates each fusible group's shared weight ``global_amax`` and promotes it onto the
member NVFP4-static quantizers, so siblings read the unified value instead of their own
``_amax``; under the default patterns, verifies the name groups were actually synced.
Call once ``_amax`` is final: single-process, or after the distributed amax sync.
"""
SharedWeightGlobalAmaxState.populate(model)
promote_nvfp4_static_quantizers(model)
# Under the default patterns, verify the fusible name groups were actually synced.
if weight_patterns == list(SHARED_PATTERNS):
_check_grouped_weight_global_amax_synced(model)
CalibratorFactory: TypeAlias = Callable[
[torch.Tensor, int | tuple | list | None, Callable[..., torch.Tensor]], _Calibrator
]
_FP8_SWEEP_CALIBRATOR_REGISTRY: dict[str, CalibratorFactory] = {}
def _register_fp8_sweep_calibrator(backend: str, calibrator_factory: CalibratorFactory) -> None:
"""Register a custom calibrator factory for a quantization backend.
When ``fp8_scale_sweep=True`` is passed to :func:`mse_calibrate`, any weight
quantizer whose ``backend`` attribute matches a registered key will use the
corresponding factory instead of the default :class:`MseCalibrator`.
Args:
backend: Backend name string (must match ``TensorQuantizer.backend``).
calibrator_factory: Callable with signature
``(amax: Tensor, axis: int | tuple | list | None, quant_func: Callable)``
that returns a :class:`_Calibrator` instance.
"""
_FP8_SWEEP_CALIBRATOR_REGISTRY[backend] = calibrator_factory
def _uses_modelopt_fp8_weight_scales(weight_quantizer: TensorQuantizer) -> bool:
"""Whether the internal ModelOpt FP8-scale MSE sweep applies to this quantizer."""
return weight_quantizer.backend is None and weight_quantizer.is_nvfp4_static
def weight_only_quantize(model: nn.Module):
"""Just quantize the weights of the model."""
name_to_module = dict(model.named_modules())
seen_modules = set()
for module in name_to_module.values():
if module in seen_modules:
continue
if isinstance(module, QuantModule):
with enable_weight_access_and_writeback(module, model, name_to_module):
for weight, weight_quantizer in module.iter_weights_for_calibration():
weight_quantizer(weight)
seen_modules.add(module)
def _run_and_load_max_stats(model: nn.Module, forward_loop: ForwardLoop | None = None):
"""Run max-stat collection and load collected stats without post-processing."""
enable_stats_collection(model)
if forward_loop is None:
weight_only_quantize(model)
else:
forward_loop(model)
finish_stats_collection(model)
def _has_expert_parallelism(module: nn.Module) -> bool:
"""Check if module has expert parallelism enabled."""
ps = getattr(module, "parallel_state", None)
return ps is not None and ps.expert_model_parallel_group.is_initialized()
def _iter_leaf_quantizers(quantizer):
if isinstance(quantizer, SequentialQuantizer):
for _q in quantizer:
yield from _iter_leaf_quantizers(_q)
return
yield quantizer
def _check_moe_calibration_complete(quantizer, parallel_state):
"""Raise error if MoE calibration is incomplete across distributed MoE ranks."""
for leaf_quantizer in _iter_leaf_quantizers(quantizer):
has_amax = getattr(leaf_quantizer, "_amax", None) is not None
for group in [
parallel_state.data_parallel_group,
parallel_state.expert_model_parallel_group,
parallel_state.tensor_parallel_group,
]:
if not group.is_initialized():
continue
amax_states = DistributedProcessGroup.get_dist_syncd_obj(
has_amax, group, lambda objs: objs
)
if any(amax_states) and not all(amax_states):
raise RuntimeError(
"MoE calibration incomplete: some experts received no tokens during "
"calibration. Increase --calib-size to ensure all experts see calibration "
"data."
)
def _is_routed_expert(parent_name: str) -> bool:
"""Routed-expert FQN contains ``experts`` but not ``shared_experts`` (covers SequentialMLP and TEGroupedMLP)."""
return "experts" in parent_name and "shared_experts" not in parent_name
def _should_sync_amax_across_ep(
parent_name: str, child_name: str, sync_expert_weight_amax: bool
) -> bool:
"""Skip EP sync for routed-expert weights (per-rank shards differ).
SequentialMLP opts in via sync_expert_weight_amax.
"""
if "weight_quantizer" in child_name and _is_routed_expert(parent_name):
return sync_expert_weight_amax
return True
@torch.no_grad()
def max_calibrate(
model: nn.Module,
forward_loop: ForwardLoop | None = None,
distributed_sync=True,
sync_expert_weight_amax=False,
shared_states: Mapping[str, Mapping[str, Sequence[str]]] | None = None,
):
"""Calibrate the model using max.
Args:
model: Model to be calibrated.
forward_loop: A callable which takes the model as argument and
forwards calibration data through the model.
distributed_sync: Whether to sync input_quantizer amax across distributed processes.
sync_expert_weight_amax: SequentialMLP only — share one weight amax across all experts
in a MoE layer (within-rank sync + EP all-reduce when EP>1).
shared_states: Optional dict keyed by shared-state name. ``"weight_global_amax"`` is
implemented today and accepts ``{"patterns": [...]}``; omitted patterns use
``SHARED_PATTERNS``, while an empty list disables the state.
See :class:`MaxCalibConfig <modelopt.torch.quantization.config.MaxCalibConfig>` for
details on the remaining arguments.
"""
# Discover fusible sibling groups by name regex and attach the (initially empty) shared
# state up front, so parent-level runtime hooks can be installed by future concrete
# states. Discovery is structural (a pattern over the module tree), so it needs no
# ``_amax``; per-member values are aggregated later by
# SharedWeightGlobalAmaxState.populate, after the forward and any cross-rank ``_amax`` sync.
weight_patterns = SharedWeightGlobalAmaxState.resolve_patterns(shared_states=shared_states)
SharedWeightGlobalAmaxState.attach(model, patterns=weight_patterns)
# Always run weight calibration on the weight tensor directly so every weight
# quantizer gets ``_amax``, regardless of MoE routing. Downstream algorithms
# (MSE, AWQ, export) then no longer need to patch in a missing ``_amax``.
enable_stats_collection(model)
weight_only_quantize(model)
if forward_loop is not None:
forward_loop(model)
finish_stats_collection(model)
# Sync quantizer amax across local experts within each rank (for SequentialMLP)
for name, module in model.named_modules():
if hasattr(module, "layer_sync_moe_local_experts_amax"):
module.layer_sync_moe_local_experts_amax(sync_weight_amax=sync_expert_weight_amax)
# Fail fast on NVFP4 static-block with TP>1 (sharded_state_dict treats _amax as replicated).
try:
from .plugins.megatron import _check_nvfp4_static_tp_supported
except ImportError:
pass
else:
_check_nvfp4_static_tp_supported(model)
if not distributed_sync:
# Single-process: _amax is final.
_finalize_with_shared_state(model, weight_patterns)
return
# Check MoE calibration completeness before sync
for name, module in model.named_modules():
if isinstance(module, QuantModule) and _has_expert_parallelism(module):
for child in module.children():
if isinstance(child, (TensorQuantizer, SequentialQuantizer)):
_check_moe_calibration_complete(child, module.parallel_state)
def sync_quantizer_amax_across_dp_ep(quantizer, parallel_state, parent_name, child_name):
"""Sync amax across DP (always) and EP (filtered — see _should_sync_amax_across_ep)."""
if isinstance(quantizer, SequentialQuantizer):
for _q in quantizer:
sync_quantizer_amax_across_dp_ep(_q, parallel_state, parent_name, child_name)
return
if getattr(quantizer, "_amax", None) is None:
return
quantizer.sync_amax_across_distributed_group(parallel_state.data_parallel_group)
if _should_sync_amax_across_ep(parent_name, child_name, sync_expert_weight_amax):
quantizer.sync_amax_across_distributed_group(parallel_state.expert_model_parallel_group)
# Step 2:Sync amax across data parallelism
for name, module in model.named_modules():
if isinstance(module, QuantModule):
for child_name, child in module.named_children():
if isinstance(child, (TensorQuantizer, SequentialQuantizer)):
sync_quantizer_amax_across_dp_ep(child, module.parallel_state, name, child_name)
# Step 3: TP sync
# Objective: the quantization parameters when TP = 8 then changed to TP=4 then back to TP=8 should be the same
# ColumnParallel: X @ [A_1, A_2] (weights split along Cout)
# activations: TPG should have the same amax if axis in [None, -1]
# weights: TPG should have the same amax if axis in [None, -1] (note: we dont use -1 axis for weights)
# RowParallel: [X_1, X_2] @ [A_1
# A_2] (weights split along Cin)
# activations: TPG should have the same amax if axis in [None]
# weights: TPG should have the same amax if axis in [None, 0]
def sync_quantizer_amax_across_tp(
quantizer: TensorQuantizer | SequentialQuantizer,
linear_name: str,
quantizer_type: str,
axes_for_sync: list,
parallel_state: ParallelState,
):
# Syncing amax across TP for sequential quantizer
if isinstance(quantizer, SequentialQuantizer):
for _q in quantizer:
sync_quantizer_amax_across_tp(
_q, linear_name, quantizer_type, axes_for_sync, parallel_state
)
return
# sync is not needed for block quantization
if quantizer.block_sizes is not None:
if hasattr(quantizer, "_padding"):
warnings.warn(
f"Found block-quantized padded {quantizer_type} for {linear_name}, amax will"
" not be synced correctly."
)
# Skip amax sync for INT4 / W4A8 block quantization
# Sync amax for NVFP4 (dynamic per-block, static per-tensor quantized scale)
if getattr(quantizer.block_sizes, "type", None) == "dynamic":
return
if quantizer.axis in axes_for_sync and quantizer.amax is not None:
quantizer.sync_amax_across_distributed_group(parallel_state.tensor_parallel_group)
# Step 2: Sync amax across relevant parallelism (such as TP / EP)
for name, module in model.named_modules():
if getattr(module, "_parallel_state", None) is None:
continue
if is_quantized_column_parallel_linear(module):
sync_quantizer_amax_across_tp(
module.input_quantizer,
name,
"input_quantizer",
axes_for_sync=[None, -1],
parallel_state=module.parallel_state,
)
sync_quantizer_amax_across_tp(
module.weight_quantizer,
name,
"weight_quantizer",
axes_for_sync=[None, -1],
parallel_state=module.parallel_state,
)
if is_quantized_row_parallel_linear(module):
sync_quantizer_amax_across_tp(
module.input_quantizer,
name,
"input_quantizer",
axes_for_sync=[None],
parallel_state=module.parallel_state,
)
sync_quantizer_amax_across_tp(
module.weight_quantizer,
name,
"weight_quantizer",
axes_for_sync=[None, 0],
parallel_state=module.parallel_state,
)
# KV Cache Quantization
if hasattr(module, "k_bmm_quantizer") and hasattr(module, "v_bmm_quantizer"):
# We only support KVCache quantization with scalar per-tensor states for now (NVFP4 & FP8 KV cache)
# So we should sync amax across DP and TP for these quantizers (DP is already synced from above)
for quantizer in [module.k_bmm_quantizer, module.v_bmm_quantizer]:
if isinstance(quantizer, TensorQuantizer) and quantizer.amax is not None:
quantizer.sync_amax_across_distributed_group(
module.parallel_state.tensor_parallel_group
)
# _amax is now cross-rank consistent across ranks.
_finalize_with_shared_state(model, weight_patterns)
def _mse_quant_func(x, amax, quantizer):
"""Quantization function for MSE calibration."""
original_amax = quantizer._amax.clone() if hasattr(quantizer, "_amax") else None
quantizer._amax = amax
try:
with (
enable_quant(quantizer),
disable_calib(quantizer),
enable_fake_quant(quantizer),
):
if hasattr(quantizer, "_original_shape"):
x = quantizer._reset_to_original_shape(x)
xq = quantizer(x)
if hasattr(quantizer, "_block_reshape_size"):
# Reapply static block padding before returning to the calibration block layout.
xq = quantizer._process_for_blockquant(xq)
finally:
if original_amax is not None:
quantizer._amax = original_amax
else:
delattr(quantizer, "_amax")
return xq
def _make_weight_mse_calibrator(
weight_quantizer: TensorQuantizer,
step_size: float,
start_multiplier: float,
stop_multiplier: float,
fp8_scale_sweep: bool,
error_func: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
hessian: torch.Tensor | None = None,
) -> _Calibrator | None:
"""Create the MSE calibrator for one eligible weight quantizer (``None`` if ineligible).
``error_func`` overrides the squared-error metric (local-Hessian's per-block weighting).
``hessian`` (the same per-cin-block metric as a raw tensor) enables NVFP4's Hessian-weighted
Triton fast path; ``error_func`` then serves only as the reference fallback.
"""
if (
not isinstance(weight_quantizer, TensorQuantizer)
or not weight_quantizer.is_enabled
or weight_quantizer._dynamic
or weight_quantizer._calibrator is None
or getattr(weight_quantizer, "_amax", None) is None
):
return None
initial_amax = weight_quantizer._amax.clone().detach()
axis = weight_quantizer._calibrator._axis
quant_func = partial(_mse_quant_func, quantizer=weight_quantizer)
if fp8_scale_sweep:
backend: str | None = getattr(weight_quantizer, "backend", None)
backend_factory = (
_FP8_SWEEP_CALIBRATOR_REGISTRY.get(backend) if backend is not None else None
)
if backend is not None and backend_factory is not None:
if error_func is not None:
# Registered backend factories don't accept a custom error_func.
warnings.warn(
f"backend '{backend}' does not support a custom error function; skipping "
"error-function-weighted MSE calibration for this quantizer."
)
return None
return backend_factory(initial_amax, axis, quant_func)
if _uses_modelopt_fp8_weight_scales(weight_quantizer):
return NVFP4MSECalibrator(
amax=initial_amax,
axis=axis,
global_amax=weight_quantizer.global_amax,
quant_func=quant_func,
error_func=error_func,
hessian=hessian,
)
# fp8_scale_sweep applies only to registered backends and static NVFP4; skip others.
return None
# No fp8_scale_sweep: multiplier-search MSE for all quantizers.
return MseCalibrator(
amax=initial_amax,
axis=axis,
step_size=step_size,
start_multiplier=start_multiplier,
stop_multiplier=stop_multiplier,
quant_func=quant_func,
error_func=error_func,
)
@torch.no_grad()
def mse_calibrate(
model: nn.Module,
forward_loop: ForwardLoop | None = None,
distributed_sync=True,
step_size: float = 0.1,
start_multiplier: float = 0.25,
stop_multiplier: float = 4.0,
fp8_scale_sweep: bool = False,
shared_states: Mapping[str, Mapping[str, Sequence[str]]] | None = None,
):
"""Calibrate weight quantizers using MSE-based amax search.
This calibration method first uses max calibration to initialize amax values for
all quantizers, then searches for better weight amax values by minimizing the MSE
between original and quantized weights.
Args:
model: Model to be calibrated.
forward_loop: A callable which takes the model as argument and
forwards calibration data through the model.
distributed_sync: Whether to sync amax across distributed processes.
step_size: Step size for amax search (default: 0.1).
start_multiplier: Starting multiplier for amax search (default: 0.25).
stop_multiplier: Ending multiplier for amax search (default: 4.0).
fp8_scale_sweep: If True, only ModelOpt static NVFP4 weights and registered
custom backends are MSE-calibrated (via FP8 E4M3 scale-value sweep); all
other weight quantizers (INT8, plain FP8, unregistered backends, etc.) are
skipped and left at their max-calibrated amax. If False, all weight
quantizers use the multiplier search.
See :class:`MseCalibConfig <modelopt.torch.quantization.config.MseCalibConfig>` for
details on the remaining arguments.
"""
# max_calibrate initializes activations and weights; MSE only refines weights below.
max_calibrate(model, forward_loop, distributed_sync, shared_states=shared_states)
name_to_module = dict(model.named_modules())
_mse_calibrate_weights(
model,
name_to_module,
step_size=step_size,
start_multiplier=start_multiplier,
stop_multiplier=stop_multiplier,
fp8_scale_sweep=fp8_scale_sweep,
)
@torch.no_grad()
def _mse_calibrate_weights(
model: nn.Module,
name_to_module: dict[str, nn.Module],
step_size: float,
start_multiplier: float,
stop_multiplier: float,
fp8_scale_sweep: bool,
error_func_for: Callable[[TensorQuantizer], Callable | None] | None = None,
hessian_for: Callable[[TensorQuantizer], torch.Tensor | None] | None = None,
):
"""Run MSE weight calibration over all eligible quantizers (shared by mse / local-Hessian).
``error_func_for`` maps a weight quantizer to an optional per-weight error function
(local-Hessian's Hessian metric); ``None`` means plain squared error. ``hessian_for``
maps a weight quantizer to the same metric as a raw per-cin-block Hessian tensor,
enabling the Hessian-weighted Triton fast path.
"""
seen_modules: set[int] = set()
pbar = tqdm(desc="MSE weight calibration")
for parent_module in name_to_module.values():
if id(parent_module) in seen_modules or not isinstance(parent_module, QuantModule):
continue
seen_modules.add(id(parent_module))
with enable_weight_access_and_writeback(parent_module, model, name_to_module):
for weight, weight_quantizer in parent_module.iter_weights_for_calibration():
error_func = error_func_for(weight_quantizer) if error_func_for else None
hessian = hessian_for(weight_quantizer) if hessian_for else None
cal = _make_weight_mse_calibrator(
weight_quantizer,
step_size,
start_multiplier,
stop_multiplier,
fp8_scale_sweep,
error_func=error_func,
hessian=hessian,
)
if cal is None:
continue
weight_quantizer._calibrator = cal
_run_and_load_max_stats(
weight_quantizer, partial(_collect_weight_stats, weight=weight)
)
if hasattr(cal, "reset"):
cal.reset()
pbar.update(1)
pbar.close()
class _LocalHessianAccumulator:
"""Per-block local Hessian ``H = ΣXᵀX`` for one weight quantizer.
Partitioned over ``cin`` into ``cin // block_size`` blocks to match the NVFP4 per-block
scale; the buffer is allocated lazily so never-routed experts cost nothing.
"""
def __init__(self, cout: int, cin: int, block_size: int):
self.cout = cout
self.cin = cin
self.block_size = block_size
self.num_blocks_per_cin = cin // block_size
# Not block-divisible -> no Hessian (falls back to plain MSE).
self.is_enabled = cin % block_size == 0
self.hessian_per_block: torch.Tensor | None = None
self._normalized_hessian: torch.Tensor | None = None
self.num_samples = 0
@torch.no_grad()
def accumulate(self, input_tensor: torch.Tensor) -> None:
"""Accumulate ``XᵀX`` per block from an activation of shape ``(..., cin)``."""
if not self.is_enabled:
return
# fp32 GEMM avoids bf16/fp16 precision loss; (cin, tokens) -> (n_blocks, bs, tokens).
x = input_tensor.reshape(-1, self.cin).to(torch.float32).T
x = x.reshape(self.num_blocks_per_cin, self.block_size, -1)
hessian_batch = x @ x.transpose(-1, -2)
if self.hessian_per_block is None:
self.hessian_per_block = hessian_batch
else:
self.hessian_per_block += hessian_batch
self.num_samples += input_tensor.numel() // self.cin
def normalized_hessian(self) -> torch.Tensor | None:
"""Per-cin-block Hessian ``H / num_samples`` (``None`` if no samples).
Shared by both the Triton fast path and the reference ``error_func`` so the two
consume one tensor; cached because the accumulated buffer may be freed afterwards.
"""
if (
self._normalized_hessian is None
and self.hessian_per_block is not None
and self.num_samples
):
self._normalized_hessian = self.hessian_per_block / self.num_samples
return self._normalized_hessian
def build_error_func(
self, keep_buffer: bool = False
) -> Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None:
"""Hessian-weighted error function (``None`` if no samples).
Frees the raw Hessian buffer unless ``keep_buffer`` (kept for debug inspection).
"""
hessian = self.normalized_hessian()
if hessian is None:
return None
cout = self.cout
bs = self.block_size
if not keep_buffer:
self.hessian_per_block = None
def local_hessian_error(x: torch.Tensor, xq: torch.Tensor) -> torch.Tensor:
original_shape = x.shape
# Per-block weighted error: dw (cout,n,bs) · H (n,bs,bs) -> (cout,n).
dw = (x - xq).view(cout, -1, bs)
block_loss = torch.einsum("cnb,nbd,cnd->cn", dw, hessian, dw).reshape(-1)
return block_loss.unsqueeze(-1).expand(-1, bs).reshape(original_shape)
return local_hessian_error
def _warn_if_block_size_mismatch(weight_quantizer: TensorQuantizer, block_size: int, name: str):
"""Warn if the Hessian block_size differs from the quantizer's scale block (misaligns)."""
block_sizes = getattr(weight_quantizer, "block_sizes", None)
quant_block = block_sizes.get(-1) if block_sizes else None
if quant_block is not None and quant_block != block_size:
warn_rank_0(
f"local_hessian: block_size ({block_size}) != quantizer scale block "
f"({quant_block}) for {name}; Hessian weighting will not align with the scale blocks."
)
def _warn_local_hessian_fallback(name, weight, weight_quantizer, block_size, warned: set):
"""Warn once per ``(name, cin)`` when a captured layer falls back to plain MSE."""
if weight.dim() < 2:
return
cin = weight.shape[1]
if (name, cin) in warned:
return
warned.add((name, cin))
if cin % block_size != 0:
warn_rank_0(
f"local_hessian: {name} input features ({cin}) not divisible by block_size "
f"({block_size}); falling back to plain MSE for these weights."
)
_warn_if_block_size_mismatch(weight_quantizer, block_size, name)
def _is_quant_fused_experts(module: nn.Module) -> bool:
"""Whether ``module`` is a converted HF fused-MoE-experts wrapper with per-expert quantizers."""
first_proj_attr = getattr(module, "_first_proj_attr", "gate_up_proj")
return hasattr(module, "_current_expert_idx") and hasattr(
module, f"{first_proj_attr}_weight_quantizers"
)
def _register_local_hessian_input_hooks(model, name_to_module, capture, block_size, warned):
"""Register forward hooks feeding each weight's input activations to ``capture``.
Local-Hessian-specific (kept here rather than as a general ``QuantModule`` API): dense
quantized linears hook the layer input; HF fused-MoE experts hook the shared input quantizers,
keyed by the active expert (``_current_expert_idx``). Weights without a hook (conv,
SequentialQuantizer, non-eager experts) fall back to plain MSE. Returns removable handles.
"""
handles: list = []
def _make_expert_hook(expert_module, weight_name, quantizers, enabled):
def _expert_hook(_input_quantizer, args):
if not args:
return
idx = expert_module._current_expert_idx
if idx in enabled:
# Read the weight fresh (valid under accelerate/FSDP re-materialization).
capture(quantizers[idx], getattr(expert_module, weight_name)[idx], args[0])
return _expert_hook
for name, module in name_to_module.items():
if is_quantized_linear(module) and isinstance(module.weight_quantizer, TensorQuantizer):
with enable_weight_access_and_writeback(module, model, name_to_module):
# ``weight`` may be absent (e.g. TE GroupedLinear exposes weight0..N, not weight);
# such modules have no single 2-D weight to pair and fall back to plain MSE.
weight = getattr(module, "weight", None)
if weight is None or weight.dim() != 2 or not module.weight_quantizer.is_enabled:
continue
_warn_local_hessian_fallback(
name, weight, module.weight_quantizer, block_size, warned
)
def _dense_hook(linear, args):
if args:
capture(linear.weight_quantizer, linear.weight, args[0])
handles.append(module.register_forward_pre_hook(_dense_hook))
elif _is_quant_fused_experts(module):
with enable_weight_access_and_writeback(module, model, name_to_module):
first_proj_attr = getattr(module, "_first_proj_attr", "gate_up_proj")
for weight_name, quantizers_name, input_q_name in (
(
first_proj_attr,
f"{first_proj_attr}_weight_quantizers",
f"{first_proj_attr}_input_quantizer",
),
("down_proj", "down_proj_weight_quantizers", "down_proj_input_quantizer"),
):
weight = getattr(module, weight_name, None)
quantizers = getattr(module, quantizers_name, None)
input_quantizer = getattr(module, input_q_name, None)
if weight is None or quantizers is None or input_quantizer is None:
continue
_warn_local_hessian_fallback(
f"{name}.{weight_name}", weight[0], quantizers[0], block_size, warned
)
# Snapshot which experts are enabled now, before the caching forward silences
# all weight quantizers — so we don't capture (and discard) disabled experts.
enabled = {i for i, q in enumerate(quantizers) if q.is_enabled}
handles.append(
input_quantizer.register_forward_pre_hook(
_make_expert_hook(module, weight_name, quantizers, enabled)
)
)
return handles
@torch.no_grad()
def local_hessian_calibrate(
model: nn.Module,
forward_loop: ForwardLoop | None = None,
distributed_sync: bool = True,
step_size: float = 0.1,
start_multiplier: float = 0.25,
stop_multiplier: float = 4.0,
fp8_scale_sweep: bool = True,
block_size: int = 16,
debug: bool = False,
shared_states: Mapping[str, Mapping[str, Sequence[str]]] | None = None,
):
"""Calibrate weight quantizers by minimizing the Hessian-weighted error.
Minimizes ``(W - Wq)ᵀ H (W - Wq)`` with per-block Hessian ``H = ΣXᵀX`` (approximating the
output error ``||WX - WqX||²``), built from a forward with weight fake-quant disabled
(input quantizers untouched) and fed to :func:`mse_calibrate`'s weight search via ``error_func``.
Like :func:`mse_calibrate`, TensorQuantizer weights are calibrated — with the Hessian
metric where a weight pairs with its input activations (dense linears and HF fused-MoE
experts), plain MSE otherwise. Other quantizer types (e.g. SequentialQuantizer) are
unsupported and left at their max-calibrated scale.
Args:
model: Model to be calibrated.
forward_loop: A callable which takes the model as argument and
forwards calibration data through the model. Required for this algorithm.
distributed_sync: Whether to sync amax across distributed processes.
step_size: Step size for amax search (default: 0.1).
start_multiplier: Starting multiplier for amax search (default: 0.25).
stop_multiplier: Ending multiplier for amax search (default: 4.0).
fp8_scale_sweep: If True, sweep over all 128 possible FP8 E4M3 scale values
for NVFP4 per-block quantization (default: True).
block_size: Block size for local Hessian computation (default: 16).
debug: If True, retain the per-quantizer Hessian accumulators on the model
(``model._local_hessian_accumulators``) for inspection.
See :class:`LocalHessianCalibConfig <modelopt.torch.quantization.config.LocalHessianCalibConfig>`
for details on the configuration options.
"""
if forward_loop is None:
warnings.warn("forward_loop must be provided for local_hessian; skipping local_hessian")
return
# Phase 1: max-calibrate (also bootstraps dead experts + promotes/syncs NVFP4 static).
print_rank_0("local_hessian: Running max calibration for all quantizers...")
max_calibrate(model, forward_loop, distributed_sync, shared_states=shared_states)
name_to_module = dict(model.named_modules())
# Hessians keyed by id(weight_quantizer); modules pair weights<->activations via the hook.
accumulators: dict[int, _LocalHessianAccumulator] = {}
def capture(weight_quantizer, weight, input_tensor):
input_local = input_tensor.to_local() if hasattr(input_tensor, "to_local") else input_tensor
acc = accumulators.get(id(weight_quantizer))
if acc is None:
acc = _LocalHessianAccumulator(weight.shape[0], weight.shape[1], block_size)
accumulators[id(weight_quantizer)] = acc
acc.accumulate(input_local)
# Phase 2: capture each weight's input activations during a forward with weight fake-quant
# disabled (so H = ΣXᵀX reflects full-precision weights); input quantizers are left as-is.
warned: set = set()
handles = _register_local_hessian_input_hooks(
model, name_to_module, capture, block_size, warned
)
print_rank_0("local_hessian: Caching activations and computing local Hessian...")
try:
with set_quantizer_by_cfg_context(
model, [{"quantizer_name": "*weight_quantizer", "enable": False}]
):
forward_loop(model)
finally:
for handle in handles:
handle.remove()
# TODO(fridah-nv): the per-block Hessian is not synced across TP/DP ranks (max_calibrate's
# amax sync runs before this), so refined amaxes can diverge. All-reduce Hessian / re-sync.
if dist_is_initialized() and dist_size() > 1:
warn_rank_0(
"local_hessian: Hessian is not synced across ranks; refined weight amaxes may "
"diverge under tensor/data parallelism. Treat local_hessian as single-rank for now."
)
# Phase 3: weight search. Build error_funcs first so build_error_func caches the normalized
# Hessian (freeing the raw buffer) before normalized_hessian() reuses it; the fast path
# (tensor) and reference fallback (error_func) then share that one tensor.
error_funcs = {
qid: acc.build_error_func(keep_buffer=debug) for qid, acc in accumulators.items()
}
hessians = {qid: acc.normalized_hessian() for qid, acc in accumulators.items()}
print_rank_0("local_hessian: Running MSE calibration with local Hessian loss...")
_mse_calibrate_weights(
model,
name_to_module,
step_size=step_size,
start_multiplier=start_multiplier,
stop_multiplier=stop_multiplier,
fp8_scale_sweep=fp8_scale_sweep,
error_func_for=lambda q: error_funcs.get(id(q)),
hessian_for=lambda q: hessians.get(id(q)),
)
# Release the per-block Hessians (held by the error_func closures, calibrators, and the
# accumulators' cache) before empty_cache so export starts defragmented; keep only for debug.
error_funcs.clear()
hessians.clear()
for module in name_to_module.values():
if isinstance(module, TensorQuantizer) and isinstance(module._calibrator, MseCalibrator):
module._calibrator._error_func = None
if isinstance(module._calibrator, NVFP4MSECalibrator):
module._calibrator._hessian = None
if debug:
model._local_hessian_accumulators = accumulators
else:
accumulators.clear()
if torch.cuda.is_available():
torch.cuda.empty_cache()
print_rank_0("local_hessian: Calibration complete.")
def enable_stats_collection(model: nn.Module):
"""Enable stats collection for all quantizers in the model."""
for name, module in model.named_modules():
if isinstance(module, TensorQuantizer) and not module._disabled:
if module._use_constant_amax or module._constant_amax is not None:
# Quantizers with a constant amax use a fixed amax and don't need calibration.
# Disable quantization during calibration so it doesn't affect other quantizers.
module.disable_quant()
continue
elif module._calibrator is not None:
module.disable_quant()
module.enable_calib()
else:
module.disable()
def finish_stats_collection(model: nn.Module, method: str | None = None, **kwargs):
"""Finish stats collection for all quantizers in the model."""
for _, module in model.named_modules():
if not isinstance(module, TensorQuantizer) or module._disabled:
continue
if module._use_constant_amax or module._constant_amax is not None:
# Re-enable quantization for constant-amax quantizers disabled in enable_stats_collection.
module.enable_quant()
continue
cal = getattr(module, "_calibrator", None)
if cal and not getattr(module, "_dynamic", False):
if method == "entropy":
if cal.compute_amax(method) is not None:
module.load_calib_amax("entropy", **kwargs)
elif cal.compute_amax(**kwargs) is not None:
module.load_calib_amax(**kwargs)
if module.bias_calibrator is not None and module.bias_type == "static":
module.load_calib_bias()
module.enable_quant()
module.disable_calib()
@torch.no_grad()
def disable_pre_quant_scale_and_resmooth(linear: nn.Module, delete_pre_quant_scale: bool = False):
"""Disable pre_quant_scale and resmooth the quantized linear weights."""
assert is_quantized_linear(linear), "Only quantized linear modules are supported"
assert linear.input_quantizer._enable_pre_quant_scale, (
"pre_quant_scale should be enabled first!"
)
assert hasattr(linear.input_quantizer, "_pre_quant_scale"), (
"pre_quant_scale should be available"
)
pre_quant_scale = linear.input_quantizer._pre_quant_scale.to(torch.float32)
linear.weight.copy_(
(linear.weight * pre_quant_scale.squeeze()[None, :]).to(linear.weight.dtype)
)
linear.weight_quantizer.reset_amax()
max_calibrate(linear, lambda linear: linear.weight_quantizer(linear.weight))
# Lets not delete the _pre_quant_scale, it might useful later; Instead we will disable it
linear.input_quantizer._enable_pre_quant_scale = False
if linear.input_quantizer.amax is not None:
assert hasattr(linear.input_quantizer, "_amax_for_smoothing")
device, dtype = linear.weight.device, linear.weight.dtype
linear.input_quantizer.amax = linear.input_quantizer._amax_for_smoothing.amax().to(
device=device, dtype=dtype
)
if delete_pre_quant_scale:
delattr(linear.input_quantizer, "_pre_quant_scale")
linear.input_quantizer._enable_pre_quant_scale = False
# A global variable used during auto_quantize to avoid folding pre_quant_scale to weights
_ENABLE_FOLDING_PQS_TO_WEIGHTS = True
@torch.no_grad()
def _apply_weight_pre_quant_scale(linear, pre_quant_scale):