Skip to content

The platform for continuously improving AI agents.

Serve dedicated BF16 chat on SGLang where it won, with DFlash (#289)

Rohit Guptaa31f940587b7
diff --git a/.agents/skills/backend-architecture/references/serving.md b/.agents/skills/backend-architecture/references/serving.md
index 92e32841..17189848 100644
--- a/.agents/skills/backend-architecture/references/serving.md
+++ b/.agents/skills/backend-architecture/references/serving.md
@@ -4,13 +4,13 @@
- `deployment.serves_as_adapter` decides the shape. A dense or explicitly supported MoE Modal-trained LoRA is served as an adapter on a shared BF16 base, and every deployment on that base shares one container pool. Everything else (full finetunes, unsupported MoE, other providers) is merged into a private checkpoint, quantized to FP8 unless the catalog entry sets `fp8_supported: false`. Native decision deployments copy their verified artifact without a merge.
- The shared base stays BF16: an FP8 base measurably degrades adapter quality. MoE models need verified `inference.lora_supported` in `models.json`. `inference.min_vram_gb` is a measured floor; a deployment below it is raised before the next boot.
-- Base weights live only in `.base_models/{org--model}` on the weights Volume. `fetch_base_model` is the only writer and a global mutex; it seals `.base-manifest.json` and validates it on reuse. Celery waits on it before spawning GPU training, so a cold base downloads on CPU. Training fails on an incomplete snapshot; there is no Hub fallback.
+- Base weights live only in `.base_models/{org--model}` on the weights Volume. `fetch_base_model` is the only writer and a global mutex; it seals `.base-manifest.json` and validates it on reuse. Celery waits on it before spawning GPU training, so a cold base downloads on CPU. Training fails on an incomplete snapshot; there is no Hub fallback. Qwen3.5 27B and 35B-A3B, Qwen3 4B and 8B, Qwen3-Coder-30B-A3B, Llama-3.1-8B, gpt-oss-20b, and Gemma 4 26B-A4B and 31B also get their DFlash draft under `.drafts/` in that same call. Qwen3.5 0.8B, 2B, 4B, and 9B, and Qwen3.6-27B, use the checkpoint MTP head on SGLang (EAGLE, 3 steps, 4 draft tokens) and do not download a draft. Qwen3.8-27B and Muse-Glimmer-30B get DFlash2, 7 tokens. BF16 serving passes it as `--speculative-config`; an FP8 merged checkpoint does not.
- Nothing on the `overmind-sft` Volume is read at serve time. `tasks/cleanup_modal.py` sweeps it daily. A Modal deploy restores from the S3 archive only when retention already pruned the checkpoint (`register_model._dispatch_download`); the first Modal deploy never round-trips through S3.
- Torch compile files stay on the container disk. A Modal volume's 500k inode cap cannot hold them.
## Dedicated deployments
-A ready `DeployedModel` has at most one live `DedicatedDeployment` on the private `overmind-dedicated` app. The menu is every GPU at or above the memory floor, including H100 whenever A100-80GB fits. Serverless `select_gpu` still skips H100. Chat shapes are `lora_bf16` and `merged_fp8`. Decision models use `DecisionEndpoint` and report latency only. A release that accepts `pool` isolates one deployment; a release published before that parameter shares one option set per artifact and GPU. Speed comes from `overbae/modal/serving_benchmarks.json` (one bench per base, shape, and GPU); a missing cell stays unmeasured. The hourly price is the live Modal GPU rate plus that worker's CPU and memory (100 credits = $1); a missing rate refuses start. `min_containers` is the replica floor, `scaledown_window` is the idle timeout, and scale-up is demand up to `max_containers` (at most 8). Chat vLLM stores the KV cache in FP8. The sequence cap is how many full-context sequences fit on that GPU, at most 32; a lower cap is also that container's Modal input target. The 15-second deployment controller meters whole minutes of running replicas at the snapshotted rate and stops the deployment when billing is on and the balance cannot cover the next minute. Zero replicas cost nothing. Stopping drains the runtime with a zero replica floor while retaining the saved GPU and scaling configuration for restart; the Console joins Configure GPU and Start/Stop, and MCP uses the same start/stop services. A dedicated LoRA is applied while `{gpu}_vllm_dedicated` reads the base shards. Those shards are symlinked into the serve directory, not copied. That name is separate from the serverless `{gpu}_vllm` global, because Modal loads the class by module attribute. That container sleeps the loaded engine and Modal snapshots it; later replicas of the same deployment wake the snapshot. A chat or decision request connects to the container the controller already scaled; it does not call `update_autoscaler` or reread the base manifest. Chat completions with `stream: true` use the worker's `infer_stream` and flush each server-sent event. `run_inference` and the inference-request job still wait for the finished reply, because a tool result has no open token stream. Gateway ids `dedicated/<trained model id>` skip `inference-ft-model` charges. The capability alias stays on the shared active model. The Console lists each model's current dedicated deployment and opens it on that model's inference page. MCP tools are `list_dedicated_gpus`, `start_dedicated_deployment`, `update_dedicated_deployment`, and `stop_dedicated_deployment`; `run_inference` accepts `dedicated/<trained model id>`. `seed_demo` does not create a live dedicated row.
+A ready `DeployedModel` has at most one live `DedicatedDeployment` on the private `overmind-dedicated` app. Bases where SGLang won the sentence bench use `{gpu}_sglang_dedicated` (`lmsysorg/sglang:v0.5.22`) and fold the LoRA into a local checkpoint before launch. Gemma 4, Muse, Qwen3-Coder, and Llama stay on `{gpu}_vllm_dedicated` (`vllm/vllm-openai:v0.33.0`), which still snapshots the slept engine. SGLang containers do not; they open the port forward once the server is healthy. The shared inference pool stays on v0.30.0. Engine choice is internal; MCP start, stop, and `run_inference` are unchanged. The menu is every GPU at or above the memory floor, including H100 whenever A100-80GB fits. Serverless `select_gpu` still skips H100. Chat shapes are `lora_bf16` and `merged_fp8`. Decision deployments use the same `{gpu}_vllm_dedicated` class and `POST /v1/systemone`. They report latency only. Serverless decision calls stay on `DecisionEndpoint` in the model's decision-serving app, which boots vLLM 0.33.0 and posts `/v1/systemone` in the container. One artifact still owns that container. A catalog base with no artifact is the same class with `base_repo` set and no LoRA. Speed comes from `overbae/modal/serving_benchmarks.json` (one bench per base, shape, and GPU); a missing cell stays unmeasured. The hourly price is the live Modal GPU rate plus that worker's CPU and memory (100 credits = $1); a missing rate refuses start. `min_containers` is the replica floor, `scaledown_window` is the idle timeout, and scale-up is demand up to `max_containers` (at most 8). Chat vLLM stores the KV cache in FP8. The sequence cap is how many full-context sequences fit on that GPU, at most 32; a lower cap is also that container's Modal input target. The 15-second deployment controller meters whole minutes of running replicas at the snapshotted rate and stops the deployment when billing is on and the balance cannot cover the next minute. Zero replicas cost nothing. Stopping drains the runtime with a zero replica floor while retaining the saved GPU and scaling configuration for restart; the Console joins Configure GPU and Start/Stop, and MCP uses the same start/stop services. A dedicated vLLM LoRA is applied while `{gpu}_vllm_dedicated` reads the base shards. Those shards are symlinked into the serve directory, not copied. An SGLang LoRA is written out as a folded checkpoint on container disk, with the same delta, and the server reads that directory. Dedicated chat turns thinking off on every request. Auto tool choice leaves parallel calls on unless the request disables them. A required or named tool choice is one call unless the request sets parallel_tool_calls. Gemma 4 and Muse constrain that choice to their native tool-call syntax, because their parsers skip JSON guided decoding. gpt-oss stops a required or named choice after one call. A harmony call left in the message text is returned as that tool call. tool_choice none omits the tool list. SGLang launch passes that family's tool parser, mapping openai to gpt-oss, llama3_json to llama3, and muse_glimmer to muse. That name is separate from the serverless `{gpu}_vllm` global, because Modal loads the class by module attribute. That container sleeps the loaded engine and Modal snapshots it; later replicas of the same deployment wake the snapshot. A chat or decision request connects to the container the controller already scaled; it does not call `update_autoscaler` or reread the base manifest. Dedicated chat looks up the worker once, then posts to the port forward on that container. A parametrized web endpoint cannot accept POST. Shared inference still uses the `infer` RPC. Chat completions with `stream: true` flush each server-sent event. `run_inference` and the inference-request job still wait for the finished reply, because a tool result has no open token stream. Gateway ids `dedicated/<trained model id>` skip `inference-ft-model` charges. The capability alias stays on the shared active model. The Console lists each model's current dedicated deployment and opens it on that model's inference page. MCP tools are `list_dedicated_gpus`, `start_dedicated_deployment`, `update_dedicated_deployment`, and `stop_dedicated_deployment`; `run_inference` accepts `dedicated/<trained model id>`. `seed_demo` does not create a live dedicated row.
## Workers
diff --git a/.gitignore b/.gitignore
index 4b635d69..190052b0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -195,3 +195,6 @@ tests/journeys/.runs/
# Local verification output; maintained regression inputs belong in tests/fixtures.
/tests/evidence/*
!/tests/evidence/README.md
+
+# Local interview packs (candidate task and answer key)
+/interview/
diff --git a/frontend/src/lib/inference-snippets.ts b/frontend/src/lib/inference-snippets.ts
index 6b07307d..ec359e35 100644
--- a/frontend/src/lib/inference-snippets.ts
+++ b/frontend/src/lib/inference-snippets.ts
@@ -101,8 +101,6 @@ export function buildDecisionSnippets(
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\"'\"'")}'`;
return {
curl: [
- "# pip install typesafe-sdk — or send the same body with curl.",
- "# A cold start can take a few minutes. The call waits for the answer.",
`curl --fail-with-body --silent --show-error --max-time 200 ${shellQuote(endpoint)} \\`,
' -H "Authorization: Bearer $OVERMIND_API_KEY" \\',
' -H "Content-Type: application/json" \\',
diff --git a/modal_shared/images/serve.py b/modal_shared/images/serve.py
index cef9bdd9..534a9c8d 100644
--- a/modal_shared/images/serve.py
+++ b/modal_shared/images/serve.py
@@ -57,6 +57,17 @@ def _from_vllm_openai(tag: str, *extra_pip: str, snapshot: bool = False) -> moda
# LoRA get_mm_mapping (#53513) both need this release.
_VLLM_TAG = "v0.30.0"
vllm_image = _from_vllm_openai(_VLLM_TAG)
+# Dedicated pools only. The shared inference app stays on _VLLM_TAG.
+_DEDICATED_VLLM_TAG = "v0.33.0"
+dedicated_vllm_image = _from_vllm_openai(_DEDICATED_VLLM_TAG)
+# v0.5.23-cu130 lowered Qwen3.5-4B from 443 to 347 tok/s on H100.
+_DEDICATED_SGLANG_TAG = "v0.5.22"
+dedicated_sglang_image = attach_serving_args(
+ modal.Image.from_registry(
+ f"lmsysorg/sglang:{_DEDICATED_SGLANG_TAG}",
+ setup_dockerfile_commands=["RUN ln -sf $(command -v python3) /usr/local/bin/python"],
+ ).entrypoint([])
+)
SERVE_IMAGES: dict[str, modal.Image] = {
SERVE_VLLM: vllm_image,
diff --git a/modal_shared/serving/args.py b/modal_shared/serving/args.py
index 599762a7..5a35c956 100644
--- a/modal_shared/serving/args.py
+++ b/modal_shared/serving/args.py
@@ -88,6 +88,9 @@ class VllmServeContext:
# Where to read chat_template.jinja from. An adapter carries the template it was trained
# with, which is not the stock base's.
chat_template_dir: str = ""
+ # DFlash draft directory on the weights volume. Empty leaves speculative decoding off.
+ draft_model: str = ""
+ draft_tokens: int = 0
def _serve_chat_template_path(model_path: str) -> str | None:
@@ -187,13 +190,30 @@ def build_vllm_args(ctx: VllmServeContext, spec: FamilySpec | None = None) -> li
"runai_streamer",
"--model-loader-extra-config",
json.dumps({"distributed": True}, separators=(",", ":")),
- "--cudagraph-capture-sizes",
- *([str(s) for s in CUDAGRAPH_CAPTURE_SIZES if s <= ctx.max_num_seqs] or ["1"]),
]
+ # The short capture list drops DFlash acceptance to about 5%, and the draft
+ # overhead then makes the server slower than the base. vLLM's own list does not.
+ if not ctx.draft_model:
+ cmd += [
+ "--cudagraph-capture-sizes",
+ *([str(s) for s in CUDAGRAPH_CAPTURE_SIZES if s <= ctx.max_num_seqs] or ["1"]),
+ ]
chat_tmpl = _serve_chat_template_path(ctx.chat_template_dir or ctx.model_path)
if chat_tmpl:
cmd += ["--chat-template", chat_tmpl]
+ if ctx.draft_model:
+ cmd += [
+ "--speculative-config",
+ json.dumps(
+ {
+ "method": "dflash",
+ "model": ctx.draft_model,
+ "num_speculative_tokens": ctx.draft_tokens,
+ },
+ separators=(",", ":"),
+ ),
+ ]
return cmd
diff --git a/modal_shared/serving/decision_http.py b/modal_shared/serving/decision_http.py
new file mode 100644
index 00000000..8956dfc3
--- /dev/null
+++ b/modal_shared/serving/decision_http.py
@@ -0,0 +1,125 @@
+"""vLLM /v1/systemone argv and the predict envelope DecisionEndpoint returns."""
+
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+
+from modal_shared.serving.args import snap_lora_rank
+
+
+def decision_vllm_command(
+ *,
+ model_path: str,
+ served_name: str,
+ adapter_path: str,
+ max_lora_rank: int,
+ max_model_len: int,
+ port: int = 8000,
+) -> list[str]:
+ """One joint head overlaid on the base, then that artifact's LoRA."""
+ rank = int(max_lora_rank or 0)
+ config = Path(adapter_path) / "adapter_config.json"
+ if config.is_file():
+ stored = int(json.loads(config.read_text()).get("r") or 0)
+ rank = max(rank, stored)
+ rank = snap_lora_rank(rank or 16)
+ return [
+ "vllm",
+ "serve",
+ model_path,
+ "--served-model-name",
+ f"{served_name}--base",
+ "--enable-lora",
+ "--max-loras",
+ "1",
+ "--max-lora-rank",
+ str(rank),
+ "--lora-modules",
+ f"{served_name}={adapter_path}",
+ "--host",
+ "0.0.0.0",
+ "--port",
+ str(port),
+ "--max-model-len",
+ str(max_model_len),
+ "--gpu-memory-utilization",
+ "0.90",
+ "--enforce-eager",
+ "--trust-remote-code",
+ "--dtype",
+ "bfloat16",
+ ]
+
+
+def decision_base_vllm_command(
+ *, model_path: str, served_name: str, max_model_len: int, port: int = 8000
+) -> list[str]:
+ """A catalog base whose decision head is already in the checkpoint."""
+ return [
+ "vllm",
+ "serve",
+ model_path,
+ "--served-model-name",
+ served_name,
+ "--host",
+ "0.0.0.0",
+ "--port",
+ str(port),
+ "--max-model-len",
+ str(max_model_len),
+ "--gpu-memory-utilization",
+ "0.90",
+ "--enforce-eager",
+ "--trust-remote-code",
+ "--dtype",
+ "bfloat16",
+ ]
+
+
+def systemone_question(request: dict) -> dict:
+ kind = request["kind"]
+ if kind == "noul":
+ return {"type": "noul", "instructions": request["question"]}
+ if kind == "score":
+ return {
+ "type": "score",
+ "instructions": request["question"],
+ "criteria": list(request["options"]),
+ }
+ return {
+ "type": "choice",
+ "instructions": request["question"],
+ "criteria": {option: option for option in request["options"]},
+ }
+
+
+def probabilities_for(request: dict, answer: dict) -> list[float]:
+ options = request["options"]
+ raw = answer.get("probabilities")
+ if isinstance(raw, dict):
+ values = [float(raw.get(option) or 0) for option in options]
+ elif isinstance(raw, list) and len(raw) == len(options):
+ values = [float(item) for item in raw]
+ elif request["kind"] == "noul" and "noul" in answer:
+ # Wire order matches the socket worker: options[1] is the positive class.
+ positive = float(answer["noul"])
+ values = [1 - positive, positive]
+ else:
+ raise ValueError("Invalid decision probabilities")
+ if len(values) != len(options) or any(
+ not math.isfinite(value) or not 0 <= value <= 1 for value in values
+ ):
+ raise ValueError("Invalid decision probabilities")
+ if not math.isclose(sum(values), 1, abs_tol=1e-3):
+ raise ValueError("Invalid decision probabilities")
+ return values
+
+
+def systemone_body(request: dict, served_name: str) -> dict:
+ return {
+ "model": served_name,
+ "state": request["state"],
+ "questions": {"0": systemone_question(request)},
+ }
diff --git a/modal_shared/serving/engine.py b/modal_shared/serving/engine.py
new file mode 100644
index 00000000..c4663216
--- /dev/null
+++ b/modal_shared/serving/engine.py
@@ -0,0 +1,36 @@
+"""Which dedicated engine serves a base.
+
+In-GPU sentence tok/s with the draft loaded. Absent means vLLM.
+"""
+
+from __future__ import annotations
+
+# Faster on SGLang than on vLLM for ordinary text.
+_SGLANG = frozenset(
+ {
+ "Qwen/Qwen3.5-0.8B",
+ "unsloth/Qwen3.5-0.8B",
+ "Qwen/Qwen3.5-2B",
+ "unsloth/Qwen3.5-2B",
+ "Qwen/Qwen3.5-4B",
+ "unsloth/Qwen3.5-4B",
+ "Qwen/Qwen3.5-9B",
+ "unsloth/Qwen3.5-9B",
+ "Qwen/Qwen3-4B",
+ "unsloth/Qwen3-4B",
+ "Qwen/Qwen3-8B",
+ "unsloth/Qwen3-8B",
+ "Qwen/Qwen3.6-27B",
+ "unsloth/Qwen3.6-27B",
+ "Qwen/Qwen3.8-27B",
+ "unsloth/Qwen3.8-27B",
+ "openai/gpt-oss-20b",
+ "unsloth/gpt-oss-20b-BF16",
+ }
+)
+
+
+def engine_for(repo: str) -> str:
+ if repo in _SGLANG:
+ return "sglang"
+ return "vllm"
diff --git a/modal_shared/serving/merge.py b/modal_shared/serving/merge.py
index 6c226db1..6c2a2adb 100644
--- a/modal_shared/serving/merge.py
+++ b/modal_shared/serving/merge.py
@@ -87,3 +87,56 @@ def _pair_prefix(tensor_name: str, lora_weights: dict[str, torch.Tensor]) -> str
if f"{outer}.lora_A.weight" in lora_weights and f"{outer}.lora_B.weight" in lora_weights:
return outer
return None
+
+
+def write_folded_checkpoint(base: Path, adapter: Path, output: Path) -> None:
+ """Write a full checkpoint with this adapter folded in.
+
+ SGLang reads safetensors itself, so the vLLM streamer hook cannot fold for it.
+ The delta is the same one ``install_weight_fold`` applies.
+ """
+ import gc
+ import shutil
+
+ from safetensors.torch import save_file
+
+ base = base.resolve()
+ output = output.resolve()
+ if output == base or output.is_relative_to(base):
+ raise ValueError(f"refusing to fold onto the base checkpoint: {output}")
+ weights = _load_adapter(adapter / "adapter_model.safetensors")
+ scale = _scale(json.loads((adapter / "adapter_config.json").read_text()))
+ if output.exists():
+ shutil.rmtree(output)
+ output.mkdir(parents=True)
+ for path in base.iterdir():
+ if path.suffix == ".safetensors":
+ continue
+ dest = output / path.name
+ if path.is_dir():
+ shutil.copytree(path, dest, dirs_exist_ok=True)
+ elif path.is_file():
+ shutil.copy2(path, dest)
+ consumed: set[str] = set()
+ shards = sorted(base.glob("*.safetensors"))
+ if not shards:
+ raise FileNotFoundError(f"No *.safetensors in base checkpoint: {base}")
+ for shard in shards:
+ tensors: dict[str, torch.Tensor] = {}
+ with safe_open(shard, framework="torch") as handle:
+ for name in handle.keys(): # noqa: SIM118
+ tensor = handle.get_tensor(name)
+ prefix = _pair_prefix(name, weights)
+ if prefix is not None:
+ delta = weights[f"{prefix}.lora_B.weight"] @ weights[f"{prefix}.lora_A.weight"]
+ tensor = tensor + scale * delta.to(dtype=tensor.dtype)
+ consumed.add(f"{prefix}.lora_A.weight")
+ consumed.add(f"{prefix}.lora_B.weight")
+ tensors[name] = tensor
+ save_file(tensors, output / shard.name)
+ del tensors
+ gc.collect()
+ leftover = set(weights) - consumed
+ if leftover:
+ first = sorted(leftover)[0]
+ raise RuntimeError(f"{len(leftover)} adapter keys were not merged; first: {first}")
diff --git a/modal_shared/serving/sglang.py b/modal_shared/serving/sglang.py
new file mode 100644
index 00000000..6b7de34f
--- /dev/null
+++ b/modal_shared/serving/sglang.py
@@ -0,0 +1,97 @@
+"""SGLang dedicated launch command."""
+
+from __future__ import annotations
+
+# vLLM's parser names that SGLang spells differently. Other names match.
+_TOOL_PARSER_NAMES = {
+ "openai": "gpt-oss",
+ "llama3_json": "llama3",
+ "muse_glimmer": "muse",
+}
+# Harmony has no thinking-off switch. This parser keeps the analysis channel out of content.
+_REASONING_PARSER_NAMES = {
+ "openai_gptoss": "gpt-oss",
+ "muse_glimmer": "muse",
+}
+
+
+def sglang_tool_parser(name: str) -> str:
+ return _TOOL_PARSER_NAMES.get(name, name)
+
+
+def sglang_reasoning_parser(name: str) -> str:
+ return _REASONING_PARSER_NAMES.get(name, name)
+
+
+def attention_backend(gpu_type: str, *, model: str = "") -> str:
+ # fa3 is the Hopper kernel. On Ada and Ampere it dies during graph capture.
+ hopper = gpu_type in {"H100", "H200"} or not gpu_type
+ if "gpt-oss" in model:
+ # This architecture rejects flashinfer. Triton runs on the other GPUs.
+ return "fa3" if hopper else "triton"
+ if hopper:
+ return "fa3"
+ return "flashinfer"
+
+
+def build_sglang_args(
+ *,
+ model_path: str,
+ served_name: str,
+ port: int,
+ draft_model: str = "",
+ draft_tokens: int = 0,
+ mtp: tuple[int, int, int] | None = None,
+ tool_call_parser: str = "",
+ reasoning_parser: str = "",
+ gpu_type: str = "",
+ model: str = "",
+) -> list[str]:
+ cmd = [
+ "python3",
+ "-m",
+ "sglang.launch_server",
+ "--model-path",
+ model_path,
+ "--served-model-name",
+ served_name,
+ "--tp-size",
+ "1",
+ "--attention-backend",
+ attention_backend(gpu_type, model=model),
+ "--mem-fraction-static",
+ "0.75",
+ "--dtype",
+ "bfloat16",
+ "--trust-remote-code",
+ "--host",
+ "0.0.0.0",
+ "--port",
+ str(port),
+ ]
+ if mtp:
+ steps, topk, tokens = mtp
+ cmd += [
+ "--speculative-algorithm",
+ "EAGLE",
+ "--speculative-num-steps",
+ str(steps),
+ "--speculative-eagle-topk",
+ str(topk),
+ "--speculative-num-draft-tokens",
+ str(tokens),
+ ]
+ elif draft_model:
+ cmd += [
+ "--speculative-algorithm",
+ "DFLASH",
+ "--speculative-draft-model-path",
+ draft_model,
+ "--speculative-num-draft-tokens",
+ str(draft_tokens),
+ ]
+ if tool_call_parser:
+ cmd += ["--tool-call-parser", sglang_tool_parser(tool_call_parser)]
+ if reasoning_parser:
+ cmd += ["--reasoning-parser", sglang_reasoning_parser(reasoning_parser)]
+ return cmd
diff --git a/modal_shared/serving/speculative.py b/modal_shared/serving/speculative.py
new file mode 100644
index 00000000..7faa0e24
--- /dev/null
+++ b/modal_shared/serving/speculative.py
@@ -0,0 +1,57 @@
+"""Which bases speculate. Absent means the server stays on the base alone."""
+
+from __future__ import annotations
+
+DRAFTS_DIRNAME = ".drafts"
+
+# (steps, top-k, draft tokens). The MTP head is inside the checkpoint.
+# Qwen's SGLang recipe, and what Modal's dedicated endpoints launch.
+_MTP: dict[str, tuple[int, int, int]] = {
+ "Qwen/Qwen3.5-0.8B": (3, 1, 4),
+ "unsloth/Qwen3.5-0.8B": (3, 1, 4),
+ "Qwen/Qwen3.5-2B": (3, 1, 4),
+ "unsloth/Qwen3.5-2B": (3, 1, 4),
+ "Qwen/Qwen3.5-4B": (3, 1, 4),
+ "unsloth/Qwen3.5-4B": (3, 1, 4),
+ "Qwen/Qwen3.5-9B": (3, 1, 4),
+ "unsloth/Qwen3.5-9B": (3, 1, 4),
+ "Qwen/Qwen3.6-27B": (3, 1, 4),
+ "unsloth/Qwen3.6-27B": (3, 1, 4),
+}
+
+# (draft repo, num_speculative_tokens). DFlash2 uses the same method
+# with 7 draft tokens and needs the dedicated vLLM 0.33 image.
+_DRAFTS: dict[str, tuple[str, int]] = {
+ "Qwen/Qwen3-4B": ("z-lab/Qwen3-4B-DFlash-b16", 15),
+ "unsloth/Qwen3-4B": ("z-lab/Qwen3-4B-DFlash-b16", 15),
+ "Qwen/Qwen3-8B": ("z-lab/Qwen3-8B-DFlash-b16", 15),
+ "unsloth/Qwen3-8B": ("z-lab/Qwen3-8B-DFlash-b16", 15),
+ "meta-llama/Llama-3.1-8B-Instruct": ("z-lab/LLaMA3.1-8B-Instruct-DFlash-UltraChat", 15),
+ "unsloth/Llama-3.1-8B-Instruct": ("z-lab/LLaMA3.1-8B-Instruct-DFlash-UltraChat", 15),
+ "Qwen/Qwen3.5-27B": ("z-lab/Qwen3.5-27B-DFlash", 15),
+ "unsloth/Qwen3.5-27B": ("z-lab/Qwen3.5-27B-DFlash", 15),
+ "Qwen/Qwen3-Coder-30B-A3B-Instruct": ("z-lab/Qwen3-Coder-30B-A3B-DFlash", 15),
+ "openai/gpt-oss-20b": ("z-lab/gpt-oss-20b-DFlash", 15),
+ "unsloth/gpt-oss-20b-BF16": ("z-lab/gpt-oss-20b-DFlash", 15),
+ "google/gemma-4-26B-A4B-it": ("z-lab/gemma-4-26B-A4B-it-DFlash", 15),
+ "unsloth/gemma-4-26B-A4B-it": ("z-lab/gemma-4-26B-A4B-it-DFlash", 15),
+ "Qwen/Qwen3.5-35B-A3B": ("z-lab/Qwen3.5-35B-A3B-DFlash", 15),
+ "unsloth/Qwen3.5-35B-A3B": ("z-lab/Qwen3.5-35B-A3B-DFlash", 15),
+ "google/gemma-4-31B-it": ("z-lab/gemma-4-31B-it-DFlash", 15),
+ "unsloth/gemma-4-31B-it": ("z-lab/gemma-4-31B-it-DFlash", 15),
+ "Qwen/Qwen3.8-27B": ("z-lab/Qwen3.8-27B-DFlash2", 7),
+ "unsloth/Qwen3.8-27B": ("z-lab/Qwen3.8-27B-DFlash2", 7),
+ "unsloth/Muse-Glimmer-30B": ("z-lab/Muse-Glimmer-30B-DFlash2", 7),
+}
+
+
+def mtp_for(repo: str) -> tuple[int, int, int] | None:
+ return _MTP.get(repo)
+
+
+def draft_for(repo: str) -> tuple[str, int] | None:
+ return _DRAFTS.get(repo)
+
+
+def draft_volume_path(mount: str, draft_repo: str) -> str:
+ return f"{mount}/{DRAFTS_DIRNAME}/{draft_repo.replace('/', '--')}"
diff --git a/overbae/api/inference_requests.py b/overbae/api/inference_requests.py
index 9c5747c1..2c30a84f 100644
--- a/overbae/api/inference_requests.py
+++ b/overbae/api/inference_requests.py
@@ -82,10 +82,10 @@ class DeploymentInferenceView(APIView):
)
-def _dedicated_systemone(request, model, names, decisions):
+def _dedicated_systemone(request, model):
from django.utils import timezone
- from overbae.services.dedicated import lookup, serve_decision
+ from overbae.services.dedicated import lookup, serve_systemone
from overbae.services.deployed_chat import record_inference_call
row = lookup(model, project_ids_for(request.user, request.auth))
@@ -101,7 +101,7 @@ def _dedicated_systemone(request, model, names, decisions):
)
started = timezone.now()
try:
- result = serve_decision(row, decisions)
+ result = serve_systemone(row, request.data)
except InputValidationError as exc:
code = 503 if "not online" in exc.detail else 400
return Response({"error": {"message": exc.detail, "type": "invalid_request"}}, status=code)
@@ -120,16 +120,20 @@ def _dedicated_systemone(request, model, names, decisions):
requested_model=model,
bill=False,
)
+ answers = result.get("answers")
+ if not isinstance(answers, dict):
+ return Response(
+ {"error": {"message": "Decision inference failed.", "type": "server_error"}},
+ status=502,
+ )
usage = result.get("usage") or {}
return Response(
{
"model": model,
- "answers": systemone.answer(
- names, [item["kind"] for item in decisions], result["predictions"]
- ),
+ "answers": answers,
"usage": {
- "input_tokens": usage.get("prompt_tokens") or 0,
- "output_tokens": usage.get("completion_tokens") or 0,
+ "input_tokens": usage.get("input_tokens") or usage.get("prompt_tokens") or 0,
+ "output_tokens": usage.get("output_tokens") or usage.get("completion_tokens") or 0,
"cost": None,
},
"id": str(row.id),
@@ -145,7 +149,7 @@ class SystemOneView(APIView):
try:
model, _state, names, decisions = systemone.parse(body)
if str(model).startswith("dedicated/"):
- return _dedicated_systemone(request, model, names, decisions)
+ return _dedicated_systemone(request, model)
deployment = systemone.resolve(model, project_ids_for(request.user, request.auth))
except InputValidationError as exc:
return Response(
diff --git a/overbae/modal/decision_catalog.py b/overbae/modal/decision_catalog.py
index f2c9c20e..2c4bb273 100644
--- a/overbae/modal/decision_catalog.py
+++ b/overbae/modal/decision_catalog.py
@@ -34,4 +34,5 @@ def options() -> list[dict]:
"decision_index": entry["decision"].get("decision_index"),
}
for entry in models().values()
+ if (entry.get("inference") or {}).get("enabled", True)
]
diff --git a/overbae/modal/modal_decision_serving.py b/overbae/modal/modal_decision_serving.py
index d59281cb..85e96e68 100644
--- a/overbae/modal/modal_decision_serving.py
+++ b/overbae/modal/modal_decision_serving.py
@@ -1,23 +1,29 @@
import json
-import math
import os
import re
import shutil
-import socket
import subprocess
-import sys
import tempfile
import time
+import urllib.error
+import urllib.request
from pathlib import Path
import modal
from modal_shared.decision_artifact import read_artifact
-from modal_shared.decision_inference import input_digest
from modal_shared.decisions import decision_request
+from modal_shared.images.serve import dedicated_vllm_image
from modal_shared.images.train import TRAIN_IMAGES
from modal_shared.operational_events import STORE, Journal
-from modal_shared.serving.artifacts import atomic_json, read_base_manifest
+from modal_shared.serving.artifacts import read_base_manifest
+from modal_shared.serving.decision_http import (
+ decision_base_vllm_command,
+ decision_vllm_command,
+ probabilities_for,
+ systemone_body,
+)
+from modal_shared.serving.stage import stage_base
from modal_shared.stacks import TRAIN_DECISION
from modal_shared.training_release import serving_identity
@@ -33,7 +39,6 @@ app = modal.App(
weights = modal.Volume.from_name("overmind-weights")
training = modal.Volume.from_name("overmind-sft")
image = TRAIN_IMAGES[TRAIN_DECISION]
-assets = Path("/root/sft_assets")
def artifact_path(identity):
@@ -76,131 +81,188 @@ def publish(remote_id, artifact_identity):
return {"weights_path": str(destination), "artifact_identity": artifact_identity}
- image=image,
- gpu="H100",
- timeout=1200,
- scaledown_window=120,
- max_containers=1,
- volumes={"/weights": weights},
-)
[email protected](max_inputs=16)
-class DecisionEndpoint:
- weights_path: str = modal.parameter()
- artifact_identity: str = modal.parameter()
- max_model_len: int = modal.parameter()
- # Empty stays the shared serverless pool. A dedicated id is its own pool,
- # so its autoscaler cannot pin every decision of this artifact.
- pool: str = modal.parameter(default="")
-
- @modal.enter()
- def load(self):
- weights.reload()
- checkpoint = artifact_path(self.artifact_identity)
- if str(checkpoint) != self.weights_path:
- raise ValueError("Serving path differs from the pinned artifact")
- artifact = read_artifact(checkpoint)
- if artifact["identity"] != self.artifact_identity:
- raise ValueError("Serving identity differs")
- config = artifact["training"]["model_config"]
- base = read_base_manifest(Path(config["BASE_MODEL_PATH"]))
- if base["identity"] != artifact["training"]["base_identity"]:
- raise ValueError("Serving base identity differs")
- if config["UNSLOTH_IMAGE"] != TRAIN_DECISION:
- raise ValueError("Decision artifact requires another runtime")
- self.temporary = tempfile.TemporaryDirectory(prefix="decision-serving-")
- self.work = Path(self.temporary.name)
- self.socket_path = self.work / "readout.sock"
- atomic_json(
- self.work / "preparation.json",
- {
- "context_length": self.max_model_len,
- "vocab_fingerprint": artifact["vocab_fingerprint"],
- "renderer": artifact["renderer"],
- },
- )
- env = {
- **os.environ,
- **{key: str(value) for key, value in config.items() if value is not None},
- "TRAINING_OBJECTIVE": artifact["objective"],
- "MAX_LENGTH": str(self.max_model_len),
- "SEED": str(artifact["training"]["seed"]),
- "BT_CHECKPOINT_DIR": str(checkpoint),
- "BT_RUN_DIR": str(self.work),
- "PER_DEVICE_BATCH": "16",
- "PADDED_TOKEN_BUDGET": str(max(32768, self.max_model_len)),
- "DECISION_SERVICE_SOCKET": str(self.socket_path),
- }
- self.log = (self.work / "worker.log").open("w")
- self.process = subprocess.Popen(
- [sys.executable, str(assets / "train.py")],
- cwd=self.work,
- env=env,
- stdout=self.log,
- stderr=subprocess.STDOUT,
- )
- deadline = time.monotonic() + 900
- while not self.socket_path.exists():
- if self.process.poll() is not None or time.monotonic() >= deadline:
- raise RuntimeError("Decision serving worker did not become ready")
- time.sleep(0.1)
-
- @modal.method()
- def predict(self, requests):
- if not isinstance(requests, list) or not 1 <= len(requests) <= 16:
- raise ValueError("Expected 1-16 decisions")
- requests = [decision_request(request) for request in requests]
- encoded = json.dumps(requests).encode()
- if len(encoded) > 256_000:
- raise ValueError("Decision inputs exceed the request limit")
- started = time.monotonic()
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
- connection.settimeout(900)
- connection.connect(str(self.socket_path))
- connection.sendall(encoded + b"\n")
- with connection.makefile("rb") as source:
- result = json.loads(source.readline(32 * 1024 * 1024))
- if "error" in result:
- return {"error_code": "inference_rejected"}
- predictions = result.get("predictions", [])
- if result.get("model_identity") != self.artifact_identity or len(predictions) != len(
- requests
- ):
- raise ValueError("Decision response identity or coverage differs")
- indexed = {prediction["key"]: prediction for prediction in predictions}
- if set(indexed) != {str(index) for index in range(len(requests))}:
- raise ValueError("Decision response keys differ")
- predictions = [indexed[str(index)] for index in range(len(requests))]
- for request, prediction in zip(requests, predictions, strict=True):
- probabilities = prediction["probabilities"]
- if (
- prediction["input_sha256"] != input_digest(request)
- or prediction["kind"] != request["kind"]
- or prediction["model_identity"] != self.artifact_identity
- or len(probabilities) != len(request["options"])
- or any(not math.isfinite(p) or not 0 <= p <= 1 for p in probabilities)
- or not math.isclose(sum(probabilities), 1, abs_tol=1e-6)
- ):
- raise ValueError("Invalid decision probabilities")
- prediction["options"] = request["options"]
- tokens = sum(result["input_tokens"])
- return {
- "predictions": predictions,
- "model_identity": self.artifact_identity,
- "usage": {"prompt_tokens": tokens, "completion_tokens": 0, "total_tokens": tokens},
- "latency_ms": (time.monotonic() - started) * 1000,
- "finish_reason": "stop",
- }
-
- @modal.exit()
- def stop(self):
- if hasattr(self, "process"):
- self.process.terminate()
- self.process.wait(timeout=20)
- if hasattr(self, "log"):
- self.log.close()
- if hasattr(self, "temporary"):
- self.temporary.cleanup()
+VLLM_PORT = 8000
+
+
+def _wait_until_healthy(process: subprocess.Popen, log_path: Path) -> None:
+ deadline = time.monotonic() + 900
+ url = f"http://127.0.0.1:{VLLM_PORT}/health"
+ while time.monotonic() < deadline:
+ if process.poll() is not None:
+ tail = log_path.read_text(errors="replace")[-2000:] if log_path.is_file() else ""
+ raise RuntimeError(f"vLLM exited before becoming healthy: {tail}")
+ try:
+ with urllib.request.urlopen(url, timeout=2) as response:
+ if response.status == 200:
+ return
+ except (urllib.error.URLError, TimeoutError):
+ time.sleep(1)
+ raise RuntimeError("vLLM did not become healthy")
+
+
+def _decision_worker(cls_name):
+ class DecisionEndpoint:
+ max_model_len: int = modal.parameter()
+ weights_path: str = modal.parameter(default="")
+ artifact_identity: str = modal.parameter(default="")
+ base_repo: str = modal.parameter(default="")
+
+ @modal.enter()
+ def load(self):
+ self.work = Path(tempfile.mkdtemp(prefix="decision-serving-"))
+ log_path = self.work / "worker.log"
+ self.log = log_path.open("w")
+ if self.base_repo:
+ if self.base_repo == "LiquidAI/d1-omni-600M":
+ raise ValueError(
+ "LiquidAI/d1-omni-600M cannot be served: text_config has no num_attention_heads."
+ )
+ self.served_name = self.base_repo
+ self.identity = self.base_repo
+ command = decision_base_vllm_command(
+ model_path=self.base_repo,
+ served_name=self.served_name,
+ max_model_len=self.max_model_len,
+ port=VLLM_PORT,
+ )
+ else:
+ weights.reload()
+ checkpoint = artifact_path(self.artifact_identity)
+ if str(checkpoint) != self.weights_path:
+ raise ValueError("Serving path differs from the pinned artifact")
+ artifact = read_artifact(checkpoint)
+ if artifact["identity"] != self.artifact_identity:
+ raise ValueError("Serving identity differs")
+ config = artifact["training"]["model_config"]
+ base_path = Path(config["BASE_MODEL_PATH"])
+ base = read_base_manifest(base_path)
+ if base["identity"] != artifact["training"]["base_identity"]:
+ raise ValueError("Serving base identity differs")
+ if config["UNSLOTH_IMAGE"] != TRAIN_DECISION:
+ raise ValueError("Decision artifact requires another runtime")
+ if not (checkpoint / "joint_head.safetensors").is_file():
+ raise ValueError("Decision artifact is missing its trained head")
+ staged = stage_base(base_path, checkpoint, self.work / "serve")
+ for name in (
+ "joint_head.safetensors",
+ "joint_head_config.json",
+ "unsloth_decision_config.json",
+ ):
+ src = checkpoint / name
+ if not src.is_file():
+ continue
+ dest = staged / name
+ if dest.is_symlink() or dest.exists():
+ dest.unlink()
+ dest.symlink_to(src)
+ self.served_name = "decision"
+ self.identity = self.artifact_identity
+ command = decision_vllm_command(
+ model_path=str(staged),
+ served_name=self.served_name,
+ adapter_path=str(checkpoint),
+ max_lora_rank=0,
+ max_model_len=self.max_model_len,
+ port=VLLM_PORT,
+ )
+ self.process = subprocess.Popen(
+ command,
+ cwd=self.work,
+ stdout=self.log,
+ stderr=subprocess.STDOUT,
+ )
+ _wait_until_healthy(self.process, log_path)
+
+ def _ask(self, request: dict) -> tuple[list[float], dict]:
+ body = json.dumps(systemone_body(request, self.served_name)).encode()
+ request_http = urllib.request.Request(
+ f"http://127.0.0.1:{VLLM_PORT}/v1/systemone",
+ data=body,
+ headers={"content-type": "application/json"},
+ method="POST",
+ )
+ try:
+ with urllib.request.urlopen(request_http, timeout=120) as response:
+ payload = json.loads(response.read())
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:500]
+ raise ValueError(detail or "vLLM rejected the decision") from exc
+ answer = (payload.get("answers") or {}).get("0") or {}
+ return probabilities_for(request, answer), payload.get("usage") or {}
+
+ @modal.method()
+ def predict(self, requests):
+ if not isinstance(requests, list) or not 1 <= len(requests) <= 16:
+ raise ValueError("Expected 1-16 decisions")
+ requests = [decision_request(request) for request in requests]
+ if len(json.dumps(requests).encode()) > 256_000:
+ raise ValueError("Decision inputs exceed the request limit")
+ started = time.monotonic()
+ predictions = []
+ prompt_tokens = 0
+ try:
+ for index, request in enumerate(requests):
+ probabilities, usage = self._ask(request)
+ prompt_tokens += int(
+ usage.get("input_tokens") or usage.get("prompt_tokens") or 0
+ )
+ predictions.append(
+ {
+ "key": str(index),
+ "kind": request["kind"],
+ "options": request["options"],
+ "probabilities": probabilities,
+ "model_identity": self.identity,
+ }
+ )
+ except ValueError:
+ return {"error_code": "inference_rejected"}
+ return {
+ "predictions": predictions,
+ "model_identity": self.identity,
+ "usage": {
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": 0,
+ "total_tokens": prompt_tokens,
+ },
+ "latency_ms": (time.monotonic() - started) * 1000,
+ "finish_reason": "stop",
+ }
+
+ @modal.exit()
+ def stop(self):
+ if hasattr(self, "process"):
+ self.process.terminate()
+ try:
+ self.process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ if hasattr(self, "log"):
+ self.log.close()
+ if hasattr(self, "work"):
+ shutil.rmtree(self.work, ignore_errors=True)
+
+ DecisionEndpoint.__name__ = cls_name
+ DecisionEndpoint.__qualname__ = cls_name
+ return DecisionEndpoint
+
+
+def register_decision_endpoint(modal_app, cls_name, *, max_containers=1):
+ # The serving-release secret is what lets a container import build this app object.
+ return modal_app.cls(
+ image=dedicated_vllm_image,
+ gpu="H100",
+ timeout=1800,
+ scaledown_window=120,
+ max_containers=max_containers,
+ volumes={"/weights": weights},
+ secrets=[modal.Secret.from_dict({"OVERMIND_SERVING_RELEASE": json.dumps(RELEASE)})],
+ )(modal.concurrent(max_inputs=16)(_decision_worker(cls_name)))
+
+
+DecisionEndpoint = register_decision_endpoint(app, "DecisionEndpoint")
+# Modal loads a deployed class with getattr(module, name). This is the user class.
+decision_dedicated = _decision_worker("decision_dedicated")
@app.function(image=image, timeout=1200)
diff --git a/overbae/modal/modal_dedicated_worker.py b/overbae/modal/modal_dedicated_worker.py
index 48fd2d70..baaf355a 100644
--- a/overbae/modal/modal_dedicated_worker.py
+++ b/overbae/modal/modal_dedicated_worker.py
@@ -5,7 +5,8 @@ Deploy alongside the shared inference app:
modal deploy overbae/modal/modal_dedicated_worker.py --env overmind-dev
H100 exists only here. Each deployment binds its own model name, so its
-autoscaler cannot pin the shared ``overmind-inference`` pools.
+autoscaler cannot pin the shared ``overmind-inference`` pools. Decision
+deployments use the same vLLM classes. Serverless ``DecisionEndpoint`` boots this vLLM image.
"""
# Modal deploy resolves the module attribute `app` and never calls it.
diff --git a/overbae/modal/modal_vllm_worker.py b/overbae/modal/modal_vllm_worker.py
index aa1c425c..b49f9ebe 100644
--- a/overbae/modal/modal_vllm_worker.py
+++ b/overbae/modal/modal_vllm_worker.py
@@ -54,6 +54,16 @@ TARGET_CONCURRENT_INPUTS = 28 # autoscaler only adds a replica near this load
MAX_CONTAINERS_PER_MODEL = 1 # queue excess; raise if sustained load needs fan-out
VLLM_PORT = 8000
+
+
+def _local_vllm_headers(worker, headers: dict) -> dict:
+ safe = {k: v for k, v in headers.items() if k.lower() not in ("host", "content-length")}
+ key = os.environ.get("INFERENCE_API_KEY", "")
+ if key and getattr(worker, "direct_vllm", False):
+ safe["authorization"] = f"Bearer {key}"
+ return safe
+
+
# NemotronH/Mamba-hybrid checkpoints can need 15-20+ min to become healthy on a cold
# container: large weight download plus Triton SSM-kernel autotuning on first call
# (vllm-project/vllm#34399). The ceiling must leave margin between _wait_for_vllm timing
@@ -88,6 +98,8 @@ from modal_shared.images.serve import ( # noqa: E402
LORA_SERVE_IMAGES,
SERVE_IMAGES,
api_server_image,
+ dedicated_sglang_image,
+ dedicated_vllm_image,
)
from modal_shared.stacks import GPU_TIER, WORKER_CLS, WORKER_MEMORY_MIB # noqa: E402
@@ -99,6 +111,19 @@ inference_secret = modal.Secret.from_name("overmind-inference")
_volume_mounts = {WEIGHTS_MOUNT: weights_vol}
+def _decision_serve_args(worker, model_path: str) -> list[str]:
+ from modal_shared.serving.decision_http import decision_vllm_command
+
+ return decision_vllm_command(
+ model_path=model_path,
+ served_name=worker.model_name,
+ adapter_path=worker._decision_lora,
+ max_lora_rank=int(worker.max_lora_rank or 0),
+ max_model_len=worker.max_model_len,
+ port=VLLM_PORT,
+ )
+
+
def _vllm_control(path: str):
request = urllib.request.Request(
f"http://127.0.0.1:{VLLM_PORT}{path}",
@@ -126,7 +151,9 @@ def _wait_for_vllm(
reported_at = started - 15
while time.monotonic() < deadline:
if proc is not None and proc.poll() is not None:
- raise RuntimeError(f"vLLM exited before becoming healthy (exit_code={proc.returncode})")
+ raise RuntimeError(
+ f"engine exited before becoming healthy (exit_code={proc.returncode})"
+ )
now = time.monotonic()
if journal and now - reported_at >= 15:
journal.emit(
@@ -145,7 +172,7 @@ def _wait_for_vllm(
def _make_worker_health_app():
"""Kept only so ``_resolve_worker_url`` can mint a stable URL string for the registry. Real
- traffic goes through the ``infer`` RPC."""
+ traffic on the shared pool goes through the ``infer`` RPC."""
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
@@ -338,15 +365,11 @@ class _BaseVLLMWorker:
)
adapter_rel = getattr(self, "adapter_path", "") or ""
- if adapter_rel:
- from modal_shared.serving.stage import stage_base
-
- adapter_dir = Path(WEIGHTS_MOUNT) / adapter_rel
- base_path = full_path
- staged = stage_base(Path(base_path), adapter_dir, Path("/tmp/overmind-serve"))
- _os.environ["OVERMIND_FOLD_ADAPTER"] = str(adapter_dir)
- full_path = str(staged)
- print(f"[vLLM] folding {adapter_dir} while reading {base_path}")
+ # The staged dir has no .meta.json repo, so the draft map would miss.
+ folded_repo = ""
+ base_path = Path(full_path)
+ if adapter_rel and (base_path / BASE_MANIFEST).is_file():
+ folded_repo = read_base_manifest(base_path)["repo"]
if not self.enable_lora:
_rewrite_legacy_layer_types(Path(full_path) / "config.json", _json=_json)
@@ -362,10 +385,49 @@ class _BaseVLLMWorker:
base_model = meta.get("base_model") or ""
except Exception:
pass
+ if not base_model:
+ base_model = folded_repo
+ if not base_model and ".base_models/" in self.model_path:
+ slug = self.model_path.split(".base_models/", 1)[1].split("/", 1)[0]
+ base_model = slug.replace("--", "/", 1)
+ engine = getattr(self, "engine", "vllm")
+ if adapter_rel:
+ adapter_dir = Path(WEIGHTS_MOUNT) / adapter_rel
+ if engine == "sglang":
+ from modal_shared.serving.merge import write_folded_checkpoint
+
+ folded = Path("/tmp/overmind-folded")
+ write_folded_checkpoint(base_path, adapter_dir, folded)
+ full_path = str(folded)
+ print(f"[serve] folded {adapter_dir} into {folded}")
+ else:
+ from modal_shared.serving.stage import stage_base
+
+ staged = stage_base(base_path, adapter_dir, Path("/tmp/overmind-serve"))
+ head = adapter_dir / "joint_head.safetensors"
+ if head.is_file():
+ for name in (
+ "joint_head.safetensors",
+ "joint_head_config.json",
+ "unsloth_decision_config.json",
+ ):
+ src = adapter_dir / name
+ if not src.is_file():
+ continue
+ dest = staged / name
+ if dest.is_symlink() or dest.exists():
+ dest.unlink()
+ dest.symlink_to(src)
+ self._decision_lora = str(adapter_dir)
+ print(f"[vLLM] decision head {adapter_dir} on {base_path}")
+ else:
+ _os.environ["OVERMIND_FOLD_ADAPTER"] = str(adapter_dir)
+ print(f"[vLLM] folding {adapter_dir} while reading {base_path}")
+ full_path = str(staged)
# Runtime adapter load is what lets a new deployment join an already-warm base pool
# instead of booting its own container.
- if self.enable_lora:
+ if self.enable_lora and not getattr(self, "_decision_lora", ""):
_os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "1"
base_model = read_base_manifest(Path(full_path))["repo"]
@@ -376,8 +438,22 @@ class _BaseVLLMWorker:
multimodal_text_only_args,
)
from modal_shared.serving.capacity import GPU_VRAM_GB, sequence_cap_for_checkpoint
+ from modal_shared.serving.speculative import draft_for, draft_volume_path, mtp_for
spec = resolve(base_model or self.model_name)
+ draft_model = ""
+ draft_tokens = 0
+ bf16 = (quantization or "bf16") in ("bf16", "none", "")
+ # An FP8 merged checkpoint stays on the base; the head and the drafts are BF16.
+ mtp = mtp_for(base_model) if bf16 else None
+ found = None if mtp or not bf16 else draft_for(base_model)
+ if found:
+ repo, draft_tokens = found
+ draft_model = draft_volume_path(WEIGHTS_MOUNT, repo)
+ if not (Path(draft_model) / "config.json").is_file():
+ raise RuntimeError(
+ f"DFlash draft {repo} is not on the weights volume ({draft_model})"
+ )
vram_gb = GPU_VRAM_GB.get(getattr(self, "gpu_type", ""), 0)
cap = sequence_cap_for_checkpoint(
Path(full_path), vram_gb=vram_gb, max_model_len=self.max_model_len
@@ -385,53 +461,79 @@ class _BaseVLLMWorker:
# 0 means one full sequence does not fit; still admit one so the boot error is vLLM's.
max_num_seqs = MAX_CONCURRENT_INPUTS if cap is None else max(1, cap)
print(
- f"[vLLM] Serving {full_path} "
+ f"[{engine}] Serving {full_path} "
f"(quantization={quantization!r} base_model={base_model!r} "
f"tool_parser={spec.tool_call_parser} family={spec.key} "
f"max_num_seqs={max_num_seqs} vram_gb={vram_gb})"
)
- cmd = build_vllm_args(
- VllmServeContext(
+ if engine == "sglang":
+ from modal_shared.serving.sglang import build_sglang_args
+
+ # gpt-oss has no thinking-off switch. The parser keeps analysis out of content.
+ cmd = build_sglang_args(
model_path=full_path,
- model_name=self.model_name,
- max_model_len=self.max_model_len,
+ served_name=self.model_name,
port=VLLM_PORT,
- max_num_seqs=max_num_seqs,
- quantization=quantization,
- base_model=base_model,
- enable_lora=self.enable_lora,
- max_lora_rank=self.max_lora_rank,
- ),
- spec,
- )
- if self.snapshot_weights:
- if not self.enable_lora:
- raise ValueError("Snapshot workers require shared-base LoRA mode")
- cmd += [
- "--enable-sleep-mode",
- "--distributed-executor-backend",
- "modal_shared.serving.snapshot.SnapshotExecutor",
- "--worker-extension-cls",
- "modal_shared.serving.weights.SharedBaseWeights",
- ]
- elif getattr(self, "snapshot_engine", False):
- cmd.append("--enable-sleep-mode")
- if "--chat-template" in cmd:
- print(f"[vLLM] Using checkpoint chat template: {full_path}/chat_template.jinja")
-
- if _is_text_only_finetune_of_multimodal_base(base_model, full_path, self.model_name):
- # Skip vLLM's multimodal init entirely, or it looks for the
- # preprocessor_config.json this checkpoint does not have.
- print(
- f"[vLLM] {base_model!r}/{self.model_name!r} is natively multimodal "
- "but checkpoint has no preprocessor/processor_config.json — "
- "serving language-model-only"
+ draft_model=draft_model,
+ draft_tokens=draft_tokens,
+ mtp=mtp,
+ tool_call_parser=spec.tool_call_parser,
+ reasoning_parser=spec.reasoning_parser or "",
+ gpu_type=getattr(self, "gpu_type", ""),
+ model=base_model,
)
- cmd += multimodal_text_only_args()
-
- if _os.environ.get("OVERMIND_FOLD_ADAPTER"):
- cmd = [sys.executable, "-m", "modal_shared.serving.fold_serve", *cmd[1:]]
- print("Starting vLLM:", " ".join(cmd))
+ else:
+ cmd = (
+ _decision_serve_args(self, full_path)
+ if getattr(self, "_decision_lora", "")
+ else build_vllm_args(
+ VllmServeContext(
+ model_path=full_path,
+ model_name=self.model_name,
+ max_model_len=self.max_model_len,
+ port=VLLM_PORT,
+ max_num_seqs=max_num_seqs,
+ quantization=quantization,
+ base_model=base_model,
+ enable_lora=self.enable_lora,
+ max_lora_rank=self.max_lora_rank,
+ draft_model=draft_model,
+ draft_tokens=draft_tokens,
+ ),
+ spec,
+ )
+ )
+ if self.snapshot_weights:
+ if not self.enable_lora:
+ raise ValueError("Snapshot workers require shared-base LoRA mode")
+ cmd += [
+ "--enable-sleep-mode",
+ "--distributed-executor-backend",
+ "modal_shared.serving.snapshot.SnapshotExecutor",
+ "--worker-extension-cls",
+ "modal_shared.serving.weights.SharedBaseWeights",
+ ]
+ elif getattr(self, "snapshot_engine", False):
+ cmd.append("--enable-sleep-mode")
+ if "--chat-template" in cmd:
+ print(f"[vLLM] Using checkpoint chat template: {full_path}/chat_template.jinja")
+
+ if _is_text_only_finetune_of_multimodal_base(base_model, full_path, self.model_name):
+ # Skip vLLM's multimodal init entirely, or it looks for the
+ # preprocessor_config.json this checkpoint does not have.
+ print(
+ f"[vLLM] {base_model!r}/{self.model_name!r} is natively multimodal "
+ "but checkpoint has no preprocessor/processor_config.json — "
+ "serving language-model-only"
+ )
+ cmd += multimodal_text_only_args()
+
+ if _os.environ.get("OVERMIND_FOLD_ADAPTER"):
+ cmd = [sys.executable, "-m", "modal_shared.serving.fold_serve", *cmd[1:]]
+ print(f"Starting {engine}:", " ".join(cmd))
+ if getattr(self, "direct_vllm", False) and _os.environ.get("INFERENCE_API_KEY"):
+ # The public tunnel hits this port. The key is not part of the logged command.
+ cmd += ["--api-key", _os.environ["INFERENCE_API_KEY"]]
self._serve_command = cmd
# List form (no shell) so JSON kwargs like --default-chat-template-kwargs
# are not mangled by the shell.
@@ -443,6 +545,9 @@ class _BaseVLLMWorker:
# Level 2 discards the weights, and the next container has nothing to wake.
_vllm_control("/sleep?level=1")
print("[vLLM] slept engine for snapshot", flush=True)
+ elif getattr(self, "direct_vllm", False):
+ # No snapshot, so nothing runs wake(). The tunnel has to open here.
+ self._open_direct()
def wake(self) -> None:
if not getattr(self, "snapshot_engine", False) or getattr(self, "_startup_error", None):
@@ -452,11 +557,29 @@ class _BaseVLLMWorker:
_vllm_control("/wake_up?tags=weights")
_vllm_control("/wake_up?tags=kv_cache")
_wait_for_vllm(proc=getattr(self, "_proc", None))
+ self._open_direct()
except Exception as error:
self._fail_startup(error)
return
print("[vLLM] snapshot restore ready", flush=True)
+ def _open_direct(self) -> None:
+ if getattr(self, "_tunnel", None) is not None or not getattr(self, "direct_vllm", False):
+ return
+ # A parametrized web endpoint 303s and drops POST. A port forward does not.
+ self._tunnel_cm = modal.forward(VLLM_PORT)
+ self._tunnel = self._tunnel_cm.__enter__()
+
+ @modal.method()
+ def direct_url(self) -> str:
+ err = getattr(self, "_startup_error", None)
+ if err:
+ raise RuntimeError(err)
+ tunnel = getattr(self, "_tunnel", None)
+ if tunnel is None:
+ raise RuntimeError("Dedicated tunnel did not open.")
+ return tunnel.url
+
@modal.exit()
def shutdown(self) -> None:
if hasattr(self, "_proc") and self._proc.poll() is None:
@@ -538,7 +661,13 @@ class _BaseVLLMWorker:
self._ensure_ready()
- if path not in {"/health", "/v1/models", "/v1/chat/completions", "/v1/completions"}:
+ if path not in {
+ "/health",
+ "/v1/models",
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/systemone",
+ }:
raise ValueError("Only inference endpoints may be proxied")
if adapter:
@@ -559,9 +688,7 @@ class _BaseVLLMWorker:
).encode(),
}
url = f"http://localhost:{VLLM_PORT}{path}"
- safe_headers = {
- k: v for k, v in headers.items() if k.lower() not in ("host", "content-length")
- }
+ safe_headers = _local_vllm_headers(self, headers)
async with httpx.AsyncClient(timeout=300) as client:
if journal:
await asyncio.to_thread(journal.emit, "generating")
@@ -614,9 +741,7 @@ class _BaseVLLMWorker:
).encode()
return
url = f"http://localhost:{VLLM_PORT}{path}"
- safe_headers = {
- k: v for k, v in headers.items() if k.lower() not in ("host", "content-length")
- }
+ safe_headers = _local_vllm_headers(self, headers)
async with (
httpx.AsyncClient(timeout=300) as client,
client.stream(method, url, headers=safe_headers, content=body) as resp,
@@ -939,9 +1064,12 @@ def _register_worker(
pin_resources=False,
max_containers: int | None = None,
owner=None,
+ image_override=None,
+ snapshot=True,
+ engine="vllm",
) -> None:
bucket, default_len = GPU_TIER[gpu_type]
- image = (LORA_SERVE_IMAGES if lora else SERVE_IMAGES)[serve_image]
+ image = image_override or (LORA_SERVE_IMAGES if lora else SERVE_IMAGES)[serve_image]
parameters = {
"__annotations__": {
"model_path": str,
@@ -965,14 +1093,19 @@ def _register_worker(
# A post-snapshot hook on the common base would also run for LoRA restores.
# Dedicated containers snapshot the slept engine, so startup runs before the
# snapshot and wake runs after every restore.
- parameters["startup"] = modal.enter(snap=bool(pin_resources))(_BaseVLLMWorker.startup)
+ parameters["engine"] = engine
+ parameters["startup"] = modal.enter(snap=bool(pin_resources and snapshot))(
+ _BaseVLLMWorker.startup
+ )
if pin_resources:
+ parameters["direct_vllm"] = True
# Empty serves the base. A path folds that one adapter while the shards are read.
parameters["__annotations__"]["adapter_path"] = str
parameters["adapter_path"] = modal.parameter(default="")
- parameters["__annotations__"]["snapshot_engine"] = bool
- parameters["snapshot_engine"] = modal.parameter(default=True)
- parameters["wake"] = modal.enter(snap=False)(_BaseVLLMWorker.wake)
+ if snapshot:
+ parameters["__annotations__"]["snapshot_engine"] = bool
+ parameters["snapshot_engine"] = modal.parameter(default=True)
+ parameters["wake"] = modal.enter(snap=False)(_BaseVLLMWorker.wake)
cls = type(
cls_name,
(_SharedBaseVLLMWorker if lora else _BaseVLLMWorker,),
@@ -1008,8 +1141,17 @@ def _register_worker(
"enable_memory_snapshot": True,
"experimental_options": {"enable_gpu_snapshot": True},
}
- if pin_resources
- else {}
+ if pin_resources and snapshot
+ else (
+ {
+ "cpu": 8,
+ "memory": WORKER_MEMORY_MIB[gpu_type],
+ # Modal's GPU disk floor. The folded checkpoint and compile cache fit.
+ "ephemeral_disk": 524288,
+ }
+ if pin_resources
+ else {}
+ )
)
),
},
@@ -1032,8 +1174,24 @@ def register_dedicated_classes(target_app, owner) -> None:
pin_resources=True,
max_containers=8,
owner=slot,
+ image_override=dedicated_vllm_image,
)
owner[name] = slot[name]
+ sglang_name = f"{token}_sglang_dedicated"
+ sglang_slot = {}
+ _register_worker(
+ sglang_name,
+ gpu_type,
+ "vllm",
+ target_app=target_app,
+ pin_resources=True,
+ snapshot=False,
+ engine="sglang",
+ max_containers=8,
+ owner=sglang_slot,
+ image_override=dedicated_sglang_image,
+ )
+ owner[sglang_name] = sglang_slot[sglang_name]
for (_gpu, _serve_image), _cls_name in WORKER_CLS.items():
diff --git a/overbae/modal/models.json b/overbae/modal/models.json
index 70b8ea8b..2645c20c 100644
--- a/overbae/modal/models.json
+++ b/overbae/modal/models.json
@@ -3673,7 +3673,8 @@
"hidden_size": 1024,
"inference": {
"gpu_type": "L4",
- "max_model_len": 16384
+ "max_model_len": 16384,
+ "enabled": false
},
"finetuning": {
"context_length": 16384,
@@ -3684,7 +3685,7 @@
"enabled": false
},
"lora": {
- "enabled": true
+ "enabled": false
}
}
},
@@ -3699,7 +3700,7 @@
"decision_index_edition": "0.3.2"
},
"disabled": true,
- "disabled_reason": "Exact training and verified serving runtime not yet qualified"
+ "disabled_reason": "vLLM 0.33.0 cannot load this checkpoint: text_config has no num_attention_heads."
},
{
"id": "LiquidAI/d1-3B",
diff --git a/overbae/modal/register_model.py b/overbae/modal/register_model.py
index 78e46dcd..aefb16a4 100644
--- a/overbae/modal/register_model.py
+++ b/overbae/modal/register_model.py
@@ -13,6 +13,7 @@ Storage layout:
/weights/{job_id}/.meta.json ready marker + serve metadata
/weights/.staging/{job_id}/ raw download; gone once the serving copy is ready
/weights/.base_models/{org--model}/ shared HF bases: LoRA merge source and serving base
+ /weights/.drafts/{org--draft}/ DFlash drafts for the bases that use one
/weights/.adapters/{job_id}/ LoRA adapters served on a shared base
S3 (baseten/modal only), the durable provider-independent home the UI's checkpoint-download
@@ -993,6 +994,32 @@ def list_base_models() -> list[str]:
)
+def _ensure_draft(base_model: str) -> None:
+ from huggingface_hub import snapshot_download # noqa: PLC0415
+
+ from modal_shared.serving.speculative import draft_for, draft_volume_path
+
+ found = draft_for(base_model)
+ if not found:
+ return
+ repo, _tokens = found
+ dest = Path(draft_volume_path(WEIGHTS_MOUNT, repo))
+ if _snapshot_is_complete(dest):
+ print(f"[draft] {repo} already cached at {dest}")
+ return
+ print(f"[draft] Downloading {repo} → {dest}")
+ dest.mkdir(parents=True, exist_ok=True)
+ snapshot_download(
+ repo_id=repo,
+ local_dir=str(dest),
+ ignore_patterns=["*.bin", "original/*", "*.pt"],
+ token=os.environ.get("HF_TOKEN") or None,
+ max_workers=16,
+ )
+ if not _snapshot_is_complete(dest):
+ raise RuntimeError(f"DFlash draft {repo} is incomplete after download ({dest})")
+
+
@app.function(
image=download_image,
timeout=4 * 60 * 60,
@@ -1017,38 +1044,33 @@ def fetch_base_model(*, base_model: str) -> dict:
weights_vol.reload()
base_dir = _base_model_dir(base_model)
- if _snapshot_is_complete(base_dir):
+ cached = _snapshot_is_complete(base_dir)
+ if cached:
manifest = seal_base(base_dir, base_model)
- weights_vol.commit()
print(f"[base] {base_model} already cached at {base_dir}")
- return {
- "base_model": base_model,
- "base_model_path": str(base_dir),
- "cached": True,
- "base_identity": manifest["identity"],
- }
-
- print(f"[base] Downloading {base_model} → {base_dir}")
- base_dir.mkdir(parents=True, exist_ok=True)
- snapshot_download(
- repo_id=base_model,
- local_dir=str(base_dir),
- ignore_patterns=["*.bin", "original/*", "*.pt"],
- token=os.environ.get("HF_TOKEN") or None,
- max_workers=16,
- )
- if not _snapshot_is_complete(base_dir):
- raise RuntimeError(
- f"Base snapshot for {base_model} is incomplete after download "
- f"({base_dir}) — refusing to hand a partial base to the LoRA merge"
+ else:
+ print(f"[base] Downloading {base_model} → {base_dir}")
+ base_dir.mkdir(parents=True, exist_ok=True)
+ snapshot_download(
+ repo_id=base_model,
+ local_dir=str(base_dir),
+ ignore_patterns=["*.bin", "original/*", "*.pt"],
+ token=os.environ.get("HF_TOKEN") or None,
+ max_workers=16,
)
- manifest = seal_base(base_dir, base_model)
+ if not _snapshot_is_complete(base_dir):
+ raise RuntimeError(
+ f"Base snapshot for {base_model} is incomplete after download "
+ f"({base_dir}) — refusing to hand a partial base to the LoRA merge"
+ )
+ manifest = seal_base(base_dir, base_model)
+ print(f"[base] {base_model} ready at {base_dir}")
+ _ensure_draft(base_model)
weights_vol.commit()
- print(f"[base] {base_model} ready at {base_dir}")
return {
"base_model": base_model,
"base_model_path": str(base_dir),
- "cached": False,
+ "cached": cached,
"base_identity": manifest["identity"],
}
diff --git a/overbae/services/dedicated.py b/overbae/services/dedicated.py
index 26661a8f..18ba9e8c 100644
--- a/overbae/services/dedicated.py
+++ b/overbae/services/dedicated.py
@@ -357,20 +357,63 @@ def _require_chat(row: DedicatedDeployment):
def serve_chat(row: DedicatedDeployment, body: bytes):
_require_chat(row)
- return dedicated_runtime.chat(dedicated_runtime.connect(row), row, body)
+ return dedicated_runtime.chat(row, body)
def serve_chat_stream(row: DedicatedDeployment, body: bytes):
_require_chat(row)
- return dedicated_runtime.iter_chat_stream(dedicated_runtime.connect(row), row, body)
+ return dedicated_runtime.iter_chat_stream(row, body)
-def serve_decision(row: DedicatedDeployment, decisions: list) -> dict:
+def _online_decision(row: DedicatedDeployment) -> None:
if row.deployed_model.inference_contract != "decision":
raise InputValidationError("This dedicated deployment is a chat model.")
if row.status != DedicatedDeployment.Status.ONLINE:
raise InputValidationError(NOT_ONLINE)
- return dedicated_runtime.predict(dedicated_runtime.connect(row), decisions, row)
+
+
+def serve_systemone(row: DedicatedDeployment, body: dict) -> dict:
+ _online_decision(row)
+ payload = dict(body)
+ payload["model"] = row.served_model_id
+ return dedicated_runtime.post_systemone(row, payload)
+
+
+def serve_decision(row: DedicatedDeployment, decisions: list) -> dict:
+ _online_decision(row)
+ questions = {}
+ for index, item in enumerate(decisions):
+ kind = item.get("kind") or "choice"
+ if kind == "classification":
+ kind = "choice"
+ questions[str(index)] = {
+ "type": kind,
+ "instructions": item["question"],
+ "criteria": {option: option for option in item["options"]},
+ }
+ result = dedicated_runtime.post_systemone(
+ row,
+ {
+ "model": row.served_model_id,
+ "state": decisions[0]["state"],
+ "questions": questions,
+ },
+ )
+ answers = result.get("answers") or {}
+ predictions = []
+ for index, item in enumerate(decisions):
+ answer = answers.get(str(index)) or {}
+ probabilities = answer.get("probabilities") or {}
+ predictions.append(
+ {
+ "options": item["options"],
+ "probabilities": [
+ float(probabilities.get(option) or 0) for option in item["options"]
+ ],
+ }
+ )
+ result["predictions"] = predictions
+ return result
def complete_request(payload: dict) -> dict:
diff --git a/overbae/services/dedicated_runtime.py b/overbae/services/dedicated_runtime.py
index f20dd49f..52782405 100644
--- a/overbae/services/dedicated_runtime.py
+++ b/overbae/services/dedicated_runtime.py
@@ -4,11 +4,15 @@ from __future__ import annotations
import inspect
import json
+import logging
import os
+import re
from decimal import Decimal
+import httpx
import modal
from asgiref.sync import async_to_sync
+from django.conf import settings
from modal_shared.serving.capacity import sequence_cap
from modal_shared.shared import rel_weights_path
@@ -17,15 +21,14 @@ from overbae.modal.gpu_selector import gpu_vram_gb
from overbae.modal.model_registry import get_model_config_any_backend
from overbae.services.dedicated_offer import serving_shape
+logger = logging.getLogger(__name__)
+
APP_NAME = "overmind-dedicated"
WORKER_UNAVAILABLE = "Dedicated worker is not deployed."
# with_options() builds a separate autoscaler. Keep one option set and change
# min, max, and idle through update_autoscaler, or a GPU change leaves the old set running.
_STABLE_MAX = 8
_STABLE_WINDOW = 3600
-# Releases published before the pool parameter reject the name. Those dedicated
-# starts share one option set per artifact and GPU.
-_unpooled_apps: set[str] = set()
def environment() -> str:
@@ -42,41 +45,32 @@ def _drive(result):
return result
-def worker_class_name(_deployed, gpu_type: str) -> str:
+def worker_class_name(deployed, gpu_type: str) -> str:
# Not `{gpu}_vllm`: that global is the serverless class, and Modal loads a class
# with getattr(module, name).
- token = gpu_type.replace("-", "")
- return f"{token}_vllm_dedicated"
-
-
-def _app_name(deployed) -> str:
- runtime = deployed.serving_runtime if isinstance(deployed.serving_runtime, dict) else {}
- return str(runtime.get("app") or "")
-
+ from modal_shared.serving.engine import engine_for
-def _pool_rejected(exc: BaseException) -> bool:
- text = str(exc)
- return "pool" in text and "not defined" in text
-
-
-def _drop_pool(deployment, exc: BaseException) -> bool:
- if deployment.deployed_model.inference_contract != "decision" or not _pool_rejected(exc):
- return False
- _unpooled_apps.add(_app_name(deployment.deployed_model))
- return True
+ token = gpu_type.replace("-", "")
+ engine = "vllm"
+ quant = getattr(deployed, "quantization", None) or "bf16"
+ if getattr(deployed, "inference_contract", "") != "decision" and quant in ("bf16", "none", ""):
+ engine = engine_for(getattr(deployed, "base_model_id", "") or "")
+ return f"{token}_{engine}_dedicated"
def parameters(deployment) -> dict:
deployed = deployment.deployed_model
if deployed.inference_contract == "decision":
- params = {
- "weights_path": deployed.weights_path,
- "artifact_identity": deployed.checkpoint_hash,
+ base = (deployed.base_model_id or "").replace("/", "--")
+ return {
+ "model_path": f".base_models/{base}",
+ "model_name": deployment.served_model_id,
"max_model_len": deployed.max_model_len,
+ "enable_lora": True,
+ "max_lora_rank": int(deployed.lora_rank or 0),
+ "adapter_path": rel_weights_path(deployed.weights_path),
+ "snapshot_engine": False,
}
- if _app_name(deployed) not in _unpooled_apps:
- params["pool"] = str(deployment.id)
- return params
path = rel_weights_path(deployed.weights_path)
params = {
"model_path": path,
@@ -132,7 +126,7 @@ def _variant(cls, deployment, *, maximum: int, idle_seconds: int):
return cls
-def _scale_once(cls, deployment, *, minimum: int, maximum: int, idle_seconds: int):
+def _scale(cls, deployment, *, minimum: int, maximum: int, idle_seconds: int):
instance = cls(**parameters(deployment))
method = getattr(instance, "update_autoscaler", None)
if method is not None:
@@ -146,24 +140,9 @@ def _scale_once(cls, deployment, *, minimum: int, maximum: int, idle_seconds: in
return instance
-def _scale(cls, deployment, *, minimum: int, maximum: int, idle_seconds: int):
- try:
- return _scale_once(
- cls, deployment, minimum=minimum, maximum=maximum, idle_seconds=idle_seconds
- )
- except Exception as exc:
- if not _drop_pool(deployment, exc):
- raise
- return _scale_once(
- cls, deployment, minimum=minimum, maximum=maximum, idle_seconds=idle_seconds
- )
-
-
def release(deployment, gpu_type: str) -> None:
"""Drop every autoscaler variant for one GPU class."""
deployed = deployment.deployed_model
- if deployed.inference_contract == "decision":
- return
try:
cls = _chat_cls(deployed, gpu_type)
option_sets = (
@@ -193,8 +172,6 @@ def release(deployment, gpu_type: str) -> None:
def retire_previous_options(deployment) -> None:
"""Scale down an option set that is not the stable one for this GPU."""
deployed = deployment.deployed_model
- if deployed.inference_contract == "decision":
- return
key = (max(int(deployment.max_replicas), 1), _window(deployment.idle_shutdown_seconds))
if key == (_STABLE_MAX, _STABLE_WINDOW):
return
@@ -217,23 +194,7 @@ def connect(deployment):
"""The container advance() already scaled. A request must not call update_autoscaler:
that control-plane round trip is seconds, and the GPU is already warm."""
deployed = deployment.deployed_model
- env = environment()
try:
- if deployed.inference_contract == "decision":
- runtime = deployed.serving_runtime or {}
- app_name = runtime.get("app")
- if not app_name:
- raise InputValidationError(WORKER_UNAVAILABLE)
- cls = modal.Cls.from_name(
- app_name, "DecisionEndpoint", environment_name=runtime.get("environment") or env
- )
- if hasattr(cls, "with_options"):
- cls = cls.with_options(
- gpu=deployment.gpu_type,
- max_containers=max(deployment.max_replicas, 1),
- scaledown_window=_window(deployment.idle_shutdown_seconds),
- )
- return cls(**parameters(deployment))
cls = _variant(
_chat_cls(deployed, deployment.gpu_type),
deployment,
@@ -249,25 +210,7 @@ def connect(deployment):
def bind(deployment, *, minimum: int, maximum: int, idle_seconds: int):
deployed = deployment.deployed_model
- env = environment()
try:
- if deployed.inference_contract == "decision":
- runtime = deployed.serving_runtime or {}
- app_name = runtime.get("app")
- if not app_name:
- raise InputValidationError(WORKER_UNAVAILABLE)
- cls = modal.Cls.from_name(
- app_name, "DecisionEndpoint", environment_name=runtime.get("environment") or env
- )
- if hasattr(cls, "with_options"):
- cls = cls.with_options(
- gpu=deployment.gpu_type,
- max_containers=max(maximum, 1),
- scaledown_window=_window(idle_seconds),
- )
- return _scale(
- cls, deployment, minimum=minimum, maximum=maximum, idle_seconds=idle_seconds
- )
cls = _chat_cls(deployed, deployment.gpu_type)
return _scale(
_variant(cls, deployment, maximum=_STABLE_MAX, idle_seconds=_STABLE_WINDOW),
@@ -284,30 +227,33 @@ def bind(deployment, *, minimum: int, maximum: int, idle_seconds: int):
def spawn_probe(instance, deployment) -> str:
deployed = deployment.deployed_model
- if deployed.inference_contract == "decision":
- call = instance.predict.spawn(
- [
- {
- "state": "Serving readiness check.",
- "question": "Select an option.",
- "kind": "choice",
- "options": ["A", "B"],
- }
- ]
- )
- else:
- call = instance.infer.spawn(
- method="POST",
- path="/v1/chat/completions",
- body=json.dumps(
- {
- "model": deployment.served_model_id,
- "messages": [{"role": "user", "content": "ping"}],
- "max_tokens": 1,
+ body = (
+ {
+ "model": deployment.served_model_id,
+ "state": "Serving readiness check.",
+ "questions": {
+ "ready": {
+ "type": "choice",
+ "instructions": "Select an option.",
+ "criteria": {"A": "A", "B": "B"},
}
- ).encode(),
- headers={"content-type": "application/json"},
- )
+ },
+ }
+ if deployed.inference_contract == "decision"
+ else {
+ "model": deployment.served_model_id,
+ "messages": [{"role": "user", "content": "ping"}],
+ "max_tokens": 1,
+ }
+ )
+ call = instance.infer.spawn(
+ method="POST",
+ path="/v1/systemone"
+ if deployed.inference_contract == "decision"
+ else "/v1/chat/completions",
+ body=json.dumps(body).encode(),
+ headers={"content-type": "application/json"},
+ )
return call.object_id
@@ -329,9 +275,9 @@ def probe_state(call_id: str) -> str:
def runner_count(instance, *, decision: bool) -> int | None:
- method = instance.predict if decision else instance.infer
+ del decision
try:
- stats_call = method.get_current_stats
+ stats_call = instance.infer.get_current_stats
stats = _drive(stats_call.aio()) if hasattr(stats_call, "aio") else stats_call()
except Exception:
return None
@@ -339,12 +285,179 @@ def runner_count(instance, *, decision: bool) -> int | None:
return int(value) if value is not None else None
+_HTTP: httpx.Client | None = None
+_DIRECT: dict[tuple[str, str], str] = {}
+
+
+def _http() -> httpx.Client:
+ global _HTTP
+ if _HTTP is None:
+ _HTTP = httpx.Client(timeout=300)
+ return _HTTP
+
+
+def _tunnel(deployment) -> str:
+ key = (str(deployment.id), deployment.gpu_type)
+ cached = _DIRECT.get(key)
+ if cached:
+ return cached
+ url = connect(deployment).direct_url.remote() or ""
+ if url:
+ _DIRECT[key] = url
+ return url
+
+
+def _post(deployment, body: bytes, *, stream: bool, payload: bytes | None = None) -> httpx.Response:
+ base = _tunnel(deployment)
+ if not base:
+ raise InputValidationError(WORKER_UNAVAILABLE)
+ if payload is None:
+ payload = _served_body(deployment, body, stream=stream)
+ return _http().send(
+ _http().build_request(
+ "POST",
+ base.rstrip("/") + "/v1/chat/completions",
+ content=payload,
+ headers={
+ "content-type": "application/json",
+ "authorization": f"Bearer {settings.INFERENCE_API_KEY}",
+ },
+ ),
+ stream=stream,
+ )
+
+
class ChatStreamError(Exception):
def __init__(self, status: int, body: bytes):
self.status = status
self.body = body
+def _named_tool(choice) -> str:
+ if not isinstance(choice, dict) or choice.get("type") != "function":
+ return ""
+ function = choice.get("function")
+ name = function.get("name") if isinstance(function, dict) else ""
+ return name if isinstance(name, str) else ""
+
+
+def _pin_system(payload: dict, line: str) -> None:
+ messages = payload.get("messages")
+ if not isinstance(messages, list):
+ payload["messages"] = [{"role": "system", "content": line}]
+ return
+ if (
+ messages
+ and isinstance(messages[0], dict)
+ and messages[0].get("role") in ("system", "developer")
+ ):
+ content = messages[0].get("content")
+ if isinstance(content, str) and content:
+ messages[0]["content"] = f"{content}\n{line}"
+ elif isinstance(content, list):
+ content.append({"type": "text", "text": line})
+ else:
+ messages[0]["content"] = line
+ return
+ messages.insert(0, {"role": "system", "content": line})
+
+
+def _tool_names(tools, only: str) -> list[str]:
+ if only:
+ return [only]
+ names = []
+ for tool in tools:
+ if not isinstance(tool, dict) or not isinstance(tool.get("function"), dict):
+ continue
+ name = tool["function"].get("name")
+ if isinstance(name, str) and name:
+ names.append(name)
+ return names
+
+
+def _forced_tool_regex(spec_key: str, names: list[str]) -> str:
+ alt = "|".join(re.escape(name) for name in names)
+ if spec_key == "gemma4":
+ # The gemma4 parser refuses JSON guided decoding, so the native call is the constraint.
+ return rf"<\|tool_call>call:(?:{alt})\{{[^{{}}]*\}}<tool_call\|>"
+ # Same skip in the Muse parser. The completion starts after `<|start|>assistant`.
+ return (
+ rf" to=(?:{alt})<\|message\|><atem:function_calls>\n"
+ rf"<atem:invoke name=\"(?:{alt})\">\n"
+ rf"(?:<atem:parameter name=\"[A-Za-z_][A-Za-z0-9_]*\">[^<]*</atem:parameter>\n)*"
+ rf"</atem:invoke>\n</atem:function_calls><\|eot\|>"
+ )
+
+
+def shape_chat_payload(payload: dict, *, base_model_id: str) -> None:
+ """Thinking stays off. A forced tool choice is a single call unless the request says otherwise."""
+ from modal_shared.modelfam import resolve
+
+ spec = resolve(base_model_id or "")
+ kwargs = dict(payload.get("chat_template_kwargs") or {})
+ for key, value in spec.default_chat_template_kwargs:
+ kwargs.setdefault(key, value)
+ kwargs["enable_thinking"] = False
+ kwargs["thinking"] = False
+ payload["chat_template_kwargs"] = kwargs
+ if spec.suppress_reasoning_output and "include_reasoning" not in payload:
+ payload["include_reasoning"] = False
+ if spec.default_reasoning_effort and "reasoning_effort" not in payload:
+ payload["reasoning_effort"] = spec.default_reasoning_effort
+ max_tokens = payload.get("max_tokens")
+ if (
+ spec.min_max_tokens
+ and isinstance(max_tokens, int)
+ and not isinstance(max_tokens, bool)
+ and max_tokens < spec.min_max_tokens
+ ):
+ payload["max_tokens"] = spec.min_max_tokens
+ if payload.get("tool_choice") == "none":
+ # The schemas stay in the prompt otherwise, and the model emits the call as text.
+ payload.pop("tools", None)
+ payload.pop("tool_choice", None)
+ payload.pop("parallel_tool_calls", None)
+ return
+ tools = payload.get("tools")
+ if not tools:
+ return
+ # Gemma 4 and Muse skip JSON guided decoding for these choices. gpt-oss emits
+ # one call when parallel calls are off; the parser misses it, so the reply lifts it out.
+ name = _named_tool(payload.get("tool_choice"))
+ forced = payload.get("tool_choice") == "required" or bool(name)
+ if name:
+ chosen = [
+ tool
+ for tool in tools
+ if isinstance(tool, dict)
+ and isinstance(tool.get("function"), dict)
+ and tool["function"].get("name") == name
+ ]
+ if chosen:
+ payload["tools"] = chosen
+ tools = chosen
+ # A named choice plus a regex is rejected. required is allowed, and the
+ # regex only matches this function.
+ payload["tool_choice"] = "required"
+ if "parallel_tool_calls" not in payload:
+ payload["parallel_tool_calls"] = not forced
+ if name:
+ _pin_system(payload, f"Call {name}.")
+ elif payload.get("tool_choice") == "required":
+ _pin_system(payload, "Call one of the available functions.")
+ elif spec.key == "muse_glimmer" and payload.get("parallel_tool_calls") is True:
+ _pin_system(
+ payload,
+ "Put one atem:invoke for each item the user names, and separate assistant "
+ "tool messages with <|eom|> rather than ending the turn after the first.",
+ )
+ if not forced or payload.get("structured_outputs"):
+ return
+ names = _tool_names(tools, name)
+ if spec.key in ("gemma4", "muse_glimmer") and names:
+ payload["structured_outputs"] = {"regex": _forced_tool_regex(spec.key, names)}
+
+
def _served_body(deployment, body: bytes, *, stream: bool) -> bytes:
try:
payload = json.loads(body)
@@ -354,6 +467,9 @@ def _served_body(deployment, body: bytes, *, stream: bool) -> bytes:
return body
payload["model"] = deployment.served_model_id
payload["stream"] = stream
+ shape_chat_payload(
+ payload, base_model_id=getattr(deployment.deployed_model, "base_model_id", "") or ""
+ )
if stream:
# Usage and per-request timing ride the last SSE chunk. The view strips both
# unless the caller asked to see usage.
@@ -366,72 +482,129 @@ def _served_body(deployment, body: bytes, *, stream: bool) -> bytes:
return json.dumps(payload).encode()
-def _chat_kwargs(instance, deployment, body: bytes, *, stream: bool) -> tuple[object, dict]:
- method = instance.infer_stream if stream else instance.infer
- return method, {
- "method": "POST",
- "path": "/v1/chat/completions",
- "body": _served_body(deployment, body, stream=stream),
- "headers": {"content-type": "application/json"},
- }
+_HARMONY_CALL = re.compile(
+ r"<\|channel\|>commentary to=functions\.(?P<name>[A-Za-z0-9_.-]+)"
+ r"<\|constrain\|>json<\|message\|>(?P<args>\{[^{}]*\})"
+)
-def chat(instance, deployment, body: bytes) -> tuple[int, bytes, str]:
- method, kwargs = _chat_kwargs(instance, deployment, body, stream=False)
- result = method.remote(**kwargs)
- status = int(result.get("status") or 502)
- payload = result.get("body") or b""
- if isinstance(payload, str):
- payload = payload.encode()
- content_type = (result.get("headers") or {}).get("content-type") or "application/json"
- return status, payload, content_type
+def _args_match(tool: dict, arguments: dict) -> bool:
+ params = (tool.get("function") or {}).get("parameters") or {}
+ if not isinstance(params, dict):
+ return True
+ required = params.get("required") or []
+ properties = params.get("properties") or {}
+ if any(not isinstance(key, str) or key not in arguments for key in required):
+ return False
+ return not properties or all(key in properties for key in arguments)
-def iter_chat_stream(instance, deployment, body: bytes):
- method, kwargs = _chat_kwargs(instance, deployment, body, stream=True)
- frames = method.remote_gen(**kwargs)
+def repair_forced_calls(raw: bytes, shaped: bytes) -> bytes:
+ """Keep the schema-valid tool-call prefix. gpt-oss leaves the call in content."""
try:
+ request = json.loads(shaped)
+ body = json.loads(raw)
+ except json.JSONDecodeError:
+ return raw
+ if not isinstance(request, dict) or not isinstance(body, dict):
+ return raw
+ if request.get("tool_choice") != "required":
+ return raw
+ tools = request.get("tools")
+ choices = body.get("choices")
+ if not isinstance(tools, list) or not choices or not isinstance(choices[0], dict):
+ return raw
+ message = choices[0].get("message")
+ if not isinstance(message, dict):
+ return raw
+ calls = list(message.get("tool_calls") or [])
+ if not calls:
+ content = message.get("content") or ""
+ if isinstance(content, str):
+ for index, match in enumerate(_HARMONY_CALL.finditer(content)):
+ calls.append(
+ {
+ "id": f"call_{index}",
+ "type": "function",
+ "function": {"name": match.group("name"), "arguments": match.group("args")},
+ }
+ )
+ if calls:
+ message["content"] = None
+ kept = []
+ by_name = {
+ tool["function"]["name"]: tool
+ for tool in tools
+ if isinstance(tool, dict) and isinstance(tool.get("function"), dict)
+ }
+ for call in calls:
+ function = call.get("function") if isinstance(call, dict) else None
+ if not isinstance(function, dict):
+ break
+ tool = by_name.get(function.get("name"))
try:
- first = next(frames)
- except StopIteration as exc:
- raise InputValidationError(WORKER_UNAVAILABLE) from exc
- if not isinstance(first, dict):
- raise InputValidationError(WORKER_UNAVAILABLE)
- status = int(first.get("status") or 502)
- if status >= 400:
- rejected = bytearray()
- for chunk in frames:
- if isinstance(chunk, str):
- chunk = chunk.encode()
- rejected.extend(chunk)
- if len(rejected) > 65536:
- break
- raise ChatStreamError(status, bytes(rejected))
- for chunk in frames:
- if isinstance(chunk, str):
- chunk = chunk.encode()
+ arguments = json.loads(function.get("arguments") or "{}")
+ except json.JSONDecodeError:
+ break
+ if tool is None or not isinstance(arguments, dict) or not _args_match(tool, arguments):
+ break
+ function["arguments"] = json.dumps(
+ {
+ key: value[1:-1]
+ if isinstance(value, str) and len(value) >= 2 and value[0] == value[-1] == '"'
+ else value
+ for key, value in arguments.items()
+ }
+ )
+ kept.append(call)
+ if kept:
+ message["tool_calls"] = kept
+ choices[0]["finish_reason"] = "tool_calls"
+ elif calls:
+ message["tool_calls"] = None
+ return json.dumps(body).encode()
+
+
+def chat(deployment, body: bytes) -> tuple[int, bytes, str]:
+ shaped = _served_body(deployment, body, stream=False)
+ response = _post(deployment, body, stream=False, payload=shaped)
+ try:
+ content_type = response.headers.get("content-type") or "application/json"
+ raw = response.content
+ if response.status_code < 400 and "json" in content_type:
+ raw = repair_forced_calls(raw, shaped)
+ return response.status_code, raw, content_type
+ finally:
+ response.close()
+
+
+def iter_chat_stream(deployment, body: bytes):
+ response = _post(deployment, body, stream=True)
+ try:
+ if response.status_code >= 400:
+ rejected = response.read()
+ logger.warning("dedicated chat upstream %s %s", response.status_code, rejected[:300])
+ raise ChatStreamError(response.status_code, rejected)
+ for chunk in response.iter_bytes():
if chunk:
yield chunk
finally:
- close = getattr(frames, "close", None)
- if close is not None:
- close()
+ response.close()
-def _read_prediction(instance, decisions: list) -> dict:
- result = instance.predict.remote(decisions)
- if not isinstance(result, dict) or result.get("error_code"):
+def post_systemone(deployment, body: dict) -> dict:
+ base = _tunnel(deployment)
+ if not base:
raise InputValidationError(WORKER_UNAVAILABLE)
- return result
-
-
-def predict(instance, decisions: list, deployment=None) -> dict:
- try:
- return _read_prediction(instance, decisions)
- except Exception as exc:
- if deployment is None or not _drop_pool(deployment, exc):
- raise
- return _read_prediction(connect(deployment), decisions)
+ response = _http().post(
+ base.rstrip("/") + "/v1/systemone",
+ json=body,
+ headers={"authorization": f"Bearer {settings.INFERENCE_API_KEY}"},
+ timeout=300,
+ )
+ if response.status_code >= 400:
+ raise InputValidationError(response.text[:500] or WORKER_UNAVAILABLE)
+ return response.json()
def minute_usd(rate: Decimal, replicas: int) -> Decimal:
diff --git a/scripts/dedicated_matrix.py b/scripts/dedicated_matrix.py
new file mode 100644
index 00000000..5f97d82c
--- /dev/null
+++ b/scripts/dedicated_matrix.py
@@ -0,0 +1,646 @@
+"""Dedicated inference for every catalog model, then one adapter serve.
+
+Cold start is the wait until the dedicated tunnel is open. The warm numbers are
+the next requests, after one short completion. Streaming and non-streaming use
+the same prompt and a 128-token cap.
+
+ PYTHONPATH=. uv run python scripts/dedicated_matrix.py
+"""
+
+from __future__ import annotations
+
+import inspect
+import json
+import os
+import sys
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from pathlib import Path
+
+import httpx
+import modal
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+os.environ.setdefault("POSTGRES_HOST", "127.0.0.1")
+os.environ.setdefault("DJANGO_DEBUG", "True")
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "overbae.settings")
+
+import django # noqa: E402
+
+django.setup()
+
+from django.conf import settings # noqa: E402
+
+from modal_shared.serving.engine import engine_for # noqa: E402
+from modal_shared.serving.speculative import draft_for, mtp_for # noqa: E402
+from modal_shared.shared import rel_weights_path # noqa: E402
+from overbae.modal.gpu_selector import dedicated_gpu_names # noqa: E402
+from overbae.models import DeployedModel # noqa: E402
+from overbae.services.dedicated_runtime import shape_chat_payload # noqa: E402
+
+ENV = "overmind-dev"
+SERVED = "matrix"
+OUT = ROOT / "experiments" / "dedicated_matrix" / "results.jsonl"
+PROMPT = (
+ "Explain how a bicycle stays upright when the rider leans into a turn. "
+ "Use plain language and several sentences."
+)
+MAX_TOKENS = 128
+WRITE = threading.Lock()
+
+WEATHER = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Current weather for a city.",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+}
+CLOCK = {
+ "type": "function",
+ "function": {
+ "name": "get_time",
+ "description": "Current local time in a city.",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+}
+
+
+def speculative(repo: str) -> str:
+ if mtp_for(repo):
+ return "MTP"
+ found = draft_for(repo)
+ if not found:
+ return "nothing"
+ name, _tokens = found
+ if "DFlash2" in name:
+ return "DFlash2"
+ return "DFlash"
+
+
+def catalog() -> list[dict]:
+ doc = json.loads((ROOT / "overbae" / "modal" / "models.json").read_text())
+ grouped: dict[str, list[dict]] = {}
+ order: list[str] = []
+ for entry in doc["models"]:
+ grouped.setdefault(entry["id"], []).append(entry)
+ if entry["id"] not in order:
+ order.append(entry["id"])
+ rows = []
+ for model_id in order:
+ entries = grouped[model_id]
+ baseten = next((e for e in entries if e.get("backend") == "baseten"), None)
+ chosen = baseten or entries[0]
+ rows.append(
+ {
+ "model": model_id,
+ "entry": chosen,
+ "disabled": all(e.get("disabled") for e in entries),
+ "disabled_reason": next(
+ (e.get("disabled_reason") for e in entries if e.get("disabled_reason")),
+ None,
+ ),
+ "kind": chosen.get("type") or chosen.get("backend"),
+ "tools": bool(chosen.get("supports_tool_calling")),
+ "servable": bool(
+ baseten and not baseten.get("disabled") and baseten.get("type") == "chat"
+ ),
+ }
+ )
+ return rows
+
+
+def pick_gpu(entry: dict) -> tuple[list[str], int] | None:
+ requested = int((entry.get("inference") or {}).get("max_model_len") or 8192)
+ for length in (requested, 4096, 2048, 1024):
+ names = dedicated_gpu_names(entry, length, fp8=False)
+ if names:
+ return names, length
+ return None
+
+
+def record(row: dict) -> None:
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ with WRITE, OUT.open("a") as handle:
+ handle.write(json.dumps(row) + "\n")
+ handle.flush()
+ err = row.get("error")
+ label = err.splitlines()[-1][:180] if err else "ok"
+ print(
+ f"[{row.get('kind')}] {row['model']} {label} "
+ f"cold={row.get('cold_start_s')} ttft={row.get('warm_ttft_s')}",
+ flush=True,
+ )
+
+
+def finished() -> set[tuple[str, str]]:
+ if not OUT.exists():
+ return set()
+ done = set()
+ for line in OUT.read_text().splitlines():
+ if not line.strip():
+ continue
+ row = json.loads(line)
+ if row.get("error"):
+ continue
+ if row.get("kind") == "base" and row.get("servable") and "cold_start_s" not in row:
+ continue
+ done.add((row["model"], row.get("kind") or "base"))
+ return done
+
+
+def payload(
+ model: str, messages: list, *, stream: bool, max_tokens: int, tools=None, parallel=None
+):
+ body = {
+ "model": SERVED,
+ "messages": messages,
+ "max_tokens": max_tokens,
+ "temperature": 0,
+ "stream": stream,
+ }
+ if tools is not None:
+ body["tools"] = tools
+ if parallel is not None:
+ body["parallel_tool_calls"] = parallel
+ if stream:
+ body["stream_options"] = {"include_usage": True}
+ shape_chat_payload(body, base_model_id=model)
+ body["model"] = SERVED
+ body["stream"] = stream
+ return body
+
+
+def _calls(message: dict) -> list[dict]:
+ calls = message.get("tool_calls") or []
+ out = []
+ for call in calls:
+ fn = call.get("function") or {}
+ out.append(
+ {
+ "name": fn.get("name"),
+ "arguments": fn.get("arguments"),
+ "id": call.get("id"),
+ }
+ )
+ return out
+
+
+def complete(url: str, body: dict) -> dict:
+ headers = {
+ "content-type": "application/json",
+ "authorization": f"Bearer {settings.INFERENCE_API_KEY}",
+ }
+ started = time.perf_counter()
+ if not body.get("stream"):
+ response = httpx.post(
+ url.rstrip("/") + "/v1/chat/completions",
+ json=body,
+ headers=headers,
+ timeout=600,
+ )
+ elapsed = time.perf_counter() - started
+ data = response.json()
+ if response.status_code >= 400:
+ raise RuntimeError(f"HTTP {response.status_code}: {json.dumps(data)[:500]}")
+ choice = (data.get("choices") or [{}])[0]
+ message = choice.get("message") or {}
+ usage = data.get("usage") or {}
+ tokens = usage.get("completion_tokens")
+ return {
+ "latency_s": round(elapsed, 3),
+ "tokens_per_s": round(tokens / elapsed, 2) if tokens else None,
+ "completion_tokens": tokens,
+ "finish_reason": choice.get("finish_reason"),
+ "tool_calls": _calls(message),
+ "content": message.get("content"),
+ }
+ ttft = None
+ usage = None
+ tool_bits: list[dict] = []
+ with httpx.stream(
+ "POST",
+ url.rstrip("/") + "/v1/chat/completions",
+ json=body,
+ headers=headers,
+ timeout=600,
+ ) as response:
+ if response.status_code >= 400:
+ raw = response.read().decode()[:500]
+ raise RuntimeError(f"HTTP {response.status_code}: {raw}")
+ buffer = ""
+ for chunk in response.iter_text():
+ buffer += chunk
+ while "\n" in buffer:
+ line, buffer = buffer.split("\n", 1)
+ line = line.strip()
+ if not line.startswith("data:"):
+ continue
+ data = line[5:].strip()
+ if data == "[DONE]":
+ continue
+ try:
+ event = json.loads(data)
+ except json.JSONDecodeError:
+ continue
+ if event.get("usage"):
+ usage = event["usage"]
+ choices = event.get("choices") or []
+ if not choices:
+ continue
+ delta = choices[0].get("delta") or {}
+ content = delta.get("content") or ""
+ if (content or delta.get("tool_calls")) and ttft is None:
+ ttft = time.perf_counter() - started
+ for piece in delta.get("tool_calls") or []:
+ tool_bits.append(piece)
+ elapsed = time.perf_counter() - started
+ tokens = (usage or {}).get("completion_tokens")
+ return {
+ "latency_s": round(elapsed, 3),
+ "ttft_s": round(ttft, 3) if ttft is not None else None,
+ "tokens_per_s": round(tokens / elapsed, 2) if tokens else None,
+ "completion_tokens": tokens,
+ "tool_deltas": len(tool_bits),
+ }
+
+
+def tool_report(url: str, model: str) -> dict:
+ tools = [WEATHER, CLOCK]
+
+ def ask(messages, *, parallel=None):
+ body = payload(
+ model, messages, stream=False, max_tokens=256, tools=tools, parallel=parallel
+ )
+ return complete(url, body)
+
+ report = {}
+ single = ask([{"role": "user", "content": "What is the weather in Paris?"}])
+ report["single"] = {
+ "ok": [c["name"] for c in single["tool_calls"]] == ["get_weather"],
+ "calls": single["tool_calls"],
+ "finish_reason": single["finish_reason"],
+ "content": (single.get("content") or "")[:240],
+ }
+
+ parallel = ask(
+ [
+ {
+ "role": "user",
+ "content": "Look up the weather in Paris and the weather in London.",
+ }
+ ],
+ parallel=True,
+ )
+ names = [c["name"] for c in parallel["tool_calls"]]
+ report["parallel"] = {
+ "ok": names.count("get_weather") >= 2,
+ "calls": parallel["tool_calls"],
+ "finish_reason": parallel["finish_reason"],
+ }
+
+ first = ask([{"role": "user", "content": "What is the weather in Paris?"}])
+ follow = {"ok": False, "calls": [], "finish_reason": None}
+ if first["tool_calls"]:
+ call = first["tool_calls"][0]
+ follow = ask(
+ [
+ {"role": "user", "content": "What is the weather in Paris?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": call["id"] or "call_weather",
+ "type": "function",
+ "function": {
+ "name": call["name"],
+ "arguments": call["arguments"] or "{}",
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": call["id"] or "call_weather",
+ "content": '{"city":"Paris","temp_c":18}',
+ },
+ {"role": "user", "content": "Now get the local time in that city."},
+ ]
+ )
+ follow = {
+ "ok": any(c["name"] == "get_time" for c in follow["tool_calls"]),
+ "calls": follow["tool_calls"],
+ "finish_reason": follow["finish_reason"],
+ }
+ report["multi_step"] = follow
+
+ history = ask(
+ [
+ {"role": "user", "content": "What is the weather in Paris?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_weather",
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "arguments": '{"city":"Paris"}',
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_weather",
+ "content": '{"city":"Paris","temp_c":18}',
+ },
+ {"role": "assistant", "content": "It is 18C in Paris."},
+ {"role": "user", "content": "What time is it there?"},
+ ]
+ )
+ report["assistant_history"] = {
+ "ok": any(c["name"] == "get_time" for c in history["tool_calls"]),
+ "calls": history["tool_calls"],
+ "finish_reason": history["finish_reason"],
+ }
+ return report
+
+
+def open_worker(job: dict):
+ gpu = job["gpu"]
+ engine = job["engine"]
+ token = gpu.replace("-", "")
+ cls = modal.Cls.from_name(
+ "overmind-dedicated",
+ f"{token}_{engine}_dedicated",
+ environment_name=ENV,
+ )
+ cls = cls.with_options(max_containers=48, scaledown_window=120)
+ kwargs = {
+ "model_path": job["model_path"],
+ "model_name": SERVED,
+ "max_model_len": job["max_model_len"],
+ "enable_lora": False,
+ "max_lora_rank": 16,
+ "adapter_path": job.get("adapter_path") or "",
+ }
+ if engine == "vllm":
+ kwargs["snapshot_engine"] = True
+ instance = cls(**kwargs)
+ started = time.perf_counter()
+ url = instance.direct_url.spawn().get(timeout=2400)
+ cold = time.perf_counter() - started
+ if not url:
+ raise RuntimeError("Dedicated worker returned an empty tunnel URL.")
+ return instance, url, cold
+
+
+def release(instance) -> None:
+ try:
+ from asgiref.sync import async_to_sync
+
+ result = instance.update_autoscaler(min_containers=0, max_containers=1, scaledown_window=2)
+ if inspect.iscoroutine(result):
+
+ async def _wait():
+ return await result
+
+ async_to_sync(_wait)()
+ except Exception as exc:
+ print(f"release failed: {exc}", flush=True)
+
+
+def measure(job: dict) -> dict:
+ row = {
+ "model": job["model"],
+ "kind": job["kind"],
+ "engine": job["engine"],
+ "speculative": job["speculative"],
+ "gpu": job["gpu"],
+ "max_model_len": job["max_model_len"],
+ "supports_tool_calling": job["tools"],
+ }
+ instance = None
+ try:
+ instance, url, cold = open_worker(job)
+ row["cold_start_s"] = round(cold, 1)
+ complete(
+ url,
+ payload(
+ job["model"], [{"role": "user", "content": "ping"}], stream=False, max_tokens=16
+ ),
+ )
+ streamed = complete(
+ url,
+ payload(
+ job["model"],
+ [{"role": "user", "content": PROMPT}],
+ stream=True,
+ max_tokens=MAX_TOKENS,
+ ),
+ )
+ plain = complete(
+ url,
+ payload(
+ job["model"],
+ [{"role": "user", "content": PROMPT}],
+ stream=False,
+ max_tokens=MAX_TOKENS,
+ ),
+ )
+ row["warm_ttft_s"] = streamed.get("ttft_s")
+ row["stream_latency_s"] = streamed["latency_s"]
+ row["stream_tokens_per_s"] = streamed["tokens_per_s"]
+ row["stream_completion_tokens"] = streamed["completion_tokens"]
+ row["nonstream_latency_s"] = plain["latency_s"]
+ row["nonstream_tokens_per_s"] = plain["tokens_per_s"]
+ row["nonstream_completion_tokens"] = plain["completion_tokens"]
+ try:
+ row["tools"] = tool_report(url, job["model"])
+ except Exception as exc:
+ row["tools"] = {"error": str(exc)[:800]}
+ except Exception as exc:
+ row["error"] = str(exc)[:2000]
+ finally:
+ if instance is not None:
+ release(instance)
+ return row
+
+
+def serve_jobs(cached: set[str]) -> tuple[list[dict], list[dict]]:
+ jobs = []
+ skipped = []
+ for item in catalog():
+ if not item["servable"]:
+ reason = item["disabled_reason"] or (
+ "Decision models do not serve chat completions."
+ if item["kind"] == "decision"
+ else "Not in the Modal chat catalog."
+ )
+ skipped.append(
+ {
+ "model": item["model"],
+ "kind": "skipped",
+ "engine": None,
+ "speculative": None,
+ "reason": reason,
+ "servable": False,
+ }
+ )
+ continue
+ picked = pick_gpu(item["entry"])
+ if picked is None:
+ skipped.append(
+ {
+ "model": item["model"],
+ "kind": "base",
+ "engine": engine_for(item["model"]),
+ "speculative": speculative(item["model"]),
+ "error": "No GPU holds the BF16 weights.",
+ "servable": True,
+ }
+ )
+ continue
+ gpus, length = picked
+ hf = item["entry"].get("hf_model_id") or item["model"]
+ if item["model"] in cached:
+ repo, ready = item["model"], True
+ elif hf in cached:
+ repo, ready = hf, True
+ else:
+ repo, ready = hf, False
+ jobs.append(
+ {
+ "model": item["model"],
+ "kind": "base",
+ "engine": engine_for(item["model"]),
+ "speculative": speculative(item["model"]),
+ "gpu": gpus[0],
+ "gpus": gpus,
+ "max_model_len": length,
+ "model_path": ".base_models/" + repo.replace("/", "--"),
+ "fetch_repo": repo,
+ "tools": item["tools"],
+ "cached": ready,
+ }
+ )
+ return jobs, skipped
+
+
+def adapter_job() -> dict | None:
+ deployed = (
+ DeployedModel.objects.filter(status=DeployedModel.Status.READY, is_lora=True)
+ .order_by("-created_at")
+ .first()
+ )
+ if deployed is None:
+ return None
+ entry = next(item["entry"] for item in catalog() if item["model"] == deployed.base_model_id)
+ picked = pick_gpu(entry)
+ if picked is None:
+ return None
+ gpus, length = picked
+ return {
+ "model": deployed.base_model_id,
+ "kind": "adapter",
+ "engine": engine_for(deployed.base_model_id),
+ "speculative": speculative(deployed.base_model_id),
+ "gpu": gpus[0],
+ "gpus": gpus,
+ "max_model_len": min(length, deployed.max_model_len or length),
+ "model_path": rel_weights_path(deployed.weights_path),
+ "adapter_path": rel_weights_path(deployed.adapter_path),
+ "tools": True,
+ "cached": True,
+ "adapter_model_id": deployed.model_id,
+ }
+
+
+def fetch_base(model: str) -> None:
+ print(f"fetch {model}", flush=True)
+ modal.Function.from_name("overmind-register", "fetch_base_model", environment_name=ENV).remote(
+ base_model=model
+ )
+
+
+def run_one(job: dict) -> dict:
+ try:
+ if not job.get("cached"):
+ fetch_base(job.get("fetch_repo") or job["model"])
+ row = measure(job)
+ err = row.get("error") or ""
+ if "DFlash draft" in err or "not on the weights volume" in err:
+ fetch_base(job.get("fetch_repo") or job["model"])
+ row = measure(job)
+ err = row.get("error") or ""
+ gpus = job.get("gpus") or []
+ idx = gpus.index(job["gpu"]) if job.get("gpu") in gpus else -1
+ while err and "exit_code" in err and idx + 1 < len(gpus):
+ idx += 1
+ print(f"retry {job['model']} on {gpus[idx]}", flush=True)
+ row = measure({**job, "gpu": gpus[idx]})
+ err = row.get("error") or ""
+ return row
+ except Exception as exc:
+ return {
+ "model": job["model"],
+ "kind": job["kind"],
+ "engine": job.get("engine"),
+ "speculative": job.get("speculative"),
+ "gpu": job.get("gpu"),
+ "error": str(exc)[:1500],
+ }
+
+
+def main() -> None:
+ done = finished()
+ cached = set(
+ modal.Function.from_name(
+ "overmind-register", "list_base_models", environment_name=ENV
+ ).remote()
+ )
+ print(f"cached bases: {len(cached)}", flush=True)
+ jobs, skipped = serve_jobs(cached)
+ for row in skipped:
+ if (row["model"], row.get("kind") or "base") not in done:
+ record(row)
+ jobs = [job for job in jobs if (job["model"], job["kind"]) not in done]
+ only = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
+ if only:
+ jobs = [job for job in jobs if job["model"] in only]
+ adapter = adapter_job()
+ if adapter is not None and (adapter["model"], adapter["kind"]) not in done:
+ print(f"adapter {adapter['adapter_model_id']} on {adapter['model']}", flush=True)
+ jobs.append(adapter)
+ elif adapter is None and (None, "adapter") not in done:
+ record(
+ {
+ "model": None,
+ "kind": "adapter",
+ "error": "No ready LoRA adapter. A fine-tune was not started in this pass.",
+ }
+ )
+ print(f"launching {len(jobs)}", flush=True)
+ if not jobs:
+ return
+ with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
+ futures = [pool.submit(run_one, job) for job in jobs]
+ for future in as_completed(futures):
+ record(future.result())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/fakes/modal.py b/tests/fakes/modal.py
index c7b736ca..0d04d267 100644
--- a/tests/fakes/modal.py
+++ b/tests/fakes/modal.py
@@ -9,6 +9,7 @@ import threading
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -563,3 +564,31 @@ class DecisionBackend:
"usage": {"prompt_tokens": 8 * len(requests), "completion_tokens": 0},
"finish_reason": "stop",
}
+
+
+def open_chat_tunnel(cloud: FakeModal, cls_name: str, reply: dict, stream: bytes | None = None):
+ """The dedicated worker's port forward. Chat posts here; the probe still uses infer."""
+ encoded = json.dumps(reply).encode()
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self):
+ size = int(self.headers.get("Content-Length") or 0)
+ incoming = json.loads(self.rfile.read(size) or b"{}")
+ if incoming.get("stream"):
+ body, content_type = stream or b"", "text/event-stream"
+ else:
+ body, content_type = encoded, "application/json"
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format, *args):
+ return
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ url = f"http://127.0.0.1:{server.server_address[1]}"
+ cloud.deploy("overmind-dedicated", f"{cls_name}.direct_url", lambda **_kwargs: url)
+ return server
diff --git a/tests/journeys/test_serve.py b/tests/journeys/test_serve.py
index 5c9fbe15..dbcfc398 100644
--- a/tests/journeys/test_serve.py
+++ b/tests/journeys/test_serve.py
@@ -5,6 +5,7 @@ from overmind.client import Client, OvermindInferenceError
from overbae.models import Dataset, DedicatedDeployment, DeployedModel, FinetuningJob, Project
from overbae.services.provider_pricing import refresh_rates
+from tests.fakes.modal import open_chat_tunnel
from .datasets import until
@@ -76,6 +77,20 @@ def test_serve(
refresh_rates()
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _dedicated_reply)
+ open_chat_tunnel(
+ fake_modal,
+ "H100_vllm_dedicated",
+ {
+ "model": "dedicated/internal",
+ "choices": [
+ {
+ "message": {"role": "assistant", "content": "Order 42 left the depot."},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 5, "total_tokens": 6},
+ },
+ )
fake_modal.worker_stats = {"num_total_runners": 1, "backlog": 0, "num_running_inputs": 0}
started = mcp.call(
"start_dedicated_deployment",
diff --git a/tests/test_decision_job_identity.py b/tests/test_decision_job_identity.py
index 937d201c..44bd8ab1 100644
--- a/tests/test_decision_job_identity.py
+++ b/tests/test_decision_job_identity.py
@@ -66,6 +66,7 @@ def test_decision_identity_reuses_the_exact_training_run(monkeypatch, settings):
assert {entry["family"] for entry in entries.values()} == {"clef", "d3", "d1"}
assert entries["Cloudflare/clef-flash"]["training_available"]
assert not entries["vllm-sr/d3-edge"]["training_available"]
+ assert "LiquidAI/d1-omni-600M" not in entries
payload = {
"project": str(project.id),
"model": "Cloudflare/clef-flash",
diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.py
index cc3236c6..81092e72 100644
--- a/tests/test_dedicated_deployment.py
+++ b/tests/test_dedicated_deployment.py
@@ -18,6 +18,7 @@ from overbae.models.billing import BillingService
from overbae.models.inference import DeployedModel
from overbae.services import dedicated
from overbae.services.provider_pricing import refresh_rates
+from tests.fakes.modal import open_chat_tunnel
pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]
@@ -176,6 +177,16 @@ def test_dedicated_chat_skips_per_request_billing_and_appears_in_the_model_list(
ProjectMembership.objects.create(user=user, project=project)
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
+ open_chat_tunnel(
+ fake_modal,
+ "H100_vllm_dedicated",
+ {
+ "model": "dedicated/internal",
+ "system_fingerprint": "vllm-0.30.0-nohash",
+ "choices": [{"message": {"content": "hi"}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ )
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
@@ -207,35 +218,31 @@ def test_dedicated_chat_streams_tokens_before_the_reply_finishes(fake_modal):
ProjectMembership.objects.create(user=user, project=project)
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
-
- def stream(**kwargs):
- body = json.loads(kwargs["body"])
- assert body["stream"] is True
- piece = json.dumps(
- {
- "model": "internal",
- "system_fingerprint": "vllm",
- "choices": [{"delta": {"content": "hi"}, "finish_reason": None}],
- }
- )
- usage = json.dumps(
- {
- "model": "internal",
- "choices": [],
- "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
- "metrics": {
- "time_to_first_token_ms": 20,
- "generation_time_ms": 40,
- "tokens_per_second": 50,
- },
- }
- )
- raw = f"data: {piece}\n\ndata: {usage}\n\ndata: [DONE]\n\n".encode()
- yield {"status": 200, "headers": {"content-type": "text/event-stream"}}
- yield raw[:12]
- yield raw[12:]
-
- fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer_stream", stream)
+ piece = json.dumps(
+ {
+ "model": "internal",
+ "system_fingerprint": "vllm",
+ "choices": [{"delta": {"content": "hi"}, "finish_reason": None}],
+ }
+ )
+ usage = json.dumps(
+ {
+ "model": "internal",
+ "choices": [],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
+ "metrics": {
+ "time_to_first_token_ms": 20,
+ "generation_time_ms": 40,
+ "tokens_per_second": 50,
+ },
+ }
+ )
+ open_chat_tunnel(
+ fake_modal,
+ "H100_vllm_dedicated",
+ {"choices": [{"message": {"content": "hi"}}]},
+ stream=f"data: {piece}\n\ndata: {usage}\n\ndata: [DONE]\n\n".encode(),
+ )
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
diff --git a/tests/test_dedicated_lora_merge.py b/tests/test_dedicated_lora_merge.py
index 3cf0d278..84458f5e 100644
--- a/tests/test_dedicated_lora_merge.py
+++ b/tests/test_dedicated_lora_merge.py
@@ -10,7 +10,12 @@ import pytest
from overbae.modal import modal_vllm_worker as serving
from overbae.services import dedicated_runtime
-from overbae.services.dedicated_runtime import chat, parameters, worker_class_name
+from overbae.services.dedicated_runtime import (
+ parameters,
+ repair_forced_calls,
+ shape_chat_payload,
+ worker_class_name,
+)
pytestmark = pytest.mark.covers("model-runtime")
@@ -31,6 +36,18 @@ def test_dedicated_lora_uses_the_plain_worker_and_no_runtime_adapter():
)
assert worker_class_name(deployed, "A100-80GB") == "A10080GB_vllm_dedicated"
+ qwen = SimpleNamespace(
+ inference_contract="chat",
+ base_model_id="Qwen/Qwen3.5-4B",
+ quantization="bf16",
+ )
+ assert worker_class_name(qwen, "H100") == "H100_sglang_dedicated"
+ fp8 = SimpleNamespace(
+ inference_contract="chat",
+ base_model_id="Qwen/Qwen3.5-4B",
+ quantization="fp8",
+ )
+ assert worker_class_name(fp8, "H100") == "H100_vllm_dedicated"
assert parameters(deployment) == {
"model_path": ".base_models/Qwen--Qwen2.5-0.5B-Instruct",
"model_name": "dedicated/ft-9be76bc2",
@@ -39,14 +56,6 @@ def test_dedicated_lora_uses_the_plain_worker_and_no_runtime_adapter():
"max_lora_rank": 16,
"adapter_path": ".adapters/ft-9be76bc2",
}
- sent = {}
-
- def remote(**kwargs):
- sent.update(kwargs)
- return {"status": 200, "body": b"{}", "headers": {}}
-
- chat(SimpleNamespace(infer=SimpleNamespace(remote=remote)), deployment, b"{}")
- assert "adapter" not in sent
def test_prod_snapshot_engine_enables_the_sleep_route(monkeypatch, tmp_path):
@@ -89,17 +98,24 @@ def test_dedicated_worker_is_not_the_serverless_class():
find = discovery._find_partial_methods_for_user_cls
assert set(find(dedicated, flags.ENTER_PRE_SNAPSHOT)) == {"startup"}
assert set(find(dedicated, flags.ENTER_POST_SNAPSHOT)) == {"wake"}
+ sglang = serving.H100_sglang_dedicated._get_user_cls()
+ assert sglang.engine == "sglang"
+ assert "snapshot_engine" not in sglang.__annotations__
+ assert "adapter_path" in sglang.__annotations__
-def _decision(app="overmind-decision-serve-old"):
+def _decision():
return SimpleNamespace(
id="dep-1",
gpu_type="A100-80GB",
- max_replicas=1,
+ max_replicas=2,
idle_shutdown_seconds=900,
+ served_model_id="dedicated/dep-1",
deployed_model=SimpleNamespace(
inference_contract="decision",
- serving_runtime={"app": app, "environment": "overmind-prod"},
+ base_model_id="Cloudflare/clef",
+ lora_rank=0,
+ serving_runtime={"app": "overmind-decision-serve-old", "environment": "overmind-prod"},
weights_path="/weights/.decisions/abc",
checkpoint_hash="abc",
max_model_len=4096,
@@ -107,61 +123,177 @@ def _decision(app="overmind-decision-serve-old"):
)
-def test_older_decision_release_scales_without_pool(monkeypatch):
- dedicated_runtime._unpooled_apps.clear()
- seen = []
+def test_dedicated_decision_binds_its_own_class(monkeypatch):
+ seen = {}
class Endpoint:
def __init__(self, **kwargs):
- seen.append(kwargs)
- self.kwargs = kwargs
+ seen["params"] = kwargs
- def update_autoscaler(self, **_kwargs):
- if "pool" in self.kwargs:
- raise RuntimeError(
- "parameter names were provided but are not defined "
- "class modal.parameters for the class: pool"
- )
+ def update_autoscaler(self, **kwargs):
+ seen["scale"] = kwargs
class Remote:
- def with_options(self, **_kwargs):
+ def with_options(self, **kwargs):
+ seen["options"] = kwargs
return Endpoint
- monkeypatch.setattr(dedicated_runtime.modal.Cls, "from_name", lambda *_a, **_k: Remote())
- dedicated_runtime.bind(_decision(), minimum=1, maximum=1, idle_seconds=900)
- assert "pool" in seen[0]
- assert "pool" not in seen[1]
- dedicated_runtime._unpooled_apps.clear()
+ def from_name(app_name, cls_name, *, environment_name):
+ seen["lookup"] = (app_name, cls_name, environment_name)
+ return Remote()
+ monkeypatch.setenv("MODAL_ENVIRONMENT", "overmind-dev")
+ monkeypatch.setattr(dedicated_runtime.modal.Cls, "from_name", from_name)
+ monkeypatch.setattr(dedicated_runtime, "chat_sequence_cap", lambda deployment: None)
+ dedicated_runtime.bind(_decision(), minimum=1, maximum=2, idle_seconds=900)
+ assert seen["lookup"] == ("overmind-dedicated", "A10080GB_vllm_dedicated", "overmind-dev")
+ assert seen["params"] == {
+ "model_path": ".base_models/Cloudflare--clef",
+ "model_name": "dedicated/dep-1",
+ "max_model_len": 4096,
+ "enable_lora": True,
+ "max_lora_rank": 0,
+ "adapter_path": ".decisions/abc",
+ "snapshot_engine": False,
+ }
+ assert "gpu" not in seen["options"]
+ assert seen["scale"]["min_containers"] == 1
-def test_decision_predict_retries_when_the_release_rejects_pool(monkeypatch):
- dedicated_runtime._unpooled_apps.clear()
- deployment = _decision("overmind-decision-serve-other")
- calls = []
- class Instance:
- def __init__(self, **kwargs):
- self.kwargs = kwargs
-
- class Predict:
- def remote(self, _decisions):
- calls.append(kwargs)
- if "pool" in kwargs:
- raise RuntimeError(
- "parameter names were provided but are not defined "
- "class modal.parameters for the class: pool"
- )
- return {"predictions": [{"key": "0"}]}
-
- self.predict = Predict()
-
- monkeypatch.setattr(
- dedicated_runtime,
- "connect",
- lambda row: Instance(**dedicated_runtime.parameters(row)),
- )
- result = dedicated_runtime.predict(Instance(**parameters(deployment)), [], deployment)
- assert result["predictions"] == [{"key": "0"}]
- assert "pool" in calls[0]
- assert "pool" not in calls[1]
- dedicated_runtime._unpooled_apps.clear()
+def test_dedicated_chat_disables_thinking_and_keeps_parallel_tools():
+ payload = {
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "get_weather"}}],
+ "chat_template_kwargs": {"enable_thinking": True},
+ "max_tokens": 16,
+ }
+ shape_chat_payload(payload, base_model_id="unsloth/Muse-Glimmer-30B")
+ assert payload["chat_template_kwargs"]["enable_thinking"] is False
+ assert payload["chat_template_kwargs"]["thinking"] is False
+ assert payload["chat_template_kwargs"]["reasoning_strength"] == "low"
+ assert payload["include_reasoning"] is False
+ assert payload["parallel_tool_calls"] is True
+ assert payload["max_tokens"] == 48
+
+ held = {
+ "tools": [{"type": "function", "function": {"name": "get_weather"}}],
+ "parallel_tool_calls": False,
+ "tool_choice": "none",
+ }
+ shape_chat_payload(held, base_model_id="Qwen/Qwen3-4B")
+ assert "tools" not in held
+ assert "tool_choice" not in held
+ assert held["chat_template_kwargs"] == {"enable_thinking": False, "thinking": False}
+
+ oss = {"max_tokens": 32}
+ shape_chat_payload(oss, base_model_id="openai/gpt-oss-20b")
+ assert oss["include_reasoning"] is False
+ assert oss["reasoning_effort"] == "low"
+ assert "parallel_tool_calls" not in oss
+ assert payload["messages"][0] == {
+ "role": "system",
+ "content": (
+ "Put one atem:invoke for each item the user names, and separate assistant "
+ "tool messages with <|eom|> rather than ending the turn after the first."
+ ),
+ }
+
+ named = {
+ "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
+ "tools": [
+ {"type": "function", "function": {"name": "get_weather"}},
+ {"type": "function", "function": {"name": "get_time"}},
+ ],
+ "tool_choice": {"type": "function", "function": {"name": "get_time"}},
+ }
+ shape_chat_payload(named, base_model_id="google/gemma-4-26B-A4B-it")
+ assert [tool["function"]["name"] for tool in named["tools"]] == ["get_time"]
+ assert named["parallel_tool_calls"] is False
+ assert named["messages"][0]["content"] == "Call get_time."
+ assert named["tool_choice"] == "required"
+ assert "get_time" in named["structured_outputs"]["regex"]
+ assert "get_weather" not in named["structured_outputs"]["regex"]
+
+ required = {
+ "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}],
+ "tools": [{"type": "function", "function": {"name": "get_weather"}}],
+ "tool_choice": "required",
+ }
+ shape_chat_payload(required, base_model_id="openai/gpt-oss-20b")
+ assert required["parallel_tool_calls"] is False
+ assert "structured_outputs" not in required
+ assert required["messages"][0]["content"] == "Be brief.\nCall one of the available functions."
+
+ kept = {
+ "tools": [{"type": "function", "function": {"name": "get_weather"}}],
+ "tool_choice": "required",
+ "parallel_tool_calls": True,
+ }
+ shape_chat_payload(kept, base_model_id="openai/gpt-oss-20b")
+ assert kept["parallel_tool_calls"] is True
+
+ shaped = json.dumps(
+ {
+ "tool_choice": "required",
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_time",
+ "parameters": {
+ "type": "object",
+ "properties": {"timezone": {"type": "string"}},
+ "required": ["timezone"],
+ },
+ },
+ }
+ ],
+ }
+ ).encode()
+ raw = json.dumps(
+ {
+ "choices": [
+ {
+ "finish_reason": "stop",
+ "message": {
+ "role": "assistant",
+ "content": (
+ "<|channel|>commentary to=functions.get_time<|constrain|>json"
+ '<|message|>{"timezone":"UTC"}<|call|>'
+ "<|channel|>commentary to=functions.get_time<|constrain|>json"
+ '<|message|>{"result":"later"}<|call|>'
+ ),
+ },
+ }
+ ]
+ }
+ ).encode()
+ repaired = json.loads(repair_forced_calls(raw, shaped))
+ calls = repaired["choices"][0]["message"]["tool_calls"]
+ assert [call["function"]["name"] for call in calls] == ["get_time"]
+ assert json.loads(calls[0]["function"]["arguments"]) == {"timezone": "UTC"}
+
+ quoted = json.dumps(
+ {
+ "choices": [
+ {
+ "message": {
+ "tool_calls": [
+ {
+ "id": "call_0",
+ "type": "function",
+ "function": {
+ "name": "get_time",
+ "arguments": json.dumps({"timezone": '"Europe/Paris"'}),
+ },
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ).encode()
+ repaired = json.loads(repair_forced_calls(quoted, shaped))
+ assert json.loads(
+ repaired["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"]
+ ) == {"timezone": "Europe/Paris"}
diff --git a/tests/test_serving_args.py b/tests/test_serving_args.py
index 492af6f5..855d549c 100644
--- a/tests/test_serving_args.py
+++ b/tests/test_serving_args.py
@@ -13,6 +13,12 @@ from modal_shared.serving.args import (
VllmServeContext,
build_vllm_args,
)
+from modal_shared.serving.decision_http import (
+ decision_base_vllm_command,
+ decision_vllm_command,
+ probabilities_for,
+ systemone_body,
+)
pytestmark = pytest.mark.covers("model-runtime")
@@ -115,6 +121,115 @@ def test_base_keeps_its_name_without_adapters(tmp_path: Path) -> None:
assert cmd[cmd.index("--served-model-name") + 1] == "deploy-1"
+def test_sglang_dflash_argv_and_engine_choice() -> None:
+ from modal_shared.serving.engine import engine_for
+ from modal_shared.serving.sglang import build_sglang_args, sglang_tool_parser
+
+ cmd = build_sglang_args(
+ model_path="/tmp/folded",
+ served_name="dedicated/ft",
+ port=8000,
+ draft_model="/weights/.drafts/z-lab--Qwen3.5-4B-DFlash",
+ draft_tokens=15,
+ tool_call_parser="qwen3_coder",
+ reasoning_parser="openai_gptoss",
+ )
+ assert cmd[cmd.index("--attention-backend") + 1] == "fa3"
+ ada = build_sglang_args(
+ model_path="/tmp/folded",
+ served_name="dedicated/ft",
+ port=8000,
+ gpu_type="L4",
+ )
+ assert ada[ada.index("--attention-backend") + 1] == "flashinfer"
+ oss = build_sglang_args(
+ model_path="/tmp/folded",
+ served_name="dedicated/ft",
+ port=8000,
+ gpu_type="A100-80GB",
+ model="openai/gpt-oss-20b",
+ )
+ assert oss[oss.index("--attention-backend") + 1] == "triton"
+ assert cmd[cmd.index("--tool-call-parser") + 1] == "qwen3_coder"
+ assert cmd[cmd.index("--reasoning-parser") + 1] == "gpt-oss"
+ assert sglang_tool_parser("openai") == "gpt-oss"
+ assert sglang_tool_parser("llama3_json") == "llama3"
+ assert sglang_tool_parser("muse_glimmer") == "muse"
+ assert cmd[cmd.index("--speculative-algorithm") + 1] == "DFLASH"
+ assert cmd[cmd.index("--speculative-num-draft-tokens") + 1] == "15"
+ mtp_cmd = build_sglang_args(
+ model_path="/tmp/folded",
+ served_name="dedicated/ft",
+ port=8000,
+ mtp=(3, 1, 4),
+ tool_call_parser="qwen3_coder",
+ )
+ assert mtp_cmd[mtp_cmd.index("--speculative-algorithm") + 1] == "EAGLE"
+ assert mtp_cmd[mtp_cmd.index("--speculative-num-steps") + 1] == "3"
+ assert mtp_cmd[mtp_cmd.index("--speculative-eagle-topk") + 1] == "1"
+ assert mtp_cmd[mtp_cmd.index("--speculative-num-draft-tokens") + 1] == "4"
+ assert "--speculative-draft-model-path" not in mtp_cmd
+ assert "--mamba-scheduler-strategy" not in cmd
+ assert engine_for("Qwen/Qwen3.5-4B") == "sglang"
+ assert engine_for("unsloth/Qwen3.5-9B") == "sglang"
+ assert engine_for("Qwen/Qwen3.8-27B") == "sglang"
+ assert engine_for("openai/gpt-oss-20b") == "sglang"
+ assert engine_for("google/gemma-4-26B-A4B-it") == "vllm"
+ assert engine_for("unsloth/Muse-Glimmer-30B") == "vllm"
+ assert engine_for("Qwen/Qwen3-Coder-30B-A3B-Instruct") == "vllm"
+ assert engine_for("meta-llama/Llama-3.1-8B-Instruct") == "vllm"
+ assert engine_for("Qwen/Qwen3-14B") == "vllm"
+
+
+def test_dflash_argv_for_the_three_bases(tmp_path: Path) -> None:
+ from modal_shared.serving.speculative import draft_for, draft_volume_path, mtp_for
+
+ cmd = _args(
+ _checkpoint(tmp_path),
+ base_model="unsloth/Qwen3-4B",
+ draft_model="/weights/.drafts/z-lab--Qwen3-4B-DFlash-b16",
+ draft_tokens=15,
+ )
+ payload = json.loads(cmd[cmd.index("--speculative-config") + 1])
+ assert payload == {
+ "method": "dflash",
+ "model": "/weights/.drafts/z-lab--Qwen3-4B-DFlash-b16",
+ "num_speculative_tokens": 15,
+ }
+ assert "--cudagraph-capture-sizes" not in cmd
+ for repo in (
+ "Qwen/Qwen3.5-4B",
+ "unsloth/Qwen3.5-4B",
+ "Qwen/Qwen3.5-2B",
+ "unsloth/Qwen3.5-2B",
+ "Qwen/Qwen3.5-0.8B",
+ "unsloth/Qwen3.5-0.8B",
+ "Qwen/Qwen3.5-9B",
+ "unsloth/Qwen3.5-9B",
+ "Qwen/Qwen3.6-27B",
+ "unsloth/Qwen3.6-27B",
+ ):
+ assert mtp_for(repo) == (3, 1, 4)
+ assert draft_for(repo) is None
+ assert draft_for("Qwen/Qwen3-4B") == ("z-lab/Qwen3-4B-DFlash-b16", 15)
+ assert draft_volume_path("/weights", draft_for("Qwen/Qwen3-4B")[0]).startswith(
+ "/weights/.drafts/"
+ )
+ assert draft_for("unsloth/Qwen3.8-27B") == ("z-lab/Qwen3.8-27B-DFlash2", 7)
+ assert draft_for("Qwen/Qwen3.8-27B") == ("z-lab/Qwen3.8-27B-DFlash2", 7)
+ assert draft_for("unsloth/Muse-Glimmer-30B") == ("z-lab/Muse-Glimmer-30B-DFlash2", 7)
+ assert draft_for("unsloth/Llama-3.1-8B-Instruct") == (
+ "z-lab/LLaMA3.1-8B-Instruct-DFlash-UltraChat",
+ 15,
+ )
+ assert draft_for("unsloth/gemma-4-26B-A4B-it") == ("z-lab/gemma-4-26B-A4B-it-DFlash", 15)
+ assert draft_for("unsloth/gemma-4-31B-it") == ("z-lab/gemma-4-31B-it-DFlash", 15)
+ assert draft_for("unsloth/Qwen3.5-27B") == ("z-lab/Qwen3.5-27B-DFlash", 15)
+ assert draft_for("unsloth/Qwen3.5-35B-A3B") == ("z-lab/Qwen3.5-35B-A3B-DFlash", 15)
+ assert draft_for("Qwen/Qwen3-14B") is None
+ assert "--speculative-config" not in _args(_checkpoint(tmp_path), base_model="Qwen/Qwen3-14B")
+
+
def test_lora_slots_capped(tmp_path: Path) -> None:
adapters = tuple((f"a{i}", f"/weights/a{i}") for i in range(MAX_LORA_SLOTS + 4))
cmd = _args(_checkpoint(tmp_path), lora_adapters=adapters)
@@ -145,3 +260,40 @@ def test_chat_template_read_from_adapter_dir(tmp_path: Path) -> None:
chat_template_dir=str(adapter),
)
assert cmd[cmd.index("--chat-template") + 1].startswith(str(adapter))
+
+
+def test_decision_vllm_command_serves_one_adapter(tmp_path: Path) -> None:
+ adapter = tmp_path / "adapter"
+ adapter.mkdir()
+ (adapter / "adapter_config.json").write_text(json.dumps({"r": 8}))
+ cmd = decision_vllm_command(
+ model_path="/tmp/serve",
+ served_name="decision",
+ adapter_path=str(adapter),
+ max_lora_rank=0,
+ max_model_len=4096,
+ )
+ assert cmd[cmd.index("--max-loras") + 1] == "1"
+ assert cmd[cmd.index("--max-lora-rank") + 1] == "8"
+ assert cmd[cmd.index("--lora-modules") + 1] == f"decision={adapter}"
+ assert "--load-format" not in cmd
+ base = decision_base_vllm_command(
+ model_path="vllm-sr/d3-nano", served_name="vllm-sr/d3-nano", max_model_len=4096
+ )
+ assert "--enable-lora" not in base
+ assert base[base.index("--served-model-name") + 1] == "vllm-sr/d3-nano"
+
+
+def test_systemone_probabilities_follow_the_option_order() -> None:
+ request = {
+ "state": "The invoice is overdue.",
+ "question": "What is the risk?",
+ "kind": "choice",
+ "options": ["low", "high"],
+ }
+ body = systemone_body(request, "decision")
+ assert body["model"] == "decision"
+ assert body["questions"]["0"]["criteria"] == {"low": "low", "high": "high"}
+ assert probabilities_for(request, {"probabilities": {"low": 0.2, "high": 0.8}}) == [0.2, 0.8]
+ noul = {**request, "kind": "noul"}
+ assert probabilities_for(noul, {"noul": 0.75}) == [0.25, 0.75]
diff --git a/tests/test_shared_base_serving.py b/tests/test_shared_base_serving.py
index 5b0df106..8102c6c1 100644
--- a/tests/test_shared_base_serving.py
+++ b/tests/test_shared_base_serving.py
@@ -24,6 +24,9 @@ def test_shared_worker_resolves_family_from_sealed_base(monkeypatch, tmp_path):
obj.enable_lora = True
obj.max_lora_rank = 16
(tmp_path / "base").mkdir()
+ draft = tmp_path / ".drafts" / "z-lab--Qwen3-Coder-30B-A3B-DFlash"
+ draft.mkdir(parents=True)
+ (draft / "config.json").write_text("{}")
monkeypatch.setattr(serving, "WEIGHTS_MOUNT", str(tmp_path))
monkeypatch.setattr(serving, "weights_vol", Mock())
monkeypatch.setattr(