Skip to content

server : --cache-ram auto - #429

Open
danielhanchen wants to merge 6 commits into
base/upstream-f5e6915c2from
server-cache-ram-auto
Open

danielhanchen wants to merge 6 commits into
base/upstream-f5e6915c2from
server-cache-ram-auto

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds --cache-ram auto (also LLAMA_ARG_CACHE_RAM=auto). It sizes the host prompt cache from the RAM that is still available after the model and the context are loaded, and logs the chosen size. The default stays 8192 MiB, and explicit N, -1 and 0 behave exactly as before.

This is a pin branch on upstream b12651 (f5e6915c2). The diff is additive: one new option value, two helpers in server-common, one sizing block in load_model, and tests. It merges cleanly onto the current pin set (53c976b17, last pin #421) and onto ggml-org master (b12f22d2f).

Why

A user reported that Unsloth Desktop hangs their whole laptop when it serves Inkling-2-Mini UD-IQ3_XXS on an 8 GB VRAM + 16 GB RAM machine. VRAM is not the problem: it stays under 8 GB on every build with --fit. Host RAM is. We reproduced it on a larger host with an 8 GB VRAM cap and a cgroup RAM limit:

  • Studio launched with --load-mode none. That put 6.2 to 7.2 GB of CPU expert weights into a CUDA_Host buffer (cudaMallocHost), which cannot be paged out.
  • Over a few chats, llama-server then grew from about 7 GB to 10 to 11 GB RSS. The growth came from context checkpoints (164 MiB each), speculative decoding state, and the host prompt cache, whose 8192 MiB default does not depend on how much RAM the machine has.
  • Under MemoryMax=9G the server was killed (rc -9).

The prompt cache is the one large growth term with a fixed size. On a 16 GB machine, 8192 MiB is half of RAM. Before this change, a caller that wanted a cache sized to the host had to work out the available RAM itself, before the model was loaded, without knowing how much host memory the load would take. With --cache-ram auto the server does that sizing after the load.

The Studio side of the fix (keep mmap when pinning would hold too much RAM, price the server's growth, lower --cache-ram, one slot when the weights overflow a small card) is a separate unslothai/unsloth PR. It probes for --cache-ram N|auto in --help and fails closed on builds without it.

The rule

cache_mib = min(8192, (available - max(2 GiB, total / 8)) / 4)
            0 if that is below 256 MiB
            8192 if host RAM cannot be read
  • available:
    • Linux: the tighter of MemAvailable and the cgroup headroom. The headroom is memory.max and memory.high minus memory.current, taken over this cgroup and every ancestor; cgroup v1 uses memory.limit_in_bytes.
    • Windows: GlobalMemoryStatusEx.
    • macOS: free + inactive + purgeable pages.
    • With mmap (--load-mode auto or mmap), the host-side weights from the memory breakdown are subtracted from the system figure first. Mapped weights sit in the page cache, which counts as available but has to stay resident. They are not subtracted from the cgroup headroom, because memory.current already charges the pages this cgroup faulted in.
  • total: physical RAM, or the cgroup limit when that is lower.
  • reserve max(2 GiB, total/8): room for the OS and the desktop.
  • a quarter of the rest: the prompt cache is not the only thing that grows after load. Checkpoints, speculative state and the HTTP layer also need room.
  • cap 8192: auto never raises the cache above today's default. On a big host it picks exactly what the default already does.
  • floor 256 MiB: a smaller cache cannot hold a useful saved state, so the cache is turned off and --cache-idle-slots is disabled with it, exactly as with --cache-ram 0.
  • Decision models: they keep their default of no cache under auto. Only an explicit N turns the cache on for them.

The size is computed again on every load_model, including a resume from sleep, and it is logged at info level:

load_model: --cache-ram auto: prompt cache size limit 693 MiB (host RAM: 4821 MiB available, 12288 MiB total, 0 MiB of mmap-ed weights not counted as available)

Why auto is not the default

The default stays 8192 and auto is opt-in:

  • On big hosts auto already resolves to 8192, so making it the default would only matter on small and mid hosts. There, it would change the cache size for every existing user and script of the prebuilt, not only Studio.
  • The available-RAM reading is a snapshot taken at load time. It depends on what else is running at that moment, so a default built on it would not be reproducible from one launch to the next.
  • Upstream documents 8192 as the default, and keeping the fork's default equal to upstream keeps this pin a pure addition.

Studio passes an explicit integer when it has priced the load itself, and auto when its placement failed and nothing was priced.

Before and after

The before column is the existing behaviour, which was also checked on this branch with --cache-ram 512 and with no flag. All runs are a CPU build in a systemd scope with MemoryMax and no swap. The model is LFM2.5-24B-A2B UD-IQ2_XXS (7.0 GB of host weights) on the b12651 base. The last two rows use Inkling-2-Mini UD-IQ3_XXS on the pin set plus this branch.

Model, limit, load mode Before (default) After (--cache-ram auto)
LFM2.5, no cgroup limit, mmap 8192 MiB 8192 MiB (big host, unchanged)
LFM2.5, MemoryMax=16G, mmap 8192 MiB 3456 MiB
LFM2.5, MemoryMax=12G, mmap 8192 MiB 2414 MiB
LFM2.5, MemoryMax=16G, --load-mode none 8192 MiB 1717 MiB
LFM2.5, MemoryMax=12G, --load-mode none 8192 MiB 693 MiB
LFM2.5, MemoryMax=10G, --load-mode none (4.8 GB left after load) 8192 MiB 0 (disabled)
Inkling-2-Mini IQ3_XXS, no limit, mmap 8192 MiB 8192 MiB
Inkling-2-Mini IQ3_XXS, MemoryMax=16G, mmap 8192 MiB 2850 MiB

With an explicit value the old behaviour is untouched. --cache-ram 512 logs prompt cache is enabled, size limit: 512 MiB, and no flag logs 8192 MiB.

Tests

  • test-server-component gets a new cache_ram_auto case with 10 assertions. It covers an unknown host, big hosts capped at 8192, a 16 GB laptop with pinned weights, the total/8 reserve on 32 GB, the 256 MiB floor at its edge, and nothing free.
  • test-arg-parser: --cache-ram auto sets cache_ram_auto and leaves cache_ram_explicit off, so decision models keep the cache off. 512, -1 and 0 stay explicit sizes, and lots is rejected.
  • llama-gen-docs regenerates tools/server/README.md and tools/cli/README.md byte-identical to the committed rows.
  • Both tests pass on this branch (CPU build) and on the pin set 53c976b17 with this branch merged on top (CPU build).

Not covered

  • Only Linux was run. The Windows (GlobalMemoryStatusEx) and macOS (host_statistics64) branches compile only on those platforms, so the nightly legs are their first build.
  • On Linux, when another cgroup already holds the mapped weights in the page cache, they are not charged to this cgroup. The headroom can then be larger than what this process could use if those pages were evicted and faulted back in.
  • The cgroup headroom counts page cache charged to this cgroup as used. After a --load-mode none load under a memory limit, the model file's pages are charged to the server's cgroup, so auto can see almost nothing free and pick 0 even when several GB could be reclaimed. That errs on the safe side. Subtracting inactive_file from memory.stat (as docker and kubelet do) would fix it, but it interacts with the mmap subtraction, so it is left for a follow-up.
  • available is read once per load (and again on wake from sleep). A later spike from another program is not tracked: the cache keeps the size it was given.

Size the host prompt cache from the RAM available after the model and
the context are loaded: min(8192, (available - max(2 GiB, total/8)) / 4)
MiB, 0 below 256 MiB, 8192 when host RAM cannot be read. Linux takes the
tighter of MemAvailable and the cgroup headroom (memory.max and
memory.high of this cgroup and its ancestors), Windows uses
GlobalMemoryStatusEx and macOS host_statistics64. With mmap the host
weights live in the page cache, which counts as available, so they are
subtracted first. The chosen size is logged.

The default stays 8192 and explicit N, -1 and 0 are unchanged; auto
keeps the decision-model default of no cache.
… only

The cgroup headroom already charges the page cache this cgroup faulted
in, so subtracting the weights from it as well counted them twice.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T15:56:57.548524Z 65a6d3f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cdd7405972

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}
}
const server_host_memory mem = server_get_host_memory(host_weights);
params_base.cache_ram_mib = server_cache_ram_auto_mib(mem.avail, mem.total);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset the existing prompt cache when auto resolves to zero

