Repository navigation
memory: --gpu-ceiling-gib / --memory-preset, and one owner for the served context - #1365
Conversation
…--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
|
🤖 MLXServe-PRBot — code review No conflicts with main. A ceiling above the device's working set now disables the load preflight's cap (
The The PR's purpose is planning a big Mac as a smaller one, so clamp it. In Generated by Claude Code |
|
🤖 MLXServe-PRBot — code review Delta since
This is past the 1000-line auto-merge limit, so ddalcu merges it. Generated by Claude Code |
…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.
# Conflicts: # docs/gotchas/engine-mlx.md
|
🤖 MLXServe-PRBot — code review The delta since Still blocking:
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.
|
🤖 MLXServe-PRBot — code review The delta since Still blocking, unchanged: 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.
|
🤖 MLXServe-PRBot — code review The delta since
The There are no conflicts with main. At over 1,000 lines it merges by hand once it is green. Generated by Claude Code |
… 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.
✅ 🟢 APPROVED🤖 MLXServe-PRBot approved — reviewed at head The delta since
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 |
…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.
Branch
ds41-gpu-ceiling-flag. Base v26.11.4 (45df50e), thenmainmerged in (449d850), then the served-contextbranch merged in, then
mainagain (6d602bd, then 5bc670c). All commits are signed.mainowner's ceiling test under a preset; the recommended pack per preset in
docs/cli.mdfor, and is warned (also regenerates
docs/plugin-abi.mdfor the served-context fields)main(6d602bd): one conflict,docs/gotchas/engine-mlx.md, where both sides added a story; bothare kept
main(5bc670c: LoopCD, MLX v0.33.0 / mlx-c v0.8.0, the test split); no conflictsThe 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_MBsetsoverrides().static_ceiling, whichstaticGpuMemoryCeiling()and the admissionguards read. DeepSeek-V4.1's streamed expert bank does not read it.
deepseek_v41/bill.zigstreamBudgetcallsmlx.maxRecommendedWorkingSet()itself, so a 512 GB Mac told to plan as a 256 GB Mac still sizes the bank's slot rowsto the whole machine.
Three more bills read the device directly:
preflight.loadGpuLimit);plugin_host_impl.workingSetHeadroom);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 theforced ceiling when one is set.
getGpuWorkingSetLimit, the load preflight, the host table's ceiling and the autoresident 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.streamBudgettakes the host's ceiling,LoadCtx.gpuCeiling(). The driver already fills that field fromstaticGpuMemoryCeiling(). 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 asMLX_SERVE_GPU_CEILING_MBandwins over it.
--memory-preset <name>names a Mac. Its ceiling is the Mac's RAM less 16 GiB:m5-96m5-128iogpu.wired_limit_mb=114688)m5-256One table,
memory_ceiling.memory_presets, feeds both the parser and the--helptext.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
--helpsays that any model runs under any preset.Docs:
--help,docs/cli.md, the flag list indocs/reference.md,docs/plugins.md,docs/plugin-abi.md, theenv.zigentry 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 alwaysthe context its load serves. A DeepSeek-V4.1 EXL3 streamed pack, started with no
--ctx-size, advertised 1,048,576tokens 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-sizeadvertised the flagrather 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:decide, before the runtime opens: the model's maximum, a per-modelctx_size,--ctx-size, the memory limitand 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-presetand--gpu-ceiling-gibbind it) less the OS reserve. It never reads the memory in use now.confirmtakes the runtime's answer.How the two parts agree
There is one ceiling reading,
deviceWorkingSet(). The owner's memory limit reads it throughcontextCeiling(), andthe DeepSeek bank's budget reads it through
LoadCtx.gpuCeiling()(filled fromstaticGpuMemoryCeiling()). The bankgets the host's ask (
LoadCtx.servedContext()) and the host's ceiling in the same call, then reports the context itwas billed for (
reportGrant). The host advertises that number and refuses a longer prompt before prefill.For users
ctx_sizeabove 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
mainitwas served verbatim.
still get the memory guard's 400 when other apps hold memory.
cannot answer before it opens, shows
nulluntil 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 gainmeta.context_state(decided,at_load,unservable,pending),context_source,context_epoch(it goes upwhen the number a model serves changes) and
context_note.--ctx-sizeon a streamed DeepSeek bank asks for at most that number: the bank takes a smaller rung, with awarning, where
mainfailed the load. A reload asks the bank for exactly the number it gave before.(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.Model context length: N tokensis replaced byContext size of <id>: N tokens (<source>; …).because the memory limit needs the plugin's bill, which the row does not ask for.
For plugin and engine authors
Engine.context_foris appended to the engine table: whatopenwould hold, answered before it opens. The hostreads 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
opengives.LoadCtx.served_context/served_askcarry the number in, andLoadCtx.reportGrantcarries the plugin's answerout. Both are read by size, so a new plugin on an older host reads its
ctx_sizesetting as before. A plugin thatreports declares the
Caps.served_contextbit.Caps.served_context(one builtbefore this kit) is never refused. It loads, serves the context it was asked for (what
mainadvertised), and thehost 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, andturboexl3_qwen38does not stream. An outside model plugin built before this kit (for example
sushi_ds41) keeps loading under thefallback above.
sushi_ds41sizes its expert cache for 131,072 positions by default, below the context the hostadvertises for it, on
mainas 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.mdnow lists these next to--memory-preset. They are recommendations, not requirements: any pack runsunder any preset (below). The rule: the highest-bpw pack that serves a 1,032,192-token prompt at
--ctx-size 1048576under the preset's ceiling and decodes at least 50 tok/s on the standard cell (p01, p14, p21;greedy; the mean of the three).
turboderp's KLD 0.0384 against our 2.81bpw's 0.0396 (measured on different sets).
--memory-preset m5-128. No pack reaches 50 tok/s there (1.68bpwdecodes 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.
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.ceilingFlag: either flag alone, neither, and both (refused).deviceWorkingSet,staticGpuMemoryCeilingand the owner'scontextCeilingunder a forced ceiling.a forced ceiling above this Mac's Metal working set plans with the Mac's: above the device, the reading is thedevice'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 doesnot lift the load preflight's cap.
streamBudgetfollows the host ceiling: 60 GiB more ceiling gives 60 GiB more row budget in each phase. At 0 itkeeps the device's value.
Part 2 tests cover
decide/confirm/ reload, the load key over every per-model setting, the ABI read by size inboth 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 unpatchedmain:main--ctx-sizeabove a model's limit is clamped, warning names both numbersctx_sizeabove the limit refuses the loadEngine.context_foranswers before openCompatibility tests (0a9afd0):
plugin config: a plugin that streams its weights binds whether or not it reports its context. On 5ce6247, whichrefused 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 (noCaps.served_context, its grant unwritten) gets the 262,144 tokens it was askedfor 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 (
mainat 5bc670c merged, MLX v0.33.0):zig build check,python3 scripts/lint.py --strict,tests/test_plugin_abi_doc.sh: clean.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 asmain(below).memory_ceiling,preflight,hot_cache_plan,prefill_chunkandkeyOffail 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.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 asmain(below).On ebf856a (the tree with
mainat 6d602bd merged in; 8863700 after it changesdocs/cli.mdonly):tests/test_plugin_abi_doc.sh,zig build check,python3 scripts/lint.py --strict: clean.plugin config,driver:,abi plugin,served context,dsv41 bank: all pass.zig build test -Dslow-tests: 5789 of 6216 passed, 425 skipped, 2 failed. Unpatchedmainat 6d602bd on the sameMac: 5789 of 6216 passed, 425 skipped, the same 2 failed (
volumeSpaceand the DSpark rounds check, below). Theequal 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.plugin config,driver:,abi plugin,served context,dsv41 bank: all pass.zig build test -Dslow-tests: the same 2 failures asmain(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 checkandpython3 scripts/lint.py --strict: clean.zig build test -Dslow-tests: 5813 of 6240 passed, 425 skipped, 2 failed. Unpatchedmainon the same Mac failsthe 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 checkunrelated to either part.
zig build -Doptimize=ReleaseFast: builds.Live check:
--memory-preset m5-256, no--ctx-sizeDeepSeek-V4.1-Flash EXL3 2.68bpw streamed pack through CommunityServe
turboexl3_ds41, on the merged tree(5ce6247), one fresh server:
[mem] GPU ceiling forced to 245760 MiB (--memory-preset),[preflight] ... available 240.00 GB384 prompt / 384 decode slot rows per layer ... for a 262144-token contextContext size of <id>: 262144 tokens (runtime; model max 1048576; ...; mlx_bank 262144) [epoch 0]/v1/modelscontext_length262,144;context_state: decided,context_source: runtime,context_epoch0,model_max_tokens1,048,576Prompt exceeds maximum context length: 434625 tokens requested, 262144 available (the model's served context; change it with --ctx-size / --memory-preset)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 (CommunityServeturboexl3_ds41) sizes its slot rows to the 240 GiB ceiling. One 1,032,192-token request each:Any pack under any preset, no
--ctx-size: every DeepSeek-V4.1-Flash-1017 EXL3 pack under every preset and with nopreset, 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.
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:
media_load,media_jobs/plugin/engine,sdk/media/job,minimax_h3,qwen4_exp/ple_gpu;deepseek_v4.