-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Expand file tree
/
Copy pathsave.py
More file actions
5959 lines (5311 loc) · 236 KB
/
Copy pathsave.py
File metadata and controls
5959 lines (5311 loc) · 236 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 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
#
# 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.
from unsloth_zoo.utils import Version
from importlib.metadata import version as importlib_version
from unsloth_zoo.hf_utils import dtype_from_config, HAS_TORCH_DTYPE
from unsloth_zoo.llama_cpp import (
convert_to_gguf,
quantize_gguf,
use_local_gguf,
install_llama_cpp,
check_llama_cpp,
_download_convert_hf_to_gguf,
)
# H4: Defensive imports -- these were added in unsloth-zoo PR #526
# and may not exist on older versions
try:
from unsloth_zoo.llama_cpp import LLAMA_CPP_DEFAULT_DIR, IS_WINDOWS
except ImportError:
import sys
IS_WINDOWS = sys.platform == "win32"
LLAMA_CPP_DEFAULT_DIR = "llama.cpp"
# Without bnb, peft stops exporting its 4bit LoRA layer too. Both names only feed
# isinstance checks, so placeholders nothing can match are exact stand-ins.
try:
from bitsandbytes.nn import Linear4bit as Bnb_Linear4bit
from peft.tuners.lora import Linear4bit as Peft_Linear4bit
except Exception:
class Bnb_Linear4bit:
pass
class Peft_Linear4bit:
pass
from peft.tuners.lora import Linear as Peft_Linear
from typing import Optional, Callable, Union, List
import sys
import requests
import torch
import os
import json
import shutil
import pickle
import gc
import functools
from transformers.models.llama.modeling_llama import logger
from .kernels import fast_dequantize, QUANT_STATE, get_lora_parameters_bias
import subprocess
import traceback
import psutil
import re
from transformers.models.llama.modeling_llama import logger
from .models.loader_utils import (
get_model_name,
_resolve_hub_repo_cached_file,
_tokenizer_cache_dir,
_tokenizer_revision,
_tokenizer_wants_local_only,
)
from .models._utils import _convert_torchao_model
from .ollama_template_mappers import OLLAMA_TEMPLATES, MODEL_TO_OLLAMA_TEMPLATE_MAPPER
from transformers import ProcessorMixin, PreTrainedTokenizerBase
from huggingface_hub import HfApi
try:
from huggingface_hub import get_token
except:
try:
from huggingface_hub.utils import get_token
except:
# For older versions of huggingface_hub
from huggingface_hub.utils._token import get_token
from pathlib import Path
from peft import PeftModelForCausalLM, PeftModel
__all__ = [
"print_quantization_methods",
"unsloth_save_model",
"save_to_gguf",
"patch_saving_functions",
"create_huggingface_repo",
]
# llama.cpp specific targets - all takes 90s. Below takes 60s
LLAMA_CPP_TARGETS = [
"llama-quantize",
"llama-cli",
"llama-server",
]
# Check environments
keynames = "\n" + "\n".join(os.environ.keys())
IS_COLAB_ENVIRONMENT = "\nCOLAB_" in keynames
IS_KAGGLE_ENVIRONMENT = "\nKAGGLE_" in keynames
KAGGLE_TMP = "/tmp"
del keynames
# Weights
LLAMA_WEIGHTS = (
"self_attn.q_proj",
"self_attn.k_proj",
"self_attn.v_proj",
"self_attn.o_proj",
"mlp.gate_proj",
"mlp.up_proj",
"mlp.down_proj",
)
LLAMA_LAYERNORMS = (
"input_layernorm",
"post_attention_layernorm",
"pre_feedforward_layernorm",
"post_feedforward_layernorm",
"self_attn.q_norm",
"self_attn.k_norm",
)
# https://github.com/ggerganov/llama.cpp/blob/master/examples/quantize/quantize.cpp#L19
# From https://mlabonne.github.io/blog/posts/Quantize_Llama_2_models_using_ggml.html
ALLOWED_QUANTS = {
"not_quantized": "Recommended. Fast conversion. Slow inference, big files.",
"fast_quantized": "Recommended. Fast conversion. OK inference, OK file size.",
"quantized": "Recommended. Slow conversion. Fast inference, small files.",
"f32": "Not recommended. Retains 100% accuracy, but super slow and memory hungry.",
"bf16": "Bfloat16 - Fastest conversion + retains 100% accuracy. Slow and memory hungry.",
"f16": "Float16 - Fastest conversion + retains 100% accuracy. Slow and memory hungry.",
"q8_0": "Fast conversion. High resource use, but generally acceptable.",
"q4_k_m": "Recommended. Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q4_K",
"q5_k_m": "Recommended. Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q5_K",
"q2_k": "Uses Q4_K for the attention.vw and feed_forward.w2 tensors, Q2_K for the other tensors.",
"q2_k_l": "Q2_K_L with q8_0 output/token embeddings for higher quality than plain Q2_K.",
"q3_k_l": "Uses Q5_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K",
"q3_k_m": "Uses Q4_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K",
"q3_k_s": "Uses Q3_K for all tensors",
"q4_0": "Original quant method, 4-bit.",
"q4_1": "Higher accuracy than q4_0 but not as high as q5_0. However has quicker inference than q5 models.",
"q4_k_s": "Uses Q4_K for all tensors",
"q4_k": "alias for q4_k_m",
"q5_k": "alias for q5_k_m",
"q5_0": "Higher accuracy, higher resource usage and slower inference.",
"q5_1": "Even higher accuracy, resource usage and slower inference.",
"q5_k_s": "Uses Q5_K for all tensors",
"q6_k": "Uses Q8_K for all tensors",
"q3_k_xs": "3-bit extra small quantization",
}
# IQ (importance-matrix) quants. llama.cpp refuses these without an imatrix, so they are only
# accepted when imatrix_file=... is supplied to save_pretrained_gguf / push_to_hub_gguf.
IMATRIX_QUANTS = {
"iq1_s": "1.56 bpw. Smallest, lowest quality. Needs an imatrix.",
"iq1_m": "1.75 bpw. Very small. Needs an imatrix.",
"iq2_xxs": "2.06 bpw. Needs an imatrix.",
"iq2_xs": "2.31 bpw. Needs an imatrix.",
"iq2_s": "2.5 bpw. Needs an imatrix.",
"iq2_m": "2.7 bpw. Needs an imatrix.",
"iq3_xxs": "3.06 bpw. Needs an imatrix.",
"iq3_s": "3.44 bpw. Needs an imatrix.",
"iq3_m": "3.66 bpw. Needs an imatrix.",
"iq4_nl": "4.5 bpw non-linear. Benefits from an imatrix.",
"iq4_xs": "4.25 bpw. Benefits from an imatrix.",
}
def has_curl():
return shutil.which("curl") is not None
CURL_FLAG = "-DLLAMA_CURL=ON" if has_curl() else "-DLLAMA_CURL=OFF"
# FP8/FP4 compressed export via llm-compressor (for vLLM).
# save_method alias -> (llm-compressor scheme, needs_calibration, output dir suffix).
# alias -> (llm-compressor scheme, needs_calibration, output-dir suffix). needs_calibration is
# True only for schemes with static activation scales (FP8 static, NVFP4); everything else is
# weight-only or dynamic-activation and runs data-free. Unsupported schemes in the installed
# compressed-tensors (e.g. MXFP8 on older stacks) are gated by _scheme_is_available at runtime.
COMPRESSED_EXPORT_SCHEMES = {
# FP8
"fp8": ("FP8_DYNAMIC", False, "fp8"),
"fp8_dynamic": ("FP8_DYNAMIC", False, "fp8"),
"dynamic_fp8": ("FP8_DYNAMIC", False, "fp8"),
"w8a8_fp8": ("FP8_DYNAMIC", False, "fp8"),
"fp8_static": ("FP8", True, "fp8-static"),
"static_fp8": ("FP8", True, "fp8-static"),
"fp8_block": ("FP8_BLOCK", False, "fp8-block"),
"block_fp8": ("FP8_BLOCK", False, "fp8-block"),
# INT8 / INT-weight
"int8": ("INT8", False, "int8"),
"w8a8": ("W8A8", False, "w8a8"),
"w8a8_int8": ("W8A8", False, "w8a8"),
"w8a16": ("W8A16", False, "w8a16"),
"int8_weight": ("W8A16", False, "w8a16"),
"w4a16": ("W4A16", False, "w4a16"),
"int4": ("W4A16", False, "w4a16"),
"int4_weight": ("W4A16", False, "w4a16"),
"w4a16_asym": ("W4A16_ASYM", False, "w4a16-asym"),
"w4a8": ("W4A8", False, "w4a8"),
"w4afp8": ("W4AFP8", False, "w4afp8"),
# MXFP (microscaling)
"mxfp8": ("MXFP8", False, "mxfp8"),
"w8a8_mxfp8": ("MXFP8", False, "mxfp8"),
"mxfp4": ("MXFP4", False, "mxfp4"),
"w4a4_mxfp4": ("MXFP4", False, "mxfp4"),
"mxfp4a16": ("MXFP4A16", False, "mxfp4a16"),
"w4a16_mxfp4": ("MXFP4A16", False, "mxfp4a16"),
# NVFP4
"nvfp4": ("NVFP4", True, "nvfp4"),
"w4a4_nvfp4": ("NVFP4", True, "nvfp4"),
"nvfp4a16": ("NVFP4A16", False, "nvfp4a16"),
"w4a16_nvfp4": ("NVFP4A16", False, "nvfp4a16"),
}
# torchao "portable" quant export: device-agnostic FP8 / INT8, no NVIDIA GPU needed.
# alias -> (kind, sibling suffix). FP8 saves to safetensors, INT8 to .bin; both load in vLLM.
TORCHAO_EXPORT_SCHEMES = {
"torchao_fp8": ("fp8", "torchao-fp8"),
"torchao_int8": ("int8", "torchao-int8"),
"portable_fp8": ("fp8", "torchao-fp8"),
"portable_int8": ("int8", "torchao-int8"),
}
def _normalize_torchao_method(save_method):
"""Return (kind, suffix) if `save_method` is a torchao portable FP8/INT8 export, else None."""
if not isinstance(save_method, str):
return None
key = save_method.lower().strip().replace("-", "_").replace(" ", "_")
return TORCHAO_EXPORT_SCHEMES.get(key)
def _loaded_via_remote_code(obj):
"""True if `obj`'s class comes from downloaded custom code (an auto_map module).
Transformers loads auto_map code into the ``transformers_modules`` package, so a
``transformers_modules`` class proves the original load actually ran that remote code
(which the caller's / Unsloth's consent gate scans at load time). Export paths derive their
reload trust_remote_code from this - the already approved load decision - instead of from a
checkpoint's static ``auto_map``: a model that loads with built-in classes must not have its
unvetted remote code run when it is re-read during quantization export. Walks PEFT / wrapper
layers so a LoRA over a custom-code base is still detected, and processor components so a
custom tokenizer held inside a built-in processor keeps its approved trust.
"""
seen = set()
queue = [obj]
while queue and len(seen) < 16:
node = queue.pop(0)
if node is None or id(node) in seen:
continue
seen.add(id(node))
# __module__ can be None/absent on some dynamically created or C-extension classes;
# treat anything non-string as "not remote code" rather than crashing the export.
module = getattr(type(node), "__module__", None)
if isinstance(module, str) and module.startswith("transformers_modules"):
return True
if hasattr(node, "get_base_model"):
try:
queue.append(node.get_base_model())
except Exception:
pass
# PEFT / trainer wrappers hold the real model in base_model / model; a built-in
# ProcessorMixin holds its (possibly custom-code) components as attributes.
for attr in (
"base_model",
"model",
"tokenizer",
"image_processor",
"feature_extractor",
"video_processor",
):
queue.append(getattr(node, attr, None))
return False
def _normalize_compressed_method(save_method):
"""Return (scheme, needs_calibration, suffix) if `save_method` is an FP8/FP4 compressed
export, else None (so normal lora / merged_16bit / merged_4bit handling proceeds).
Near-miss FP8/FP4 names that are not supported raise a precise error instead of silently
falling through to the generic "unknown save_method" message.
"""
if not isinstance(save_method, str):
return None
key = save_method.lower().strip().replace("-", "_").replace(" ", "_")
# torchao aliases route to the torchao path, so skip them before the "fp8" near-miss check.
if key in TORCHAO_EXPORT_SCHEMES:
return None
if key in COMPRESSED_EXPORT_SCHEMES:
return COMPRESSED_EXPORT_SCHEMES[key]
if any(tag in key for tag in ("fp8", "fp4", "mxfp", "nvfp", "w4a", "w8a", "int4", "int8")):
supported = ", ".join(sorted(COMPRESSED_EXPORT_SCHEMES.keys()))
raise RuntimeError(
f"Unsloth: save_method='{save_method}' is not a supported compressed export.\n"
f"Supported compressed-tensors export methods: {supported}"
)
return None
def _is_cmake_only_llama_cpp(llama_cpp_dir: str = "llama.cpp") -> bool:
"""
True if llama.cpp's Makefile is the post-CMake-migration deprecation stub,
so `make` cannot build it. A genuinely missing/empty checkout returns False
so it isn't treated as CMake-only: the caller then probes make and fails
loudly on a real error rather than silently assuming a CMake build.
"""
makefile_path = os.path.join(llama_cpp_dir, "Makefile")
if not os.path.exists(makefile_path):
# No Makefile: only CMake-only if a real CMake project is present
return os.path.exists(os.path.join(llama_cpp_dir, "CMakeLists.txt"))
try:
with open(makefile_path, "r", encoding = "utf-8", errors = "ignore") as f:
content = f.read(4096).lower()
if "cmake" in content and "deprecated" in content:
return True
if "build system changed" in content:
return True
except (IOError, OSError):
pass
return False
def print_quantization_methods():
for key, value in ALLOWED_QUANTS.items():
print(f'"{key}" ==> {value}')
print("\nIQ low-bit quants (save_pretrained_gguf(..., imatrix_file=True or '...path')):")
for key, value in IMATRIX_QUANTS.items():
print(f'"{key}" ==> {value}')
print("\nCompressed-tensors export (save_pretrained_merged(..., save_method=...), for vLLM):")
seen = set()
for key, (scheme, needs_calib, _suffix) in COMPRESSED_EXPORT_SCHEMES.items():
if scheme in seen:
continue
seen.add(scheme)
note = "needs calibration data" if needs_calib else "data-free"
print(f'"{key}" ==> llm-compressor {scheme} ({note})')
def _quantize_q2_k_l(
input_gguf: Union[str, os.PathLike],
output_gguf: Union[str, os.PathLike],
quantizer_location: Union[str, os.PathLike],
n_threads: int,
print_output: bool = True,
imatrix = None,
):
# "Q2_K_L" is an Unsloth preset, not a native llama.cpp ftype: q2_k with
# output/token-embedding tensors kept at q8_0 for higher precision.
command = [
str(quantizer_location),
*(["--imatrix", str(imatrix)] if imatrix else []),
"--output-tensor-type",
"q8_0",
"--token-embedding-type",
"q8_0",
str(input_gguf),
str(output_gguf),
"q2_k",
str(n_threads),
]
if print_output:
print(
"Unsloth: Quantizing as Q2_K_L preset "
"(q2_k + --output-tensor-type q8_0 --token-embedding-type q8_0)..."
)
try:
if print_output:
with subprocess.Popen(
command,
shell = False,
text = True,
encoding = "utf-8",
errors = "replace",
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
bufsize = 1,
) as sp:
assert sp.stdout is not None
for line in sp.stdout:
print(line, end = "", flush = True)
returncode = sp.wait()
if returncode != 0:
raise RuntimeError(
f"Failed to quantize {input_gguf} to q2_k_l: process exited with code {returncode}"
)
else:
subprocess.run(
command,
shell = False,
check = True,
capture_output = True,
text = True,
encoding = "utf-8",
errors = "replace",
)
except subprocess.CalledProcessError as e:
if print_output and hasattr(e, "stdout") and e.stdout:
print(e.stdout)
error_details = ""
if hasattr(e, "stdout") and e.stdout:
error_details += f"\nSubprocess stdout:\n{e.stdout}"
if hasattr(e, "stderr") and e.stderr:
error_details += f"\nSubprocess stderr:\n{e.stderr}"
raise RuntimeError(f"Failed to quantize {input_gguf} to q2_k_l: {e}{error_details}")
output_path = Path(output_gguf)
if not output_path.exists():
raise RuntimeError(f"Quantization failed - output file {output_gguf} not created")
if print_output:
file_size_bytes = output_path.stat().st_size
file_size_gb = file_size_bytes / (1024**3)
print(f"Unsloth: Successfully quantized to {output_gguf} (size: {file_size_gb:.2f}GB)")
return str(output_gguf)
def check_if_sentencepiece_model(model, temporary_location = "_unsloth_sentencepiece_temp"):
if not hasattr(model, "_saved_temp_tokenizer"):
return False
temp_tokenizer = model._saved_temp_tokenizer
sentencepiece_model = False
file_location = os.path.join(temporary_location, temp_tokenizer.name_or_path)
created_folder = False
if not os.path.exists(file_location):
created_folder = True
os.makedirs(file_location)
temp_tokenizer.save_pretrained(file_location)
if os.path.isfile(f"{file_location}/tokenizer.model"):
sentencepiece_model = True
if created_folder:
shutil.rmtree(file_location, ignore_errors = True)
return sentencepiece_model
_TOKENIZER_MODEL_CACHE = {}
def _has_tokenizer_model(tokenizer, token = None):
tokenizer = tokenizer.tokenizer if hasattr(tokenizer, "tokenizer") else tokenizer
if tokenizer is None:
return False
source = getattr(tokenizer, "name_or_path", None)
if not isinstance(source, str) or not source:
return False
if os.path.isdir(source):
return os.path.isfile(os.path.join(source, "tokenizer.model"))
# Refs of one repo can differ in whether they ship the asset, so memoize per ref.
revision = _tokenizer_revision(tokenizer)
cache_key = (source, revision)
if cache_key in _TOKENIZER_MODEL_CACHE:
return _TOKENIZER_MODEL_CACHE[cache_key]
# Hub repo id: probe local cache before model_info (issue #7481).
cache_dir = _tokenizer_cache_dir(tokenizer) or os.environ.get("HF_HUB_CACHE")
if not cache_dir:
hf_home = os.environ.get("HF_HOME")
if hf_home:
cache_dir = os.path.join(hf_home, "hub")
cached_path = _resolve_hub_repo_cached_file(
source,
"tokenizer.model",
token = token,
local_files_only = True,
cache_dir = cache_dir,
revision = revision,
)
if cached_path is not None:
_TOKENIZER_MODEL_CACHE[cache_key] = True
return True
if _tokenizer_wants_local_only(tokenizer):
return False
try:
repo_info = HfApi(token = token).model_info(source, revision = revision, files_metadata = False)
except Exception:
return False
has_tokenizer_model = any(
sibling.rfilename == "tokenizer.model" for sibling in (repo_info.siblings or [])
)
_TOKENIZER_MODEL_CACHE[cache_key] = has_tokenizer_model
return has_tokenizer_model
def _preserve_sentencepiece_tokenizer_assets(
tokenizer,
save_directory,
token = None,
):
tokenizer = tokenizer.tokenizer if hasattr(tokenizer, "tokenizer") else tokenizer
if tokenizer is None or not os.path.isdir(save_directory):
return
tokenizer_config_path = os.path.join(save_directory, "tokenizer_config.json")
if os.path.isfile(tokenizer_config_path):
desired_added_tokens_decoder = {}
for token_id, added_token in getattr(tokenizer, "added_tokens_decoder", {}).items():
desired_added_tokens_decoder[str(token_id)] = {
"content": getattr(added_token, "content", str(added_token)),
"single_word": getattr(added_token, "single_word", False),
"lstrip": getattr(added_token, "lstrip", False),
"rstrip": getattr(added_token, "rstrip", False),
"normalized": getattr(added_token, "normalized", True),
"special": getattr(added_token, "special", False),
}
if desired_added_tokens_decoder:
with open(tokenizer_config_path, "r", encoding = "utf-8") as file:
tokenizer_config = json.load(file)
if tokenizer_config.get("added_tokens_decoder") != desired_added_tokens_decoder:
tokenizer_config["added_tokens_decoder"] = desired_added_tokens_decoder
with open(tokenizer_config_path, "w", encoding = "utf-8") as file:
json.dump(tokenizer_config, file, indent = 2, ensure_ascii = False)
file.write("\n")
logger.warning_once(
f"Unsloth: Restored added_tokens_decoder metadata in {tokenizer_config_path}."
)
tokenizer_model = os.path.join(save_directory, "tokenizer.model")
downloaded_path = None
if not os.path.isfile(tokenizer_model) and _has_tokenizer_model(
tokenizer,
token = token,
):
source = getattr(tokenizer, "name_or_path", None)
if isinstance(source, str) and source:
if os.path.isdir(source):
local_path = os.path.join(source, "tokenizer.model")
if os.path.isfile(local_path):
downloaded_path = local_path
else:
cache_dir = _tokenizer_cache_dir(tokenizer) or os.environ.get("HF_HUB_CACHE")
if not cache_dir:
hf_home = os.environ.get("HF_HOME")
if hf_home:
cache_dir = os.path.join(hf_home, "hub")
cached_path = _resolve_hub_repo_cached_file(
source,
"tokenizer.model",
token = token,
local_files_only = True,
cache_dir = cache_dir,
revision = _tokenizer_revision(tokenizer),
)
if cached_path is not None:
downloaded_path = cached_path
else:
from huggingface_hub import hf_hub_download
try:
downloaded_path = hf_hub_download(
repo_id = source,
filename = "tokenizer.model",
token = token,
local_files_only = _tokenizer_wants_local_only(tokenizer),
cache_dir = cache_dir,
revision = _tokenizer_revision(tokenizer),
)
except Exception:
downloaded_path = None
if not os.path.isfile(tokenizer_model) and downloaded_path is not None:
shutil.copy2(downloaded_path, tokenizer_model)
logger.warning_once(
f"Unsloth: Preserved sentencepiece asset `tokenizer.model` in {save_directory}."
)
def _free_cached_model(model):
from huggingface_hub import scan_cache_dir
cached_repos = list(scan_cache_dir().repos)
# Go through every cached repo, and delete the one that matches the model we want to save.
# Can save 4GB of disk space - useful for Kaggle systems.
for cached_repo in cached_repos:
if cached_repo.repo_id == model.config._name_or_path:
remove_cache_commit = list(cached_repo.revisions)[0].commit_hash
delete_strategy = scan_cache_dir().delete_revisions(
remove_cache_commit,
)
logger.warning_once(
"Unsloth: Will remove a cached repo with size "
+ delete_strategy.expected_freed_size_str,
)
delete_strategy.execute()
def _merge_lora(layer, name):
bias = getattr(layer, "bias", None)
if isinstance(layer, (Bnb_Linear4bit, Peft_Linear4bit, Peft_Linear)):
# Is LoRA so we need to merge!
W, quant_state, A, B, s, bias = get_lora_parameters_bias(layer)
if quant_state is not None:
dtype = quant_state.dtype if type(quant_state) is not list else quant_state[2]
W = fast_dequantize(W, quant_state)
else:
dtype = W.dtype
W = W.to(torch.float32).t()
# W = W.t()
if A is not None:
# sAB = (A.t().to(torch.float32) @ (s * B.t().to(torch.float32)))
# W += sAB
W.addmm_(A.t().to(torch.float32), B.t().to(torch.float32), alpha = s)
# W.addmm_(A.t().to(W.dtype), B.t().to(W.dtype), alpha = s)
# if not torch.isfinite(W).all():
maximum_element = torch.max(W.min().abs(), W.max())
if not torch.isfinite(maximum_element).item():
raise ValueError(f"Unsloth: Merge failed.\n{name} has some elements = infinity.")
W = W.t().to(dtype)
else:
W = layer.weight
return W, bias
def fast_save_pickle(shard, name):
# Use this if # CPUs is <= 2
print(f"Unsloth: Saving {name}...")
torch.save(
shard,
name,
# HIGHEST_PROTOCOL seems to not work with Pytorch!
# pickle_module = pickle,
# pickle_protocol = pickle.HIGHEST_PROTOCOL,
)
return
def _preserve_tokenizer_eos_token(
tokenizer,
save_directory,
filename_prefix = None,
):
"""Restore tokenizer_config.json eos_token from the tokenizer passed to save.
Some merge paths may re-save or mutate tokenizer metadata after the tokenizer
is written. Gemma 4 instruct models use `<turn|>` as their chat EOS token;
if tokenizer_config.json is reset to the raw base `<eos>` token, runtimes such
as vLLM will not stop generation correctly. Keep the serialized metadata in
sync with the source tokenizer without failing the save if the config is not
present or cannot be edited.
`filename_prefix` mirrors the same argument on Transformers'
`PreTrainedTokenizerBase.save_pretrained`: when provided, the tokenizer
config is written as `{filename_prefix}-tokenizer_config.json` instead of
`tokenizer_config.json`.
"""
if tokenizer is None or save_directory is None:
return
source_tokenizer = tokenizer.tokenizer if hasattr(tokenizer, "tokenizer") else tokenizer
eos_token = getattr(source_tokenizer, "eos_token", None)
if eos_token is None and source_tokenizer is not tokenizer:
eos_token = getattr(tokenizer, "eos_token", None)
if eos_token is None:
return
eos_token = str(eos_token)
tokenizer_config_name = (
f"{filename_prefix}-tokenizer_config.json" if filename_prefix else "tokenizer_config.json"
)
tokenizer_config = os.path.join(str(save_directory), tokenizer_config_name)
if not os.path.isfile(tokenizer_config):
return
try:
with open(tokenizer_config, "r", encoding = "utf-8") as file:
config = json.load(file)
if config.get("eos_token") == eos_token:
return
config["eos_token"] = eos_token
with open(tokenizer_config, "w", encoding = "utf-8") as file:
json.dump(config, file, indent = 2, ensure_ascii = False)
file.write("\n")
except Exception as error:
logger.warning_once(
f"Unsloth: Could not preserve tokenizer eos_token in {tokenizer_config}: {error}"
)
def _is_qwen3_5_vlm(model):
config = getattr(model, "config", None)
if config is None or not hasattr(config, "vision_config"):
return False
architectures = getattr(config, "architectures", None) or ()
return any(
architecture
in (
"Qwen3_5ForConditionalGeneration",
"Qwen3_5MoeForConditionalGeneration",
)
for architecture in architectures
) or getattr(config, "model_type", None) in ("qwen3_5", "qwen3_5_moe")
def _is_gpt_oss(model):
config = getattr(model, "config", None)
if config is None:
return False
architectures = getattr(config, "architectures", None) or ()
return "GptOssForCausalLM" in architectures or getattr(config, "model_type", None) in (
"gpt-oss",
"gpt_oss",
)
def _is_vlm(model):
config = getattr(model, "config", None)
if config is None:
return False
architectures = getattr(config, "architectures", None) or ()
return hasattr(config, "vision_config") or any(
x.endswith(("ForConditionalGeneration", "ForVisionText2Text")) for x in architectures
)
def _qwen3_5_vlm_state_dict_for_save(state_dict):
remapped_state_dict = {}
for key, value in state_dict.items():
if key.startswith("language_model.model."):
new_key = "model.language_model." + key[len("language_model.model.") :]
elif key.startswith("visual."):
new_key = "model.visual." + key[len("visual.") :]
elif key.startswith("language_model.lm_head."):
new_key = "lm_head." + key[len("language_model.lm_head.") :]
else:
new_key = key
remapped_state_dict[new_key] = value
return remapped_state_dict
def _coerce_tied_weights_keys_to_dict(model):
"""Coerce each module's legacy list/tuple/set ``_tied_weights_keys`` to dict form,
returning ``[(module, original), ...]`` for the caller to restore.
transformers >= 5 ``save_pretrained`` reads ``_tied_weights_keys.keys()``, so a model
still declaring it as a list (e.g. NemotronH) crashes mid-save.
"""
originals = []
try:
modules = list(model.modules())
except Exception:
return originals
for module in modules:
keys = getattr(module, "_tied_weights_keys", None)
if isinstance(keys, (list, tuple, set)):
try:
module._tied_weights_keys = {k: k for k in keys}
originals.append((module, keys))
except Exception:
pass
return originals
def _restore_tied_weights_keys(originals):
"""Undo _coerce_tied_weights_keys_to_dict."""
for module, keys in originals:
try:
module._tied_weights_keys = keys
except Exception:
pass
def _normalize_tied_weights_keys_for_save(save_fn):
"""Coerce legacy list-form ``_tied_weights_keys`` to dict for the duration of a save,
then restore: transformers >= 5 re-ties from the dict's *values*, so a persisted
``{k: k}`` self-map would no-op a later resize/re-tie. ``model`` is the first positional
arg (bound-method ``self``) or the ``model=`` keyword.
"""
@functools.wraps(save_fn)
def wrapper(*args, **kwargs):
model = kwargs.get("model")
if model is None and args:
model = args[0]
if model is None:
model = kwargs.get("self")
originals = _coerce_tied_weights_keys_to_dict(model) if model is not None else []
try:
return save_fn(*args, **kwargs)
finally:
_restore_tied_weights_keys(originals)
return wrapper
@_normalize_tied_weights_keys_for_save
@torch.inference_mode
def unsloth_save_model(
model,
tokenizer,
save_directory: Union[str, os.PathLike],
save_method: str = "lora", # ["lora", "merged_16bit", "merged_4bit"]
push_to_hub: bool = False,
token: Optional[Union[str, bool]] = None,
is_main_process: bool = True,
state_dict: Optional[dict] = None,
save_function: Callable = torch.save,
max_shard_size: Union[int, str] = "5GB",
safe_serialization: bool = True,
variant: Optional[str] = None,
save_peft_format: bool = True,
# Push to hub
use_temp_dir: Optional[bool] = None,
commit_message: Optional[str] = "Trained with Unsloth",
private: Optional[bool] = None,
create_pr: bool = False,
revision: str = None,
commit_description: str = "Upload model trained with Unsloth 2x faster",
tags: List[str] = None,
# Our functions
temporary_location: str = "_unsloth_temporary_saved_buffers",
maximum_memory_usage: float = 0.9,
datasets: Optional[List[str]] = None,
):
if isinstance(tokenizer, (PreTrainedTokenizerBase, ProcessorMixin)):
tokenizer = patch_saving_functions(tokenizer)
if token is None:
token = get_token()
if commit_message is None:
commit_message = ""
if "Unsloth" not in commit_message:
commit_message += " (Trained with Unsloth)"
commit_message = commit_message.lstrip()
if commit_description is None:
commit_description = "Upload model trained with Unsloth 2x faster"
elif "Unsloth 2x faster" not in commit_description:
commit_description += " (Trained with Unsloth 2x faster)"
if save_method == "merged_4bit":
raise RuntimeError(
"Unsloth: Merging into 4bit will cause your model to lose accuracy if you plan\n"
"to merge to GGUF or others later on. I suggest you to do this as a final step\n"
"if you're planning to do multiple saves.\n"
"If you are certain, change `save_method` to `merged_4bit_forced`."
)
elif save_method == "merged_4bit_forced":
save_method = "merged_4bit"
save_pretrained_settings = dict(locals())
for deletion in (
"model",
"tokenizer",
"save_method",
"temporary_location",
"maximum_memory_usage",
"datasets",
):
del save_pretrained_settings[deletion]
# First check for a token!
if push_to_hub:
from huggingface_hub import whoami
try:
username = whoami(token = token)["name"]
except:
raise RuntimeError(
"Unsloth: Please supply a token!\nGo to https://huggingface.co/settings/tokens"
)
assert maximum_memory_usage > 0 and maximum_memory_usage <= 0.95
# Clean memory up first
for _ in range(3):
torch.cuda.empty_cache()
gc.collect()
save_method = save_method.lower().replace(" ", "_")
if save_method != "lora" and save_method != "merged_16bit" and save_method != "merged_4bit":
raise RuntimeError(
"Unsloth: You must select one of 3 options when saving models:\n"
'"lora" ==> This is the fastest and easiet. Just saves LoRA modules.\n'
'"merged_16bit" ==> This merges LoRA weights and saves to float16. Needed for llama.cpp / GGUF.\n'
'"merged_4bit" ==> This merges LoRA weights and saves to 4bit. Useful for DPO / inference.'
)
if save_method == "merged_4bit":
print("Unsloth: Merging 4bit and LoRA weights to 4bit...")
print("This might take 5 minutes...")
# Counteract no LoRA adapters!
if hasattr(model, "merge_and_unload"):
model = model.merge_and_unload()
print("Done.")
if tags is not None:
assert isinstance(tags, (list, tuple))
tags = list(tags) + [
"unsloth",
]
else:
tags = [
"unsloth",
]
save_pretrained_settings["tags"] = tags
if ((save_method == "lora") or (save_method == "merged_4bit")) and push_to_hub:
if token is None:
raise RuntimeError(
"Unsloth: Pushing to HF requires a token. Pass `token = 'hf_....'`\n"
"Go to https://huggingface.co/settings/tokens."
)
if save_method == "lora":
print("Unsloth: Saving LoRA adapters. Please wait...")
elif save_method == "merged_4bit":
print("Unsloth: Saving 4bit Bitsandbytes model. Please wait...")
# Update model tag
_ = upload_to_huggingface(
model,
save_directory,
token,
"finetuned",
"trl",
file_location = None,
old_username = None,
private = private,
datasets = datasets,
)
getattr(model, "original_push_to_hub", model.push_to_hub)(
repo_id = save_directory,
use_temp_dir = use_temp_dir,
commit_message = commit_message,
private = private,
token = token,
max_shard_size = max_shard_size,
create_pr = create_pr,
safe_serialization = safe_serialization,
revision = revision,
commit_description = commit_description,
tags = tags,
)
if tokenizer is not None:
# Set padding side to left for inference
_tokenizer = tokenizer.tokenizer if hasattr(tokenizer, "tokenizer") else tokenizer
old_padding_side = _tokenizer.padding_side
_tokenizer.padding_side = "left"
getattr(tokenizer, "original_push_to_hub", tokenizer.push_to_hub)(
repo_id = save_directory,
use_temp_dir = use_temp_dir,
commit_message = commit_message,
private = private,
token = token,
max_shard_size = max_shard_size,
create_pr = create_pr,
safe_serialization = safe_serialization,
revision = revision,
commit_description = commit_description,
tags = tags,
)
# Revert back padding side
_tokenizer.padding_side = old_padding_side
if hasattr(model, "config"):
print(f"Saved {save_method} model to https://huggingface.co/" + save_directory)
return save_directory, None
# Tokenizer has different saving arguments
tokenizer_save_settings = {
"save_directory": save_pretrained_settings["save_directory"],
"legacy_format": None,
"filename_prefix": None,
"push_to_hub": save_pretrained_settings["push_to_hub"],
"private": save_pretrained_settings["private"],
"token": save_pretrained_settings["token"],
}
# Check if PEFT Model or not - if yes, 3 levels. If not 2 levels.
from peft import PeftModelForCausalLM
if isinstance(model, PeftModelForCausalLM):