Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
94 commits
Select commit Hold shift + click to select a range
c06fa19
Studio: add opt-in vLLM and SGLang inference engines
oobabooga Sep 21, 2026
42e5c51
Studio: extend optional engines with vision, precision and parallel m…
oobabooga Sep 21, 2026
a67b8f1
Studio: allow loading explicitly restored inference engines
oobabooga Sep 21, 2026
5b6e9f8
Studio: support tool calling with managed inference engines
oobabooga Sep 21, 2026
3960bdf
Merge main into feat/studio-opt-in-engines
oobabooga Sep 22, 2026
eec4b11
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 22, 2026
c38665c
Restore managed engine settings on rollback and launch the normalized…
oobabooga Sep 22, 2026
b3fa171
Run optional engine checks in validate before the picker unloads
oobabooga Sep 22, 2026
26b2bd4
Patch the httpx module the managed tool route imports in its tests
oobabooga Sep 22, 2026
f0d40ad
Fetch remote image URLs in Studio before forwarding them to a managed…
oobabooga Sep 22, 2026
b624522
Give managed engine requests the llama-server first-token deadline
oobabooga Sep 22, 2026
daa5da8
Refuse an outdated engine profile on the backend unless it was restored
oobabooga Sep 22, 2026
5b0c980
Name the text encoding for engine subprocess output and the lease file
oobabooga Sep 22, 2026
21a9b95
Update repository guard tests for the optional engine changes
oobabooga Sep 22, 2026
d4e098a
Merge main into feat/studio-opt-in-engines
oobabooga Sep 23, 2026
bfe7a08
Run optional engines on Studio's PyTorch instead of a separate Python…
oobabooga Sep 23, 2026
bf56a58
Keep the chat GPU claim when a managed engine does not stop on unload
oobabooga Sep 24, 2026
424e26b
Report a managed engine that survives load cancellation and keep it h…
oobabooga Sep 24, 2026
86cfd70
Launch managed engines only on GPUs visible to Studio
oobabooga Sep 24, 2026
2394aa4
Default the engine GPU picker to the first GPU Studio sees
oobabooga Sep 24, 2026
c1649be
Merge main into feat/studio-opt-in-engines
oobabooga Sep 25, 2026
3d563ec
Load a compare pane with its remembered vLLM or SGLang settings
oobabooga Sep 25, 2026
0dffb49
Validate a model switch on the GPUs its load will use
oobabooga Sep 25, 2026
a2c3765
Trim comments in opt-in engine code
danielhanchen Sep 25, 2026
300b507
Send managed engines only data URL images
danielhanchen Sep 25, 2026
3e095cb
Keep engine status probes from failing real engine work
danielhanchen Sep 25, 2026
afb6f34
Give the load-time nvidia-smi probes the same 60s allowance
danielhanchen Sep 25, 2026
b7c2a63
Time out engine startup on silence, not a fixed 15 minutes
danielhanchen Sep 25, 2026
8482d76
Disable vLLM's vendored DeepGEMM when it was built for another Python
danielhanchen Sep 25, 2026
cedc789
Start a model switch without a saved config on the default engine
danielhanchen Sep 25, 2026
4fabd0f
Cache a failed nvidia-smi probe for 5 minutes
danielhanchen Sep 25, 2026
9a8715e
Format the engine switch test
danielhanchen Sep 25, 2026
b8057ec
Give the engine silence test room for a slow interpreter start
danielhanchen Sep 25, 2026
38bc4b0
Never run nvidia-smi inside an engines status poll
danielhanchen Sep 25, 2026
6ca8706
Run the malware and remote-code consent gates before a managed engine…
danielhanchen Sep 25, 2026
11c6df2
Treat saved vLLM/SGLang targets as managed in image checks
danielhanchen Sep 25, 2026
ec7c160
Let the legacy model_id-only delete clear a saved engine choice
danielhanchen Sep 25, 2026
c9ac7d8
Merge main into feat/studio-opt-in-engines
danielhanchen Sep 25, 2026
0f6207d
Reap a crashed engine before engine status, install, repair or removal
danielhanchen Sep 25, 2026
5250577
Count managed-engine tokens when reasoning_effort is "none"
danielhanchen Sep 25, 2026
3412f23
Tighten engine comments
danielhanchen Sep 25, 2026
d8ea265
Merge main into feat/studio-opt-in-engines
danielhanchen Sep 26, 2026
f602f83
Share Studio's PyTorch with engines installed from the PyTorch index
danielhanchen Sep 26, 2026
59a5f65
Keep each engine environment's FlashInfer JIT cache inside it
danielhanchen Sep 26, 2026
0c3c2e9
Hide Studio's NVFP4 FlashInfer from shared engine environments
danielhanchen Sep 26, 2026
dc683cf
Give engines the locked pip nvcc for FlashInfer JIT on driver-only hosts
danielhanchen Sep 26, 2026
b226fc6
Download only what Studio lacks: reuse its accepted versions, fetch F…
danielhanchen Sep 26, 2026
0e061d6
Require glibc 2.35 for vLLM, whose wheel is manylinux_2_35
danielhanchen Sep 26, 2026
0513f1e
Update engines to vLLM 0.26.0 and SGLang 0.5.17
danielhanchen Sep 26, 2026
0417f6c
Keep TorchAO precisions working on the upgraded engines
danielhanchen Sep 26, 2026
511e5fe
Merge remote-tracking branch 'origin/main' into r11491
danielhanchen Sep 27, 2026
6e6fedb
Accept a text response_format on managed engines and name audio model…
danielhanchen Sep 27, 2026
8f8beca
Merge remote-tracking branch 'origin/main' into r11491
danielhanchen Sep 28, 2026
3df4446
Merge remote-tracking branch 'origin/main' into r11491
danielhanchen Sep 28, 2026
e1a7439
Serve managed-engine n > 1 one choice at a time, reap an engine a can…
danielhanchen Sep 28, 2026
916e2e3
Report the public model id on managed-engine tool responses
danielhanchen Sep 28, 2026
4af4116
Serve a tool catalog with tool_choice none as plain chat on models wi…
danielhanchen Sep 28, 2026
fdf3502
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 28, 2026
c1d084d
Store only non-default engine fields in model overrides, so an all-de…
danielhanchen Sep 29, 2026
abeaca9
Refuse to start training while a managed engine that failed to stop s…
danielhanchen Sep 29, 2026
7c0c000
Pass the engine key in the environment and guard every vLLM route wit…
danielhanchen Sep 29, 2026
5acac1d
Reuse Studio's TorchAO for engines only at the version the adapter co…
danielhanchen Sep 29, 2026
571a37c
Leave engine-specific VRAM headroom measured on a 24 GB card
danielhanchen Sep 29, 2026
c9e9a10
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 29, 2026
36c20fc
Merge main into feat/studio-opt-in-engines
danielhanchen Sep 29, 2026
08d934f
Keep the NVIDIA driver's library path for managed engines and their i…
danielhanchen Sep 29, 2026
5f6a726
Revert the driver library path change; it moves to its own PR
danielhanchen Sep 29, 2026
3be719c
Merge main into feat/studio-opt-in-engines
danielhanchen Oct 1, 2026
7d82b0f
Engines: lock a release per Studio PyTorch (vLLM 0.30 / SGLang 0.5.20…
danielhanchen Oct 1, 2026
197d96f
SGLang 0.5.18+: run without --torchao-config and refuse load-time INT…
danielhanchen Oct 1, 2026
7c419a1
Precision picker: disable INT8 and 4-bit for SGLang releases without …
danielhanchen Oct 1, 2026
d070583
SGLang 0.5.18+: disable CUDA graphs with the per-phase backend flags
danielhanchen Oct 1, 2026
54b15c0
Merge main into feat/studio-opt-in-engines
danielhanchen Oct 1, 2026
6899423
Merge remote-tracking branch 'origin/main' into r11491
danielhanchen Oct 2, 2026
24dd21e
Engines: skip CUTLASS DSL's CUDA 12 libraries, which a driver 580 hos…
danielhanchen Oct 2, 2026
ea82f00
unsloth run: --engine vllm|sglang serves through an optional engine, …
danielhanchen Oct 2, 2026
5915028
Engines: share nvcc's headers only at the locked release, so FlashInf…
danielhanchen Oct 2, 2026
55df9b3
Engines: take nvcc and its headers from one release, all from Studio …
danielhanchen Oct 2, 2026
a900d9f
Reaping a crashed engine also drops its chat GPU claim and shared res…
danielhanchen Oct 2, 2026
2b03e2d
Shared engines: keep the engine's nvidia tree first when Studio's sit…
danielhanchen Oct 2, 2026
22019df
Engines: an INT4 / INT8 SGLang cannot convert resets on switching and…
danielhanchen Oct 2, 2026
3badbb7
Engines: CUDA runtime headers travel with nvcc, so a shared engine ne…
danielhanchen Oct 2, 2026
3632693
unsloth run --engine: a restored engine loads as is
danielhanchen Oct 2, 2026
feb9ac1
Engines: one merged CUDA include tree, so Studio headers pick up the …
danielhanchen Oct 2, 2026
bc06998
Engines: keep a share of large GPUs free for vLLM's sampler warmup
danielhanchen Oct 2, 2026
829ce71
Engines: keep the current-date note on rebuilt managed-engine messages
danielhanchen Oct 2, 2026
1c03ce1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 2, 2026
c5d783b
Model picker: keep GGUF row badges aligned with rows that have the se…
danielhanchen Oct 2, 2026
edc9f42
Engines: validate the INT4 a legacy load_in_4bit request becomes, bef…
danielhanchen Oct 2, 2026
0c6c6a0
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 2, 2026
4757676
Engines: keep lock files byte-exact on Windows clones; mark Linux-onl…
danielhanchen Oct 2, 2026
ee2c279
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 2, 2026
95df13b
Engines: install-machinery tests are Linux engine-host tests
danielhanchen Oct 2, 2026
246a61b
Merge main into feat/studio-opt-in-engines
danielhanchen Oct 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
unsloth run: --engine vllm|sglang serves through an optional engine, …
…installed on first use after a confirmation
  • Loading branch information
danielhanchen committed Oct 2, 2026
commit ea82f00dd600f6d3cbfbd3e6194b2808efdd5858
92 changes: 91 additions & 1 deletion unsloth_cli/commands/studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -1673,6 +1673,8 @@ def _load_model_via_http(
llama_extra_args: Optional[List[str]] = None,
timeout: int = 600,
request_host: str = "127.0.0.1",
engine: str = "auto",
engine_precision: str = "auto",
) -> dict:
import json
import urllib.request
Expand All @@ -1698,6 +1700,9 @@ def _load_model_via_http(
payload["spec_draft_n_max"] = spec_draft_n_max
if llama_extra_args:
payload["llama_extra_args"] = list(llama_extra_args)
if engine != "auto":
payload["engine"] = engine
payload["engine_precision"] = engine_precision

data = json.dumps(payload).encode()
url = f"http://{_url_host(request_host)}:{port}/api/inference/load"
Expand All @@ -1723,6 +1728,56 @@ def _load_model_via_http(
raise RuntimeError(f"Model load failed (HTTP {exc.code}): {body}") from exc


def _ensure_engine_installed(engine: str, yes: bool, silent: bool) -> None:
"""Install an optional serving engine on first use, only after the owner agrees."""
import time

from core.inference import engine_install

# status() answers "still checking" while the GPU probe runs; this caller can wait for it.
reason = engine_install.support_reason(engine)
if reason:
raise RuntimeError(reason)
row = engine_install.status(engine)
if row.get("current"):
return
size = row.get("download_bytes")
action = "Update" if row.get("installed") else "Install"
question = f"{action} {engine} {row['version']}" + (
f" (about {size / 1024**3:.1f} GiB to download)" if size else ""
)
notice = _engine_install_notice(engine, row)
if not yes:
if not sys.stdin.isatty():
raise RuntimeError(
f"{engine} is not installed. Re-run with --yes to install it, or install it "
"from Settings > Inference engines."
)
if notice:
typer.echo(notice)
if not typer.confirm(f"{question}?", default = False):
raise RuntimeError(f"{engine} was not installed, so the model was not loaded.")
elif not silent:
typer.echo(f"{question}: --yes given, installing.")
engine_install.start_install(engine)
last = None
while True:
job = engine_install.status(engine)["job"]
if job.get("state") != "running":
break
message = job.get("message") or job.get("phase")
if message != last and not silent:
typer.echo(f" {engine}: {message}")
last = message
time.sleep(2)
if job.get("state") != "success":
raise RuntimeError(f"{engine} installation did not finish: {job.get('message')}")


def _engine_install_notice(engine: str, row: dict) -> Optional[str]:
return None


def _format_context_length_line(load_result: dict) -> Optional[str]:
value = load_result.get("context_length")
if isinstance(value, bool):
Expand Down Expand Up @@ -2406,6 +2461,22 @@ def run(
"decode speed, MoE usually don't."
),
),
engine: Literal["auto", "vllm", "sglang"] = typer.Option(
"auto",
"--engine",
rich_help_panel = _RUN_PANEL_MODEL,
help = (
"Serve a safetensors model with vLLM or SGLang instead of Studio's default "
"backend. Installed on first use after a confirmation (--yes skips it); "
"Linux NVIDIA, or Windows through WSL2."
),
),
engine_precision: Literal["auto", "bf16", "fp16", "int4", "int8", "fp8"] = typer.Option(
"auto",
"--engine-precision",
rich_help_panel = _RUN_PANEL_MODEL,
help = "Weight precision for --engine vllm/sglang (auto keeps the checkpoint's).",
),
start_api_key_marker: bool = typer.Option(
False,
"--start-api-key-marker",
Expand Down Expand Up @@ -2477,7 +2548,9 @@ def run(
# Set before any re-exec. --log-verbose keeps llama-server's own -v passthrough working.
if verbose:
_enable_verbose_access_logs()
if not any(a in ("--verbose", "-v", "--log-verbose") for a in extra_llama_args):
if engine == "auto" and not any(
a in ("--verbose", "-v", "--log-verbose") for a in extra_llama_args
):
extra_llama_args.append("--log-verbose")
if disable_dns_pinning:
os.environ["UNSLOTH_STUDIO_DISABLE_DNS_PINNING"] = "1"
Expand Down Expand Up @@ -2520,6 +2593,13 @@ def run(
raise typer.Exit(1)
model = parsed_repo
gguf_variant = gguf_variant or embedded_variant
if engine != "auto" and (gguf_variant or extra_llama_args):
typer.echo(
f"Error: --engine {engine} serves safetensors checkpoints; GGUF variants and "
"llama-server flags apply only to the default backend.",
err = True,
)
raise typer.Exit(2)

_require_bind_host(host)

Expand Down Expand Up @@ -2668,6 +2748,8 @@ def run(
args.append("--no-cloudflare")
args.append("--secure" if secure else "--no-secure")
args.append("--tensor-parallel" if tensor_parallel else "--no-tensor-parallel")
if engine != "auto":
args.extend(["--engine", engine, "--engine-precision", engine_precision])
if verbose:
args.append("--verbose")
if extra_llama_args:
Expand Down Expand Up @@ -2739,6 +2821,12 @@ def run(
typer.echo(f"UNSLOTH_START_PORT: {actual_port}")
typer.echo(f"UNSLOTH_START_API_KEY: {api_key}")

if engine != "auto":
try:
_ensure_engine_installed(engine, yes, silent)
except RuntimeError as exc:
typer.echo(f"Error: {exc}", err = True)
raise typer.Exit(1)
if not silent:
typer.echo(f"Loading model: {model}...")
try:
Expand All @@ -2755,6 +2843,8 @@ def run(
spec_draft_n_max = spec_draft_n_max,
llama_extra_args = extra_llama_args,
request_host = request_host,
engine = engine,
engine_precision = engine_precision,
)
except RuntimeError as exc:
typer.echo(f"Error: {exc}", err = True)
Expand Down
161 changes: 161 additions & 0 deletions unsloth_cli/tests/test_studio_run_engine_flag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""`unsloth run --engine vllm|sglang`: the load payload, re-exec forwarding, and the
install-on-first-use consent."""

from __future__ import annotations

import inspect
import sys
import types
from pathlib import Path

import pytest
import typer

_REPO_ROOT = Path(__file__).resolve().parents[2]
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))

from unsloth_cli.commands import studio as studio_mod


def test_engine_options_are_registered_on_run():
sig = inspect.signature(studio_mod.run)
assert set(sig.parameters["engine"].default.param_decls) == {"--engine"}
assert sig.parameters["engine"].default.default == "auto"
assert set(sig.parameters["engine_precision"].default.param_decls) == {"--engine-precision"}


def test_reexec_forwards_the_engine():
src = inspect.getsource(studio_mod.run)
assert 'args.extend(["--engine", engine, "--engine-precision", engine_precision])' in src


def _capture_payload(monkeypatch, **kwargs):
seen = {}

class _Resp:
def __enter__(self):
return self

def __exit__(self, *a):
return False

def read(self):
return b'{"status": "loaded", "model": "m"}'

def fake_urlopen(req, timeout = None):
import json
seen.update(json.loads(req.data))
return _Resp()

monkeypatch.setattr(studio_mod, "_direct_urlopen", fake_urlopen)
import unsloth_cli._inference as inf

monkeypatch.setattr(inf, "raise_for_deferred_error", lambda url, body: body)
monkeypatch.setattr(inf, "require_completed_padded_body", lambda url, body: body)
studio_mod._load_model_via_http(8888, "k", "m", None, 4096, False, **kwargs)
return seen


def test_default_load_payload_has_no_engine(monkeypatch):
payload = _capture_payload(monkeypatch)
assert "engine" not in payload and "engine_precision" not in payload


def test_engine_load_payload(monkeypatch):
payload = _capture_payload(monkeypatch, engine = "vllm", engine_precision = "fp8")
assert payload["engine"] == "vllm" and payload["engine_precision"] == "fp8"


class _FakeInstall:
def __init__(
self,
row,
finish = "success",
):
self.row = dict(row)
self.started = 0
self.finish = finish

def status(self, engine):
job = {"state": self.finish if self.started else "idle", "message": "done"}
return {**self.row, "job": job}

def support_reason(self, engine):
return self.row["unsupported_reason"]

def start_install(self, engine):
self.started += 1
return self.status(engine)


@pytest.fixture
def fake_install(monkeypatch):
def make(row, finish = "success"):
fake = _FakeInstall(row, finish)
core = types.ModuleType("core")
inference = types.ModuleType("core.inference")
inference.engine_install = fake
core.inference = inference
monkeypatch.setitem(sys.modules, "core", core)
monkeypatch.setitem(sys.modules, "core.inference", inference)
monkeypatch.setitem(sys.modules, "core.inference.engine_install", fake)
return fake

return make


_MISSING = {
"version": "0.30.0",
"installed": False,
"current": False,
"unsupported_reason": None,
"download_bytes": 1073741824,
}


def test_installed_engine_is_not_reinstalled(fake_install):
fake = fake_install({**_MISSING, "installed": True, "current": True})
studio_mod._ensure_engine_installed("vllm", yes = False, silent = True)
assert fake.started == 0


def test_missing_engine_without_a_terminal_needs_yes(fake_install, monkeypatch):
fake = fake_install(_MISSING)
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
with pytest.raises(RuntimeError, match = "--yes"):
studio_mod._ensure_engine_installed("vllm", yes = False, silent = True)
assert fake.started == 0


def test_declined_prompt_installs_nothing(fake_install, monkeypatch):
fake = fake_install(_MISSING)
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
asked = []
monkeypatch.setattr(typer, "confirm", lambda text, default = False: asked.append(text) or False)
with pytest.raises(RuntimeError, match = "not installed"):
studio_mod._ensure_engine_installed("vllm", yes = False, silent = True)
assert fake.started == 0
assert asked == ["Install vllm 0.30.0 (about 1.0 GiB to download)?"]


def test_yes_installs_and_waits(fake_install):
fake = fake_install(_MISSING)
studio_mod._ensure_engine_installed("vllm", yes = True, silent = True)
assert fake.started == 1


def test_failed_install_is_an_error(fake_install):
fake_install(_MISSING, finish = "error")
with pytest.raises(RuntimeError, match = "did not finish"):
studio_mod._ensure_engine_installed("vllm", yes = True, silent = True)


def test_unsupported_host_is_refused_before_installing(fake_install):
fake = fake_install({**_MISSING, "unsupported_reason": "vLLM needs an NVIDIA GPU."})
with pytest.raises(RuntimeError, match = "NVIDIA"):
studio_mod._ensure_engine_installed("vllm", yes = True, silent = True)
assert fake.started == 0