Skip to content

Studio: use --load-mode none when the model fits without paging - #9565

Merged
danielhanchen merged 28 commits into
mainfrom
studio-load-mode-none-when-it-fits
Aug 26, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
studio-load-mode-none-when-it-fits

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Studio now picks --load-mode none directly whenever the model fits, and leaves llama.cpp's own auto in place otherwise.

Why

--load-mode maps to use_mmap in llama-model-loader.cpp: auto / mmap / mmap+mlock turn mmap on, none and dio turn it off. The interesting part is what that does to the loader:

  • With mmap on and a discrete GPU, buffer_from_host_ptr is unsupported, so the mmap-backed-buffer branch never fires and every tensor takes a synchronous ggml_backend_tensor_set out of a page-faulting mapping. No pinning, no pipelining.
  • With mmap off, upload_backend is constructed (it is gated on use_mmap being false), giving chunked reads into 4 x 64 MiB pinned host buffers with double-buffered async uploads to the GPU.

mmap earns its keep by demand-paging a footprint the machine cannot hold. A load that fits does not need it. So the rule is simply: if it fits, take none; if it does not, keep auto, where the mapping is what stops an over-committed load from being killed outright.

Measured, though, none is not the fast one. See the verification comment below for the numbers: dropping mmap does unlock the async uploader, but none still reads through the page cache and pays that copy, and on local NVMe that costs slightly more than the uploader wins. dio takes the same uploader and skips the page cache, and on a 17 GB MoE it is 2.4x faster cold. The picked mode is a single constant, _FIT_LOAD_MODE, kept at none as asked; switching it is one line.

What "fits" means

_fits_without_paging answers it, next to the existing host-RAM guards:

  1. Price the whole footprint: weights, a CPU-pinned projector, KV at the effective context, the MTP reserve, the flat and context-linear compute buffers, and the soft overhead. The refusal guards next door deliberately price weights only, because understating there can only fail to refuse a load that would have worked. Here the bias runs the other way, so every term the launch knows about is charged.
  2. Compare against free VRAM on the devices the launch actually pins. Fits, done.
  3. Otherwise compare the spill against available system RAM, less the same 2 GiB headroom _host_offload_shortfall_message keeps free.

Shared iGPU memory is dropped from the VRAM term and carried by the RAM term, so it is never counted on both sides. That is the same split _launch_host_shortfall_message already uses. gpus is used rather than _detected_gpus, so a launch the arch gate forces onto --device none gets no credit for VRAM the child never reaches.

Two cases abstain and keep auto: an unsized KV cache (the estimator returns 0 without the GGUF dims, and a 0 KV term on a long-context load is exactly the missing term that would turn a paging load into none) and unreadable host RAM. The verdict is bound before the placement try like the other verdict flags, so the --fit on except path cannot hit an UnboundLocalError, and a failed fit proves nothing either way.

Precedence

Unchanged, and still in one place. The fit only fills in for a model with no pick of its own:

  • an explicit per-model load mode beats the fit
  • the Model Memory settings beat both, exactly as the Run settings panel says
  • a hand-typed flag in the extras still wins by last-arg, because the managed block is emitted ahead of them

Tests

New studio/backend/tests/test_load_mode_fit.py, 12 cases pinning the predicate: VRAM-only fit, pooled fit across cards, spill that fits in RAM, spill that does not, the headroom boundary, abstention on unknown RAM and on an unsized footprint, shared-iGPU double counting, unpinned cards holding nothing, and a probe reporting negative free VRAM.

961 passed across the new file plus test_model_memory_settings, test_llama_server_args, test_gpu_selection, test_host_offload_ram_guard, test_llama_cpp_placement and test_gpu_arch_gate_consumers_7624.

One thing to weigh

This makes none the common case, since most models fit in VRAM plus RAM. On discrete GPUs that is a clear win. On unified memory (Apple Silicon, Vulkan iGPU, ROCm APU) it is a trade rather than a win: there is no double copy, because Metal buffers are host buffers and llama.cpp reads straight into them, but the pages become anonymous rather than file-backed, so a reload re-reads the GGUF instead of coming back warm from the page cache. _weights_in_host_memory already identifies all three if we want to carve them out later.

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

