-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathmodel.py
More file actions
1910 lines (1581 loc) · 72.9 KB
/
model.py
File metadata and controls
1910 lines (1581 loc) · 72.9 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 (c) 2025 Intel Corporation
#
# 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 collections
import inspect
import json
import os
import re
from collections import UserDict
from pathlib import Path
from typing import Union
import psutil
import torch
import transformers
from packaging import version
from auto_round import envs
from auto_round.export.export_to_gguf.config import ModelType
from auto_round.logger import logger
from auto_round.schemes import QuantizationScheme
from auto_round.utils.weight_handler import (
_dequant_fp8_linear_weight,
check_and_mark_quantized_module,
convert_module_to_hp_if_necessary,
is_quantized_input_module,
)
FIX_MISTRAL_REGEX_MODEL_TYPE_LIST = ["longcat_next"]
def clean_module_parameter(submodule: torch.nn.Module, param_name: str) -> None:
"""This function is recommended to be used instead of module.weight = None.
For models like `tie_word_embeddings`, setting the embedding weight to None
causes `lm_head` to reallocate memory for its weight instead of treating it as a "bound shared weight,"
it's now iterated over as an independent parameter,
resulting in an additional `lm_head` parameter in `named_parameters`.
Args:
submodule (torch.nn.Module): submodule to clean
param_name (str): "weight" or "bias"
"""
if submodule is None:
return
is_buffer = param_name in submodule._buffers
with torch.no_grad():
if is_buffer:
buf = submodule._buffers[param_name]
if buf is not None:
buf.data = torch.empty(0, dtype=buf.dtype, device=buf.device)
buf.requires_grad = False
else:
param = submodule._parameters[param_name]
if param is not None:
param.data = torch.empty(0, dtype=param.dtype, device=param.device)
param.requires_grad = False
def convert_dtype_str2torch(str_dtype):
"""Converts a string dtype to its corresponding PyTorch dtype.
Args:
str_dtype (str): The string representation of the dtype.
Returns:
torch.dtype: The PyTorch dtype.
Raises:
ValueError: If the input str_dtype is unsupported.
"""
if isinstance(str_dtype, torch.dtype) or str_dtype is None:
return str_dtype
if str_dtype == "int8":
return torch.int8
elif str_dtype == "fp32" or str_dtype == "float32" or str_dtype == "auto":
return torch.float
elif str_dtype == "fp16" or str_dtype == "float16":
return torch.float16
elif str_dtype == "bf16" or str_dtype == "bfloat16":
return torch.bfloat16
else:
raise ValueError(f"Unsupported string dtype '{str_dtype}' for conversion to torch dtype.")
def convert_dtype_torch2str(dtype):
"""Converts a PyTorch dtype to its corresponding string representation.
Args:
dtype: PyTorch dtype or str. The dtype to convert.
Returns:
str: The string representation of the dtype.
Raises:
ValueError: If the input dtype is unsupported.
"""
if isinstance(dtype, str) or dtype is None:
return dtype
if dtype == torch.int8:
return "int8"
elif dtype == torch.float:
return "fp32"
elif dtype == torch.float16:
return "fp16"
elif dtype == torch.bfloat16:
return "bf16"
elif isinstance(dtype, str) and dtype in ["int8", "fp32", "fp16", "bf16"]:
return dtype
else:
raise ValueError(f"Unsupported PyTorch dtype '{dtype}' for conversion to string dtype.")
def convert_dtype_torch2str_hf(dtype):
"""Converts a PyTorch dtype to its corresponding huggingface string dtype, e.g. torch.float32 -> 'float32'.
Args:
dtype: PyTorch dtype or str. The dtype to convert.
Returns:
str: The string representation of the dtype.
Raises:
ValueError: If the input str_dtype is unsupported.
"""
if dtype is None:
return dtype
if isinstance(dtype, str):
if "float" not in dtype and "int" not in dtype:
dtype = convert_dtype_str2torch(dtype)
else:
return dtype
str_dtype = str(dtype)
if "." not in str_dtype:
raise ValueError(f"Unsupported pytorch dtype '{dtype}' for conversion to huggingface str dtype")
str_dtype = str_dtype.split(".")[1]
return str_dtype
def check_diffusers_installed(): # pragma: no cover
try:
import diffusers # noqa: F401
return True
except ImportError:
logger.error("Please install diffusers via 'pip install diffusers'" " to run diffusion model")
exit(-1)
def check_start_with_block_name(name: str, block_name_to_quantize: list):
"""
Checks if the given layer name starts with any of the block names to be quantized.
Args:
name (str): The name of the layer.
block_name_to_quantize (list): A list of block names to check against.
Returns:
bool: True if the layer name starts with any of the block names, False otherwise.
"""
for block_name in block_name_to_quantize:
if name.startswith(block_name):
return True
return False
def download_or_get_path(repo_id: str, platform: str = None) -> str:
from auto_round import envs
if platform is None:
if envs.AR_USE_MODELSCOPE:
platform = "model_scope"
else:
platform = "hf"
if platform == "model_scope":
return download_modelscope_model(repo_id)
else:
return download_hf_model(repo_id)
def download_modelscope_model(repo_id: str, local_dir: str = None, cache_dir: str = None):
from modelscope.utils.file_utils import get_modelscope_cache_dir # pylint: disable=E0401
system_cache = cache_dir if cache_dir is not None else get_modelscope_cache_dir()
if local_dir:
directory = os.path.abspath(local_dir)
elif cache_dir:
directory = os.path.join(system_cache, *repo_id.split("/"))
else:
directory = os.path.join(system_cache, "models", *repo_id.split("/"))
if os.path.exists(directory):
return directory
else:
from modelscope.hub.snapshot_download import snapshot_download # pylint: disable=E0401
return snapshot_download(repo_id)
def download_hf_model(repo_id, cache_dir=None, repo_type=None, revision=None):
"""Download hugging face model from hf hub."""
from huggingface_hub.constants import DEFAULT_REVISION, HUGGINGFACE_HUB_CACHE
from huggingface_hub.file_download import REGEX_COMMIT_HASH, repo_folder_name
if cache_dir is None:
cache_dir = HUGGINGFACE_HUB_CACHE
if revision is None:
revision = DEFAULT_REVISION
if repo_type is None:
repo_type = "model"
storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
commit_hash = None
if REGEX_COMMIT_HASH.match(revision):
commit_hash = revision
else:
ref_path = os.path.join(storage_folder, "refs", revision)
if os.path.exists(ref_path):
with open(ref_path) as f:
commit_hash = f.read()
if storage_folder and commit_hash:
pointer_path = os.path.join(storage_folder, "snapshots", commit_hash)
if os.path.isdir(pointer_path):
return pointer_path
else: # pragma: no cover
from huggingface_hub import snapshot_download
model_path = snapshot_download(repo_id)
return model_path
def _check_accelerate_version():
from auto_round.utils.common import get_library_version
accelerate_version = get_library_version("accelerate")
from packaging.version import Version
if Version(accelerate_version) > Version("1.5.1") and Version(accelerate_version) < Version("1.10.0"):
logger.warning(
f"Detected accelerate version {accelerate_version}. "
"Versions between 1.5.1 and 1.10.0 may cause high RAM usage during model loading. "
"It is recommended to upgrade to version 1.10.0 or above."
)
_MXFP4_SUPPORTED_MODEL_TYPES = {"gpt_oss"}
def _is_mxfp4_model(model_path, trust_remote_code=True):
"""Check if a model is an MXFP4 quantized model supported for direct loading.
Only checks when transformers >= 5.0.0. Returns False immediately for older versions,
adding zero overhead to non-MXFP4 model loading.
"""
from transformers import AutoConfig
try: # in case of config loading failure for new models
config = AutoConfig.from_pretrained(model_path, trust_remote_code=trust_remote_code)
except:
return False
model_type = getattr(config, "model_type", "")
if model_type not in _MXFP4_SUPPORTED_MODEL_TYPES:
return False
quant_config = getattr(config, "quantization_config", None)
if quant_config is None:
return False
quant_method = (
quant_config.get("quant_method", "")
if isinstance(quant_config, dict)
else getattr(quant_config, "quant_method", "")
)
return quant_method == "mxfp4" and model_type in _MXFP4_SUPPORTED_MODEL_TYPES
def llm_load_model(
pretrained_model_name_or_path: str,
platform: str = "hf",
trust_remote_code: bool = True,
model_dtype: str = None,
device: str = "cpu",
**kwargs,
):
assert platform.lower() in [
"hf",
"model_scope",
], "current only support hf or model_scope platform to load pretrained model."
if platform.lower() == "model_scope" and not envs.AR_USE_MODELSCOPE:
envs.set_config(AR_USE_MODELSCOPE=True)
_check_accelerate_version()
if platform == "model_scope":
from modelscope import AutoModel, AutoModelForCausalLM, AutoTokenizer # pylint: disable=E0401
else:
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
from auto_round.utils.device import (
_use_hpu_compile_mode,
fake_cuda_for_hpu,
fake_triton_for_hpu,
get_device_and_parallelism,
is_hpex_available,
override_cuda_device_capability,
)
device_str, use_auto_mapping = get_device_and_parallelism(device)
torch_dtype = "auto"
if device_str is not None and "hpu" in device_str:
torch_dtype = torch.bfloat16
load_kwargs = {
"torch_dtype": torch_dtype,
"trust_remote_code": trust_remote_code,
"device_map": "auto" if use_auto_mapping else None,
}
if version.parse(transformers.__version__) >= version.parse("5.0.0"):
is_mxfp4 = _is_mxfp4_model(pretrained_model_name_or_path, trust_remote_code=trust_remote_code)
if is_mxfp4:
from transformers import Mxfp4Config
load_kwargs["quantization_config"] = Mxfp4Config(dequantized=True)
logger.info("Detected MXFP4 quantized model, using Mxfp4Config(dequantized=True) for loading.")
is_glm = bool(re.search("chatglm", pretrained_model_name_or_path.lower()))
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, trust_remote_code=trust_remote_code)
model_cls = AutoModel if is_glm else AutoModelForCausalLM
if "deepseek" in pretrained_model_name_or_path.lower() and trust_remote_code:
logger.warning("trust_remote_code is enabled by default, please ensure its correctness.")
if is_hpex_available():
# For loading FP8 model on HPU
with fake_cuda_for_hpu(), fake_triton_for_hpu(), override_cuda_device_capability():
model = model_cls.from_pretrained(pretrained_model_name_or_path, **load_kwargs)
else:
try:
model = model_cls.from_pretrained(pretrained_model_name_or_path, **load_kwargs)
except ValueError as e:
if "FP8 quantized" in str(e):
with override_cuda_device_capability():
model = model_cls.from_pretrained(pretrained_model_name_or_path, **load_kwargs)
logger.warning("the support for fp8 model as input is experimental, please use with caution.")
else:
raise
except OSError as e:
logger.warning(f"fail to load {pretrained_model_name_or_path}, set trust_remote_code to False and retry.")
model = model_cls.from_pretrained(
pretrained_model_name_or_path, **{**load_kwargs, "trust_remote_code": False}
)
model = model.eval()
check_and_mark_quantized_module(model)
handle_generation_config(model)
model = _to_model_dtype(model, model_dtype)
return model, tokenizer
def _find_pipeline_model_subfolder(model_dir_or_repo: str, file_list: list = None) -> tuple:
"""Find model/processor subfolders from a pipeline's model_index.json.
Works for both local directories and remote HF repos.
Args:
model_dir_or_repo: Local directory path or HF repo id.
file_list: If provided, treat *model_dir_or_repo* as a remote HF repo
and use *file_list* (from ``list_repo_files``) to check file existence.
If ``None``, treat it as a local directory.
Returns:
(model_subfolder, processor_subfolder, config_dict)
"""
is_local = file_list is None
if is_local:
index_path = os.path.join(model_dir_or_repo, "model_index.json")
if not os.path.exists(index_path):
raise FileNotFoundError(f"No config.json or model_index.json found under {model_dir_or_repo}")
else:
from huggingface_hub import hf_hub_download
index_path = hf_hub_download(model_dir_or_repo, "model_index.json")
with open(index_path, "r", encoding="utf-8") as f:
model_index = json.load(f)
processor_subfolder = None
for name, value in model_index.items():
if name == "processor" and isinstance(value, list):
processor_subfolder = "processor"
break
candidates = []
for name, value in model_index.items():
if name.startswith("_") or not isinstance(value, list) or len(value) < 2:
continue
# Load component config.json
if is_local:
cfg_path = os.path.join(model_dir_or_repo, name, "config.json")
if not os.path.isfile(cfg_path):
continue
with open(cfg_path, "r", encoding="utf-8") as f:
comp_config = json.load(f)
else:
comp_config_file = f"{name}/config.json"
if comp_config_file not in file_list:
continue
cfg_path = hf_hub_download(model_dir_or_repo, comp_config_file)
with open(cfg_path, "r", encoding="utf-8") as f:
comp_config = json.load(f)
if "architectures" in comp_config:
candidates.append((name, comp_config))
if not candidates:
raise FileNotFoundError(
f"model_index.json found in {model_dir_or_repo} but no component with 'architectures' in its config.json"
)
for name, comp_config in candidates:
arch = comp_config["architectures"][0]
if "CausalLM" in arch or "ConditionalGeneration" in arch:
return name, processor_subfolder, comp_config
return candidates[0][0], processor_subfolder, candidates[0][1]
def mllm_load_model(
pretrained_model_name_or_path: str,
platform: str = "hf",
device: str = "cpu",
torch_dtype: str = "auto",
use_auto_mapping: bool = True,
trust_remote_code: bool = True,
model_dtype: str = None,
**kwargs,
):
from auto_round.special_model_handler import MISTRAL_3_2_MODELS
_check_accelerate_version()
assert platform.lower() in [
"hf",
"model_scope",
], "current only support hf or model_scope platform to load pretrained model."
if platform.lower() == "model_scope" and not envs.AR_USE_MODELSCOPE:
envs.set_config(AR_USE_MODELSCOPE=True)
if platform == "model_scope":
import modelscope # pylint: disable=E0401
from modelscope import AutoModel, AutoModelForCausalLM, AutoProcessor, AutoTokenizer # pylint: disable=E0401
base_lib = modelscope
else:
import transformers
from transformers import AutoModel, AutoModelForCausalLM, AutoProcessor, AutoTokenizer
base_lib = transformers
from auto_round.utils.device import get_device_and_parallelism, override_cuda_device_capability
device_str, use_auto_mapping = get_device_and_parallelism(device)
torch_dtype = "auto"
if device_str is not None and "hpu" in device_str:
torch_dtype = torch.bfloat16
model_subfolder = None
processor_subfolder = None
if os.path.isdir(pretrained_model_name_or_path):
config_path = os.path.join(pretrained_model_name_or_path, "config.json")
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
else:
model_subfolder, processor_subfolder, config = _find_pipeline_model_subfolder(pretrained_model_name_or_path)
else:
from huggingface_hub import hf_hub_download, list_repo_files
file_list = list_repo_files(pretrained_model_name_or_path)
if "config.json" in file_list:
config_path = hf_hub_download(pretrained_model_name_or_path, "config.json")
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
elif "model_index.json" in file_list:
model_subfolder, processor_subfolder, config = _find_pipeline_model_subfolder(
pretrained_model_name_or_path, file_list
)
elif "config.json.gz" in file_list:
# Load gzipped JSON
import gzip
config_path = hf_hub_download(pretrained_model_name_or_path, "config.json.gz")
with gzip.open(config_path, "rt", encoding="utf-8") as f:
config = json.load(f)
else:
raise FileNotFoundError(f"No config.json or config.json.gz found for {pretrained_model_name_or_path}")
if "model_type" in config:
model_type = config["model_type"]
else:
model_type = None
if model_type == "qwen2_5_omni":
if version.parse(transformers.__version__) < version.parse("4.52.0"):
raise RuntimeError(
f"Qwen2.5-Omni requires transformers >= 4.52.0, but found {transformers.__version__}. "
"Please upgrade: pip install transformers>=4.52.0"
)
if model_type == "qwen3_omni_moe":
if version.parse(transformers.__version__) < version.parse("5.1.0"):
raise RuntimeError(
f"Qwen3-Omni requires transformers >= 5.1.0, but found {transformers.__version__}. "
"Please upgrade: pip install transformers>=5.1.0"
)
processor, image_processor = None, None
if "deepseek_vl_v2" == model_type:
from deepseek_vl2.models import DeepseekVLV2ForCausalLM, DeepseekVLV2Processor # pylint: disable=E0401
processor = DeepseekVLV2Processor.from_pretrained(pretrained_model_name_or_path)
tokenizer = processor.tokenizer
model: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
torch_dtype=torch_dtype,
device_map="auto" if use_auto_mapping else None,
)
else:
architectures = config["architectures"][0]
if architectures == "LlavaLlamaForCausalLM":
from llava.model.builder import load_pretrained_model # pylint: disable=E0401
tokenizer, model, image_processor, _ = load_pretrained_model(
pretrained_model_name_or_path,
model_base=None,
model_name=pretrained_model_name_or_path,
torch_dtype=torch_dtype,
)
else:
if architectures.endswith("Model") and hasattr(
base_lib, n := architectures.replace("Model", "ForConditionalGeneration")
):
cls = getattr(base_lib, n)
elif hasattr(base_lib, architectures):
cls = getattr(base_lib, architectures)
else:
cls = AutoModelForCausalLM
try:
model_load_kwargs = {}
if model_subfolder is not None:
model_load_kwargs["subfolder"] = model_subfolder
model = cls.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
torch_dtype=torch_dtype,
device_map="auto" if use_auto_mapping else None,
**model_load_kwargs,
)
except ValueError as e:
if "FP8 quantized" in str(e):
with override_cuda_device_capability():
model_load_kwargs = {}
if model_subfolder is not None:
model_load_kwargs["subfolder"] = model_subfolder
model = cls.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
torch_dtype=torch_dtype,
device_map="auto" if use_auto_mapping else None,
**model_load_kwargs,
)
logger.warning("the support for fp8 model as input is experimental, please use with caution.")
else:
raise
if any([name in model.name_or_path for name in MISTRAL_3_2_MODELS]):
from mistral_common.tokens.tokenizers.mistral import MistralTokenizer # pylint: disable=E0401
if os.path.isdir(pretrained_model_name_or_path):
tokenizer = MistralTokenizer.from_file(os.path.join(pretrained_model_name_or_path, "tekken.json"))
else:
tokenizer = MistralTokenizer.from_hf_hub(pretrained_model_name_or_path)
else:
processor_load_kwargs = {}
if processor_subfolder is not None:
processor_load_kwargs["subfolder"] = processor_subfolder
tokenizer = AutoTokenizer.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
fix_mistral_regex=True if model_type in FIX_MISTRAL_REGEX_MODEL_TYPE_LIST else False,
**processor_load_kwargs,
)
processor = AutoProcessor.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
**processor_load_kwargs,
)
try:
if platform == "model_scope":
from modelscope import AutoImageProcessor # pylint: disable=E0401
else:
from transformers import AutoImageProcessor
image_processor_load_kwargs = {}
if processor_subfolder is not None:
image_processor_load_kwargs["subfolder"] = processor_subfolder
image_processor = AutoImageProcessor.from_pretrained(
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
**image_processor_load_kwargs,
)
except Exception as e:
pass
if model_type == "glm_image" and image_processor is not None:
from transformers.models.glm_image.processing_glm_image import GlmImageProcessor
processor = GlmImageProcessor(image_processor=image_processor, tokenizer=tokenizer)
model = model.eval()
check_and_mark_quantized_module(model)
handle_generation_config(model)
model = _to_model_dtype(model, model_dtype)
if model_subfolder is not None:
model._autoround_pipeline_subfolder = model_subfolder
return model, processor, tokenizer, image_processor
def diffusion_load_model(
pretrained_model_name_or_path: str,
platform: str = "hf",
device: Union[str, torch.device] = "cpu",
torch_dtype: Union[str, torch.dtype] = "auto",
use_auto_mapping: bool = False,
trust_remote_code: bool = True,
model_dtype: str = None,
**kwargs,
):
from functools import partial
from auto_round.utils.common import LazyImport
from auto_round.utils.device import get_device_and_parallelism
_check_accelerate_version()
if platform != "hf":
raise NotImplementedError(
f"auto_round current only support hf as platform for diffusion model, but get {platform}"
)
device_str, use_auto_mapping = get_device_and_parallelism(device)
torch_dtype = "auto"
if device_str is not None and "hpu" in device_str:
torch_dtype = torch.bfloat16
pipelines = LazyImport("diffusers.pipelines")
if isinstance(pretrained_model_name_or_path, str):
if torch_dtype == "auto":
torch_dtype = {}
model_index = os.path.join(pretrained_model_name_or_path, "model_index.json")
with open(model_index, "r", encoding="utf-8") as file:
config = json.load(file)
for k, v in config.items():
component_folder = os.path.join(pretrained_model_name_or_path, k)
if isinstance(v, list) and os.path.exists(os.path.join(component_folder, "config.json")):
component_folder = os.path.join(pretrained_model_name_or_path, k)
with open(os.path.join(component_folder, "config.json"), "r", encoding="utf-8") as file:
component_config = json.load(file)
torch_dtype[k] = component_config.get("torch_dtype", "auto")
pipe = pipelines.auto_pipeline.AutoPipelineForText2Image.from_pretrained(
pretrained_model_name_or_path, torch_dtype=torch_dtype
)
pipe_config = pipe.load_config(pretrained_model_name_or_path)
elif isinstance(pretrained_model_name_or_path, pipelines.pipeline_utils.DiffusionPipeline):
pipe = pretrained_model_name_or_path
pipe_config = pipe.load_config(pipe.config["_name_or_path"])
else:
raise ValueError(
f"Only support str or DiffusionPipeline class for model, but get {type(pretrained_model_name_or_path)}"
)
# add missing key
for k, v in pipe_config.items():
if k not in pipe.config:
pipe.config[k] = v
pipe = _to_model_dtype(pipe, model_dtype)
model = pipe.transformer
def config_save_pretrained(config, file_name, save_directory):
if os.path.isfile(save_directory):
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
os.makedirs(save_directory, exist_ok=True)
output_config_file = os.path.join(save_directory, file_name)
config_dict = dict(config)
if file_name == "config.json" and hasattr(model.config, "quantization_config"):
config_dict["quantization_config"] = model.config.quantization_config
with open(output_config_file, "w", encoding="utf-8") as writer:
writer.write(json.dumps(config_dict, indent=2, sort_keys=True) + "\n")
# meta model uses model.config.save_pretrained for config saving
setattr(model.config, "save_pretrained", partial(config_save_pretrained, model.config, "config.json"))
setattr(pipe.config, "save_pretrained", partial(config_save_pretrained, pipe.config, "model_index.json"))
def model_save_pretrained(model, save_directory, **kwargs):
super(model.__class__, model).save_pretrained(save_directory, **kwargs)
if hasattr(model.config, "quantization_config"):
model.config["quantization_config"] = model.config.quantization_config
with open(os.path.join(save_directory, "config.json"), "w", encoding="utf-8") as writer:
writer.write(json.dumps(dict(model.config), indent=2, sort_keys=True) + "\n")
# non-meta model uses model.save_pretrained for model and config saving
setattr(model, "save_pretrained", partial(model_save_pretrained, model))
return pipe, model.to(device)
def is_pure_text_model(model):
"""verify on: phi-3.5, Mistral-Small-3.1, gemma-3, qwen2-vl,"""
if hasattr(model, "config") and hasattr(model.config, "vision_config"):
return False
if hasattr(model.__class__, "main_input_name") and model.__class__.main_input_name != "input_ids":
return False
for module in model.modules():
if hasattr(module.__class__, "main_input_name") and module.__class__.main_input_name != "input_ids":
return False
if "vision" in str(module.__class__).lower():
return False
if "image" in str(module.__class__).lower():
return False
if "img" in str(module.__class__).lower():
return False
return True
def is_mllm_model(model_or_path: Union[str, torch.nn.Module], platform: str = None):
from auto_round.utils.common import MM_KEYS
model_path = model_or_path if isinstance(model_or_path, str) else model_or_path.name_or_path
# For dummy model, model_path could be "".
if model_path and not os.path.isdir(model_path):
model_path = download_or_get_path(model_path, platform=platform)
if isinstance(model_path, str):
if os.path.exists(os.path.join(model_path, "preprocessor_config.json")):
return True
if os.path.exists(os.path.join(model_path, "processor_config.json")):
return True
if os.path.exists(os.path.join(model_path, "config.json")):
with open(os.path.join(model_path, "config.json")) as f:
config = json.load(f)
for key in config.keys():
if any([k in key for k in MM_KEYS]):
return True
if isinstance(model_or_path, torch.nn.Module):
for name, module in model_or_path.named_modules():
if any([k in name for k in MM_KEYS]):
return True
return False
def is_gguf_model(model_path: Union[str, torch.nn.Module]) -> bool:
is_gguf_file = False
if isinstance(model_path, str):
if os.path.isfile(model_path) and model_path.endswith(".gguf"):
is_gguf_file = True
elif os.path.exists(model_path):
for file in os.listdir(model_path):
if file.endswith(".gguf"):
is_gguf_file = True
break
return is_gguf_file
def is_diffusion_model(model_or_path: Union[str, object]) -> bool:
from auto_round.utils.common import LazyImport
if isinstance(model_or_path, str):
index_file = None
if not os.path.isdir(model_or_path):
try:
from huggingface_hub import hf_hub_download
index_file = hf_hub_download(model_or_path, "model_index.json")
check_diffusers_installed()
except Exception as e:
print(e)
index_file = None
elif os.path.exists(os.path.join(model_or_path, "model_index.json")):
check_diffusers_installed()
index_file = os.path.join(model_or_path, "model_index.json")
return index_file is not None
elif not isinstance(model_or_path, torch.nn.Module):
check_diffusers_installed()
pipeline_utils = LazyImport("diffusers.pipelines.pipeline_utils")
return isinstance(model_or_path, pipeline_utils.DiffusionPipeline)
else:
return False
def is_moe_layer(module: torch.nn.Module) -> bool:
"""Returns whether the module is an MOE layer."""
return "moe" in type(module).__name__.lower() or any(
key in type(module).__name__.lower()
for key in [
"MixtralSparseMoeBlock".lower(),
"ArcticMoE".lower(),
"DbrxFFN".lower(),
"MoELayer".lower(),
"PhimoeSparseMoeBlock".lower(),
"DeepseekMoE".lower(),
"DeepseekV2MoE".lower(),
"DeepseekV3MoE".lower(),
"Qwen2MoeSparseMoeBlock".lower(),
"Qwen3MoeSparseMoeBlock".lower(),
"Qwen3VLMoeTextSparseMoeBlock".lower(),
"Qwen3OmniMoeThinkerTextSparseMoeBlock".lower(),
"Qwen3OmniMoeTalkerTextSparseMoeBlock".lower(),
]
)
def get_block_names(model, quant_vision=False):
"""Get the block names for transformers-like networks.
Args:
model: The model.
Returns:
block_names: A list whose elements are list of block's layer names
"""
from auto_round.special_model_handler import SPECIAL_MULTIMODAL_BLOCK
def _search_block(name, module):
if hasattr(type(module), "__name__") and "ModuleList" in type(module).__name__:
return [(name, module)]
target_modules = []
for n, m in module.named_children():
if hasattr(type(m), "__name__") and "NgramEmbedding" in type(m).__name__:
continue
if hasattr(type(m), "__name__") and "ModuleList" in type(m).__name__:
target_modules.append((".".join(filter(None, (name, n))), m))
else:
target_modules.extend(_search_block(".".join(filter(None, (name, n))), m))
return target_modules
def _get_llm_block_names(model):
block_names = []
target_modules = _search_block("", model)
for i, target_m in enumerate(target_modules):
block_names.append([])
for n, m in target_m[1].named_children():
block_names[i].append(target_m[0] + "." + n)
return block_names
def _get_vlm_block_names(model, quant_vision=False, ignore_audio=True):
# Since calibration dataset doesn't contain audio data, audio-related blocks will be ignored by default.
if (
hasattr(model, "config")
and hasattr(model.config, "model_type")
and model.config.model_type in SPECIAL_MULTIMODAL_BLOCK.keys()
):
return SPECIAL_MULTIMODAL_BLOCK.get(model.config.model_type)(model, quant_vision=quant_vision)
block_names = []
target_modules = []
vision_blocks_tuple = ("vision", "visual", "image", "img")
audio_blocks_tuple = ("audio", "speech", "wav", "waveform")
target_modules = _search_block("", model)
for i, target_m in enumerate(target_modules):
if quant_vision or all(key not in target_m[0].lower() for key in (vision_blocks_tuple)):
if ignore_audio and any(key in target_m[0].lower() for key in audio_blocks_tuple):
continue
block_names.append([])
for n, m in target_m[1].named_children():
block_names[-1].append(target_m[0] + "." + n)
return block_names
if quant_vision or not is_pure_text_model(model):
return _get_vlm_block_names(model, quant_vision=quant_vision)
else:
return _get_llm_block_names(model)
def get_lm_head_name(model):
block_names = get_block_names(model, True)
last_name = None
for n, m in model.named_modules():
if any(m.children()):
continue
last_name = n
for l in block_names:
if last_name in l:
last_name = None
break
return last_name
# please refer to https://github.com/NVIDIA/TensorRT-Model-Optimizer
# /blob/4c611e47a60084a86e1de7e48690a692a1b8170c/modelopt/torch/export/layer_utils.py#L976
def get_expert_linear_names(module: torch.nn.Module) -> list[str]:
"""Get the list of linear names for the experts."""
def module_match_name_list(module, name_list):
"""Check if the module name matches any of the names in the list.
e.g. module_match_name_list(QuantQwen3MoeSparseMoeBlock, ['Qwen3MoeSparseMoeBlock']) -> True
"""
return any(name.lower() in type(module).__name__.lower() for name in name_list)
if module_match_name_list(
module,
[
"Qwen2MoeSparseMoeBlock",
"Qwen3MoeSparseMoeBlock",
"DeepseekMoE",
"DeepseekV2MoE",
"DeepseekV3MoE",
"Qwen3VLMoeTextSparseMoeBlock",
"Qwen3OmniMoeThinkerTextSparseMoeBlock",
"Qwen3OmniMoeTalkerTextSparseMoeBlock",
],
):
return ["gate_proj", "down_proj", "up_proj"]
elif module_match_name_list(module, ["MixtralMoeSparseMoeBlock"]):
return ["linear_fc1", "linear_fc2"]
elif module_match_name_list(module, ["DBRXMoeSparseMoeBlock"]):
return ["w1_linear", "w2_linear", "v1_linear"]
else:
# assuming w1, w2, w3 by default
return ["w1", "w2", "w3"]
def get_expert_input_proj_names(module: torch.nn.Module) -> list[str]:
"""Get the list of input projection names for MoE experts.
Input projections are the first linear layers that receive the expert's input directly.
For FP8 dispatch efficiency, these projections need unified input scales across all experts.
Args:
module: The MoE module (e.g., SparseMoeBlock)
Returns:
List of input projection names (e.g., ['gate_proj', 'up_proj'])
"""
def module_match_name_list(module, name_list):
"""Check if the module name matches any of the names in the list."""
return any(name.lower() in type(module).__name__.lower() for name in name_list)
if module_match_name_list(
module,
[
"Qwen2MoeSparseMoeBlock",
"Qwen3MoeSparseMoeBlock",
"Qwen3VLMoeTextSparseMoeBlock",
"Qwen3OmniMoeThinkerTextSparseMoeBlock",
"Qwen3OmniMoeTalkerTextSparseMoeBlock",
"DeepseekMoE",
"DeepseekV2MoE",
"DeepseekV3MoE",
],
):
# gate_proj and up_proj are input projections, down_proj is output
return ["gate_proj", "up_proj"]
elif module_match_name_list(module, ["MixtralMoeSparseMoeBlock"]):
# Mixtral uses linear_fc1 as input projection, linear_fc2 is output
return ["linear_fc1"]
elif module_match_name_list(module, ["DBRXMoeSparseMoeBlock"]):
# w1_linear and v1_linear are input projections, w2_linear is output
return ["w1_linear", "v1_linear"]
else:
logger.warning_once("Using default input projection names ['w1', 'w3'] for MoE expert alignment. ")
# Default: w1 and w3 are input projections, w2 is output
return ["w1", "w3"]