When a server using --cache-ram auto wakes from sleep with less available RAM, this calculation can change a previously positive cache limit to zero. However, destroy() leaves prompt_cache alive, and the following zero-size branch only logs that caching is disabled. Since init() is skipped on resume, cache_idle_slots also remains enabled. Requests therefore continue using the old cache and its previous limit precisely when auto-sizing determined that no cache fits. Clear the existing cache and update the idle-slot caching state when the recomputed limit is zero.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48d237d. On a reload (is_resume), the auto block now calls server_cache_ram_auto_reload. It drops the old prompt_cache and sets cache_idle_slots to the value first asked for, and only when the new limit is not 0. load_model then builds a new cache at the new size when the limit is not 0, so a changed limit also resizes it. The first load keeps the --cache-idle-slots value that was asked for, because init() turns it off at 0 and does not run again on a reload. A new cache_ram_auto_reload case in test-server-component covers three steps: a limit that drops to 0, a later reload with room again, and idle slots that were never asked for. I also ran the server live with --sleep-idle-seconds 3 under a cgroup limit: it went to sleep, a request woke it, and the cache was sized again on the reload.

Comment thread tools/server/server-common.cpp Outdated
Comment on lines +2471 to +2475
const std::filesystem::path dir = std::filesystem::path("/sys/fs/cgroup/memory") / std::filesystem::path(v1_path).relative_path();
int64_t limit = 0;
int64_t usage = 0;
if (read_i64((dir / "memory.limit_in_bytes").string(), limit) && read_i64((dir / "memory.usage_in_bytes").string(), usage)) {
consider(limit, usage);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check ancestor limits for the cgroup v1 memory controller

On cgroup v1 systems where a parent group imposes the memory limit and the process's leaf group has no local limit, reading only the leaf returns unknown headroom and ignores the effective constraint. An isolated fixture using this helper with an unlimited child and a parent limited to 4 GiB with 3 GiB usage returned -1 instead of 1 GiB. Consequently, --cache-ram auto can size against host RAM and select a cache larger than the group's remaining allowance. Walk the v1 ancestors as the v2 branch already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48d237d. v1 now walks from this process's cgroup up to the root of the memory hierarchy, the same as v2. It reads memory.limit_in_bytes and memory.usage_in_bytes at each level and keeps the smallest headroom and the smallest limit. The "no limit" value near INT64_MAX is ignored. In the new cgroup_headroom test, the leaf has no limit and the parent has a 2 GiB limit, and the test checks that the parent's limit is used.

Comment thread tools/server/server-common.cpp Outdated
}
dir = dir.parent_path();
}
} else if (!v1_path.empty()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back to v1 when the unified hierarchy lacks memory accounting

On hybrid cgroup systems, /proc/self/cgroup can contain both a 0:: entry and a separate v1 memory entry. The presence of v2_path unconditionally selects the unified hierarchy, even when memory is controlled exclusively by v1, so the else if prevents reading the actual memory limit. An isolated fixture with both entries and a finite v1 limit returned unknown headroom. Select the hierarchy that exposes the memory controller, or fall back to v1 when v2 memory accounting is unavailable, so auto-sizing respects the process's limit.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48d237d. The kernel binds a controller to one hierarchy only. So when a v1 line in /proc/self/cgroup lists memory, the v1 hierarchy is used. Otherwise the 0:: (v2) path is used, and a v1 line without memory (for example cpu,cpuacct) does not count. The parsing now takes the /proc/self/cgroup text and the mount root as arguments, so the fixture tests can drive it. These cases cover a hybrid layout with a tighter v2 tree that has to be ignored, a v1 line without the memory controller, and no limit or no cgroup at all.

Comment thread tools/server/server-context.cpp Outdated
Comment on lines +1626 to +1627
// mmap-ed weights sit in the page cache, which counts as available but has to stay resident,
// so they are not free room for the cache (weights held in host buffers already are not available)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep comment sentences on a single line

The new explanation splits one sentence across two comment lines. The repository's AGENTS.md explicitly prohibits splitting sentences across lines and hard-wrapping comments. Join this sentence onto one line, and apply the same correction to the new split comment in server-common.h.

AGENTS.md reference: AGENTS.md:L84-L84

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48d237d. Each comment sentence is now on one line. This covers the two you flagged and the sizing comment in server_cache_ram_auto_mib.

Comment thread tools/server/server-context.cpp Outdated
Comment on lines +1629 to +1632
if (params_base.load_mode == LLAMA_LOAD_MODE_AUTO || params_base.load_mode == LLAMA_LOAD_MODE_MMAP) {
for (const auto & row : common_memory_breakdown_rows(ctx_tgt)) {
if (row.kind == common_memory_breakdown_row::HOST) {
host_weights += (int64_t) row.model;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the resolved loading mode before subtracting host weights

With --load-mode auto and a backend that does not support mmap, such as Vulkan on an integrated GPU or OpenCL, llama_model_base::load_tensors() disables ml.use_mmap without changing params_base.load_mode. This condition still treats the host weights as file-backed and subtracts them from available RAM, although their allocated buffers have already reduced that figure. For a partially offloaded model with 7 GiB of host weights and 6 GiB genuinely available on a 16 GiB host, this incorrectly disables the prompt cache instead of selecting 1024 MiB. Determine whether the weights are actually mmap-backed rather than inferring it from the requested AUTO mode.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48d237d. The new server_model_uses_mmap(model, load_mode) uses the loader's own rule:

  • If llama_supports_mmap() is false, there is no mmap.
  • mmap means mmap.
  • auto means mmap only when every device of the model reports caps.mmap_support. This is the same check llama_model_base::load_tensors makes, through llama_model_n_devices / llama_model_get_device. So Vulkan iGPU and OpenCL loads, where auto falls back to reading the weights in, no longer have their host weights subtracted.
  • none, mlock, mmap+mlock and dio never subtract them.

- size from the resolved mmap state: load_mode auto turns mmap off when a
  device of the model has no mmap support, as load_tensors does
- on a reload after sleep, drop the old prompt cache and make idle-slot
  caching follow the new limit (off at 0, back on when asked for)
- cgroup v1: walk the ancestors for memory.limit_in_bytes, as for v2
- hybrid cgroups: use the hierarchy that holds the memory controller
  (v1 when a v1 line lists it, else v2)
- one sentence per comment line
- tests: cgroup v1/v2/hybrid fixture trees and the reload helper
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48d237d115

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1641 to +1642
const server_host_memory mem = server_get_host_memory(host_weights);
params_base.cache_ram_mib = server_cache_ram_auto_mib(mem.avail, mem.total);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release the old prompt cache before measuring RAM on resume

When resuming after the prompt cache has accumulated states, destroy() leaves those allocations alive, so this memory measurement includes the old cache even though server_cache_ram_auto_reload() immediately discards it afterward. This can disable caching without any increase in external memory pressure: on a 16 GiB host, 3 GiB of available RAM initially selects 256 MiB, but populating that cache makes the resume calculation select zero; releasing it restores enough RAM for the original 256 MiB limit. Reset the old cache before sampling available memory so the replacement limit is not reduced by allocations that are about to disappear.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 20ee3db. On a reload after sleep, the auto block now releases the old prompt_cache before it samples host RAM. The new limit therefore no longer counts the cache it is about to replace. After sizing, server_cache_ram_auto_reload sets idle-slot caching from the new limit as before, and load_model builds the new cache when the limit is not 0. I checked this live: under a 16G cgroup with 2 slots, --sleep-idle-seconds 4, and two chats to fill the cache, the server slept, woke on a request and served it. The size it logged after waking (3448 MiB) was within a few MiB of the first load's (3451 MiB).

Comment thread tools/server/server-context.cpp Outdated
Comment on lines +1634 to +1637
if (server_model_uses_mmap(model_tgt, params_base.load_mode)) {
for (const auto & row : common_memory_breakdown_rows(ctx_tgt)) {
if (row.kind == common_memory_breakdown_row::HOST) {
host_weights += (int64_t) row.model;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include mmap-backed draft weights in the RAM adjustment

On Linux with a separate mmap-backed draft model whose weights reside on the CPU, this loop accounts only for ctx_tgt. The draft model is already loaded into model_dft/ctx_dft, but its file-backed pages remain included in MemAvailable, just like the target model's mapped weights. Consequently, a GPU-offloaded target paired with a substantial CPU draft can receive a cache limit based on RAM that the draft needs to remain resident, causing weight eviction and inference slowdown as the cache fills. Include the separate draft model's mmap-backed host weights in this adjustment, while avoiding double-counting shared MTP weights.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 20ee3db. A separate draft model's mmap-ed host weights are now taken off available RAM along with the target's. The check is the same server_model_uses_mmap on the draft model, and the bytes come from the HOST row of ctx_dft's memory breakdown. An MTP draft has no model of its own (spec_init->model() is null and its context runs on the target model), so it is skipped and the target's weights are counted only once. A draft that the server drops because speculative decoding did not initialize is also skipped, because the server clears model_dft before sizing. test-server-component has no model to load, so I checked this live: a CPU run with -md and --spec-type draft-simple logged 13889 MiB of mmap-ed weights (target 6944 plus draft 6944), and the same run without a draft logged 6944.

…draft weights

- on a reload after sleep, release the old prompt cache before host RAM
  is sampled, so the new limit does not count the cache it replaces
- take a separate draft model's mmap-ed host weights off available RAM
  too; an MTP draft context runs on the target model and is not counted
  twice
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 20ee3dbc4c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tools/server/server-common.cpp Outdated
Comment on lines +2459 to +2460
const std::filesystem::path base = v1_memory ? std::filesystem::path(root) / "memory" : std::filesystem::path(root);
const std::filesystem::path rel = std::filesystem::path(v1_memory ? v1_path : v2_path).relative_path();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve the actual cgroup mount before reading memory limits

On hybrid Linux systems where memory is controlled by v2 mounted at /sys/fs/cgroup/unified and other controllers use v1, this base path points outside the unified hierarchy. server_get_host_memory() always passes /sys/fs/cgroup, so all memory-accounting reads fail and auto-sizing silently falls back to host RAM, potentially exceeding the process's memory allowance. An isolated fixture with this layout, a 4 GiB limit, and 3 GiB usage returned unknown headroom instead of 1 GiB. Resolve the hierarchy's mount point and mount root from /proc/self/mountinfo before walking its ancestors.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3de20ee. server_cgroup_headroom now also reads /proc/self/mountinfo. It finds the mount that holds the memory controller: cgroup2 for v2, or a cgroup mount whose options list memory for v1. It then walks from that mount point, so v2 at /sys/fs/cgroup/unified on a hybrid system is found. When the mount root is not / (a container that sees its own cgroup at the mount point), that root is removed from the /proc/self/cgroup path first. If there is no such mount, the old /sys/fs/cgroup (v2) or /sys/fs/cgroup/memory (v1) path is still used. New cgroup_headroom cases cover v2 at unified with a 4 GiB limit and 3 GiB used (now 1 GiB), and a v1 container mount root. With the mountinfo lookup turned off, both cases fail.

Comment thread tools/server/server-common.cpp Outdated
status.dwLength = sizeof(status);
if (GlobalMemoryStatusEx(&status)) {
mem.total = (int64_t) status.ullTotalPhys;
mem.avail = std::max<int64_t>(0, (int64_t) status.ullAvailPhys - page_cache_bytes);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid subtracting resident mmap weights twice on Windows

On Windows with CPU-resident mmap-backed weights, the default warmup in common_init_from_params() accesses the weights before this measurement, bringing their pages into the process working set. Unlike Linux's MemAvailable, ullAvailPhys counts standby, free, and zero-list pages, not pages currently in a working set. Subtracting the entire mapped host-weight size therefore counts the resident weights twice and can unnecessarily disable caching: a 16 GiB host with 7 GiB of resident mapped weights and 6 GiB available resolves to zero instead of 1024 MiB. Use Windows-specific accounting that subtracts only mapped pages actually included in the available-memory figure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3de20ee. ullAvailPhys counts only the standby, free and zero lists. Mapped pages in the working set are not in it, so on Windows the mmap-ed host weights are no longer subtracted from it. After warmup the CPU weights are in the working set, so the 16 GiB host in your example with 6 GiB available now gets 1024 MiB. Mapped pages that were trimmed to the standby list are still counted as available. That is a small overcount, and the cache limit is a quarter of the headroom above the reserve. Linux and macOS are unchanged.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 24, 2026
…oad (unslothai#19231)

## Summary

A user reported that Unsloth Desktop hangs the whole laptop when serving
Inkling-2-Mini `UD-IQ3_XXS` on an 8 GB VRAM + 16 GB RAM machine. VRAM is
not the problem: it stays under 8 GB on every build. The problem is host
RAM.

On that hardware Studio's default plan is Auto context 8K, 4 slots with
`--kv-unified`, `--fit on` and `--load-mode none`. `--load-mode none` is
picked because the fit check sees about 10.5 GB of RAM available and
decides the load fits without paging. With a CUDA build, though, `none`
puts the 6.2 to 7.2 GB of expert weights that overflow the card into a
`CUDA_Host` buffer (`cudaMallocHost`), and the OS cannot page that out.
After a few chats llama-server then grows from about 7 GB to 10 to 11 GB
RSS:

- the host prompt cache (`--cache-ram` defaults to 8192 MiB, and
`_sized_cache_ram_mib` could only raise it);
- context checkpoints (164 MiB each, per slot);
- speculation state and the server's own baseline.

None of that growth was priced when the load mode was chosen. Under a
`MemoryMax=9G` cgroup the reported plan gets killed (rc -9). On a real
laptop it pushes the desktop into swap until the machine stops
responding.

## Changes (studio/backend/core/inference/llama_cpp.py)

1. **Pinned-memory guard.** A `--load-mode none` verdict is kept only if
two checks pass. First, the fit must still hold once llama-server's
post-load growth is added. Second, the host-side weights plus that
growth must stay under a safe share of total RAM: 50% (0.5) by default
and 40% (0.4) on Windows. If either check fails, the load keeps mmap,
whose weight pages the OS can evict. The 50% comes from the measurements
below: a 7.7 GB peak (49% of 16 GB) ran, while 10 to 11 GB (63 to 70%)
hung the machine. CPU-only loads skip the share check because they pin
nothing. Apple Silicon is unchanged because the fit already abstains
there.
2. **Price llama-server's host growth.** The new
`_llama_server_growth_bytes` term prices the prompt cache at its
configured `--cache-ram` capacity (Studio's sized value, else the user's
or the 8192 MiB default), because llama-server's cache keeps earlier
prompts and raises its token limit until the size cap is full. An
unbounded cache (`-1`) keeps at most `n_ctx` tokens and is priced at one
full-context state. The server baseline (`_LLAMA_SERVER_HOST_MIB`) is
added, and checkpoints were already in the host-only term. The guard
above uses this growth term. Studio also logs an estimated llama-server
peak host RSS.
3. **Lower `--cache-ram` when host RAM is tight.** When the 8192 MiB
default no longer fits beside the load, `_sized_cache_ram_mib` now
returns half of the room that fits beside the load, down to 0. The cache
fills to its cap, and the other half absorbs what the fit does not
price: the desktop, the browser, and on Windows CUDA the WDDM sysmem
fallback. Anything below 256 MiB becomes 0, because a cache that small
cannot hold a useful state. If the load does not fit even with no cache,
it is paging anyway, and the default is kept as before. The help probe
also detects `--cache-ram N|auto` (the `auto` value is
unslothai/llama.cpp#429) (`supports_cache_ram_auto`, same mechanism as
`supports_moe_cache_auto`). Studio passes `--cache-ram auto` only when
its own placement threw and nothing was priced. In every other case it
passes its own integer, which is deterministic and works on every build.
Upstream builds fail closed and never see `auto`.
4. **One slot by default when the weights overflow a small card.** The
cut is recorded for runtime intent matching, like the drafter's slot
cut, so a later request for an explicit slot count reloads instead of
reusing the one-slot server. This applies when the weights alone exceed
the free VRAM of every discrete card and no card is larger than 12 GB.
The slot count drops from the default to 1, because each extra slot adds
checkpoints and a saved prompt state in host RAM, not VRAM. It only
happens when the slot count came from the default: a slot count set in
the UI or in the extra arguments is left alone.
5. **Retries keep a lowered cache.** A retry that gives up the fit's
load mode (the `--flash-attn off` respawn, the `--fit on` retry after an
optimistic `--fit off`, the projector-on-CPU retry, the CPU fallback)
used to strip Studio's `--cache-ram` along with `--load-mode none`,
which sent the relaunch back to the 8192 MiB default. It now strips only
a cache that was raised above the default. A lowered one, or `auto`, is
the safe side of host RAM and carries over.

Big hosts are unchanged. The planner argv for the same model on a 24 GB
card with 64 GB RAM is byte-identical before and after, on Linux and
Windows, with default slots and with 4 slots.

## Plan before and after (planner driven with a mocked 8 GB card and 16
GB host, the real GGUF and a b12649 llama-server)

| | Before | After |
|---|---|---|
| Linux, 11.5 GB available | `--parallel 4 --kv-unified -c 8192
--ctx-checkpoints 2 --load-mode none`, cache 8192 (default) |
`--parallel 1 -c 8192 --ctx-checkpoints 6 --cache-ram 902`, mmap |
| Windows, 11.5 GB available | same as Linux | `--parallel 1 -c 8192
--ctx-checkpoints 6 --cache-ram 646`, mmap |
| Slots set to 4 by the user | `--parallel 4 ... --load-mode none` |
`--parallel 4 ... --cache-ram 499`, mmap |
| 24 GB card, 64 GB RAM, Linux, 4 slots | `--parallel 4 -c 295936
--cache-ram 13168 --load-mode none` | identical |

Studio's estimated llama-server peak for the new Linux plan is 8.35 GiB
and for the Windows plan 8.6 GiB. With 4 slots set by the user, the
Linux plan estimates 8.74 GiB. With mmap, about 6 GiB of that is
evictable file-backed weights.

## Measured (llama-server b12649, 8 GB VRAM cap, systemd scope with
MemoryMax and no swap, 4 concurrent chats of 1500 prompt + 64 generated
tokens)

| | Before (Studio default plan) | After (new plan) |
|---|---|---|
| MemoryMax=9G | **killed (rc -9)** | runs, cgroup peak 8.1 GB |
| MemoryMax=12G, cgroup peak | 10.5 GB, all pinned or anonymous | 8.1
GB, mostly evictable file pages |
| MemoryMax=12G, anonymous RSS peak | 3.7 GB on top of 6.6 GB pinned |
3.0 GB, nothing pinned |
| VRAM peak | 7206 MiB | 7138 MiB |
| Decode tok/s, 4 concurrent chats | 6.7 to 8.0 | 13.7 to 30.1 |
| Decode tok/s, single chat | 18.8 | 23.9 |

These runs emulate the laptop on a larger host, using a VRAM cap shim
and a cgroup RAM limit.

Re-run (same harness, `MemoryMax=9G`, 4 concurrent chats) with the Linux
plan at `--cache-ram 1804` (fit target 1097), twice the 902 MiB the
final head emits, and the Windows plan (`--cache-ram 646`, fit target
1609) both finished with rc 0. Anonymous RSS peaked at 2.9 GB (Linux)
and 1.9 GB (Windows), with VRAM peaks of 7100 and 6690 MiB. Decode speed
in that run is not comparable to the table above because the GPUs were
shared with other jobs at the time.

## Tests

- New `studio/backend/tests/test_host_ram_growth_guard.py` (25 cases)
covers:
  - growth pricing;
  - the reported laptop keeping mmap;
  - big hosts keeping `none`;
  - the Windows share;
  - growth that no longer fits available RAM;
  - CPU-only loads;
  - the peak estimate;
- the one-slot rule matrix (small card, weights fit, card above 12 GB,
two small cards, user-set slots, shared memory, Apple Silicon);
- `auto` pricing and the `--cache-ram auto` help probe (no flag,
upstream, fork);
  - another server's `auto` cap.
- `test_prompt_cache_sized_to_context.py`: a host without room for the
default now gets a lowered cache rather than the default. Added cases
for turning the cache off, for a load that pages anyway keeping the
default, and for a lowered cache being recorded for the retry rungs.

## Not covered

- Windows WDDM was not tested on real hardware. Its 40% share is a
design choice, not a measurement.
- The MoE expert cache (`--moe-cache-mib`) still prices pinned experts
against available RAM only, not against the safe share.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3de20ee0f9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tools/server/server-common.cpp Outdated
Comment on lines +2560 to +2561
mem.avail = (int64_t) (vmstat.free_count + vmstat.inactive_count + vmstat.purgeable_count) * (int64_t) page_size;
mem.avail = std::max<int64_t>(0, mem.avail - page_cache_bytes);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid subtracting active mmap weights twice on macOS

On macOS with CPU-resident mmap-backed weights, pages accessed during warmup can be on the active queue, which this availability calculation already excludes. Darwin reports active and inactive pages separately in its host statistics implementation. Subtracting the entire host-weight size again therefore understates available RAM and can unnecessarily disable caching: a 16 GiB host with 7 GiB of active mapped weights and 6 GiB in the counted available queues resolves to zero instead of 1024 MiB. Adjust only for mapped weights actually included in the counted reclaimable pages, rather than deducting their full size.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 65a6d3f. Same reasoning as the Windows case: free + inactive + purgeable leaves out the active queue, where the mapped weights sit after warmup, so the macOS branch no longer takes the host-weight size off that figure. Mapped pages that age back to the inactive queue are counted as available, a small overcount. Linux still subtracts, since MemAvailable includes reclaimable file pages. The startup log now says the weights are taken off on Linux only.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 65a6d3f7d1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant