Skip to content

The platform for continuously improving AI agents.

refactor(serving): put engine choice on the model row (#349)

Rohit Gupta4212fc491018
diff --git a/.agents/skills/finetuning-model-onboarding/SKILL.md b/.agents/skills/finetuning-model-onboarding/SKILL.md
index 96a18533..0770526a 100644
--- a/.agents/skills/finetuning-model-onboarding/SKILL.md
+++ b/.agents/skills/finetuning-model-onboarding/SKILL.md
@@ -95,7 +95,7 @@ If the family has no existing icon mapping, it falls through to a generic simple
A catalog row that only trains is unfinished. Serving is measured on Modal `--env overmind-dev`. Independent GPU jobs run at the same time.
1. **Thinking has to turn off.** `is_always_on_thinking_template` must be false for the live `hf_model_id` chat template. Then one completion with `chat_template_kwargs.enable_thinking=false` (dedicated serving sets this on every request). `content` has to be the answer. An open `<think>`, or an empty `content` whose answer sits only in `reasoning_content`, is the LFM2.5-2.6B failure: leave the row `disabled` and do not train it.
-1. **Engine.** First boot the pinned dedicated vLLM image and the pinned SGLang image on L4. If both refuse the architecture, try the vendor image and record which image actually loaded. A new serve stack is a new image key (`modal_shared/stacks.py`), not a pin edit on an existing key. `engine_for` gets the winner from measured tokens/s, not from the vendor's preference.
+1. **Engine.** First boot the pinned dedicated vLLM image and the pinned SGLang image on L4. If both refuse the architecture, try the vendor image and record which image actually loaded. A new serve stack is a new image key (`modal_shared/stacks.py`), not a pin edit on an existing key. Record the winner on the catalog row as `inference.dedicated_engine` and `inference.serverless_engine`. Omit a key to use the family `serve_image`. `engine_for` and `serverless_engine` read that row, then the family. Do not add the id to a Python set.
1. **Speculative decoding.** Native MTP only when the checkpoint config has the MTP head (`mtp_for`). DFlash or DFlash2 only when a draft repo exists (`draft_for`). EAGLE with no draft is a refusal. No draft means the server stays on the base.
1. **GPUs.** After one engine loads, repeat on every dedicated GPU that fits: L4, L40S, A100-80GB, H100, H200. Record tokens/s. A missing cell in `serving_benchmarks.json` stays unmeasured in the Console.
1. **Order.** Catalog row first. Then a `MAX_STEPS=2` LoRA through Docker Compose (the Training API, not a side Modal app), which also checks pretok Path A. Then serverless completions of the base and of that adapter. Then dedicated speed on that same adapter (`lora_bf16`, and `merged_fp8` only when `fp8_supported` is true), including H100 when the weights fit in 80 GB. A longer training run can overlap the serving sweep. Context-length probes still follow §4 and are what flips `validated_context_length`.
@@ -115,7 +115,7 @@ A catalog row that only trains is unfinished. Serving is measured on Modal `--en
- [ ] Frontend icon mapped if the family is new
- [ ] Benchmark artifact (`overbae/services/benchmarks/data/benchmark_results.json`) refreshed by a maintainer once the model is in `models.json`, so its benchmark results feed model recommendations; the sync runs outside this repo
- [ ] Thinking can be disabled: template gate plus one live completion whose `content` is the answer with `enable_thinking=false`
-- [ ] Dedicated engine chosen from a pinned-image bake-off (vLLM, SGLang, then a vendor image only if both refuse). `engine_for` matches the measured winner
+- [ ] Dedicated engine chosen from a pinned-image bake-off (vLLM, SGLang, then a vendor image only if both refuse). `inference.dedicated_engine` and `inference.serverless_engine` match the measured winners
- [ ] Speculative decoding recorded: native MTP, DFlash, or DFlash2 when a head or draft exists; otherwise left off
- [ ] `overbae/modal/serving_benchmarks.json` has a row per eligible GPU and serving shape (`lora_bf16`, `merged_fp8`, and `decision` where that contract exists), including H100 when the model fits in 80 GB. Leave a GPU out and the Console shows that speed as unmeasured. Nothing benches from the API process
- [ ] Quick LoRA (`MAX_STEPS=2`) and a longer run went through Docker Compose, then serverless base and LoRA completions, then dedicated tokens/s on that adapter
diff --git a/modal_shared/images/__init__.py b/modal_shared/images/__init__.py
index 2e0864da..b223723f 100644
--- a/modal_shared/images/__init__.py
+++ b/modal_shared/images/__init__.py
@@ -10,16 +10,19 @@ _MODAL_SHARED_DIR = Path(__file__).resolve().parents[1] # modal_shared/
_REPO_ROOT = _MODAL_SHARED_DIR.parent
_ASSETS_DIR = _REPO_ROOT / "overbae" / "services" / "sft_assets"
_ASSETS_REMOTE = "/root/sft_assets"
+_CATALOG = _REPO_ROOT / "overbae" / "modal" / "models.json"
+# engine.py parents[2] is /root when modal_shared lives at /root/modal_shared.
+CATALOG_REMOTE = "/root/overbae/modal/models.json"
def attach_modal_shared(image: modal.Image) -> modal.Image:
- """Mount the whole modal_shared package at /root so containers can import it.
+ """Mount modal_shared and the model catalog.
- modal_shared has zero dependency on the ``overbae`` Django package (which
- would drag in Celery/Django settings on import), so it's safe to side-load
- wholesale — covers modelfam, shared.py, and serving/args.py alike.
+ The catalog file is data. The Django package is not imported.
"""
- return image.add_local_python_source("modal_shared")
+ return image.add_local_python_source("modal_shared").add_local_file(
+ str(_CATALOG), remote_path=CATALOG_REMOTE
+ )
# Back-compat aliases — both used to ship distinct subsets before modal_shared
diff --git a/modal_shared/images/serve.py b/modal_shared/images/serve.py
index f7ea91da..28635ca8 100644
--- a/modal_shared/images/serve.py
+++ b/modal_shared/images/serve.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import modal
-from modal_shared.images import attach_modelfam, attach_serving_args
+from modal_shared.images import attach_modelfam
from modal_shared.stacks import SERVE_SGLANG, SERVE_SGLANG_KEV, SERVE_SGLANG_LFM3, SERVE_VLLM
_SERVE_ENV = {
@@ -21,33 +21,31 @@ _SERVE_ENV = {
def _from_vllm_openai(tag: str, *extra_pip: str, snapshot: bool = False) -> modal.Image:
"""Official ``vllm/vllm-openai`` image. ENTRYPOINT is ``vllm serve`` — must be
cleared or Modal never runs the worker. Image has python3 only."""
- return attach_serving_args(
- attach_modelfam(
- modal.Image.from_registry(
- f"vllm/vllm-openai:{tag}",
- setup_dockerfile_commands=[
- "RUN ln -sf $(command -v python3) /usr/local/bin/python",
- ],
- )
- .entrypoint([])
- .pip_install(
- "httpx>=0.28.0",
- # Concurrent safetensors reads into GPU; vLLM extra `runai`.
- "runai-model-streamer==0.16.1" if snapshot else "runai-model-streamer>=0.15.7",
- *extra_pip,
- )
- .env(
- {
- **_SERVE_ENV,
- **(
- dict.fromkeys(
- ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"), "8"
- )
- if snapshot
- else {}
- ),
- }
- )
+ return attach_modelfam(
+ modal.Image.from_registry(
+ f"vllm/vllm-openai:{tag}",
+ setup_dockerfile_commands=[
+ "RUN ln -sf $(command -v python3) /usr/local/bin/python",
+ ],
+ )
+ .entrypoint([])
+ .pip_install(
+ "httpx>=0.28.0",
+ # Concurrent safetensors reads into GPU; vLLM extra `runai`.
+ "runai-model-streamer==0.16.1" if snapshot else "runai-model-streamer>=0.15.7",
+ *extra_pip,
+ )
+ .env(
+ {
+ **_SERVE_ENV,
+ **(
+ dict.fromkeys(
+ ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"), "8"
+ )
+ if snapshot
+ else {}
+ ),
+ }
)
)
@@ -60,7 +58,7 @@ _DEDICATED_VLLM_TAG = _VLLM_TAG
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(
+dedicated_sglang_image = attach_modelfam(
modal.Image.from_registry(
f"lmsysorg/sglang:{_DEDICATED_SGLANG_TAG}",
setup_dockerfile_commands=["RUN ln -sf $(command -v python3) /usr/local/bin/python"],
@@ -68,7 +66,7 @@ dedicated_sglang_image = attach_serving_args(
.entrypoint([])
.pip_install("runai-model-streamer>=0.15.7")
)
-dedicated_sglang_kev_image = attach_serving_args(
+dedicated_sglang_kev_image = attach_modelfam(
modal.Image.from_registry(
"lmsysorg/sglang:v0.5.23",
setup_dockerfile_commands=["RUN ln -sf $(command -v python3) /usr/local/bin/python"],
@@ -78,7 +76,7 @@ dedicated_sglang_kev_image = attach_serving_args(
)
# LFM3 conv layers are absent from v0.5.22 and from vLLM 0.33. Support is the
# untagged image built from sgl-project/sglang#46858. Do not point other models here.
-dedicated_sglang_lfm3_image = attach_serving_args(
+dedicated_sglang_lfm3_image = attach_modelfam(
modal.Image.from_registry(
"lmsysorg/sglang:dev-lfm3",
setup_dockerfile_commands=["RUN ln -sf $(command -v python3) /usr/local/bin/python"],
diff --git a/modal_shared/modelfam/__init__.py b/modal_shared/modelfam/__init__.py
index b0632bde..a6bd3b42 100644
--- a/modal_shared/modelfam/__init__.py
+++ b/modal_shared/modelfam/__init__.py
@@ -12,6 +12,7 @@ from modal_shared.modelfam.registry import (
FAMILY_NOTES,
all_force_mask_pairs,
all_pretok_headers,
+ clamp_training_gpus,
family_key,
fixups_for_model_type,
is_llama31_family,
@@ -35,6 +36,7 @@ __all__ = [
"all_force_mask_pairs",
"all_pretok_headers",
"catalog_hf_id",
+ "clamp_training_gpus",
"family_key",
"fixups_for_model_type",
"has_training_generation_markers",
diff --git a/modal_shared/modelfam/families.py b/modal_shared/modelfam/families.py
index 1bd792d6..9ac2017e 100644
--- a/modal_shared/modelfam/families.py
+++ b/modal_shared/modelfam/families.py
@@ -15,6 +15,19 @@ from modal_shared.stacks import (
TRAIN_U2026_11_9,
)
+# Gemma 4 parser refuses JSON guided decoding. The native call is the constraint.
+_GEMMA_TOOL_REGEX = r"<\|tool_call>call:(?:{alt})\{[^{}]*\}<tool_call\|>"
+_MUSE_TOOL_REGEX = (
+ r" to=(?:{alt})<\|message\|><atem:function_calls>\n"
+ r"<atem:invoke name=\"(?:{alt})\">\n"
+ r"(?:<atem:parameter name=\"[A-Za-z_][A-Za-z0-9_]*\">[^<]*</atem:parameter>\n)*"
+ r"</atem:invoke>\n</atem:function_calls><\|eot\|>"
+)
+_MUSE_PARALLEL_HINT = (
+ "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."
+)
+
KEV = FamilySpec(
key="kev",
patterns=("jaredpalmer/kev-",),
@@ -73,6 +86,7 @@ GPT_OSS = FamilySpec(
"stock/BF16/MXFP4 start id skips BnB experts and breaks)."
),
hooks_module="families.gpt_oss",
+ lora_load_in_4bit=True,
)
PHI4 = FamilySpec(
@@ -98,6 +112,10 @@ GEMMA4 = FamilySpec(
"(Unsloth offload GC mismatches activations on Gemma4)."
),
hooks_module="families.gemma4",
+ packing=False,
+ max_train_gpus=1,
+ zero_lora_dropout_tokens=("a4b",),
+ forced_tool_regex=_GEMMA_TOOL_REGEX,
)
MUSE_GLIMMER = FamilySpec(
@@ -129,6 +147,9 @@ MUSE_GLIMMER = FamilySpec(
"multimodal-mapping fix (vLLM #53513)."
),
hooks_module="families.muse_glimmer",
+ packing=False,
+ forced_tool_regex=_MUSE_TOOL_REGEX,
+ parallel_tool_hint=_MUSE_PARALLEL_HINT,
)
LFM3 = FamilySpec(
@@ -146,6 +167,10 @@ LFM3 = FamilySpec(
dtype_override="bfloat16",
notes="Tri-hybrid conv + sliding + full attention. Custom code. Thinking closes when enable_thinking is false.",
hooks_module="families.lfm3",
+ # The LFM3 image allowlist has no conv or MLP names. "all" admits them.
+ sglang_serve_lora_targets="all",
+ sglang_adapter_targets="q_proj,k_proj,v_proj,o_proj,in_proj,out_proj",
+ sglang_process_env="modal_shared.serving.lfm3_lora",
)
LFM2 = FamilySpec(
@@ -189,6 +214,7 @@ BOLT = FamilySpec(
force_mask_pairs=(("<|tool_response>", "<tool_response|>"),),
notes="Gemma 4 E4B finetune. FastModel, SDPA, checkpointing off.",
hooks_module="families.bolt",
+ forced_tool_regex=_GEMMA_TOOL_REGEX,
)
# Before generic NEMOTRON — "nemotron-3.5" would otherwise inherit SPECIAL_N pretok.
@@ -207,6 +233,8 @@ NEMOTRON35 = FamilySpec(
"Nemotron 3.5 Lightning hybrid MoE (mamba+attn+experts); LoRA-only Unsloth "
"on u2026_8_tf510; vLLM parsers nemotron_v3 / qwen3_coder."
),
+ packing=False,
+ vllm_process_env="modal_shared.serving.nemotron_lora",
)
NEMOTRON = FamilySpec(
@@ -245,6 +273,7 @@ QWEN38 = FamilySpec(
config_fixups=("nest_qwen3_5_text",),
notes="Qwen3.8 XML tool calls; natively multimodal; Unsloth 2026.9.2 train image.",
hooks_module="families.qwen35",
+ string_content_as_parts=True,
)
QWEN35 = FamilySpec(
@@ -258,6 +287,7 @@ QWEN35 = FamilySpec(
config_fixups=("nest_qwen3_5_text",),
notes="Qwen3.5/3.6 and their Ornith and Fara finetunes. XML tool calls; natively multimodal.",
hooks_module="families.qwen35",
+ string_content_as_parts=True,
)
QWEN3_CODER = FamilySpec(
@@ -276,8 +306,9 @@ QWEN_MM = FamilySpec(
pretok_headers=(r"<\|im_start\|>(\w+)\n",),
natively_multimodal=True,
multimodal_id_tokens=("qwen3-vl", "qwen2-5-vl", "qwen2-vl"),
- notes="Qwen-VL natively multimodal — wrap content as text-typed parts; JSON hermes tools.",
+ notes="Qwen-VL natively multimodal. JSON hermes tools.",
hooks_module="families.qwen_mm",
+ string_content_as_parts=True,
)
QWEN = FamilySpec(
diff --git a/modal_shared/modelfam/registry.py b/modal_shared/modelfam/registry.py
index b1b1ed27..b529536c 100644
--- a/modal_shared/modelfam/registry.py
+++ b/modal_shared/modelfam/registry.py
@@ -76,8 +76,8 @@ def resolve(model_id: str) -> FamilySpec:
def serve_image_key(*blobs: str) -> str:
"""Shared-pool image for these ids.
- A bake-off winner is matched by model id before the family default, because
- one family contains both SGLang and vLLM winners.
+ serverless_engine reads the catalog measurement, then this family's serve image.
+ One family can contain both SGLang and vLLM winners, so the catalog wins.
"""
from modal_shared.serving.engine import serverless_engine
@@ -87,12 +87,17 @@ def serve_image_key(*blobs: str) -> str:
engine = serverless_engine(blob)
if engine != "vllm":
return engine
- key = resolve(blob).serve_image
- if key != "vllm":
- return key
return "vllm"
+def clamp_training_gpus(model_id: str, gpu_type: str, gpu_count: int) -> tuple[str, int]:
+ """Honor FamilySpec.max_train_gpus. Gemma4's balanced device_map crashes."""
+ spec = resolve(model_id)
+ if spec.max_train_gpus and gpu_count > spec.max_train_gpus:
+ return spec.clamped_train_gpu, spec.max_train_gpus
+ return gpu_type, gpu_count
+
+
def serve_image_from_checkpoint(
*,
model_name: str = "",
diff --git a/modal_shared/modelfam/spec.py b/modal_shared/modelfam/spec.py
index d1bdb006..6843f8cc 100644
--- a/modal_shared/modelfam/spec.py
+++ b/modal_shared/modelfam/spec.py
@@ -19,7 +19,7 @@ class FamilySpec:
patterns: tuple[str, ...]
# Modal Unsloth image key — frozen stack id in modal_shared.stacks.
train_image: str = "u2026_8_18"
- # Family default. Per-model shared-pool overrides live in serverless_engine.
+ # Family default when the catalog row omits dedicated_engine / serverless_engine.
serve_image: str = "vllm"
trust_remote_code: bool = False
# Antares/Granite MoE hybrid — skip Unsloth for_inference / use_cache.
@@ -60,3 +60,24 @@ class FamilySpec:
hooks_module: str | None = None
# Extra substrings that flip trust_remote / llama31 helpers without changing key.
llama31_patterns: tuple[str, ...] = field(default_factory=tuple)
+ # False when packing fills the step to MAX_LENGTH and the family OOMs.
+ packing: bool = True
+ # Modal refuses a larger GPU count and moves the run to clamped_train_gpu.
+ max_train_gpus: int | None = None
+ clamped_train_gpu: str = "H200"
+ # model_id substrings that force LoRA dropout to 0.
+ zero_lora_dropout_tokens: tuple[str, ...] = ()
+ # LoRA loads 4-bit even when the memory plan says bf16 fits.
+ lora_load_in_4bit: bool = False
+ # Bare string content hits the vision loader. Text parts do not.
+ string_content_as_parts: bool = False
+ # Dedicated forced-tool pattern. {alt} is the escaped function names.
+ forced_tool_regex: str | None = None
+ parallel_tool_hint: str = ""
+ # SGLang --lora-target-modules when the family list is not in the image allowlist.
+ sglang_serve_lora_targets: str = ""
+ # Adapter tensors to keep. Empty uses lora_target_modules.
+ sglang_adapter_targets: str = ""
+ # Module with process_env(), imported for that engine only.
+ sglang_process_env: str = ""
+ vllm_process_env: str = ""
diff --git a/modal_shared/serving/engine.py b/modal_shared/serving/engine.py
index 6d014815..c1e948e5 100644
--- a/modal_shared/serving/engine.py
+++ b/modal_shared/serving/engine.py
@@ -1,92 +1,69 @@
-"""Which dedicated engine serves a base.
+"""Dedicated and serverless engine for a base.
-In-GPU sentence tok/s with the draft loaded. Absent means vLLM.
+inference.dedicated_engine and inference.serverless_engine on the catalog row
+win. Otherwise the family serve image. The catalog is mounted into Modal
+images at /root/overbae/modal/models.json. A missing file means vllm
+unless the family names another image.
"""
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",
- }
+import json
+from functools import lru_cache
+from pathlib import Path
+
+# Repo checkout, then the path attach_modal_shared writes into a Modal image.
+_CATALOG_CANDIDATES = (
+ Path(__file__).resolve().parents[2] / "overbae" / "modal" / "models.json",
+ Path("/root/overbae/modal/models.json"),
)
+_ENGINE_KEYS = ("dedicated_engine", "serverless_engine")
-# Pinned vLLM and SGLang both refuse this architecture. The class suffix selects
-# dedicated_sglang_lfm3_image.
-_SGLANG_LFM3 = frozenset({"LiquidAI/LFM3-1.7B"})
+def _catalog_file() -> Path | None:
+ for path in _CATALOG_CANDIDATES:
+ if path.is_file():
+ return path
+ return None
-def engine_for(repo: str) -> str:
- if repo in _SGLANG_LFM3:
- return "sglang_lfm3"
- if repo in _SGLANG:
- return "sglang"
- return "vllm"
+@lru_cache(maxsize=1)
+def _engines() -> dict[str, dict[str, str]]:
+ catalog = _catalog_file()
+ if catalog is None:
+ return {}
+ doc = json.loads(catalog.read_text())
+ index: dict[str, dict[str, str]] = {}
+ for row in doc.get("models") or []:
+ inference = row.get("inference") or {}
+ if not isinstance(inference, dict):
+ continue
+ chosen = {key: inference[key] for key in _ENGINE_KEYS if inference.get(key)}
+ if not chosen:
+ continue
+ aliases = {
+ row.get("id"),
+ row.get("hf_model_id"),
+ *(row.get("benchmark_hf_model_ids") or []),
+ }
+ for alias in aliases:
+ if alias and alias not in index:
+ index[str(alias)] = chosen
+ return index
-# Adapter bake-off, both engines serving the same LoRA, higher decode tok/s.
-# This is not the dedicated sentence map: Qwen3-14B and the small Qwen2.5 and
-# Llama rows won here and lost there, and the reverse is true for gpt-oss.
-_SERVERLESS_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.5-35B-A3B",
- "unsloth/Qwen3.5-35B-A3B",
- "Qwen/Qwen3-0.6B",
- "unsloth/Qwen3-0.6B",
- "Qwen/Qwen3-1.7B",
- "unsloth/Qwen3-1.7B",
- "Qwen/Qwen3-4B",
- "unsloth/Qwen3-4B",
- "Qwen/Qwen3-8B",
- "unsloth/Qwen3-8B",
- "Qwen/Qwen3-14B",
- "unsloth/Qwen3-14B",
- "Qwen/Qwen2.5-0.5B-Instruct",
- "unsloth/Qwen2.5-0.5B-Instruct",
- "Qwen/Qwen2.5-7B-Instruct",
- "unsloth/Qwen2.5-7B-Instruct",
- "Qwen/Qwen2.5-14B-Instruct",
- "unsloth/Qwen2.5-14B-Instruct",
- "meta-llama/Llama-3.2-1B-Instruct",
- "unsloth/Llama-3.2-1B-Instruct",
- "meta-llama/Llama-3.2-3B-Instruct",
- "unsloth/Llama-3.2-3B-Instruct",
- "fdtn-ai/antares-350m",
- }
-)
+def _family_serve(repo: str) -> str:
+ from modal_shared.modelfam.registry import resolve
+
+ return resolve(repo).serve_image or "vllm"
+
+
+def engine_for(repo: str) -> str:
+ chosen = _engines().get(repo) or {}
+ return chosen.get("dedicated_engine") or _family_serve(repo)
def serverless_engine(repo: str) -> str:
- """Shared-pool engine. vLLM except where an adapter bake-off picked SGLang."""
- if repo in _SGLANG_LFM3:
- return "sglang_lfm3"
- if repo in _SERVERLESS_SGLANG:
- return "sglang"
- return "vllm"
+ """Shared-pool engine. Catalog measurement, then the family serve image."""
+ chosen = _engines().get(repo) or {}
+ return chosen.get("serverless_engine") or _family_serve(repo)
diff --git a/overbae/modal/modal_vllm_worker.py b/overbae/modal/modal_vllm_worker.py
index 76ebd595..70756fe9 100644
--- a/overbae/modal/modal_vllm_worker.py
+++ b/overbae/modal/modal_vllm_worker.py
@@ -38,6 +38,17 @@ from modal_shared.serving.artifacts import BASE_MANIFEST, read_base_manifest
from modal_shared.serving.sglang import select_sglang_adapter
MODAL_ENVIRONMENT = os.environ.get("MODAL_ENVIRONMENT", "overmind-dev")
+
+
+def _serve_process_env(engine: str, spec) -> dict | None:
+ name = spec.sglang_process_env if str(engine).startswith("sglang") else spec.vllm_process_env
+ if not name:
+ return None
+ import importlib
+
+ return importlib.import_module(name).process_env()
+
+
IS_DEV = MODAL_ENVIRONMENT == "overmind-dev"
MINUTES = 60 # seconds
@@ -509,9 +520,7 @@ class _BaseVLLMWorker:
from modal_shared.serving.sglang import build_sglang_args
# gpt-oss has no thinking-off switch. The parser keeps analysis out of content.
- # The LFM3 image's --lora-target-modules allowlist has no conv or MLP
- # names. "all" admits them; the hidden-dim patch supplies their shapes.
- lora_targets = "all" if engine == "sglang_lfm3" else (spec.lora_target_modules or "")
+ lora_targets = spec.sglang_serve_lora_targets or spec.lora_target_modules or ""
cmd = build_sglang_args(
model_path=full_path,
served_name=self.model_name,
@@ -587,15 +596,7 @@ class _BaseVLLMWorker:
# List form (no shell) so JSON kwargs like --default-chat-template-kwargs
# are not mangled by the shell.
self._journal.emit("starting_engine_process")
- launch_env = None
- if engine == "sglang_lfm3":
- from modal_shared.serving.lfm3_lora import process_env
-
- launch_env = process_env()
- elif spec.key == "nemotron35" and engine == "vllm":
- from modal_shared.serving.nemotron_lora import process_env as nemotron_env
-
- launch_env = nemotron_env()
+ launch_env = _serve_process_env(engine, spec)
self._proc = subprocess.Popen(cmd, env=launch_env) # noqa: S603
_wait_for_vllm(proc=self._proc, journal=self._journal)
if getattr(self, "snapshot_engine", False):
@@ -680,12 +681,7 @@ class _BaseVLLMWorker:
from modal_shared.serving.sglang import normalize_sglang_adapter
spec = resolve(getattr(self, "base_identity", "") or "")
- if engine == "sglang_lfm3":
- from modal_shared.serving.lfm3_lora import SGLANG_TARGETS
-
- keep_targets = SGLANG_TARGETS
- else:
- keep_targets = spec.lora_target_modules or ""
+ keep_targets = spec.sglang_adapter_targets or spec.lora_target_modules or ""
normalize_sglang_adapter(staged, keep_targets=keep_targets)
load_url = f"http://localhost:{VLLM_PORT}/load_lora_adapter"
payload = {"lora_name": name, "lora_path": str(staged)}
@@ -1698,9 +1694,8 @@ def inference_request(request_id: str, payload: dict) -> dict:
model_name=base_pool_name(rel_path) if adapter_path else payload["model_id"],
max_model_len=payload["max_model_len"],
serve_image=_serve_image_for(
- hinted=serve_image_key(
- payload.get("base_model_id") or "", payload["model_id"], rel_path
- )
+ hinted=payload.get("serve_image")
+ or serve_image_key(payload.get("base_model_id") or "", payload["model_id"])
),
enable_lora=bool(adapter_path),
max_lora_rank=payload.get("lora_rank") or 16,
@@ -1774,7 +1769,7 @@ def pre_warm(
journal = Journal("call:" + modal.current_function_call_id())
journal.emit("resolving_worker")
rel_path = rel_weights_path(weights_path)
- serve_image = _serve_image_for(hinted=serve_image_key(base_model_id, model_id, rel_path))
+ serve_image = _serve_image_for(hinted=serve_image_key(base_model_id, model_id))
worker, _cls_name = _make_worker(
gpu_type=gpu_type,
model_path=rel_path,
diff --git a/overbae/modal/models.json b/overbae/modal/models.json
index 7bcded12..51ad1dca 100644
--- a/overbae/modal/models.json
+++ b/overbae/modal/models.json
@@ -1,5 +1,5 @@
{
- "comment": "Single source of truth for all models supported by the Overmind platform. Each entry carries a 'backend' field naming the provider that trains and serves it (modal | decision). Models available on several backends appear as separate entries with their own inference/finetuning sub-configs. inference.gpu_type is the default for base-model inference (BF16 serving, single GPU). inference.lora_supported declares verified shared-base LoRA support for MoE models; dense models support it by default. inference.min_vram_gb is a measured minimum GPU capacity enforced for automatic inference selection, including short contexts. num_attn_layers/num_kv_heads/head_dim are used by gpu_selector.py to derive the optimal GPU + concurrency for a model at its serving max_model_len, including input and reserved output. For hybrid models (Qwen3.5), num_attn_layers counts only full-attention layers. Use model_registry.py helpers to filter by backend. To add/remove models, edit only this file. modal models train LoRA or Full on H100s/H200s via our train.py; finetuning.context_length is the model's max trainable context = HF config max_position_embeddings (Qwen2.5 32768, Qwen3 dense 40960, Qwen3.5/3.6/3.8/Coder 262144, Llama 3.x / GPT-OSS / Antares-1B 131072, Antares-350M 32768, LFM3-1.7B 262144, LFM2.5-230M/350M/1.2B 32768 per Liquid's documented window, LFM2.5-8B-A1B 128000, LFM2.5-2.6B 131072; train.py applies no RoPE scaling). context_length (top-level) is the published inference window (YaRN-extended where the vendor documents it: Qwen2.5\u22657B and Qwen3 dense \u2192 131072; Qwen2.5-0.5B stays 32768). The runner snaps the actual training MAX_LENGTH up from dataset stats using finetuning_providers.<backend> policy below. pricing.train_from_usd is the 'from' price of a typical small LoRA run at cost: its typical GPU-minutes \u00d7 Modal's H100 rate ($3.95/h, modal.com/pricing, retrieved 2026-11-20) on 1\u00d7H100 (\u226472B). pricing.run_from_usd_per_1m_output is serving per 1M output tokens (Modal L4/L40S self-hosted vLLM floors; MoE uses active-param band). group is the marketing library tab label (Group on /models specs); provider comes from providers.display_names. model.marketing holds buyer-facing copy per model (pitch, description, overview, good_for) for the marketing site detail pages. group is only the library tab/filter label. library_filters defines the marketing /models multi-select filters (use_case, tier, context); each model.use_cases lists which use-case filter ids apply. tier/context filters match model.tier and model.context_length against library_filters entries. The order of the models array is the catalog display order within a tier (newest generation first); recommendation ranking is decided by benchmark grades, not by this order.",
+ "comment": "Single source of truth for all models supported by the Overmind platform. Each entry carries a 'backend' field naming the provider that trains and serves it (modal | decision). Models available on several backends appear as separate entries with their own inference/finetuning sub-configs. inference.gpu_type is the default for base-model inference (BF16 serving, single GPU). inference.lora_supported declares verified shared-base LoRA support for MoE models; dense models support it by default. inference.min_vram_gb is a measured minimum GPU capacity enforced for automatic inference selection, including short contexts. num_attn_layers/num_kv_heads/head_dim are used by gpu_selector.py to derive the optimal GPU + concurrency for a model at its serving max_model_len, including input and reserved output. For hybrid models (Qwen3.5), num_attn_layers counts only full-attention layers. Use model_registry.py helpers to filter by backend. To add/remove models, edit only this file. inference.dedicated_engine and inference.serverless_engine name the measured serve stack for that row. Omit a key to use the family serve image. modal models train LoRA or Full on H100s/H200s via our train.py; finetuning.context_length is the model's max trainable context = HF config max_position_embeddings (Qwen2.5 32768, Qwen3 dense 40960, Qwen3.5/3.6/3.8/Coder 262144, Llama 3.x / GPT-OSS / Antares-1B 131072, Antares-350M 32768, LFM3-1.7B 262144, LFM2.5-230M/350M/1.2B 32768 per Liquid's documented window, LFM2.5-8B-A1B 128000, LFM2.5-2.6B 131072; train.py applies no RoPE scaling). context_length (top-level) is the published inference window (YaRN-extended where the vendor documents it: Qwen2.5\u22657B and Qwen3 dense \u2192 131072; Qwen2.5-0.5B stays 32768). The runner snaps the actual training MAX_LENGTH up from dataset stats using finetuning_providers.<backend> policy below. pricing.train_from_usd is the 'from' price of a typical small LoRA run at cost: its typical GPU-minutes \u00d7 Modal's H100 rate ($3.95/h, modal.com/pricing, retrieved 2026-11-20) on 1\u00d7H100 (\u226472B). pricing.run_from_usd_per_1m_output is serving per 1M output tokens (Modal L4/L40S self-hosted vLLM floors; MoE uses active-param band). group is the marketing library tab label (Group on /models specs); provider comes from providers.display_names. model.marketing holds buyer-facing copy per model (pitch, description, overview, good_for) for the marketing site detail pages. group is only the library tab/filter label. library_filters defines the marketing /models multi-select filters (use_case, tier, context); each model.use_cases lists which use-case filter ids apply. tier/context filters match model.tier and model.context_length against library_filters entries. The order of the models array is the catalog display order within a tier (newest generation first); recommendation ranking is decided by benchmark grades, not by this order.",
"providers": {
"comment": "Friendly display name per model-id prefix (the part before the first '/'), keyed lowercase, under display_names. Used by overbae.services.model_library to label each model's family/provider on the public /library pages. Unknown prefixes fall back to a title-cased version of the raw prefix \u2014 add an entry here instead of hardcoding it in Python.",
"display_names": {
@@ -33,6 +33,8 @@
"hidden_size": 2560,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -96,6 +98,8 @@
"hidden_size": 2048,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -159,6 +163,8 @@
"hidden_size": 1024,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -223,6 +229,8 @@
"hidden_size": 2560,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -286,6 +294,7 @@
"hidden_size": 2048,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -347,6 +356,7 @@
"hidden_size": 1024,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -408,6 +418,7 @@
"hidden_size": 896,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -469,6 +480,7 @@
"hidden_size": 3072,
"fp8_supported": false,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -530,6 +542,7 @@
"hidden_size": 2048,
"fp8_supported": false,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -961,6 +974,7 @@
"hidden_size": 1024,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 8192
},
@@ -1021,6 +1035,8 @@
"hidden_size": 4096,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 16384
},
@@ -1085,6 +1101,8 @@
"hidden_size": 4096,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 16384
},
@@ -1148,6 +1166,7 @@
"hidden_size": 3584,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L4",
"max_model_len": 16384
},
@@ -1522,6 +1541,7 @@
"hidden_size": 5120,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
"gpu_type": "L40S",
"max_model_len": 16384
},
@@ -1585,6 +1605,7 @@
"hidden_size": 5120,
"fp8_supported": true,
"inference": {
+ "dedicated_engine": "sglang",
"gpu_type": "L40S",
"max_model_len": 16384
},
@@ -1775,6 +1796,7 @@
"hidden_size": 5120,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L40S",
"max_model_len": 16384
},
@@ -1838,6 +1860,7 @@
"hidden_size": 5120,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "L40S",
"max_model_len": 16384
},
@@ -2026,6 +2049,7 @@
"fp8_supported": false,
"moe": true,
"inference": {
+ "dedicated_engine": "sglang",
"gpu_type": "A100-80GB",
"max_model_len": 16384
},
@@ -2090,6 +2114,7 @@
"hidden_size": 2048,
"fp8_supported": true,
"inference": {
+ "serverless_engine": "sglang",
"gpu_type": "H100",
"max_model_len": 16384
},
diff --git a/overbae/services/dedicated_runtime.py b/overbae/services/dedicated_runtime.py
index 3543d9df..d7a9f02e 100644
--- a/overbae/services/dedicated_runtime.py
+++ b/overbae/services/dedicated_runtime.py
@@ -382,18 +382,9 @@ def _tool_names(tools, only: str) -> list[str]:
return names
-def _forced_tool_regex(spec_key: str, names: list[str]) -> str:
+def _forced_tool_regex(pattern: 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\|>"
- )
+ return pattern.replace("{alt}", alt)
def shape_chat_payload(payload: dict, *, base_model_id: str) -> None:
@@ -452,17 +443,13 @@ def shape_chat_payload(payload: dict, *, base_model_id: str) -> None:
_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.",
- )
+ elif spec.parallel_tool_hint and payload.get("parallel_tool_calls") is True:
+ _pin_system(payload, spec.parallel_tool_hint)
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)}
+ if spec.forced_tool_regex and names:
+ payload["structured_outputs"] = {"regex": _forced_tool_regex(spec.forced_tool_regex, names)}
def _served_body(deployment, body: bytes, *, stream: bool) -> bytes:
diff --git a/overbae/services/finetuning_policy.py b/overbae/services/finetuning_policy.py
index 0917562a..dbbf5a91 100644
--- a/overbae/services/finetuning_policy.py
+++ b/overbae/services/finetuning_policy.py
@@ -541,12 +541,14 @@ def derive_training_plan(
lora_dropout = float(hp["lora_dropout"])
else:
lora_dropout = float(qlora["lora_dropout"])
- # Gemma4 MoE (26B-A4B): PEFT ParamWrapper on expert params rejects dropout ≠ 0.
- if model_id and lora_dropout and "a4b" in model_id.lower():
- if "lora_dropout" in training_type or "lora_dropout" in hp:
- raise TrainingPlanError("lora_dropout must be 0 for Gemma4 MoE.")
- notes.append("lora_dropout=0 required for Gemma4 MoE")
- lora_dropout = 0.0
+ # PEFT ParamWrapper on some expert params rejects dropout ≠ 0.
+ if model_id and lora_dropout:
+ spec = resolve(model_id)
+ if any(token in model_id.lower() for token in spec.zero_lora_dropout_tokens):
+ if "lora_dropout" in training_type or "lora_dropout" in hp:
+ raise TrainingPlanError(f"lora_dropout must be 0 for {spec.key}.")
+ notes.append(f"lora_dropout=0 required for {spec.key}")
+ lora_dropout = 0.0
lora_target_modules = str(
training_type.get("lora_trainable_modules")
or _default_lora_target_modules(model_id)
@@ -575,19 +577,12 @@ def derive_training_plan(
raise TrainingPlanError(
"packing is unsupported for native decision training; choose packing=false."
)
- # Gemma4/Muse: Unsloth forces GC off + flex_attention. Nemotron 3.5: hybrid mamba.
- # Packing fills every step to MAX_LENGTH → OOM on 1×H100.
- if packing and model_id:
- from modal_shared.modelfam import family_key # noqa: PLC0415
-
- fam = family_key(model_id)
- if fam in ("gemma4", "muse_glimmer", "nemotron35"):
- if hp.get("packing"):
- raise TrainingPlanError(f"packing is unsupported for {fam}; choose packing=false.")
- packing = False
- notes.append(
- "packing disabled for Gemma4/Muse/Nemotron 3.5 (hybrid / no gradient checkpointing)"
- )
+ if packing and model_id and not resolve(model_id).packing:
+ fam = resolve(model_id).key
+ if hp.get("packing"):
+ raise TrainingPlanError(f"packing is unsupported for {fam}; choose packing=false.")
+ packing = False
+ notes.append(f"packing disabled for {fam}")
# Train images have no flash-attn varlen. SDPA still crosses packed rows.
if packing:
from overbae.services.sft_assets.packing import packs_safely # noqa: PLC0415
diff --git a/overbae/services/finetuning_runner.py b/overbae/services/finetuning_runner.py
index 85317427..57fb44c3 100644
--- a/overbae/services/finetuning_runner.py
+++ b/overbae/services/finetuning_runner.py
@@ -72,17 +72,6 @@ def _remote_call_failed(call_id: str) -> bool:
return any(node.function_call_id == call_id and node.status in terminal for node in graph)
-def clamp_gemma4_training_gpu(model_id: str, gpu_type: str, gpu_count: int) -> tuple[str, int]:
- """Gemma4 Unsloth cannot pipeline-split: device_map=balanced crashes with
- ``indices should be either on cpu or on the same device as the indexed
- tensor``. Keep a single GPU; upgrade to H200 when the table asked for >1.
- Catalog already disables Full on 26B/31B (would OOM on 1× anyway)."""
- mid = (model_id or "").lower()
- if gpu_count <= 1 or ("gemma-4" not in mid and "gemma4" not in mid):
- return gpu_type, gpu_count
- return "H200", 1
-
-
@dataclass
class SubmissionResult:
remote_id: str
@@ -685,6 +674,8 @@ class ModalRunner(BaseFinetuningRunner):
return config
def _select_training_gpu(self, job, *, context_length: int = 0) -> tuple[str, int]:
+ from modal_shared.modelfam import clamp_training_gpus # noqa: PLC0415
+
try:
cfg = self.model_config(job.base_model)
params_b = (
@@ -699,8 +690,8 @@ class ModalRunner(BaseFinetuningRunner):
if params_b <= max_b:
if context_length > self._LONG_CONTEXT_H200 and count == 1 and gpu == "H100":
gpu = "H200"
- return clamp_gemma4_training_gpu(job.base_model, gpu, count)
- return clamp_gemma4_training_gpu(job.base_model, "H200", 4)
+ return clamp_training_gpus(job.base_model, gpu, count)
+ return clamp_training_gpus(job.base_model, "H200", 4)
@staticmethod
def _gpu_string(gpu_type: str, gpu_count: int) -> str:
@@ -747,18 +738,14 @@ class ModalRunner(BaseFinetuningRunner):
"DECISION_PRE_TRAINING_BASELINE": "1" if plan.pre_training_baseline else "0",
"PACK_ROWS": "1" if plan.packing else "0",
}
- from overbae.modal.model_registry import get_unsloth_image # noqa: PLC0415
-
- env["UNSLOTH_IMAGE"] = get_unsloth_image(model_id)
- from modal_shared.modelfam import family_key # noqa: PLC0415
+ from modal_shared.modelfam import resolve # noqa: PLC0415
- is_gpt_oss = family_key(str(model_id)) == "gpt_oss"
- if plan.training_type == "Lora" and (plan.load_in_4bit or is_gpt_oss):
+ # Family compile flags are hooks.env_overrides, applied before unsloth.
+ # 4-bit is also recorded here so the saved job parameters match the run.
+ if plan.training_type == "Lora" and (
+ plan.load_in_4bit or resolve(model_id).lora_load_in_4bit
+ ):
env["LOAD_IN_4BIT"] = "1"
- if is_gpt_oss:
- env["UNSLOTH_COMPILE_DISABLE"] = "1"
- if family_key(str(model_id)) in {"qwen35", "qwen38"}:
- env["UNSLOTH_BLOCK_COMPILE"] = "0"
if max_steps > 0:
# Probe-run cap only: the wizard and recommender never set max_steps.
env["MAX_STEPS"] = str(max_steps)
@@ -788,10 +775,6 @@ class ModalRunner(BaseFinetuningRunner):
model_cfg = self.model_config(job.base_model)
ft_cfg = model_cfg.get("finetuning") or {}
stats = dict((job.cell.stats if job.cell_id else None) or {})
- try:
- max_row_tokens = int(stats.get("max_token_length") or 0)
- except (TypeError, ValueError):
- max_row_tokens = 0
hp = dict(job.hyperparameters or {})
training_kind = "full" if str(hp.get("training_type", {}).get("type")) == "Full" else "lora"
# Exact preprocessing, not the character estimate, owns the chosen context.
diff --git a/overbae/services/inference_requests.py b/overbae/services/inference_requests.py
index 8cc73ee9..82abdbdd 100644
--- a/overbae/services/inference_requests.py
+++ b/overbae/services/inference_requests.py
@@ -16,6 +16,7 @@ from modal_shared.context_budget import (
DEFAULT_OUTPUT_TOKENS,
INCOMPLETE_FINISH_REASONS,
)
+from modal_shared.modelfam import serve_image_key
from modal_shared.operational_events import STORE
from overbae.core.errors import InputValidationError
from overbae.modal.model_registry import get_hf_base
@@ -23,7 +24,7 @@ from overbae.models import InferenceCall, InferenceRequest, Project
from overbae.services import operational_progress
from overbae.services.decision_serving import validate_requests
from overbae.services.deployed_chat import is_cold_start, record_inference_call
-from overbae.services.deployment import modal_environment, poll_operation
+from overbae.services.deployment import modal_environment, poll_operation, serving_gpu
from overbae.services.provider_progress import collect
logger = logging.getLogger(__name__)
@@ -84,7 +85,8 @@ def submit(deployment, user, request_key, payload, *, source="mcp", dedicated=No
"model_id": deployment.model_id,
"base_model_id": get_hf_base(deployment.base_model_id),
"weights_path": deployment.weights_path,
- "gpu_type": deployment.gpu_type,
+ "gpu_type": serving_gpu(deployment),
+ "serve_image": serve_image_key(deployment.base_model_id, deployment.model_id),
"max_model_len": deployment.max_model_len,
"lora_rank": deployment.lora_rank,
"adapter_path": deployment.adapter_path,
diff --git a/overbae/services/provider_progress.py b/overbae/services/provider_progress.py
index abc95607..bb9c073f 100644
--- a/overbae/services/provider_progress.py
+++ b/overbae/services/provider_progress.py
@@ -107,9 +107,11 @@ def collect(run, *, environment, call_id="", deployed=None):
and deployed.weights_path
and deployed.gpu_type
):
+ from overbae.services.deployment import serving_gpu
+
lora = bool(deployed.adapter_path)
cls_name = worker_cls_name(
- deployed.gpu_type,
+ serving_gpu(deployed),
serve_image_key(deployed.base_model_id, deployed.model_id),
enable_lora=lora,
)
diff --git a/overbae/services/sft_assets/families/__init__.py b/overbae/services/sft_assets/families/__init__.py
index a9edf4bc..2df388c3 100644
--- a/overbae/services/sft_assets/families/__init__.py
+++ b/overbae/services/sft_assets/families/__init__.py
@@ -26,6 +26,10 @@ class TrainerHooks(Protocol):
def peft_lora_dropout(self, default: float, *, model_id: str) -> float: ...
+ def normalize_messages(
+ self, messages: list[dict], tools: list[dict] | None
+ ) -> tuple[list[dict], list[dict] | None]: ...
+
class DefaultHooks:
def env_overrides(self, *, use_lora: bool) -> dict[str, str]:
@@ -52,6 +56,11 @@ class DefaultHooks:
def peft_lora_dropout(self, default: float, *, model_id: str) -> float:
return default
+ def normalize_messages(
+ self, messages: list[dict], tools: list[dict] | None
+ ) -> tuple[list[dict], list[dict] | None]:
+ return messages, tools
+
_DEFAULT = DefaultHooks()
diff --git a/overbae/services/sft_assets/families/gpt_oss.py b/overbae/services/sft_assets/families/gpt_oss.py
index 14a5748d..4e740a15 100644
--- a/overbae/services/sft_assets/families/gpt_oss.py
+++ b/overbae/services/sft_assets/families/gpt_oss.py
@@ -164,7 +164,11 @@ class GptOssHooks(DefaultHooks):
_require_kernels()
out: dict[str, str] = {}
if use_lora:
- out["LOAD_IN_4BIT"] = "1"
+ from catalog import resolve
+
+ model_id = os.environ.get("MODEL_ID") or "gpt-oss"
+ if resolve(model_id).lora_load_in_4bit:
+ out["LOAD_IN_4BIT"] = "1"
# Keep Unsloth's default reshaped-2D GptOssExperts (matches the
# BF16 repo's fused tensors) instead of the ModuleList class that
# expects a pre-split checkpoint — see module docstring.
diff --git a/overbae/services/sft_assets/families/phi4.py b/overbae/services/sft_assets/families/phi4.py
index c433158c..c5880336 100644
--- a/overbae/services/sft_assets/families/phi4.py
+++ b/overbae/services/sft_assets/families/phi4.py
@@ -1,5 +1,60 @@
-"""Phi-4 placeholder hooks — behavior lives in pretok's normalize_messages_for_model."""
+"""Phi-4 tool rows. The template ignores tool_calls."""
+
+from __future__ import annotations
+
+import json
from families import DefaultHooks
-hooks = DefaultHooks()
+
+class Phi4Hooks(DefaultHooks):
+ def normalize_messages(
+ self, messages: list[dict], tools: list[dict] | None
+ ) -> tuple[list[dict], list[dict] | None]:
+ if tools is None:
+ return messages, tools
+ # system.tools is a JSON string. Assistant content is {name, arguments}.
+ # A tool role's content is the result JSON. Tools are not also a kwarg.
+ msgs: list[dict] = []
+ tools_json = json.dumps(tools)
+ has_system = False
+ for raw in messages:
+ message = dict(raw)
+ role = message.get("role")
+ if role == "system":
+ has_system = True
+ message["tools"] = tools_json
+ msgs.append(message)
+ continue
+ if role == "assistant" and message.get("tool_calls"):
+ call = message["tool_calls"][0]
+ function = call.get("function") or call
+ msgs.append(
+ {
+ "role": "assistant",
+ "content": json.dumps(
+ {
+ "name": function.get("name"),
+ "arguments": function.get("arguments", {}),
+ }
+ ),
+ }
+ )
+ continue
+ if role == "tool":
+ msgs.append({"role": "tool", "content": message.get("content", "")})
+ continue
+ msgs.append({key: value for key, value in message.items() if key != "tool_calls"})
+ if not has_system:
+ msgs.insert(
+ 0,
+ {
+ "role": "system",
+ "content": "You are a helpful assistant.",
+ "tools": tools_json,
+ },
+ )
+ return msgs, None
+
+
+hooks = Phi4Hooks()
diff --git a/overbae/services/sft_assets/families/qwen_mm.py b/overbae/services/sft_assets/families/qwen_mm.py
index 12a8de24..8c08f8fd 100644
--- a/overbae/services/sft_assets/families/qwen_mm.py
+++ b/overbae/services/sft_assets/families/qwen_mm.py
@@ -1,4 +1,4 @@
-"""Qwen multimodal — pretok wraps content as text parts."""
+"""Qwen multimodal. String content becomes text parts via FamilySpec."""
from families import DefaultHooks
diff --git a/overbae/services/sft_assets/pretok.py b/overbae/services/sft_assets/pretok.py
index 132ec8ec..5ff0f53e 100644
--- a/overbae/services/sft_assets/pretok.py
+++ b/overbae/services/sft_assets/pretok.py
@@ -22,7 +22,8 @@ import sys
from pathlib import Path
from typing import Any
-from catalog import family_key
+from catalog import resolve
+from families import load_hooks
from training_chat_template import patch_known_training_template
# Optional TRL>=1.4 training-template helpers.
@@ -164,59 +165,18 @@ def normalize_messages_for_model(
"""Family-specific message/tool shaping before apply_chat_template."""
tools = ensure_tool_param_descriptions(tools)
messages = normalize_openai_wire(messages)
- fam = family_key(model_id)
-
- if fam == "phi4" and tools is not None:
- # The Phi-4 template ignores tool_calls and instead expects
- # system.tools = JSON string, assistant.content = JSON {name, arguments},
- # and a tool role whose content is the result JSON.
- msgs: list[dict] = []
- tools_json = json.dumps(tools)
- has_system = False
- for m in messages:
- m = dict(m)
- role = m.get("role")
- if role == "system":
- has_system = True
- m["tools"] = tools_json
- msgs.append(m)
- continue
- if role == "assistant" and m.get("tool_calls"):
- tc = m["tool_calls"][0]
- fn = tc.get("function") or tc
- args = fn.get("arguments", {})
- msgs.append(
- {
- "role": "assistant",
- "content": json.dumps({"name": fn.get("name"), "arguments": args}),
- }
- )
- continue
- if role == "tool":
- msgs.append({"role": "tool", "content": m.get("content", "")})
- continue
- msgs.append({k: v for k, v in m.items() if k != "tool_calls"})
- if not has_system:
- msgs.insert(
- 0,
- {"role": "system", "content": "You are a helpful assistant.", "tools": tools_json},
- )
- # Phi embeds tools on the system message — don't also pass tools= kwarg.
- return msgs, None
-
- if fam in ("qwen_mm", "qwen35", "qwen38"):
- # The template's bare-string `content` branch runs everything through the
- # vision image loader; typed text parts take the branch that only
- # image-loads dict parts tagged "image"/"video".
- msgs = []
- for m in messages:
- content = m.get("content")
- if isinstance(content, str):
- m = {**m, "content": [{"type": "text", "text": content}]}
- msgs.append(m)
- return msgs, tools
-
- return messages, tools
+ spec = resolve(model_id)
+ messages, tools = load_hooks(spec.hooks_module).normalize_messages(messages, tools)
+ if not spec.string_content_as_parts:
+ return messages, tools
+ # Bare string content runs through the vision image loader.
+ wrapped = []
+ for message in messages:
+ content = message.get("content")
+ if isinstance(content, str):
+ message = {**message, "content": [{"type": "text", "text": content}]}
+ wrapped.append(message)
+ return wrapped, tools
def _unwrap_tokenizer(tok):
diff --git a/tests/test_dedicated_lora_merge.py b/tests/test_dedicated_lora_merge.py
index ceb37657..33eb0e44 100644
--- a/tests/test_dedicated_lora_merge.py
+++ b/tests/test_dedicated_lora_merge.py
@@ -254,6 +254,14 @@ def test_dedicated_chat_disables_thinking_and_keeps_parallel_tools():
assert "get_time" in named["structured_outputs"]["regex"]
assert "get_weather" not in named["structured_outputs"]["regex"]
+ bolt = {
+ "messages": [{"role": "user", "content": "time"}],
+ "tools": [{"type": "function", "function": {"name": "get_time"}}],
+ "tool_choice": "required",
+ }
+ shape_chat_payload(bolt, base_model_id="nvidia/NVIDIA-Nemotron-3.5-Bolt-E4B-BF16")
+ assert "get_time" in bolt["structured_outputs"]["regex"]
+
required = {
"messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}],
"tools": [{"type": "function", "function": {"name": "get_weather"}}],
diff --git a/tests/test_finetuning_new.py b/tests/test_finetuning_new.py
index b084cd47..255fd06a 100644
--- a/tests/test_finetuning_new.py
+++ b/tests/test_finetuning_new.py
@@ -1249,10 +1249,10 @@ class TestTrainingPlan:
snap_context_length(999_999, model_max=32768)
def test_gemma4_full_never_gets_multi_gpu(self):
- from overbae.services.finetuning_runner import clamp_gemma4_training_gpu
+ from modal_shared.modelfam import clamp_training_gpus
- assert clamp_gemma4_training_gpu("google/gemma-4-31B-it", "H100", 4) == ("H200", 1)
- assert clamp_gemma4_training_gpu("Qwen/Qwen3-32B", "H100", 4) == ("H100", 4)
+ assert clamp_training_gpus("google/gemma-4-31B-it", "H100", 4) == ("H200", 1)
+ assert clamp_training_gpus("Qwen/Qwen3-32B", "H100", 4) == ("H100", 4)
def test_a_modal_run_stages_the_hub_base_weights_before_the_gpu_starts(self, sft, fake_modal):
from overbae.services.deployment import get_hf_base
diff --git a/tests/test_serving_args.py b/tests/test_serving_args.py
index 72468bf6..4a667959 100644
--- a/tests/test_serving_args.py
+++ b/tests/test_serving_args.py
@@ -7,6 +7,7 @@ from pathlib import Path
import pytest
+from modal_shared.modelfam import resolve
from modal_shared.serving.args import (
CUDAGRAPH_CAPTURE_SIZES,
MAX_LORA_SLOTS,
@@ -133,6 +134,7 @@ def test_base_keeps_its_name_without_adapters(tmp_path: Path) -> None:
def test_sglang_dflash_argv_and_engine_choice() -> None:
from modal_shared.serving.engine import engine_for, serverless_engine
+ from modal_shared.serving.lfm3_lora import SGLANG_TARGETS
from modal_shared.serving.sglang import build_sglang_args, sglang_tool_parser
cmd = build_sglang_args(
@@ -202,6 +204,9 @@ def test_sglang_dflash_argv_and_engine_choice() -> None:
assert serverless_engine("Qwen/Qwen3-Coder-30B-A3B-Instruct") == "vllm"
assert serverless_engine("LiquidAI/LFM3-1.7B") == "sglang_lfm3"
assert serverless_engine("openai/gpt-oss-20b") == "vllm"
+ lfm = resolve("LiquidAI/LFM3-1.7B")
+ assert lfm.sglang_adapter_targets == SGLANG_TARGETS
+ assert lfm.sglang_serve_lora_targets == "all"
gemma = build_sglang_args(
model_path="/tmp/folded",
served_name="dedicated/ft",
diff --git a/tests/test_sft_tool_rows.py b/tests/test_sft_tool_rows.py
index 14c3be1f..83aac505 100644
--- a/tests/test_sft_tool_rows.py
+++ b/tests/test_sft_tool_rows.py
@@ -11,7 +11,7 @@ import pytest
# other by bare name and only resolve with the directory itself on sys.path.
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"))
-from pretok import normalize_openai_wire # noqa: E402
+from pretok import normalize_messages_for_model, normalize_openai_wire # noqa: E402
pytestmark = pytest.mark.covers("model-runtime")
@@ -79,3 +79,24 @@ def test_input_messages_are_not_mutated():
def test_plain_turns_are_untouched():
messages = [{"role": "user", "content": "hi"}, {"role": "tool", "content": "{}"}]
assert normalize_openai_wire(messages) == messages
+
+
+def test_phi4_puts_tools_on_the_system_message():
+ messages, tools = normalize_messages_for_model(
+ "microsoft/Phi-4-mini-instruct",
+ [{"role": "user", "content": "hi"}],
+ [{"type": "function", "function": {"name": "send_email", "parameters": {}}}],
+ )
+ assert tools is None
+ assert messages[0]["role"] == "system"
+ assert "send_email" in messages[0]["tools"]
+
+
+def test_qwen35_string_content_becomes_a_text_part():
+ messages, tools = normalize_messages_for_model(
+ "Qwen/Qwen3.5-4B",
+ [{"role": "user", "content": "hi"}],
+ None,
+ )
+ assert tools is None
+ assert messages[0]["content"] == [{"type": "text", "text": "hi"}]
diff --git a/tests/test_stacks.py b/tests/test_stacks.py
index 1e33edb7..9f4b96a8 100644
--- a/tests/test_stacks.py
+++ b/tests/test_stacks.py
@@ -51,6 +51,22 @@ def test_canaries_cover_unsloth_stacks() -> None:
assert not missing, f"unsloth stacks with no canary: {missing}"
+def test_catalog_engines_are_known_stacks() -> None:
+ from modal_shared.images import CATALOG_REMOTE
+ from modal_shared.serving.engine import _CATALOG_CANDIDATES
+
+ assert Path(CATALOG_REMOTE) in _CATALOG_CANDIDATES
+ data = json.loads(_MODELS_JSON.read_text())
+ bad = []
+ for entry in data["models"]:
+ inference = entry.get("inference") or {}
+ for key in ("dedicated_engine", "serverless_engine"):
+ engine = inference.get(key)
+ if engine and engine not in SERVE_STACKS:
+ bad.append((entry["id"], key, engine))
+ assert not bad, bad
+
+
def test_catalog_unsloth_image_matches_family() -> None:
data = json.loads(_MODELS_JSON.read_text())
mismatches = []
diff --git a/tests/test_training_plan.py b/tests/test_training_plan.py
index 2038c208..a5b14737 100644
--- a/tests/test_training_plan.py
+++ b/tests/test_training_plan.py
@@ -34,6 +34,11 @@ def _plan(**overrides):
return derive_training_plan(**kwargs)
+def test_gpt_oss_lora_records_4bit():
+ plan = _plan(model_id="openai/gpt-oss-20b", params_b=21.0)
+ assert ModalRunner._training_env(plan, "openai/gpt-oss-20b")["LOAD_IN_4BIT"] == "1"
+
+
def test_modal_plan_uses_its_catalog_bounds_for_shared_model_id():
config = ModalRunner.model_config("Qwen/Qwen3.5-2B")
assert config["backend"] == "modal"
@@ -84,7 +89,6 @@ class TestExplicitValuesWin:
assert plan.token_budget == 32768
env = ModalRunner._training_env(plan, "Qwen/Qwen3.5-4B")
assert env["PADDED_TOKEN_BUDGET"] == "32768"
- assert env["UNSLOTH_BLOCK_COMPILE"] == "0"
@pytest.mark.parametrize("enabled", [True, False])
def test_native_baseline_choice_reaches_worker_environment(self, enabled):