ℹ️ 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 +18035 to +18039
if self._fits_without_paging(
_fit_footprint,
gpus,
gpu_indices = gpu_indices,
shared_gpu_ids = _shared_gpu_ids,

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 Exclude ROCm APU memory from the VRAM sum

On a ROCm unified-memory APU such as gfx115x, _shared_gpu_ids is always empty because it is populated only for Vulkan, so this call allows _fits_without_paging to add ROCm's reported VRAM to available system RAM even though both represent the same physical pool. A model whose weights fit but whose KV cache and scratch push the full footprint beyond RAM can consequently be marked as fitting and launched with --load-mode none, removing the mmap paging path and risking an OOM kill; include the selected ROCm unified-memory GPU IDs in the shared set before evaluating the fit.

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.

Already handled at head. _fit_derived_load_mode unions the ROCm unified-memory devices into the shared set before pricing, via the same _amd_apu_wants_unified_memory predicate the rest of the launch uses, so their VRAM is dropped from the VRAM term and carried by host RAM instead. The premise that _shared_gpu_ids is empty under ROCm is right, and that union is what compensates for it. The is_vulkan_backend guard beside it is deliberate rather than a gap: under Vulkan the ids are Vulkan ordinals, which the ROCm helper would read as physical ids. test_unified_memory_is_never_counted_twice covers exactly this case with an APU row whose shared set is empty.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Verification pass on this PR. Summary first: the change is sound and now covers five holes it did not, but the measurement does not support the load-time claim I opened it with, and I think we should reconsider which mode the fit picks.

Before and after

Before: --load-mode was emitted only when a model had an explicit per-model pick, or when the Model Memory settings asked for a page lock. A model with no pick got no flag, so llama.cpp used its own default.

After: a model with no pick, whose whole footprint the placement can price and prove fits (in VRAM, or in VRAM plus host RAM), gets --load-mode none. Everything else is untouched.

Is it a real issue

Half real. The mechanism is real: upload_backend in llama-model-loader.cpp is constructed only when use_mmap is false, so with mmap on and a discrete GPU every tensor takes a synchronous copy out of a page-faulting mapping instead of a pipelined async upload from pinned memory.

The payoff is not what I assumed. Measured on a B200 over local NVMe against llama.cpp b10360, the build Studio ships today, load-to-ready, median of 3, full offload:

model mode cold warm
Qwen3-4B Q4_K_M (2.5 GB) mmap (no flag) 1.81 1.42
none 2.04 1.49
dio 2.05 1.69
Qwen3-30B-A3B UD-Q4_K_XL (17 GB) mmap (no flag) 5.43 2.81
none 5.49 3.21
dio 2.26 2.30

none is consistently a little slower than plain mmap. It drops mmap and does get the async uploader, but it still reads through the page cache and pays that copy, and here the copy costs more than the uploader wins. dio takes the same uploader and skips the page cache, and on the model big enough for load time to matter it is 2.4x faster cold. Upstream's own docs say the same thing, that dio is the answer when you were reaching for --no-mmap.

The picked mode is now a single constant, _FIT_LOAD_MODE, with those numbers recorded beside it, and the tests read the constant rather than the literal. It stays at none as asked. Switching it to dio is that one line.

Will merging break anything

Five things it would have broken, now fixed:

  1. Unified memory counted twice. A ROCm APU reports free "VRAM" out of the same pool the host-RAM term prices, so 40 GB against a 32 GB APU with 32 GB of RAM added to 64 GB and "fit". Only Vulkan iGPUs were dropped from the VRAM term. ROCm APUs are dropped now too.
  2. An unreadable model size fell through as 0, so a load whose weights could not be sized was judged on its KV and buffers alone. Abstains now, as does an engaged but unsized drafter.
  3. Apple Silicon. Metal is the one backend where buffer_from_host_ptr is supported, so mmap wraps the weights in a Metal buffer in place, zero copy and file backed. none allocates the same bytes anonymously, and an evictable 30 GB mapping on a 32 GB machine is the difference between working and being jetsammed. MemAvailable is also the wrong ceiling there. Abstains outright.
  4. The --fit on retry kept the flag. That retry runs precisely because the full-offload prediction did not hold, so a conclusion drawn from that prediction cannot ride into a launch about to offload to the CPU. Dropped there now.
  5. The CPU fallback kept it too. That replay runs --device none, so the VRAM half of the fit is void and the whole model comes out of host RAM, which is exactly where mmap is what makes it survivable. Dropped there too.

Only Unsloth's own tokens are stripped in 4 and 5: _fit_load_mode_flags records the flag only when the fit chose it, so a mode a user asked for survives every fallback.

No new hardware path is added. The fit runs on the placement numbers that were already computed, and where it cannot prove a fit it emits nothing, which is exactly the old behaviour.

Old installs

supports_load_mode is probed from --help, and a build that predates the enum gets --no-mmap, the pre-enum spelling of the same mode, through the existing _LEGACY_LOAD_MODE_FLAGS map. Worth recording: the b10360 line Studio ships today rejects --load-mode auto outright (its --help still reads default: mmap); auto only became an accepted value upstream later. Studio never sends auto verbatim, which the matrix test now pins, so this is safe in both directions.

Simulation

End to end, real server. 4 placements (full offload, --fit on, half the layers on CPU, --device none CPU replay) x 6 modes (unset, auto, none, mmap, mmap+mlock, dio), each launched against a real GGUF, timed to /health, then asked for a completion and checked for the right answer. 20 of 20 valid combinations serve. The 4 failures are all --load-mode auto on a build that does not accept it.

MoE. llama.cpp issue 14999 reported memory errors with --no-mmap on MoE models and named unsloth dynamic quants specifically. It does not reproduce on b10360: Qwen3-30B-A3B UD-Q4_K_XL loads and answers correctly under none, dio and mmap alike.

The matrix. test_load_mode_fit_matrix.py walks [Linux, Windows, WSL, macOS] x [NVIDIA, NVIDIA multi, AMD discrete, AMD APU, Vulkan iGPU, CPU only] x [fits in VRAM, fits in VRAM plus RAM, fits nowhere], then the whole policy chain over toggles x user pick x fit pick x build capability x host residency, then both fallback paths. The upgrade-safety case is checked against a literal copy of the pre-change chain: wherever the fit abstains, the argv is byte-identical to a Studio that never had this.

1315 in the two new files, 2395 across those plus test_llama_server_args, test_model_memory_settings, test_gpu_selection, test_llama_cpp_placement, test_amd_apu_unified_memory, test_host_offload_ram_guard, test_llama_cpp_context_fit and test_gpu_arch_gate_consumers_7624. The full backend suite has 176 pre-existing failures in the video, diffusion, RAG and MCP suites; 90 of the same fail on the unmodified base commit, so none of them are this.

No frontend behaviour changes, so there is nothing browser-specific to check. The only frontend edit is the comment describing what a null loadMode now means.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Cross-platform CI on real runners, against this PR's current head (6c6b0d0). Run on a staging fork rather than here so the org queue is spared.

runner result
macos-15 success, 1315 passed / 32 skipped in 4.64s
ubuntu-latest success, 1315 passed / 32 skipped in 8.04s
windows-latest success, 1315 passed / 32 skipped in 19.14s

Same counts on all three, and the same counts as locally, so the suite really executed on each rather than being waved through by the workflow's missing-dependency escape hatch.

Those files are test_load_mode_fit.py and test_load_mode_fit_matrix.py, which between them walk [Linux, Windows, WSL, macOS] x [NVIDIA, NVIDIA multi, AMD discrete, AMD APU, Vulkan iGPU, CPU only] x [fits in VRAM, fits in VRAM plus RAM, fits nowhere], the policy chain over toggles x user pick x fit pick x build capability x host residency, and both fallback paths. The platform axis is simulated by monkeypatching, so what these runs add on top of that is the real thing: that the module imports, the host-RAM probe resolves, and the path handling behaves identically on each OS.

An earlier round on the previous head (f0b02fe) also passed on all three with identical counts, so nothing in the _FIT_LOAD_MODE commit moved them.

danielhanchen and others added 5 commits August 24, 2026 08:27
llama.cpp builds its async pinned-buffer upload path only when mmap is off
(llama-model-loader.cpp, upload_backend). With mmap on and a discrete GPU,
buffer_from_host_ptr is unsupported, so every tensor takes a synchronous
copy out of a page-faulting mapping instead.

mmap earns its keep by demand-paging a footprint the machine cannot hold,
so a load that fits does not need it. Pick --load-mode none whenever the
whole load fits in VRAM, or in VRAM plus host RAM, and leave llama.cpp's
own auto in place for anything larger, where the mapping is what stops an
over-committed load from being killed outright.

_fits_without_paging prices weights + projector + KV + MTP reserve +
compute buffers + soft overhead against free VRAM on the devices the launch
actually pins, then against available RAM less the same headroom the
host-offload guard keeps free. Shared iGPU memory is dropped from the VRAM
term and carried by the RAM term so it is never counted twice. An unsized
KV or unreadable host RAM abstains and keeps auto, since an understated
footprint would claim a fit that is not there and hand the load a loader
that cannot page.

Precedence is unchanged: the fit only fills in for a model with no pick of
its own, an explicit per-model mode beats it, the Model Memory settings
beat both, and a hand-typed flag in the extras still wins by last-arg.
Five real holes found by walking the launch paths and the OS/GPU matrix:

Unified memory was counted twice. A ROCm APU reports free "VRAM" out of the
same pool the host-RAM term prices, so a 40 GB load against a 32 GB APU and
32 GB of RAM added up to 64 GB and "fit". Only Vulkan iGPUs were dropped from
the VRAM term; the ROCm ones are now dropped too, off the same predicate the
rest of the launch uses, and both end up priced against host RAM alone.

An unreadable model size fell through as 0, so a load whose weights could not
be sized was judged on its KV and buffers alone and could "fit". It abstains
now, as does an engaged but unsized drafter, which the placement itself covers
with a flat cushion rather than a number.

Apple Silicon abstains outright. Metal is the one backend where
buffer_from_host_ptr is supported, so mmap wraps the weights in a Metal buffer
in place, zero copy and file backed; none would allocate the same bytes
anonymously, and an evictable 30 GB mapping on a 32 GB machine is the
difference between working and being jetsammed. MemAvailable is the wrong
ceiling there anyway, per _apple_metal_memory_budget_bytes.

The --fit on retry kept the flag. That retry exists precisely because the
full-offload prediction did NOT hold, so the conclusion drawn from it cannot
ride along into a launch that is about to offload to the CPU. It is dropped
there now, mirroring how the page-lock is re-armed.

The CPU fallback kept it too. That replay runs with --device none, so the VRAM
half of the fit is void and the whole model has to come out of host RAM, which
is exactly where mmap is what makes it survivable.

Only Unsloth's own tokens are stripped in either place: _fit_load_mode_flags
records the flag solely when the FIT chose it, so a mode the user asked for is
theirs and survives every fallback.

The verdict moves into _fit_derived_load_mode so the matrix can drive it
directly. No behaviour change from the move.

Tests: test_load_mode_fit_matrix.py walks [Linux, Windows, WSL, macOS] x
[NVIDIA, NVIDIA multi, AMD discrete, AMD APU, Vulkan iGPU, CPU only] x [fits in
VRAM, fits in VRAM plus RAM, fits nowhere], the whole policy chain over
toggles x user pick x fit pick x build capability x host residency, and both
fallback paths. The upgrade-safety case is checked against a literal copy of
the pre-change chain: wherever the fit abstains, the argv is byte-identical.

Also corrects the frontend note on what a null loadMode means, and records that
"auto" is a value the b10360 line Studio ships today rejects outright, which is
why it is never sent verbatim.
Ran every mode Studio can emit against a real llama-server (b10360, the build
Studio ships today) on a B200 over local NVMe: 4 placements x 6 modes, each
launched, timed to /health, and asked for a completion. All 20 valid
combinations serve. The 4 that fail are --load-mode auto, which that build
rejects outright; Studio never sends it, which the matrix test now pins.

Load-to-ready, median of 3, full offload:

  Qwen3-4B Q4_K_M (2.5 GB)          cold   warm
    mmap (no flag)                  1.81   1.42
    none                            2.04   1.49
    dio                             2.05   1.69
  Qwen3-30B-A3B UD-Q4_K_XL (17 GB)  cold   warm
    mmap (no flag)                  5.43   2.81
    none                            5.49   3.21
    dio                             2.26   2.30

That does not say what the first commit assumed. Dropping mmap does unlock
llama.cpp's async pinned-buffer uploader, but "none" still reads through the
page cache and pays that copy, and on this storage the copy costs more than the
uploader wins: "none" is consistently a little SLOWER than plain mmap. "dio"
takes the same uploader and skips the page cache, and on the model big enough
for load time to matter it is 2.4x faster cold.

So the picked mode is now a single named constant, _FIT_LOAD_MODE, with the
measurements recorded beside it. It stays "none" because that is what was
asked for, and the tests read the constant rather than the literal so flipping
it moves the matrix with it.

Also checked the MoE case from llama.cpp issue 14999, which reported memory
errors with --no-mmap on MoE models and named unsloth dynamic quants. It does
not reproduce on b10360: the UD-Q4_K_XL above loads and answers correctly under
none, dio and mmap alike.
Three paths where the load-mode fit's proof stops holding but the flag it
derived from that proof survives anyway. All three are the same shape as the
--fit on retry and the CPU fallback this PR already handles.

Pass-through placement overrides. The extras are appended AFTER this launch's
own -ngl and llama.cpp assigns n_gpu_layers and devices on every occurrence, so
a hand-typed -ngl 0, a --device naming no GPU, or a CPU tensor override runs the
weights out of host RAM the planner had just credited to a card. The Model
Memory host-residency gate already carries exactly this guard for the page-lock
decision, with the same last-wins reasoning; the load-mode decision was the one
sibling without it. The VRAM credit is dropped rather than abstaining, because a
load host RAM holds whole is still safe wherever those flags put it. The mass
case is not a hand-typed -ngl but the common MoE paste, --n-cpu-moe N or
-ot ".ffn_.*_exps.=CPU".

A CPU-pinned separate drafter. Dropping it from the VRAM budget is right, none
of it is on the GPU, but the bytes did not go anywhere, they moved to host RAM,
and llama.cpp carries the process-wide load mode into the draft model
(common_base_params_to_speculative starts from result = params and overrides
only devices, model and n_gpu_layers), so none de-mmaps the draft GGUF too.
Charging it is the same reasoning that already keeps a CPU-pinned projector in
the footprint. Unpriceable means abstain, like every other unreadable term. Only
reachable when the target keeps recurrent rollback state, since otherwise the
replaced overhead callback goes None and the fit abstains already.

The arch-crash retry. It replaces the pinned device set with the survivors, a
set the fit never priced, and respawns from cmd. Its two host guards are
weights-only floors by design, so they cannot re-establish a whole-footprint
proof, and host-resident weights without mmap are anonymous rather than
file-backed, which is an OOM where the mapping would only have paged.

Only Unsloth's own tokens are stripped, so a mode the user asked for still
survives every fallback.
@danielhanchen
danielhanchen force-pushed the studio-load-mode-none-when-it-fits branch from 6c6b0d0 to 1fb7d01 Compare August 24, 2026 08:28
@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: 1fb7d01772

ℹ️ 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 +18313 to +18318
_fit_load_mode = self._fit_derived_load_mode(
model_size = model_size,
mmproj_pinned_bytes = _mmproj_pinned_bytes,
kv_cache_bytes = kv_cache_bytes,
kv_sized = self._can_estimate_kv(),
mtp_bytes = _mtp_bytes(effective_ctx) + (_cpu_draft_fit_bytes or 0),

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 Reserve prompt-cache RAM before selecting none

When --cache-ram is positive—or omitted and therefore uses the 8192 MiB default—the fit passed here ignores host memory that llama-server may subsequently fill with evicted prompt state. A partially offloaded model can be declared to fit with only a small amount of RAM left, receive anonymous host weight buffers via --load-mode none, and then exceed RAM as the prompt cache grows; with mmap, those weight pages remain reclaimable instead of competing as a fixed anonymous allocation. Include the effective cache-RAM allowance in the host-side footprint, and abstain for the unlimited -1 setting.

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.

Not taking this one. --cache-ram is a lazily grown, self-limiting host cache: nothing is allocated at load, oversized entries are skipped, older entries are evicted before a new one is allocated (server-task.cpp alloc(), the while loop over states.pop_front()), and a bad_alloc shrinks the limit to 40 percent rather than dying. Even -1 is bounded by limit_tokens = n_ctx. Reserving the 8192 MiB default up front would suppress none on essentially every partially offloaded model, to guard a post-load consumer that grows the same way under mmap.

Comment on lines +18316 to +18317
kv_cache_bytes = kv_cache_bytes,
kv_sized = self._can_estimate_kv(),

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 Treat a zero context as an unsized KV cache

When GPU Memory is Manual with Auto layers and the context is left blank, the planner intentionally keeps effective_ctx at 0 so llama.cpp's --fit chooses the real context, but _estimate_kv_cache_bytes(0) returns zero while this argument still marks the KV term as sized whenever the GGUF dimensions are known. The fit can therefore select --load-mode none from weights alone even though the launched command allocates at least the fitter's context floor (or an inherited positive LLAMA_ARG_CTX_SIZE), and the omitted KV and context-linear scratch can push a RAM-resident load into OOM. Abstain when effective_ctx <= 0, or price the same context floor the child will use.

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.

Not taking this one. The premise is right that _estimate_kv_cache_bytes returns 0 for a zero context while kv_sized never looks at the context, but the branch that leaves effective_ctx at 0 is Manual with Auto layers, and it sets gpus = [] on the same lines. The VRAM credit is therefore zero and the entire model is charged to host RAM, against a child that --fits most of it onto the GPU, so the guard is already conservative by the whole offloaded weight fraction, which dominates the unpriced KV. The residue is a GGUF carrying no context_length at all, which is not well-formed input.

Three follow-ups on last round's fixes.

A CPU-pinned drafter was pooled into the aggregate footprint, so the
free-VRAM fast path could satisfy bytes the child only ever allocates on the
host. -ngld 0 is not in _GPU_LAYER_FLAGS either, so the pass-through override
guard never voids the VRAM credit for it. It becomes host_only_bytes: counted
in the whole footprint, charged to the RAM term alone. The spill is now one
expression rather than a fast path plus a subtraction, and is bit-identical
when the new terms are zero.

Under --fit on, llama.cpp's fitter keeps --fit-target free on every device it
uses (default 1024 MiB, common/common.h fit_params_target) and spills weights
to host RAM rather than dip into it, so that margin is not VRAM this fit may
spend. It is now subtracted per device. Zero on the proved path, which emits
-ngl -1 --fit off and runs no fitter at all. _fit_target_margin_mib is the one
reader for both the emitted flag and the fit, so the margin the child is told
to keep and the margin the fit refuses to spend cannot drift.

The --fit on retry cleared the recorded tokens after stripping them from its
own argv, but that record describes cmd, which the retry never rewrites. A
kernel-image crash reaches that arm first, since it excludes only the
split-axis and HIP/ROCr cases, so the arch-crash and CPU fallbacks that
respawn from cmd were left carrying a mode they could no longer name. The
record is kept until a retry rewrites cmd itself; stripping an already
stripped argv is a no-op.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three narrow corrections to the fit-derived --load-mode none decision:

- The guard that voids the VRAM credit now passes the launch env into
  _device_selection_is_cpu and _env_places_tensors_on_cpu. It was the only
  caller omitting it, so an inherited LLAMA_ARG_DEVICE=none ran the model on
  CPU while the fit still credited every card. It also counts an explicit
  --device narrowing against the number of devices the fit credited, since
  --device is opt-in under auto GPU selection and never stripped there.

- The fitter margin is charged from the effective --fit state rather than
  Studio's own use_fit. -ngl -1 is llama.cpp's own default, and the fitter
  aborts only on a value that differs from the default, so a pass-through
  --fit on still rewrites the layer split. A pass-through --fit-target is
  now read as well, via fit_target_margin_in.

- The no-flash-attention retries drop the derived load mode at both sites
  (startup crash and MTP first decode). The MLA KV estimate prices only
  bpe_k and ignores flash_attn, so the f16 K upcast on that retry is
  unpriced.

Adds coverage for inherited LLAMA_ARG_DEVICE, --device narrowing including
last-wins, fit_target_margin_in, effective fitter state, and both no-flash
strip sites.
@danielhanchen

Copy link
Copy Markdown
Member Author

Round 3 addressed in 3ba8c89. All three items were genuine and are fixed:

  • The load mode guard now receives the launch env, so an inherited LLAMA_ARG_DEVICE=none no longer leaves the fit crediting VRAM the child will not open. It also voids the credit when --device narrows the launch to fewer devices than the fit counted.
  • The fitter margin is charged from the effective --fit state rather than Studio's own flag, since -ngl -1 is llama.cpp's default and does not hold the fitter off. A pass-through --fit-target is now read as well.
  • Both no-flash-attention retries drop the derived load mode, not just the startup one.

Targeted suites: 1864 passed, 32 skipped. Cross-platform CI on ubuntu-latest, macos-15 and windows-latest all passed earlier at 1315 passed / 32 skipped each.

One structural note, since nine items across three rounds have all been the same shape. Every one of them is a case where something later in the launch either shrinks the VRAM the fit credited or grows the footprint, after the decision was already taken. None of them can create a fit the early computation missed, so the decision never needs to be recomputed late, only revoked. _spawn_and_wait is a single choke point that sees the literal argv and the literal child env on every spawn, including the internal --fit off and --fit on retries, and the revocation helper it would use already exists and is position independent.

I would rather not fold that into this PR. It would delete the four strip sites whose tests are the current evidence that the fallback behaviour is correct, in the same diff that changes the fit itself, which makes a regression in either one hard to attribute. Planning it as a follow-up that turns "every new respawn path must remember to strip" into something enforced at one place.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A projector resolved for the launch is priced at file size plus 40 percent
(_MMPROJ_VRAM_SAFETY), because the runtime buffer runs about 1.3x the file. One
inherited from LLAMA_ARG_MMPROJ was priced at raw file size with no allowance at
all. The gate is effective_is_vision, which is itself gated on
launch_mmproj_path, and the inherited arm is reached only when that path is
empty, so the allowance could never apply there.

Direction is the dangerous one: the footprint comes out 40 percent of a
projector short, which is how a load that does not fit gets a --load-mode none
that leaves it unable to page.

Charged on the VRAM arm only. When the resolved offload says CPU the bytes are
host-resident and the resolved projector is charged raw there too, so both arms
keep the same split.

Two review items were rejected. Letting an explicit --mlock stand the fit down
is a no-op twice over: --mlock sets LLAMA_LOAD_MODE_MLOCK (common/arg.cpp) and
use_mmap is only set for mmap, mmap+mlock and auto (llama-model-loader.cpp), so
a bare --mlock is already a no-mmap full host copy rather than the mmap-plus-lock
the item assumes; and the managed block is appended before the user extras, which
llama.cpp resolves last-wins, so their flag already governs. The environment case
genuinely does need its own check, because llama.cpp reads LLAMA_ARG_* before
argv, which is why the two are treated differently. The other item asks for
user-facing help text describing Auto as fit-derived; the premise is right but it
is documentation rather than a correctness defect.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three rungs already re-recorded the effective memory state after dropping the
fit's --load-mode none, and three did not. Without "none" the child is back on
llama.cpp's auto, which maps (common.h defaults load_mode to auto and
llama-model-loader derives use_mmap from mmap, mmap+mlock and auto), so a record
still saying the launch reserves RAM makes memory_state_satisfies_settings
answer a later "Don't reserve system RAM" with a full reload the running server
already satisfies, and the settings route hint agrees with it. Pessimistic
rather than dangerous, but wrong, and the invariant was already kept elsewhere.

Two of the three were the no-flash and CPU-projector rungs, raised in review.

The third I found while checking the remedy the review proposed. The arch-crash
rung rebuilt the record from _mem_managed + _mem_extras, and its comment claimed
that was what remained after removing the pair. It is not: by that point cmd may
have been reassigned to the CPU, device-gated, no-tensor-split or arch-retry
argv, so the parts no longer add up to it and anything memory-relevant those
paths added is dropped. That direction is the opposite one, recording an
unlocked child that is in fact locked, which is why it is worth fixing rather
than leaving. All three now recompute from the stripped argv, which is what the
--fit on and --fit off rungs already did.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… rung

LLAMA_ARG_NO_KV_OFFLOAD was ignored. common/arg.cpp registers -kvo with
args_neg -nkvo and set_env("LLAMA_ARG_KV_OFFLOAD"), and get_value_from_env
rewrites LLAMA_ARG_ to LLAMA_ARG_NO_ and, when that variable EXISTS, sets the
value to "0" and returns before it ever reads the affirmative one. So presence
decides, not truth: LLAMA_ARG_NO_KV_OFFLOAD=0 or an empty value disables
offload just as well, and it beats LLAMA_ARG_KV_OFFLOAD=1. Environment is
processed before argv.

Missing it left _kv_on_host False, which keeps the cache bytes in the pooled
term free VRAM may pay for, so the fit could answer "fits" on a load whose cache
is entirely host-resident and hand it --load-mode none. That is an OOM where
llama.cpp's auto would have paged. The same negative-alias rule is already
documented and implemented in this tree for the mmap and direct-IO pairs; this
helper was simply not updated. The argv loop is untouched, so a command line
-kvo still takes it back.

The CPU fallback is the fourth rung that strips the fit's --load-mode none
without recomputing the memory record, after the three fixed last round. Same
pessimistic consequence: the record still says the launch reserves RAM while the
stripped child is back on auto and maps, so a later "Don't reserve system RAM"
spends a full reload the running server already satisfies. Both entry points are
covered, the crash path and the replayed request. The crash path recomputes from
_last_spawn_cmd rather than from the parts, since the --fit retries append a
page-lock to their own argv and rebuilding would record it away.
Not from this PR. tests/studio/playwright_declared_polls.py came in with #9665
and the repo's own guard rejects it: a checked-in file read or written with the
platform default encoding breaks on Windows the moment it gains a non-ASCII
byte. It reached this branch through the merge with main and is the only red
check here, so it is fixed rather than left blocking.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2de0f1b5fe

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

The hint still said Auto memory-maps unless a device cannot, which was true
before this PR. Auto now runs the fit first and picks None when the model is
proved to fit without paging, falling back to llama.cpp's own choice otherwise,
so the text described behaviour the option no longer has.

Raised in review and initially declined as documentation rather than a defect,
which was the wrong call for the one string a user actually reads before
choosing. The API docstring for the same field is left alone: it describes the
wire contract, where omitting the field really does mean the llama.cpp default.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6ce12701c1

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

Development

Successfully merging this pull request may close these issues.

1 participant