forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.py
More file actions
1467 lines (1281 loc) · 49.6 KB
/
Copy pathexport.py
File metadata and controls
1467 lines (1281 loc) · 49.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
"""soup export — convert a model to GGUF format for Ollama / llama.cpp."""
import json
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Optional
import typer
from rich.console import Console
from rich.markup import escape
from rich.panel import Panel
console = Console()
SUPPORTED_FORMATS = (
"gguf", "onnx", "tensorrt", "awq", "gptq",
# v0.52.0 Part D — BitNet 1.58-bit + TQ1_0 GGUF.
# Schema-only stubs in v0.52.0; live conversion lands in v0.52.1.
"bitnet", "tq1_0",
# v0.53.1 #142 — TorchAO PTQ live wiring (Int4WeightOnly / Int8DynActInt4 /
# Float8DynActFloat8 / NVFP4). Requires --quant-config <yaml>.
"torchao",
# v0.53.1 #139 — UD/IQ/Apple-ARM GGUFs via llama.cpp imatrix.
"gguf-ud",
)
GGUF_QUANT_TYPES = ("q4_0", "q4_k_m", "q5_k_m", "q8_0", "f16", "f32")
LLAMA_CPP_DIR_NAME = "llama.cpp"
# Pin to a known release tag for supply-chain safety
LLAMA_CPP_TAG = "b5270"
def export(
model: str = typer.Option(
...,
"--model",
"-m",
help="Path to model directory (full model or LoRA adapter)",
),
fmt: str = typer.Option(
"gguf",
"--format",
"-f",
help="Export format: gguf, onnx, tensorrt, awq, gptq, bitnet, tq1_0",
),
quant: str = typer.Option(
"q4_k_m",
"--quant",
"-q",
help="Quantization type: q4_0, q4_k_m, q5_k_m, q8_0, f16, f32",
),
output: Optional[str] = typer.Option(
None,
"--output",
"-o",
help="Output file path. Default: <model-name>.<quant>.gguf",
),
base: Optional[str] = typer.Option(
None,
"--base",
"-b",
help="Base model ID (for LoRA adapters). Auto-detected if not set.",
),
llama_cpp_path: Optional[str] = typer.Option(
None,
"--llama-cpp",
help="Path to llama.cpp directory. Auto-detected or cloned to ~/.soup/llama.cpp",
),
onnx_task: str = typer.Option(
"text-generation",
"--onnx-task",
help="ONNX export task: text-generation (causal LM) or feature-extraction (embedding)",
),
deploy: Optional[str] = typer.Option(
None,
"--deploy",
help="Auto-deploy after export. Currently supported: ollama",
),
deploy_name: Optional[str] = typer.Option(
None,
"--deploy-name",
help="Model name for deployment (used with --deploy)",
),
bits: int = typer.Option(
4,
"--bits",
help="Quantization bits for AWQ/GPTQ: 4 or 8",
),
group_size: int = typer.Option(
128,
"--group-size",
help="Group size for AWQ/GPTQ quantization",
),
calibration_data: Optional[str] = typer.Option(
None,
"--calibration-data",
help="Path to calibration JSONL for AWQ/GPTQ (default: use built-in sample)",
),
calibration_samples: int = typer.Option(
128,
"--calibration-samples",
help="Number of calibration samples for AWQ/GPTQ",
),
registry_id: Optional[str] = typer.Option(
None,
"--registry-id",
help="Attach exported artifact to this registry entry "
"(default: auto-match by source --model output dir)",
),
trust_remote_code: bool = typer.Option(
False,
"--trust-remote-code",
help=(
"Allow loading models that ship custom Python via auto_map. "
"Default deny (v0.36.0). Only enable if you trust the source."
),
),
quant_config: Optional[str] = typer.Option(
None,
"--quant-config",
help=(
"Path to YAML for torchao PTQ export (v0.53.1 #142). "
"Required when --format=torchao."
),
),
gguf_flavour: Optional[str] = typer.Option(
None,
"--gguf-flavour",
help=(
"Advanced GGUF format flag — UD-Q*_K_XL / IQ*_M / Q4_0_4_4 / etc. "
"Required when --format=gguf-ud (v0.53.1 #139)."
),
),
hub: str = typer.Option(
"hf",
"--hub",
help=(
"Source hub for the base model when --model is a LoRA adapter: "
"hf (default) / modelscope / modelers (v0.53.10 #152)."
),
),
):
"""Export a model to GGUF, ONNX, TensorRT-LLM, AWQ, GPTQ, or TorchAO format."""
# v0.53.10 #152 — pre-fetch the base model from a non-HF hub. ``model``
# is typically a local merged dir / adapter dir; only ``base`` is rewritten.
if hub and hub != "hf":
from soup_cli.utils.hubs import apply_hub_to_cli_model
try:
_, base = apply_hub_to_cli_model(model, base, hub, console=console)
except (TypeError, ValueError) as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(code=2) from exc
except ImportError as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(code=1) from exc
model_path = Path(model)
# --- Validate ---
if not model_path.exists():
console.print(f"[red]Model path not found: {model_path}[/]")
raise typer.Exit(1)
if fmt not in SUPPORTED_FORMATS:
console.print(
f"[red]Unsupported format: {fmt}[/]\n"
f"Supported: {', '.join(SUPPORTED_FORMATS)}"
)
raise typer.Exit(1)
# --- ONNX export path ---
if fmt == "onnx":
_export_onnx(model_path, output, base, onnx_task, trust_remote_code)
return
# --- TensorRT-LLM export path ---
if fmt == "tensorrt":
_export_tensorrt(model_path, output, base, trust_remote_code)
return
# --- AWQ export path ---
if fmt == "awq":
_export_awq(
model_path, output, base, bits, group_size,
calibration_data, calibration_samples, trust_remote_code,
)
return
# --- GPTQ export path ---
if fmt == "gptq":
_export_gptq(
model_path, output, base, bits, group_size,
calibration_data, calibration_samples, trust_remote_code,
)
return
# --- TorchAO PTQ export path (v0.53.1 #142) ---
if fmt == "torchao":
_export_torchao_cli(
model_path, output, quant_config, trust_remote_code,
)
return
# --- Advanced GGUF export path (UD / IQ / Apple-ARM, v0.53.1 #139) ---
if fmt == "gguf-ud":
_export_gguf_advanced(
model_path=model_path,
output=output,
base=base,
gguf_flavour=gguf_flavour,
calibration_data=calibration_data,
llama_cpp_path=llama_cpp_path,
trust_remote_code=trust_remote_code,
)
return
# --- BitNet 1.58-bit / TQ1_0 GGUF (v0.71.20 #134) ---
# Live llama.cpp TQ1_0 ternary export. Requires a built llama.cpp
# toolchain; the convert/quantize binaries surface a friendly
# FileNotFoundError when absent (infra-blocked, mirrors gguf-ud).
if fmt in ("bitnet", "tq1_0"):
_export_bitnet_gguf(
model_path=model_path,
output=output,
base=base,
export_format=fmt,
llama_cpp_path=llama_cpp_path,
trust_remote_code=trust_remote_code,
)
return
if quant not in GGUF_QUANT_TYPES:
console.print(
f"[red]Unsupported quantization: {quant}[/]\n"
f"Supported: {', '.join(GGUF_QUANT_TYPES)}"
)
raise typer.Exit(1)
# --- Check if LoRA adapter (needs merge first) ---
adapter_config_path = model_path / "adapter_config.json"
is_adapter = adapter_config_path.exists()
merge_dir = None
if is_adapter:
console.print("[yellow]LoRA adapter detected - merging with base model first...[/]")
base_model = base or _detect_base_model(adapter_config_path)
if not base_model:
console.print(
"[red]Cannot detect base model from adapter_config.json.[/]\n"
"Please specify with [bold]--base[/] flag."
)
raise typer.Exit(1)
merge_dir = model_path.parent / f".soup_merge_tmp_{model_path.name}"
_merge_adapter(
str(model_path), base_model, str(merge_dir), trust_remote_code,
)
model_path = merge_dir
# --- Find llama.cpp ---
llama_dir = _find_llama_cpp(llama_cpp_path)
# --- Convert to GGUF ---
model_name = Path(model).name
if output:
output_path = Path(output)
else:
output_path = Path(model).parent / f"{model_name}.{quant}.gguf"
console.print(
Panel(
f"Model: [bold]{model_path}[/]\n"
f"Format: [bold]{fmt}[/]\n"
f"Quant: [bold]{quant}[/]\n"
f"Output: [bold]{output_path}[/]",
title="Export Plan",
)
)
try:
# Step 1: Convert HF model to GGUF (f16)
convert_script = llama_dir / "convert_hf_to_gguf.py"
if not convert_script.exists():
console.print(
f"[red]convert_hf_to_gguf.py not found in {llama_dir}[/]\n"
"Make sure llama.cpp is properly cloned."
)
raise typer.Exit(1)
if quant in ("f16", "f32"):
# Direct conversion without quantization
outtype = "f16" if quant == "f16" else "f32"
console.print(f"[dim]Converting to GGUF ({outtype})...[/]")
_run_convert(convert_script, model_path, output_path, outtype)
else:
# Convert to f16 first, then quantize
f16_path = output_path.parent / f"{model_name}.f16.gguf"
console.print("[dim]Converting to GGUF (f16)...[/]")
_run_convert(convert_script, model_path, f16_path, "f16")
# Quantize
console.print(f"[dim]Quantizing to {quant}...[/]")
_run_quantize(llama_dir, f16_path, output_path, quant)
# Clean up intermediate f16 file
if f16_path.exists() and f16_path != output_path:
f16_path.unlink()
finally:
# Clean up temporary merge directory
if merge_dir and merge_dir.exists():
console.print("[dim]Cleaning up temporary merge files...[/]")
shutil.rmtree(merge_dir, ignore_errors=True)
if not output_path.exists():
console.print("[red]Export failed - output file not created.[/]")
raise typer.Exit(1)
# v0.33.0 #35: optional auto-attach to registry entry
_maybe_attach_export(
artifact_path=str(output_path), kind="gguf",
explicit_id=registry_id, source_model=str(Path(model)),
)
file_size = output_path.stat().st_size
size_str = _format_size(file_size)
console.print(
Panel(
f"Output: [bold]{output_path}[/]\n"
f"Size: [bold]{size_str}[/]\n"
f"Quant: [bold]{quant}[/]\n\n"
f"Use with Ollama:\n"
f" 1. Create a Modelfile:\n"
f" [bold]echo 'FROM {output_path}' > Modelfile[/]\n"
f" 2. Create the model:\n"
f" [bold]ollama create {model_name} -f Modelfile[/]\n"
f" 3. Run it:\n"
f" [bold]ollama run {model_name}[/]",
title="[bold green]Export Complete![/]",
)
)
# --- Auto-deploy to Ollama if requested ---
if deploy:
_auto_deploy_ollama(output_path, model_name, deploy, deploy_name)
def _detect_base_model(adapter_config_path: Path) -> Optional[str]:
"""Read base_model_name_or_path from adapter_config.json."""
try:
with open(adapter_config_path, encoding="utf-8") as f:
config = json.load(f)
return config.get("base_model_name_or_path")
except (json.JSONDecodeError, OSError):
return None
def _merge_adapter(
adapter_path: str,
base_model: str,
output_dir: str,
trust_remote_code: bool = False,
):
"""Merge LoRA adapter with base model."""
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
from soup_cli.utils.trust_remote import (
model_requires_trust_remote_code,
resolve_trust_remote_code,
)
requires = model_requires_trust_remote_code(adapter_path) or False
trc = resolve_trust_remote_code(
base_model,
requested=trust_remote_code,
console=console,
requires_remote_code=requires,
)
console.print(f"[dim]Loading base model: {base_model}...[/]")
model = AutoModelForCausalLM.from_pretrained(
base_model,
dtype=torch.float16,
trust_remote_code=trc,
device_map="cpu",
)
console.print(f"[dim]Loading LoRA adapter: {adapter_path}...[/]")
model = PeftModel.from_pretrained(model, adapter_path)
console.print("[dim]Merging weights...[/]")
model = model.merge_and_unload()
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
model.save_pretrained(str(out))
tokenizer = AutoTokenizer.from_pretrained(adapter_path, trust_remote_code=trc)
tokenizer.save_pretrained(str(out))
console.print("[green]Adapter merged successfully.[/]")
# llama.cpp's own requirements.txt pins `torch~=2.2.1` against the CPU wheel
# index plus an old `transformers`. Installing it into the user's interpreter
# silently DOWNGRADES a CUDA torch to CPU-only and breaks their training setup
# (observed live on Windows during the v0.71.35 GGUF validation: torch
# 2.5.1+cu -> 2.2.2+cpu, transformers 4.57 -> 4.46). Soup's `[train]` extra
# already provides torch / transformers / numpy, so install ONLY the extra
# packages the convert script needs, unpinned, and never touch the rest.
_CONVERT_EXTRA_DEPS = ("gguf", "sentencepiece", "protobuf")
def _install_convert_deps() -> None:
"""Install the convert script's extra deps without disturbing torch."""
try:
subprocess.run(
[sys.executable, "-m", "pip", "install", "-q", *_CONVERT_EXTRA_DEPS],
check=True,
capture_output=True,
text=True,
)
except (subprocess.CalledProcessError, FileNotFoundError) as exc:
# Non-fatal: the user may already have them, or manage deps themselves.
detail = getattr(exc, "stderr", "") or type(exc).__name__
console.print(
"[yellow]Could not auto-install the GGUF convert dependencies "
f"({', '.join(_CONVERT_EXTRA_DEPS)}).[/]\n"
f"[dim]{escape(str(detail)[:200])}[/]\n"
"Install them manually if the conversion fails."
)
def _find_llama_cpp(user_path: Optional[str] = None) -> Path:
"""Find or clone llama.cpp directory."""
from soup_cli.utils.constants import SOUP_DIR
# 1. User-specified path
if user_path:
path = Path(user_path)
if path.exists():
return path
console.print(f"[red]llama.cpp not found at: {path}[/]")
raise typer.Exit(1)
# 2. LLAMA_CPP_PATH env var
import os
env_path = os.environ.get("LLAMA_CPP_PATH")
if env_path:
path = Path(env_path)
if path.exists():
return path
# 3. Check ~/.soup/llama.cpp
# SOUP_DIR is a bare name (".soup"), so it MUST be anchored to the home
# directory the way tracker.py / registry/store.py do. Using it relatively
# made the lookup cwd-dependent: llama.cpp was never found in the canonical
# ~/.soup, and the auto-clone dropped a fresh ~200 MB checkout into whatever
# directory the user happened to run from (v0.71.35 GGUF validation).
soup_llama = Path.home() / SOUP_DIR / LLAMA_CPP_DIR_NAME
if soup_llama.exists() and (soup_llama / "convert_hf_to_gguf.py").exists():
return soup_llama
# 4. Auto-clone
console.print("[yellow]llama.cpp not found. Cloning to ~/.soup/llama.cpp...[/]")
console.print("[dim]This is a one-time setup for GGUF export.[/]")
try:
subprocess.run(
["git", "clone", "--depth", "1", "--branch", LLAMA_CPP_TAG,
"https://github.com/ggerganov/llama.cpp.git", str(soup_llama)],
check=True,
capture_output=True,
text=True,
)
_install_convert_deps()
console.print("[green]llama.cpp cloned successfully.[/]")
return soup_llama
except subprocess.CalledProcessError as exc:
console.print(f"[red]Failed to clone llama.cpp: {exc.stderr}[/]")
console.print(
"Please clone manually:\n"
f" [bold]git clone https://github.com/ggerganov/llama.cpp.git {soup_llama}[/]\n"
"Or specify path: [bold]--llama-cpp /path/to/llama.cpp[/]"
)
raise typer.Exit(1)
except FileNotFoundError:
console.print(
"[red]git not found.[/] Please install git or clone llama.cpp manually:\n"
f" [bold]git clone https://github.com/ggerganov/llama.cpp.git {soup_llama}[/]"
)
raise typer.Exit(1)
def _run_convert(script: Path, model_dir: Path, output_path: Path, outtype: str):
"""Run llama.cpp convert_hf_to_gguf.py script."""
output_path.parent.mkdir(parents=True, exist_ok=True)
cmd = [
sys.executable, str(script),
str(model_dir),
"--outfile", str(output_path),
"--outtype", outtype,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
console.print(f"[red]Conversion failed:[/]\n{result.stderr}")
raise typer.Exit(1)
def _run_quantize(llama_dir: Path, input_path: Path, output_path: Path, quant_type: str):
"""Run llama-quantize (or llama.cpp/build/bin/llama-quantize)."""
# Try to find the quantize binary
quantize_bin = _find_quantize_binary(llama_dir)
if not quantize_bin:
console.print(
"[red]llama-quantize binary not found.[/]\n"
"Build llama.cpp first:\n"
f" [bold]cd {llama_dir} && make llama-quantize[/]\n"
"Or use [bold]--quant f16[/] to skip quantization."
)
raise typer.Exit(1)
cmd = [str(quantize_bin), str(input_path), str(output_path), quant_type.upper()]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
console.print(f"[red]Quantization failed:[/]\n{result.stderr}")
raise typer.Exit(1)
# MSVC / Xcode are multi-config generators: they nest binaries under a
# per-configuration subdirectory (build/bin/Release/llama-quantize.exe) rather
# than the flat build/bin/ that single-config generators (Make/Ninja) produce.
# Without these, `soup export --format gguf` cannot find a correctly-built
# llama.cpp on Windows (v0.71.35 GGUF-on-Windows validation, #70/#144).
_CMAKE_CONFIG_DIRS = ("Release", "RelWithDebInfo", "MinSizeRel", "Debug")
def _find_quantize_binary(llama_dir: Path) -> Optional[Path]:
"""Find the llama-quantize binary."""
# Check common locations
candidates = [
llama_dir / "build" / "bin" / "llama-quantize",
llama_dir / "build" / "bin" / "llama-quantize.exe",
llama_dir / "llama-quantize",
llama_dir / "llama-quantize.exe",
llama_dir / "build" / "llama-quantize",
]
# Multi-config generator layouts (MSVC on Windows, Xcode on macOS).
for config in _CMAKE_CONFIG_DIRS:
candidates.append(llama_dir / "build" / "bin" / config / "llama-quantize")
candidates.append(llama_dir / "build" / "bin" / config / "llama-quantize.exe")
candidates.append(llama_dir / "build" / config / "llama-quantize.exe")
for candidate in candidates:
if candidate.exists():
return candidate
# Check if it's in PATH
which_result = shutil.which("llama-quantize")
if which_result:
return Path(which_result)
return None
def _export_onnx(
model_path: Path, output: Optional[str], base: Optional[str],
task: str = "text-generation",
trust_remote_code: bool = False,
):
"""Export model to ONNX format via optimum."""
try:
from optimum.exporters.onnx import main_export
except ImportError:
console.print(
"[red]optimum not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[onnx]\"[/]\n"
"Or directly: [bold]pip install optimum[onnx][/]"
)
raise typer.Exit(1)
# Check if LoRA adapter
adapter_config_path = model_path / "adapter_config.json"
is_adapter = adapter_config_path.exists()
merge_dir = None
source_path = model_path
if is_adapter:
console.print("[yellow]LoRA adapter detected - merging with base model first...[/]")
base_model = base or _detect_base_model(adapter_config_path)
if not base_model:
console.print(
"[red]Cannot detect base model from adapter_config.json.[/]\n"
"Please specify with [bold]--base[/] flag."
)
raise typer.Exit(1)
merge_dir = model_path.parent / f".soup_merge_tmp_{model_path.name}"
_merge_adapter(str(model_path), base_model, str(merge_dir), trust_remote_code)
source_path = merge_dir
output_path = Path(output) if output else model_path.parent / f"{model_path.name}_onnx"
console.print(
Panel(
f"Model: [bold]{source_path}[/]\n"
f"Format: [bold]ONNX[/]\n"
f"Output: [bold]{output_path}[/]",
title="Export Plan",
)
)
try:
console.print(
"[yellow]Warning: ONNX export may execute custom model code "
"if the model uses trust_remote_code.[/]"
)
console.print("[dim]Exporting to ONNX...[/]")
main_export(
model_name_or_path=str(source_path),
output=str(output_path),
task=task,
)
except Exception as exc:
console.print(f"[red]ONNX export failed:[/] {exc}")
raise typer.Exit(1)
finally:
if merge_dir and merge_dir.exists():
console.print("[dim]Cleaning up temporary merge files...[/]")
shutil.rmtree(merge_dir, ignore_errors=True)
console.print(
Panel(
f"Output: [bold]{output_path}[/]\n"
f"Format: [bold]ONNX[/]\n\n"
f"Use with ONNX Runtime:\n"
f" [bold]from optimum.onnxruntime import ORTModelForCausalLM[/]\n"
f" [bold]model = ORTModelForCausalLM.from_pretrained('{output_path}')[/]",
title="[bold green]ONNX Export Complete![/]",
)
)
def _export_tensorrt(
model_path: Path,
output: Optional[str],
base: Optional[str],
trust_remote_code: bool = False,
):
"""Export model to TensorRT-LLM format."""
# TensorRT-LLM uses trtllm-build CLI from the tensorrt_llm package
trtllm_available = False
try:
import tensorrt_llm # noqa: F401
trtllm_available = True
except ImportError:
pass
if not trtllm_available:
console.print(
"[red]tensorrt_llm not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[tensorrt]\"[/]\n"
"Or follow: https://github.com/NVIDIA/TensorRT-LLM#installation"
)
raise typer.Exit(1)
# Check if LoRA adapter
adapter_config_path = model_path / "adapter_config.json"
is_adapter = adapter_config_path.exists()
merge_dir = None
source_path = model_path
if is_adapter:
console.print("[yellow]LoRA adapter detected - merging with base model first...[/]")
base_model = base or _detect_base_model(adapter_config_path)
if not base_model:
console.print(
"[red]Cannot detect base model from adapter_config.json.[/]\n"
"Please specify with [bold]--base[/] flag."
)
raise typer.Exit(1)
merge_dir = model_path.parent / f".soup_merge_tmp_{model_path.name}"
_merge_adapter(str(model_path), base_model, str(merge_dir), trust_remote_code)
source_path = merge_dir
output_path = Path(output) if output else model_path.parent / f"{model_path.name}_trt"
console.print(
Panel(
f"Model: [bold]{source_path}[/]\n"
f"Format: [bold]TensorRT-LLM[/]\n"
f"Output: [bold]{output_path}[/]",
title="Export Plan",
)
)
try:
# Step 1: Convert HF model to TensorRT-LLM checkpoint
console.print("[dim]Converting to TensorRT-LLM checkpoint...[/]")
ckpt_dir = output_path / "checkpoint"
ckpt_dir.mkdir(parents=True, exist_ok=True)
try:
result = subprocess.run(
[
sys.executable, "-m",
"tensorrt_llm.commands.convert_checkpoint",
"--model_dir", str(source_path),
"--output_dir", str(ckpt_dir),
"--dtype", "float16",
],
capture_output=True,
text=True,
)
except FileNotFoundError:
console.print("[red]Python executable not found.[/]")
raise typer.Exit(1)
if result.returncode != 0:
console.print(
f"[red]Checkpoint conversion failed:[/]\n{result.stderr}"
)
raise typer.Exit(1)
# Step 2: Build TensorRT engine
console.print("[dim]Building TensorRT engine...[/]")
engine_dir = output_path / "engine"
engine_dir.mkdir(parents=True, exist_ok=True)
try:
result = subprocess.run(
[
"trtllm-build",
"--checkpoint_dir", str(ckpt_dir),
"--output_dir", str(engine_dir),
"--gemm_plugin", "float16",
],
capture_output=True,
text=True,
)
except FileNotFoundError:
console.print(
"[red]trtllm-build not found in PATH.[/]\n"
"Ensure tensorrt_llm is installed and "
"trtllm-build is available."
)
raise typer.Exit(1)
if result.returncode != 0:
console.print(
f"[red]TensorRT engine build failed:[/]\n{result.stderr}"
)
raise typer.Exit(1)
finally:
if merge_dir and merge_dir.exists():
console.print("[dim]Cleaning up temporary merge files...[/]")
shutil.rmtree(merge_dir, ignore_errors=True)
console.print(
Panel(
f"Output: [bold]{output_path}[/]\n"
f"Format: [bold]TensorRT-LLM[/]\n\n"
f"Use with TensorRT-LLM:\n"
f" [bold]import tensorrt_llm[/]\n"
f" [bold]runner = tensorrt_llm.ModelRunner.from_dir('{engine_dir}')[/]",
title="[bold green]TensorRT-LLM Export Complete![/]",
)
)
def _validate_output_path(output: Optional[str]) -> Optional[Path]:
"""Validate output path stays under cwd (path traversal protection)."""
if output is None:
return None
# realpath + commonpath containment (is_under_cwd) — Path.resolve() +
# relative_to() breaks on Windows 8.3 short names.
from soup_cli.utils.paths import is_under_cwd
out_path = Path(output).resolve()
if not is_under_cwd(output):
console.print("[red]Output path must be under the current working directory.[/]")
raise typer.Exit(1)
return out_path
def _validate_calibration_path(calibration_data: Optional[str]) -> Optional[Path]:
"""Validate calibration data path stays under cwd."""
if calibration_data is None:
return None
from soup_cli.utils.paths import is_under_cwd
cal_path = Path(calibration_data).resolve()
if not is_under_cwd(calibration_data):
console.print("[red]Calibration data path must be under the current working directory.[/]")
raise typer.Exit(1)
if not cal_path.exists():
console.print(f"[red]Calibration data not found: {cal_path}[/]")
raise typer.Exit(1)
return cal_path
def _load_calibration_texts(cal_path: Optional[Path], max_samples: int = 128) -> list:
"""Load calibration texts from JSONL file."""
if cal_path is None:
return []
texts = []
with open(cal_path, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
# Support "text" field or concatenate all string values
if "text" in row:
texts.append(str(row["text"]))
else:
texts.append(" ".join(str(v) for v in row.values() if v))
except json.JSONDecodeError:
continue
if len(texts) >= max_samples:
break
return texts
def _export_awq(
model_path: Path,
output: Optional[str],
base: Optional[str],
bits: int = 4,
group_size: int = 128,
calibration_data: Optional[str] = None,
calibration_samples: int = 128,
trust_remote_code: bool = False,
) -> None:
"""Export model to AWQ format via autoawq."""
# Validate bits
valid_bits = {4, 8}
if bits not in valid_bits:
console.print(
f"[red]Invalid --bits {bits}. Must be one of: {sorted(valid_bits)}[/]"
)
raise typer.Exit(1)
# Validate output path (security: path traversal protection)
validated_output = _validate_output_path(output)
# Validate calibration path (security: path traversal protection)
cal_path = _validate_calibration_path(calibration_data)
try:
from awq import AutoAWQForCausalLM
except ImportError:
console.print(
"[red]autoawq not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[awq]\"[/]\n"
"Or directly: [bold]pip install autoawq[/]"
)
raise typer.Exit(1)
from transformers import AutoTokenizer
# Check if LoRA adapter — merge first
adapter_config_path = model_path / "adapter_config.json"
is_adapter = adapter_config_path.exists()
merge_dir = None
source_path = model_path
if is_adapter:
console.print("[yellow]LoRA adapter detected - merging with base model first...[/]")
base_model = base or _detect_base_model(adapter_config_path)
if not base_model:
console.print(
"[red]Cannot detect base model from adapter_config.json.[/]\n"
"Please specify with [bold]--base[/] flag."
)
raise typer.Exit(1)
merge_dir = model_path.parent / f".soup_merge_tmp_{model_path.name}"
_merge_adapter(str(model_path), base_model, str(merge_dir), trust_remote_code)
source_path = merge_dir
default_out = model_path.parent / f"{model_path.name}_awq"
output_path = validated_output if validated_output else default_out
console.print(
Panel(
f"Model: [bold]{source_path}[/]\n"
f"Format: [bold]AWQ[/]\n"
f"Bits: [bold]{bits}[/]\n"
f"Group size: [bold]{group_size}[/]\n"
f"Output: [bold]{output_path}[/]",
title="Export Plan",
)
)
try:
console.print(
Panel(
"[yellow]Warning:[/] Loading model with trust_remote_code=True.\n"
"This may execute custom code from the model directory.",
title="Security Notice",
)
)
console.print("[dim]Loading model for AWQ quantization...[/]")
model = AutoAWQForCausalLM.from_pretrained(str(source_path))
from soup_cli.utils.trust_remote import (
model_requires_trust_remote_code,
resolve_trust_remote_code,
)
requires_tok = model_requires_trust_remote_code(str(source_path)) or False
trc_tok = resolve_trust_remote_code(
str(source_path),
requested=trust_remote_code,
console=console,
requires_remote_code=requires_tok,
)
tokenizer = AutoTokenizer.from_pretrained(str(source_path), trust_remote_code=trc_tok)
quant_config = {"zero_point": True, "q_group_size": group_size, "w_bit": bits}
# Load calibration data if provided
calib_data = (
_load_calibration_texts(cal_path, max_samples=calibration_samples)
if cal_path else None
)
console.print(f"[dim]Quantizing to AWQ {bits}-bit (group_size={group_size})...[/]")
if calib_data:
model.quantize(tokenizer, quant_config=quant_config, calib_data=calib_data)
else:
model.quantize(tokenizer, quant_config=quant_config)
console.print("[dim]Saving quantized model...[/]")
model.save_quantized(str(output_path))
tokenizer.save_pretrained(str(output_path))
except Exception as exc:
console.print(f"[red]AWQ export failed:[/] {exc}")
raise typer.Exit(1)
finally:
if merge_dir and merge_dir.exists():
console.print("[dim]Cleaning up temporary merge files...[/]")
shutil.rmtree(merge_dir, ignore_errors=True)
console.print(
Panel(
f"Output: [bold]{output_path}[/]\n"
f"Format: [bold]AWQ {bits}-bit[/]\n\n"
f"Use with vLLM:\n"
f" [bold]from vllm import LLM[/]\n"
f" [bold]llm = LLM(model='{output_path}', quantization='awq')[/]",
title="[bold green]AWQ Export Complete![/]",
)
)
def _export_gptq(
model_path: Path,
output: Optional[str],
base: Optional[str],
bits: int = 4,
group_size: int = 128,
calibration_data: Optional[str] = None,
calibration_samples: int = 128,
trust_remote_code: bool = False,
) -> None:
"""Export model to GPTQ format via auto-gptq."""
# Validate bits
valid_bits = {4, 8}
if bits not in valid_bits:
console.print(
f"[red]Invalid --bits {bits}. Must be one of: {sorted(valid_bits)}[/]"
)
raise typer.Exit(1)
# Validate output path (security: path traversal protection)
validated_output = _validate_output_path(output)
# Validate calibration path (security: path traversal protection)
cal_path = _validate_calibration_path(calibration_data)
try:
from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
except ImportError:
console.print(
"[red]auto-gptq not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[gptq]\"[/]\n"
"Or directly: [bold]pip install auto-gptq[/]"
)
raise typer.Exit(1)
from transformers import AutoTokenizer
# Check if LoRA adapter — merge first
adapter_config_path = model_path / "adapter_config.json"