Repository navigation
Expand file tree
/
Copy pathexample_utils.py
More file actions
executable file
·1270 lines (1107 loc) · 55.6 KB
/
Copy pathexample_utils.py
File metadata and controls
executable file
·1270 lines (1107 loc) · 55.6 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.
import argparse
import copy
import hashlib
import inspect
import json
import logging
import os
import warnings
from collections.abc import Iterator
from contextlib import contextmanager, nullcontext
from pathlib import Path
from typing import Any
import torch
import transformers
from accelerate import infer_auto_device_map, init_empty_weights
from accelerate.utils import get_max_memory
from cast_mxfp4_to_nvfp4 import force_weight_quantizers_static
from safetensors import safe_open
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoTokenizer,
PreTrainedTokenizerBase,
)
from modelopt.recipe import ModelOptAutoQuantizeRecipe, load_recipe
from modelopt.recipe.presets import QUANT_CFG_CHOICES
from modelopt.torch.export import has_spec_opt
from modelopt.torch.export.trtllm.enc_dec import is_trtllm_enc_dec_export
from modelopt.torch.models import get_ptq_spec, hf_model_type
from modelopt.torch.models.hf import (
checkpoint_has_mtp,
forward_calibration_batch,
prefers_bundled_code,
prepare_model_for_loading,
)
from modelopt.torch.quantization.mode import get_modelike_from_algo_cfg
from modelopt.torch.speculative.utils import is_speculative_config
from modelopt.torch.utils import distributed as dist_utils
from modelopt.torch.utils.distributed import DistributionPlan, distribution_plan
from modelopt.torch.utils.fsdp2_utils import fsdp2_root_unsharded
from modelopt.torch.utils.logging import warn_rank_0
from modelopt.torch.utils.mlflow import Tool, resolved_recipe_texts, tracked_run
from modelopt.torch.utils.plugins.model_load_utils import (
load_pretrained,
resolve_distribution_plan,
resolve_model_class,
)
logger = logging.getLogger(__name__)
def _calibration_methods(args) -> set[str]:
"""The calibration methods (``max``, ``awq_lite``, ...) the run's --recipe or --qformat uses."""
if getattr(args, "recipe", None) is not None:
recipe = load_recipe(args.recipe)
configs = [getattr(recipe, "quantize", None)]
search = getattr(recipe, "auto_quantize", None) # the KV-cache search allows only max
if search is not None:
configs += search.candidate_formats
configs += [c for space in search.module_search_spaces for c in space.candidate_formats]
algorithms = [config.algorithm for config in configs if config is not None]
else:
preset = QUANT_CFG_CHOICES.get(getattr(args, "qformat", None) or "")
algorithms = [preset.get("algorithm")] if preset is not None else []
return {
mode.removesuffix("_calibrate")
for algorithm in algorithms
for mode, _ in get_modelike_from_algo_cfg(algorithm)
}
def _awq_calibrations(args) -> set[str]:
"""The AWQ calibrations (``awq_lite``, ``awq_full``) the run's --recipe or --qformat uses."""
return _calibration_methods(args) & {"awq_lite", "awq_full"}
def validate_fsdp2_supported(args, config):
"""Raise ``NotImplementedError`` for model/CLI combos the FSDP2 path doesn't support yet."""
issues = []
if (unsupported := get_ptq_spec(hf_model_type(config)).fsdp2_unsupported) is not None:
issues.append(unsupported)
# A layout whose decoder layers cannot be found fails in fsdp2_wrap. Encoder-decoder models
# have no single decoder stack. Without --calib_with_images a VLM calibrates on text, which a
# forward that requires images cannot run.
if getattr(config, "is_encoder_decoder", False):
issues.append("encoder-decoder models")
elif _is_multimodal_config(config) and not getattr(args, "calib_with_images", False):
model_class = resolve_model_class(config, getattr(args, "trust_remote_code", False))
if model_class is not None and forward_requires_images(model_class):
issues.append(
f"{model_class.__name__} without --calib_with_images "
"(its forward requires image inputs)"
)
if any(
getattr(cfg, "quantization_config", None) is not None
for cfg in (config, getattr(config, "text_config", None))
):
issues.append("pack-quantized / compressed-tensors checkpoints")
if getattr(args, "specdec_offline_dataset", None) is not None:
issues.append("speculative decoding (--specdec_offline_dataset)")
if getattr(args, "low_memory_mode", False):
issues.append("--low_memory_mode (redundant with FSDP2)")
if dist_utils.size() > 1 and (awq := _awq_calibrations(args)):
issues.append(
f"AWQ calibration ({', '.join(sorted(awq))}) on more than one rank: each rank would fold "
"its own smoothing scale into its weight shard (drop --use_fsdp2, run on one rank, or "
"use a non-AWQ format)"
)
if not issues and checkpoint_has_mtp(config.model_type, args.local_checkpoint_path):
issues.append("MTP weights (auxiliary modules are not constructed by the FSDP2 loader)")
if issues:
raise NotImplementedError(
"--use_fsdp2 does not support:\n - "
+ "\n - ".join(issues)
+ "\nRemove --use_fsdp2 or use a standard causal-LM checkpoint."
)
def exports_tensorrt_llm_checkpoint(args, model_type: str | None) -> bool:
"""Whether the run exports through the deprecated TensorRT-LLM checkpoint exporter."""
return (
is_trtllm_enc_dec_export(model_type)
or args.sparsity_fmt != "dense"
or "int8_smoothquant" in args.qformat
)
def resolve_distribution(args) -> tuple[DistributionPlan, Any]:
"""Decide how hf_ptq distributes the model, refusing what that run cannot do: ``(plan, config)``.
:func:`resolve_distribution_plan` decides; ``--use_fsdp2`` asks it for FSDP2 without expert
parallelism.
"""
if args.use_fsdp2:
# Before the decision, which builds the model on the meta device: some checkpoints these
# checks refuse (VILA, multimodal, pack-quantized) cannot be built there.
validate_fsdp2_supported(
args,
AutoConfig.from_pretrained(
args.local_checkpoint_path, trust_remote_code=args.trust_remote_code
),
)
plan, hf_config = resolve_distribution_plan(
args.local_checkpoint_path,
trust_remote_code=args.trust_remote_code,
ep_size=1 if args.use_fsdp2 else None,
dense="fsdp" if args.use_fsdp2 else None,
)
if plan.is_fsdp_dense and not plan.is_expert_parallel and not args.use_fsdp2:
raise RuntimeError(
f"{plan!r} FSDP2-shards the model, which this script does under --use_fsdp2. Pass it, "
"or set MODELOPT_FSDP_SIZE=1 if the model does fit one GPU; an MoE can instead shard its "
"experts (MODELOPT_EP_DEGREE above 1)."
)
if plan.world_size > 1 and exports_tensorrt_llm_checkpoint(args, hf_model_type(hf_config)):
# That exporter takes the process count for tensor parallelism.
raise NotImplementedError(
f"{plan!r}: the TensorRT-LLM checkpoint export (encoder-decoder models, "
"--sparsity_fmt, int8_smoothquant) runs in a single process; launch hf_ptq without "
"torchrun for it."
)
if (plan.is_expert_parallel or plan.is_fsdp_dense) and args.vllm_fakequant_export:
# It writes the whole model from every rank that exports, and every rank of a sharded
# model exports.
raise NotImplementedError(
f"{plan!r}: --vllm_fakequant_export writes the whole model from one process, which "
"holds only its own part of a sharded model; launch hf_ptq without torchrun for it."
)
if plan.is_expert_parallel and args.experts_implementation is not None:
# The expert-parallel load runs the experts through torch_a2a whatever the flag names.
raise NotImplementedError(
f"{plan!r}: --experts_implementation picks the experts backend a model is loaded with, "
"but the expert-parallel load runs the routed experts through torch_a2a whatever it "
"names. Drop it, or quantize without expert parallelism: with --use_fsdp2, or in a "
"single process."
)
if (
plan.world_size > 1
and not args.use_fsdp2
and args.recipe is not None
and isinstance(load_recipe(args.recipe), ModelOptAutoQuantizeRecipe)
):
# Each rank would score its own data, and could pick other formats per layer.
raise NotImplementedError(
f"{plan!r}: AutoQuantize scores each rank's own calibration data and reduces no score "
"across ranks, so ranks could choose different formats per layer; launch hf_ptq "
"without torchrun for an AutoQuantize recipe."
)
if plan.world_size > 1 and not args.use_fsdp2 and "lsq" in _calibration_methods(args):
# Its scale calibration is the algorithm it runs first, synced or refused as that one is,
# but nothing has checked its learnable scales across ranks yet.
warn_rank_0(
f"{plan!r}: LSQ has not been validated on a run of several ranks: nothing checks that "
"the ranks' learnable scales match. Launch hf_ptq without torchrun for the tested path."
)
if (
plan.world_size > 1
and args.recipe is not None
and layerwise_export_requested(recipe_layerwise_blocks(load_recipe(args.recipe)))
):
# Every rank would write the same shard files.
raise NotImplementedError(
f"{plan!r}: the recipe's layerwise export writes its checkpoint shards from one "
"process; launch hf_ptq without torchrun for it."
)
if plan.world_size > 1 and not args.use_fsdp2:
# Options for loading one model in a single process, refused rather than ignored.
# --max_cpu_memory_gb and --max_gpu_memory_gb come only with --offload_folder.
for flag, given in (
("--low_memory_mode", args.low_memory_mode),
("--use_seq_device_map", args.use_seq_device_map),
("--offload_folder", args.offload_folder is not None),
):
if given:
raise NotImplementedError(
f"{plan!r}: {flag} configures loading one model in a single process, but each "
"rank of this run loads its own share or copy of it onto its own GPU. Drop it, "
"or launch hf_ptq without torchrun to use it."
)
return plan, hf_config
def preview_generate_kwargs(model) -> dict[str, Any]:
"""Extra ``generate`` kwargs that keep every rank of a sharded model decoding a preview.
Each rank previews the first sample of its own calibration shard, so the ranks finish at
different steps. A model its plan shards runs a collective in every forward (the routed experts'
all-to-all, FSDP2's all-gathers): a rank that stopped decoding would leave the others blocked in
it. ``synced_gpus`` keeps every rank stepping until all of them have finished.
"""
plan = distribution_plan(model)
sharded = plan.world_size > 1 and (plan.is_expert_parallel or plan.is_fsdp_dense)
return {"synced_gpus": True} if sharded else {}
@contextmanager
def keep_the_experts_implementation(model) -> Iterator[None]:
"""Keep ``generate`` from switching a MoE's experts to ``batched_mm`` while it decodes.
On a GPU, ``generate`` runs the experts of a ``grouped_mm`` MoE on ``batched_mm`` for the
decoding stage and switches them back (``_optimize_model_for_decode``, Transformers 5.0 and
later). Two things follow. ModelOpt's quantizers sit on the ``eager``, ``grouped_mm`` and
``torch_a2a`` forwards, which ``batched_mm`` bypasses, so the preview after PTQ would decode on
unquantized experts. And Transformers refuses the switch for an FSDP2-wrapped model, whose class
is a subclass built outside its modeling module: ``FSDPQwen3MoeForCausalLM does not support
setting experts implementation``. Every module of the model that has the hook is kept from it:
a model can generate through a submodule, as a Nemotron-VL model's ``chat`` generates through
its language model.
"""
modules = [m for m in model.modules() if hasattr(m, "_optimize_model_for_decode")]
# Put back what each module itself held, if anything: a nested use, or a hook bound per instance.
own = [(module, vars(module).get("_optimize_model_for_decode")) for module in modules]
for module in modules:
module._optimize_model_for_decode = nullcontext
try:
yield
finally:
for module, held in own:
if held is None:
del module._optimize_model_for_decode
else:
module._optimize_model_for_decode = held
def run_vlm_preview(
full_model,
tokenizer,
input_ids,
pyt_ckpt_path,
stage_name,
allow_fallback=False,
trust_remote_code=False,
):
"""Run text-only and VL preview generation for VLM wrappers.
Args:
full_model: The full VL model
tokenizer: The tokenizer
input_ids: Input tensor for generation
pyt_ckpt_path: Path to the model checkpoint
stage_name: Description of the stage (e.g., "before quantization", "after quantization")
allow_fallback: Whether to allow fallback to standard generate on failure
trust_remote_code: Whether to trust remote code for Huggingface models and tokenizers
Returns:
Generated text response or None if generation failed
"""
from vlm_utils import run_text_only_generation, run_vl_preview_generation
with keep_the_experts_implementation(full_model):
print(f"Running text-only preview generation for the VLM wrapper ({stage_name})...")
question = tokenizer.decode(input_ids[0], skip_special_tokens=True)
lockstep = preview_generate_kwargs(full_model)
generation_config = {
"max_new_tokens": 100,
"do_sample": False,
"eos_token_id": tokenizer.eos_token_id,
**lockstep,
}
# Try text-only generation (may fail for encoder-decoder models)
text_response = run_text_only_generation(
full_model, tokenizer, question, generation_config, pyt_ckpt_path, trust_remote_code
)
generated_ids = None
if text_response is not None:
print(f"✅ Text-only generation successful: {text_response[:100]}...")
generated_ids = text_response
elif allow_fallback:
print("Text-only generation failed, falling back to standard generate...")
generated_ids = full_model.generate(input_ids, max_new_tokens=100, **lockstep)
# Run additional VL test with images
print(f"Running additional VL test with images ({stage_name})...")
run_vl_preview_generation(
full_model, tokenizer, pyt_ckpt_path, stage_name, trust_remote_code, lockstep
)
return generated_ids
def _is_multimodal_config(config):
"""Check if a config indicates a multimodal model (config-only version of is_multimodal_model)."""
return (
hasattr(config, "vision_config") # Standard vision config (e.g., Qwen2.5-VL)
or getattr(config, "is_encoder_decoder", False) # Encoder-decoder VL models
or any( # Architecture-based detection for custom VL models (e.g., Nemotron-Parse)
"conditionalgeneration" in arch.lower() for arch in getattr(config, "architectures", [])
)
)
def forward_requires_images(model: "torch.nn.Module | type[torch.nn.Module]") -> bool:
"""Whether ``model.forward`` cannot run without images (``pixel_values`` has no default)."""
param = inspect.signature(model.forward).parameters.get("pixel_values")
return param is not None and param.default is inspect.Parameter.empty
def create_vlm_calibration_forward(full_model):
"""Return ``forward(batch)``, which runs one multimodal calibration batch through the VLM.
It filters the batch kwargs to the parameters the model's forward accepts, then calls the
appropriate forward method. :func:`create_vlm_calibration_loop` runs it over a dataloader; an
expert-parallel run hands it to ``distributed_forward_loop`` instead.
Args:
full_model: The full VLM model
Returns:
A function that runs one batch through ``full_model``
"""
# Check if model is encoder-decoder (needs decoder_input_ids instead of input_ids)
is_enc_dec = getattr(full_model.config, "is_encoder_decoder", False)
# Inspect model's forward signature to determine what parameters it accepts
forward_params = inspect.signature(full_model.forward).parameters
accepts_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in forward_params.values())
allowed_keys = set(forward_params.keys())
def forward(batch):
# For encoder-decoder models, rename input_ids → decoder_input_ids
# and disable KV caching to avoid tuple index errors in decoder layers
if is_enc_dec and "input_ids" in batch and "pixel_values" in batch:
batch["decoder_input_ids"] = batch.pop("input_ids")
if "attention_mask" in batch:
batch["decoder_attention_mask"] = batch.pop("attention_mask")
batch["use_cache"] = False
# Filter batch to only include parameters the model accepts
if accepts_kwargs:
call_kwargs = batch
else:
call_kwargs = {k: v for k, v in batch.items() if k in allowed_keys}
# Remove None values
call_kwargs = {k: v for k, v in call_kwargs.items() if v is not None}
# A model whose plugin has its own calibration forward runs the batch itself.
if not forward_calibration_batch(full_model, call_kwargs):
full_model(**call_kwargs)
return forward
def create_vlm_calibration_loop(full_model, calib_dataloader):
"""Create a calibration loop for VLM models that handles multimodal inputs.
It runs every batch through :func:`create_vlm_calibration_forward`.
Args:
full_model: The full VLM model
calib_dataloader: DataLoader yielding multimodal batches
Returns:
A calibration function that can be passed to mtq.quantize()
"""
def calibrate_loop(_model):
forward = create_vlm_calibration_forward(full_model)
full_model.eval()
# The safe-forward branch calls submodules directly, skipping the FSDP2 root's pre-forward.
with torch.no_grad(), fsdp2_root_unsharded(full_model):
for batch in calib_dataloader:
forward(batch)
return calibrate_loop
def build_quant_cfg(
quant_cfg,
awq_block_size,
moe_calib_experts_ratio: float | None = None,
) -> dict[str, Any]:
quant_cfg = copy.deepcopy(quant_cfg)
if "awq" in str(quant_cfg.get("algorithm")):
from modelopt.torch.quantization.config import find_quant_cfg_entry_by_path
weight_quantizer_entry = find_quant_cfg_entry_by_path(
quant_cfg["quant_cfg"], "*weight_quantizer"
)
weight_quantizer = weight_quantizer_entry.get("cfg") or {}
if isinstance(weight_quantizer, list):
weight_quantizer = weight_quantizer[0]
# If awq_block_size argument is provided, update weight_quantizer
if awq_block_size:
weight_quantizer["block_sizes"][-1] = awq_block_size
if moe_calib_experts_ratio:
assert 0 < moe_calib_experts_ratio <= 1, "moe_calib_experts_ratio must be between 0 and 1"
if isinstance(quant_cfg["algorithm"], str):
quant_cfg["algorithm"] = {
"method": quant_cfg["algorithm"],
"moe_calib_experts_ratio": moe_calib_experts_ratio,
}
elif isinstance(quant_cfg["algorithm"], dict):
quant_cfg["algorithm"]["moe_calib_experts_ratio"] = moe_calib_experts_ratio
elif isinstance(quant_cfg["algorithm"], list) and all(
isinstance(algorithm, dict) for algorithm in quant_cfg["algorithm"]
):
# e.g. [gptq, imatrix]: each algorithm runs its own calibration, so each gets the ratio.
for algorithm in quant_cfg["algorithm"]:
algorithm["moe_calib_experts_ratio"] = moe_calib_experts_ratio
else:
warnings.warn(
f"Quantization algorithm: {quant_cfg['algorithm']} does not support setting moe_calib_experts_ratio"
)
return quant_cfg
def get_tokenizer(ckpt_path, trust_remote_code=False, **kwargs) -> PreTrainedTokenizerBase:
print(f"Initializing tokenizer from {ckpt_path}")
tokenizer = AutoTokenizer.from_pretrained(
ckpt_path, trust_remote_code=trust_remote_code, **kwargs
)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
assert tokenizer.pad_token is not None, f"Pad token for {ckpt_path} cannot be set!"
return tokenizer
def get_dtype(dtype):
if dtype == "bf16":
dtype = torch.bfloat16
elif dtype == "fp16":
dtype = torch.float16
elif dtype == "fp32":
dtype = torch.float32
else:
raise NotImplementedError(f"Unknown dtype {dtype}")
return dtype
def _unpack_compressed_linear_weights(model, ckpt_path=None):
"""Hybrid restoration: restores BF16 layers and fixes expert metadata.
1. BF16 layers (vision, lm_head) are restored from checkpoint and marked non-compressed.
2. INT4 experts stay compressed in HBM to save memory (decompressed on-the-fly).
3. Metadata (weight_shape) is fixed to avoid decompression errors.
"""
try:
from compressed_tensors.linear.compressed_linear import CompressedLinear
from compressed_tensors.quantization import QuantizationStatus
except ImportError:
return
if ckpt_path is None:
ckpt_path = getattr(model.config, "_name_or_path", None)
if not ckpt_path:
return
def _resolve_file(filename):
local = os.path.join(ckpt_path, filename)
return local if os.path.exists(local) else None
# Load non-expert weights and metadata from safetensors
checkpoint_weights = {}
index_file = _resolve_file("model.safetensors.index.json")
if index_file:
with open(index_file) as f:
index = json.load(f)
st_filenames = list(set(index.get("weight_map", {}).values()))
else:
st_filenames = ["model.safetensors"]
for fname in st_filenames:
sf_path = _resolve_file(fname)
if sf_path is None:
continue
with safe_open(sf_path, framework="pt") as f:
for key in f.keys(): # noqa: SIM118 - safe_open is not iterable
if ".mlp.experts." not in key or "weight_shape" in key:
checkpoint_weights[key] = f.get_tensor(key)
# Hybrid restoration
for name, module in model.named_modules():
if not isinstance(module, CompressedLinear):
continue
with torch.no_grad():
target_device = next(module.parameters()).device
# CASE A: Real BF16 weight exists (vision, lm_head)
if f"{name}.weight" in checkpoint_weights:
w = checkpoint_weights[f"{name}.weight"].to(target_device)
module._parameters.pop("weight", None)
module._buffers.pop("weight", None)
module.__dict__.pop("weight", None)
param = torch.nn.Parameter(w, requires_grad=False)
module._parameters["weight"] = param
module.__dict__["weight"] = param
module.quantization_status = QuantizationStatus.FROZEN
logger.debug("Restored BF16 layer: %s", name)
# CASE B: Expert (stay compressed, fix metadata)
elif f"{name}.weight_shape" in checkpoint_weights:
ws = checkpoint_weights[f"{name}.weight_shape"]
if f"{name}.weight_packed" in checkpoint_weights:
module.weight_packed = checkpoint_weights[f"{name}.weight_packed"].to(
torch.int32
)
module._parameters.pop("weight", None)
module._buffers.pop("weight", None)
module.__dict__.pop("weight", None)
shape_param = torch.nn.Parameter(ws.to(torch.int32), requires_grad=False)
module._parameters.pop("weight_shape", None)
module.__dict__.pop("weight_shape", None)
module._parameters["weight_shape"] = shape_param
module.__dict__["weight_shape"] = shape_param
# Ensure compressed experts do not carry a stale weight attribute
for name, module in model.named_modules():
if not isinstance(module, CompressedLinear):
continue
if getattr(module, "quantization_status", None) != QuantizationStatus.COMPRESSED:
continue
module._parameters.pop("weight", None)
module._buffers.pop("weight", None)
module.__dict__.pop("weight", None)
def get_original_hf_quant_method(config) -> str | None:
"""Return the checkpoint's original ``quantization_config.quant_method``, if any.
Returns e.g. ``"mxfp4"`` for native MXFP4 checkpoints (OpenAI's gpt-oss family), or
``None`` for unquantized models. Handles ``quantization_config`` stored as a dict or a
config object, and the nested ``text_config`` of multi-modal models.
"""
for cfg in (config, getattr(config, "text_config", None)):
quant_cfg = getattr(cfg, "quantization_config", None)
method = (
quant_cfg.get("quant_method")
if isinstance(quant_cfg, dict)
else getattr(quant_cfg, "quant_method", None)
)
if method:
return str(method)
return None
def _resolve_init_config(hf_config, auto_model_module, ckpt_path, config_kwargs):
"""Re-derive a built-in config when a remote-code config is used with a built-in model
class, so it matches the model definition's version; fall back to hf_config otherwise.
"""
if auto_model_module in [AutoModelForCausalLM, AutoModel]:
return hf_config
if not type(hf_config).__module__.startswith("transformers_modules"):
return hf_config
builtin_config_kwargs = {k: v for k, v in config_kwargs.items() if k != "trust_remote_code"}
try:
return AutoConfig.from_pretrained(ckpt_path, **builtin_config_kwargs)
except Exception as e:
warnings.warn(
f"Could not re-derive a built-in config for {ckpt_path} ({e}); using the "
"remote-code config for device-map inference."
)
return hf_config
def _get_config_dtype(config):
config_dtype = (
getattr(config, "dtype", None) or getattr(config, "torch_dtype", None) or torch.bfloat16
)
if isinstance(config_dtype, str):
config_dtype = getattr(torch, config_dtype)
return config_dtype
def _apply_dtype_to_config(model_kwargs, config_dtype, dtype_kwarg, apply_config_dtype=False):
model_kwargs = model_kwargs.copy()
if dtype_kwarg == "torch_dtype":
model_kwargs["torch_dtype"] = config_dtype
model_kwargs.pop("dtype", None)
elif apply_config_dtype:
model_kwargs["dtype"] = config_dtype
return model_kwargs
def _fmt_max_memory(max_memory: dict) -> str:
"""Format a ``{device: bytes}`` budget dict into a human-readable string."""
parts = []
for key in sorted(max_memory.keys(), key=lambda k: (isinstance(k, str), k)):
val = max_memory[key]
label = f"{val / 1024**3:.1f} GiB" if isinstance(val, int) else str(val)
key_str = f"GPU {key}" if isinstance(key, int) else str(key)
parts.append(f" {key_str}: {label}")
return "\n".join(parts)
def get_model(
ckpt_path,
device="cuda",
gpu_mem_percentage=0.8,
trust_remote_code=False,
use_seq_device_map=False,
attn_implementation=None,
experts_implementation=None,
offload_folder=None,
max_cpu_memory_gb=None,
max_gpu_memory_gb=None,
distribution: DistributionPlan | None = None,
):
print(f"Initializing model from {ckpt_path}")
# The plan to load the whole model by on every rank; a single process's by default. Only a plan
# the caller gave reaches load_pretrained: without one it decides itself as before, and refuses
# MODELOPT_* knobs asking to shard over a launch whose process group is not set up.
plan = distribution or DistributionPlan()
if plan.is_expert_parallel or plan.is_fsdp_dense:
raise ValueError(
f"{plan!r} shards the model over the ranks, but get_model loads the whole model on "
"every rank: load it with load_pretrained."
)
routing = {} if distribution is None else {"distribution": distribution}
_disk_offload = offload_folder is not None
if _disk_offload and max_cpu_memory_gb is None:
warnings.warn(
"offload_folder is set but max_cpu_memory_gb is not specified. "
"CPU memory usage during model load will be unbounded. "
"Pass max_cpu_memory_gb to cap CPU usage.",
UserWarning,
)
# Under torchrun each rank asks for its own "cuda:<local_rank>". Do not fall through to "auto":
# accelerate runs its placement heuristic INDEPENDENTLY in every rank, and on a node whose GPUs
# are all idle every rank scores them identically and picks the SAME card. All ranks' weights,
# and with them every quantizer's _amax buffer, then live on one GPU; the first NCCL collective
# binds the whole data-parallel group to that single device and aborts with "Duplicate GPU
# detected : rank 1 and rank 0 both on CUDA device ...". Every load path below honours the pin
# except those that load with no device map (a spec's ``no_auto_device_map`` or
# ``no_device_map``): each rank builds a whole copy in host memory and only then moves it to
# its own GPU, so the node needs one host copy per rank.
# A dense model too large to replicate per rank wants --use_fsdp2, not "auto" sharding: under
# data-parallel calibration each rank must own its own GPU. A single process keeps "auto".
# hf_ptq hands in its run's torch.device, which never equals a string such as "cpu".
on_cpu = torch.device(device).type == "cpu"
if plan.world_size > 1 and not on_cpu and ":" not in str(device):
raise ValueError(
f"{plan!r} has each rank hold its own copy of the model on its own GPU, but "
f"device={device!r} names no GPU index; pass the rank's own GPU, cuda:<local_rank>."
)
pinned = {"": str(device)} if not on_cpu and plan.world_size > 1 else None
device_map = "cpu" if on_cpu else pinned or "auto"
# Prepare config kwargs for loading
config_kwargs = {"trust_remote_code": trust_remote_code} if trust_remote_code else {}
# Load config once and handle VL model detection
try:
hf_config = AutoConfig.from_pretrained(ckpt_path, **config_kwargs)
except Exception as e:
print(f"Error: Could not load config from {ckpt_path}: {e}")
raise RuntimeError(f"Failed to load model configuration from {ckpt_path}") from e
ptq = get_ptq_spec(hf_model_type(hf_config))
if ptq.no_auto_device_map is not None:
print(f"Loading without an automatic device map: {ptq.no_auto_device_map}.")
device_map = None
if attn_implementation is not None:
config_kwargs["attn_implementation"] = attn_implementation
# Note: Forcibly converting the model precision between bf16 and fp16 may introduce accuracy drop
model_kwargs = config_kwargs.copy()
model_kwargs.setdefault("dtype", "auto")
# Only when asked, on every load below: an explicit None is a value transformers stores.
experts_kwargs = (
{} if experts_implementation is None else {"experts_implementation": experts_implementation}
)
model_kwargs.update(experts_kwargs)
# Multi-GPU only: a single GPU cannot split what is tied, and sequential would needlessly cap
# max_memory there.
if (
not pinned
and not on_cpu
and torch.cuda.device_count() > 1
and ptq.sequential_device_map is not None
):
print(f"Using device_map='sequential': {ptq.sequential_device_map}.")
use_seq_device_map = True
if use_seq_device_map and pinned:
raise ValueError(
f"--use_seq_device_map spreads one model over every GPU, but each rank of this run "
f"holds its own copy on its own GPU ({device}). Drop it, or shard the model with "
"--use_fsdp2."
)
if use_seq_device_map:
device_map = "sequential"
# If we use sequential, set max_memory limit to ensure that the model does not occupy the full GPU
max_memory = get_max_memory()
max_memory = {key: value * gpu_mem_percentage for key, value in max_memory.items()}
model_kwargs["max_memory"] = max_memory
if ptq.no_device_map is not None:
print(f"Loading without a device map: {ptq.no_device_map}.")
device_map = None
# Helper function to check if model has pack-quantized config. Checks both the top-level
# config and the nested ``text_config`` of multi-modal models (e.g. kimi k2.5), and handles
# ``quantization_config`` stored as either a dict or a config object.
def has_pack_quantized_config(config):
for cfg in (config, getattr(config, "text_config", None)):
quant_cfg = getattr(cfg, "quantization_config", None)
fmt = (
quant_cfg.get("format")
if isinstance(quant_cfg, dict)
else getattr(quant_cfg, "format", None)
)
if fmt == "pack-quantized":
return True
return False
# Only the general load path below threads max_memory/offload_folder into
# from_pretrained; the specialized loaders build their own calls.
if _disk_offload and (
is_speculative_config(hf_config)
or has_pack_quantized_config(hf_config)
or get_original_hf_quant_method(hf_config) == "mxfp4"
):
warnings.warn(
"offload_folder is ignored for speculative, pack-quantized, and MXFP4 "
"checkpoints: these use dedicated load paths that cannot offload. The model "
"will be loaded fully resident.",
UserWarning,
)
if is_speculative_config(hf_config):
model = load_pretrained(
ckpt_path,
AutoModelForCausalLM,
model_type=hf_config.model_type,
**routing,
device_map=device_map,
**model_kwargs,
)
elif has_pack_quantized_config(hf_config):
from modelopt.torch.quantization.plugins.huggingface import patch_compressed_linear_loading
with patch_compressed_linear_loading():
model = load_pretrained(
ckpt_path,
AutoModelForCausalLM,
model_type=hf_config.model_type,
**routing,
device_map=pinned or "auto",
trust_remote_code=trust_remote_code,
dtype="auto",
**experts_kwargs,
)
elif get_original_hf_quant_method(hf_config) == "mxfp4":
# Native MXFP4 checkpoints (e.g. openai/gpt-oss-*) must be dequantized to
# plain BF16 experts (``GptOssExperts``) so ModelOpt can insert and export
# quantizers: the packed-kernel experts wrapper (``Mxfp4GptOssExperts``,
# used when the optional ``kernels`` package is present) is not supported by
# the unified HF export. Force dequantization regardless of whether
# ``kernels`` is installed.
# Local import: ``Mxfp4Config`` only exists in newer Transformers (gpt-oss support);
# importing it at module scope would break example_utils for users on older
# Transformers running unrelated (non-MXFP4) models.
from transformers import Mxfp4Config
# Load with a *sequential* device map (not "auto"): the MXFP4->BF16 dequant
# runs inside Transformers' threaded weight loader, and an "auto"/balanced
# split across multiple GPUs trips a CUDA illegal-memory access during dequant
# materialization. Sequential keeps each shard's dequant on a single device
# (the whole model lands on one GPU when it fits there).
model_kwargs["quantization_config"] = Mxfp4Config(dequantize=True)
model = load_pretrained(
ckpt_path,
AutoModelForCausalLM,
model_type=hf_config.model_type,
**routing,
device_map="cpu" if on_cpu else pinned or "sequential",
**model_kwargs,
)
else:
if not hf_config.architectures:
raise ValueError(f"Model config at {ckpt_path} has no architectures defined")
architecture = hf_config.architectures[0]
# Use the checkpoint's bundled code when the model plugin says the built-in class can't
# represent it (dense Nemotron-H on Transformers 5.5, whose built-in class is MoE-only) or
# is the wrong one for it (a DeepSeek architecture).
use_bundled_code = (
trust_remote_code
and hasattr(transformers, architecture)
and prefers_bundled_code(hf_config.model_type, hf_config, ckpt_path, config_kwargs)
)
if not hasattr(transformers, architecture) or use_bundled_code:
if not hasattr(transformers, architecture):
warnings.warn(
f"Architecture {architecture} not found in transformers: {transformers.__version__}. "
"Falling back to AutoModelForCausalLM (or AutoModel for non-causal architectures)."
)
assert trust_remote_code, (
"Please set trust_remote_code to True if you want to use this architecture"
)
# Use AutoModelForCausalLM for causal LMs, AutoModel for encoder-decoder models
if getattr(hf_config, "is_encoder_decoder", False):
auto_model_module = AutoModel
else:
auto_model_module = AutoModelForCausalLM
from_config = auto_model_module.from_config
else:
auto_model_module = getattr(transformers, architecture)
from_config = auto_model_module._from_config
config_for_init = _resolve_init_config(
hf_config, auto_model_module, ckpt_path, config_kwargs
)
with (
prepare_model_for_loading(
hf_config.model_type,
ckpt_path,
trust_remote_code,
model_class=(
None
if auto_model_module in (AutoModel, AutoModelForCausalLM)
else auto_model_module
),
),
init_empty_weights(include_buffers=True),
):
# When computing the device_map, assuming bfloat16 precision by default,
# unless specified by the hf_config.
config_dtype = _get_config_dtype(config_for_init)
model_kwargs2 = _apply_dtype_to_config(
model_kwargs, config_dtype, ptq.dtype_kwarg, apply_config_dtype=True
)
if auto_model_module not in [AutoModelForCausalLM, AutoModel]:
model_kwargs2.pop("trust_remote_code", None)
model_kwargs2.pop("max_memory", None)
model = from_config(config_for_init, **model_kwargs2)
max_memory = get_max_memory()
if _disk_offload:
for _k in max_memory:
if isinstance(_k, int):
if max_gpu_memory_gb is not None:
max_memory[_k] = int(max_gpu_memory_gb * 1024**3)
else:
max_memory[_k] = int(max_memory[_k] * gpu_mem_percentage)
if max_cpu_memory_gb is not None:
max_memory["cpu"] = int(max_cpu_memory_gb * 1024**3)
model_kwargs["max_memory"] = max_memory
print(
"Disk-offload mode enabled. "
f"Memory budgets: {_fmt_max_memory(max_memory)}\n"
f"Offload folder: {offload_folder}\n"
"Weights exceeding GPU+CPU budgets will be streamed from disk."
)
elif not pinned:
# A pinned copy goes onto its rank's GPU whole, by a map that ignores max_memory: sizing
# it over the node's GPUs would print a limit the load does not apply.
inferred_device_map = infer_auto_device_map(model, max_memory=max_memory)
if "cpu" in inferred_device_map.values():
for _device in max_memory:
if isinstance(_device, int):
max_memory[_device] *= gpu_mem_percentage
print(
"Model does not fit to the GPU mem. "
f"We apply the following memory limit for calibration: \n{max_memory}\n"
"If you hit GPU OOM issue, please adjust `gpu_mem_percentage` or "
"reduce the calibration `batch_size` manually."
)
model_kwargs["max_memory"] = max_memory
model_kwargs2 = _apply_dtype_to_config(model_kwargs, config_dtype, ptq.dtype_kwarg)
if _disk_offload:
model_kwargs2["offload_folder"] = offload_folder
model = load_pretrained(
ckpt_path,
auto_model_module,
model_type=hf_config.model_type,
**routing,
device_map=device_map,
**model_kwargs2,
)
model.eval()
if has_pack_quantized_config(hf_config):
_unpack_compressed_linear_weights(model, ckpt_path)
# If device_map was disabled (None), manually move model to target device
if device_map is None and not on_cpu:
print(f"Moving model to {device} device...")
model = model.to(device)
if torch.device(device).type == "cuda" and not is_model_on_gpu(model):
print("Warning: Some parameters are not on a GPU. Calibration can be slow or hit OOM")
return model
def is_model_on_gpu(model) -> bool:
"""Returns if the model is fully loaded on GPUs."""
return all("cuda" in str(param.device) for param in model.parameters())
def generate_excludes_prompt(model) -> bool:
"""Return whether ``model.generate()`` returns only the decoder sequence, without the prompt.
True for encoder-decoder models, so ``hf_ptq.py`` decodes their preview output whole instead
of slicing off a prompt-length prefix. A model whose spec says ``generate()`` includes the
prompt, though it is structurally encoder-decoder, is excluded (AR-style decode applies).
"""
config = model.config
includes_prompt = get_ptq_spec(hf_model_type(config)).generate_includes_prompt
return bool(getattr(config, "is_encoder_decoder", False)) and includes_prompt is None
def save_source_config(args, export_path) -> None:
"""Copy the source model's config to the export path, for VLMs the exporters skip."""
print(f"Saving original model config to {export_path}")
config_kwargs = {"trust_remote_code": args.trust_remote_code}
if args.attn_implementation is not None:
config_kwargs["attn_implementation"] = args.attn_implementation
AutoConfig.from_pretrained(args.local_checkpoint_path, **config_kwargs).save_pretrained(
export_path
)
def _prepare_quant_cfg(
args: argparse.Namespace, quant_cfg: dict[str, Any], full_model: torch.nn.Module
) -> dict[str, Any]:
"""Apply shared checkpoint-local adjustments to a PTQ configuration."""
# Resolve the real export directory before resolve_checkpoint_dir hashes the config; otherwise
# distinct --export_path values containing the placeholder would share one checkpoint path.
if args.layerwise_export:
assert_layerwise_export_compatible(args, full_model, quant_cfg.get("algorithm"))
quant_cfg = set_layerwise_export_dir(quant_cfg, args.export_path)
print(f"Layerwise export enabled: writing quantized shards to {args.export_path}")
# Shards are resumable only while the manifest naming their resume point remains beside