Skip to content

The platform for continuously improving AI agents.

Serve chat with an FP8 KV cache and a per-model sequence cap (#275)

Rohit Gupta614c0a35e831
diff --git a/.agents/skills/backend-architecture/references/serving.md b/.agents/skills/backend-architecture/references/serving.md
index 7d8f30f9..2657a946 100644
--- a/.agents/skills/backend-architecture/references/serving.md
+++ b/.agents/skills/backend-architecture/references/serving.md
@@ -10,7 +10,7 @@
## 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` with a per-deployment `pool` and report latency only. 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). 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. 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. 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` with a per-deployment `pool` and report latency only. 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.
## Workers
diff --git a/modal_shared/serving/args.py b/modal_shared/serving/args.py
index 24454e3b..599762a7 100644
--- a/modal_shared/serving/args.py
+++ b/modal_shared/serving/args.py
@@ -130,6 +130,8 @@ def build_vllm_args(ctx: VllmServeContext, spec: FamilySpec | None = None) -> li
ctx.gpu_memory_utilization,
"--max-num-seqs",
str(ctx.max_num_seqs),
+ "--kv-cache-dtype",
+ "fp8",
"--enable-force-include-usage",
"--enable-auto-tool-choice",
"--tool-call-parser",
@@ -186,7 +188,7 @@ def build_vllm_args(ctx: VllmServeContext, spec: FamilySpec | None = None) -> li
"--model-loader-extra-config",
json.dumps({"distributed": True}, separators=(",", ":")),
"--cudagraph-capture-sizes",
- *(str(s) for s in 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)
diff --git a/modal_shared/serving/capacity.py b/modal_shared/serving/capacity.py
new file mode 100644
index 00000000..24a8f383
--- /dev/null
+++ b/modal_shared/serving/capacity.py
@@ -0,0 +1,99 @@
+"""How many full-context sequences fit on one GPU.
+
+Chat serving stores the KV cache in FP8, so each element is one byte. The 2 in
+the per-token size is the K tensor plus the V tensor, not the dtype width.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+GPU_MEMORY_UTILIZATION = 0.90
+# Non-KV memory vLLM holds beyond the weights: peak activations, CUDA context,
+# allocator slack, and captured CUDA graphs. Measured at 3.25 GiB on
+# Qwen2.5-72B-Instruct FP8 / H200; the short capture list adds 0.16-0.22 GiB
+# of graphs plus ~0.15 GiB of activation, so 4.0 keeps the eager 3.5 margin.
+# MoE bases run higher (~5.1 GiB). That gap only skews the concurrency estimate.
+ACTIVATION_OVERHEAD_GB = 4.0
+KV_DTYPE_BYTES = 1
+MAX_CONCURRENT = 32
+
+GPU_VRAM_GB = {
+ "L4": 24,
+ "L40S": 48,
+ "A100-80GB": 80,
+ "H100": 80,
+ "H200": 141,
+ "B200": 192,
+ "B300": 288,
+}
+
+
+def sequence_cap(
+ *,
+ vram_gb: float,
+ weight_gb: float,
+ num_attn_layers: int | None,
+ num_kv_heads: int | None,
+ head_dim: int | None,
+ max_model_len: int,
+) -> int | None:
+ """Sequences that fit, or 0 when one full sequence does not. None if the shape is unknown."""
+ if not vram_gb or not num_attn_layers or not num_kv_heads or not head_dim or not max_model_len:
+ return None
+ per_token = 2 * int(num_attn_layers) * int(num_kv_heads) * int(head_dim) * KV_DTYPE_BYTES
+ one_seq_gb = (int(max_model_len) * per_token) / (1024**3)
+ if one_seq_gb <= 0:
+ return None
+ budget = float(vram_gb) * GPU_MEMORY_UTILIZATION - float(weight_gb) - ACTIVATION_OVERHEAD_GB
+ if budget < one_seq_gb:
+ return 0
+ return max(1, min(MAX_CONCURRENT, int(budget / one_seq_gb)))
+
+
+def arch_from_config(cfg: dict) -> tuple[int, int, int] | None:
+ text = cfg.get("text_config")
+ if not isinstance(text, dict) or not text.get("num_hidden_layers"):
+ text = cfg
+ types = text.get("layer_types")
+ if isinstance(types, list) and any(kind == "full_attention" for kind in types):
+ layers = sum(1 for kind in types if kind == "full_attention")
+ else:
+ layers = text.get("num_hidden_layers") or text.get("n_layer")
+ heads = text.get("num_key_value_heads") or text.get("num_kv_heads") or text.get("n_head_kv")
+ dim = text.get("head_dim")
+ if dim is None:
+ hidden = text.get("hidden_size") or text.get("n_embd")
+ n_heads = text.get("num_attention_heads") or text.get("n_head")
+ if hidden and n_heads:
+ dim = int(hidden) // int(n_heads)
+ if not layers or not heads or not dim:
+ return None
+ return int(layers), int(heads), int(dim)
+
+
+def weight_gib(path: Path) -> float | None:
+ files = [p for p in Path(path).glob("*.safetensors") if p.is_file()]
+ if not files:
+ return None
+ return sum(p.stat().st_size for p in files) / (1024**3)
+
+
+def sequence_cap_for_checkpoint(path: Path, *, vram_gb: float, max_model_len: int) -> int | None:
+ config_path = Path(path) / "config.json"
+ if not config_path.is_file():
+ return None
+ arch = arch_from_config(json.loads(config_path.read_text()))
+ weight = weight_gib(path)
+ if arch is None or weight is None:
+ return None
+ layers, heads, dim = arch
+ return sequence_cap(
+ vram_gb=vram_gb,
+ weight_gb=weight,
+ num_attn_layers=layers,
+ num_kv_heads=heads,
+ head_dim=dim,
+ max_model_len=max_model_len,
+ )
diff --git a/modal_shared/serving/fold_serve.py b/modal_shared/serving/fold_serve.py
new file mode 100644
index 00000000..99d87174
--- /dev/null
+++ b/modal_shared/serving/fold_serve.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from modal_shared.serving.merge import install_weight_fold
+
+
+def main() -> None:
+ # The streamer binds the weight iterator at import, so the fold is installed first.
+ install_weight_fold()
+ from vllm.entrypoints.cli.main import main as vllm_main
+
+ vllm_main()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/modal_shared/serving/merge.py b/modal_shared/serving/merge.py
new file mode 100644
index 00000000..6c226db1
--- /dev/null
+++ b/modal_shared/serving/merge.py
@@ -0,0 +1,89 @@
+"""Fold one LoRA into base tensors as vLLM reads them.
+
+The delta is applied to each tensor the runai streamer yields. No second
+checkpoint is written; another container cannot see this process's memory.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from collections.abc import Generator
+from pathlib import Path
+
+import torch
+from safetensors import safe_open
+
+_ENV = "OVERMIND_FOLD_ADAPTER"
+
+
+def install_weight_fold(adapter: Path | None = None) -> None:
+ path = adapter or os.environ.get(_ENV)
+ if not path:
+ return
+ adapter_dir = Path(path)
+ scale = _scale(json.loads((adapter_dir / "adapter_config.json").read_text()))
+ weights = _load_adapter(adapter_dir / "adapter_model.safetensors")
+ consumed: set[str] = set()
+
+ import vllm.model_executor.model_loader.weight_utils as weight_utils
+
+ original = weight_utils.runai_safetensors_weights_iterator
+
+ def folded(
+ hf_weights_files: list[str],
+ use_tqdm_on_load: bool,
+ is_distributed: bool = False,
+ ) -> Generator[tuple[str, torch.Tensor]]:
+ for name, tensor in original(hf_weights_files, use_tqdm_on_load, is_distributed):
+ 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(device=tensor.device, dtype=tensor.dtype)
+ consumed.add(f"{prefix}.lora_A.weight")
+ consumed.add(f"{prefix}.lora_B.weight")
+ yield name, tensor
+ leftover = set(weights) - consumed
+ if leftover:
+ first = sorted(leftover)[0]
+ raise RuntimeError(f"{len(leftover)} adapter keys were not merged; first: {first}")
+
+ weight_utils.runai_safetensors_weights_iterator = folded
+ loader = sys.modules.get("vllm.model_executor.model_loader.runai_streamer_loader")
+ if loader is not None:
+ loader.runai_safetensors_weights_iterator = folded
+ print(f"[vLLM] folding {adapter_dir} into weights as they load", flush=True)
+
+
+def _scale(config: dict) -> float:
+ rank = config.get("r")
+ alpha = config.get("lora_alpha")
+ if not isinstance(rank, int) or rank < 1 or not isinstance(alpha, (int, float)):
+ raise ValueError("adapter_config.json needs integer r and lora_alpha")
+ divisor = rank**0.5 if config.get("use_rslora") else rank
+ return float(alpha) / divisor
+
+
+def _load_adapter(path: Path) -> dict[str, torch.Tensor]:
+ weights: dict[str, torch.Tensor] = {}
+ with safe_open(path, framework="torch") as handle:
+ for name in handle.keys(): # noqa: SIM118
+ key = name.removeprefix("base_model.model.")
+ if not (key.endswith(".lora_A.weight") or key.endswith(".lora_B.weight")):
+ raise ValueError(f"Unexpected adapter key: {name}")
+ weights[key] = handle.get_tensor(name)
+ return weights
+
+
+def _pair_prefix(tensor_name: str, lora_weights: dict[str, torch.Tensor]) -> str | None:
+ if not tensor_name.endswith(".weight"):
+ return None
+ prefix = tensor_name.rsplit(".", 1)[0]
+ if f"{prefix}.lora_A.weight" in lora_weights and f"{prefix}.lora_B.weight" in lora_weights:
+ return prefix
+ if prefix.endswith(".linear"):
+ outer = prefix[: -len(".linear")]
+ if f"{outer}.lora_A.weight" in lora_weights and f"{outer}.lora_B.weight" in lora_weights:
+ return outer
+ return None
diff --git a/modal_shared/serving/stage.py b/modal_shared/serving/stage.py
new file mode 100644
index 00000000..3ecde842
--- /dev/null
+++ b/modal_shared/serving/stage.py
@@ -0,0 +1,45 @@
+"""Point vLLM at the base checkpoint without copying its weights.
+
+Shard files are symlinks. Config, tokenizer, and the adapter chat template are
+small copies, so a rewrite cannot land on the shared weights volume.
+"""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+
+def stage_base(base: Path, adapter: Path, output: Path) -> Path:
+ base = base.resolve()
+ output = output.resolve()
+ if output == base or output.is_relative_to(base):
+ raise ValueError(f"refusing to stage onto the base checkpoint: {output}")
+ shards = sorted(base.glob("*.safetensors"))
+ if not shards:
+ raise FileNotFoundError(f"No *.safetensors in base checkpoint: {base}")
+ if not (adapter / "adapter_model.safetensors").is_file():
+ raise FileNotFoundError(
+ f"LoRA adapter weights not found: {adapter / 'adapter_model.safetensors'}"
+ )
+ if not (adapter / "adapter_config.json").is_file():
+ raise FileNotFoundError(f"LoRA adapter config not found: {adapter / 'adapter_config.json'}")
+
+ if output.exists():
+ shutil.rmtree(output)
+ output.mkdir(parents=True)
+ for shard in shards:
+ (output / shard.name).symlink_to(shard)
+ 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)
+ else:
+ shutil.copy2(path, dest)
+ for name in ("chat_template.jinja", "tokenizer_config.json", "tokenizer.json"):
+ src = adapter / name
+ if src.is_file():
+ shutil.copy2(src, output / name)
+ return output
diff --git a/overbae/api/completions.py b/overbae/api/completions.py
index 3cb3f3ae..1c01ed45 100644
--- a/overbae/api/completions.py
+++ b/overbae/api/completions.py
@@ -27,7 +27,7 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
-from modal_shared.context_budget import reserve_output
+from modal_shared.context_budget import is_context_limit_error, reserve_output
from overbae.api.scoping import project_ids_for
from overbae.api.streaming import (
JSON_IDLE_PING,
@@ -775,6 +775,8 @@ def _dedicated_chat(request, model_id: str, data: dict, started_at):
},
status=status.HTTP_404_NOT_FOUND,
)
+ if data.get("stream"):
+ return _dedicated_chat_stream(request, row, data, started_at)
try:
upstream, raw, content_type = serve_chat(row, json.dumps(data).encode())
except InputValidationError as exc:
@@ -829,6 +831,115 @@ def _dedicated_chat(request, model_id: str, data: dict, started_at):
return Response(parsed, status=upstream)
+def _dedicated_sse_lines(chunks):
+ pending = ""
+ for chunk in chunks:
+ pending += chunk.decode(errors="replace") if isinstance(chunk, bytes) else chunk
+ while "\n" in pending:
+ line, pending = pending.split("\n", 1)
+ if line.endswith("\r"):
+ line = line[:-1]
+ if line:
+ yield line + "\n\n"
+ if pending.strip():
+ yield pending + "\n\n"
+
+
+def _with_public_model(line: str, public_id: str) -> str:
+ stripped = line.strip()
+ if not stripped.startswith("data:") or stripped[5:].strip() == "[DONE]":
+ return line
+ try:
+ payload = json.loads(stripped[5:].strip())
+ except json.JSONDecodeError:
+ return line
+ if not isinstance(payload, dict):
+ return line
+ payload.pop("system_fingerprint", None)
+ if "model" in payload:
+ payload["model"] = public_id
+ return f"data: {json.dumps(payload)}\n\n"
+
+
+def _dedicated_stream_error(message: str, error_type: str) -> str:
+ return "data: " + json.dumps({"error": {"message": message, "type": error_type}}) + "\n\n"
+
+
+def _dedicated_chat_stream(request, row, data: dict, started_at):
+ from overbae.core.errors import InputValidationError
+ from overbae.services.dedicated import serve_chat_stream
+ from overbae.services.dedicated_runtime import ChatStreamError
+
+ include_usage = bool((data.get("stream_options") or {}).get("include_usage"))
+ public_id = row.public_model_id
+ try:
+ upstream = serve_chat_stream(row, json.dumps(data).encode())
+ except InputValidationError as exc:
+ code = (
+ status.HTTP_400_BAD_REQUEST
+ if "systemone" in exc.detail
+ else status.HTTP_503_SERVICE_UNAVAILABLE
+ )
+ return Response(
+ {"error": {"message": exc.detail, "type": "invalid_request_error"}},
+ status=code,
+ )
+
+ def events():
+ captured: dict[str, Any] = {"usage": None, "metrics": None}
+ outcome, error_code = "failed", "incomplete_stream"
+ try:
+ lines = iter_keeping_idle_alive(
+ _dedicated_sse_lines(upstream),
+ ping=SSE_IDLE_PING,
+ )
+ for line in lines:
+ if line.strip() == "data: [DONE]":
+ outcome, error_code = "succeeded", ""
+ forwarded = _process_stream_chunk(line, captured, include_usage)
+ if forwarded is not None:
+ yield _with_public_model(forwarded, public_id)
+ if outcome != "succeeded":
+ raise RuntimeError("incomplete dedicated stream")
+ except InputValidationError as exc:
+ outcome, error_code = "failed", "inference_rejected"
+ yield _dedicated_stream_error(exc.detail, "invalid_request_error")
+ yield "data: [DONE]\n\n"
+ except ChatStreamError as exc:
+ context_error = is_context_limit_error(exc.status, exc.body)
+ outcome = "failed"
+ error_code = "context_length_exceeded" if context_error else "inference_rejected"
+ yield _dedicated_stream_error(
+ CONTEXT_BUDGET_MESSAGE if context_error else "Dedicated inference failed.",
+ error_code,
+ )
+ yield "data: [DONE]\n\n"
+ except Exception:
+ logger.exception("Dedicated chat stream failed for %s", public_id)
+ outcome, error_code = "failed", "server_error"
+ yield _dedicated_stream_error("Dedicated inference failed.", "server_error")
+ yield "data: [DONE]\n\n"
+ finally:
+ record_inference_call(
+ row.deployed_model,
+ captured["usage"],
+ (timezone.now() - started_at).total_seconds() * 1000,
+ user=request.user,
+ metrics=captured.get("metrics"),
+ outcome=outcome,
+ error_code=error_code,
+ source="application" if isinstance(request.auth, APIToken) else "internal",
+ requested_model=public_id,
+ bill=False,
+ )
+
+ return StreamingHttpResponse(
+ AsyncStream(events()),
+ content_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
+
+
def _present_dedicated_body(raw: bytes, public_id: str) -> bytes:
text = raw.decode()
lines = []
diff --git a/overbae/modal/gpu_selector.py b/overbae/modal/gpu_selector.py
index e5d99274..de579fc7 100644
--- a/overbae/modal/gpu_selector.py
+++ b/overbae/modal/gpu_selector.py
@@ -10,26 +10,17 @@ from __future__ import annotations
import logging
from typing import Any
+from modal_shared.serving.capacity import (
+ ACTIVATION_OVERHEAD_GB,
+ GPU_MEMORY_UTILIZATION,
+ GPU_VRAM_GB,
+ MAX_CONCURRENT,
+ sequence_cap,
+)
from overbae.core.errors import InputValidationError
logger = logging.getLogger(__name__)
-GPU_MEMORY_UTILIZATION = 0.90
-# Non-KV memory vLLM holds beyond the weights: peak activations, CUDA context,
-# NCCL/allocator slack, and captured CUDA graphs. Measured at 3.25 GiB on
-# Qwen2.5-72B-Instruct FP8 / H200; capturing CUDAGRAPH_CAPTURE_SIZES adds
-# 0.16-0.22 GiB of graphs plus ~0.15 GiB of activation on L4/L40S/H100, so 4.0
-# keeps the same margin the eager 3.5 had. Widening the capture list costs
-# 1.0-1.43 GiB instead and would need this raised again.
-#
-# MoE bases run higher — Qwen3-Coder-30B-A3B measured ~5.1 GiB even eager, from
-# expert-routing buffers rather than graphs. That gap predates graph capture and
-# only skews the concurrency estimate, since vLLM sizes KV from actual free VRAM.
-ACTIVATION_OVERHEAD_GB = 4.0
-# KV cache dtype bytes: vLLM uses BF16 KV cache by default even for FP8 models.
-KV_DTYPE_BYTES = 2
-# Hard ceiling on concurrent inputs — matches MAX_CONCURRENT_INPUTS in modal_vllm_worker.py
-MAX_CONCURRENT = 32
# KV allowance used only by the missing-arch-constants fallback, where the real
# per-token KV size is unknown. Roughly one mid-length sequence.
FALLBACK_KV_RESERVE_GB = 4.0
@@ -39,14 +30,14 @@ FALLBACK_KV_RESERVE_GB = 4.0
# H100 (same VRAM as A100-80GB, dearer — selection is capacity-only), RTX PRO 6000
# (96 GB but ~1.8 TB/s against H200's 4.8).
GPU_TIERS: list[dict[str, Any]] = [
- {"name": "L4", "vram_gb": 24, "enabled": True},
- {"name": "L40S", "vram_gb": 48, "enabled": True},
- {"name": "A100-80GB", "vram_gb": 80, "enabled": True},
- {"name": "H200", "vram_gb": 141, "enabled": True},
- {"name": "B200", "vram_gb": 192, "enabled": True},
+ {"name": "L4", "vram_gb": GPU_VRAM_GB["L4"], "enabled": True},
+ {"name": "L40S", "vram_gb": GPU_VRAM_GB["L40S"], "enabled": True},
+ {"name": "A100-80GB", "vram_gb": GPU_VRAM_GB["A100-80GB"], "enabled": True},
+ {"name": "H200", "vram_gb": GPU_VRAM_GB["H200"], "enabled": True},
+ {"name": "B200", "vram_gb": GPU_VRAM_GB["B200"], "enabled": True},
# Needs vLLM 0.19.0+: earlier builds hang on SM103 TRTLLM attention, where it
# now falls back to FlashInfer.
- {"name": "B300", "vram_gb": 288, "enabled": True},
+ {"name": "B300", "vram_gb": GPU_VRAM_GB["B300"], "enabled": True},
]
@@ -66,13 +57,8 @@ def _smallest_tier_holding_weights(model_cfg: dict[str, Any], tiers: list[dict[s
# Same VRAM as A100-80GB. Serverless selection omits it; dedicated offers it as a
# speed and price choice beside A100, not as extra capacity.
DEDICATED_TIERS: list[dict[str, Any]] = [
- {"name": "L4", "vram_gb": 24},
- {"name": "L40S", "vram_gb": 48},
- {"name": "A100-80GB", "vram_gb": 80},
- {"name": "H100", "vram_gb": 80},
- {"name": "H200", "vram_gb": 141},
- {"name": "B200", "vram_gb": 192},
- {"name": "B300", "vram_gb": 288},
+ {"name": name, "vram_gb": GPU_VRAM_GB[name]}
+ for name in ("L4", "L40S", "A100-80GB", "H100", "H200", "B200", "B300")
]
@@ -98,14 +84,18 @@ def fitting_gpu_names(model_cfg: dict[str, Any], max_model_len: int, *, fp8: boo
fallback = inference.get("gpu_type") or _smallest_tier_holding_weights(cfg, tiers)
floor = gpu_vram_gb(fallback)
return [tier["name"] for tier in tiers if tier["vram_gb"] >= floor]
- weights_gb = cfg.get("total_params_b") or 0
- weights_gb *= 1 if fp8 else 2
- kv_bytes_per_tok = 2 * num_attn_layers * num_kv_heads * head_dim * KV_DTYPE_BYTES
- min_kv_1seq_gb = (max_model_len * kv_bytes_per_tok) / (1024**3)
+ weights_gb = (cfg.get("total_params_b") or 0) * (1 if fp8 else 2)
names = []
for tier in tiers:
- usable = tier["vram_gb"] * GPU_MEMORY_UTILIZATION
- if usable - weights_gb - ACTIVATION_OVERHEAD_GB >= min_kv_1seq_gb:
+ cap = sequence_cap(
+ vram_gb=tier["vram_gb"],
+ weight_gb=weights_gb,
+ num_attn_layers=num_attn_layers,
+ num_kv_heads=num_kv_heads,
+ head_dim=head_dim,
+ max_model_len=max_model_len,
+ )
+ if cap:
names.append(tier["name"])
return names
@@ -151,30 +141,26 @@ def select_gpu(
return fallback_gpu, MAX_CONCURRENT
fp8 = model_cfg.get("fp8_supported", False)
- bytes_per_param = 1 if fp8 else 2
- weights_gb = model_cfg["total_params_b"] * bytes_per_param
-
- # KV cache bytes per token for full-attention layers only.
- kv_bytes_per_tok = 2 * num_attn_layers * num_kv_heads * head_dim * KV_DTYPE_BYTES
- min_kv_1seq_gb = (max_model_len * kv_bytes_per_tok) / (1024**3)
+ weights_gb = model_cfg["total_params_b"] * (1 if fp8 else 2)
for tier in tiers:
- usable = tier["vram_gb"] * GPU_MEMORY_UTILIZATION
- kv_budget = usable - weights_gb - ACTIVATION_OVERHEAD_GB
- if kv_budget < min_kv_1seq_gb:
+ max_concurrent = sequence_cap(
+ vram_gb=tier["vram_gb"],
+ weight_gb=weights_gb,
+ num_attn_layers=num_attn_layers,
+ num_kv_heads=num_kv_heads,
+ head_dim=head_dim,
+ max_model_len=max_model_len,
+ )
+ if not max_concurrent:
continue
- raw_concurrent = int(kv_budget / min_kv_1seq_gb)
- max_concurrent = max(1, min(MAX_CONCURRENT, raw_concurrent))
logger.info(
- "gpu_selector: model=%s max_model_len=%d → gpu=%s concurrent=%d "
- "(weights=%.1fGB kv_budget=%.1fGB min_kv=%.2fGB)",
+ "gpu_selector: model=%s max_model_len=%d → gpu=%s concurrent=%d (weights=%.1fGB)",
model_cfg.get("id"),
max_model_len,
tier["name"],
max_concurrent,
weights_gb,
- kv_budget,
- min_kv_1seq_gb,
)
return tier["name"], max_concurrent
diff --git a/overbae/modal/modal_vllm_worker.py b/overbae/modal/modal_vllm_worker.py
index f7d3afcb..e60e6d9b 100644
--- a/overbae/modal/modal_vllm_worker.py
+++ b/overbae/modal/modal_vllm_worker.py
@@ -18,6 +18,7 @@ import json
import os
import shutil
import subprocess
+import sys
import threading
import time
import urllib.request
@@ -98,6 +99,18 @@ inference_secret = modal.Secret.from_name("overmind-inference")
_volume_mounts = {WEIGHTS_MOUNT: weights_vol}
+def _vllm_control(path: str):
+ request = urllib.request.Request(
+ f"http://127.0.0.1:{VLLM_PORT}{path}",
+ data=b"",
+ headers={"content-type": "application/json"},
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=WORKER_TIMEOUT_SECONDS) as response:
+ body = response.read()
+ return json.loads(body) if body else None
+
+
def _wait_for_vllm(
timeout: int = 30 * MINUTES, *, proc: subprocess.Popen | None = None, journal=None
) -> None:
@@ -313,9 +326,6 @@ class _BaseVLLMWorker:
self._journal.emit("refreshing_volumes")
weights_vol.reload()
- if not self.enable_lora:
- _rewrite_legacy_layer_types(Path(full_path) / "config.json", _json=_json)
-
# Fail before allocating GPU/vLLM when the weights are genuinely gone, or a bad
# param-set crash-loops the input backlog for minutes per attempt.
self._journal.emit("validating_weights")
@@ -325,6 +335,20 @@ class _BaseVLLMWorker:
"refusing to start — re-register the deployment"
)
+ 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}")
+
+ if not self.enable_lora:
+ _rewrite_legacy_layer_types(Path(full_path) / "config.json", _json=_json)
+
meta_path = f"{full_path}/.meta.json"
quantization = None
base_model = ""
@@ -349,12 +373,20 @@ class _BaseVLLMWorker:
build_vllm_args,
multimodal_text_only_args,
)
+ from modal_shared.serving.capacity import GPU_VRAM_GB, sequence_cap_for_checkpoint
spec = resolve(base_model or self.model_name)
+ 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
+ )
+ # 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"(quantization={quantization!r} base_model={base_model!r} "
- f"tool_parser={spec.tool_call_parser} family={spec.key})"
+ 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(
@@ -362,7 +394,7 @@ class _BaseVLLMWorker:
model_name=self.model_name,
max_model_len=self.max_model_len,
port=VLLM_PORT,
- max_num_seqs=MAX_CONCURRENT_INPUTS,
+ max_num_seqs=max_num_seqs,
quantization=quantization,
base_model=base_model,
enable_lora=self.enable_lora,
@@ -380,6 +412,8 @@ class _BaseVLLMWorker:
"--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")
@@ -393,6 +427,8 @@ class _BaseVLLMWorker:
)
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))
self._serve_command = cmd
# List form (no shell) so JSON kwargs like --default-chat-template-kwargs
@@ -400,6 +436,24 @@ class _BaseVLLMWorker:
self._journal.emit("starting_engine_process")
self._proc = subprocess.Popen(cmd) # noqa: S603
_wait_for_vllm(proc=self._proc, journal=self._journal)
+ if getattr(self, "snapshot_engine", False):
+ # Level 1 copies weights into CPU memory so the snapshot keeps them.
+ # 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)
+
+ def wake(self) -> None:
+ if not getattr(self, "snapshot_engine", False) or getattr(self, "_startup_error", None):
+ return
+ print("[vLLM] waking snapshot", flush=True)
+ try:
+ _vllm_control("/wake_up?tags=weights")
+ _vllm_control("/wake_up?tags=kv_cache")
+ _wait_for_vllm(proc=getattr(self, "_proc", None))
+ except Exception as error:
+ self._fail_startup(error)
+ return
+ print("[vLLM] snapshot restore ready", flush=True)
@modal.exit()
def shutdown(self) -> None:
@@ -899,6 +953,7 @@ def _register_worker(
"max_model_len": modal.parameter(default=default_len),
"enable_lora": modal.parameter(default=lora),
"max_lora_rank": modal.parameter(default=16),
+ "gpu_type": gpu_type,
}
if lora:
parameters["__annotations__"]["base_identity"] = str
@@ -906,7 +961,16 @@ def _register_worker(
else:
# Modal discovers hooks separately by snapshot phase across the entire MRO.
# A post-snapshot hook on the common base would also run for LoRA restores.
- parameters["startup"] = modal.enter()(_BaseVLLMWorker.startup)
+ # 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)
+ if pin_resources:
+ # 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)
cls = type(
cls_name,
(_SharedBaseVLLMWorker if lora else _BaseVLLMWorker,),
@@ -933,7 +997,18 @@ def _register_worker(
"experimental_options": {"enable_gpu_snapshot": True},
}
if lora
- else ({"cpu": 8, "memory": WORKER_MEMORY_MIB[gpu_type]} if pin_resources else {})
+ else (
+ {
+ "cpu": 8,
+ "memory": WORKER_MEMORY_MIB[gpu_type],
+ # Modal rejects a GPU snapshot below this disk floor.
+ "ephemeral_disk": 524288,
+ "enable_memory_snapshot": True,
+ "experimental_options": {"enable_gpu_snapshot": True},
+ }
+ if pin_resources
+ else {}
+ )
),
},
)(cls)
@@ -944,21 +1019,19 @@ def register_dedicated_classes(target_app, owner) -> None:
"""One class per GPU on the dedicated app, including H100. Not the shared inference app."""
for gpu_type in GPU_TIER:
token = gpu_type.replace("-", "")
- for lora in (False, True):
- name = f"{token}_vllm_lora" if lora else f"{token}_vllm"
- slot = {}
- _register_worker(
- name,
- gpu_type,
- "vllm",
- lora=lora,
- target_app=target_app,
- pin_resources=True,
- max_containers=8,
- owner=slot,
- )
- # Keep a serverless class already bound to this module. Add names that loop does not.
- owner.setdefault(name, slot[name])
+ # `{gpu}_vllm` is the serverless global. Modal loads classes by attribute.
+ name = f"{token}_vllm_dedicated"
+ slot = {}
+ _register_worker(
+ name,
+ gpu_type,
+ "vllm",
+ target_app=target_app,
+ pin_resources=True,
+ max_containers=8,
+ owner=slot,
+ )
+ owner[name] = slot[name]
for (_gpu, _serve_image), _cls_name in WORKER_CLS.items():
diff --git a/overbae/services/dedicated.py b/overbae/services/dedicated.py
index 56389ec7..af7cfb3c 100644
--- a/overbae/services/dedicated.py
+++ b/overbae/services/dedicated.py
@@ -333,20 +333,23 @@ def advance(deployment_id: str) -> None:
dedicated_progress.collect(row)
-def serve_chat(row: DedicatedDeployment, body: bytes):
+def _require_chat(row: DedicatedDeployment):
if row.deployed_model.inference_contract == "decision":
raise InputValidationError(
"This model returns decision probabilities. Call POST /api/v1/systemone."
)
if row.status != DedicatedDeployment.Status.ONLINE:
raise InputValidationError(NOT_ONLINE)
- instance = dedicated_runtime.bind(
- row,
- minimum=row.min_replicas,
- maximum=row.max_replicas,
- idle_seconds=row.idle_shutdown_seconds,
- )
- return dedicated_runtime.chat(instance, row, body)
+
+
+def serve_chat(row: DedicatedDeployment, body: bytes):
+ _require_chat(row)
+ return dedicated_runtime.chat(dedicated_runtime.connect(row), 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)
def serve_decision(row: DedicatedDeployment, decisions: list) -> dict:
@@ -354,13 +357,7 @@ def serve_decision(row: DedicatedDeployment, decisions: list) -> dict:
raise InputValidationError("This dedicated deployment is a chat model.")
if row.status != DedicatedDeployment.Status.ONLINE:
raise InputValidationError(NOT_ONLINE)
- instance = dedicated_runtime.bind(
- row,
- minimum=row.min_replicas,
- maximum=row.max_replicas,
- idle_seconds=row.idle_shutdown_seconds,
- )
- return dedicated_runtime.predict(instance, decisions)
+ return dedicated_runtime.predict(dedicated_runtime.connect(row), decisions)
def complete_request(payload: dict) -> dict:
diff --git a/overbae/services/dedicated_progress.py b/overbae/services/dedicated_progress.py
index 25d494ef..ccb5ce33 100644
--- a/overbae/services/dedicated_progress.py
+++ b/overbae/services/dedicated_progress.py
@@ -94,7 +94,7 @@ async def _observe(row, state, since):
env = dedicated_runtime.environment()
app = await modal.App.lookup.aio(dedicated_runtime.APP_NAME, environment_name=env)
workers = set(state.get("workers", []))
- marker = f"dedicated-base-{row.id}" if row.deployed_model.is_lora else row.served_model_id
+ marker = row.served_model_id
until = timezone.now()
discovered = 0
async for entry in app.logs.fetch.aio(since=since, until=until, search_text=marker):
@@ -132,7 +132,7 @@ async def _observe(row, state, since):
dedicated_runtime.worker_class_name(deployed, row.gpu_type),
rel_weights_path(deployed.weights_path),
deployed.max_model_len,
- bool(deployed.is_lora),
+ False,
deployed.lora_rank or 16,
)
try:
diff --git a/overbae/services/dedicated_runtime.py b/overbae/services/dedicated_runtime.py
index 61573c78..b05d9123 100644
--- a/overbae/services/dedicated_runtime.py
+++ b/overbae/services/dedicated_runtime.py
@@ -10,8 +10,12 @@ from decimal import Decimal
import modal
from asgiref.sync import async_to_sync
+from modal_shared.serving.capacity import sequence_cap
from modal_shared.shared import rel_weights_path
from overbae.core.errors import InputValidationError
+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
APP_NAME = "overmind-dedicated"
WORKER_UNAVAILABLE = "Dedicated worker is not deployed."
@@ -35,21 +39,11 @@ 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_lora" if deployed.is_lora else f"{token}_vllm"
-
-
-def _base_identity(model_path: str) -> str:
- try:
- volume = modal.Volume.from_name("overmind-weights", environment_name=environment())
- raw = b"".join(volume.read_file(f"{model_path}/.base-manifest.json"))
- identity = json.loads(raw)["identity"]
- except Exception as exc:
- raise InputValidationError(WORKER_UNAVAILABLE) from exc
- if not isinstance(identity, str) or not identity:
- raise InputValidationError(WORKER_UNAVAILABLE)
- return identity
+ return f"{token}_vllm_dedicated"
def parameters(deployment) -> dict:
@@ -62,19 +56,15 @@ def parameters(deployment) -> dict:
"pool": str(deployment.id),
}
path = rel_weights_path(deployed.weights_path)
- # Unique model name: a shared base name would put every LoRA of that base
- # in one pool and one tenant's floor would warm the others.
params = {
"model_path": path,
- "model_name": deployment.served_model_id
- if not deployed.is_lora
- else f"dedicated-base-{deployment.id}",
+ "model_name": deployment.served_model_id,
"max_model_len": deployed.max_model_len,
- "enable_lora": bool(deployed.is_lora),
+ "enable_lora": False,
"max_lora_rank": deployed.lora_rank or 16,
}
if deployed.is_lora:
- params["base_identity"] = _base_identity(path)
+ params["adapter_path"] = rel_weights_path(deployed.adapter_path)
return params
@@ -88,14 +78,38 @@ def _chat_cls(deployed, gpu_type: str):
)
-def _variant(cls, *, maximum: int, idle_seconds: int):
- if not hasattr(cls, "with_options"):
- return cls
- return cls.with_options(
- max_containers=max(int(maximum), 1), scaledown_window=_window(idle_seconds)
+def chat_sequence_cap(deployment) -> int | None:
+ """Full-context sequences on this deployment's GPU. None when the shape is unknown."""
+ deployed = deployment.deployed_model
+ cfg = get_model_config_any_backend(deployed.base_model_id) or {}
+ params = cfg.get("total_params_b")
+ if not params:
+ return None
+ fp8 = serving_shape(deployed) == "merged_fp8" and bool(cfg.get("fp8_supported"))
+ return sequence_cap(
+ vram_gb=gpu_vram_gb(deployment.gpu_type),
+ weight_gb=float(params) * (1 if fp8 else 2),
+ num_attn_layers=cfg.get("num_attn_layers"),
+ num_kv_heads=cfg.get("num_kv_heads"),
+ head_dim=cfg.get("head_dim"),
+ max_model_len=deployed.max_model_len,
)
+def _variant(cls, deployment, *, maximum: int, idle_seconds: int):
+ if hasattr(cls, "with_options"):
+ cls = cls.with_options(
+ max_containers=max(int(maximum), 1), scaledown_window=_window(idle_seconds)
+ )
+ cap = chat_sequence_cap(deployment)
+ # The class default is 32. A lower fit has to be its own input target or Modal
+ # keeps filling a container that can only run a few sequences.
+ if cap is not None and cap < 32 and hasattr(cls, "with_concurrency"):
+ admitted = max(cap, 1)
+ cls = cls.with_concurrency(max_inputs=admitted, target_inputs=max(1, int(admitted * 0.7)))
+ return cls
+
+
def _scale(cls, deployment, *, minimum: int, maximum: int, idle_seconds: int):
instance = cls(**parameters(deployment))
method = getattr(instance, "update_autoscaler", None)
@@ -128,7 +142,7 @@ def release(deployment, gpu_type: str) -> None:
continue
seen.add(key)
_scale(
- _variant(cls, maximum=maximum, idle_seconds=idle_seconds),
+ _variant(cls, deployment, maximum=maximum, idle_seconds=idle_seconds),
deployment,
minimum=0,
maximum=1,
@@ -152,7 +166,10 @@ def retire_previous_options(deployment) -> None:
cls = _chat_cls(deployed, deployment.gpu_type)
_scale(
_variant(
- cls, maximum=deployment.max_replicas, idle_seconds=deployment.idle_shutdown_seconds
+ cls,
+ deployment,
+ maximum=deployment.max_replicas,
+ idle_seconds=deployment.idle_shutdown_seconds,
),
deployment,
minimum=0,
@@ -161,6 +178,40 @@ def retire_previous_options(deployment) -> None:
)
+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,
+ maximum=_STABLE_MAX,
+ idle_seconds=_STABLE_WINDOW,
+ )
+ return cls(**parameters(deployment))
+ except InputValidationError:
+ raise
+ except Exception as exc:
+ raise InputValidationError(WORKER_UNAVAILABLE) from exc
+
+
def bind(deployment, *, minimum: int, maximum: int, idle_seconds: int):
deployed = deployment.deployed_model
env = environment()
@@ -184,7 +235,7 @@ def bind(deployment, *, minimum: int, maximum: int, idle_seconds: int):
)
cls = _chat_cls(deployed, deployment.gpu_type)
return _scale(
- _variant(cls, maximum=_STABLE_MAX, idle_seconds=_STABLE_WINDOW),
+ _variant(cls, deployment, maximum=_STABLE_MAX, idle_seconds=_STABLE_WINDOW),
deployment,
minimum=minimum,
maximum=maximum,
@@ -210,12 +261,6 @@ def spawn_probe(instance, deployment) -> str:
]
)
else:
- adapter = None
- if deployed.is_lora:
- adapter = (
- deployment.served_model_id,
- rel_weights_path(deployed.adapter_path),
- )
call = instance.infer.spawn(
method="POST",
path="/v1/chat/completions",
@@ -227,7 +272,6 @@ def spawn_probe(instance, deployment) -> str:
}
).encode(),
headers={"content-type": "application/json"},
- adapter=adapter,
)
return call.object_id
@@ -260,7 +304,13 @@ def runner_count(instance, *, decision: bool) -> int | None:
return int(value) if value is not None else None
-def _served_body(deployment, body: bytes) -> bytes:
+class ChatStreamError(Exception):
+ def __init__(self, status: int, body: bytes):
+ self.status = status
+ self.body = body
+
+
+def _served_body(deployment, body: bytes, *, stream: bool) -> bytes:
try:
payload = json.loads(body)
except json.JSONDecodeError:
@@ -268,21 +318,32 @@ def _served_body(deployment, body: bytes) -> bytes:
if not isinstance(payload, dict):
return body
payload["model"] = deployment.served_model_id
+ payload["stream"] = stream
+ if stream:
+ # Usage and per-request timing ride the last SSE chunk. The view strips both
+ # unless the caller asked to see usage.
+ payload["include_metrics"] = True
+ options = payload.get("stream_options")
+ if not isinstance(options, dict):
+ options = {}
+ options["include_usage"] = True
+ payload["stream_options"] = options
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"},
+ }
+
+
def chat(instance, deployment, body: bytes) -> tuple[int, bytes, str]:
- deployed = deployment.deployed_model
- adapter = None
- if deployed.is_lora:
- adapter = (deployment.served_model_id, rel_weights_path(deployed.adapter_path))
- result = instance.infer.remote(
- method="POST",
- path="/v1/chat/completions",
- body=_served_body(deployment, body),
- headers={"content-type": "application/json"},
- adapter=adapter,
- )
+ 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):
@@ -291,6 +352,37 @@ def chat(instance, deployment, body: bytes) -> tuple[int, bytes, str]:
return status, payload, content_type
+def iter_chat_stream(instance, deployment, body: bytes):
+ method, kwargs = _chat_kwargs(instance, deployment, body, stream=True)
+ frames = method.remote_gen(**kwargs)
+ try:
+ 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()
+ if chunk:
+ yield chunk
+ finally:
+ close = getattr(frames, "close", None)
+ if close is not None:
+ close()
+
+
def predict(instance, decisions: list) -> dict:
result = instance.predict.remote(decisions)
if not isinstance(result, dict) or result.get("error_code"):
diff --git a/tests/fakes/modal.py b/tests/fakes/modal.py
index 90710e91..6ff887dc 100644
--- a/tests/fakes/modal.py
+++ b/tests/fakes/modal.py
@@ -133,6 +133,15 @@ class FakeFunction:
def remote(self) -> _Method:
return _Method(self._remote)
+ def remote_gen(self, *args, **kwargs):
+ handler, _ = self._handler()
+ self.cloud.log.append(("remote_gen", self.name, args, kwargs))
+ produced = handler(*args, **kwargs)
+ if isinstance(produced, dict):
+ yield produced
+ else:
+ yield from produced
+
@property
def spawn(self) -> _Method:
return _Method(self._spawn)
diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.py
index 3ab8f664..c702dd6c 100644
--- a/tests/test_dedicated_deployment.py
+++ b/tests/test_dedicated_deployment.py
@@ -7,6 +7,7 @@ import uuid
from datetime import timedelta
import pytest
+from conftest import drain_stream
from django.utils import timezone
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken
@@ -84,7 +85,7 @@ def test_missing_rate_refuses_start_and_a_second_start_conflicts(fake_modal):
deployed = _ready(project)
with pytest.raises(InputValidationError, match="price is unavailable"):
dedicated.start(deployed, user, gpu_type="L4")
- fake_modal.deploy("overmind-dedicated", "H100_vllm.infer", _ok)
+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100")
assert row.credits_per_gpu_hour > 0
with pytest.raises(InputValidationError, match="already has a dedicated"):
@@ -96,7 +97,7 @@ def test_stopped_deployment_can_restart_with_its_saved_configuration(fake_modal)
user = _user()
project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
- fake_modal.deploy("overmind-dedicated", "H100_vllm.infer", _ok)
+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(
deployed,
user,
@@ -135,7 +136,7 @@ def test_running_replicas_are_metered_and_idle_replicas_are_not(fake_modal):
user = _user()
project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
- fake_modal.deploy("overmind-dedicated", "H100_vllm.infer", _ok)
+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
fake_modal.worker_stats = {"num_total_runners": 2, "backlog": 0, "num_running_inputs": 0}
row = dedicated.start(deployed, user, gpu_type="H100", min_replicas=1, max_replicas=2)
dedicated.advance(str(row.id))
@@ -169,7 +170,7 @@ def test_gpu_change_scales_the_previous_gpu_to_zero(fake_modal):
user = _user()
project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
- fake_modal.deploy("overmind-dedicated", "H100_vllm.infer", _ok)
+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100", min_replicas=1, max_replicas=1)
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
@@ -177,7 +178,9 @@ def test_gpu_change_scales_the_previous_gpu_to_zero(fake_modal):
drained = [
kwargs
for kind, name, _, kwargs in fake_modal.log
- if kind == "autoscaler" and name.endswith("H100_vllm") and kwargs.get("min_containers") == 0
+ if kind == "autoscaler"
+ and name.endswith("H100_vllm_dedicated")
+ and kwargs.get("min_containers") == 0
]
assert drained
row.refresh_from_db()
@@ -193,7 +196,7 @@ 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.infer", _ok)
+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
@@ -216,6 +219,73 @@ def test_dedicated_chat_skips_per_request_billing_and_appears_in_the_model_list(
assert row.public_model_id in {item["id"] for item in listed.json()["data"]}
+def test_dedicated_chat_streams_tokens_before_the_reply_finishes(fake_modal):
+ refresh_rates()
+ user = _user()
+ project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
+ from overbae.models import ProjectMembership
+
+ 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)
+ row = dedicated.start(deployed, user, gpu_type="H100")
+ dedicated.advance(str(row.id))
+ dedicated.advance(str(row.id))
+ row.refresh_from_db()
+ client = APIClient()
+ token = RefreshToken.for_user(user)
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.access_token}")
+ response = client.post(
+ "/api/v1/chat/completions",
+ {
+ "model": row.public_model_id,
+ "messages": [{"role": "user", "content": "Hi"}],
+ "stream": True,
+ },
+ format="json",
+ )
+ assert response.status_code == 200
+ assert "text/event-stream" in response["Content-Type"]
+ text = drain_stream(response).decode()
+ assert '"content": "hi"' in text
+ assert f'"model": "{row.public_model_id}"' in text
+ assert "system_fingerprint" not in text
+ assert "tokens_per_second" not in text
+ assert text.strip().endswith("data: [DONE]")
+ call = InferenceCall.objects.get(requested_model=row.public_model_id)
+ assert call.tokens_per_second == 50
+ assert call.cost is None
+
+
def test_dedicated_list_returns_the_latest_row_for_each_model():
from overbae.models import ProjectMembership
diff --git a/tests/test_dedicated_fold_stage.py b/tests/test_dedicated_fold_stage.py
new file mode 100644
index 00000000..01032a2b
--- /dev/null
+++ b/tests/test_dedicated_fold_stage.py
@@ -0,0 +1,27 @@
+"""Dedicated LoRA serves the base shards through symlinks. Weights are not copied."""
+
+from pathlib import Path
+
+from modal_shared.serving.stage import stage_base
+
+
+def test_stage_links_shards_and_overlays_the_adapter_template(tmp_path: Path):
+ base = tmp_path / "base"
+ adapter = tmp_path / "adapter"
+ base.mkdir()
+ adapter.mkdir()
+ shard = base / "model-00001-of-00001.safetensors"
+ shard.write_bytes(b"weights")
+ (base / "config.json").write_text('{"model_type": "qwen2"}')
+ (adapter / "adapter_model.safetensors").write_bytes(b"lora")
+ (adapter / "adapter_config.json").write_text('{"r": 8, "lora_alpha": 16}')
+ (adapter / "chat_template.jinja").write_text("adapter template")
+
+ staged = stage_base(base, adapter, tmp_path / "serve")
+
+ link = staged / shard.name
+ assert link.is_symlink()
+ assert link.resolve() == shard.resolve()
+ assert (staged / "config.json").read_text() == '{"model_type": "qwen2"}'
+ assert (staged / "chat_template.jinja").read_text() == "adapter template"
+ assert link.read_bytes() == b"weights"
diff --git a/tests/test_dedicated_lora_merge.py b/tests/test_dedicated_lora_merge.py
new file mode 100644
index 00000000..af38e6f3
--- /dev/null
+++ b/tests/test_dedicated_lora_merge.py
@@ -0,0 +1,56 @@
+"""A dedicated LoRA boots on its own worker and folds one adapter at startup."""
+
+import importlib
+from types import SimpleNamespace
+
+from overbae.modal import modal_vllm_worker as serving
+from overbae.services.dedicated_runtime import chat, parameters, worker_class_name
+
+
+def test_dedicated_lora_uses_the_plain_worker_and_no_runtime_adapter():
+ deployed = SimpleNamespace(
+ inference_contract="chat",
+ weights_path="/weights/.base_models/Qwen--Qwen2.5-0.5B-Instruct",
+ adapter_path="/weights/.adapters/ft-9be76bc2",
+ is_lora=True,
+ max_model_len=16384,
+ lora_rank=16,
+ )
+ deployment = SimpleNamespace(
+ id="dep",
+ deployed_model=deployed,
+ served_model_id="dedicated/ft-9be76bc2",
+ )
+
+ assert worker_class_name(deployed, "A100-80GB") == "A10080GB_vllm_dedicated"
+ assert parameters(deployment) == {
+ "model_path": ".base_models/Qwen--Qwen2.5-0.5B-Instruct",
+ "model_name": "dedicated/ft-9be76bc2",
+ "max_model_len": 16384,
+ "enable_lora": False,
+ "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_dedicated_worker_is_not_the_serverless_class():
+ discovery = importlib.import_module("modal._partial_function")
+ flags = discovery._PartialFunctionFlags
+ dedicated = serving.B200_vllm_dedicated._get_user_cls()
+ serverless = serving.B200_vllm._get_user_cls()
+ assert dedicated is not serverless
+ assert "snapshot_engine" not in serverless.__annotations__
+ assert "adapter_path" not in serverless.__annotations__
+ assert dedicated.__annotations__["adapter_path"] is str
+ assert dedicated.__annotations__["snapshot_engine"] is bool
+ 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"}
diff --git a/tests/test_finetuning_new.py b/tests/test_finetuning_new.py
index ea264c23..c5347433 100644
--- a/tests/test_finetuning_new.py
+++ b/tests/test_finetuning_new.py
@@ -1277,12 +1277,12 @@ class TestGPUSelectorLogic:
assert gpu == "L4"
assert conc >= 1
- def test_8b_fp8_at_131k_context_needs_l40s(self):
- """L4 has 24 GB; 8 GB FP8 weights + 8×32×128×2 KV at 131 k tokens ≈ 17 GB — doesn't fit."""
+ def test_8b_fp8_at_131k_context_fits_l4(self):
+ """FP8 KV at 131k is 8 GB. L4's 9.6 GB budget holds one sequence."""
from overbae.modal.gpu_selector import select_gpu
gpu, conc = select_gpu(self._cfg(8.0, True, 32, 8, 128), 131072)
- assert gpu == "L40S"
+ assert gpu == "L4"
assert conc >= 1
def test_70b_fp8_at_131k_picks_h200_not_b200(self):
@@ -1292,29 +1292,29 @@ class TestGPUSelectorLogic:
gpu, conc = select_gpu(self._cfg(70.0, True, 80, 8, 128, static_gpu="B200"), 131072)
assert gpu == "H200"
- def test_70b_bf16_at_131k_context_needs_b300(self):
- """BF16 70B weights = 140 GB; KV at 131k ≈ 40 GB → B200 budget only 31 GB, needs B300."""
+ def test_70b_bf16_at_131k_context_fits_b200(self):
+ """BF16 70B weights are 140 GB. FP8 KV at 131k is 20 GB, inside B200's 28.8 GB budget."""
from overbae.modal.gpu_selector import select_gpu
gpu, conc = select_gpu(self._cfg(70.0, False, 80, 8, 128, static_gpu="B300"), 131072)
- assert gpu == "B300"
+ assert gpu == "B200"
+ assert conc >= 1
- def test_32b_fp8_at_40k_fits_a100(self):
- """Qwen3-32B FP8 (32 GB) + KV at 40k tokens fits on A100-80GB with concurrent=3."""
+ def test_32b_fp8_at_40k_fits_l40s(self):
+ """FP8 KV at 40k is 5 GB. L40S's 7.2 GB budget holds one sequence."""
from overbae.modal.gpu_selector import select_gpu
gpu, conc = select_gpu(self._cfg(32.0, True, 64, 8, 128, static_gpu="A100-80GB"), 40960)
- assert gpu == "A100-80GB"
- assert conc >= 2
+ assert gpu == "L40S"
+ assert conc >= 1
- def test_32b_fp8_at_32k_does_not_squeeze_onto_l40s(self):
- """A 32B at 32k OOMs on an L40S: measured non-KV overhead is 3.25 GiB, and
- a concurrent=1 fit has zero slack by construction."""
+ def test_32b_fp8_at_32k_fits_l40s(self):
+ """FP8 KV at 32k is 4 GB, leaving slack inside the 4 GB non-KV reserve on an L40S."""
from overbae.modal.gpu_selector import select_gpu
gpu, conc = select_gpu(self._cfg(32.0, True, 64, 8, 128, static_gpu="A100-80GB"), 32768)
- assert gpu == "A100-80GB"
- assert conc >= 2
+ assert gpu == "L40S"
+ assert conc >= 1
def test_hybrid_model_small_kv_due_to_few_attn_layers(self):
"""Qwen3.5-0.8B has 6 full-attention layers (not 24 total) → tiny KV cache → high concurrency."""
@@ -1322,7 +1322,7 @@ class TestGPUSelectorLogic:
gpu, conc = select_gpu(self._cfg(0.8, True, 6, 2, 256), 131072)
assert gpu == "L4"
- # KV/tok = 2*6*2*256*2 = 12 288 B; at 131072 tokens = 1.5 GB; L4 budget ≈ 19 GB → ≥ 12 concurrent
+ # KV/tok = 2*6*2*256*1 = 6144 B; at 131072 tokens = 0.75 GB.
assert conc >= 8
def test_missing_arch_constants_falls_back_to_static_gpu(self):
@@ -1543,19 +1543,19 @@ class TestDeploymentGPUDerivation:
gpu, _ = self._select("Qwen/Qwen2.5-7B-Instruct", 32768)
assert gpu == "L4"
- def test_llama_8b_at_131k_picks_l40s(self):
- """8B at 131k context: KV cache pushes past L4 budget → L40S."""
+ def test_llama_8b_at_131k_picks_l4(self):
+ """8B FP8 weights plus an FP8 KV cache at 131k fit one sequence on an L4."""
gpu, _ = self._select("meta-llama/Llama-3.1-8B-Instruct", 131072)
- assert gpu == "L40S"
+ assert gpu == "L4"
def test_llama_70b_at_131k_picks_h200(self):
"""70B FP8 at 131k context fits H200; no need for B200."""
gpu, _ = self._select("meta-llama/Llama-3.3-70B-Instruct", 131072)
assert gpu == "H200"
- def test_qwen3_32b_at_40k_picks_a100(self):
+ def test_qwen3_32b_at_40k_picks_l40s(self):
gpu, _ = self._select("Qwen/Qwen3-32B", 40960)
- assert gpu == "A100-80GB"
+ assert gpu == "L40S"
def test_zero_training_ctx_falls_back_to_static_max_model_len(self):
from overbae.modal.gpu_selector import select_gpu
diff --git a/tests/test_serving_args.py b/tests/test_serving_args.py
index ff3d8c50..503ff12a 100644
--- a/tests/test_serving_args.py
+++ b/tests/test_serving_args.py
@@ -30,6 +30,22 @@ def _args(path: Path, **kw) -> list[str]:
return build_vllm_args(ctx)
+def test_kv_cache_is_fp8(tmp_path: Path) -> None:
+ cmd = _args(_checkpoint(tmp_path))
+ assert cmd[cmd.index("--kv-cache-dtype") + 1] == "fp8"
+
+
+def test_capture_sizes_stay_within_the_sequence_cap(tmp_path: Path) -> None:
+ cmd = _args(_checkpoint(tmp_path), max_num_seqs=4)
+ start = cmd.index("--cudagraph-capture-sizes") + 1
+ emitted = []
+ for token in cmd[start:]:
+ if token.startswith("--"):
+ break
+ emitted.append(token)
+ assert emitted == ["1", "2", "4"]
+
+
def test_graphs_captured_and_never_eager(tmp_path: Path) -> None:
cmd = _args(_checkpoint(tmp_path))
assert "--enforce-eager" not in cmd
@@ -68,6 +84,28 @@ def test_base_gets_a_distinct_served_name(tmp_path: Path) -> None:
assert cmd[cmd.index("--served-model-name") + 1] == "deploy-1--base"
+def test_checkpoint_cap_uses_full_attention_layers(tmp_path: Path) -> None:
+ from modal_shared.serving.capacity import arch_from_config, sequence_cap_for_checkpoint
+
+ arch = arch_from_config(
+ {
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 2,
+ "head_dim": 256,
+ "layer_types": ["linear_attention"] * 18 + ["full_attention"] * 6,
+ }
+ )
+ assert arch == (6, 2, 256)
+
+ checkpoint = tmp_path / "weights"
+ checkpoint.mkdir()
+ (checkpoint / "config.json").write_text(
+ '{"num_hidden_layers": 32, "num_key_value_heads": 8, "head_dim": 128}'
+ )
+ (checkpoint / "model.safetensors").write_bytes(b"x" * 1024)
+ assert sequence_cap_for_checkpoint(checkpoint, vram_gb=24, max_model_len=512) == 32
+
+
def test_base_keeps_its_name_without_adapters(tmp_path: Path) -> None:
cmd = _args(_checkpoint(tmp_path))
assert cmd[cmd.index("--served-model-name") + 1] == "deploy-1"