Skip to content

memory: --gpu-ceiling-gib / --memory-preset, and one owner for the served context - #1365

Merged
ddalcu merged 18 commits into
ddalcu:mainfrom
davidtai:ds41-gpu-ceiling-flag
Nov 29, 2026
Merged

ddalcu merged 18 commits into
ddalcu:mainfrom
davidtai:ds41-gpu-ceiling-flag

Conversation

@davidtai

@davidtai davidtai commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Branch ds41-gpu-ceiling-flag. Base v26.11.4 (45df50e), then main merged in (449d850), then the served-context
branch merged in, then main again (6d602bd, then 5bc670c). All commits are signed.

  • f808b4e memory: one forced GPU ceiling for every bill; --gpu-ceiling-gib and --memory-preset
  • 8c2e56c memory: an m5-96 preset (80 GiB) for the 96 GB M5 Macs
  • 3cc374e memory: say that a preset sets the GPU ceiling only, never the model
  • 425d107 merge main
  • 05f0e89 served context: one owner decides it before the model is ready
  • e784cda engines: context_for answers the context an open would hold, before it opens
  • 01db0b7 plugins: a load is asked its served context and reports what it serves
  • 53e78bc /v1/models: an unloaded row shows the owner's decision, read off the lock
  • 79fce36 launch: a row with no context yet bakes nothing
  • 47bc6a9 docs: the served context's owner, its rules and the class's story
  • 9a1bb18 comments: name the owner where two comments still named the deleted pin
  • 5ce6247 merge the served-context branch: the DeepSeek bank takes both the host's ceiling and the host's ask; the
    owner's ceiling test under a preset; the recommended pack per preset in docs/cli.md
  • 0a9afd0 served context: a streamed plugin that does not report its context loads, serves the context it was asked
    for, and is warned (also regenerates docs/plugin-abi.md for the served-context fields)
  • ebf856a merge main (6d602bd): one conflict, docs/gotchas/engine-mlx.md, where both sides added a story; both
    are kept
  • 8863700 docs: the m5-128 row of the recommended-pack table, measured on an M5 Max 128 GB
  • 47e718d memory: a forced GPU ceiling never goes past this Mac's Metal working set
  • 22c2386 merge main (5bc670c: LoopCD, MLX v0.33.0 / mlx-c v0.8.0, the test split); no conflicts
  • bc87838 tests: a fixture's machine is a stand-in for Metal's working set, not the runner's

The PR has two parts. Part 1 makes every memory bill read one GPU ceiling, which a flag can set. Part 2 makes one
owner decide the context a model serves, under that same ceiling.

Part 1: one forced GPU ceiling for every bill

Problem

MLX_SERVE_GPU_CEILING_MB sets overrides().static_ceiling, which staticGpuMemoryCeiling() and the admission
guards read. DeepSeek-V4.1's streamed expert bank does not read it. deepseek_v41/bill.zig streamBudget calls
mlx.maxRecommendedWorkingSet() itself, so a 512 GB Mac told to plan as a 256 GB Mac still sizes the bank's slot rows
to the whole machine.

Three more bills read the device directly:

  • the load preflight (preflight.loadGpuLimit);
  • the ceiling the host table gives plugins (plugin_host_impl.workingSetHeadroom);
  • the registry's auto resident cap (main.autoResidentMemBytes). Its doc says it moves with the preflight.

