Skip to content

feat(server): detect stalled engines and support model-card lookup - #3692

Merged
inureyes merged 9 commits into
lablup:mainfrom
Jaeyeong-CHOI:feat/server-3633
Dec 2, 2026
Merged

inureyes merged 9 commits into
lablup:mainfrom
Jaeyeong-CHOI:feat/server-3633

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Add opt-in stalled-engine health checks and OpenAI model-card lookup

Addresses #3633. A loaded, idle server still returns the b10621 health response. Both server CLIs accept --stall-timeout (or MLXCEL_STALL_TIMEOUT); when enabled, a scheduler that has work but stops stepping returns 503 Engine stalled. New arrivals cannot postpone the deadline. The next step or idle transition restores readiness.

The /models/{id} and /v1/models/{id} routes look up the same cards as the inventory, including side models and IDs with slashes. An unknown ID returns the OpenAI model_not_found envelope. Router mode looks up visible cards without loading the model; the existing /models/sse endpoint retains its meaning.

On Spark1, we served Qwen3-0.6B weights with the published mistralai/Mistral-7B-Instruct-v0.3 chat template. On the unpatched binary, both a later system message and a user turn immediately after a tool result returned HTTP 400 from /v1/chat/completions. With the patch, both returned 200. /apply-template confirmed the later system text, tool result, follow-up text and call ID survived. This tests the Mistral template, not Mistral model weights. The shared renderer probes before folding either order. The Mistral Small 3.2 template already renders later system turns and does not accept tool turns at all.

No output-parser change: upstream removes leading CR/LF after reasoning/tool blocks. With Qwen3-0.6B-4bit, raw output contained a closing think tag and two newlines before “First”, while parsed JSON and SSE content both started with “First”.

Validation on DGX Spark1

On commit fc876f905, the CUDA build, Clippy with warnings denied, formatting and 232 focused tests passed (4 template tests ignored). Live Qwen serving returned 200 for health and chat. The isolated unpatched binary returned 404 for the listed alias lab/Qwen3-0.6B on both lookup routes; the patched binary returned 200 with the listed card and the expected JSON error for a missing ID. The stall/recovery sequence was tested at the HTTP handler, not by hanging a live GPU.

The full CUDA gate on that commit found one patch regression: the runtime-settings schema omitted the new startup field. The follow-up commit classifies it as a read-only integer and updates the 119-field invariant. The other two gate failures, mlx_test_guard_coverage and step3p7_parity, reproduced separately on the isolated unpatched checkout.

On the final commit, 8d6a74698 (tree 867ea22a133ccc5fc18fd7ee0d4c50334e58efa0, matched on Spark1), formatting and all 14 CUDA runtime-settings tests passed, including the schema invariant and field fixture. A separate catalog check found English and Korean labels for all 142 fixture fields and sub-fields. The full CUDA gate was rerun on this exact commit: 18,647 passed, 2 failed, 540 ignored. Both failures matched the unpatched baseline: mlx_test_guard_coverage reported the same missing guard and step3p7_parity failed the same padded-prefill assertion. No new failure was observed. Live smoke was not rerun after the settings-only changes.

Upstream comparison: the branch is based on a8eb71599; a local merge-tree check against upstream 97b63a2e8 found no conflicts. The hypothetical merge tree was not built or tested.

Closes #3633

@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:low Low priority labels Dec 2, 2026
The /health stall deadline was stored as Unix wall-clock milliseconds, so an NTP step or manual clock change could fake a stall or hide one. The probe now reads a process-local Instant on an offset scale that never equals the idle sentinel.

The system-turn fold joined every run of consecutive user turns once a template needed it, including user turns the client sent back to back. It now joins only the run that holds folded system text.

Document how to size --stall-timeout against the longest single scheduler step, and add tests for the monotonic deadline and the narrowed fold.

Refs lablup#3633
@inureyes

inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3633. Items 1 and 2 meet their acceptance lines, items 3 and 4 are resolved and recorded in the PR body, /health without --stall-timeout is unchanged, and the router front serves the card lookup from its inventory snapshot without loading a model. Scope is limited to #3633; the 48-file count came from the committed WebUI bundle.

Changes pushed:

  • Merged current origin/main. Main (refactor(webui): stop committing the compiled WebUI bundle #3684) stopped committing the compiled WebUI bundle, so the regenerated bundle files on this branch were dropped; startup-strings.ts and tests/fixtures/webui/strings.json stay in sync. No conflicts with fix(server): report undecodable tool calls across APIs #3690 or feat(server): align Anthropic Messages generation and stop semantics #3696.
  • The stall deadline used Unix wall-clock milliseconds, so an NTP step or manual clock change could fake or hide a stall. It now uses a process-local Instant on an offset scale that never equals the idle sentinel (last_step_ms).
  • With the system-turn fold active, every run of consecutive user turns was joined, including turns the client sent back to back. Only the run holding folded system text is joined now.
  • Documented sizing --stall-timeout above the longest single scheduler step (a prefill chunk, a decode step, a vision encode at admission, first-request kernel compilation).

Verified without change: later arrivals only arm an idle deadline and never extend it; idle and prompt-cache warmup clear it; a worker waking from --sleep-idle-seconds arms it only after the reload; a long prompt prefills in chunks with a step recorded per chunk. Slash IDs route through {*id} and are compared only against listed cards, so there is no filesystem path. The routes share the existing auth scope, and an unknown ID returns the model_not_found envelope.

Validation (fork PRs skip the self-hosted jobs): cargo fmt, and clippy -D warnings on the workspace with default features and with --features cuda. All 4,699 server:: lib tests ran, including health, models, router, observability, chat template, runtime settings and auth; 4,694 passed. The 5 failures are server::webui::catalog tests, which fail the same way on origin/main. check_env_var_docs.py and check_llama_compat_manifest.py pass, and so do WebUI vitest (settings plus the strings fixture, 146 tests). mlx_test_guard_coverage fails on origin/main too (nemotron_h_nano_omni_tests.rs:276), so it is not from this PR.

@inureyes
inureyes merged commit 176e69c into lablup:main Dec 2, 2026
36 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 2, 2026
inureyes added a commit that referenced this pull request Dec 3, 2026
## Summary

On CUDA an eligible decode step is now captured once as one CUDA graph and every later step with the same key launches it: one `cudaGraphLaunch`, one upload of the step inputs and one readback of the tokens, with no per-kernel graph or launch call. Part of epic #3671.

- **Path.** Default on for pooled families on CUDA (Llama, Qwen and other families whose rows live in the paged pool). A replayed step is synchronous, so by default a tick of more than one row that the lookahead pipeline can run stays with the pipeline; a single row, and every tick the pipeline cannot run (`--ctx-size` or `--max-kv-size` set, a pending admission), is replayed, and `MLXCEL_DECODE_GRAPHS=always` replays the multi-row ticks too. Gemma 4 and Gemma 3 are graph-eligible through paged sliding state. This PR makes it the CUDA default again for Gemma 4 only (`MLXCEL_PAGED_SLIDING`, see below); Gemma 3 keeps dense sliding state on CUDA by default and `MLXCEL_PAGED_SLIDING=1` makes it eligible. Dense per-sequence caches, whose shapes grow every step, stay eager (tested).
- **Mechanism.** A step-capture mode in the CUDA encoder overlay defers every commit of one evaluation, so its kernel nodes and cuBLAS child graphs land in one `cudaGraph_t` that is instantiated once. With MLX's CUDA graphs on, the nodes keep the dependencies the encoder derives; with `MLX_USE_CUDA_GRAPHS=0`, which mlxcel sets for Gemma 4 (#688), each node depends on the one before it, so the graph runs in the order the direct launches had. The graph owns what its step allocated plus the small host constants it was keyed by (the capture arena); pool slabs and weights stay solely owned by their owners. `cudaStreamBeginCapture` over direct launches was rejected by analysis, not measured: MLX's stream-ordered allocations and event records made during the evaluation would be captured into the graph.
- **Key.** A hash of the step's lazy graph (primitive, shapes, topology, custom kernel name, grid and scalars), the device address of every evaluated input, the contents of small host constants, the staging layout and the sampler parameters, plus a per-primitive `is_equivalent` check and a direct comparison of every captured input's device address before each launch (strides and sizes are covered by the hash), so input identity does not rest on the 64-bit hash alone. A step that would hand the GPU anything else is evaluated; a key seen twice is captured.
- **Step structure of a graph step.** Always the fused paged read, planned for the batch's page tier (a power of two) with the page table staged at the tier's size; fresh blocks through the batched in-place write; one row through the batched model entry and array-offset RoPE; the draw over every row of the bucket. For Gemma 4 the KV donor rows of a checkpoint with no KV-shared layer are not stored, since nothing reads them, and a single Gemma 3 or Gemma 4 row goes through the batched forward.
- **Eligibility.** Pool-backed rows, one shared greedy draw, no penalty, structured-output mask, token override, logprobs or speculative dispatch. A token bias stays eligible. Everything else runs the eager step it ran before.
- **Controls.** `MLXCEL_DECODE_GRAPHS` (`0`, `always`, `eager`, `verify`), `MLXCEL_DECODE_GRAPH_MAX_BS`, `MLXCEL_DECODE_GRAPH_DUMP`; four counters on `/metrics`. At most 24 graphs and 2 GiB of step buffers are kept per engine (a single graph over the byte cap is dropped after its step runs, and its bucket and larger ones run eagerly from then on); 64 eligible steps in a row that match no graph, or 24 evictions within 60 s, suspend the feature for 60 s, so a model whose step changes every time keeps its previous path; a CUDA error on a replay fails the step and disables graphs for that engine.
- **Metal, ROCm, CPU unchanged.** `step_graph::mode_from` returns off for every backend but CUDA whatever the environment says (unit-tested per backend), so no structure scope, capture or graph is ever constructed there; the non-CUDA bridge is a refusing stub and the default-features check passes.

## Deviations and known limits

- **The lazy graph is still built on every replayed step.** It is not evaluated. That build is the host plan, shared with the eager step, so the two cannot diverge. It costs 0.2 ms of a 4.7 ms step for one Llama 3.2 1B row and 1.0 ms of 74 ms for four Gemma 4 12B rows; the walk that keys it costs about the same again.
- **Capture at first use, not at startup.** A key is captured at its second sighting and logs `Captured <n> decode graphs (buckets [...]) in <s> s, arena <GiB>`.
- **No pipelined replay.** A replayed step is synchronous. For pooled families a tick of more than one row that the lookahead pipeline can run therefore stays eager by default, and `MLXCEL_DECODE_GRAPHS=always` replays it. Measured on GB10 with Llama 3.2 1B in a default launch: pipelined eager 134.3, 133.9 and 134.2 steps/s at four rows against 127.1, 125.5 and 126.3 replayed, and 100.5 against 94.8 at eight, while one row replayed at 205.6 and 207.4 against 179.8 and 180.5. The pipeline does not run Gemma 4 rows, so its multi-row ticks replay by default.
- **A stochastic draw is not eligible.** Its random key advances on the host.
- **Graph buffers are outside the startup memory plan.** They are capped at 24 graphs and 2 GiB per engine (554 MB for one 256-row Llama graph, 352 MB for two 8-row Gemma 4 12B graphs).
- **Graphs on and graphs off can sample different tokens.** The graph step always takes the fused read with a tier plan; the off arm uses the gather path below the fused floor and a per-step chunk plan. Pinning both arms to the fused read and one chunk per request makes Llama identical (20 of 20 server rows, 32 of 32 rows of the 32-row test on f16 and FP8), so the cause is plan-shape numerics.
- **Gemma 4 pinned residual.** Pinned the same way, Gemma 4 matches graphs off in 8 of 10 server rows. The remaining structural difference is the two KV donor layers (per-row gather in the off arm, fused read in the graph step); that attribution is not confirmed.

## Validation on GB10 (shared host, load 3 to 7)

Replay against evaluation, token for token (`verify` mode plus replay vs the `eager` arm of the same structure), each over 70 to 280 steps crossing page and tier boundaries:

| Model | Buckets and cases | Result |
|---|---|---|
| Llama 3.2 1B 4bit, f16 pool | 1, 4, 8, 32, 256, 3 rows padded to 4, logit bias, context past 1024, admission between replays | identical, no verify mismatch |
| Llama 3.2 1B 4bit, FP8 pool | 1, 4, 32, 3 padded to 4 | identical |
| Qwen3 1.7B 4bit | 1, 4 | identical |
| Gemma 3 1B 4bit, paged sliding | 1, 4 | identical |
| Gemma 4 12B 4bit, paged sliding | 1, 4, context past the 1024 window, admission; FP8 at 4 | identical |

Eager fallbacks tested: stochastic draw, penalty, logprobs, structured-output mask, dense caches, bucket over the cap, graphs off, speculative dispatch. Core tests pass with CUDA graphs on (43) and with `MLX_USE_CUDA_GRAPHS=0` (29); `batch::scheduler` passes 349; scoped clippy on both crates, `cargo fmt`, the default-features check and the `verify-*` contract list pass. The nsys counts on the branch were rerun on the final head with the same result; the main-side counts are from 22ee939. Bucket 256 holds 554 MB of step buffers. With the slab-ownership fix reverted locally the admission test fails (the slabs move and the graphs hold 1.6 GB). A host constant above 4096 bytes is keyed by its address and read at launch, and the 24-graph cap evicts the least recently used graph, which is captured again after two sightings (both tested). A steady Gemma 4 batch captures two graphs per row count, one per page tier it crosses. Not run: Gemma 4 above four rows, the FP8 pool at 256 rows.

nsys, four concurrent greedy requests, 10 s steady window, calls per decode step:

| | graph build and update | graph or kernel launches | `cudaMemcpyAsync` |
|---|---|---|---|
| Llama 1B, main | 345 `AddKernelNode`, 17.2 each of `Create`, `ExecUpdate`, `AddDependencies`, `Destroy` | 17.2 `cudaGraphLaunch` | 2.0 |
| Llama 1B, this PR | 0 on 1170 replayed steps | 1.0 `cudaGraphLaunch` | 2.0 |
| Gemma 4 12B paged, main | none (`MLX_USE_CUDA_GRAPHS=0`) | 1341 direct kernel launches | 2.0 |
| Gemma 4 12B paged, this PR | 0 | 1.0 `cudaGraphLaunch` | 2.0 |

The Llama window also held one evaluated step and one capture (a page-tier crossing), which account for the 674 `AddKernelNode`, 18 `Create` and 1 `Instantiate` calls it recorded.

mlxcel-server parity with `--parallel 8 --ctx-size 16384`, 64 to 96 tokens, two repetitions, rerun on the final head: graphs on against the `eager` arm is identical in every row (Llama f16 at 1, 4 and 5 requests, Gemma 4 paged at 1 and 4; Llama FP8 at 1 and 4 on the earlier build). Against `MLXCEL_DECODE_GRAPHS=0` Llama f16 matches in 17 of 20 rows and Gemma 4 paged in 5 of 10. The cause is plan-shape numerics: the off arm keeps the gather path below the fused floor and a per-step chunk plan. With both arms pinned to the fused read and one chunk per request (`MLXCEL_PAGED_ATTENTION_NATIVE=1 MLXCEL_PAGED_DECODE_V2_TARGET_CTAS=1`) Llama matches in 20 of 20 server rows, and the 32-row scheduler test, which matched 27 of 32 unpinned, matches 32 of 32 on the f16 pool and on the FP8 pool (also with one chunk per page). Gemma 4 paged matches 8 of 10 pinned; the remaining structural difference there is the two KV donor layers, which the off arm runs through per-row gather and the graph step through the fused read, and that was not isolated. A default launch with the prompt cache on ran `verify` mode at one and four requests, repeated so the second pass adopts cached prefixes, without a mismatch. In a default launch the default mode replays one Llama row (90 of 95 steps) and leaves four rows to the pipeline (93 of 95), `always` replays both, and all three arms give the same tokens as graphs off.

Timing, indicative only. Llama 3.2 1B with `--ctx-size` set (no lookahead pipeline), median decode tick in one instrumented build, graphs off against on: 6.23 to 4.75 ms at one row, 9.06 to 7.76 ms at four, 12.0 to 10.9 ms at eight (n=1). The Gemma 4 comparison is in the next section.

## `MLXCEL_PAGED_SLIDING` on CUDA: on by default again

#3676 turned paged sliding state off on CUDA for a B200 decode regression. The rule for this epic was to turn it back on only if paged is not slower, after a correctness check. Both hold on GB10 for Gemma 4, so its default is on everywhere and `MLXCEL_PAGED_SLIDING=0` restores the dense ring storage. They do not hold for Gemma 3 (below), which keeps the #3676 CUDA default through a separate `gemma3_paged_sliding_state_default`.

Speed, Gemma 4 12B 4bit, final binary, default launch flags (`-m <model> --port <p> --metrics`, plus `--parallel 8` for eight requests), default graph mode, 20 s windows, two interleaved rounds, steps/s:

| Requests | Dense, round 1 / 2 | Paged, round 1 / 2 | Paged steps replayed |
|---|---|---|---|
| 1 greedy | 15.9 / 15.9 | 16.5 / 16.6 | 510 of 516 |
| 4 greedy | 12.2 / 12.4 | 13.6 / 13.7 | 423 of 429 |
| 8 greedy | 8.9 / 8.7 | 10.3 / 10.3 | 317 of 323 |
| 4 at temperature 0.7 | 12.2 / 12.3 | 12.3 / 12.5 | none (eager) |

Correctness: greedy output is not always token-identical between the two storages (two of four chat requests matched over 64 tokens at four concurrent requests, none of one at a single request, the same with graphs off). With top-2 logprobs on both arms, the first differing token is a near-tie in every case:

| Request | Token | Dense | Paged |
|---|---|---|---|
| 1 request, row 0 | 21 | ` frequently` -1.125, ` often` -1.25 | ` often` -1.125, ` frequently` -1.25 |
| 4 requests, row 0 | 21 | same | both -1.125 |
| 4 requests, row 1 | 42 | ` escapes` -0.6875, ` goes` -0.8125 | both -0.75 |

The margin is at most 0.125 nats, one step of the logits' resolution, so the difference is kernel rounding.

Knock-ons of the new Gemma 4 default:

- A Gemma 4 checkpoint that declares FP8 KV, such as the 31B NVFP4, now stores FP8 in the pool by default on CUDA sm_89 and newer. That checkpoint was not exercised here; the 12B 4bit declares none and its default launch runs f16 (confirmed in its log).
- Gemma 3 stays dense on CUDA by default. Its multi-row ticks run on the lookahead pipeline, which does not replay, and there its paged path was slower: Gemma 3 1B 4bit at the default launch, two interleaved rounds, 123.1 and 123.4 steps/s paged against 130.8 and 135.7 dense at four requests, while one replayed row was faster (102.2 and 97.5 against 78.1 and 79.2). With `MLXCEL_PAGED_SLIDING=1` it replays (one row: 121 of 126 steps; `verify` clean at one and four rows, and against dense the same tokens at one request and in three of four at four). Its default launch on the final binary is token-identical to main with 0 replays.
- Gemma 4 12B at a default launch with no environment set: paged path, 60 of 63 steps replayed at one request and 121 of 126 after four, same tokens as the earlier `MLXCEL_PAGED_SLIDING=1` run.

The B200 figure that motivated #3676 has not been re-measured with graphs.

## Branch against main with the switches off

Final binary against the main binary (22ee939), default launch flags, 64 tokens, one and four concurrent greedy requests, two repetitions: Llama 3.2 1B with `MLXCEL_DECODE_GRAPHS=0`, Gemma 4 12B with `MLXCEL_PAGED_SLIDING=0`, and Gemma 3 1B with `MLXCEL_PAGED_SLIDING=0` (and at its new default) are token-identical to main in every row, with 0 replays and 0 captures in `/metrics`. This is also the server-level check that dense sliding state stays eager, which test builds cannot reach. After the flip, the tests of every module it touched pass (`kv_fp8` 11, `memory_estimate` 77, `memory_plan` 8, `models::gemma3` 74, `models::gemma4` 153, `model_worker` 46, core `paged_geometry` and `memory::`), and the Llama decode graph suite runs all 18 tests with no skip (bucket 256: 68 replays, one capture, 554 MB).

## Changes during review

- A failed capture (instantiate failure, a throw mid-evaluation, a refusal after capture) could leave the step's arrays marked evaluated without any kernel having run, so the eager fallback returned unwritten tokens as a success. Every exit of `step_graph::capture` now either launches the captured nodes once and waits, or throws a `[step_graph] fatal:` error on which graphs are disabled and the step fails; graph edges are added at most once (tests for a refused strided output, a mid-step throw and an empty capture).
- A step with a lazy node on another stream is refused before evaluation; address-keyed inputs are also keyed (hashed) by strides, data size and contiguity; replay compares captured input addresses directly.
- Capture churn a client could drive by varying bucket and page tier is bounded (24 evictions in 60 s suspend graphs for 60 s), and the 2 GiB cap is enforced for a single oversized graph.
- Merged main with #3692 (stalled-engine detection): a capture tick is one slower step and replayed ticks count as progress; with `--stall-timeout 3` no stall was reported on Llama 3.2 1B or Gemma 4 12B (capture took 10 ms and about 90 ms).
- Tests: the #3667 step-input tests pin graphs off (graph steps always take the fused read), `dense_caches_run_eagerly` skips models whose sliding layers live in the pool, and the 256-row test accepts the Gemma 4 12B graph being dropped over the byte cap (its vocabulary reaches it at 256 rows; buckets 1, 4, 8 and 32 replay).

Known limits found in review and left open: with one long row among short ones the uniform tier plan gives the long row about 1/B of the attention parallelism the per-step heuristic would (multi-row graph steps only); `held_bytes` counts the step's array outputs but not the encoder's scratch buffers; Gemma 4 12B at one request and temperature 0.7 (eager, not replayed) measured 15.45 and 15.46 tok/s paged against 15.74 and 15.78 dense, about 2% and inside GB10 noise, to be re-checked on the B200; `OxideFusedAddRmsNorm` (opt-in) defines no `is_equivalent`, so a step using it never replays.

## Deferred to the B200 follow-up measurement issue

- Serving TPOT from `scripts/bench/serving_compare.py` (12.0 ms at c=1, 8.5 ms at c=8, 10.5 ms at c=32) and the c=1, 8, 32 serving table; no B200 or 31B number backs this PR.
- nsys over 25 s at c=8 on Gemma 4 31B NVFP4.
- Re-measuring paged against dense sliding state with graphs on the B200 and the 31B, including its FP8 pool.
- Pipelined replay (which would let multi-row ticks replay by default), a device-side random key for stochastic draws, capture of every bucket at startup, and charging the graph buffers to the startup memory plan.

Closes #3668
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Opt-in stalled /health and GET /v1/models/{id}

2 participants