Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

perf(models): read a single Qwen3.8-27B-FP8 page image at 3.2 megapixels and compile compact JSON grammars (#466)

svonava329df878acd1
diff --git a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
index b7d23e48c..5edde14c5 100644
--- a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
@@ -14,6 +14,16 @@ inputs:
# Qwen documents native video understanding, but video is not yet wired
# through the SIE generation request surface.
video: false
+# A request with ONE image reads it at up to 3,211,264 pixels (3,136 visual
+# tokens, one per merged 32x32 patch), the resolution a dense form or statement
+# needs: at the family's 1,003,520 a full page came back with misread names and
+# digits. SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS raises the bound for single-image
+# requests only; a request with two or more images keeps --mm-process-config's
+# 1,003,520 per image, so multi-image requests fit the 8K window exactly as
+# before. The worker reserves the matching bound per request. Every profile
+# also compiles JSON-schema grammars without free whitespace, so greedy
+# decoding cannot pad a reply with indentation or run to the output cap in
+# spaces.
tasks:
generate:
# Keep the bare route conservative. Native context is exposed only through
@@ -53,6 +63,8 @@ profiles:
kv_budget_tokens: 8192
adapter_options:
loadtime:
+ extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
mem_fraction_static: 0.85
served_model_name: Qwen/Qwen3.8-27B-FP8
disable_cuda_graph: true
@@ -64,6 +76,7 @@ profiles:
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -110,6 +123,7 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: true
@@ -120,6 +134,7 @@ profiles:
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -159,12 +174,14 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: false
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -207,12 +224,14 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: false
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -271,12 +290,14 @@ profiles:
reasoning_parser: qwen3
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: false
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -333,6 +354,7 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: true
@@ -343,6 +365,7 @@ profiles:
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -382,12 +405,14 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: false
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -427,6 +452,7 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: true
@@ -437,6 +463,7 @@ profiles:
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
@@ -474,12 +501,14 @@ profiles:
grammar_backend: xgrammar
tool_call_parser: qwen3_coder
extra_env:
+ SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
SGLANG_JIT_DEEPGEMM_FAST_WARMUP: "1"
speculative:
enabled: false
extra_launch_args:
- "--mm-process-config"
- '{"image":{"min_pixels":65536,"max_pixels":1003520}}'
+ - "--constrained-json-disable-any-whitespace"
- "--kv-cache-dtype"
- "bfloat16"
- "--mamba-ssm-dtype"
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py
index 796131527..f1d909712 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py
@@ -6,6 +6,13 @@ Hugging Face processor. Upstream #18467 now passes them as ``images_kwargs``.
This site hook runs only in the SGLang generation subprocess and can be removed
when the shared bundle advances to a release containing that fix.
+The hook also applies ``SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS``: when set, a
+request that carries exactly one image is processed with that ``max_pixels``
+instead of ``--mm-process-config``'s, so one document page can be read at a
+higher resolution while a request with several images keeps the launch bound
+(and still fits the context window it fitted before). The raised bound is
+applied to a shallow per-call copy of the processor, never to the shared one.
+
The same hook redacts multimodal load failures: SGLang raises
``Error while loading data {data}`` with the full inline payload, which its
serving layer then logs with a traceback. The redacted error is a
@@ -16,6 +23,7 @@ into a 400 response; the adapter maps its fixed message to ``invalid_request``.
from __future__ import annotations
import builtins
+import copy
import os
import sys
from collections.abc import Mapping, Sequence
@@ -26,6 +34,24 @@ from typing import Any
_BASE_PROCESSOR_MODULE = "sglang.srt.multimodal.processors.base_processor"
_CLASS_PATCH_MARKER = "_sie_mm_process_config_compat"
_IMPORT_HOOK_MARKER = "_sie_mm_process_config_deferred_compat"
+SINGLE_IMAGE_MAX_PIXELS_ENV = "SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS"
+
+
+def _single_image_max_pixels() -> int | None:
+ """The raised per-image bound for single-image requests, or ``None``."""
+ raw = os.environ.get(SINGLE_IMAGE_MAX_PIXELS_ENV, "").strip()
+ if not raw.isdigit():
+ return None
+ value = int(raw)
+ return value if value > 0 else None
+
+
+def _image_count(images: Any) -> int:
+ if images is None:
+ return 0
+ if isinstance(images, (list, tuple)):
+ return len(images)
+ return 1
def _patch_base_processor_module(module: ModuleType) -> None:
@@ -46,11 +72,17 @@ def _patch_base_processor_module(module: ModuleType) -> None:
audios: Any = None,
**kwargs: Any,
) -> dict[str, Any]:
+ target = self
image_config = getattr(self, "image_config", None)
+ single_max = _single_image_max_pixels()
+ if single_max is not None and _image_count(images) == 1 and isinstance(image_config, dict) and image_config:
+ target = copy.copy(self)
+ target.image_config = {**image_config, "max_pixels": single_max}
+ image_config = target.image_config
if images and isinstance(image_config, dict) and image_config:
kwargs.setdefault("images_kwargs", {}).update(image_config)
return original_process(
- self,
+ target,
input_text,
images=images,
videos=videos,
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 93495f414..1bd88f864 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -62,6 +62,10 @@ from sie_server.types.inputs import ImageInput, VideoInput, media_bytes
logger = logging.getLogger(__name__)
+# Pixels per visual token for the Qwen3.x vision encoders SGLang serves here: a
+# 16-pixel patch merged 2x2, so one token covers 32x32 pixels.
+_MERGED_PATCH_PIXELS = 32 * 32
+
# HTTP timeout knobs for /generate. The worker-side admission/cancel layer is
# the source of truth for total request lifetime, so the streaming read timeout
# is disabled by default (``read=None`` — keep reading as long as bytes arrive).
@@ -656,6 +660,43 @@ class SGLangGenerationAdapter(GenerationAdapter):
"""Return the child parser used to separate private reasoning output."""
return self._reasoning_parser
+ @property
+ def image_token_budget(self) -> int | None:
+ """Return the most visual tokens ONE image of a single-image request can expand to.
+
+ A Qwen3.x vision encoder emits one token per merged 32x32 patch, so the
+ bound is ``ceil(max_pixels / 1024)``. ``max_pixels`` is
+ ``SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS`` from the profile's ``extra_env``
+ when set (the compat hook applies it to single-image requests), else
+ the launch's ``--mm-process-config`` ``image.max_pixels``. ``None`` when
+ neither is set, and the worker falls back to its family-wide estimate.
+ """
+ single = str(self._extra_env.get("SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS", "")).strip()
+ if single.isdigit() and int(single) > 0:
+ return math.ceil(int(single) / _MERGED_PATCH_PIXELS)
+ return self.multi_image_token_budget
+
+ @property
+ def multi_image_token_budget(self) -> int | None:
+ """Return the most visual tokens each image of a multi-image request can expand to.
+
+ Read from the launch's ``--mm-process-config`` ``image.max_pixels``;
+ ``None`` when the launch sets no image bound.
+ """
+ args = self._extra_launch_args
+ if "--mm-process-config" not in args:
+ return None
+ index = args.index("--mm-process-config")
+ if index + 1 >= len(args):
+ return None
+ try:
+ max_pixels = json.loads(args[index + 1]).get("image", {}).get("max_pixels")
+ except (json.JSONDecodeError, AttributeError):
+ return None
+ if not isinstance(max_pixels, int) or max_pixels <= 0:
+ return None
+ return math.ceil(max_pixels / _MERGED_PATCH_PIXELS)
+
def _compat_pythonpath_entries(self) -> tuple[str, ...]:
"""Return trusted compatibility paths for the SGLang child.
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 7bde90200..5f3aa010f 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -286,13 +286,32 @@ _MAX_IMAGES_PER_REQUEST = 16
# admission reservation. The chat template renders each image as a short
# placeholder, but the vision encoder expands it into many tokens (Qwen-VL:
# up to ~1280 at max_pixels). Exact counts need the image dimensions + the
-# model's vision tokenizer, which we don't have at this layer. Qwen SGLang
-# profiles cap preprocessing at 1280 visual tokens, so this value is both a
-# conservative reservation and a hard upper bound for the image-capable
-# generation family. Under-counting risks a context-window overflow and
-# admission over-admit.
+# model's vision tokenizer, which we don't have at this layer. Most Qwen SGLang
+# profiles cap preprocessing at 1280 visual tokens, so this value is the
+# family-wide floor. A profile that reads pages at a higher resolution declares
+# it and the adapter reports the larger bound; see ``_vision_tokens_for_images``. Under-counting
+# risks a context-window overflow and admission over-admit.
_VISION_TOKENS_PER_IMAGE_ESTIMATE = 1280
+
+def _vision_tokens_for_images(adapter: object, count: int) -> int:
+ """Visual tokens to reserve for ``count`` images on this adapter's launch.
+
+ A single image may be read at the launch's raised single-image bound
+ (``image_token_budget``); two or more use the per-image launch bound
+ (``multi_image_token_budget``). Neither is ever reserved below the
+ family-wide estimate, so every launch keeps at least today's reservation.
+ """
+ if count <= 0:
+ return 0
+ name = "image_token_budget" if count == 1 else "multi_image_token_budget"
+ budget = getattr(adapter, name, None)
+ per_image = _VISION_TOKENS_PER_IMAGE_ESTIMATE
+ if isinstance(budget, int) and not isinstance(budget, bool) and budget > per_image:
+ per_image = budget
+ return count * per_image
+
+
# Hard ceiling on a single decoded image's bytes. Bounds worker memory on the
# decode path even for the direct-queue caller that bypasses the gateway's
# request-body cap. Checked from the base64 length BEFORE decoding (so a huge
@@ -2041,7 +2060,7 @@ class StreamingProcessor:
# Include the coarse per-image token estimate so vision requests
# reserve KV budget proportional to their real (placeholder-expanded)
# footprint instead of just the short placeholder text.
- image_reserve = (len(request_images) if request_images else 0) * _VISION_TOKENS_PER_IMAGE_ESTIMATE
+ image_reserve = _vision_tokens_for_images(adapter, len(request_images) if request_images else 0)
image_reserve += (len(request_videos) if request_videos else 0) * _VISION_TOKENS_PER_VIDEO_ESTIMATE
reserve_tokens = estimate_tokens_from_chars(prompt_str) + params.max_new_tokens + image_reserve
effective_budget = budget_override if budget_override is not None else self._kv_budget_tokens
@@ -3685,7 +3704,7 @@ class StreamingProcessor:
# in ``prompt`` tokenizes to a handful of text tokens but expands to
# many tokens at inference. Add a coarse per-image estimate so the
# guard fires before SGLang overflows its context window.
- image_tokens = num_images * _VISION_TOKENS_PER_IMAGE_ESTIMATE + num_videos * _VISION_TOKENS_PER_VIDEO_ESTIMATE
+ image_tokens = _vision_tokens_for_images(adapter, num_images) + num_videos * _VISION_TOKENS_PER_VIDEO_ESTIMATE
input_tokens = prompt_tokens + image_tokens
image_note = f" + ~image_tokens ({image_tokens})" if image_tokens else ""
if adapter.context_length_accounting == "independent":
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index ca8d1dead..90f2c3dc5 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -2475,6 +2475,60 @@ print("mm-process-config-ready")
assert completed.stdout.strip() == "mm-process-config-ready"
+def test_mm_process_config_compat_raises_the_bound_for_single_image_requests_only(tmp_path: Path) -> None:
+ package_root = tmp_path / "site"
+ processors = package_root / "sglang" / "srt" / "multimodal" / "processors"
+ processors.mkdir(parents=True)
+ for package in (
+ package_root / "sglang",
+ package_root / "sglang" / "srt",
+ package_root / "sglang" / "srt" / "multimodal",
+ processors,
+ ):
+ (package / "__init__.py").write_text("", encoding="utf-8")
+ # The pinned SGLang release forwards image_config itself inside
+ # process_mm_data, after the hook runs; the fake does the same.
+ (processors / "base_processor.py").write_text(
+ """class BaseMultimodalProcessor:
+ def __init__(self):
+ self.image_config = {"min_pixels": 65536, "max_pixels": 1003520}
+
+ def process_mm_data(self, input_text, images=None, videos=None, audios=None, **kwargs):
+ if images and self.image_config:
+ kwargs.setdefault("images_kwargs", {}).update(self.image_config)
+ return kwargs
+""",
+ encoding="utf-8",
+ )
+ compat_dir = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang/_compat"
+ script = """import sitecustomize
+from sglang.srt.multimodal.processors.base_processor import BaseMultimodalProcessor
+
+processor = BaseMultimodalProcessor()
+one = processor.process_mm_data("x", images=[b"page"])
+two = processor.process_mm_data("x", images=[b"a", b"b"])
+assert one["images_kwargs"] == {"min_pixels": 65536, "max_pixels": 3211264}, one
+assert two["images_kwargs"] == {"min_pixels": 65536, "max_pixels": 1003520}, two
+assert processor.image_config == {"min_pixels": 65536, "max_pixels": 1003520}
+assert processor.process_mm_data("x", images=None) == {}
+print("single-image-bound-ready")
+"""
+ env = dict(os.environ)
+ env["PYTHONPATH"] = os.pathsep.join((str(compat_dir), str(package_root)))
+ env["SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT"] = "1"
+ env["SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS"] = "3211264"
+ completed = subprocess.run( # noqa: S603 - executes the fixed local interpreter
+ [sys.executable, "-c", script],
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=15,
+ check=False,
+ )
+ assert completed.returncode == 0, completed.stderr
+ assert completed.stdout.strip() == "single-image-bound-ready"
+
+
def test_mm_process_config_compat_redacts_media_load_failures(tmp_path: Path) -> None:
package_root = tmp_path / "fake-package"
processors = package_root / "sglang" / "srt" / "multimodal" / "processors"
diff --git a/packages/sie_server/tests/adapters/test_sglang_launch_flags.py b/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
index 569f4f7c6..46727e6b4 100644
--- a/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
+++ b/packages/sie_server/tests/adapters/test_sglang_launch_flags.py
@@ -50,6 +50,9 @@ _DECLARED_IN_PINNED_ENGINE = frozenset(
"--lora-paths",
"--max-loras-per-batch",
"--mem-fraction-static",
+ # Read, not emitted: generation.py derives the per-image token budget
+ # from the profile's own ``--mm-process-config``, which both engines parse.
+ "--mm-process-config",
"--model-path",
"--nccl-port",
"--port",
@@ -93,6 +96,7 @@ _OLDER_ENGINE_ONLY = frozenset(
_CU130_PROFILE_FLAGS = frozenset(
{
"--chunked-prefill-size",
+ "--constrained-json-disable-any-whitespace",
"--cuda-graph-max-bs-decode",
"--disable-overlap-schedule",
"--enable-strict-thinking",
diff --git a/packages/sie_server/tests/config/test_qwen38_generation_profiles.py b/packages/sie_server/tests/config/test_qwen38_generation_profiles.py
index c9613953b..fed522c37 100644
--- a/packages/sie_server/tests/config/test_qwen38_generation_profiles.py
+++ b/packages/sie_server/tests/config/test_qwen38_generation_profiles.py
@@ -76,7 +76,7 @@ def test_qwen38_default_is_a_conservative_non_speculative_route() -> None:
assert default.loadtime["disable_cuda_graph"] is True
assert default.loadtime["speculative"] == {"enabled": False}
assert default.loadtime["attention_backend"] == "flashinfer"
- assert "extra_env" not in default.loadtime
+ assert default.loadtime["extra_env"] == {"SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS": "3211264"}
default_args = default.loadtime["extra_launch_args"]
assert default_args[default_args.index("--mamba-ssm-dtype") + 1] == "float32"
# Qwen3 structured output is not constrained when thinking is disabled
@@ -158,7 +158,10 @@ def test_qwen38_hardware_launches_keep_fp8_weights_with_tuned_state_precision()
assert args[args.index("--page-size") + 1] == "64"
assert args[args.index("--max-running-requests") + 1] == "1"
assert args[args.index("--cuda-graph-max-bs-decode") + 1] == "1"
- assert profile.loadtime["extra_env"] == {"SGLANG_JIT_DEEPGEMM_FAST_WARMUP": "1"}
+ assert profile.loadtime["extra_env"] == {
+ "SGLANG_JIT_DEEPGEMM_FAST_WARMUP": "1",
+ "SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS": "3211264",
+ }
for profile_name in (
"h100-256k",
@@ -265,3 +268,34 @@ def test_qwen38_h100_batch_grammar_requests_stay_on_the_batch_launch() -> None:
resolve_grammar_serving_model(registry, f"{_MODEL_ID}:h100-256k-batch-no-spec")
== f"{_MODEL_ID}:h100-256k-batch-no-spec"
)
+
+
+def test_qwen38_reads_one_page_at_document_resolution_with_compact_json() -> None:
+ import json
+
+ from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
+ from sie_server.processors.streaming import _VISION_TOKENS_PER_IMAGE_ESTIMATE, _vision_tokens_for_images
+
+ config = load_model_config(_MODEL_PATH)
+ assert config.tasks.generate is not None
+ window = config.tasks.generate.context_length
+ output_cap = config.tasks.generate.max_output_tokens
+ for name in config.profiles:
+ loadtime = config.resolve_profile(name).loadtime
+ args = loadtime["extra_launch_args"]
+ # The launch bound, which every multi-image request keeps, is unchanged.
+ assert args.count("--mm-process-config") == 1, name
+ image = json.loads(args[args.index("--mm-process-config") + 1])["image"]
+ assert image == {"min_pixels": 65536, "max_pixels": 1003520}, name
+ assert loadtime["extra_env"]["SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS"] == "3211264", name
+ assert args.count("--constrained-json-disable-any-whitespace") == 1, name
+
+ adapter = SGLangGenerationAdapter.__new__(SGLangGenerationAdapter)
+ adapter._extra_launch_args = list(args)
+ adapter._extra_env = dict(loadtime["extra_env"])
+ assert _vision_tokens_for_images(adapter, 1) == 3136, name
+ for count in (2, 4, 16):
+ assert _vision_tokens_for_images(adapter, count) == count * _VISION_TOKENS_PER_IMAGE_ESTIMATE, name
+
+ # The bare route still fits one full-resolution page and the whole output cap.
+ assert 3136 + output_cap < window
diff --git a/packages/sie_server/tests/processors/test_vision_token_budget.py b/packages/sie_server/tests/processors/test_vision_token_budget.py
new file mode 100644
index 000000000..26afc8ae8
--- /dev/null
+++ b/packages/sie_server/tests/processors/test_vision_token_budget.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
+from sie_server.processors.streaming import _VISION_TOKENS_PER_IMAGE_ESTIMATE, _vision_tokens_for_images
+
+_TODAY = ["--mm-process-config", '{"image":{"min_pixels":65536,"max_pixels":1003520}}']
+
+
+def _adapter(args: list[str], env: dict[str, str] | None = None) -> SGLangGenerationAdapter:
+ adapter = SGLangGenerationAdapter.__new__(SGLangGenerationAdapter)
+ adapter._extra_launch_args = args
+ adapter._extra_env = env or {}
+ return adapter
+
+
+def test_single_image_budget_follows_the_raised_bound() -> None:
+ adapter = _adapter(_TODAY, {"SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS": "3211264"})
+ assert adapter.image_token_budget == 3136
+ assert adapter.multi_image_token_budget == 980
+
+
+def test_without_the_raised_bound_both_budgets_are_the_launch_bound() -> None:
+ adapter = _adapter(_TODAY)
+ assert adapter.image_token_budget == adapter.multi_image_token_budget == 980
+
+
+def test_budget_is_absent_without_an_image_bound() -> None:
+ assert _adapter([]).image_token_budget is None
+ assert _adapter(["--mm-process-config"]).multi_image_token_budget is None
+ assert _adapter(["--mm-process-config", "not json"]).multi_image_token_budget is None
+ assert _adapter(["--mm-process-config", '{"video":{"total_pixels":8388608}}']).multi_image_token_budget is None
+ assert _adapter([], {"SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS": "junk"}).image_token_budget is None
+
+
+def test_worker_reserves_the_raised_bound_only_for_one_image() -> None:
+ adapter = _adapter(_TODAY, {"SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS": "3211264"})
+ assert _vision_tokens_for_images(adapter, 0) == 0
+ assert _vision_tokens_for_images(adapter, 1) == 3136
+ # Two or more images reserve exactly what they reserved before the raise.
+ assert _vision_tokens_for_images(adapter, 2) == 2 * _VISION_TOKENS_PER_IMAGE_ESTIMATE
+ assert _vision_tokens_for_images(adapter, 4) == 4 * _VISION_TOKENS_PER_IMAGE_ESTIMATE
+
+
+def test_worker_never_reserves_below_the_family_estimate() -> None:
+ assert _vision_tokens_for_images(SimpleNamespace(), 1) == _VISION_TOKENS_PER_IMAGE_ESTIMATE
+ assert _vision_tokens_for_images(SimpleNamespace(image_token_budget=980), 1) == _VISION_TOKENS_PER_IMAGE_ESTIMATE
+ assert _vision_tokens_for_images(SimpleNamespace(image_token_budget=True), 1) == _VISION_TOKENS_PER_IMAGE_ESTIMATE