Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(sglang): apply the served LoRA adapter on every request (#1724) (#1732)

Batyrkhan3cef6003cfc8
diff --git a/changelog.d/0.76.0/1732.fixed.md b/changelog.d/0.76.0/1732.fixed.md
new file mode 100644
index 00000000..bb0e178c
--- /dev/null
+++ b/changelog.d/0.76.0/1732.fixed.md
@@ -0,0 +1,11 @@
+- `soup serve --backend sglang` now applies a LoRA adapter passed as `--model`. SGLang
+ applies an adapter only to the requests that name it in `lora_path` and runs every other
+ request on the base weights. The backend registered the adapter at startup but never
+ named it, so every answer came from the base model while `/v1/models` and each response
+ reported the adapter. The adapter is now registered under the name `adapter`
+ (`adapter=<path>`, which also keeps a path holding `=` from being split there), and every
+ request names it, on the token-ids and the string route, streaming or not. A full
+ model's requests name no adapter and are unchanged. The `[sglang]` extra and
+ `soup doctor` now require `sglang>=0.5.1` (was `>=0.2.0`): older releases refuse to
+ start an engine with a LoRA adapter unless its radix cache is turned off, which Soup
+ does not do (#1724 by @Batyrkhantzy111 in #1732).
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index d9c6c9e6..f921e7d1 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -400,6 +400,10 @@ soup serve --model ./output --backend sglang
soup serve --model ./output --backend sglang --tensor-parallel 2
```
+The backend needs SGLang 0.5.1 or later, which the `[sglang]` extra installs: older
+releases refuse to start an engine with a LoRA adapter unless its radix cache is turned
+off, and Soup leaves it on.
+
Like the transformers and vLLM backends, the SGLang backend applies the
**model's own chat template** via the same shared prompt builder (falling back
to a generic `User:` / `Assistant:` prompt for template-less models). When the
@@ -411,6 +415,15 @@ reports `"length"` when a response hits `max_tokens` and `"stop"` otherwise, so
a client doing continue-on-length can tell a truncated answer from a completed
one (#360).
+A LoRA adapter passed as `--model` is served on its base model (read from
+`adapter_config.json`, or `--base`), with the adapter registered in the engine
+under the name `adapter`. SGLang applies an adapter only to the requests that
+name it and runs every other request on the base weights, so the backend names
+it in every request, streaming or not. **This changed:** the adapter used to be
+registered but never named, so every answer came from the base model while the
+response reported the adapter's name (#1724). A full model's requests name no
+adapter.
+
It also honours `--trust-remote-code` like every other backend. **This changed:**
the SGLang runtime and its tokenizer previously loaded with `trust_remote_code`
hardcoded on, so a model's custom repo code executed whether or not you opted in
diff --git a/pyproject.toml b/pyproject.toml
index 25e6a838..624035ad 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -176,7 +176,7 @@ tensorrt = ["tensorrt_llm>=0.9.0"]
audio = ["librosa>=0.10.0", "soundfile>=0.12.0", "torchaudio>=2.6.0,<3.0.0"]
awq = ["autoawq>=0.2.0"]
gptq = ["auto-gptq>=0.7.0"]
-sglang = ["sglang>=0.2.0", "fastapi>=0.104.0", "uvicorn>=0.24.0", "httpx>=0.24.0"]
+sglang = ["sglang>=0.5.1", "fastapi>=0.104.0", "uvicorn>=0.24.0", "httpx>=0.24.0"]
mlx = [
"mlx>=0.20.0",
"mlx-lm>=0.31.3",
diff --git a/src/soup_cli/commands/doctor.py b/src/soup_cli/commands/doctor.py
index 7573637a..47848c2a 100644
--- a/src/soup_cli/commands/doctor.py
+++ b/src/soup_cli/commands/doctor.py
@@ -44,7 +44,7 @@ DEPS = [
("unsloth", "unsloth", "2024.8", False),
("PIL", "Pillow", "9.0.0", False),
("torchao", "torchao", TORCHAO_MIN_VERSION, False),
- ("sglang", "sglang", "0.2.0", False),
+ ("sglang", "sglang", "0.5.1", False),
("librosa", "librosa", "0.10.0", False),
]
diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.py
index a4a59d2f..f7303ea9 100644
--- a/src/soup_cli/commands/serve.py
+++ b/src/soup_cli/commands/serve.py
@@ -1340,7 +1340,7 @@ def _serve_sglang(
)
)
console.print("[dim]Initializing SGLang runtime...[/]")
- runtime, runtime_model_name = create_sglang_runtime(
+ runtime, runtime_model_name, lora_name = create_sglang_runtime(
model_path=str(model_path),
base_model=base_model,
is_adapter=is_adapter,
@@ -1387,6 +1387,9 @@ def _serve_sglang(
model_name=str(model_path.name),
max_tokens_default=max_tokens_default,
tokenizer=tokenizer,
+ # The name the adapter was registered under; every request has to name
+ # it, or SGLang answers from the base model (#1724).
+ lora_name=lora_name,
)
return app
diff --git a/src/soup_cli/utils/sglang.py b/src/soup_cli/utils/sglang.py
index 631acad4..fdd2a37e 100644
--- a/src/soup_cli/utils/sglang.py
+++ b/src/soup_cli/utils/sglang.py
@@ -50,6 +50,7 @@ def generate_with_runtime(
prompt: str,
prompt_token_ids: Optional[list[int]],
sampling_params: dict,
+ lora_name: Optional[str] = None,
) -> dict:
"""Run one generation on an SGLang ``Runtime`` and return the response dict (#785).
@@ -75,9 +76,19 @@ def generate_with_runtime(
``Runtime.generate`` re-encodes the server's JSON as a string (#76), the
direct post has the dict already, and :func:`decode_sglang_response`
accepts both.
+
+ ``lora_name`` is the name :func:`create_sglang_runtime` registered the
+ adapter under. SGLang applies a LoRA only to a request that names it in
+ ``lora_path`` and runs any other request on the base weights, so both
+ routes send the name whenever there is one (#1724). A full model has none,
+ and its requests carry no ``lora_path`` at all.
"""
+ # ``lora_path`` is SGLang's field name; it takes the registered name.
+ selector = {} if lora_name is None else {"lora_path": lora_name}
if prompt_token_ids is None:
- return decode_sglang_response(runtime.generate(prompt, sampling_params=sampling_params))
+ return decode_sglang_response(
+ runtime.generate(prompt, sampling_params=sampling_params, **selector)
+ )
try:
import httpx # the repo's HTTP client (utils/webhooks.py, commands/generate.py)
@@ -91,7 +102,7 @@ def generate_with_runtime(
# ``runtime.url`` from producing ``//generate``.
response = httpx.post(
runtime.url.rstrip("/") + "/generate",
- json={"input_ids": prompt_token_ids, "sampling_params": sampling_params},
+ json={"input_ids": prompt_token_ids, "sampling_params": sampling_params, **selector},
timeout=300.0,
)
response.raise_for_status()
@@ -173,7 +184,9 @@ def create_sglang_runtime(
custom code whether or not the user opted in.
Returns:
- (runtime, runtime_model_name) tuple.
+ (runtime, runtime_model_name, lora_name) tuple. ``lora_name`` is the
+ name the adapter is registered under, to be sent with every request
+ (#1724); None for a full model.
"""
import re
@@ -187,18 +200,22 @@ def create_sglang_runtime(
"not a URL"
)
- # For LoRA adapters, load the base model
+ # For LoRA adapters, load the base model and register the adapter under a
+ # name of its own: SGLang names a bare path entry after the whole string,
+ # and splits one that holds ``=`` into a name and a different path.
if is_adapter and base_model:
+ lora_name = "adapter" # the name the vLLM backend gives its LoRARequest
runtime = sgl.Runtime(
model_path=base_model,
tp_size=tensor_parallel_size,
mem_fraction_static=mem_fraction_static,
dtype=dtype,
trust_remote_code=trust_remote_code,
- lora_paths=[model_path],
+ lora_paths=[f"{lora_name}={model_path}"],
)
runtime_model_name = base_model
else:
+ lora_name = None
runtime = sgl.Runtime(
model_path=model_path,
tp_size=tensor_parallel_size,
@@ -208,7 +225,7 @@ def create_sglang_runtime(
)
runtime_model_name = model_path
- return runtime, runtime_model_name
+ return runtime, runtime_model_name, lora_name
def create_sglang_app(
@@ -217,6 +234,7 @@ def create_sglang_app(
model_name: str,
max_tokens_default: int = 512,
tokenizer=None,
+ lora_name: Optional[str] = None,
):
"""Create a FastAPI app using SGLang runtime for inference.
@@ -230,6 +248,10 @@ def create_sglang_app(
encodes the rendered prompt so the server does not add a second
BOS to it (#785). None degrades to the legacy role-prefixed
format, same as the vLLM backend.
+ lora_name: The name ``create_sglang_runtime`` registered the adapter
+ under. Every request, streaming or not, names it as ``lora_path``,
+ since SGLang runs a request that names no adapter on the base
+ weights (#1724). None for a full model.
Returns:
FastAPI application.
@@ -316,6 +338,7 @@ def create_sglang_app(
sampling_params=sampling_params,
request_id=request_id,
model_name=model_name,
+ lora_name=lora_name,
),
media_type="text/event-stream",
)
@@ -323,7 +346,7 @@ def create_sglang_app(
# Non-streaming
try:
response = generate_with_runtime(
- runtime, prompt, prompt_token_ids, sampling_params
+ runtime, prompt, prompt_token_ids, sampling_params, lora_name
)
response_text = response["text"]
prompt_tokens = response.get("meta_info", {}).get("prompt_tokens", 0)
@@ -366,13 +389,14 @@ def create_sglang_app(
sampling_params: dict,
request_id: str,
model_name: str,
+ lora_name: Optional[str],
):
"""Stream SSE chunks from SGLang runtime."""
created = int(time.time())
try:
response = generate_with_runtime(
- runtime, prompt, prompt_token_ids, sampling_params
+ runtime, prompt, prompt_token_ids, sampling_params, lora_name
)
response_text = response["text"]
meta_info = response.get("meta_info")
diff --git a/tests/test_issue360_sglang_prompt_finish_reason.py b/tests/test_issue360_sglang_prompt_finish_reason.py
index 8b08e9b2..60869922 100644
--- a/tests/test_issue360_sglang_prompt_finish_reason.py
+++ b/tests/test_issue360_sglang_prompt_finish_reason.py
@@ -308,7 +308,7 @@ class TestServeSglangWiring:
monkeypatch.setattr(
sglang_mod,
"create_sglang_runtime",
- lambda **kwargs: (MagicMock(), "runtime-model"),
+ lambda **kwargs: (MagicMock(), "runtime-model", None),
raising=False,
)
monkeypatch.setattr(
diff --git a/tests/test_sglang_serve.py b/tests/test_sglang_serve.py
index 28a13e78..37fb5faf 100644
--- a/tests/test_sglang_serve.py
+++ b/tests/test_sglang_serve.py
@@ -1,10 +1,15 @@
"""Tests for SGLang backend — detection, runtime creation, serve --backend flag, FastAPI app."""
+import json
+import sys
+from types import SimpleNamespace
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
import pytest
+from tests.test_issue360_sglang_prompt_finish_reason import _FakeTokenizer
+
def _has_fastapi():
try:
@@ -71,7 +76,7 @@ class TestSGLangRuntimeCreation:
with mock_patch.dict("sys.modules", {"sglang": mock_sgl}):
from soup_cli.utils.sglang import create_sglang_runtime
- runtime, model_name = create_sglang_runtime(
+ runtime, model_name, _ = create_sglang_runtime(
model_path="/path/to/model",
)
@@ -96,7 +101,7 @@ class TestSGLangRuntimeCreation:
with mock_patch.dict("sys.modules", {"sglang": mock_sgl}):
from soup_cli.utils.sglang import create_sglang_runtime
- runtime, model_name = create_sglang_runtime(
+ runtime, model_name, lora_name = create_sglang_runtime(
model_path="/path/to/adapter",
base_model="meta-llama/Llama-3.1-8B",
is_adapter=True,
@@ -104,7 +109,7 @@ class TestSGLangRuntimeCreation:
call_kwargs = mock_sgl.Runtime.call_args[1]
assert call_kwargs["model_path"] == "meta-llama/Llama-3.1-8B"
- assert call_kwargs["lora_paths"] == ["/path/to/adapter"]
+ assert call_kwargs["lora_paths"] == [f"{lora_name}=/path/to/adapter"]
assert model_name == "meta-llama/Llama-3.1-8B"
def test_create_sglang_runtime_tensor_parallel(self):
@@ -312,7 +317,131 @@ class TestSGLangSSRF:
with mock_patch.dict("sys.modules", {"sglang": mock_sgl}):
from soup_cli.utils.sglang import create_sglang_runtime
- runtime, name = create_sglang_runtime(
+ runtime, name, _ = create_sglang_runtime(
model_path="meta-llama/Llama-3.1-8B",
)
assert name == "meta-llama/Llama-3.1-8B"
+
+
+# ─── Adapter Selected On Every Request (#1724) ───────────────────────────
+
+
+class _RecordingEngine:
+ """The SGLang engine as the backend reaches it, with nothing behind it.
+
+ ``sglang.Runtime(...)`` starts it; ``Runtime.generate`` is the string route
+ and a POST to ``<url>/generate`` is the token-ids route (#995). Each request
+ is recorded as the fields the engine would receive.
+ """
+
+ url = "http://127.0.0.1:30000"
+
+ def __init__(self):
+ self.started_with = None
+ self.requests = []
+
+ def start(self, **kwargs): # sglang.Runtime(...)
+ self.started_with = kwargs
+ return self
+
+ def generate(self, prompt, **kwargs): # Runtime.generate
+ self.requests.append({"route": "string", "text": prompt, **kwargs})
+ return json.dumps({"text": "ok", "meta_info": {}})
+
+ def post(self, url, **kwargs): # httpx.post(<url>/generate, json=...)
+ import httpx
+
+ self.requests.append({"route": "ids", **kwargs["json"]})
+ return httpx.Response(
+ 200, json={"text": "ok", "meta_info": {}}, request=httpx.Request("POST", url)
+ )
+
+
+def _tokenizer_for(route):
+ """A rendered chat template sends token ids; no template sends the string."""
+ return _FakeTokenizer() if route == "ids" else None
+
+
+def _serve(monkeypatch, model_dir, *, adapter, tokenizer):
+ """``_serve_sglang`` as ``soup serve --backend sglang`` runs it, on a recording engine."""
+ import soup_cli.commands.serve as serve_mod
+
+ engine = _RecordingEngine()
+ monkeypatch.setitem(sys.modules, "sglang", SimpleNamespace(Runtime=engine.start))
+ monkeypatch.setattr("httpx.post", engine.post)
+ monkeypatch.setattr(serve_mod, "_load_serve_tokenizer", lambda **kwargs: tokenizer)
+ app = serve_mod._serve_sglang(
+ model_path=model_dir,
+ base_model="org/base-model" if adapter else None,
+ is_adapter=adapter,
+ max_tokens_default=16,
+ tensor_parallel=1,
+ gpu_memory_utilization=0.9,
+ )
+ return app, engine
+
+
+def _chat(app, *, stream):
+ from fastapi.testclient import TestClient
+
+ response = TestClient(app).post(
+ "/v1/chat/completions",
+ json={"messages": [{"role": "user", "content": "hi"}], "stream": stream},
+ )
+ assert response.status_code == 200, response.text
+
+
+def _name_sglang_gives(entry):
+ """The name SGLang registers a ``lora_paths`` entry under: ``name=path`` is
+ split on its first ``=``, any other string names itself (sglang 0.5.21
+ ``srt/arg_groups/lora_hook.py:60-75``)."""
+ return entry.split("=", 1)[0] if "=" in entry else entry
+
+
[email protected](not _has_fastapi(), reason="fastapi not installed")
+class TestAdapterIsSelectedOnEveryRequest:
+ """SGLang applies a LoRA only to a request whose ``lora_path`` names it; a
+ request without one runs on the base weights. The backend registered the
+ adapter at startup and never named it, so every answer came from the base
+ model while the response reported the adapter's name (#1724)."""
+
+ @pytest.mark.parametrize("stream", [False, True], ids=["non-streaming", "streaming"])
+ @pytest.mark.parametrize("route", ["ids", "string"])
+ def test_every_request_names_the_registered_adapter(
+ self, monkeypatch, tmp_path, route, stream
+ ):
+ app, engine = _serve(
+ monkeypatch, tmp_path / "lora", adapter=True, tokenizer=_tokenizer_for(route)
+ )
+
+ _chat(app, stream=stream)
+
+ (entry,) = engine.started_with["lora_paths"]
+ assert [request["route"] for request in engine.requests] == [route]
+ assert engine.requests[0].get("lora_path") == _name_sglang_gives(entry)
+
+ def test_the_adapter_is_registered_under_a_name_of_its_own(self, monkeypatch, tmp_path):
+ """With the path doubling as the name, SGLang splits a path that holds
+ ``=`` and loads what follows it; an explicit name keeps the whole path."""
+ adapter_dir = tmp_path / "lora-r=16"
+ _, engine = _serve(monkeypatch, adapter_dir, adapter=True, tokenizer=None)
+
+ (entry,) = engine.started_with["lora_paths"]
+ name, path = entry.split("=", 1) # what SGLang does with the entry
+
+ assert path == str(adapter_dir)
+ assert name
+
+ @pytest.mark.parametrize("stream", [False, True], ids=["non-streaming", "streaming"])
+ @pytest.mark.parametrize("route", ["ids", "string"])
+ def test_control_a_full_model_sends_no_lora_path(self, monkeypatch, tmp_path, route, stream):
+ """CONTROL: a full model registers no adapter, so its requests carry no
+ ``lora_path``; naming one SGLang has not loaded makes it refuse them."""
+ app, engine = _serve(
+ monkeypatch, tmp_path / "model", adapter=False, tokenizer=_tokenizer_for(route)
+ )
+
+ _chat(app, stream=stream)
+
+ assert [request["route"] for request in engine.requests] == [route]
+ assert "lora_path" not in engine.requests[0]
diff --git a/tests/test_sglang_trust_contract.py b/tests/test_sglang_trust_contract.py
index 203ab8c6..9f47aeaa 100644
--- a/tests/test_sglang_trust_contract.py
+++ b/tests/test_sglang_trust_contract.py
@@ -106,7 +106,7 @@ class TestServeSglangThreadsTheResolvedValue:
def _runtime(**kwargs):
seen["runtime"] = kwargs
- return MagicMock(), "runtime-model"
+ return MagicMock(), "runtime-model", None
def _tokenizer(**kwargs):
seen["tokenizer"] = kwargs