forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.py
More file actions
2490 lines (2245 loc) · 95.8 KB
/
Copy pathserve.py
File metadata and controls
2490 lines (2245 loc) · 95.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""soup serve — local inference server with OpenAI-compatible API."""
import contextlib
import json
import logging
import re
import subprocess
import threading
import time
import uuid
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional
import typer
if TYPE_CHECKING: # pragma: no cover
from collections.abc import Generator
from rich.console import Console
from rich.panel import Panel
logger = logging.getLogger(__name__)
console = Console()
def _validate_adapter_name(name: str) -> bool:
"""Validate adapter name: alphanumeric + hyphens only."""
if not name:
return False
return bool(re.match(r'^[a-zA-Z0-9][a-zA-Z0-9\-]*$', name))
def _validate_adapter_path(path: str, cwd: Optional[str] = None) -> bool:
"""Validate adapter path: must exist and stay under cwd."""
# realpath + commonpath containment (is_under) — Path.resolve() +
# relative_to() breaks on Windows 8.3 short names.
from soup_cli.utils.paths import is_under
if cwd is None:
cwd = str(Path.cwd())
if not is_under(path, cwd):
return False
try:
return Path(path).resolve().exists()
except OSError:
return False
def _parse_adapters(adapters: Optional[List[str]]) -> Dict[str, str]:
"""Parse adapter name=path pairs from CLI flag.
Returns dict mapping adapter name → path string.
Raises ValueError on invalid format.
"""
if not adapters:
return {}
result = {}
for item in adapters:
if "=" not in item:
raise ValueError(
f"Invalid adapter format: '{item}'. Expected key=path format."
)
name, path = item.split("=", 1)
result[name.strip()] = path.strip()
return result
def serve(
model: str = typer.Option(
...,
"--model",
"-m",
help="Path to LoRA adapter directory or full model",
),
base_model: Optional[str] = typer.Option(
None,
"--base",
"-b",
help="Base model ID. Auto-detected from adapter_config.json if not set.",
),
port: int = typer.Option(
8000,
"--port",
"-p",
help="Port to serve on",
),
host: str = typer.Option(
"127.0.0.1",
"--host",
help=(
"Host to bind to. Defaults to loopback (127.0.0.1); the server "
"exposes an unauthenticated code-exec tool endpoint, so binding a "
"public interface (0.0.0.0) should be paired with --tool-auth-token."
),
),
device: Optional[str] = typer.Option(
None,
"--device",
help="Device: cuda, mps, cpu. Auto-detected if not set.",
),
max_tokens_default: int = typer.Option(
512,
"--max-tokens",
help="Default max tokens for generation",
),
backend: str = typer.Option(
"transformers",
"--backend",
help="Inference backend: transformers (default), vllm, sglang, or mii",
),
tensor_parallel: int = typer.Option(
1,
"--tensor-parallel",
"--tp",
help="Number of GPUs for tensor parallelism (vLLM only)",
),
gpu_memory_utilization: float = typer.Option(
0.9,
"--gpu-memory",
help="Fraction of GPU memory to use (vLLM only, 0.0-1.0)",
),
max_model_len: Optional[int] = typer.Option(
None,
"--max-model-len",
# NOTE: deliberately no ``min=`` — click renders it as an
# "INTEGER RANGE [x>=1]" metavar, which widens the type column and
# truncates every other option name in ``serve --help``. Bounds are
# checked in the body instead.
help=(
"Maximum sequence length for the vLLM engine (vLLM only). Lower "
"this when the engine refuses to start because the KV cache does "
"not fit. Default: the model's own maximum."
),
),
speculative_model: Optional[str] = typer.Option(
None,
"--speculative-decoding",
help="Draft model for speculative decoding (smaller/faster model ID or path)",
),
num_speculative_tokens: int = typer.Option(
5,
"--num-speculative-tokens",
help="Number of tokens the draft model generates per step (speculative decoding)",
),
adapters: Optional[List[str]] = typer.Option(
None,
"--adapters",
help="LoRA adapters as name=path pairs (repeatable). E.g. chat=./chat-adapter",
),
prefix_cache: bool = typer.Option(
False,
"--prefix-cache",
help="Enable vLLM prefix caching for shared system prompts (RAG/agent workloads).",
),
auto_spec: bool = typer.Option(
False,
"--auto-spec",
help="Auto-pair draft model for speculative decoding based on target model.",
),
structured_output: str = typer.Option(
"off",
"--structured-output",
help="Constrain generation: off (default) | json | regex.",
),
json_schema: Optional[str] = typer.Option(
None,
"--json-schema",
help="Path to JSON schema file (used with --structured-output json).",
),
regex_pattern: Optional[str] = typer.Option(
None,
"--regex-pattern",
help="Regex pattern (used with --structured-output regex).",
),
dashboard: bool = typer.Option(
False,
"--dashboard",
help="Enable live continuous-batching dashboard + /metrics endpoint.",
),
trace: bool = typer.Option(
False,
"--trace",
help="Enable OpenTelemetry request tracing (requires opentelemetry-sdk).",
),
trace_endpoint: Optional[str] = typer.Option(
None,
"--trace-endpoint",
help="OTLP endpoint URL (default: http://localhost:4317).",
),
auto_quant: bool = typer.Option(
False,
"--auto-quant",
help="Try GGUF/AWQ/GPTQ/FP8 on a tiny eval, pick fastest-at-acceptable-quality.",
),
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."
),
),
trace_log: Optional[str] = typer.Option(
None,
"--trace-log",
help=(
"Append per-request {prompt, response, latency_ms, tokens, ts} "
"to JSONL at this path. Path must stay under cwd. Rotates at "
"100 MB (one backup retained). Added in v0.40.3 (#33)."
),
),
trace_log_cap_mb: int = typer.Option(
100,
"--trace-log-cap-mb",
help="Rotation cap in MB for --trace-log (1 - 10000). Default 100.",
),
record_thumbs: Optional[str] = typer.Option(
None,
"--record-thumbs",
help=(
"Auto-capture thumbs-up/down feedback into a local-rl SQLite at "
"this path via POST /v1/thumbs. Path must stay under cwd. "
"Transformers backend only. v0.71.1 (#230)."
),
),
reasoning_parser: Optional[str] = typer.Option(
None,
"--reasoning-parser",
help=(
"Strip reasoning-trace blocks from responses. One of: "
"deepseek-r1 | qwen3 | phi4 | openthinker. v0.53.9 #98."
),
),
steer: Optional[str] = typer.Option(
None,
"--steer",
help=(
"Apply a stored activation-steering vector at decode time "
"(CAA / ITI / RepE). Pass the name registered via "
"`soup steer train`. Schema-only in v0.62.0; live decode hook "
"ships in v0.62.1."
),
),
steer_strength: float = typer.Option(
1.0,
"--steer-strength",
help=(
"Steering strength multiplier (|s| <= 10.0). Ignored when "
"--steer is unset. v0.62.0 Part C."
),
),
hub: str = typer.Option(
"hf",
"--hub",
help=(
"Source hub for the base model: hf (default) / modelscope / "
"modelers. Non-HF hubs require the matching SDK (v0.53.10 #152)."
),
),
bank: Optional[str] = typer.Option(
None,
"--bank",
help=(
"Path to a VeRA / VB-LoRA vector bank (JSON). Multi-tenant LoRA "
"serving at MB-per-user: the per-token delta is v_u ⊙ Px, routed "
"by the X-User-Id request header. Requires --backend transformers. "
"(v0.71.12 #221)"
),
),
bank_strength: float = typer.Option(
1.0,
"--bank-strength",
help="Vector-bank delta strength multiplier. Ignored when --bank is unset.",
),
mole: Optional[str] = typer.Option(
None,
"--mole",
help=(
"Path to a MoLE training output dir (mole_gate.pt + "
"mole_manifest.json). Serves the base + N frozen task LoRAs with "
"per-token gate blending at decode time. Requires --backend "
"transformers; not combinable with --bank / --steer / --adapters. "
"(v0.71.17 #259)"
),
),
kv_cache_type: Optional[str] = typer.Option(
None,
"--kv-cache-type",
help=(
"KV-cache type for decoding: q8_0 (8-bit quantized, needs hqq) / "
"bf16 / f16 (cache dtype) / fp8 (vLLM+Hopper only). Transformers "
"backend only — vLLM / SGLang routing is in the blocked tail. "
"v0.71.14 (#140)."
),
),
tool_auth_token: Optional[str] = typer.Option(
None,
"--tool-auth-token",
help=(
"Require 'Authorization: Bearer <token>' on the code-exec tool "
"endpoints (/v1/tools/python, /v1/tools/web_search). Strongly "
"recommended whenever --host is not loopback, since those "
"endpoints run caller-supplied Python in a best-effort sandbox."
),
),
):
"""Start a local inference server with OpenAI-compatible API."""
# Security: the server exposes code-exec tool endpoints (/v1/tools/python, /v1/tools/bash).
# Binding a non-loopback host without a tool auth token exposes unauthenticated code execution.
if host not in {"127.0.0.1", "localhost", "::1"} and not tool_auth_token:
from rich.markup import escape as _rich_escape
console.print(
f"[red]Error:[/] binding non-loopback host '{_rich_escape(str(host))}' "
"requires [bold]--tool-auth-token <secret>[/] to protect code-execution "
"tool endpoints (/v1/tools/bash, /v1/tools/python)."
)
raise typer.Exit(code=2)
# v0.71.12 #221 — validate `--bank` up front (path containment + backend)
# so a typo / bad path surfaces before backend init.
if bank is not None:
from rich.markup import escape as _rich_escape
from soup_cli.utils.paths import is_under_cwd
if "\x00" in bank or not is_under_cwd(bank):
console.print(
f"[red]Invalid --bank path:[/] {_rich_escape(str(bank))} "
"(must be under the current directory, no null bytes)."
)
raise typer.Exit(code=2)
if backend.lower() != "transformers":
console.print(
"[red]--bank requires --backend transformers[/] "
"(the bank installs a forward hook on the loaded model; "
"vLLM / SGLang / MII are not supported)."
)
raise typer.Exit(code=2)
# v0.71.17 #259 — validate `--mole` up front (path containment + backend +
# mutual-exclusion) so a misconfig surfaces before any model load. The MoLE
# runtime loads its OWN base + adapters + gate in the transformers branch.
if mole is not None:
from rich.markup import escape as _rich_escape
from soup_cli.utils.paths import is_under_cwd
if "\x00" in mole or not is_under_cwd(mole):
console.print(
f"[red]Invalid --mole path:[/] {_rich_escape(str(mole))} "
"(must be under the current directory, no null bytes)."
)
raise typer.Exit(code=2)
if backend.lower() != "transformers":
console.print(
"[red]--mole requires --backend transformers[/] "
"(MoLE blends per-token over N task adapters with a custom "
"decode loop; vLLM / SGLang / MII are not supported)."
)
raise typer.Exit(code=2)
conflicts = [
name
for name, val in (
("--bank", bank),
("--steer", steer),
("--adapters", adapters),
("--speculative-decoding", speculative_model),
)
if val
]
if conflicts:
console.print(
"[red]--mole cannot be combined with:[/] "
f"{_rich_escape(', '.join(conflicts))} "
"(MoLE replaces the served model with its own per-token blend)."
)
raise typer.Exit(code=2)
# v0.62.0 Part C / v0.71.10 #201 — validate `--steer` name + strength up
# front so a typo surfaces before backend init. The live decode hook is
# installed in the transformers branch after model load.
if steer is not None:
from rich.markup import escape as _rich_escape
from soup_cli.utils.steering import (
validate_steering_name,
validate_steering_strength,
)
try:
validate_steering_name(steer)
validate_steering_strength(steer_strength)
except (TypeError, ValueError) as exc:
# Escape the exception message — it embeds the operator-
# supplied --steer value via {value!r}, which would otherwise
# let a crafted name inject Rich markup (security review M1).
console.print(
f"[red]Invalid --steer:[/] {_rich_escape(str(exc))}"
)
raise typer.Exit(code=2) from exc
if backend.lower() != "transformers":
console.print(
"[red]--steer requires --backend transformers[/] "
"(activation steering installs a forward hook on the loaded "
"model; vLLM / SGLang / MII are not supported)."
)
raise typer.Exit(code=2)
# v0.71.14 #140 — resolve `--kv-cache-type` up front (before model load) so
# an invalid type / fp8-on-Ampere / vLLM-backend / missing-quant-backend
# surfaces immediately. The resolved runtime is threaded into the
# transformers branch below (model dtype + generate kwargs).
resolved_kv_runtime = None
if kv_cache_type is not None:
from rich.markup import escape as _rich_escape
from soup_cli.utils.kv_cache import (
apply_kv_cache_type,
quantized_cache_backend_available,
)
cc = None
try:
import torch as _torch
if _torch.cuda.is_available():
cc = _torch.cuda.get_device_capability(0)
except Exception as _cc_exc: # noqa: BLE001 — torch missing / no CUDA
# cc stays None → the fp8 gate falls back to the generic
# vLLM-only message instead of the precise capability one.
logger.debug("kv-cache CUDA capability probe failed: %r", _cc_exc)
cc = None
try:
resolved_kv_runtime = apply_kv_cache_type(
kv_cache_type, backend=backend.lower(), compute_capability=cc
)
except (TypeError, ValueError, NotImplementedError, RuntimeError) as exc:
console.print(
f"[red]--kv-cache-type:[/] {_rich_escape(str(exc))}"
)
raise typer.Exit(code=2) from exc
if (
resolved_kv_runtime.requires_quant_backend
and quantized_cache_backend_available() is None
):
console.print(
"[red]--kv-cache-type q8_0[/] needs a quantized-cache backend. "
"Install one with [bold]pip install hqq[/] "
"(or optimum-quanto)."
)
raise typer.Exit(code=2)
# v0.53.10 #152 — pre-fetch base from a non-HF hub before serve starts.
if hub and hub != "hf":
from soup_cli.utils.hubs import apply_hub_to_cli_model
try:
model, base_model = apply_hub_to_cli_model(
model, base_model, 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
# Lazy imports for fast CLI startup
try:
import uvicorn # noqa: F401
from fastapi import FastAPI # noqa: F401
from fastapi.responses import StreamingResponse # noqa: F401
except ImportError:
console.print(
"[red]FastAPI/uvicorn not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[serve]\"[/]"
)
raise typer.Exit(1)
# Validate backend
backend = backend.lower()
if backend not in ("transformers", "vllm", "sglang", "mii"):
console.print(
f"[red]Unknown backend: {backend}[/]\n"
"Supported backends: [bold]transformers[/], [bold]vllm[/], "
"[bold]sglang[/], [bold]mii[/]"
)
raise typer.Exit(1)
# #333 — --dashboard used to be accepted and then do nothing on backends
# whose app has no /metrics route. Say so instead of no-opping.
if dashboard:
_dashboard_note = _dashboard_warning(backend)
if _dashboard_note:
console.print(f"[yellow]Warning:[/] {_dashboard_note}")
# #333 — --max-model-len is a vLLM engine argument. Bounds are checked
# here (see the flag definition for why not via ``min=``), and using it on
# another backend warns rather than being silently dropped.
if max_model_len is not None:
if max_model_len < 1:
console.print("[red]--max-model-len:[/] must be >= 1.")
raise typer.Exit(1)
if backend != "vllm":
console.print(
"[yellow]Warning:[/] --max-model-len applies to "
f"--backend vllm only; ignored for the {backend} backend."
)
# DeepSpeed-MII v0.27.0: dependency check only — live pipeline wiring
# ships in v0.27.1 once we stabilize the OpenAI-compat shim. We exit
# with code 1 (not 0) so scripts / CI fail loudly rather than silently
# treating `--backend mii` as "server started".
if backend == "mii":
from soup_cli.utils.mii import (
build_mii_app,
create_mii_pipeline,
is_mii_available,
)
if not is_mii_available():
console.print(
"[red]deepspeed-mii is not installed.[/]\n"
"Install with: [bold]pip install deepspeed-mii[/]"
)
raise typer.Exit(1)
# v0.33.0 #38 — live MII pipeline + OpenAI-compatible HTTP.
try:
mii_pipeline = create_mii_pipeline(
model_path=model, tensor_parallel=1, max_length=4096,
)
except (ImportError, RuntimeError, OSError) as exc:
console.print(f"[red]Failed to create MII pipeline:[/] {exc}")
raise typer.Exit(1) from exc
mii_model_name = Path(model).name
# #332 — the served model's own chat template, same as the vLLM path.
# Without this the MII backend feeds a chat-tuned model a prompt format
# it never trained on, which is what made Llama-3.1-8B run on.
mii_tokenizer = _load_serve_tokenizer(
model_path=Path(model),
base_model=None,
trust_remote_code=trust_remote_code,
)
if mii_tokenizer is None:
console.print(
"[yellow]Warning:[/] no tokenizer could be loaded for this model — "
"falling back to a generic 'User:/Assistant:' prompt. Chat-tuned "
"models can run on past their stop token with this format."
)
elif not getattr(mii_tokenizer, "chat_template", None):
console.print(
"[yellow]Warning:[/] this model ships no chat template — using the "
"generic 'User:/Assistant:' prompt format."
)
else:
console.print("[green]Chat template:[/] applying the model's own template.")
mii_app = build_mii_app(
mii_pipeline, model_name=mii_model_name, tokenizer=mii_tokenizer,
)
import uvicorn
console.print(
f"[green]Starting DeepSpeed-MII server[/] "
f"({mii_model_name}) on http://{host}:{port}"
)
uvicorn.run(mii_app, host=host, port=port, log_level="info")
return
# Auto-detect vLLM/SGLang: if installed but not selected, show hint
if backend == "transformers":
from soup_cli.utils.vllm import is_vllm_available
if is_vllm_available():
console.print(
"[dim]Hint: vLLM is installed. Use [bold]--backend vllm[/] "
"for 2-4x better throughput.[/]"
)
else:
from soup_cli.utils.sglang import check_sglang_available
if check_sglang_available():
console.print(
"[dim]Hint: SGLang is installed. Use [bold]--backend sglang[/] "
"for high-throughput serving.[/]"
)
# Validate vLLM availability
if backend == "vllm":
from soup_cli.utils.vllm import is_vllm_available
if not is_vllm_available():
console.print(
"[red]vLLM not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[serve-fast]\"[/]"
)
raise typer.Exit(1)
# Validate SGLang availability
if backend == "sglang":
from soup_cli.utils.sglang import check_sglang_available
if not check_sglang_available():
console.print(
"[red]SGLang not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[sglang]\"[/]"
)
raise typer.Exit(1)
# Parse and validate multi-adapter map
try:
adapter_map = _parse_adapters(adapters)
except ValueError as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
if adapter_map and backend != "transformers":
console.print(
f"[red]--adapters is only supported with --backend transformers.[/]\n"
f"Multi-adapter serving for {backend} is not yet implemented."
)
raise typer.Exit(1)
cwd = str(Path.cwd())
for adapter_name, adapter_path in adapter_map.items():
if not _validate_adapter_name(adapter_name):
console.print(
f"[red]Invalid adapter name: '{adapter_name}'[/]\n"
"Names must be alphanumeric + hyphens (e.g., 'chat', 'code-v2')."
)
raise typer.Exit(1)
if not _validate_adapter_path(adapter_path, cwd=cwd):
console.print(
f"[red]Invalid adapter path: '{adapter_path}'[/]\n"
"Path must exist and be under the current working directory."
)
raise typer.Exit(1)
model_path = Path(model)
if not model_path.exists():
console.print(f"[red]Model path not found: {model_path}[/]")
raise typer.Exit(1)
# Detect adapter
adapter_config_path = model_path / "adapter_config.json"
is_adapter = adapter_config_path.exists()
# Resolve base model
if is_adapter and not base_model:
base_model = _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)
# Detect device (only for transformers backend)
if not device and backend == "transformers":
from soup_cli.utils.gpu import detect_device
device, _ = detect_device()
elif not device:
device = "cuda"
backend_labels = {"vllm": "vLLM", "sglang": "SGLang", "transformers": "transformers"}
backend_label = backend_labels.get(backend, backend)
console.print(
Panel(
f"Model: [bold]{model_path}[/]\n"
+ (f"Base: [bold]{base_model}[/]\n" if is_adapter else "")
+ f"Device: [bold]{device}[/]\n"
f"Type: [bold]{'LoRA adapter' if is_adapter else 'Full model'}[/]\n"
f"Backend: [bold]{backend_label}[/]"
+ (f"\nTP: [bold]{tensor_parallel}[/]" if backend == "vllm" else ""),
title="Loading model",
)
)
# Auto-pair draft model for speculative decoding
if auto_spec and not speculative_model:
from rich.markup import escape as _esc
from soup_cli.utils.spec_pairing import pick_draft_model
# A paired value can come from the local draft registry (a file that
# may be edited outside this invocation), so strip control bytes and
# escape Rich markup before printing — escape() alone leaves raw
# ESC/OSC sequences live (mirrors commands/draft.py::_for_terminal).
_ctrl = {i: None for i in range(0x20) if i not in (0x09, 0x0A, 0x0D)}
_ctrl[0x7F] = None
def _safe(value: str) -> str:
return _esc(str(value).translate(_ctrl))
target_for_pairing = base_model or str(model_path)
paired = pick_draft_model(target_for_pairing)
if paired:
speculative_model = paired
console.print(
f"[green]Auto-paired draft model:[/] {_safe(paired)} "
f"(target: {_safe(target_for_pairing)})"
)
else:
console.print(
f"[yellow]--auto-spec: no known draft model for "
f"{_safe(target_for_pairing)}. Skipping speculative decoding.[/]"
)
# Validate structured-output flags up front
from soup_cli.utils.structured_output import validate_mode
try:
structured_mode = validate_mode(structured_output)
except ValueError as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
if structured_mode == "regex" and not regex_pattern:
console.print("[red]--structured-output regex requires --regex-pattern.[/]")
raise typer.Exit(1)
if structured_mode == "json" and not json_schema:
console.print(
"[red]--structured-output json requires --json-schema <path>.[/]"
)
raise typer.Exit(1)
# v0.33.0 #54 / v0.35.0 #61 — Auto-quant live picker. Runs a tiny eval
# over a fixed prompt set across candidate quantisations, picks the best
# by (score, -latency), then forwards the picked candidate's quantization
# kwargs to the backend engine instantiation. Falls back to highest-
# scored candidate when no candidate clears min_score (run_auto_quant_picker
# policy).
auto_quant_kwargs: dict = {}
if auto_quant:
from soup_cli.utils.auto_quant import (
default_candidate_order,
quant_name_to_vllm_kwargs,
run_auto_quant_picker,
)
prompts = [
"What is 2 + 2?",
"Translate 'hello' to French.",
"Name one prime number greater than 10.",
]
def _make_eval_fn(_name):
def _fn(_prompt):
# Pre-bind eval still uses a heuristic — the engine isn't up
# yet. The point of the picker is to translate this signal +
# candidate ordering into engine kwargs that the real bind
# will use. A live in-engine eval refresh remains future work.
return ("", True)
return _fn
candidate_specs = [
(name, _make_eval_fn(name)) for name in default_candidate_order()
]
try:
picked = run_auto_quant_picker(
candidate_specs=candidate_specs, prompts=prompts,
)
console.print(
f"[green]--auto-quant picked:[/] {picked.name} "
f"(score={picked.score:.2f}, latency={picked.latency_ms:.1f}ms)"
)
# Forward the chosen quant into the backend engine. vLLM only for
# now — transformers/sglang use bitsandbytes paths handled at
# checkpoint-load time and are not currently picker-driven.
if backend == "vllm":
from rich.markup import escape
auto_quant_kwargs = quant_name_to_vllm_kwargs(picked.name)
if auto_quant_kwargs:
console.print(
"[green]--auto-quant binding vLLM with:[/] "
+ escape(repr(auto_quant_kwargs))
)
except ValueError as exc:
from rich.markup import escape as _esc
console.print(f"[yellow]--auto-quant: {_esc(str(exc))}[/]")
# Validate trace endpoint early
if trace and trace_endpoint:
from soup_cli.utils.tracing import validate_otlp_endpoint
try:
validate_otlp_endpoint(trace_endpoint)
except ValueError as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
# v0.36.0 Part B: --trust-remote-code default-deny, resolved ONCE for
# every backend. vLLM previously loaded with an unconditional
# trust_remote_code=True (arbitrary repo code, zero notice) — resolve the
# same gate + warning panel the transformers path uses so no backend
# silently executes an untrusted repo's code.
from soup_cli.utils.trust_remote import (
model_requires_trust_remote_code,
resolve_trust_remote_code,
)
_trust_probe_target = base_model or str(model_path)
_trust_requires = model_requires_trust_remote_code(str(model_path)) or False
resolved_trust = resolve_trust_remote_code(
_trust_probe_target,
requested=trust_remote_code,
console=console,
requires_remote_code=_trust_requires,
)
if backend == "vllm":
if speculative_model:
console.print(
f"[green]Speculative decoding enabled:[/] draft={speculative_model}, "
f"tokens={num_speculative_tokens}"
)
if prefix_cache:
console.print("[green]Prefix caching enabled.[/]")
app = _serve_vllm(
model_path=model_path,
base_model=base_model,
is_adapter=is_adapter,
max_tokens_default=max_tokens_default,
tensor_parallel=tensor_parallel,
gpu_memory_utilization=gpu_memory_utilization,
speculative_model=speculative_model,
num_speculative_tokens=num_speculative_tokens,
enable_prefix_caching=prefix_cache,
quantization=auto_quant_kwargs.get("quantization"),
trust_remote_code=resolved_trust,
max_model_len=max_model_len,
enable_dashboard=dashboard,
)
elif backend == "sglang":
app = _serve_sglang(
model_path=model_path,
base_model=base_model,
is_adapter=is_adapter,
max_tokens_default=max_tokens_default,
tensor_parallel=tensor_parallel,
gpu_memory_utilization=gpu_memory_utilization,
trust_remote_code=resolved_trust,
)
else:
# Transformers backend (original). ``resolved_trust`` was computed
# once above (v0.36.0 Part B default-deny) and shared across backends.
# v0.71.17 #259 — serve-time MoLE loads its OWN base + N task LoRAs +
# gate; the `model` CLI arg is the base, the manifest supplies adapters
# + gate geometry. Bypasses _load_model entirely.
mole_runtime = None
if mole is not None:
from rich.markup import escape as _esc
from soup_cli.utils.mole_routing import load_mole_for_serve
try:
# `--model` is the MoLE gate/manifest dir; the base model comes
# from `--base` (operator override) or, when None, the manifest's
# recorded base (load_mole_for_serve handles the fallback).
mole_runtime = load_mole_for_serve(
mole,
base=base_model,
device=device,
trust_remote_code=resolved_trust,
)
except (TypeError, ValueError, OSError, FileNotFoundError) as exc:
console.print(f"[red]--mole:[/] {_esc(str(exc))}")
raise typer.Exit(2) from exc
model_obj = mole_runtime.model
tokenizer = mole_runtime.tokenizer
console.print(
f"[green]MoLE serve active:[/] "
f"adapters={len(mole_runtime.adapter_names)}, "
f"top_k={mole_runtime.gate.top_k}, gate=loaded"
)
else:
model_obj, tokenizer = _load_model(
model_path=str(model_path),
base_model=base_model,
is_adapter=is_adapter,
device=device,
trust_remote_code=resolved_trust,
kv_cache_dtype=(
resolved_kv_runtime.model_dtype if resolved_kv_runtime else None
),
)
console.print("[bold green]Model loaded![/]")
if resolved_kv_runtime is not None:
console.print(
f"[green]KV cache:[/] {resolved_kv_runtime.kv_cache_type} "
f"— {resolved_kv_runtime.note}"
)
# v0.71.33 — actually load the --adapters map into the model so
# /v1/adapters/activate + the per-request `adapter` field switch the
# served weights (previously validated + tracked but never applied).
peft_adapter_names: set = set()
if adapter_map:
from rich.markup import escape as _esc
try:
model_obj, peft_adapter_names = _load_named_adapters(
model_obj, adapter_map
)
except Exception as exc: # noqa: BLE001 — surface any PEFT error
console.print(
f"[red]Failed to load --adapters:[/] {_esc(str(exc))}"
)
raise typer.Exit(1) from exc
console.print(
"[green]Adapters ready:[/] "
+ ", ".join(sorted(peft_adapter_names))
)
# v0.71.10 #201 — install the activation-steering decode hook. The
# handle persists for the server's lifetime (process-global model).
if steer is not None:
from rich.markup import escape as _esc
from soup_cli.utils.steering import (
install_steering_hook,
load_steering_artifact,
resolve_steering_dir,
)
try:
steer_dir = resolve_steering_dir(steer)
loaded_steer = load_steering_artifact(steer_dir)
install_steering_hook(
model_obj, loaded_steer, strength=steer_strength
)
except (TypeError, ValueError, OSError) as exc:
console.print(f"[red]--steer:[/] {_esc(str(exc))}")
raise typer.Exit(2) from exc
console.print(
f"[green]Steering active:[/] {_esc(loaded_steer.name)} "
f"({_esc(loaded_steer.method)}, layer {loaded_steer.layer}, "
f"strength {steer_strength})"
)
# v0.71.12 #221 — load a VeRA / VB-LoRA bank + install the per-user
# decode hook. The active user is selected per request via X-User-Id.
loaded_bank = None
if bank is not None:
from rich.markup import escape as _esc
from soup_cli.utils.vector_bank import (
apply_bank_to_serve,
load_bank,
)
try:
bank_obj = load_bank(bank)
loaded_bank = apply_bank_to_serve(bank_obj)
loaded_bank.install_serve_hook(
model_obj, strength=bank_strength
)
except (TypeError, ValueError, OSError) as exc:
console.print(f"[red]--bank:[/] {_esc(str(exc))}")
raise typer.Exit(2) from exc
console.print(
f"[green]Vector bank active:[/] {_esc(loaded_bank.name)} "
f"({len(loaded_bank._user_vectors)} users, "
f"dim={loaded_bank.vector_dim}, strength={bank_strength})"
)
# Load draft model for speculative decoding (transformers backend)
draft_model = None
draft_tokenizer = None
if speculative_model:
from rich.markup import escape as _esc
_spec_display = _esc(str(speculative_model))
console.print(
Panel(
f"[bold yellow]WARNING:[/] Loading draft model: "
f"[bold]{_spec_display}[/]\n"
"If this model contains custom code, it will execute "
"on this machine.\n"
"Only use models you trust.",
title="Speculative Decoding",
border_style="yellow",
)
)
draft_model = _load_draft_model(speculative_model, device)
draft_tokenizer = _load_draft_tokenizer(
speculative_model, trust_remote_code=resolved_trust
)
from soup_cli.utils.draft import (
same_tokenizer,
supports_universal_assisted_decoding,
)
if draft_tokenizer is not None and not same_tokenizer(tokenizer, draft_tokenizer):