Skip to content

Studio: price llama-server host RAM growth before pinning a spilled load - #19231

Merged
danielhanchen merged 5 commits into
mainfrom
studio-host-ram-guard
Nov 24, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-host-ram-guard

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

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 server : --cache-ram auto 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.

On an 8 GB card with 16 GB of RAM, a MoE whose weights overflow the card
was launched with --load-mode none, 4 slots and the 8192 MiB prompt cache
default. The host-side experts land in a pinned CUDA_Host buffer, and
llama-server then grows into the prompt cache, checkpoints and its own
baseline, reaching 10-11 GB and hanging the machine.

- Keep mmap unless the pinned host-side weights plus llama-server's
  post-load growth still fit available RAM and stay under a safe share of
  total RAM (50%, 40% on Windows).
- Price that growth: prompt cache (its cap, bounded by one full-context
  state per slot) plus the server baseline.
- Let _sized_cache_ram_mib lower --cache-ram below the default, down to 0,
  when the default no longer fits beside the load; detect a --cache-ram
  auto build and use it only for an unpriced launch.
- Serve one slot by default when the weights overflow every card of 12 GB
  or less into host RAM; a user-set slot count is kept.
A retry that gives up the fit's load mode now drops only a prompt cache
that was raised above the 8192 MiB default; a lowered one (or auto) is
the safe side of host RAM and carries over instead of going back to the
default. On Windows CUDA, where WDDM spills over-budget VRAM into the
same RAM, a lowered cache takes half of the room that fits.
@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-24T11:47:16.440897Z 0067da9 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.

@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: 5d594a2e08

ℹ️ 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 +17462 to +17463
per_slots = max(0, int(state_bytes)) * max(1, int(n_parallel or 1))
cache = per_slots if prompt_cache_bytes is None else min(prompt_cache_bytes, per_slots)

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 Price the prompt cache up to its configured capacity

When the configured cache exceeds one full-context state per slot, this minimum underestimates its eventual RAM consumption. The llama-server prompt cache retains historical prompts, not just one entry per serving slot; the inspected server_prompt_cache::update() also increases its token limit to use the configured memory capacity. For example, a single-slot launch with a 1 GiB state and the default 8 GiB cache is charged only 1 GiB of cache growth, although switching between unrelated conversations can fill the cache. Consequently, _pinned_load_mode_keeps() can approve non-pageable weights despite the actual peak exceeding both available RAM and the safe share. Charge the configured cache capacity rather than treating the slot count as a cache-entry 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 0067da9.

  • _llama_server_growth_bytes now prices the configured --cache-ram capacity rather than one state per slot. That capacity is Studio's sized value when it sets one, otherwise the user's flag or env, otherwise the 8192 MiB default, with auto read as 8192.
  • An unbounded cache (-1) is priced at one full-context state, because with no size cap server_prompt_cache::update keeps at most n_ctx tokens in all.
  • The peak estimate now reads the same configured value through _prompt_cache_host_bytes.
  • With the full cap priced, the Linux laptop plan estimated 9.23 GiB, so a lowered cache now takes half of the room beside the load on every platform, not only on Windows CUDA.
  • plan_drive with an 8 GB card, 16 GB RAM and 11.5 GB available:
    • Linux: --parallel 1 --cache-ram 902, mmap, estimated peak 8.35 GiB.
    • Windows: --parallel 1 --cache-ram 646, mmap, estimated peak 8.60 GiB.
    • 4 slots set by the user: --cache-ram 499, mmap, estimated peak 8.74 GiB.
  • The 24 GB + 64 GB argv is byte-identical to origin/main on Linux and Windows, with default slots and with 4 slots.
  • Four placement tests on an 8 GiB card with 12 GiB RAM now run with the prompt cache off, so the lazy table alone decides the pinned load. With the cap priced, 12 GiB cannot hold the default 8 GiB cache beside the weights.

Comment on lines +26750 to +26752
n_parallel = 1 # allow-slot-clamp: weights spill to host RAM
_effective_ubatch = _ubatch_for_slots(n_parallel)
planned_kv_unified = _kv_unified_from_args(extra_args, default = False)

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 Record the slot reduction for runtime intent matching

After this rule reduces the default four slots to one, explicitly selecting four slots in the UI can reuse the existing single-slot server instead of reloading it. Successful launches still record intent.n_parallel in _requested_n_parallel, while _runtime_matches_intent() distinguishes a default count from an explicitly chosen count only when _slots_cut_for_drafter is true. This reduction does not set that marker, so the explicit four-slot request incorrectly matches the runtime. Track this reduction in the runtime-matching state as well, so choosing Parallel Slots actually restores the requested concurrency.

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 0067da9. The small-card one-slot cut now keeps the slot count that was asked for (_host_ram_slots_asked). After the launch it commits _slots_cut_for_host_ram, the same way _slots_cut_for_drafter is committed. _runtime_matches_intent() treats either cut as a reason to reload when the intent's slot count was chosen, not defaulted, and _reset_effective_parallel_slots() clears the flag. New tests cover:

  • a launch on an 8 GB card with an 11 GiB model, where the default 4 slots are cut to --parallel 1 and the flag is set;
  • the intent matrix: an Auto request reuses the server, 4 explicit slots reload, and with no cut an explicit 4 matches;
  • the reset clearing the flag.