Change

  • memory_ceiling.deviceWorkingSet() is the one reading. It returns Metal's recommended working set, lowered to the
    forced ceiling when one is set. getGpuWorkingSetLimit, the load preflight, the host table's ceiling and the auto
    resident cap read it.

  • A forced ceiling never goes above this Mac's own working set. A preset plans a big Mac as a smaller one, never a
    small one as bigger. Above the device, the reading is the device's, and the server logs one warning that names the
    flag, both numbers and the value used, for example [mem] --memory-preset asks 240 GiB, above this Mac's 112 GiB Metal working set: planning with 112 GiB. With no device reading (0: CI, no GPU), the forced value stands.

  • streamBudget takes the host's ceiling, LoadCtx.gpuCeiling(). The driver already fills that field from
    staticGpuMemoryCeiling(). A host that sets no ceiling (0) keeps the device's value.

  • --gpu-ceiling-gib <n> takes whole GiB, 4 to 4096. It sets the same override as MLX_SERVE_GPU_CEILING_MB and
    wins over it.

  • --memory-preset <name> names a Mac. Its ceiling is the Mac's RAM less 16 GiB:

    Preset RAM Ceiling
    m5-96 96 GB 80 GiB
    m5-128 128 GB 112 GiB (the 128 GB M5 Max's iogpu.wired_limit_mb=114688)
    m5-256 256 GB 240 GiB

    One table, memory_ceiling.memory_presets, feeds both the parser and the --help text.

  • Giving both flags is refused by name. The server exits 1 and names both flags.

  • A preset sets the GPU ceiling and nothing else. It never selects, requires or refuses a model: the table holds
    names and RAM sizes only, and --help says that any model runs under any preset.

  • Docs: --help, docs/cli.md, the flag list in docs/reference.md, docs/plugins.md, docs/plugin-abi.md, the
    env.zig entry and the deepseek_v41 AGENTS line.

With no flag and no env var, every reading is the same as before.

Part 2: the served context has one owner

What was wrong

The context a model advertises (/v1/models, /props, /api/show, the load log, mlx-serve launch) was not always
the context its load serves. A DeepSeek-V4.1 EXL3 streamed pack, started with no --ctx-size, advertised 1,048,576
tokens while its expert bank was billed for 262,144. A longer prompt passed the host's check, prefilled up to 262,144
and then failed with a 500 that named neither number. Other paths showed the same fault: an unloaded llama.cpp GGUF
row showed the trained window while the load opened 8,192, an outside engine under --ctx-size advertised the flag
rather than its own window, and a reload re-sized the context from the memory in use at that moment.

Why it kept coming back

About ten places picked a context from their own inputs, and the host advertised its pick before the engine or plugin
made its own. Each earlier fix patched one place, and each new runtime added another. A streamed bank had no way to
report its number at all: #1131 deleted the old path through which it did.

Change

One owner, src/host/registry/served_context.zig, keeps one record per registry entry:

  1. decide, before the runtime opens: the model's maximum, a per-model ctx_size, --ctx-size, the memory limit
    and what the engine says it would open. The memory limit is this model's own weights under
    memory_ceiling.contextCeiling(): the Part 1 ceiling (deviceWorkingSet(), so --memory-preset and
    --gpu-ceiling-gib bind it) less the OS reserve. It never reads the memory in use now.
  2. The runtime opens at that number.
  3. confirm takes the runtime's answer.
  4. The model goes ready. Every reader reads the record. A reload under the same settings serves the same number.

How the two parts agree

There is one ceiling reading, deviceWorkingSet(). The owner's memory limit reads it through contextCeiling(), and
the DeepSeek bank's budget reads it through LoadCtx.gpuCeiling() (filled from staticGpuMemoryCeiling()). The bank
gets the host's ask (LoadCtx.servedContext()) and the host's ceiling in the same call, then reports the context it
was billed for (reportGrant). The host advertises that number and refuses a longer prompt before prefill.

For users

  • A per-model ctx_size above the model's limit refuses the load with an error that names both numbers. --ctx-size
    (and the app's slider) above a model's limit is clamped to it, with a warning that names both numbers. On main it
    was served verbatim.
  • The auto context no longer shrinks with other apps' memory. The cost: a prompt under the advertised context can
    still get the memory guard's 400 when other apps hold memory.
  • An unloaded row shows the same decision, computed off the registry lock. A streamed bank, or an outside engine that
    cannot answer before it opens, shows null until its first load, then the remembered number. mlx-serve launch
    (and the console's /launch-script, as a 409) refuses such a row instead of writing 32,768. Rows gain
    meta.context_state (decided, at_load, unservable, pending), context_source, context_epoch (it goes up
    when the number a model serves changes) and context_note.
  • --ctx-size on a streamed DeepSeek bank asks for at most that number: the bank takes a smaller rung, with a
    warning, where main failed the load. A reload asks the bank for exactly the number it gave before.
  • The overflow 400 keeps its prefix and adds (the model's served context; change it with --ctx-size / --memory-preset). A plugin's own refusal past its context is now that 400, not a 500.
  • The startup line Model context length: N tokens is replaced by Context size of <id>: N tokens (<source>; …).
  • Not covered yet: an unloaded plain MLX row shows the model's maximum (or the manual context) until its first load,
    because the memory limit needs the plugin's bill, which the row does not ask for.

For plugin and engine authors

  • Engine.context_for is appended to the engine table: what open would hold, answered before it opens. The host
    reads it by size, so an engine built before it still loads. ds4, llama.cpp, the Neural Engine and the example engine
    answer it. The engine contract checks the answer against the window open gives.
  • LoadCtx.served_context / served_ask carry the number in, and LoadCtx.reportGrant carries the plugin's answer
    out. Both are read by size, so a new plugin on an older host reads its ctx_size setting as before. A plugin that
    reports declares the Caps.served_context bit.
  • Compatibility: a model plugin that streams its weights and does not declare Caps.served_context (one built
    before this kit) is never refused. It loads, serves the context it was asked for (what main advertised), and the
    host logs one warning that names the plugin and says it should report its served context. A plugin that declares
    the bit is held to its grant. The in-tree plugins declare it. This PR needs no change in any outside plugin: the
    quant plugins (turboexl3_ds41, turboexl3_glm53f) ride the in-tree banks, which report, and turboexl3_qwen38
    does not stream. An outside model plugin built before this kit (for example sushi_ds41) keeps loading under the
    fallback above. sushi_ds41 sizes its expert cache for 131,072 positions by default, below the context the host
    advertises for it, on main as here; sushi_ds41: advertised context exceeds the 131,072 its expert cache is sized for (prompt past it is a 500) CommunityServe/plugins#56 asks it to report its served context.

Recommended DeepSeek-V4.1 pack per preset

docs/cli.md now lists these next to --memory-preset. They are recommendations, not requirements: any pack runs
under any preset (below). The rule: the highest-bpw pack that serves a 1,032,192-token prompt at
--ctx-size 1048576 under the preset's ceiling and decodes at least 50 tok/s on the standard cell (p01, p14, p21;
greedy; the mean of the three).

Preset Recommended pack 1M fit: slot rows (prompt / decode), peak Standard-cell decode (tok/s)
m5-256 2.68bpw 384 / 384, 220.2 GB 84.07
m5-128 2.25bpw 156 / 212, 99.6 GB (M5 Max 128 GB) 43.88 (M5 Max 128 GB)
m5-96 1.68bpw 76 / 145, 60.7 GB 52.70
  • m5-256: 2.81bpw also clears 50 tok/s (83.78) and serves 1M (374 / 384 rows, 227.5 GB). 2.68bpw is recommended, at
    turboderp's KLD 0.0384 against our 2.81bpw's 0.0396 (measured on different sets).
  • m5-128: measured on a real M5 Max 128 GB under --memory-preset m5-128. No pack reaches 50 tok/s there (1.68bpw
    decodes 45.70 on the cell), so 2.25bpw is recommended for quality (KLD 0.0803 against 1.68bpw's 0.1884,
    turboderp's set). EvalPlus pass@1, greedy: HumanEval 160/164, HumanEval+ 154/164, MBPP 368/378, MBPP+ 316/378.
  • m5-96: 2.25bpw holds 1M (48 / 104 rows, 58.9 GB) but decodes 31.25 tok/s on the cell.
  • The m5-96 and m5-256 numbers are from an M5 Ultra under the preset's ceiling, so they prove the memory fit. The
    speeds are the Ultra's. The m5-128 numbers are the M5 Max's own.

Tests

Part 1 unit tests:

  • parseGpuCeilingGib: the range limits and the bad values.
  • The presets: m5-256 = 240 GiB, m5-128 = 112 GiB and m5-96 = 80 GiB. Unknown names are refused. The usage list text.
  • ceilingFlag: either flag alone, neither, and both (refused).
  • deviceWorkingSet, staticGpuMemoryCeiling and the owner's contextCeiling under a forced ceiling.
  • a forced ceiling above this Mac's Metal working set plans with the Mac's: above the device, the reading is the
    device's; below it, the forced value stands.
  • workingSetFor: the smaller of the two, and a device that reports 0 keeps the forced value.
  • effectiveAvailableBytes is capped by the GPU working-set limit, extended: a forced ceiling above the device does
    not lift the load preflight's cap.
  • The first and third fail on 8863700, which returned the forced ceiling unclamped.
  • streamBudget follows the host ceiling: 60 GiB more ceiling gives 60 GiB more row budget in each phase. At 0 it
    keeps the device's value.

Part 2 tests cover decide / confirm / reload, the load key over every per-model setting, the ABI read by size in
both directions, ds4's and llama.cpp's answer on a GGUF header, the bank's ask, the unloaded rows, the launcher and
the 400. Eight of them, ported to main's own functions, fail on unpatched main:

Test On main
An unloaded llama.cpp GGUF row shows the 8,192 the load opens fails: shows the trained window
--ctx-size above a model's limit is clamped, warning names both numbers fails: served verbatim
A per-model ctx_size above the limit refuses the load fails: loads
A flag changed after a load does not move a loaded model's context fails: moves
The launcher refuses a row with no number yet fails: writes 32,768
The overflow 400 names the served context and the flags fails: no suffix
A plugin's refusal past its context is a 400 fails: 500
Engine.context_for answers before open fails: no such entry

Compatibility tests (0a9afd0):

  • plugin config: a plugin that streams its weights binds whether or not it reports its context. On 5ce6247, which
    refused such a plugin at bind, it fails with error.PluginReportsNoContext.
  • driver: a streamed plugin that reports no context serves the one it was asked for, and is warned; one that reports serves its grant. An old plugin (no Caps.served_context, its grant unwritten) gets the 262,144 tokens it was asked
    for and the warning. A resident plugin gets no warning. A new plugin's grant of 131,072 is what it serves.

Verification (M5 Ultra 512 GB, macOS 27.2)

On bc87838 (main at 5bc670c merged, MLX v0.33.0):

  • zig build check, python3 scripts/lint.py --strict, tests/test_plugin_abi_doc.sh: clean.
  • Filters hot_cache_plan, prefill_chunk, memory_ceiling, preflight, served context, dsv41 bank: all pass.
  • zig build test -Dslow-tests: 5815 of 6242 passed, 425 skipped, the same 2 failed as main (below).
  • With the working-set stand-in at CI's 3,535,552,432 bytes, the filters memory_ceiling, preflight,
    hot_cache_plan, prefill_chunk and keyOf fail on 22c2386 and pass on bc87838.

On 47e718d (the working-set clamp):

  • zig build check, python3 scripts/lint.py --strict, tests/test_plugin_abi_doc.sh: clean.
  • Filters memory_ceiling, preflight, served context, dsv41 bank, plugin config, driver:: all pass.
  • zig build test -Dslow-tests: 5791 of 6218 passed, 425 skipped, the same 2 failed as main (below).
  • The two new device tests fail on 8863700: expected the device's 536870912000, found the forced 554050781184.

On ebf856a (the tree with main at 6d602bd merged in; 8863700 after it changes docs/cli.md only):

  • tests/test_plugin_abi_doc.sh, zig build check, python3 scripts/lint.py --strict: clean.
  • Filters plugin config, driver:, abi plugin, served context, dsv41 bank: all pass.
  • zig build test -Dslow-tests: 5789 of 6216 passed, 425 skipped, 2 failed. Unpatched main at 6d602bd on the same
    Mac: 5789 of 6216 passed, 425 skipped, the same 2 failed (volumeSpace and the DSpark rounds check, below). The
    equal totals are most likely a coincidence of caching: the branch's shards hold more tests (776 and 775 against main's 773), and
    its unchanged non-shard steps were cached and not counted.

On 0a9afd0 (the compatibility commit):

  • tests/test_plugin_abi_doc.sh, zig build check, python3 scripts/lint.py --strict: clean.
  • Filters plugin config, driver:, abi plugin, served context, dsv41 bank: all pass.
  • zig build test -Dslow-tests: the same 2 failures as main (below), no others: 5787 of 6214 passed, 425 skipped.
    The total is 26 lower than the 5ce6247 run, most likely because test steps outside the 8 unit-test shards
    whose inputs did not change were cached and not counted.

On the merged tree (5ce6247):

  • zig build check and python3 scripts/lint.py --strict: clean.
  • zig build test -Dslow-tests: 5813 of 6240 passed, 425 skipped, 2 failed. Unpatched main on the same Mac fails
    the same two:
    • disk_tier: volumeSpace: free is what the OS grants, never less than statfs' f_bavail;
    • deepseek_v41 served: DSpark rounds (greedy, then seeded sampling) equal the legacy shell's, a DSpark text check
      unrelated to either part.
  • The kernel contract: 87 of 87 kernels pass gates 1-4, and the planted control is red.
  • zig build -Doptimize=ReleaseFast: builds.

Live check: --memory-preset m5-256, no --ctx-size

DeepSeek-V4.1-Flash EXL3 2.68bpw streamed pack through CommunityServe turboexl3_ds41, on the merged tree
(5ce6247), one fresh server:

Check Result
Ceiling [mem] GPU ceiling forced to 245760 MiB (--memory-preset), [preflight] ... available 240.00 GB
Bank 384 prompt / 384 decode slot rows per layer ... for a 262144-token context
Load log Context size of <id>: 262144 tokens (runtime; model max 1048576; ...; mlx_bank 262144) [epoch 0]
/v1/models context_length 262,144; context_state: decided, context_source: runtime, context_epoch 0, model_max_tokens 1,048,576
434,625-token prompt HTTP 400 in 0.07 s, no prefill: Prompt exceeds maximum context length: 434625 tokens requested, 262144 available (the model's served context; change it with --ctx-size / --memory-preset)
36-token prompt HTTP 200

On main (measured without a preset) this pack advertised 1,048,576, and a longer prompt prefilled to 262,144 and then failed with a 500.

Earlier live checks (Part 1, before the merge)

--memory-preset m5-256 --ctx-size 1048576: the server logs [mem] GPU ceiling forced to 245760 MiB (--memory-preset) and [preflight] ... available 240.00 GB. The DeepSeek-V4.1 EXL3 streamed bank (CommunityServe
turboexl3_ds41) sizes its slot rows to the 240 GiB ceiling. One 1,032,192-token request each:

Pack Slot rows per layer (prompt / decode) Peak footprint
2.68bpw 384 / 384 220.2 GB
2.81bpw 374 / 384 227.5 GB

Any pack under any preset, no --ctx-size: every DeepSeek-V4.1-Flash-1017 EXL3 pack under every preset and with no
preset, one fresh server each, one greedy request (a 1K-token code prompt, 512 tokens out). All 16 loaded and answered
with coherent code. None was refused. Experts that do not fit the ceiling stream from the SSD.

Pack m5-96 slot rows (prompt / decode), peak m5-128 m5-256 no preset
1.68bpw 99 / 151, 55.0 GB 218 / 270, 89.6 GB 384 / 384, 131.4 GB 384 / 384, 131.4 GB
2.25bpw 72 / 115, 55.5 GB 162 / 205, 89.7 GB 384 / 384, 169.0 GB 384 / 384, 169.0 GB
2.68bpw 56 / 90, 55.1 GB 129 / 166, 89.6 GB 384 / 384, 202.4 GB 384 / 384, 202.3 GB
2.81bpw 47 / 79, 55.2 GB 117 / 151, 89.7 GB 384 / 384, 216.2 GB 384 / 384, 216.2 GB

Slot rows are of 384 experts per layer. Without --ctx-size, the bank is sized for a 262,144-token context.

Not changed

These paths still read the device directly. None of them is in a streamed bank's bill or in DeepSeek-V4.1's load
bill:

  • the media paths: media_load, media_jobs/plugin/engine, sdk/media/job, minimax_h3, qwen4_exp/ple_gpu;
  • deepseek_v4.

…--memory-preset

DeepSeek-V4.1's streamed expert bank budgeted its slot rows against
mlx.maxRecommendedWorkingSet() directly (bill.streamBudget), so
MLX_SERVE_GPU_CEILING_MB never reached it: on a big Mac the bank sized itself
to the machine, not to the ceiling asked for. The load preflight, the host
table's memory_ceiling and the registry's auto resident cap read the device
the same way.

- memory_ceiling.deviceWorkingSet() is the one reading: the forced ceiling,
  else Metal's recommended working set. getGpuWorkingSetLimit, the load
  preflight, the host table's ceiling and the auto resident cap read it.
- streamBudget takes the host's ceiling (LoadCtx.gpuCeiling(), which the
  driver already fills from staticGpuMemoryCeiling); 0, from a host that
  sets none, keeps the device's.
- --gpu-ceiling-gib <n> (4..4096) sets the same override as the env var and
  wins over it. --memory-preset m5-128|m5-256 names a Mac: its RAM less
  16 GiB (112 and 240 GiB), from one table the parser and the usage text
  read. Giving both is refused.

With no flag and no env var every reading is the one before.
The same rule as m5-128 and m5-256 (RAM less 16 GiB), one more row of
memory_ceiling.memory_presets; the usage list and docs/cli.md follow.
--help, docs/cli.md and the preset table's comment: any model runs under any
preset; what does not fit streams from the SSD or is refused at load by name.
The context a model serves is one record on its registry entry, decided by
host/registry/served_context.zig from static inputs (the model's maximum, a
per-model ctx_size, --ctx-size, the model's own resident bill under the
static ceiling less the OS reserve) and confirmed with the runtime's answer
before ready. Every reader reads it; a reload under the same key serves the
same number. A per-model ctx_size above the model's limit refuses the load;
--ctx-size above it is clamped, by name. The prefill chunk is sized from the
same static inputs. The pin, pinned_context, manualContext and promptLimit
are gone; Admission.pin_context keeps its v1 slot and answers the record.
The overflow 400 names --ctx-size / --memory-preset.
…t opens

Engine.context_for is appended to the engine table and read by size
(Engine.min_size keeps engines built before it loading). ds4, llama.cpp,
the Neural Engine and the example engine answer it; the contract checks
the answer against the window open gives. engine_load asks it before the
open and confirms Info.context_window after, through the owner: the
write-backs (adoptEngineWindow, the Neural Engine's ctx_override clamp)
are gone, and an outside engine under --ctx-size no longer advertises the
flag over its own window.
LoadCtx.served_context / served_ask carry the record to the plugin and
LoadCtx.reportGrant carries its answer back (Caps.served_context), all read
by size: a new plugin on an older host reads its ctx_size as before. A
plugin that streams its weights and does not declare served_context is
refused by name where its parse binds. deepseek_v41's bank picks its rung
under the host's bound, reports the context it was billed for, and refuses
a prompt past it as .too_large, which the host answers as the overflow 400
(a 500 before, after minutes of prefill).
…lock

The row runs the same decide over what the host has before a load (the
pack's shell, its settings, the launch flags, an engine's context_for),
never a model plugin call. refreshStubs computes it, and the pack's stub
meta, before the registry lock; the render only reads the caches. A
streamed bank or an engine with no context_for shows null and
meta.context_state "at_load" until its first load, then the remembered
record; rows carry context_state, context_source and context_epoch.
A row whose context is decided at load used to bake the 32768 fallback
into the agent's config. The launch now stops by name on such a row and
lists only rows with a number.
# Conflicts:
#	src/plugins/deepseek_v41/plugin.zig

ddalcu commented Nov 28, 2026

Copy link
Copy Markdown
Owner

🤖 MLXServe-PRBot — code review

No conflicts with main. deviceWorkingSet() as the one reading is the right shape. Overrides is Shared, so the forced value reaches the engine unit under -Dunits. The env is applied at main.zig:604, before the flag at :1278, so the flag wins as documented. With no flag and no env every reading is unchanged. One real hole:

A ceiling above the device's working set now disables the load preflight's cap (memory_ceiling.zig:49-51, preflight.zig:256).

  • Until now loadGpuLimit read mlx.maxRecommendedWorkingSet() directly, so MLX_SERVE_GPU_CEILING_MB could never raise it.
  • Now it reads deviceWorkingSet(), which returns the forced value unclamped. --gpu-ceiling-gib accepts up to 4096, and the presets are fixed sizes.
  • So --memory-preset m5-256 on a 128 GB M5 Max (working set about 96-112 GiB) makes effectiveAvailableBytes believe it has 240 GiB. A pack that doesn't fit is no longer refused at load. It loads, and Metal's Insufficient Memory kills the process in warmup or the first request. That is the exact failure engines/mlx/AGENTS.md's "The load preflight's available is capped by Metal's working-set limit" exists to prevent.
  • The same unclamped value now also sizes DeepSeek-V4.1's slot rows (streamBudget) and the auto resident cap.

The --help line "Bounds the plans, not what Metal grants" is true and is the problem: a plan bigger than what Metal grants is the crash.

The PR's purpose is planning a big Mac as a smaller one, so clamp it. In deviceWorkingSet, return @min(forced, max_rec) when max_rec > 0 (warn once that the ceiling was lowered to the device's). Or refuse a flag above the device's working set at startup, by name. Add a test that a forced ceiling above maxRecommendedWorkingSet() reads as the device's.


Generated by Claude Code

@ddalcu ddalcu added documentation Improvements or additions to documentation enhancement New feature or request engine labels Nov 28, 2026 — with Claude

ddalcu commented Nov 28, 2026

Copy link
Copy Markdown
Owner

🤖 MLXServe-PRBot — code review

Delta since 3cc374e: a main merge plus the served-context-owner branch (7 commits). Together they put the PR at 67 files and about 2,270 lines. No conflicts with main.

  1. The earlier finding is still open, and the new code makes it worse (memory_ceiling.zig:48-51). deviceWorkingSet() still returns a forced ceiling unclamped. The new contextCeiling() builds on it, and the served-context owner decides every model's context under it. So --memory-preset m5-256 on a 128 GB M5 Max now does three things:

    • it disables the load preflight's working-set cap;
    • it inflates DSV4.1's slot rows;
    • it advertises a context in /v1/models that the box cannot hold.

    Clamp it: @min(forced, maxRecommendedWorkingSet()) when the device reports one, plus a test that a ceiling above the device reads as the device's.

  2. The PR body describes half the PR. The description still lists the three ceiling commits only. The merged branch adds a served-context owner (host/registry/served_context.zig, served_stub.zig, sdk/config/served_context.zig) and a new engine-ABI member, context_for, with a min_size compatibility rule. It also changes what /v1/models returns:

    • context_length and max_model_len are null on an unloaded row until it is decided;
    • new meta.context_state / context_source / context_epoch / context_note fields;
    • launch now bakes nothing for a row with no number.

    Those are user-visible API changes, and outside engine plugins see a table change. Write them into the body: the problem, the rule, what a client now gets, why null is safe for the OpenAI-list clients ([Feature request]: oh-my-pi support, Codex/codex-app launch integration, and finer-grained context size / max tokens controls #188), and the tests. A reviewer and the changelog read the body, not 12 commit subjects.

This is past the 1000-line auto-merge limit, so ddalcu merges it.


Generated by Claude Code

@davidtai davidtai changed the title memory: one forced GPU ceiling for every bill; --gpu-ceiling-gib and --memory-preset memory: --gpu-ceiling-gib / --memory-preset, and one owner for the served context Nov 28, 2026
…ads, serves the context it was asked for, and is warned

A plugin built before Caps.served_context (a CommunityServe sushi_ds41 on the
26.11.4 kit, say) was refused where its parse bound. It now binds and loads:
the owner confirms the context it asked for, as the host advertised before the
grant existed, and the load logs one warning naming the plugin and asking for
it to report its served context (Caps.served_context, LoadCtx.reportGrant). A
plugin that declares the bit is still held to its grant.

Also regenerates docs/plugin-abi.md (scripts/plugin_abi_doc.py) for the
served-context fields, and says so in docs/plugins.md for plugin authors.

ddalcu commented Nov 28, 2026

Copy link
Copy Markdown
Owner

🤖 MLXServe-PRBot — code review

The delta since 5ce62474 is one commit, 0a9afd00. It turns the refusal of a streamed plugin without Caps.served_context into a warning: such a plugin serves the context it was asked for. That is the right call for outside dylibs built before the grant existed, since the old plugins keep loading. confirmGrant is pure and its test covers all three arms (old streamed, resident, reporting). Know the cost: an old streamed bank once again advertises the host's ask whether or not it can hold it, and the only signal is the [plugin] … does not report the context it serves warning.

Still blocking:

  1. The merge conflict with main in docs/gotchas/engine-mlx.md. Merge main and resolve it.
  2. The earlier finding is unchanged. deviceWorkingSet() (src/host/registry/memory_ceiling.zig:48-51) still returns overrides().static_ceiling unclamped. A --gpu-ceiling-gib or --memory-preset above the device's recommended working set therefore inflates every bill that reads it: the preflight cap, the DSV4.1 slot rows, and contextCeiling(), which now sizes the served context. The result is a context the machine cannot hold, advertised as decided. Clamp to mlx.maxRecommendedWorkingSet() when that is known (log the clamp once), and test a preset above the device.

At 1,900+ / 433- lines this is past the auto-merge limit, so ddalcu merges it by hand once it is green and clean.


Generated by Claude Code

… Max 128 GB

2.25bpw under --memory-preset m5-128: a 1M fit at 156 / 212 slot rows (prompt /
decode) and a 99.6 GB peak, 43.88 tok/s decode on the standard cell (greedy,
the mean of p01/p14/p21); 1.68bpw decodes 45.70 there. The row says these are
the Max's own numbers.

ddalcu commented Nov 28, 2026

Copy link
Copy Markdown
Owner

🤖 MLXServe-PRBot — code review

The delta since 0a9afd00 is a merge of main, which resolves the docs/gotchas/engine-mlx.md conflict and leaves main's side intact, plus 88637002. That commit rewrites the m5-128 row in docs/cli.md with the M5 Max 128 GB's own numbers and says which rows were measured on an Ultra under the preset's ceiling. It is fine.

Still blocking, unchanged: deviceWorkingSet() (src/host/registry/memory_ceiling.zig:48-51) returns overrides().static_ceiling without clamping it to mlx.maxRecommendedWorkingSet(). Failure scenario: --memory-preset m5-256 (or --gpu-ceiling-gib 240) on a 128 GB Mac. Every bill, the DSV4.1 slot rows and contextCeiling() size against 240 GB, so the served context is decided at a size the machine cannot hold, and the first long prompt dies on a Metal OOM the preflight was meant to stop. Clamp to the device's recommended working set when it is known, log the clamp once, and add a test with a preset above the device.

There are no conflicts with main now. At over 1,000 lines it merges by hand.


Generated by Claude Code

… set

deviceWorkingSet() returned the forced ceiling (--memory-preset, --gpu-ceiling-gib,
MLX_SERVE_GPU_CEILING_MB) unclamped, so a preset for a bigger Mac lifted every bill
past what Metal grants: the load preflight's working-set cap, a streamed bank's slot
rows, the auto resident cap and the served context. A pack that does not fit passed
the preflight and Metal ended the server in warmup, the defect the preflight's cap
was added for.

The one reader is now the smaller of the forced ceiling and Metal's recommended
working set (workingSetFor); a device that reports 0 (CI, no GPU) keeps the forced
value. When a flag or the env asks for more than the device, the server logs one
line naming it, both numbers and the value used. The gotcha story of the preflight's
cap now names the recurrence and its cause: the cap lived at a call site, not in the
reader.

Tests: "a forced ceiling above this Mac's Metal working set plans with the Mac's" and
the extended "effectiveAvailableBytes is capped by the GPU working-set limit" both
fail on the previous head (expected the device's 536870912000, found the forced
554050781184); "workingSetFor" covers the device-0 case.

ddalcu commented Nov 29, 2026

Copy link
Copy Markdown
Owner

🤖 MLXServe-PRBot — code review

The delta since 88637002 is 47e718d8, and it is the fix that was asked for. deviceWorkingSet() now returns workingSetFor(forced, device), the smaller of the two, with the forced value standing in only when the device reports 0. A forced ceiling above the device logs one line naming both numbers. The pure function and the above-the-device case are tested.

zig-test is red on this head (job 141194192351, 5 failed, 2 crashed), and at least three of the failures are this PR's:

  1. Tests that use the forced ceiling as a "pretend this Mac is bigger" seam now get clamped to the runner.
    • admission/hot_cache_plan.zig:844 ("a streamed GLM's load-time hot-cache budget…") sets overrides().static_ceiling = 400 * GB to stand in for a big Mac. On CI's air64_v27 (7 GiB) that now reads 7 GiB, and the assertion gets found 1 instead of 6791102464.
    • admission/prefill_chunk.zig:729 ("SSD-first is gated on a DISK TIER…") fails the same way (idle_on > 0 and idle_on <= ask).
    • The clamp is right for production, but these tests need their own way to set the device: a device_working_set override beside static_ceiling that deviceWorkingSet() reads instead of mlx.maxRecommendedWorkingSet() when set. Then each test pins both numbers and passes on any host. grep -rn 'static_ceiling =' src for every other test that pretends a size.
  2. host/registry/served_context.zig:361 ("every launch flag and every per-model setting field moves the key"). The test's one: Settings literal sets every field by hand. Main has since added a Settings field (the LoopCD setting from inkling2: implement LoopCD contrastive decoding (arXiv:2610.02185) #1348), which keeps its default, so the key does not move and the test fails. Set the new field in one. Better, derive a non-default per field so a future field cannot slip past.
  3. Small trap in the new test. memory_ceiling.zig "a forced ceiling above this Mac's Metal working set…" computes device - (8 << 30). On a device reporting under 8 GiB, and the CI runner is about 7, that underflows and panics in Debug instead of failing. Use device / 2.

The ming_tts abort and the BNNS segfault in shard 1 look like the base this CI ran on (#1346 guards ming_tts on the virtual GPU). Re-check them after merging main.

There are no conflicts with main. At over 1,000 lines it merges by hand once it is green.


Generated by Claude Code

@ddalcu ddalcu added the NeedsWork label Nov 29, 2026 — with Claude
… the runner's

The clamp made deviceWorkingSet() the smaller of the forced ceiling and Metal's
working set, so a test that set the forced ceiling as "this Mac" read the runner's
working set instead: on CI's macOS VM (about 3.5 GB) hot_cache_plan's three budget
tests and prefill_chunk's SSD-first test failed, and the new working-set test
overflowed subtracting 8 GiB from the device. A box with 512 GB never clamped them.

Overrides.device_working_set stands in for Metal's working set (one reader,
metalWorkingSet, under deviceWorkingSet and the startup warning). Each fixture that
sets the forced ceiling sets the stand-in to the same machine; the working-set tests
and the preflight guard run on stand-ins, everywhere, with no device arithmetic.

keyOf's every-field test names main's new per-model setting (loopcd).

Checked with the stand-in at the runner's 3,535,552,432 bytes: the filters
memory_ceiling, preflight, hot_cache_plan, prefill_chunk and keyOf fail on the merge
of main without this commit and pass with it.

ddalcu commented Nov 29, 2026

Copy link
Copy Markdown
Owner

✅ 🟢 APPROVED

🤖 MLXServe-PRBot approved — reviewed at head bc878384, no issues found.

The delta since 47e718d8 is a merge of main plus bc878384, which closes all three findings:

  1. Overrides.device_working_set stands in for Metal's working set. metalWorkingSet() is its one reader, used by deviceWorkingSet() and the startup warning.
    • Every fixture that pretends a machine size now pins both numbers: hot_cache_plan's four, prefill_chunk's SSD-first, and the DSV4 served tests. So none of them reads the runner's 3.5 GB any more.
    • Each test saves and restores the whole Overrides struct, so the stand-in cannot leak into the next test.
  2. served_context.zig's every-field test sets main's new loopcd.
  3. The working-set tests and the preflight guard run on fixed stand-ins (36, 112 and 500 GiB), so the device - 8 GiB underflow is gone.

CI is green on this head (zig, both zig-test shards, swift-app, cuda x64/arm64), and there are no conflicts with main. At this size ddalcu merges it by hand.


Generated by Claude Code

@ddalcu ddalcu added Approved and removed NeedsWork labels Nov 29, 2026 — with Claude
@ddalcu
ddalcu merged commit c3390fd into ddalcu:main Nov 29, 2026
14 checks passed
davidtai added a commit to davidtai/mlx-serve that referenced this pull request Dec 5, 2026
…atable_prefill)

Restores 368ae96 and ad37e95 onto main. A plugin that declares
Caps.repeatable_prefill (Inkling 2) has a greedy or seeded prompt that does
not fit after the eviction pass wait for room at its pinned width, looking
every 100 ms for up to 10 s (waitForRoom), then refused by name
(PrefillDoesNotFit) as before. A sampled unseeded prompt is refused at once.

The pin half is main's static pin since ddalcu#1365 (staticPrefillChunk: the context
ceiling and resident_bill, never live memory), which ad37e95 showed equal
to the old pinFromMachine, so pinFromMachine and resident_bytes do not come
back. The test holds a repeatable_prefill model's pin at main's static width
across three forced ceilings and two free-memory readings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Approved documentation Improvements or additions to documentation engine enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants