Skip to content

fix(studio): avoid resident GGUF mappings for Windows no-reserve loads - #10618

Merged
danielhanchen merged 83 commits into
unslothai:mainfrom
Imagineer99:fix/windows-mmap-residency
Sep 14, 2026
Merged

danielhanchen merged 83 commits into
unslothai:mainfrom
Imagineer99:fix/windows-mmap-residency

Conversation

@Imagineer99

@Imagineer99 Imagineer99 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Problem

On Windows, "Don't reserve system RAM" removes the per-model None/--no-mmap choice and leaves the default mmap path. Windows cannot partially unmap the GGUF after offload, because unmap_fragment is a no-op in llama.cpp, so nearly the entire file stays resident in its mapping even after a full GPU offload. In a native Windows reproduction, a 2.99 GB GGUF stayed resident despite Task Manager showing only a small private working set.

Fixes #9033. Reproduction and loader-mode A/B evidence.

Change

Emit --load-mode dio for this policy when Windows, a confirmed full offload to a discrete GPU, and binary support for --load-mode all apply. Three parts:

Confirming the placement. The offload has to be established positively, not inferred from _weights_in_host_memory. That predicate exists to decide whether a page-lock may be skipped, so it errs towards "host resident" for a device it did not probe and stays False for an -ngl a CPU-only build accepts and ignores. Neither direction is safe for choosing a loader.

The launch asks the build instead. llama-server --list-devices is the loader's own verdict, so a CUDA build with no cudart, a HIP build with no amdhip64, a plugin renamed to disable it, a plugin built for another vendor and a plugin reachable only through GGML_BACKEND_PATH all come out right without inspecting a filename, and a pinned device the host reports but the child cannot open is caught for the same reason. The one thing ggml does not report is whether a device's VRAM is carved out of system RAM, so a Vulkan target additionally needs the existing probe to answer that every selected device is discrete. Anything unanswered declines, because an iGPU "full offload" is still host-backed. The probe runs only where its answer can reach a flag, which is Windows on a build that understands --load-mode, and once per load.

Withdrawing it when the placement changes. Under DirectIO llama.cpp does not map the file (use_mmap covers mmap / mmap+mlock / auto only), so any layer it then leaves on the CPU is an allocated buffer rather than a pageable mapping. The pair is taken back out on the three rungs that hand placement back: the --fit on retry, the arch-crash retry, and the CPU fallback replay. The --fit off retry does the reverse and applies the pair when it proves a full offload the fitted attempt did not.

Making the setting visible to the reload check. mmap and dio are both "no full host copy", so the existing (mlock, reserves_ram) state cannot tell them apart, and toggling the setting on a loaded model would silently do nothing until a manual unload. The launch records what the child runs and what a relaunch under no-reserve would run, both from one call into the real policy chain one toggle apart, and the comparator asks only whether they differ.

Explicit choices still win throughout: a per-model mmap, a hand-typed --load-mode, and an inherited LLAMA_ARG_MMAP / LLAMA_ARG_LOAD_MODE all take precedence, since no-reserve owns the reservation rather than the loader. Setting descriptions and the override notice are reworded across all twelve locales to describe the policy without promising zero host RAM.

Deliberately out of scope

The vision projector is not part of the decision. mtmd_context_params carries no use_mmap or load_mode field and clip.cpp reads the mmproj through its own ifstream into allocated buffers, so the pair says nothing about where the projector lands.

A speculative drafter pinned to the CPU does inherit --load-mode, and there is no per-model draft flag, so one setting covers both models. Keeping DirectIO trades the drafter's mapping for the main model's, which is the trade this setting exists to make.

Validation

  • 3,000 backend tests across the memory-settings, load-mode, placement, arch-gate and VRAM-budget suites.
  • Full studio/backend suite diffed against the merge base: no new failures.
  • Frontend suite: identical failing set before and after.
  • Native Windows integration test executes the original and patched policy modules and feeds their emitted flags into a b10830-mix-d5c17a0 CUDA13 server on an RTX 5070 Ti / 32 GB RAM. Stored settings and confirmed placement are fixtures: no-reserve on, keep-resident off, requested mode None.
Native policy test Before After
Effective loader mmap dio
Process working set 2.193 GiB 1.024 GiB
Dedicated GPU allocation 3.843 GiB 3.844 GiB

Both runs offload 34/34 layers of Qwen3.5-4B-MTP UD-Q4_K_XL, retain MTP, generate 16 tokens, and terminate on unload. Background RAM pressure differs between runs, so the reduction is not a fixed guarantee. Non-mapped loading still needs CPU buffers and can raise private commit while lowering resident RAM.

Remaining validation

End-to-end validation through Studio's saved settings, placement detection and UI on Windows is still outstanding; the native test covers policy output and server behaviour, not that whole path. Existing loaded models need an unload/reload. This does not address #9790's surviving process after unload.

UI evidence

Settings -> Resources -> Model Memory, driven against two isolated installs built from this PR's merge base (8ee07d6ae) and its head, with one Playwright scene run against both. "Keep model in GPU memory" is carried as a control and is byte-identical on both sides.

The row, with the one-line description:

no-reserve row, before and after

The info-icon hint, hovered. The old text promised memory-mapped loading was kept, which is the opposite of what the patched policy does on a confirmed full offload:

no-reserve hint, before and after

Before After
Description Keep no full copy in RAM. Reduce host RAM held for model weights.
Hint Stream the weights into VRAM instead of keeping a full copy in RAM. Keeps llama.cpp's memory-mapped loading and drops --no-mmap and --mlock. Skips memory-mapped loading on supported Windows builds when the model is fully offloaded to the GPU, so its pages are not held resident. Otherwise keeps memory-mapped loading. Required CPU buffers can still use RAM. Drops --no-mmap and --mlock.

The same reword is applied to all twelve locales.

@Imagineer99
Imagineer99 marked this pull request as ready for review September 9, 2026 14:46
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T12:55:47.390117Z 248cd62 Manual request
🔒 Security Review ✅ Completed 2026-09-10T00:07:58.509649Z 08137d0 New commits
ℹ️ 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[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed apply_model_memory_policy in studio/backend/core/inference/llama_server_args.py still emits nothing for the no-reserve case, so the setting has no effect on a Windows full-offload load, and the dio branch is the right place for it. You mention end-to-end validation through saved settings and placement detection is still outstanding, so let me know once that is done and I will review.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 3ddf6f7af7

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

# argv, or a stale "reserving" spends a full reload
# the running server already satisfies.
self._memory_state = resolve_effective_memory_state(
self._record_memory_state(

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 Drop managed DirectIO for the CPU-projector retry

On Windows with no-reserve enabled, if a fully offloaded vision launch fails and this recovery moves the projector into host RAM via --no-mmproj-offload, the branch strips only the fit-selected load mode and leaves the managed --load-mode dio in _cpu_projector_cmd. The surrounding code already establishes that this retry invalidates the GPU-placement memory proof; retaining DirectIO makes the CPU-resident projector use allocated, non-pageable storage rather than mmap and can substantially increase host-memory pressure or make the recovery fail. Strip the managed DirectIO pair from this copied command (without clearing the base-command record), as the --fit on and CPU-fallback retries do.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed, and it is the fourth rung of the same invariant: the block right above it already strips the fit's mode with 'it moves the projector into host RAM the fit credited to VRAM', and use_mmap covers mmap / mmap+mlock / auto only, so under dio those bytes are an allocated buffer rather than a mapping. I had covered the --fit on retry, the arch-crash retry and the CPU-fallback replay and missed this one. Now stripped with clear_record = False, matching the note there that the record must stay nameable for the fallbacks below, and the memory record is re-taken from the stripped argv.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correcting myself: I agreed with this last round and it is wrong on the same point as the round-5 projector item, so I have reverted the strip I added here.

--load-mode does not reach the projector. mtmd_context_params carries no use_mmap or load_mode field, and clip.cpp reads the mmproj through its own open_ifstream_binary into allocated buffers, so moving the projector to host RAM does not turn a mapping into a buffer: it was a buffer either way. This retry moves the projector and leaves the main model fully offloaded, which is the placement the pair was chosen for, so the pair should stay.

The block directly above it is not the precedent I took it for. It withdraws the FIT's --load-mode none because the fit's VRAM proof credited the projector to the card, which this retry voids. That is an accounting question, not a loader one.

The three rungs that keep the withdrawal all move the WEIGHTS: the --fit on retry hands placement back to llama.cpp, the arch-crash retry runs on a different device set, and the CPU replay appends --device none.

@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: f72d745005

ℹ️ 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 +23391 to +23395
_mem_gpu_offload_confirmed = bool(
not _mem_host_resident
and self._build_offers_gpu_backend(binary)
and (_detected_gpus or gpu_indices)
)

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 Exclude CPU-resident projectors from the DirectIO proof

On Windows vision loads where the main GGUF fully fits in VRAM but the auto planner has set _mmproj_cpu_pinned (or the user supplied --no-mmproj-offload), this expression still confirms full GPU offload because _mem_host_resident only classifies the main-model weights. The command later appends --no-mmproj-offload, so the projector is loaded into host memory under the managed DirectIO mode; unlike mmap, this makes its CPU-resident data an allocated, non-pageable buffer. The CPU-projector crash retry already strips DirectIO for exactly this placement, but the equivalent initial placement does not, increasing host-memory pressure and undermining the no-reserve policy.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. _mem_host_resident is the main-model answer, so a fully offloaded vision launch can still append --no-mmproj-offload and put the projector in host RAM, and use_mmap excludes dio, so those bytes are allocated rather than mapped. The asymmetry you name is exact: I added the withdrawal to the CPU-projector crash retry last round and left the identical initial placement confirming a full offload. _mem_gpu_offload_confirmed now also requires not _mem_projector_in_host_memory, built from launch_mmproj_path with _mmproj_cpu_pinned or _resolved_mmproj_offload(_mem_extra_args, _mem_env) is False, which is the same resolved helper the fit budget reads so the two cannot drift.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correcting myself: I agreed with this and it is wrong, and I have reverted the change I made for it.

The stated mechanism does not hold. --load-mode is a main-model loader setting: mtmd_context_params in tools/mtmd/mtmd.h has no use_mmap or load_mode field, and clip.cpp loads the mmproj through its own open_ifstream_binary into buffers it allocates with ggml_dup_tensor, consulting no loader mode. So the projector is an allocated host copy under mmap and under DirectIO alike, and where it lands says nothing about whether the pair is right.

What my change actually did was withhold DirectIO from the multi-GB main-model weights whenever a vision model had a CPU-pinned projector, which is precisely the resident mapping #9033 is about. Reverted in the next commit. I should have checked the loader before agreeing; the analogy I leaned on (the crash retry stripping the fit's mode) is about the fit's VRAM accounting, which the projector move really does void, not about mmap versus DirectIO.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 75b6642009

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

…rch retry agree with its own launch

Three fixes to the DirectIO gate, each one a case where a device or a
relaunch was credited with an answer nothing had given.

AMD is no longer self-evidently discrete. `_SELF_EVIDENTLY_DISCRETE` held
rocm and hip on the grounds that `_weights_in_host_memory` classifies them
upstream, but that classifier reads the driver through a ROCm torch and
`_rocm_unified_memory_gpu_ids` returns the same empty set for "no APU here"
and for "there is no ROCm torch to ask". Its own caller only skips a
page-lock, so folding the two is right there. A loader choice cannot: there
is no Windows ROCm torch wheel, so on the one platform this decision runs on
the classifier never answers, and reading that as discrete hands DirectIO to
a Strix Halo whose VRAM is system RAM -- the whole model read into allocated
host buffers, strictly worse than the mapping it replaces. A new
`_rocm_classification_answered` asks whether anything looked at the device,
and an AMD id now confirms only when something did. Same rule the Vulkan
branch already applies through `type_known`. CUDA is untouched, and where the
classifier can run a discrete Radeon confirms exactly as before.

The arch-crash retry asks residency the way its launch did. Of the three
`probe_vulkan` gates, two were widened to `_mem_should_mlock or
_mem_probe_for_dio` precisely because an unprobed Vulkan device answers the
conservative "host resident" and `_mem_should_mlock` is always False under
no-reserve. The third was left on the mlock flag alone, so on a Windows
Vulkan build that rung asked with the probe off and answered True for the
same discrete card the launch had just confirmed as a full offload.

And it records from the argv. The arm rebuilt the memory record from
`_mem_extras + _retry_managed`, which by then does not add up to `cmd` -- it
drops the managed DirectIO pair the rung above may have appended. That
recorded a mapped load for a streaming child, and the no-reserve comparator
reads `dio_applicable` with `direct_io` False as a placement needing a
reload, one the relaunch reproduces exactly. The rung 30 lines earlier states
this rule in a comment; this arm is now the argv-based form of it.
The setting descriptions promised DirectIO. Windows llama.cpp does not do
DirectIO: `llama_file::impl` there takes `use_direct_io` as `[[maybe_unused]]`
and reads through buffered `ReadFile`, and the `O_DIRECT` path is `#ifdef
__linux__`. There is no `FILE_FLAG_NO_BUFFERING` anywhere in the tree. What
`--load-mode dio` buys on Windows is the absence of the mapping, which is the
whole point of unslothai#9033, so all twelve locales and the override notice now say that
instead. Sentence structure kept identical across the locales so they stay
parallel; the `dio: "DirectIO"` label is untouched, since that is the name of
the llama.cpp mode rather than a claim about the platform.

Also condenses the comments the previous commit added, which had grown longer
than the code they explain.

Checked: python AST parses, all thirteen TS/TSX files parse via the TypeScript
compiler API, the twelve locales still define the three keys non-empty with no
interpolation placeholders, run_ruff_format leaves the Python unchanged, and the
memory / load-mode / arch-gate / placement suites are 2546 passed 0 failed.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed three fixes and a wording correction directly to this branch (ab89c159f, d00d23739). Details below, with how each was reproduced.

1. An AMD APU was confirmed as a discrete full offload, and got DirectIO

_SELF_EVIDENTLY_DISCRETE held rocm and hip, on the grounds that _weights_in_host_memory classifies AMD upstream. That classifier is _rocm_unified_memory_gpu_ids, which reads the driver through a ROCm torch and returns the empty set both for "no APU here" and for "there is no ROCm torch to ask". Only the first is a fact about the hardware.

It matters on the one platform this policy fires on: there is no Windows ROCm wheel, so on Windows the classifier never answers, and the empty set was read as "discrete". Under dio llama.cpp does not map the file, so on a unified-memory APU the whole model is read into allocated host buffers. That is a model-sized reservation, produced by the setting whose purpose is to avoid one, and strictly worse than the mmap it replaces.

Reproduced on a real Strix Halo on the AMD CI pool. Windows box DESKTOP-52OM6HM, native win32, video controller AMD Radeon(TM) 8060S Graphics:

observation before after
torch importable False False
_rocm_unified_memory_gpu_ids() [] []
_rocm_classification_answered() absent False
_gpu_offload_confirmed() True False
policy emitted --load-mode dio True False
effective DirectIO True False

The Linux half of the same pool is the control. There a ROCm torch exists (2.11.0+rocm7.13.0), _rocm_unified_memory_gpu_ids() returns [0] and positively identifies the APU, and both revisions correctly decline. So the defect is Windows-only, which is also where the feature lives.

The fix adds _rocm_classification_answered() and lets an AMD id confirm only once something has actually looked at the device. Same rule the Vulkan branch already applies through type_known. CUDA keeps its own upstream answer and is unaffected, and where the classifier can run a discrete Radeon confirms exactly as before.

2. The arch-crash retry contradicted its own launch

Of the three probe_vulkan gates in load_model, two were widened to _mem_should_mlock or _mem_probe_for_dio, with the comment at the first explaining that gating on the mlock flag alone made the DirectIO branch unreachable on a Vulkan build. The third, at the arch-crash retry, was left on _mem_should_mlock.

_mem_should_mlock is always False under no-reserve, so that rung asked the residency question with the probe switched off, and an unprobed device answers the conservative "host resident". For a discrete Vulkan card the two sites disagree:

_weights_in_host_memory(..., probe_vulkan = True)  -> False
_weights_in_host_memory(..., probe_vulkan = False) -> True

3. The same rung recorded state from parts rather than the argv

It rebuilt the record from _mem_extras + _retry_managed, which no longer adds up to cmd once the rung above has appended the managed DirectIO pair. That records a mapped load for a streaming child, and memory_state_satisfies_settings reads dio_applicable with direct_io False as a placement needing a reload, which relaunching reproduces. A permanent reload prompt.

The rung thirty lines earlier already states the rule, so this is now the argv-based form of it:

From the stripped argv, NOT rebuilt from _mem_managed + _mem_extras: by here cmd may be a fallback argv those parts no longer add up to.

4. The descriptions promised DirectIO, which Windows does not do

llama_file::impl on Windows takes use_direct_io as [[maybe_unused]] and reads through buffered ReadFile; the O_DIRECT path is #ifdef __linux__, and there is no FILE_FLAG_NO_BUFFERING in the tree. What --load-mode dio buys on Windows is the absence of the mapping, which is exactly what #9033 needs, so the twelve locales and the override notice now say that rather than naming a mechanism that does not run there. The dio: "DirectIO" label is untouched, since that is the name of the llama.cpp mode.

Worth knowing for the description: --load-mode needs llama.cpp b10105 or newer, and --mlock / --no-mmap were removed outright in b10875 (error: invalid argument, not a deprecation warning). The capability probe already lands on the right side of both, and I added tests pinning that.

Verification

  • 532 purpose-built tests over the cartesian product of [Windows, Linux, WSL, macOS] and [NVIDIA, AMD discrete, AMD APU, Vulkan discrete, Vulkan iGPU, Vulkan unknown-type, mixed CUDA+Vulkan, SYCL, OpenCL, CPU-only, unenumerable], asserting the effective loader after the full argv and environment resolve rather than searching for a dio token, against expectations written from the issue rather than from the implementation.
  • This PR's own suites: 2546 passed, 0 failed.
  • Full studio/backend suite, head against merge base: no test that passes at the base fails at the head.
  • AMD CI, real gfx1151: Linux backend suites NO_REGRESSION (2341 passed at base, 2544 at head, same two pre-existing failures at both). Windows APU differential CONFIRMED, as above.
  • Cross-platform staging CI: Playwright green across browsers, ARM64 Linux green.
  • Backwards compatibility: a pre-b10105 binary gets the legacy spellings and never --load-mode; a b10875 binary never gets --no-mmap; a _vulkan_probe.py staged by an older install emits 4 or 5 columns and reads as "type unknown", so it declines rather than guessing; an already-loaded model from before the update has no dio bookkeeping and direct_io None means "not tracked", so it is not torn down on upgrade.

One thing I did not change

_effective_gpu_selection resolves at launch against _mem_env = dict(os.environ), but the visibility mask for that launch is emitted later into the child env. With an auto-fit selection plus a user --device the two can disagree, because --device survives into the child while a mask is also emitted, so the probe enumerates the unmasked set and validates against ordinals the child will renumber. On a mixed dGPU/APU host that can classify the wrong adapter. The rung path already does this correctly by building its view with _mem_env_for(child_env); it is only the launch-time call that does not. I did not want to touch the launch path without your read on it.

Still outstanding from your side: the end-to-end check through saved settings, placement detection and the UI on Windows. The numbers above cover policy output and the classification chain, not that whole path.

Comments only, no code change: 395 added comment lines down to 249. The blocks that stay are the ones naming a mistake the next reader would otherwise make; the rest restated the code.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits September 13, 2026 12:42
unslothai#10618

The gate proved a classifier was importable and something enumerated, not that any device was read. _rocm_unified_memory_gpu_ids skips a device it cannot read, and an absent device reads as discrete, so an unreadable APU could still be handed DirectIO over its own system RAM.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 248cd62b1f

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

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

Projects

None yet

3 participants