Skip to content

The platform for continuously improving AI agents.

Add Qwen4-35B-A3B for LoRA training and SGLang serving (#379)

Rohit Gupta3324230d2a93
diff --git a/.agents/skills/finetuning-model-onboarding/SKILL.md b/.agents/skills/finetuning-model-onboarding/SKILL.md
index 26ef8728..3d174c76 100644
--- a/.agents/skills/finetuning-model-onboarding/SKILL.md
+++ b/.agents/skills/finetuning-model-onboarding/SKILL.md
@@ -1,6 +1,6 @@
---
name: finetuning-model-onboarding
-description: Rules for adding a new model or model family to the finetuning pipeline, or changing finetuning behavior for an existing one — engine-agnostic customization via family hooks instead of if/else in the shared script, TRL-compatible chat templates ({% generation %} / pretok_trl), H100-before-H200 GPU probing, populating real_max_context_length/validated_context_length in models.json, setting finetuning cost/pricing, and measuring dedicated inference (thinking off, vLLM vs SGLang, MTP/DFlash, GPU tokens/s). Use when onboarding a model to Modal+Unsloth finetuning, adding a ModelFamily, pretok_trl falls back with a training-compatible chat template error, a model fails on its assigned GPU/context length, pricing a new model's training cost, choosing a dedicated serving engine, or retiring a catalog row from finetuning and inference because a successor in a similar size range scores higher.
+description: Rules for adding a new model or model family to the finetuning pipeline, or changing finetuning behavior for an existing one — engine-agnostic customization via family hooks instead of if/else in the shared script, TRL-compatible chat templates ({% generation %} / pretok_trl), H100-before-H200 GPU probing, populating real_max_context_length/validated_context_length in models.json, setting finetuning cost/pricing, and measuring dedicated inference (thinking off, vLLM vs SGLang, MTP/DFlash, GPU tokens/s). Use when onboarding a model to Modal+Unsloth finetuning, adding a ModelFamily, pretok_trl falls back with a training-compatible chat template error, a model fails on its assigned GPU/context length, pricing a new model's training cost, choosing a dedicated serving engine, or retiring a catalog row from finetuning and inference because a successor in a similar size range scores higher. When the ask is to add a model and test fine-tuning plus serverless and dedicated inference, the proof is the running Docker Compose API (and MCP on that API when that is the user path). An experiment patch counts only after it is in platform code and that Docker run uses it.
---
# Finetuning model onboarding
@@ -12,7 +12,7 @@ All finetuning runs on Modal with Unsloth (`overbae/services/sft_assets/engine_u
`engine_unsloth.py` and `overbae/services/finetuning_runner.py`/`finetuning_policy.py` are shared by every model. If a new model needs different behavior:
- Do **not** add `if model_id == "..."` or `if family == "..."` branches to the engine, runner, or policy.
-- Do add/extend a family hooks module under `overbae/services/sft_assets/families/<family>.py`, subclassing `DefaultHooks` (`families/__init__.py`) and overriding only the hook methods you need (`env_overrides`, `load_kwargs`, `post_load`, `device_map`, `sft_config_overrides`, `peft_lora_dropout`, `peft_gradient_checkpointing`, `fast_model_cls`). Export a single `hooks = XxxHooks()`.
+- Do add/extend a family hooks module under `overbae/services/sft_assets/families/<family>.py`, subclassing `DefaultHooks` (`families/__init__.py`) and overriding only the hook methods you need (`env_overrides`, `load_kwargs`, `post_load`, `device_map`, `sft_config_overrides`, `peft_lora_dropout`, `peft_gradient_checkpointing`, `peft_kwargs`, `fast_model_cls`). Export a single `hooks = XxxHooks()`.
- Register the family in `modal_shared/modelfam/families.py` as a `FamilySpec` (patterns, images, `hooks_module="families.<family>"`), then add it to the ordered `_FAMILIES` tuple in `modal_shared/modelfam/registry.py` — **specific patterns before general ones** (e.g. `qwen38`, `qwen35` and `qwen3_coder` before `qwen_mm` before `qwen`).
- The engine calls hooks uniformly (`load_hooks(_spec.hooks_module)` then `_hooks.<method>(...)`) — it never knows which family it's running. That's the contract to preserve.
@@ -98,9 +98,33 @@ A catalog row that only trains is unfinished. Serving is measured on Modal `--en
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`.
+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`. A Modal experiment can find the shape. It does not replace this Docker run (§10).
-## 9. Retiring a model
+## 9. A pinned image that cannot load the model gets a new image, not a pin edit
+
+`modal_shared/stacks.py` pins are immutable. When the current Unsloth, vLLM, or SGLang pin cannot load the architecture (missing `model_type`, transformers cap, parser, kernel), add a new stack key, a new `Image`, a canary for a train stack, and point only that family at it. Do not change the pip or docker pin on a key other families already use.
+
+Boot the existing pinned vLLM image and the existing pinned SGLang image once, on the smallest GPU that could hold the weights, and record the refusal. The image that actually loads is a new key. Pin a digest or an immutable tag, not a floating tag such as `:qwen4`. A checkpoint whose weight bytes are already larger than a GPU's VRAM is not a probe target on that GPU: record the comparison and start at the first tier that can hold the weights.
+
+## 10. Prove the row through Docker, on Modal dev
+
+`modal run --env overmind-dev` finds a working shape: a weight fetch, a context sweep, an engine or LoRA experiment. Independent jobs may run at the same time. Context sweeps stay on one GPU so a larger length starts only after the shorter one finishes a step. That run is not the test the user asked for.
+
+When the ask is to add a model and test fine-tuning, serverless inference, and dedicated inference, drive all three through the Docker Compose stack that is already running. Do not start a second API. Create the short LoRA with the Training API, then a serverless completion and a dedicated completion of that same adapter, the way an end user calls the API. Both servings must load the LoRA. A completion that only hits the base model does not count. Serverless applies the adapter with `/load_lora_adapter` and `lora_path`. Dedicated folds that adapter at boot. `enable_thinking=false` (or the family's off switch) has to come back in `content`.
+
+MCP is the same Compose API. When the user path is MCP, call the catalog tool on that API and read the job or completion back through `get_job`. A unit test or a script that never hits the running API does not count.
+
+A fix that exists only under `experiments/` is not on the platform. Copy it into the family hook, the worker, the image, or the catalog, redeploy the Modal app the Compose worker calls, and run the Docker path again. The Docker run is what shows a patch never left the experiment.
+
+Write the context that finished a step into `training_type.lora.context_length` and set `validated_context_length` only then. The step counts when `num_tokens` is that length. Setting `max_seq_length` on a short row does not. A 131,072-token step that OOMs leaves the last finished length in place. Write measured tokens/s into `serving_benchmarks.json` for every GPU that actually served. Leave an unmeasured GPU out.
+
+A new SGLang image can 403 `/load_lora_adapter` until the server and the caller share `SGLANG_ADMIN_API_KEY`. Generate that key in the process and send it as a bearer token. Do not put it on the command line. The request still has to set `lora_path` or the server answers from the base.
+
+## 11. Copy the base checkpoint to staging and prod after dev is done
+
+Each Modal environment has its own weights volume. A snapshot on `overmind-dev` is not visible to staging or prod. Dev is where the proof runs, including the base download. Once finetuning, serverless inference, and dedicated inference all work end to end for that row, call `fetch_base_model` on `overmind-register` for the same `hf_model_id` in `overmind-staging` and `overmind-prod`. That function is the only writer, and it also pulls the draft when the row has one. Do this after the proof, not during it. A row that is still `disabled`, or whose adapter completion did not select the LoRA, does not get a staging or prod download.
+
+## 12. Retiring a model
A row leaves finetuning, serverless inference, and dedicated inference together by deleting it from `models.json`. Do not leave it `disabled`. `disabled` is for a row that stays in the catalog but cannot be offered yet, such as a checkpoint whose thinking cannot be turned off.
@@ -126,4 +150,7 @@ Current successor removals: every Qwen 2.5 row, Qwen 3 except `Qwen3-0.6B`, `Qwe
- [ ] 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
+- [ ] Existing pinned vLLM and SGLang images were booted when the architecture might already load. A miss is a new stack key and a new image, digest-pinned, not an edit to a live pin
+- [ ] The finishing proof went through the running Docker Compose API, as an end user: a short LoRA, then serverless and dedicated completions of that adapter. Both servings selected the LoRA, and `content` is the answer with thinking off. An `experiments/` script is not that proof. Every fix the experiment needed is in platform code, redeployed, and exercised by that API run. MCP, when it is the user path, is a tool call on that same API
- [ ] 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
+- [ ] After that proof, `fetch_base_model` has sealed the base (and its draft, when the row has one) on `overmind-staging` and `overmind-prod` as well as `overmind-dev`
diff --git a/collector/loadtest/locustfile.py b/collector/loadtest/locustfile.py
index 1a53b8c4..1819fc98 100644
--- a/collector/loadtest/locustfile.py
+++ b/collector/loadtest/locustfile.py
@@ -100,7 +100,11 @@ class IngestUser(FastHttpUser):
def export_traces(self):
body, trace_ids = export_request(customer_name(random.randrange(CUSTOMERS)))
with self.client.post(
- "/api/v1/traces", data=body, headers=PROTO, name="POST /api/v1/traces", catch_response=True
+ "/api/v1/traces",
+ data=body,
+ headers=PROTO,
+ name="POST /api/v1/traces",
+ catch_response=True,
) as response:
if response.status_code == 200:
ingested_trace_ids.extend(trace_ids)
@@ -122,7 +126,11 @@ class ReadUser(FastHttpUser):
def rpc(self, method: str, body: dict, name: str):
with self.client.post(
- f"/otel.trace.v1.TraceService/{method}", json=body, headers=CONNECT, name=name, catch_response=True
+ f"/otel.trace.v1.TraceService/{method}",
+ json=body,
+ headers=CONNECT,
+ name=name,
+ catch_response=True,
) as response:
if response.status_code == 200:
response.success()
@@ -141,11 +149,19 @@ class ReadUser(FastHttpUser):
@task(2)
def list_traces_by_model(self):
- self.rpc("ListTraces", {"pageSize": 50, "model": random.choice(MODELS), **self.scope}, "ListTraces ?model")
+ self.rpc(
+ "ListTraces",
+ {"pageSize": 50, "model": random.choice(MODELS), **self.scope},
+ "ListTraces ?model",
+ )
@task(1)
def list_errors(self):
- self.rpc("ListTraces", {"pageSize": 50, "allSpans": True, "hasError": True, **self.scope}, "ListTraces ?allSpans&hasError")
+ self.rpc(
+ "ListTraces",
+ {"pageSize": 50, "allSpans": True, "hasError": True, **self.scope},
+ "ListTraces ?allSpans&hasError",
+ )
@task(4)
def get_trace(self):
diff --git a/collector/scripts/import_exgentic.py b/collector/scripts/import_exgentic.py
index f9d10abb..4dc735fe 100644
--- a/collector/scripts/import_exgentic.py
+++ b/collector/scripts/import_exgentic.py
@@ -22,8 +22,8 @@ import json
import math
import sys
import time
-from collections import Counter, defaultdict
-from datetime import datetime, timezone
+from collections import Counter
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -35,7 +35,7 @@ PARQUET_LIST_URL = f"https://datasets-server.huggingface.co/parquet?dataset={DAT
DEFAULT_ENDPOINT = "http://127.0.0.1:4318/v1/traces"
DEFAULT_CACHE_DIR = Path.home() / ".cache" / "overmind-exgentic-traces"
-EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
+EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
NS_PER_SEC = 1_000_000_000
NS_PER_MS = 1_000_000
NS_PER_HOUR = 3600 * NS_PER_SEC
@@ -73,10 +73,7 @@ def parse_iso_ns(raw: str | None) -> int | None:
dt = datetime.fromisoformat(text)
except ValueError:
return None
- if dt.tzinfo is None:
- dt = dt.replace(tzinfo=timezone.utc)
- else:
- dt = dt.astimezone(timezone.utc)
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
delta = dt - EPOCH
return (delta.days * 86_400 + delta.seconds) * NS_PER_SEC + delta.microseconds * 1_000
@@ -142,10 +139,7 @@ def clip_text(text: str, max_chars: int) -> str:
def stringify_value(val: Any, max_chars: int = 32_000) -> str | None:
if val is None:
return None
- if isinstance(val, str):
- s = val
- else:
- s = json.dumps(val, ensure_ascii=False)
+ s = val if isinstance(val, str) else json.dumps(val, ensure_ascii=False)
if not s.strip():
return None
return clip_text(s, max_chars)
@@ -165,7 +159,11 @@ def extract_message_text(msg: dict[str, Any]) -> str:
ptype = part.get("type")
if ptype == "text":
content = part.get("content") or part.get("text")
- if isinstance(content, str) and content.strip() and content.strip() not in ("(no content)", "(no content"):
+ if (
+ isinstance(content, str)
+ and content.strip()
+ and content.strip() not in ("(no content)", "(no content")
+ ):
texts.append(content.strip())
elif ptype == "tool_call":
name = part.get("name") or "tool"
@@ -221,7 +219,12 @@ def cap_messages_json(raw: str | None, max_bytes: int) -> str | None:
assembled.append(
{
"role": "system",
- "parts": [{"type": "text", "content": f"[{omitted} intermediate messages omitted for size]"}],
+ "parts": [
+ {
+ "type": "text",
+ "content": f"[{omitted} intermediate messages omitted for size]",
+ }
+ ],
}
)
assembled.extend(tail)
@@ -252,7 +255,7 @@ def anchor_delta_ns(session_id: str, min_start: int, max_end: int, now_ns: int)
if thirty_days_ago <= max_end <= now_ns:
return 0
# Deterministic spread across [now - 6 days, now - 1 hour].
- h = int(hashlib.sha256(f"exgentic:anchor:{session_id}".encode("utf-8")).hexdigest()[:8], 16)
+ h = int(hashlib.sha256(f"exgentic:anchor:{session_id}".encode()).hexdigest()[:8], 16)
frac = h / 0xFFFFFFFF
span_window = 6 * NS_PER_DAY - NS_PER_HOUR
target_end = now_ns - NS_PER_HOUR - int(frac * span_window)
@@ -275,7 +278,9 @@ def convert_row_to_resource_spans(
benchmark = (row.get("benchmark") or "unknown").strip()
harness = (row.get("harness") or "unknown").strip()
- session_id = (row.get("session_id") or "").strip() or deterministic_hex(json.dumps(row, default=str)[:256], 16)
+ session_id = (row.get("session_id") or "").strip() or deterministic_hex(
+ json.dumps(row, default=str)[:256], 16
+ )
models = [m for m in (row.get("models") or []) if isinstance(m, str) and m]
collected_at = row.get("collected_at")
service_name = f"exgentic/{benchmark}"
@@ -286,7 +291,7 @@ def convert_row_to_resource_spans(
# Parse timestamps and sort spans chronologically while preserving original order on ties.
indexed_spans: list[tuple[int, int, int, dict[str, Any]]] = []
parsed_times: list[tuple[int | None, int | None]] = []
- for idx, s in enumerate(raw_spans):
+ for s in raw_spans:
st = parse_iso_ns(s.get("start_time"))
et = parse_iso_ns(s.get("end_time"))
parsed_times.append((st, et))
@@ -295,7 +300,7 @@ def convert_row_to_resource_spans(
base_fallback_ns = min(valid_starts) if valid_starts else (now_ns - 2 * NS_PER_HOUR)
cursor_ns = base_fallback_ns
- for idx, (s, (st, et)) in enumerate(zip(raw_spans, parsed_times)):
+ for idx, (s, (st, et)) in enumerate(zip(raw_spans, parsed_times, strict=True)):
start_ns = st if st is not None else cursor_ns
end_ns = et if et is not None else start_ns
if end_ns < start_ns:
@@ -405,8 +410,12 @@ def convert_row_to_resource_spans(
"gen_ai.response.model": resp_model,
"gen_ai.response.id": raw_attrs.get("gen_ai.response.id"),
"gen_ai.response.finish_reasons": raw_attrs.get("gen_ai.response.finish_reasons"),
- "gen_ai.input.messages": cap_messages_json(raw_attrs.get("gen_ai.input.messages"), max_message_bytes),
- "gen_ai.output.messages": cap_messages_json(raw_attrs.get("gen_ai.output.messages"), max_message_bytes),
+ "gen_ai.input.messages": cap_messages_json(
+ raw_attrs.get("gen_ai.input.messages"), max_message_bytes
+ ),
+ "gen_ai.output.messages": cap_messages_json(
+ raw_attrs.get("gen_ai.output.messages"), max_message_bytes
+ ),
"gen_ai.conversation.id": session_id,
"exgentic.benchmark": benchmark,
"exgentic.harness": harness,
@@ -585,7 +594,9 @@ def post_otlp_batch(
if not resource_spans:
return 0
- payload_bytes = json.dumps({"resourceSpans": resource_spans}, ensure_ascii=False).encode("utf-8")
+ payload_bytes = json.dumps({"resourceSpans": resource_spans}, ensure_ascii=False).encode(
+ "utf-8"
+ )
compressed = gzip.compress(payload_bytes, compresslevel=5)
headers = {
"Content-Type": "application/json",
@@ -609,7 +620,9 @@ def post_otlp_batch(
except (httpx.TransportError, httpx.TimeoutException) as exc:
last_exc = exc
if attempt == max_retries:
- raise RuntimeError(f"OTLP ingest failed after {max_retries} retries: {exc}") from exc
+ raise RuntimeError(
+ f"OTLP ingest failed after {max_retries} retries: {exc}"
+ ) from exc
print(
f" [retry {attempt}/{max_retries}] connection error: {exc} (sleeping {backoff:.1f}s)",
file=sys.stderr,
@@ -642,7 +655,9 @@ def download_shard(client: httpx.Client, shard: dict[str, Any], cache_dir: Path)
return target
-def select_shards_for_limit(files: list[dict[str, Any]], limit: int) -> list[tuple[dict[str, Any], int | None]]:
+def select_shards_for_limit(
+ files: list[dict[str, Any]], limit: int
+) -> list[tuple[dict[str, Any], int | None]]:
"""Return list of (shard_info, max_rows_from_shard).
When limit == 0, returns all shards with no per-shard cap.
@@ -708,7 +723,9 @@ class SpanBatcher:
self.total_spans_sent = 0
self.total_batches = 0
- def add(self, key: tuple[str, str], resource: dict[str, Any], spans: list[dict[str, Any]]) -> None:
+ def add(
+ self, key: tuple[str, str], resource: dict[str, Any], spans: list[dict[str, Any]]
+ ) -> None:
for span in spans:
span_bytes = len(json.dumps(span, ensure_ascii=False).encode("utf-8"))
if self.buffered_spans > 0 and (
@@ -734,23 +751,35 @@ class SpanBatcher:
def main() -> None:
- parser = argparse.ArgumentParser(description="Import Exgentic/agent-llm-traces into Overmind OTLP.")
- parser.add_argument("--endpoint", default=DEFAULT_ENDPOINT, help=f"OTLP HTTP traces URL (default: {DEFAULT_ENDPOINT})")
+ parser = argparse.ArgumentParser(
+ description="Import Exgentic/agent-llm-traces into Overmind OTLP."
+ )
+ parser.add_argument(
+ "--endpoint",
+ default=DEFAULT_ENDPOINT,
+ help=f"OTLP HTTP traces URL (default: {DEFAULT_ENDPOINT})",
+ )
parser.add_argument(
"--limit",
type=int,
default=0,
help="Maximum traces to import (0 = all 1,781 traces; >0 = stratified sample across shards)",
)
- parser.add_argument("--batch-size", type=int, default=80, help="Max spans per OTLP HTTP POST (default: 80)")
+ parser.add_argument(
+ "--batch-size", type=int, default=80, help="Max spans per OTLP HTTP POST (default: 80)"
+ )
parser.add_argument(
"--max-message-bytes",
type=int,
default=262_144,
help="Max UTF-8 bytes per span gen_ai.*.messages JSON attribute (default: 262144; 0 = unlimited)",
)
- parser.add_argument("--benchmark", default="", help="Optional benchmark filter (e.g. swebench, appworld)")
- parser.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE_DIR, help="Local parquet cache directory")
+ parser.add_argument(
+ "--benchmark", default="", help="Optional benchmark filter (e.g. swebench, appworld)"
+ )
+ parser.add_argument(
+ "--cache-dir", type=Path, default=DEFAULT_CACHE_DIR, help="Local parquet cache directory"
+ )
args = parser.parse_args()
t0 = time.monotonic()
@@ -767,7 +796,9 @@ def main() -> None:
else:
plan = select_shards_for_limit(files, args.limit)
- print(f"Selected {len(plan)} shard(s) for import (limit={'all' if args.limit <= 0 else args.limit})")
+ print(
+ f"Selected {len(plan)} shard(s) for import (limit={'all' if args.limit <= 0 else args.limit})"
+ )
batcher = SpanBatcher(otlp_client, args.endpoint, max_spans=max(1, args.batch_size))
traces_imported = 0
@@ -783,7 +814,10 @@ def main() -> None:
break
sz_mb = shard["size"] / (1024 * 1024)
- print(f"[{shard_pos}/{len(plan)}] Downloading/reading {shard['filename']} ({sz_mb:.2f} MB)...", flush=True)
+ print(
+ f"[{shard_pos}/{len(plan)}] Downloading/reading {shard['filename']} ({sz_mb:.2f} MB)...",
+ flush=True,
+ )
local_path = download_shard(hf_client, shard, args.cache_dir)
rows = pq.read_table(local_path).to_pylist()
@@ -826,7 +860,9 @@ def main() -> None:
model_counts[kv["value"]["stringValue"]] += 1
except Exception as exc:
failed_traces += 1
- print(f" [error] trace session={row.get('session_id')}: {exc}", file=sys.stderr)
+ print(
+ f" [error] trace session={row.get('session_id')}: {exc}", file=sys.stderr
+ )
batcher.flush()
print(
diff --git a/collector/scripts/send.py b/collector/scripts/send.py
index a6c074a9..bbf87b5f 100644
--- a/collector/scripts/send.py
+++ b/collector/scripts/send.py
@@ -7,8 +7,8 @@
# ///
"""Send sample agent traces (with events), metrics, and logs to the Rust collector.
- uv run packages/otel/examples/send.py
- uv run packages/otel/examples/send.py --traces 5 --url http://localhost:4318
+uv run packages/otel/examples/send.py
+uv run packages/otel/examples/send.py --traces 5 --url http://localhost:4318
"""
import argparse
@@ -37,7 +37,10 @@ def send_logs(url: str, service: str, records: list[dict]) -> None:
"resource": {
"attributes": [
{"key": "service.name", "value": {"stringValue": service}},
- {"key": "deployment.environment.name", "value": {"stringValue": "development"}},
+ {
+ "key": "deployment.environment.name",
+ "value": {"stringValue": "development"},
+ },
]
},
"scopeLogs": [
@@ -82,9 +85,7 @@ def main() -> None:
meter_provider = MeterProvider(
resource=resource,
metric_readers=[
- PeriodicExportingMetricReader(
- OTLPMetricExporter(endpoint=f"{args.url}/api/v1/metrics")
- )
+ PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=f"{args.url}/api/v1/metrics"))
],
)
metrics.set_meter_provider(meter_provider)
@@ -163,14 +164,22 @@ def main() -> None:
if failed:
tool.set_status(Status(StatusCode.ERROR, "search backend timeout"))
tool.set_attribute("error.type", "TimeoutError")
- tool.add_event("exception", {"exception.type": "TimeoutError", "exception.message": "search backend timeout"})
+ tool.add_event(
+ "exception",
+ {
+ "exception.type": "TimeoutError",
+ "exception.message": "search backend timeout",
+ },
+ )
log_records.append(
{
"timeUnixNano": now_ns,
"observedTimeUnixNano": now_ns,
"severityNumber": 17,
"severityText": "ERROR",
- "body": {"stringValue": f"order_lookup failed for order #{1000 + i}: timeout"},
+ "body": {
+ "stringValue": f"order_lookup failed for order #{1000 + i}: timeout"
+ },
"traceId": trace_id,
"spanId": tool_span_id,
"attributes": [
@@ -179,7 +188,9 @@ def main() -> None:
}
)
else:
- tool.set_attribute("gen_ai.tool.call.result", json.dumps({"status": "out_for_delivery"}))
+ tool.set_attribute(
+ "gen_ai.tool.call.result", json.dumps({"status": "out_for_delivery"})
+ )
log_records.append(
{
"timeUnixNano": now_ns,
@@ -190,7 +201,10 @@ def main() -> None:
"traceId": trace_id,
"spanId": root_span_id,
"attributes": [
- {"key": "gen_ai.conversation.id", "value": {"stringValue": f"conv-{i}"}}
+ {
+ "key": "gen_ai.conversation.id",
+ "value": {"stringValue": f"conv-{i}"},
+ }
],
}
)
diff --git a/frontend/src/routes/_auth/observability.$traceId.tsx b/frontend/src/routes/_auth/observability.$traceId.tsx
index d901c0f5..c23f3a0e 100644
--- a/frontend/src/routes/_auth/observability.$traceId.tsx
+++ b/frontend/src/routes/_auth/observability.$traceId.tsx
@@ -56,7 +56,6 @@ function TraceDetailPage() {
const traceData = {
isLoading,
projectId: selectedProject,
- receipt: traceQueryData?.receipt,
spans: spanList,
traceId: traceId ?? "",
traceStatus: traceQueryData?.traceStatus,
diff --git a/modal_shared/chat_checkpoint.py b/modal_shared/chat_checkpoint.py
index 10628584..c43b144d 100644
--- a/modal_shared/chat_checkpoint.py
+++ b/modal_shared/chat_checkpoint.py
@@ -26,7 +26,8 @@ def seal_checkpoint(directory: Path) -> dict:
json.loads((directory / config).read_text())
json.loads((directory / "tokenizer_config.json").read_text())
if not any(
- (directory / name).is_file() for name in ("tokenizer.json", "tokenizer.model", "vocab.json")
+ (directory / name).is_file()
+ for name in ("tokenizer.json", "tokenizer.model", "vocab.json", "tiktoken.model")
):
raise ValueError("Checkpoint has no tokenizer vocabulary")
prefix = "adapter_model" if adapter else "model"
diff --git a/modal_shared/images/serve.py b/modal_shared/images/serve.py
index e492a822..7023adbb 100644
--- a/modal_shared/images/serve.py
+++ b/modal_shared/images/serve.py
@@ -10,6 +10,7 @@ from modal_shared.stacks import (
SERVE_SGLANG_INKLING,
SERVE_SGLANG_KEV,
SERVE_SGLANG_LFM3,
+ SERVE_SGLANG_QWEN4,
SERVE_VLLM,
)
@@ -91,6 +92,13 @@ dedicated_sglang_inkling_image = attach_modelfam(
.entrypoint([])
.pip_install("runai-model-streamer>=0.15.7")
)
+# Digest of lmsysorg/sglang:qwen4. v0.5.22 has no qwen4_moe.
+dedicated_sglang_qwen4_image = attach_modelfam(
+ modal.Image.from_registry(
+ "lmsysorg/sglang@sha256:1a2931d9cb1e2815cc08b05b9c92a83a0e319ccf9519514dc31ccb2affc8165f",
+ setup_dockerfile_commands=["RUN ln -sf $(command -v python3) /usr/local/bin/python"],
+ ).entrypoint([])
+)
dedicated_sglang_lfm3_image = attach_modelfam(
modal.Image.from_registry(
"lmsysorg/sglang:dev-lfm3",
@@ -106,6 +114,7 @@ SERVE_IMAGES: dict[str, modal.Image] = {
SERVE_SGLANG_LFM3: dedicated_sglang_lfm3_image,
SERVE_SGLANG_KEV: dedicated_sglang_kev_image,
SERVE_SGLANG_INKLING: dedicated_sglang_inkling_image,
+ SERVE_SGLANG_QWEN4: dedicated_sglang_qwen4_image,
}
# The snapshot reader uses a version-specific pinned-buffer allocation site.
diff --git a/modal_shared/images/train.py b/modal_shared/images/train.py
index 7a868dc9..788ffd9a 100644
--- a/modal_shared/images/train.py
+++ b/modal_shared/images/train.py
@@ -13,6 +13,7 @@ from modal_shared.stacks import (
TRAIN_DECISION,
TRAIN_INKLING,
TRAIN_KEV,
+ TRAIN_QWEN4,
TRAIN_U2026_7,
TRAIN_U2026_8_18,
TRAIN_U2026_8_GPOS,
@@ -265,6 +266,48 @@ def _unsloth_inkling() -> modal.Image:
)
+_QWEN4_UNSLOTH = "56397f9d7b06177d035239ebed233a17646e5d42"
+_QWEN4_ZOO = "12361e94e592c794d5b90032cac55babc61deaa5"
+
+
+def _unsloth_qwen4() -> modal.Image:
+ # 2026.11.9 supplies the CUDA deps. Its own pin refuses transformers 5.26,
+ # which is the first release with qwen4_moe. The git overlay is that loader.
+ return (
+ _base_cuda.pip_install(
+ "torch==2.10.0",
+ index_url="https://download.pytorch.org/whl/cu128",
+ )
+ .pip_install(
+ "unsloth[cu128-torch2100]==2026.11.9",
+ "unsloth_zoo==2026.11.9",
+ "datasets>=3.0.0",
+ "huggingface_hub>=0.34.0",
+ "sentencepiece",
+ "protobuf",
+ "tiktoken",
+ )
+ .pip_install("transformers==5.26.0", "xgrammar")
+ .run_commands(
+ f"pip install --no-deps git+https://github.com/unslothai/unsloth.git@{_QWEN4_UNSLOTH}",
+ f"pip install --no-deps git+https://github.com/unslothai/unsloth-zoo.git@{_QWEN4_ZOO}",
+ )
+ )
+
+
+_qwen4 = _finish(
+ _clone_trl(_unsloth_qwen4()).run_commands(
+ _assert_versions("qwen4_56397f9-ok", torch_prefix="2.10", tf_min=(5, 26)),
+ 'python -c "from unsloth import FastModel"',
+ ),
+ {
+ **_SFT_ENV,
+ "TRL_SRC": "/opt/trl_src",
+ "UNSLOTH_IMAGE": TRAIN_QWEN4,
+ },
+)
+
+
_inkling = _finish(
_clone_trl(_unsloth_inkling()).run_commands(
_assert_versions("inkling_174067b-ok", torch_prefix="2.10", tf_min=(5, 24)),
@@ -405,4 +448,5 @@ TRAIN_IMAGES: dict[str, modal.Image] = {
TRAIN_U2026_10_7: _u2026_10_7,
TRAIN_U2026_11_9: _u2026_11_9,
TRAIN_INKLING: _inkling,
+ TRAIN_QWEN4: _qwen4,
}
diff --git a/modal_shared/modelfam/families.py b/modal_shared/modelfam/families.py
index 93bd0dee..5bca4619 100644
--- a/modal_shared/modelfam/families.py
+++ b/modal_shared/modelfam/families.py
@@ -6,9 +6,11 @@ from modal_shared.modelfam.spec import FamilySpec
from modal_shared.stacks import (
SERVE_SGLANG_INKLING,
SERVE_SGLANG_KEV,
+ SERVE_SGLANG_QWEN4,
TRAIN_DECISION,
TRAIN_INKLING,
TRAIN_KEV,
+ TRAIN_QWEN4,
TRAIN_U2026_8_GPOS,
TRAIN_U2026_8_TF510,
TRAIN_U2026_8_TF515,
@@ -318,6 +320,27 @@ QWEN_MM = FamilySpec(
string_content_as_parts=True,
)
+# Before the generic "qwen" pattern. qwen4 is not qwen3.5/3.6/3.8.
+QWEN4 = FamilySpec(
+ key="qwen4",
+ patterns=("qwen4",),
+ train_image=TRAIN_QWEN4,
+ serve_image=SERVE_SGLANG_QWEN4,
+ trust_remote_code=True,
+ tool_call_parser="qwen4",
+ reasoning_parser="qwen4",
+ pretok_headers=(r"<\|im_start\|>(\w+)\n",),
+ natively_multimodal=True,
+ multimodal_id_tokens=("qwen4",),
+ hooks_module="families.qwen4",
+ string_content_as_parts=True,
+ sglang_args_module="modal_shared.serving.qwen4",
+ sglang_process_env="modal_shared.serving.qwen4",
+ lora_target_modules="o_proj",
+ train_gpu="H200",
+ notes="Hybrid GDN and sparse attention. Full-attention LoRA only. SGLang qwen4 image.",
+)
+
QWEN = FamilySpec(
key="qwen",
patterns=("qwen",),
diff --git a/modal_shared/modelfam/registry.py b/modal_shared/modelfam/registry.py
index 3ae6d0ee..575ad457 100644
--- a/modal_shared/modelfam/registry.py
+++ b/modal_shared/modelfam/registry.py
@@ -27,6 +27,7 @@ from modal_shared.modelfam.families import (
PHI4,
QWEN,
QWEN3_CODER,
+ QWEN4,
QWEN35,
QWEN38,
QWEN_MM,
@@ -56,6 +57,7 @@ _FAMILIES: tuple[FamilySpec, ...] = (
QWEN35,
QWEN3_CODER,
QWEN_MM,
+ QWEN4,
QWEN,
OLMO,
GLM,
@@ -97,6 +99,8 @@ def serve_image_key(*blobs: str) -> str:
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.train_gpu:
+ return spec.train_gpu, spec.max_train_gpus or gpu_count
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
diff --git a/modal_shared/modelfam/spec.py b/modal_shared/modelfam/spec.py
index d7e6d91a..78366ddc 100644
--- a/modal_shared/modelfam/spec.py
+++ b/modal_shared/modelfam/spec.py
@@ -65,6 +65,8 @@ class FamilySpec:
# 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"
+ # Set when the checkpoint does not fit the params-based GPU table.
+ train_gpu: str | None = None
# 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.
@@ -80,6 +82,8 @@ class FamilySpec:
sglang_adapter_targets: str = ""
# Module with process_env(), imported for that engine only.
sglang_process_env: str = ""
+ # Module exposing build_args() with the same signature as serving.sglang.build_sglang_args.
+ sglang_args_module: str = ""
vllm_process_env: str = ""
# Mistral tokenizers reject chat_template_kwargs. Their instruct templates
# do not open a think block, so the request must not carry enable_thinking.
diff --git a/modal_shared/serving/qwen4.py b/modal_shared/serving/qwen4.py
new file mode 100644
index 00000000..093e278a
--- /dev/null
+++ b/modal_shared/serving/qwen4.py
@@ -0,0 +1,101 @@
+"""SGLang launch for Qwen4 MoE. The shared builder's fa3 and EAGLE flags do not load it."""
+
+from __future__ import annotations
+
+import os
+import secrets
+
+# This image 403s /load_lora_adapter unless the server and the caller share a key.
+# Generated per process so it never sits in the repo or the logged argv.
+_ADMIN_API_KEY = secrets.token_urlsafe(24)
+
+
+def build_args(
+ *,
+ model_path: str,
+ served_name: str,
+ port: int,
+ draft_model: str = "",
+ draft_tokens: int = 0,
+ mtp: tuple[int, int, int] | None = None,
+ tool_call_parser: str = "",
+ reasoning_parser: str = "",
+ gpu_type: str = "",
+ model: str = "",
+ enable_lora: bool = False,
+ max_lora_rank: int = 16,
+ lora_target_modules: str = "",
+ mem_fraction: str = "0.90",
+ max_model_len: int | None = None,
+ max_running_requests: int | None = None,
+) -> list[str]:
+ del draft_model, draft_tokens, gpu_type, model, max_running_requests
+ cmd = [
+ "python3",
+ "-m",
+ "sglang.launch_server",
+ "--model-path",
+ model_path,
+ "--served-model-name",
+ served_name,
+ "--tp-size",
+ "1",
+ "--mem-fraction-static",
+ mem_fraction,
+ "--dtype",
+ "bfloat16",
+ "--trust-remote-code",
+ "--qsa-indexer-dtype",
+ "fp8_e4m3",
+ "--linear-attn-prefill-backend",
+ "flashinfer",
+ "--linear-attn-decode-backend",
+ "flashinfer",
+ # NEXTN verify rejects a bfloat16 mamba state. Leave the dtype at the default.
+ "--host",
+ "0.0.0.0",
+ "--port",
+ str(port),
+ ]
+ if max_model_len:
+ cmd += ["--context-length", str(max_model_len)]
+ if mtp:
+ steps, topk, tokens = mtp
+ cmd += [
+ "--speculative-algorithm",
+ "NEXTN",
+ "--speculative-num-steps",
+ str(steps),
+ "--speculative-eagle-topk",
+ str(topk),
+ "--speculative-num-draft-tokens",
+ str(tokens),
+ ]
+ if enable_lora:
+ modules = [
+ part.strip() for part in (lora_target_modules or "all").split(",") if part.strip()
+ ]
+ cmd += [
+ "--enable-lora",
+ "--max-lora-rank",
+ str(max_lora_rank),
+ "--lora-target-modules",
+ *modules,
+ ]
+ cmd += [
+ "--tool-call-parser",
+ tool_call_parser or "qwen4",
+ "--reasoning-parser",
+ reasoning_parser or "qwen4",
+ ]
+ return cmd
+
+
+def process_env() -> dict[str, str]:
+ env = os.environ.copy()
+ env["SGLANG_ADMIN_API_KEY"] = _ADMIN_API_KEY
+ return env
+
+
+def admin_headers() -> dict[str, str]:
+ return {"Authorization": f"Bearer {_ADMIN_API_KEY}"}
diff --git a/modal_shared/serving/speculative.py b/modal_shared/serving/speculative.py
index bafe352b..3c0e2bf6 100644
--- a/modal_shared/serving/speculative.py
+++ b/modal_shared/serving/speculative.py
@@ -17,6 +17,8 @@ _MTP: dict[str, tuple[int, int, int]] = {
"unsloth/Qwen3.5-9B": (3, 1, 4),
"Qwen/Qwen3.6-27B": (3, 1, 4),
"unsloth/Qwen3.6-27B": (3, 1, 4),
+ # In-checkpoint MTP. The qwen4 SGLang image launches this as NEXTN, not EAGLE.
+ "Qwen/Qwen4-35B-A3B": (3, 1, 4),
}
# (draft repo, num_speculative_tokens). DFlash2 uses the same method
diff --git a/modal_shared/stacks.py b/modal_shared/stacks.py
index b1e4a33d..fc78172e 100644
--- a/modal_shared/stacks.py
+++ b/modal_shared/stacks.py
@@ -30,6 +30,8 @@ TRAIN_U2026_10_7 = "u2026_10_7"
TRAIN_U2026_11_9 = "u2026_11_9"
# Inkling2Loop landed in transformers 5.24. The 2026.11.9 image caps below 5.15.
TRAIN_INKLING = "inkling_174067b"
+# Qwen4 MoE needs transformers 5.26. Every released Unsloth wheel caps below that.
+TRAIN_QWEN4 = "qwen4_56397f9"
TRAIN_DECISION = "u2026_10_3_decision"
# Kev's trainer is not Unsloth and refuses torch 2.10. Own image, own key.
TRAIN_KEV = "kev_2026_11"
@@ -48,6 +50,7 @@ TRAIN_STACKS: tuple[str, ...] = (
TRAIN_U2026_10_7,
TRAIN_U2026_11_9,
TRAIN_INKLING,
+ TRAIN_QWEN4,
TRAIN_DECISION,
TRAIN_KEV,
)
@@ -84,6 +87,7 @@ TRAIN_STACK_PINS: dict[str, str] = {
TRAIN_U2026_10_7: "unsloth[cu128-torch2100]==2026.10.7 / unsloth_zoo==2026.10.7 / torch==2.10.0 / transformers==5.17.0 / trl v1.10.0",
TRAIN_U2026_11_9: "unsloth[cu128-torch2100]==2026.11.9 / unsloth_zoo==2026.11.9 / torch==2.10.0 / transformers>=5.10.2,<5.15 / trl v1.10.0",
TRAIN_INKLING: "unsloth@174067b17e794edd9f39bec0f1b182d9790fcbec / unsloth_zoo==2026.11.9 / torch==2.10.0 / transformers==5.24.1 / compressed-tensors>=0.15.0 / trl v1.10.0",
+ TRAIN_QWEN4: "unsloth@56397f9d7b06177d035239ebed233a17646e5d42 / unsloth_zoo@12361e94e592c794d5b90032cac55babc61deaa5 / torch==2.10.0 / transformers==5.26.0 / trl v1.10.0",
}
@@ -111,6 +115,8 @@ SERVE_SGLANG_LFM3 = "sglang_lfm3"
SERVE_SGLANG_KEV = "sglang_kev"
# Inkling2Loop is not in v0.5.22. The vendor image is the one that loads it.
SERVE_SGLANG_INKLING = "sglang_inkling"
+# Qwen4 MoE is not in v0.5.22. This digest is lmsysorg/sglang:qwen4 (linux/amd64).
+SERVE_SGLANG_QWEN4 = "sglang_qwen4"
SERVE_STACKS: tuple[str, ...] = (
SERVE_VLLM,
@@ -118,6 +124,7 @@ SERVE_STACKS: tuple[str, ...] = (
SERVE_SGLANG_LFM3,
SERVE_SGLANG_KEV,
SERVE_SGLANG_INKLING,
+ SERVE_SGLANG_QWEN4,
)
SERVE_STACK_PINS: dict[str, str] = {
@@ -126,6 +133,7 @@ SERVE_STACK_PINS: dict[str, str] = {
SERVE_SGLANG_LFM3: "lmsysorg/sglang:dev-lfm3",
SERVE_SGLANG_KEV: "lmsysorg/sglang:v0.5.23",
SERVE_SGLANG_INKLING: "lmsysorg/sglang:inkling-2-mini",
+ SERVE_SGLANG_QWEN4: "lmsysorg/sglang@sha256:1a2931d9cb1e2815cc08b05b9c92a83a0e319ccf9519514dc31ccb2affc8165f",
}
# (gpu_type, serve_image) pairs we deploy. Cls name is ``{gpu}_{serve_image}``
@@ -216,6 +224,7 @@ TRAIN_CANARIES: tuple[TrainCanary, ...] = (
TrainCanary(TRAIN_U2026_8_TF510, "nvidia/NVIDIA-Nemotron-3.5-Bolt-E4B-BF16", "Lora", 8.0, "pr"),
TrainCanary(TRAIN_U2026_11_9, "unsloth/gemma-4-E2B-it", "Lora", 5.1, "pr"),
TrainCanary(TRAIN_INKLING, "unsloth/Inkling-2-Mini", "Lora", 26.4, "nightly"),
+ TrainCanary(TRAIN_QWEN4, "Qwen/Qwen4-35B-A3B", "Lora", 35.0, "nightly"),
TrainCanary(TRAIN_U2026_7, "Qwen/Qwen3-0.6B", "Lora", 0.6, "nightly"),
TrainCanary(TRAIN_U2026_8_TF515, "unsloth/Muse-Glimmer-30B", "Lora", 30.0, "nightly"),
TrainCanary(
diff --git a/overbae/modal/modal_sft_worker.py b/overbae/modal/modal_sft_worker.py
index fde90408..8f557847 100644
--- a/overbae/modal/modal_sft_worker.py
+++ b/overbae/modal/modal_sft_worker.py
@@ -213,6 +213,14 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
sft_vol.commit()
if proc.returncode != 0:
raise RuntimeError(f"train.py exited with code {proc.returncode}")
+ # A custom tokenizer keeps its vocabulary beside tokenizer.json.
+ # Publication rejects a checkpoint that does not contain one.
+ staged_tokenizer = run_dir / "tokenizer"
+ if staged_tokenizer.is_dir():
+ for path in staged_tokenizer.iterdir():
+ dest = candidate_dir / path.name
+ if path.is_file() and not dest.exists():
+ shutil.copy2(path, dest)
if native:
report = json.loads((run_dir / "decision-reload-verification.json").read_text())
result["artifact_identity"] = seal_artifact(candidate_dir, report)["identity"]
diff --git a/overbae/modal/modal_vllm_worker.py b/overbae/modal/modal_vllm_worker.py
index 07df6f53..38730641 100644
--- a/overbae/modal/modal_vllm_worker.py
+++ b/overbae/modal/modal_vllm_worker.py
@@ -129,6 +129,7 @@ from modal_shared.images.serve import ( # noqa: E402
dedicated_sglang_inkling_image,
dedicated_sglang_kev_image,
dedicated_sglang_lfm3_image,
+ dedicated_sglang_qwen4_image,
dedicated_vllm_image,
)
from modal_shared.stacks import GPU_TIER, WORKER_CLS, WORKER_MEMORY_MIB # noqa: E402
@@ -465,10 +466,21 @@ class _BaseVLLMWorker:
full_path = str(adapter_dir)
self._kev_checkpoint = full_path
elif engine.startswith("sglang"):
+ from modal_shared.modelfam import resolve
from modal_shared.serving.merge import write_folded_checkpoint
+ from modal_shared.serving.sglang import normalize_sglang_adapter
+ # Unmatched LoRA leaves make the fold raise, and this server cannot load them.
+ spec = resolve(base_model or folded_repo)
+ staged_adapter = Path("/tmp/overmind-fold-adapter")
+ if staged_adapter.exists():
+ shutil.rmtree(staged_adapter)
+ shutil.copytree(adapter_dir, staged_adapter)
+ keep = spec.sglang_adapter_targets or spec.lora_target_modules or ""
+ if keep:
+ normalize_sglang_adapter(staged_adapter, keep_targets=keep)
folded = Path("/tmp/overmind-folded")
- write_folded_checkpoint(base_path, adapter_dir, folded)
+ write_folded_checkpoint(base_path, staged_adapter, folded)
full_path = str(folded)
print(f"[serve] folded {adapter_dir} into {folded}")
else:
@@ -563,7 +575,12 @@ class _BaseVLLMWorker:
# gpt-oss has no thinking-off switch. The parser keeps analysis out of content.
lora_targets = spec.sglang_serve_lora_targets or spec.lora_target_modules or ""
- cmd = build_sglang_args(
+ builder = build_sglang_args
+ if spec.sglang_args_module:
+ import importlib
+
+ builder = importlib.import_module(spec.sglang_args_module).build_args
+ cmd = builder(
model_path=full_path,
served_name=self.model_name,
port=VLLM_PORT,
@@ -725,6 +742,7 @@ class _BaseVLLMWorker:
staged.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source, staged)
engine = str(getattr(self, "engine", "vllm"))
+ headers: dict = {}
if engine.startswith("sglang"):
from modal_shared.modelfam import resolve
from modal_shared.serving.sglang import normalize_sglang_adapter
@@ -734,11 +752,17 @@ class _BaseVLLMWorker:
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)}
+ if spec.sglang_process_env:
+ import importlib
+
+ headers = getattr(
+ importlib.import_module(spec.sglang_process_env), "admin_headers", dict
+ )()
else:
load_url = f"http://localhost:{VLLM_PORT}/v1/load_lora_adapter"
payload = lora_load_request(name, str(staged))
async with httpx.AsyncClient(timeout=300) as client:
- resp = await client.post(load_url, json=payload)
+ resp = await client.post(load_url, json=payload, headers=headers)
text = resp.text or ""
# vLLM answers 400 "has already been loaded" when another container in this pool
# got there first, which is success as far as the caller is concerned.
@@ -1488,6 +1512,21 @@ def register_dedicated_classes(target_app, owner) -> None:
image_override=dedicated_sglang_inkling_image,
)
owner[inkling_name] = inkling_slot[inkling_name]
+ qwen4_name = f"{token}_sglang_qwen4_dedicated"
+ qwen4_slot = {}
+ _register_worker(
+ qwen4_name,
+ gpu_type,
+ "vllm",
+ target_app=target_app,
+ pin_resources=True,
+ snapshot=False,
+ engine="sglang_qwen4",
+ max_containers=8,
+ owner=qwen4_slot,
+ image_override=dedicated_sglang_qwen4_image,
+ )
+ owner[qwen4_name] = qwen4_slot[qwen4_name]
kev_name = f"{token}_sglang_kev_dedicated"
_register_kev_dedicated(kev_name, gpu_type, target_app, owner)
diff --git a/overbae/modal/models.json b/overbae/modal/models.json
index d3be8201..a19af8e1 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. 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.",
+ "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, Qwen4 1048576, 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": {
@@ -1911,6 +1911,75 @@
"openai/gpt-oss-20b"
]
},
+{
+ "id": "Qwen/Qwen4-35B-A3B",
+ "openrouter_id": null,
+ "hf_model_id": "Qwen/Qwen4-35B-A3B",
+ "display": "Qwen 4 35B MoE",
+ "tier": "large",
+ "params": "35B MoE (3B active)",
+ "total_params_b": 35.0,
+ "moe": true,
+ "context_length": 1048576,
+ "supports_tool_calling": true,
+ "type": "chat",
+ "hidden_size": 2048,
+ "fp8_supported": false,
+ "inference": {
+ "dedicated_engine": "sglang_qwen4",
+ "serverless_engine": "sglang_qwen4",
+ "gpu_type": "H200",
+ "lora_supported": true,
+ "max_model_len": 8192,
+ "min_vram_gb": 141
+ },
+ "finetuning": {
+ "context_length": 1048576,
+ "max_batch_size": 1,
+ "min_batch_size": 1,
+ "training_type": {
+ "full": {
+ "enabled": false,
+ "context_length": 1048576,
+ "validated_context_length": false
+ },
+ "lora": {
+ "enabled": true,
+ "context_length": 65536,
+ "validated_context_length": true
+ }
+ },
+ "real_max_context_length": 65536
+ },
+ "num_attn_layers": 10,
+ "num_kv_heads": 2,
+ "head_dim": 256,
+ "backend": "modal",
+ "disabled": false,
+ "disabled_reason": null,
+ "group": "Qwen 4",
+ "pricing": {
+ "train_from_usd": 1.52,
+ "run_from_usd_per_1m_output": 8.0
+ },
+ "marketing": {
+ "pitch": "Qwen 4 MoE: 35B total, 3B active, 1,048,576-token window.",
+ "description": "Qwen4-35B-A3B is a 256-expert mixture with 10 full-attention layers and a native 1,048,576-token window. Chat, tools, and vision. The BF16 checkpoint is about 106 GiB.",
+ "overview": "40 layers, hidden size 2048, 2 KV heads, head dim 256. LoRA trains the output projection. The vision tower, routed experts, and n-gram table stay frozen. A 65,536-token LoRA step fits on one H200. Serving starts at H200.",
+ "good_for": [
+ "Long-context Qwen 4 MoE serving",
+ "Attention LoRA on the Qwen 4 checkpoint",
+ "Tool-calling agents"
+ ]
+ },
+ "use_cases": [
+ "tool-calling",
+ "coding"
+ ],
+ "benchmark_hf_model_ids": [
+ "Qwen/Qwen4-35B-A3B"
+ ]
+ },
{
"id": "Qwen/Qwen3.6-35B-A3B",
"openrouter_id": null,
diff --git a/overbae/modal/register_model.py b/overbae/modal/register_model.py
index ce6c4af5..948eec46 100644
--- a/overbae/modal/register_model.py
+++ b/overbae/modal/register_model.py
@@ -794,17 +794,39 @@ def _ensure_draft(base_model: str) -> None:
raise RuntimeError(f"DFlash draft {repo} is incomplete after download ({dest})")
+def _download_base_snapshot(repo_id: str, dest: Path, *, ignore_patterns: list[str]) -> None:
+ """Xet writes to a Volume stay near 50 MB/s. Stage on container disk, then copy."""
+ from huggingface_hub import snapshot_download # noqa: PLC0415
+
+ stage = Path("/tmp/base-snapshot")
+ if stage.exists():
+ shutil.rmtree(stage)
+ stage.mkdir(parents=True)
+ snapshot_download(
+ repo_id=repo_id,
+ local_dir=str(stage),
+ ignore_patterns=ignore_patterns,
+ token=os.environ.get("HF_TOKEN") or None,
+ max_workers=16,
+ )
+ if dest.exists():
+ shutil.rmtree(dest)
+ shutil.copytree(stage, dest)
+ shutil.rmtree(stage)
+
+
@app.function(
image=download_image,
timeout=4 * 60 * 60,
scaledown_window=2,
+ ephemeral_disk=524288,
volumes={WEIGHTS_MOUNT: weights_vol},
secrets=[inference_secret],
- cpu=8.0, # HF_XET_HIGH_PERFORMANCE saturates several cores; default fraction throttles it
+ cpu=16.0,
max_containers=1, # global mutex: never let two callers write one base dir
)
@modal.concurrent(max_inputs=1)
-@container_meter.metered(lambda base_model, **_: f"base_model:{base_model}", cpu=8.0)
+@container_meter.metered(lambda base_model, **_: f"base_model:{base_model}", cpu=16.0)
def fetch_base_model(*, base_model: str) -> dict:
"""The single choke point for base downloads: ``max_containers=1`` plus ``max_inputs=1`` make
it a global mutex, so concurrent callers cannot corrupt a shared
@@ -815,7 +837,7 @@ def fetch_base_model(*, base_model: str) -> dict:
serialize here; the second sees a complete snapshot. The deploy path calls the same
Function, so a cold base is still correct.
"""
- from huggingface_hub import hf_hub_download, snapshot_download # noqa: PLC0415
+ from huggingface_hub import hf_hub_download # noqa: PLC0415
weights_vol.reload()
base_dir = _base_model_dir(base_model)
@@ -825,14 +847,11 @@ def fetch_base_model(*, base_model: str) -> dict:
print(f"[base] {base_model} already cached at {base_dir}")
else:
print(f"[base] Downloading {base_model} → {base_dir}")
- base_dir.mkdir(parents=True, exist_ok=True)
kev = BASES.get(base_model)
- snapshot_download(
- repo_id=base_model,
- local_dir=str(base_dir),
+ _download_base_snapshot(
+ base_model,
+ base_dir,
ignore_patterns=["*.bin", "original/*", *(() if kev else ("*.pt",))],
- token=os.environ.get("HF_TOKEN") or None,
- max_workers=16,
)
if kev and not (base_dir / "head.pt").is_file():
raise RuntimeError(f"Kev snapshot {base_model} is missing head.pt")
diff --git a/overbae/modal/serving_benchmarks.json b/overbae/modal/serving_benchmarks.json
index 57b3b54f..0caa2e66 100644
--- a/overbae/modal/serving_benchmarks.json
+++ b/overbae/modal/serving_benchmarks.json
@@ -2196,6 +2196,16 @@
}
}
},
+ "Qwen/Qwen4-35B-A3B": {
+ "lora_bf16": {
+ "H200": {
+ "ttft_ms_p50": 69.0,
+ "tokens_per_second_p50": 401.5,
+ "measured_at": "2026-12-04T14:32:57Z",
+ "runtime": "sglang-qwen4"
+ }
+ }
+ },
"Qwen/Qwen3-Coder-30B-A3B-Instruct": {
"lora_bf16": {
"B300": {
diff --git a/overbae/services/sft_assets/engine_unsloth.py b/overbae/services/sft_assets/engine_unsloth.py
index 67edde38..6bf5f298 100644
--- a/overbae/services/sft_assets/engine_unsloth.py
+++ b/overbae/services/sft_assets/engine_unsloth.py
@@ -444,22 +444,27 @@ def main() -> None:
f"{_spec.key}: forcing lora_dropout={_lora_dropout} (was {LORA_DROPOUT})",
flush=True,
)
- model = _fast_cls.get_peft_model(
- model,
- r=LORA_R,
- lora_alpha=LORA_ALPHA,
- lora_dropout=_lora_dropout,
- target_modules=LORA_TARGET_MODULES,
- bias="none",
- use_gradient_checkpointing=_gc,
- random_state=SEED,
- )
+ _peft_kwargs = {
+ "r": LORA_R,
+ "lora_alpha": LORA_ALPHA,
+ "lora_dropout": _lora_dropout,
+ "target_modules": LORA_TARGET_MODULES,
+ "bias": "none",
+ "use_gradient_checkpointing": _gc,
+ "random_state": SEED,
+ }
+ _peft_kwargs.update(_hooks.peft_kwargs())
+ model = _fast_cls.get_peft_model(model, **_peft_kwargs)
_hooks.post_load(model, tokenizer, use_lora=USE_LORA)
_install_qwen3_causal_mask(model)
if Path("preparation.json").exists():
emit_stage("verifying_training_tokenizer")
prepared = json.loads(Path("preparation.json").read_text())
- prepared_tokenizer = AutoTokenizer.from_pretrained("tokenizer", local_files_only=True)
+ prepared_tokenizer = AutoTokenizer.from_pretrained(
+ "tokenizer",
+ local_files_only=True,
+ trust_remote_code=_spec.trust_remote_code,
+ )
vocab = prepared_tokenizer.get_vocab()
loaded_vocab = _inner_tok.get_vocab()
fingerprint = hashlib.sha256(json.dumps(vocab, sort_keys=True).encode()).hexdigest()
diff --git a/overbae/services/sft_assets/families/__init__.py b/overbae/services/sft_assets/families/__init__.py
index 2df388c3..eb79d727 100644
--- a/overbae/services/sft_assets/families/__init__.py
+++ b/overbae/services/sft_assets/families/__init__.py
@@ -26,6 +26,8 @@ class TrainerHooks(Protocol):
def peft_lora_dropout(self, default: float, *, model_id: str) -> float: ...
+ def peft_kwargs(self) -> dict[str, Any]: ...
+
def normalize_messages(
self, messages: list[dict], tools: list[dict] | None
) -> tuple[list[dict], list[dict] | None]: ...
@@ -56,6 +58,9 @@ class DefaultHooks:
def peft_lora_dropout(self, default: float, *, model_id: str) -> float:
return default
+ def peft_kwargs(self) -> dict[str, Any]:
+ return {}
+
def normalize_messages(
self, messages: list[dict], tools: list[dict] | None
) -> tuple[list[dict], list[dict] | None]:
diff --git a/overbae/services/sft_assets/families/qwen4.py b/overbae/services/sft_assets/families/qwen4.py
new file mode 100644
index 00000000..fcbaf17e
--- /dev/null
+++ b/overbae/services/sft_assets/families/qwen4.py
@@ -0,0 +1,61 @@
+"""Qwen4 MoE. Attention LoRA only; vision, experts, and the n-gram table stay frozen."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from families import DefaultHooks
+
+_COMPAT = Path("tokenizer-compat") / "chat_template.jinja"
+
+
+class Qwen4Hooks(DefaultHooks):
+ def env_overrides(self, *, use_lora: bool) -> dict[str, str]:
+ return {"UNSLOTH_ENABLE_FLEX_ATTENTION": "0"}
+
+ def fast_model_cls(self, fast_language_model: Any, fast_model: Any | None) -> Any:
+ if fast_model is None:
+ raise RuntimeError("Qwen4 training requires Unsloth FastModel")
+ return fast_model
+
+ def peft_lora_dropout(self, default: float, *, model_id: str) -> float:
+ return 0.0
+
+ def post_load(self, model: Any, tokenizer: Any, *, use_lora: bool) -> None:
+ # The reference tokenizer ships no jinja. The compat template is the one
+ # with {% generation %} markers, so pretok can mask the assistant span.
+ del model, use_lora
+ targets = [tokenizer]
+ inner = getattr(tokenizer, "tokenizer", None)
+ if inner is not None and inner is not tokenizer:
+ targets.append(inner)
+ if any(getattr(tok, "chat_template", None) for tok in targets):
+ return
+ root = next(
+ (
+ Path(name)
+ for tok in targets
+ if (name := getattr(tok, "name_or_path", "") or "")
+ and (Path(name) / _COMPAT).is_file()
+ ),
+ None,
+ )
+ if root is None:
+ raise RuntimeError("Qwen4 tokenizer-compat/chat_template.jinja is missing")
+ text = (root / _COMPAT).read_text(encoding="utf-8")
+ for tok in targets:
+ tok.chat_template = text
+
+ def peft_kwargs(self) -> dict[str, Any]:
+ # SGLang's Qwen4 module list is qkv_proj and o_proj. Split q/k/v do not load.
+ return {
+ "target_modules": ["o_proj"],
+ "finetune_vision_layers": False,
+ "finetune_language_layers": True,
+ "finetune_attention_modules": True,
+ "finetune_mlp_modules": False,
+ }
+
+
+hooks = Qwen4Hooks()
diff --git a/tests/journeys/browser.py b/tests/journeys/browser.py
index e84cd2f1..efa63e3e 100644
--- a/tests/journeys/browser.py
+++ b/tests/journeys/browser.py
@@ -7,6 +7,8 @@ import os
import shutil
import subprocess
import threading
+import urllib.parse
+import urllib.request
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
@@ -49,11 +51,83 @@ def build_console(shared: Path) -> Path:
class _SinglePageApp(SimpleHTTPRequestHandler):
+ api_url = ""
+
def send_head(self):
if not Path(self.translate_path(self.path)).exists():
self.path = "/index.html"
return super().send_head()
+ def do_POST(self):
+ # The built console calls the collector on this origin. Journeys have no
+ # collector, and an unimplemented POST is 501, which fails the page.
+ length = int(self.headers.get("Content-Length") or 0)
+ raw = self.rfile.read(length) if length else b""
+ path = self.path.split("?", 1)[0]
+ if path.rsplit("/", 1)[-1] == "ListTraces":
+ self._json(self._list_traces(raw))
+ return
+ if path.startswith("/api.v1."):
+ self._json({})
+ return
+ self.send_error(501, "Unsupported method ('POST')")
+
+ def _list_traces(self, raw: bytes) -> dict:
+ try:
+ incoming = json.loads(raw) if raw else {}
+ except json.JSONDecodeError:
+ incoming = {}
+ page_size = int(incoming.get("pageSize") or 25)
+ token = str(incoming.get("pageToken") or "")
+ page = int(token) // page_size + 1 if token.isdigit() else 1
+ project = self.headers.get("X-Project-Id", "")
+ query = urllib.parse.urlencode(
+ {
+ "all_spans": "true" if incoming.get("allSpans") else "false",
+ "page": page,
+ "page_size": page_size,
+ "project": project,
+ "search": incoming.get("nameContains") or "",
+ }
+ )
+ url = f"{self.api_url.rstrip('/')}/api/traces/?{query}"
+ headers = {"Accept": "application/json"}
+ if auth := self.headers.get("Authorization"):
+ headers["Authorization"] = auth
+ with urllib.request.urlopen(
+ urllib.request.Request(url, headers=headers), timeout=30
+ ) as resp:
+ payload = json.loads(resp.read().decode())
+ rows = []
+ for item in payload.get("results") or []:
+ rows.append(
+ {
+ "span": {
+ "durationNs": str(item.get("duration_ns") or 0),
+ "name": item.get("name") or "",
+ "parentSpanId": item.get("parent_span_id") or "",
+ "serviceName": item.get("service_name") or "",
+ "spanId": item.get("span_id") or "",
+ "startTimeNs": str(item.get("start_time_ns") or 0),
+ "statusCode": item.get("status_code") or 0,
+ "traceId": item.get("trace_id") or "",
+ }
+ }
+ )
+ return {
+ "nextPageToken": "",
+ "rows": rows,
+ "totalCount": str(payload.get("count") or len(rows)),
+ }
+
+ def _json(self, body: dict) -> None:
+ encoded = json.dumps(body).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(encoded)))
+ self.end_headers()
+ self.wfile.write(encoded)
+
def log_message(self, *_args):
pass
@@ -67,6 +141,7 @@ def serve_console(built: Path, into: Path, api_url: str) -> Iterator[str]:
text = path.read_text()
if API_PLACEHOLDER in text:
path.write_text(text.replace(API_PLACEHOLDER, api_url))
+ _SinglePageApp.api_url = api_url
server = ThreadingHTTPServer(
("127.0.0.1", 0), functools.partial(_SinglePageApp, directory=str(dist))
)
diff --git a/tests/journeys/test_data.py b/tests/journeys/test_data.py
index 34a1c216..0a67348b 100644
--- a/tests/journeys/test_data.py
+++ b/tests/journeys/test_data.py
@@ -344,7 +344,9 @@ def land_selected_traces_as_rows(workshop, fake_llm, worker):
def open_traces_selected_in_the_console(console, workshop, project, live_api, worker):
console.goto(f"/observability?projectId={project}")
- console.click("Traces")
+ console._browser.call(
+ lambda: console._page.get_by_role("tab", name="Traces", exact=True).click()
+ )
console.sees("handle_ticket")
console._browser.call(
lambda: console._page.get_by_role("checkbox", name="Select row", exact=True).first.click()
diff --git a/tests/journeys/test_observe.py b/tests/journeys/test_observe.py
index b93146db..2b8ee826 100644
--- a/tests/journeys/test_observe.py
+++ b/tests/journeys/test_observe.py
@@ -61,9 +61,13 @@ def test_observe(
for truth in sample_agent.truth["capabilities"].values():
console.sees(truth["name"])
console.goto(f"/observability?projectId={project}")
- console.click("Signals")
+ console._browser.call(
+ lambda: console._page.get_by_role("tab", name="Signals", exact=True).click()
+ )
console.sees("Signal checks")
- console.click("Traces")
+ console._browser.call(
+ lambda: console._page.get_by_role("tab", name="Traces", exact=True).click()
+ )
console.sees("handle_ticket")
score_once_per_evidence(mcp, rest, project, key, live_api, fake_llm, worker)
diff --git a/tests/test_chat_checkpoint.py b/tests/test_chat_checkpoint.py
index aa0e99a3..3491f20b 100644
--- a/tests/test_chat_checkpoint.py
+++ b/tests/test_chat_checkpoint.py
@@ -27,3 +27,12 @@ def test_checkpoint_publication_requires_all_shards_and_tokenizer(tmp_path, adap
(tmp_path / "second.safetensors").write_bytes(b"truncated")
with pytest.raises(ValueError, match="changed"):
read_checkpoint(tmp_path)
+
+
+def test_tiktoken_model_counts_as_the_tokenizer_vocabulary(tmp_path):
+ (tmp_path / "adapter_config.json").write_text("{}")
+ (tmp_path / "tokenizer_config.json").write_text("{}")
+ (tmp_path / "tiktoken.model").write_bytes(b"vocab")
+ (tmp_path / "adapter_model.safetensors").write_bytes(b"weights")
+ manifest = seal_checkpoint(tmp_path)
+ assert "tiktoken.model" in manifest["files"]
diff --git a/tests/test_finetuning_context_length.py b/tests/test_finetuning_context_length.py
index b9918344..ea744a75 100644
--- a/tests/test_finetuning_context_length.py
+++ b/tests/test_finetuning_context_length.py
@@ -88,8 +88,8 @@ class TestRecommendFiltersByDatasetContext:
@override_settings(FINETUNING_BACKEND="modal")
def test_no_candidate_survives_rows_past_every_context_limit(self):
- # Past every SFT max.
- max_tokens = 1_000_000
+ # Past every SFT max. Qwen4-35B-A3B trains at 1,048,576.
+ max_tokens = 1_048_576
eligible, _excluded = eligible_models(has_tool_calling=False, max_row_tokens=max_tokens)
assert not eligible
@@ -107,7 +107,7 @@ class TestRecommendFiltersByDatasetContext:
# A model with no enabled training kind at all is rejected before context is
# even considered — that reason names no dataset size, unlike every other one.
assert all(
- "1,000,000" in e["reason"] or e["reason"] == "No supported fine-tuning method"
+ "1,048,576" in e["reason"] or e["reason"] == "No supported fine-tuning method"
for e in analysis["excluded"]
)
diff --git a/tests/test_modelfam.py b/tests/test_modelfam.py
index fb98bee2..67f6d14a 100644
--- a/tests/test_modelfam.py
+++ b/tests/test_modelfam.py
@@ -10,6 +10,7 @@ from modal_shared.modelfam import (
all_force_mask_pairs,
all_pretok_headers,
catalog_hf_id,
+ clamp_training_gpus,
family_key,
fixups_for_model_type,
is_always_on_thinking_template,
@@ -412,6 +413,22 @@ def test_serve_strips_training_chat_template(tmp_path) -> None:
assert Path(served).read_text(encoding="utf-8") == "hi"
+def test_qwen4_resolves_before_generic_qwen() -> None:
+ spec = resolve("Qwen/Qwen4-35B-A3B")
+ assert spec.key == "qwen4"
+ assert spec.train_image == "qwen4_56397f9"
+ assert spec.serve_image == "sglang_qwen4"
+ assert spec.tool_call_parser == "qwen4"
+ assert spec.reasoning_parser == "qwen4"
+ assert spec.sglang_args_module == "modal_shared.serving.qwen4"
+ assert spec.hooks_module == "families.qwen4"
+ assert spec.lora_target_modules == "o_proj"
+ assert spec.train_gpu == "H200"
+ assert clamp_training_gpus("Qwen/Qwen4-35B-A3B", "H100", 1) == ("H200", 1)
+ assert spec.sglang_process_env == "modal_shared.serving.qwen4"
+ assert resolve("Qwen/Qwen3-0.6B").key == "qwen"
+
+
def test_inkling_lora_targets() -> None:
spec = resolve("unsloth/Inkling-2-Mini")
assert spec.key == "inkling"
diff --git a/tests/test_serving_args.py b/tests/test_serving_args.py
index 1a3e9c2b..14ed2b30 100644
--- a/tests/test_serving_args.py
+++ b/tests/test_serving_args.py
@@ -20,6 +20,8 @@ from modal_shared.serving.decision_http import (
probabilities_for,
systemone_body,
)
+from modal_shared.serving.qwen4 import admin_headers, process_env
+from modal_shared.serving.qwen4 import build_args as build_qwen4_args
pytestmark = pytest.mark.covers("model-runtime")
@@ -136,6 +138,7 @@ 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
+ from modal_shared.serving.speculative import mtp_for
cmd = build_sglang_args(
model_path="/tmp/folded",
@@ -199,6 +202,26 @@ def test_sglang_dflash_argv_and_engine_choice() -> None:
assert engine_for("meta-llama/Llama-3.1-8B-Instruct") == "vllm"
assert engine_for("Qwen/Qwen3-0.6B") == "vllm"
assert engine_for("LiquidAI/LFM3-1.7B") == "sglang_lfm3"
+ assert engine_for("Qwen/Qwen4-35B-A3B") == "sglang_qwen4"
+ assert serverless_engine("Qwen/Qwen4-35B-A3B") == "sglang_qwen4"
+ qwen4 = build_qwen4_args(
+ model_path="/weights/qwen4",
+ served_name="Qwen/Qwen4-35B-A3B",
+ port=8000,
+ mtp=(3, 1, 4),
+ tool_call_parser="qwen4",
+ reasoning_parser="qwen4",
+ max_model_len=16384,
+ )
+ assert "--attention-backend" not in qwen4
+ assert "--mamba-ssm-dtype" not in qwen4
+ qwen4_env = process_env()
+ assert qwen4_env["SGLANG_ADMIN_API_KEY"]
+ assert admin_headers()["Authorization"].endswith(qwen4_env["SGLANG_ADMIN_API_KEY"])
+ assert qwen4[qwen4.index("--speculative-algorithm") + 1] == "NEXTN"
+ assert qwen4[qwen4.index("--qsa-indexer-dtype") + 1] == "fp8_e4m3"
+ assert qwen4[qwen4.index("--context-length") + 1] == "16384"
+ assert mtp_for("Qwen/Qwen4-35B-A3B") == (3, 1, 4)
assert serverless_engine("Qwen/Qwen3-0.6B") == "sglang"
assert serverless_engine("unsloth/Llama-3.2-1B-Instruct") == "sglang"
assert serverless_engine("Qwen/Qwen3-Coder-30B-A3B-Instruct") == "vllm"
@@ -476,3 +499,42 @@ def test_lfm3_hidden_dims_and_unsloth_target_rewrite(tmp_path: Path) -> None:
config.write_text(json.dumps({"target_modules": "model\\.layers.*"}))
normalize_sglang_adapter(adapter)
assert json.loads(config.read_text())["target_modules"] == "all-linear"
+
+
+def test_folded_sglang_checkpoint_keeps_only_named_leaves(tmp_path: Path) -> None:
+ torch = pytest.importorskip("torch")
+ from safetensors.torch import load_file, save_file
+
+ from modal_shared.serving.merge import write_folded_checkpoint
+ from modal_shared.serving.sglang import normalize_sglang_adapter
+
+ base = tmp_path / "base"
+ base.mkdir()
+ (base / "config.json").write_text("{}")
+ save_file(
+ {"model.layers.0.self_attn.o_proj.weight": torch.zeros(4, 4)},
+ base / "model.safetensors",
+ )
+ adapter = tmp_path / "adapter"
+ adapter.mkdir()
+ (adapter / "adapter_config.json").write_text(
+ json.dumps({"r": 2, "lora_alpha": 2, "target_modules": ".*"})
+ )
+ save_file(
+ {
+ "base_model.model.model.layers.0.self_attn.o_proj.lora_A.weight": torch.ones(2, 4),
+ "base_model.model.model.layers.0.self_attn.o_proj.lora_B.weight": torch.ones(4, 2),
+ "base_model.model.model.layers.0.mlp.experts.base_layer.lora_A.weight": torch.ones(
+ 2, 4
+ ),
+ "base_model.model.model.layers.0.mlp.experts.base_layer.lora_B.weight": torch.ones(
+ 4, 2
+ ),
+ },
+ adapter / "adapter_model.safetensors",
+ )
+ normalize_sglang_adapter(adapter, keep_targets="o_proj")
+ folded = tmp_path / "folded"
+ write_folded_checkpoint(base, adapter, folded)
+ weight = load_file(folded / "model.safetensors")["model.layers.0.self_attn.o_proj.weight"]
+ assert torch.equal(weight, torch.full((4, 4), 2.0))
diff --git a/tests/test_shared_base_serving.py b/tests/test_shared_base_serving.py
index f629428c..2b45fed8 100644
--- a/tests/test_shared_base_serving.py
+++ b/tests/test_shared_base_serving.py
@@ -312,7 +312,7 @@ class _AdapterClient:
async def __aexit__(self, *_exc):
return None
- async def post(self, url, json):
+ async def post(self, url, json, headers=None):
_AdapterClient.posts.append((url, json))
return Mock(status_code=200, text="")