Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
perf(qwen3-embedding): keep up to four Qwen3-Embedding-4B batches in flight to SGLang (#647)
svonava99140a475308
diff --git a/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml b/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yamlindex 92ba0eda6..1596888df 100644--- a/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml@@ -23,6 +23,10 @@ profiles:adapter_options:loadtime:mem_fraction_static: 0.85+ # Up to four batches in flight to SGLang at once, so the GPU keeps working+ # while a batch waits on its HTTP round trips: about 1.5x the documents per+ # second at 8 and 32 in flight on an H100.+ max_concurrent_dispatch: 4runtime:pooling: last_tokennormalize: truediff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex cadf48833..f97763c84 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -144,6 +144,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):dense_dim: int | None = None,startup_timeout_s: float | None = None,embed_concurrency: int | None = None,+ max_concurrent_dispatch: int = 1,# Accepted for the same reason the generation adapter accepts it: the# width is a property of a load, not of a task. No embedding profile# needs it today, and one is the byte-identical single-device case.@@ -188,6 +189,10 @@ class SGLangEmbeddingAdapter(BaseAdapter):max_loras_per_batch: Maximum LoRA adapters per batch. Default 8.dense_dim: Configured dense embedding dimension.startup_timeout_s: SGLang startup-health timeout in seconds.+ embed_concurrency: Concurrent POSTs one batch is sharded into.+ max_concurrent_dispatch: Batches the worker may have in flight to+ SGLang at once (see ``max_concurrent_dispatch()``). 1 keeps the+ worker's one-batch-at-a-time dispatch.**kwargs: Additional arguments (ignored, for compatibility)."""_ = kwargs # Unused, but accepted for loader compatibility@@ -207,6 +212,14 @@ class SGLangEmbeddingAdapter(BaseAdapter):self._max_loras_per_batch = max_loras_per_batchself._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)self._embed_concurrency = _resolve_embed_concurrency(embed_concurrency)+ if (+ isinstance(max_concurrent_dispatch, bool)+ or not isinstance(max_concurrent_dispatch, int)+ or max_concurrent_dispatch < 1+ ):+ msg = "max_concurrent_dispatch must be a positive integer"+ raise ValueError(msg)+ self._max_concurrent_dispatch = max_concurrent_dispatchself._tensor_parallel_size = _server.validate_tensor_parallel_size(tensor_parallel_size)self._disable_piecewise_cuda_graph = (self._tensor_parallel_size > 1 if disable_piecewise_cuda_graph is None else disable_piecewise_cuda_graph@@ -390,16 +403,18 @@ class SGLangEmbeddingAdapter(BaseAdapter):# Concurrent-POST fan-out: a keep-alive session with a connection pool# sized to the concurrency and a matching thread pool, so a sharded# ``encode`` keeps ``embed_concurrency`` requests in flight against- # SGLang's continuous batcher (see ``_embed_texts``). Left as ``None``- # for concurrency==1 (legacy single blocking post).+ # SGLang's continuous batcher (see ``_embed_texts``). Both are sized for+ # every batch the worker may dispatch at once, so a second batch's+ # shards do not queue behind the first's. Left as ``None`` for+ # concurrency==1 (legacy single blocking post).if self._embed_concurrency > 1:self._session = requests.Session()- pool_size = max(self._embed_concurrency, 10)+ pool_size = max(self._embed_concurrency * self._max_concurrent_dispatch, 10)http_adapter = HTTPAdapter(pool_connections=pool_size, pool_maxsize=pool_size)self._session.mount("http://", http_adapter)self._session.mount("https://", http_adapter)self._post_executor = ThreadPoolExecutor(- max_workers=self._embed_concurrency,+ max_workers=self._embed_concurrency * self._max_concurrent_dispatch,thread_name_prefix="sglang-embed-post",)@@ -658,10 +673,13 @@ class SGLangEmbeddingAdapter(BaseAdapter):``extra`` unstamped, so the counts are absent rather thanapproximated."""- tokenizer = self._get_metering_tokenizer()- if tokenizer is None:- return- counts = self._token_counts_or_none(tokenizer, non_empty_texts, expected_len=len(non_empty_texts))+ # Batches can run concurrently (``max_concurrent_dispatch``), and a fast+ # tokenizer is not re-entrant, so the lazy load and the count are serialised.+ with self._tokenizer_guard():+ tokenizer = self._get_metering_tokenizer()+ if tokenizer is None:+ return+ counts = self._token_counts_or_none(tokenizer, non_empty_texts, expected_len=len(non_empty_texts))if counts is None:returnper_item = [0] * total@@ -882,6 +900,17 @@ class SGLangEmbeddingAdapter(BaseAdapter):# LoRA Support# -------------------------------------------------------------------------+ def max_concurrent_dispatch(self) -> int:+ """Batches the worker may have in flight to SGLang at once.++ SGLang batches continuously, so while one batch waits on its HTTP+ round trips (and the JSON decode of its embeddings) the next can+ already be running on the GPU. With one batch at a time the GPU idles+ through every round trip. The worker honours values above 1 only+ when no LoRA adapters are configured.+ """+ return self._max_concurrent_dispatch+def supports_lora(self) -> bool:"""Return True if LoRA adapters are configured."""return bool(self._lora_paths)diff --git a/packages/sie_server/tests/adapters/test_sglang_embedding_dispatch.py b/packages/sie_server/tests/adapters/test_sglang_embedding_dispatch.pynew file mode 100644index 000000000..bc628acf5--- /dev/null+++ b/packages/sie_server/tests/adapters/test_sglang_embedding_dispatch.py@@ -0,0 +1,74 @@+"""SGLangEmbeddingAdapter can let the worker keep several batches in flight, with metering still exact."""++from __future__ import annotations++import threading+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Any++import pytest+from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter+from sie_server.core.inference_output import EncodeOutput+from sie_server.core.loader import load_model_config+from sie_server.core.worker.model_worker import _dispatch_width++_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+++def test_one_batch_at_a_time_unless_a_profile_asks() -> None:+ adapter = SGLangEmbeddingAdapter("test-model")+ assert adapter.max_concurrent_dispatch() == 1+ assert _dispatch_width(adapter) == 1+++def test_qwen3_embedding_4b_keeps_four_batches_in_flight() -> None:+ loadtime = load_model_config(_MODELS_DIR / "Qwen__Qwen3-Embedding-4B.yaml").resolve_profile("default").loadtime+ assert loadtime["max_concurrent_dispatch"] == 4+ adapter = SGLangEmbeddingAdapter("Qwen/Qwen3-Embedding-4B", **loadtime)+ assert _dispatch_width(adapter) == 4+++def test_lora_keeps_one_batch_at_a_time() -> None:+ adapter = SGLangEmbeddingAdapter("test-model", max_concurrent_dispatch=4, lora_paths={"legal": "org/legal-lora"})+ assert adapter.max_concurrent_dispatch() == 4+ assert _dispatch_width(adapter) == 1++[email protected]("value", [0, -1, True, 2.0, "4"])+def test_invalid_dispatch_width_is_rejected(value: Any) -> None:+ with pytest.raises(ValueError, match="max_concurrent_dispatch"):+ SGLangEmbeddingAdapter("test-model", max_concurrent_dispatch=value)+++class _NonReentrantTokenizer:+ """Fails like a fast tokenizer ("Already borrowed") when two threads use it at once."""++ def __init__(self) -> None:+ self._busy = threading.Lock()++ def __call__(self, texts: list[str], **_: Any) -> dict[str, list[list[int]]]:+ if not self._busy.acquire(blocking=False):+ msg = "Already borrowed"+ raise RuntimeError(msg)+ try:+ time.sleep(0.002)+ return {"input_ids": [[0] * len(text.split()) for text in texts]}+ finally:+ self._busy.release()+++def test_concurrent_batches_are_all_metered() -> None:+ adapter = SGLangEmbeddingAdapter("test-model", max_concurrent_dispatch=4)+ adapter._metering_tokenizer_obj = _NonReentrantTokenizer()+ adapter._metering_tokenizer_loaded = True++ def stamp(k: int) -> list[int] | None:+ output = EncodeOutput(dense=None, batch_size=2)+ adapter._stamp_input_token_counts(output, ["a b", "c d e" * (k % 3 + 1)], [0, 1], 2)+ return output.extra.get("input_token_counts")++ with ThreadPoolExecutor(max_workers=8) as pool:+ counts = list(pool.map(stamp, range(64)))+ assert all(found is not None for found in counts)