When I put _runtime_matches_intent back to checking only the drafter flag, two of these tests fail.

…ot cut

- llama-server's prompt cache keeps earlier prompts and raises its token
  limit until the size cap is full, so host growth is now the configured
  --cache-ram capacity (Studio's sized value, else the user's or the
  8192 MiB default), not one state per slot. An unbounded cache keeps at
  most n_ctx tokens and is priced at one full-context state.
- A lowered cache takes half of the room beside the load on every
  platform, which keeps the 8 GB + 16 GB plan's peak under 9 GiB.
- The one-slot cut for a small card is recorded like the drafter cut, so
  an explicit slot count from the UI reloads instead of reusing the
  1-slot server.
- The lazy-table placement tests turn the prompt cache off so the table
  alone decides the pinned load.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 0067da974d

ℹ️ 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".

@danielhanchen
danielhanchen merged commit f83d9da into main Nov 24, 2026
20 of 57 checks passed
@danielhanchen
danielhanchen deleted the studio-host-ram-guard branch November 24, 2026 13:15
danielhanchen added a commit that referenced this pull request Nov 24, 2026
## Problem

On runners with 16 GB of RAM, 35 llama.cpp placement tests fail across
`(Python 3.13, g-l)` and `(Python 3.13, m-r)`. The staging runs for
#19113, #19181 and #19244 all show them, for example:

```
test_llama_cpp_placement.py::test_the_moe_cache_stays_off[ram_cannot_pin_experts-]
  assert _load_mode(cmd) == "none"   (None == 'none')
Load mode: keeping mmap; pinning the host-side weights plus the 9.0 GB llama-server grows into
would hold more than 50% of the 15.3 GB of RAM, which the OS cannot page out.
```

They pass on larger runners and locally, so this only shows up on some
runners.

## Cause

#19231 (price llama-server host RAM growth before pinning a spilled
load) is correct. A pinned launch (`--load-mode none`) now also checks
that the pinned host-side weights plus llama-server's growth stay under
a safe share of total RAM. That total comes from
`_host_memory_capacity_mib()`, which reads the real `MemTotal` and the
cgroup limit.

The placement tests fake the GPUs and, where they care, the available
RAM. They never pin the total, so each launch decided against whatever
machine ran it. Reproduced locally by stubbing
`_total_system_memory_mib` to 15667 MiB: 35 failed, 770 passed in the
three files below.

## Fix

- `test_llama_cpp_placement.py` gets an autouse fixture,
`_pinned_host_ram`. It pins `LlamaCppBackend._total_system_memory_mib`
to 256 GiB and `_cgroup_memory_limit_mib` to `None`, so every launch
sees the same host on any runner.
- `test_lookup_table_fit.py` and `test_prompt_cache_sized_to_context.py`
launch through that file's helpers, so they import the fixture.
- Tests that are about host RAM still set their own total in the test
body, which overrides the fixture.

## Verification

- The three files on this branch: 805 passed.
- With the host forced to 15.3 GB (a plugin stubbing
`_total_system_memory_mib`): 805 passed on this branch, and 35 failed on
main.
- All 34 test files that import `test_llama_cpp_placement`: 2365 passed
and 24 skipped.
- One test failed:
`test_cached_gguf_routes.py::test_pipeline_class_guard_passes_every_shipped_family`.
- It fails identically on main, because this host has diffusers
0.41.0.dev0 and the test needs 0.42.0. It is unrelated to this change.
Hubert9204 pushed a commit to Hubert9204/Ganjalf-Studio that referenced this pull request Nov 24, 2026
…-11-23..25)

Merge of unslothai/unsloth main 2e1afd5..bd1ddf2. No textual conflicts; audited for
Ganjalf invariants (Claude API alignment, thinking budget, Qwen thinking presence 0,
check_page, guards, plugins/hooks/run_agent stop, branding via messages.ts, Ganjalf updater):
all intact.

Taken: llama.cpp/GGUF fixes (thinking budget counted with the real template unslothai#19143, native
prompt count in context fit unslothai#19159, host RAM growth priced before pinning unslothai#19231, second quant
of a loaded repo unslothai#19169, small Auto context on low-RAM CPU hosts unslothai#19142), security and
stability hardening (media bytes checked, remote-code gate, sandbox cache, managed accounts,
IPv6 loopback listeners), chat fixes (Files menu, deleted turns from other tabs, composer,
tool approvals tied to their tool), MCP, chat templates (phi-3, mistral), training/core
kernels, installer AMD/ROCm mixed hosts, Tauri security bumps, unsloth-zoo>=2026.11.11.
Branding stays Ganjalf (upstream strings are rebranded at runtime by i18n/messages.ts).

Ganjalf follow-up: the thread sampling simulation oracle expects presence 0 for Qwen
3.5/3.6 with thinking (non-thinking 1.5), as the chat table does since 369d05c.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EVYBhJeMQGvLT6Ka4nMMUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant