Skip to content

Studio: warn instead of refusing to load a model bigger than VRAM plus RAM - #9822

Merged
danielhanchen merged 28 commits into
mainfrom
host-ram-guard-warn-not-refuse
Aug 27, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
host-ram-guard-warn-not-refuse

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The problem

A GGUF whose on-disk size exceeds free VRAM plus available system RAM minus a 2 GiB headroom is refused outright. POST /api/inference/load returns 400 and llama-server is never spawned.

The predicate, from _get_gguf_size_bytes (which sums all shards of a split GGUF) and _HOST_RAM_HEADROOM_MIB = 2048:

refuse if   gguf_size_on_disk - free_VRAM  >  available_RAM - 2 GiB

That is more conservative than the engine underneath. Weights are mmap'd, so an oversized model pages in from disk rather than failing, and running a quant larger than a machine's fast memory off an SSD is a deliberate, supported thing to do. This check prices total weights against total capacity and has no idea how fast the backing store is, so it cannot tell that case apart from a mistake.

It is also not something a placement can fix: the weights exist and the VRAM exists, so the host share is fixed no matter how the offload planner arranges it.

Measured

unsloth/Qwen3.8-Flash-Next-GGUF UD-IQ1_S (67.56 GB) on a Colab T4 high-RAM VM (14.5 GiB VRAM, ~51 GB RAM), on both a git main install and the published PyPI wheel:

About 53 GB of this model does not fit in GPU memory and would run from system
RAM. Only about 51 GB is available and 2 GB of that is kept free for the rest of
the system, leaving about 48 GB usable. ...

The change

The arithmetic is unchanged, only its consequence. Both message builders now read as advisories, and the five places that turned one into a hard failure report it instead:

where was now
load_model, APU / unified memory raise RuntimeError log, launch
load_model, discrete host offload raise RuntimeError log, launch
load_model, APU on the HIP-crash retry raise RuntimeError log, respawn
load_model, offload on the HIP-crash retry raise RuntimeError log, respawn
routes/inference.py route preflight HTTPException(400) log, load

The two retry sites dropped a _kill_process() that existed only to tear down before raising; the retry path already kills before respawning.

The notice rides back on LoadResponse.memory_warning, so a client can say why generation is slow rather than leaving the user to guess, and host_offload_refusal_for_intent is renamed host_offload_warning_for_intent to match what it now does.

UNSLOTH_ALLOW_HOST_OFFLOAD is kept and still honoured so existing scripts and docs keep working. With nothing left to refuse, its only remaining effect is to silence the warning.

The non-chat GGUF refusal directly above the route change is a different guard and is left alone.

Verification

  • test_host_offload_ram_guard.py, test_llama_cpp_placement.py, test_load_mode_fit_matrix.py, test_metal_explicit_context_guard.py, test_gpu_arch_gate_os_matrix_7624.py: 1862 passed, 32 skipped.
  • 12 assertions that expected a RuntimeError now assert the load happens and carries the advisory, via a shared _launch_warns helper.
  • New test_a_wildly_oversized_model_still_loads pins the Colab shape above (67.6 GB against 14.5 GiB VRAM and 51 GB RAM) so no shortfall can block a load again, however large the gap.
  • test_the_env_escape_is_now_a_no_op_that_only_silences_the_warning covers both arms of the env var.

Note

This is the first of two. A load that gets past this guard then hits a separate crash on the planner path, fixed in #9821; both are needed before an oversized GGUF loads end to end.

danielhanchen and others added 2 commits August 27, 2026 03:45
…s RAM

A GGUF whose on-disk size exceeds free VRAM plus available system RAM minus a
2 GiB headroom was refused outright. POST /api/inference/load returned 400 and
llama-server was never spawned.

That is more conservative than the engine underneath. Weights are mmap'd, so an
oversized model pages in from disk rather than failing, and running a quant
larger than a machine's fast memory off an SSD is a deliberate, supported thing
to do. The check prices total weights against total capacity and has no idea how
fast the backing store is, so it cannot tell that case apart from a mistake.

Measured: unsloth/Qwen3.8-Flash-Next-GGUF UD-IQ1_S (67.56 GB) on a Colab T4
high-RAM VM (14.5 GiB VRAM, ~51 GB RAM) comes back

  About 53 GB of this model does not fit in GPU memory and would run from system
  RAM. Only about 51 GB is available ...

on both a git main install and the published PyPI wheel.

The arithmetic is unchanged, only its consequence. Both message builders now
read as advisories, and the five places that turned one into a hard failure
report it instead:

  - four raise RuntimeError sites in load_model (APU, discrete host offload, and
    both HIP-crash retry paths) now log and fall through to the launch. The two
    retry sites dropped a _kill_process() that only existed to tear down before
    raising; the retry path already kills before respawning.
  - the route preflight logs rather than raising HTTPException(400).

The notice rides back on LoadResponse.memory_warning so a client can say why
generation is slow instead of leaving the user to guess, and
host_offload_refusal_for_intent is renamed host_offload_warning_for_intent to
match what it now does.

UNSLOTH_ALLOW_HOST_OFFLOAD is kept and still honoured so existing scripts and
docs keep working. With nothing left to refuse, its only remaining effect is to
silence the warning.

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

ℹ️ 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 +12307 to +12308
if _host_offload_warning:
logger.warning("Loading an oversized GGUF: %s", _host_offload_warning)

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 Preserve the route warning for the response

When this preflight finds a shortfall, the warning is only logged and is never stored on llama_backend, while _gguf_load_response populates memory_warning exclusively from last_load_warning. If the later launch-time GPU probe fails or returns an empty pool, _launch_host_shortfall_message deliberately abstains, so the model can load successfully but the response contains memory_warning: null despite this earlier definitive warning. Record or hand off _host_offload_warning so the load response cannot lose it.

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 reachable on a consistent host reading, so leaving the code as is.

The route cannot warn off a failed or empty probe either: host_offload_warning_for_intent hands its probe straight to _launch_host_shortfall_message, which returns None on not gpus and not child_has_no_gpu. So that case abstains at both ends, not just at launch.

Otherwise the launch check is strictly harsher than the route check on every axis. The route prices physical totals; the launch prices free VRAM and available RAM, additionally subtracts shared iGPU rows, and can set child_has_no_gpu. Each of those moves the launch estimate toward warning, so route-warns implies launch-warns. The one structural difference is that the launch applies the ROCm arch gate and the route does not, but a gate that empties the pool means every arch is uncovered, which re-derives to _arch_gate_forced_cpu and child_has_no_gpu = True, and the launch then prices the whole model against host RAM and warns more. What is left is a probe that succeeded at the route and failed seconds later, which is a flaky probe rather than well-formed input.

You did find a real error though, just in the prose: the docstring claimed the route copy rides back on the load response. It does not and cannot, since load_model calls _begin_load_warnings on its first line, after the route runs, so anything recorded there is erased. Corrected in 5f36093.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +5808 to +5812
# Advisory only, and None on the overwhelming majority of loads. Recorded by
# load_model when the weights outgrow fast memory, so the client can say why
# generation will be slow instead of leaving the user to guess.
# getattr: older/custom backend doubles predate this additive field.
memory_warning = getattr(llama_backend, "last_load_warning", None),

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 Surface the memory warning in the Studio client

The browser never consumes this new response field: LoadModelResponse in studio/frontend/src/features/chat/types/api.ts does not declare memory_warning, and the load paths in chat-api.ts, use-chat-model-runtime.ts, and chat-adapter.ts neither inspect nor display it. Consequently, this change removes the previous user-visible refusal for an oversized model but gives Studio users no replacement warning before they encounter paging, an unresponsive machine, or an OS-killed process; only API clients inspecting the raw JSON or backend logs can see it.

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.

Factually right, and I am not going to pretend otherwise: nothing under studio/frontend/src reads memory_warning, and before this PR an oversized GGUF returned a 400 whose detail was surfaced to the user. A Studio desktop user now gets a model that loads and generates slowly with nothing on screen explaining why. That is a real loss of user-visible information.

Marking it down as a defect in this PR rather than as a fix, for two reasons. Backend-only was the deliberate scope here, and the backend contract is correct and complete on its own terms: an additive optional field, documented, populated per load, breaking no existing client. And the trade is clearly right on its own: the refusal was blocking loads llama.cpp itself performs, since mmap pages the weights in. The unmapped modes were the genuine hard-failure case and are handled separately in 5f36093.

The client surface is follow-up work, and it is small because cpu_fallback_reason is an exact precedent: declare the field on LoadModelResponse in features/chat/types/api.ts, extend loadFallbackNotice in utils/mmproj-fallback.ts to take it, and pass it through at the use-chat-model-runtime.ts and chat-adapter.ts call sites. Roughly four files and no new component. I will raise it separately rather than widen this PR.

Comment on lines +9124 to +9125
if self._last_load_warning is None:
self._last_load_warning = message

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 Replace warnings after an architecture fallback

On a mixed AMD host, the initially selected unified-memory APU can record an insufficient-system-RAM warning and then crash with a kernel-image error, after which the existing recovery path retries on a discrete GPU that may hold the model entirely in VRAM. Because the first warning always wins and a comfortable retry cannot clear it, the successful response still claims the model is loading through the APU and may be stopped by the OS even though the resident child uses the discrete card. Reset or replace the advisory when the architecture retry changes the effective placement.

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.

Correct, and reproduced: _record_load_warning keeps the first message of a load and _begin_load_warnings only runs at the top of load_model, so nothing clears the notice when the retry changes placement. On the canonical #7624 shape the APU warns, crashes with a kernel-image error, and the respawn lands on the discrete sibling that holds the weights in VRAM, leaving a served child reporting a shortfall on a device it never touches. Fixed in 5f36093 by clearing the notice where the retry already re-prices, so the surviving set's verdict is the load's answer. Both checks there price the same weights against a narrower pool than their upstream twins, so a shortfall that still applies is re-recorded. Regression test in TestArchCrashRetryReplacesTheCrashedSelectionsWarning, plus a control where the retry pool is too small and the live shortfall is still reported; both fail without the change.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026

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

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

)
if _offload_msg:
raise RuntimeError(_offload_msg)
self._record_load_warning(_offload_msg)

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 Retain the hard guard for non-pageable load modes

When an oversized model is launched with load_mode="none", --no-mmap, or an equivalent inherited setting, this path now records an advisory and starts the child even though the disk-paging rationale does not apply. The launch code itself notes that none creates a full anonymous host-memory copy (llama_cpp.py:20541-20545), so a shortfall in this configuration can still exhaust RAM or be killed during loading rather than running slowly from disk. Keep the refusal for effective non-mmap modes, or override them to a pageable mode before allowing the load.

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.

The hazard is real and I confirmed it from upstream source rather than the docs: llama-model-loader.cpp sets use_mmap = load_mode == LLAMA_LOAD_MODE_MMAP || load_mode == LLAMA_LOAD_MODE_MMAP_MLOCK || load_mode == LLAMA_LOAD_MODE_AUTO, so the unmapped set is exactly none and mlock. Worth noting mlock is in it too, which is the worse case (unmapped and pinned); mmap+mlock, which the Keep-in-GPU-memory setting emits, is pageable and untouched.

Taking your second option rather than the first. This guard must never block a load, so instead of restoring the refusal the unmapped request is overridden to its pageable equivalent in 5f36093: dropped for none, rewritten to mmap+mlock for mlock so the lock survives over a mapping, across both argv and the LLAMA_ARG_* twins llama.cpp resolves before argv. It fires only on a shortfall, so an unmapped load that fits is left byte for byte as asked, and the warning names the override rather than applying it silently. The recorded memory state and its snapshot are recomputed so the reload comparator judges the child against the mode it actually runs.

10 regression tests: four spellings asserting the child launches pageable and the warning names the override, four comfortable-fit controls asserting the argv is untouched, one for mlock becoming mmap+mlock, one for the inherited env twin. Six fail without the change; the four controls correctly do not.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026
…sized load

Two review findings on the advisory this PR introduced.

The arch-crash retry kept the crashed selection's warning. _record_load_warning
keeps the FIRST message of a load and _begin_load_warnings only runs at the top
of load_model, so the canonical #7624 shape (an APU whose shared-pool free
reading outranks the dGPU, warned about system RAM, crashed with a kernel-image
error, respawned on the discrete sibling that holds the weights in VRAM) served
a child on the discrete card while reporting a shortfall on a device it never
touched. The retry already re-prices for the surviving set, so clear the notice
there and let that verdict stand. Both checks price the same weights against a
narrower pool than their upstream twins, so a shortfall that still applies is
re-recorded.

The advisory also assumed the spill is mmap'd, which is its whole premise: the
weights page in from disk as the model runs. Upstream sets use_mmap for
mmap/mmap+mlock/auto and nothing else (llama-model-loader.cpp), so modes "none"
and "mlock" read every byte into a buffer llama.cpp allocates, and the same
shortfall is an allocation failure or an OOM kill during loading rather than
slow generation. This guard never blocks a load, so the unmapped request is
overridden instead of refused: force_pageable_load swaps in the pageable
equivalent across both argv and the LLAMA_ARG_* twins llama.cpp reads first,
keeping a lock as mmap+mlock so "keep this in RAM" survives over a mapping.
Only on a shortfall, so an unmapped load that fits is left exactly as asked, and
the override is named in the warning rather than applied silently. The recorded
memory state and its snapshot are recomputed so the reload comparator judges the
child against the mode it actually runs.

Also correct the host_offload_warning_for_intent docstring: it claimed the route
copy rides back on the load response. It does not, and cannot, because
load_model clears the recorded notice on its first line, after the route runs.
The response carries the launch-time notice; the route copy is a log line before
acquire_for(CHAT) tears down a resident pipeline.

Tests: 12 added. Without the source changes 8 of them fail and the 4
comfortable-fit controls correctly do not. Suite: 2845 passed, 32 skipped.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026

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

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

_ram_msg = None
if _ram_msg:
raise RuntimeError(_ram_msg)
self._record_load_warning(_ram_msg)

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 Remap oversized APU loads before recording the warning

When _apu_ram_shortfall_message finds a shortfall on a ROCm unified-memory APU, this line merely records it. The new force_pageable_load path runs only if the later _offload_msg is truthy, but _shared_gpu_ids is populated only for Vulkan at llama_cpp.py:17222-17227, so that later guard can credit the APU's reported GPU pool and return None even though actual available RAM produced _ram_msg. Consequently, load_mode="none" or "mlock" can still launch an oversized full host-memory copy and be OOM-killed. Fresh evidence beyond the earlier non-pageable-mode finding is that the current APU-specific shortfall path never invokes the added pageable rewrite.

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.

Confirmed, including your reasoning about why the later guard cannot cover it. _shared_gpu_ids is assigned only inside the Vulkan arm at llama_cpp.py:17222, so on a ROCm APU it is empty and the discrete guard prices the model against the APU's reported pool, which is the same system RAM: offload_bytes goes non-positive, the shared-heap branch is skipped and the message returns None. The APU shortfall was recorded and never reached the remap.

Fixed in 0229e82. One caveat on placement, since it is a deviation from the line you flagged: the rewrite cannot happen at the recording site, because cmd is not built until ~19545 and env not until ~20512, so there is no argv there to rewrite. The APU verdict is carried forward to the launch site, which is the earliest point the rewrite is physically possible and still before the spawn, and it is read after the arch-gate skip so a launch the gate moves onto discrete cards is not remapped. Four regression tests over the argv spellings, plus four fitting-load controls.

# Only on a shortfall -- an unmapped load that fits is exactly what was
# asked for and is left alone. Said out loud in the warning, since a
# silent override is its own surprise.
if _offload_msg:

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 the warning opt-out from disabling pageable loads

With UNSLOTH_ALLOW_HOST_OFFLOAD=1, _launch_host_shortfall_message returns None before calculating the shortfall (llama_cpp.py:8997-9003), so nesting the pageable rewrite under _offload_msg lets an oversized discrete-GPU load using --no-mmap, --load-mode none, or an inherited equivalent launch unchanged and exhaust host RAM. This also contradicts the new contract that the legacy variable only silences the warning. Fresh evidence beyond the earlier non-pageable-mode finding is that every newly added unmapped-load test explicitly removes this environment variable, leaving this combination uncovered; compute the remapping decision independently of warning suppression.

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.

Correct, and this one was a regression against a contract I had written one commit earlier. Reproduced at the pushed SHA: _launch_host_shortfall_message returns None at its third statement under the opt-out, before pricing anything, and the remap was nested under if _offload_msg:, so setting the variable disabled a rewrite that makes the load possible rather than merely silencing a notice. Your point about the tests is the sharper half: every unmapped test did monkeypatch.delenv, so the combination could not have been caught.

Fixed in 0229e82. The decision now comes from the load rather than from whether a warning was produced: the remap predicate re-prices with the opt-out ignored (honor_opt_out=False) instead of reading the suppressed verdict. The variable is kept and still silences the warning at its one call path, and the override is logged even when the warning is not. Regression test asserts oversized plus unmapped plus the variable set gives pageable argv, no recorded warning, override still logged.

Comment on lines +21649 to +21654
self._record_load_warning(
self._launch_host_shortfall_message(
cmd,
[row for row in _detected_gpus if row[0] in set(_remaining)],
env,
)

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 Remap nonpageable architecture retries before respawning

When the first selected GPU holds the model but crashes with a kernel-image error, narrowing to a smaller GPU can make these retry-only checks discover the first host-memory shortfall. They only record the warning; the earlier force_pageable_load block has already been bypassed because the original placement fit, and _spawn_and_wait(cmd, label="-archfallback") at line 21820 reuses the unchanged --load-mode none, mlock, or legacy equivalent. The retry can therefore allocate its newly host-resident weights into an unmapped buffer and be OOM-killed instead of paging. Fresh evidence in the current tree is that the newly added retry repricing calls never invoke the pageable rewrite before the respawn.

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.

Confirmed. Both retry checks only recorded, the upstream remap was bypassed because the original placement fit, and _spawn_and_wait(cmd, label = "-archfallback") reused the unchanged mode, so a retry that becomes the first shortfall allocated unmapped.

Fixed in 0229e82. The remap runs last in the retry block, after the tensor-split drop, the split-mode drop, the fit load-mode strip and the re-armed page-lock, all of which also rewrite cmd, and immediately before the respawn, so it cannot be undone by a later edit. The two retry messages keep their original recording order and position, so the log order is unchanged. Regression test uses the existing narrowed-pool shape (30 GB model, the 40000 MiB card crashes, a 4000 MiB survivor, 20 GB host) and also asserts the FIRST launch keeps its mode, which is what makes the retry the first shortfall rather than a repeat of one already handled upstream.

The remap added last commit was nested under the shortfall warning, which left
three holes with one root cause: the decision belongs to the LOAD (oversized and
effectively unmapped), not to whether a warning was produced.

UNSLOTH_ALLOW_HOST_OFFLOAD returned None from _launch_host_shortfall_message
before pricing anything, so the opt-out silently disabled the remap and an
oversized --no-mmap load launched unchanged and exhausted host RAM. That
contradicts the contract this PR documented, that the variable only silences the
warning. Every unmapped test deleted the variable, so the combination was
untested.

On a ROCm unified-memory APU, _shared_gpu_ids is populated only in the Vulkan
arm, so the discrete guard prices the model against the APU's reported pool,
which is the same system RAM, goes non-positive and returns None. The APU
shortfall was recorded but never reached the remap.

The arch-crash retry re-priced for the narrowed pool and only recorded, while
_spawn_and_wait respawned with the unchanged mode, so a retry that becomes the
first shortfall allocated unmapped.

One decision point now: _page_an_oversized_unmapped_load tests the effective
memory state, then the site's shortfall predicate, then rewrites. The opt-out
stays and still silences the warning; the remap predicate re-prices with
honor_opt_out=False rather than reading the suppressed verdict. The APU verdict
is carried to the launch site because cmd and env do not exist where the APU
message is produced, and that is the earliest point the rewrite is possible and
still before the spawn. The retry remap runs last in its block, after the
tensor-split, split-mode, fit and page-lock rewrites, immediately before the
respawn.

25 tests added. Without the source change 13 fail, one per reachable hole; the
fitting-load controls pass either way by construction, since they exist to prove
the override does not fire on a load that fits. Suite: 2870 passed, 32 skipped.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026

@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: 0229e82154

ℹ️ 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 +1681 to +1684
if flag in _RAM_RESERVING_FLAGS:
overridden.append(token)
i += 1
continue

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 Do not resurrect a shadowed mlock

When an oversized launch contains --mlock --no-mmap (or inherited LLAMA_ARG_MLOCK=1 followed by LLAMA_ARG_NO_MMAP), llama.cpp's last-wins semantics make the effective mode unlocked and unmapped—the existing resolver explicitly models --no-mmap as clearing mlock. Removing only the reserving selector leaves the earlier --mlock active, so the rewritten child unexpectedly runs mmap+mlock and may fault or lock the oversized mapping into the RAM this override is intended to protect. Preserve a lock only when it is effective before the rewrite, rather than retaining every bare mlock token or environment value.

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.

Correct, and this was the worst of the three: the rewrite could turn an unlocked launch into a locked one, pinning the oversized mapping into exactly the RAM the override exists to protect. Verified against the repo's own resolver rather than inference: resolve_effective_memory_state sets mlock, reserves_ram = False, True when mmap is disabled, so --mlock --no-mmap is unlocked and unmapped before the rewrite and was mmap+mlock after it.

Fixed in d774332. force_pageable_load resolves the pre-rewrite state first and strips a lock only when it was shadowed, gated on the launch actually reserving RAM so a pageable launch keeps every token byte for byte. An effective lock still survives as mmap+mlock.

Your finding reached two shapes you did not name, both now covered: --load-mode mlock --no-mmap (and the = spelling), which was being promoted to mmap+mlock, and --mlock --load-mode none. Six regression tests plus four controls, including the opposite ordering where an argv --mlock legitimately overrides an inherited LLAMA_ARG_NO_MMAP and the lock must be kept.

# remapped for a shortfall it no longer has. Independent of
# UNSLOTH_ALLOW_HOST_OFFLOAD, which this preflight never consulted.
_apu_ram_oversized = bool(_ram_msg)
self._record_load_warning(_ram_msg)

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 Honor the warning opt-out on APU shortfalls

On a unified-memory APU with a RAM shortfall, UNSLOTH_ALLOW_HOST_OFFLOAD=1 does not silence the advisory because this APU-specific path records _ram_msg without consulting _host_offload_warning_opted_out; the architecture-retry APU path does the same. This contradicts the retained environment variable's new warning-only contract and returns a non-null memory_warning for users who explicitly opted out. Keep _apu_ram_oversized independent so the pageable rewrite still occurs, but suppress only the call that records the warning when the opt-out is set.

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.

Confirmed and reachable at both sites. _apu_ram_shortfall_message is a staticmethod taking only sizes, so it never reads the environment, and both the preflight and the arch-retry passed its result straight to _record_load_warning. An opted-out user got the discrete guard silenced and the APU advisory returned anyway, which is not what the variable promises.

Fixed in d774332 exactly as you suggested: the oversized verdict stays independent of the opt-out so the pageable rewrite still happens, and only the recording call is suppressed. Applied at both APU sites. The preflight now logs an info line mirroring the one _launch_host_shortfall_message already emits, so an opted-out APU shortfall is still traceable. Four tests over the argv spellings plus a fitting-load control, and a mirror test on the arch-retry shape (crash on the dGPU, respawn on the APU) with its own control asserting the advisory still names the override when the opt-out is absent.

Comment on lines +21102 to +21105
if _offload_msg:
_offload_msg += _pageable_note
else:
self._amend_load_warning(_pageable_note)

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 Append the override note to the retained APU warning

When a unified-memory APU load is large enough for both _apu_ram_shortfall_message and _launch_host_shortfall_message to return messages, the APU warning has already been recorded and first-notice-wins keeps it. This branch appends the pageable-override note only to _offload_msg, which the following _record_load_warning then discards, so memory_warning omits that Unsloth overrode the user's non-mmap setting even though the child command changed. Amend the already-recorded warning as well whenever an APU notice is present.

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.

Confirmed, and the precondition is real rather than theoretical: with _shared_gpu_ids empty, which is the ROCm case since it is populated for Vulkan alone, _shared_heap_budget returns a zero pool, so the discrete branch still produces a message. An APU whose reported free VRAM does not cover the weights therefore raises both, the APU one is recorded first, and first-notice-wins discarded the amended string.

Fixed in d774332: _amend_load_warning is now called unconditionally whenever a note exists. It cannot double-append, since with nothing recorded it is a no-op and the note arrives via the discrete message, and with something recorded the amended discrete message is the string first-notice-wins throws away. Four tests on a backend rigged to produce both messages, with the both-guards-speak precondition pinned by a spy rather than assumed, plus a control asserting the note appears exactly once when only the launch guard warned.

Three follow-ups on the pageable override.

The rewrite could turn an unlocked launch into a locked one. llama.cpp is
last-wins and resolve_effective_memory_state models --no-mmap as clearing mlock,
so "--mlock --no-mmap" is unlocked and unmapped before the rewrite. Dropping only
the reserving selector left the earlier --mlock live and the child ran
mmap+mlock, pinning the oversized mapping into the RAM the override exists to
protect. force_pageable_load now resolves the pre-rewrite state and strips a lock
only when it was shadowed, so an effective lock still survives as mmap+mlock.
The same defect reached two shapes the review did not name, "--load-mode mlock
--no-mmap" and "--mlock --load-mode none", both covered.

UNSLOTH_ALLOW_HOST_OFFLOAD did not silence the APU advisory. _apu_ram_shortfall_message
never reads the environment, and both the preflight and the arch-retry recorded
its result directly, so an opted-out user still got a non-null memory_warning.
Both sites now keep the oversized verdict, so the rewrite still happens, and
suppress only the recording.

The override note could be dropped. When an APU load is large enough for both
guards to speak, the APU message is recorded first and first-notice-wins keeps
it, while the note was appended only to the discrete message that the following
record call then discards, so the response never said the load mode had been
overridden. The note is now amended onto whatever is already recorded as well.

24 tests added. Without the source changes 15 fail; every control passes at head,
which is what shows they are not vacuous. Suite: 2894 passed, 32 skipped.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: d774332be4

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

"UNSLOTH_ALLOW_HOST_OFFLOAD set: not recording the APU RAM advisory."
)
_ram_msg = None
self._record_load_warning(_ram_msg)

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 Reprice after dropping the CPU projector

On an APU where the base model fits but a CPU-pinned projector makes model_size + _mmproj_pinned_bytes exceed available RAM, this records the shortfall and can also force a pageable load. If projector startup later falls back to the text-only command at llama_cpp.py:22356, the successful child no longer loads those projector bytes, but neither the warning nor the load-mode override is recomputed; the response therefore warns about a shortfall that the resident model does not have and may disregard the user's otherwise-safe non-mmap setting. Clear or reprice both decisions when that fallback removes the projector.

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.

Correct, fixed in fe2e832. The APU preflight charges model_size + _mmproj_pinned_bytes because a CPU-pinned projector lands in the same system RAM as the weights, and the text-only fallback at the _strip_mmproj_args retry leaves that unpriced, so the advisory described a load nothing is running.

It is now repriced once the text-only child is healthy, not at the strip: a failed text-only retry can still replay the original vision argv on CPU further down, and that child does read the projector bytes, so only a healthy text-only server is evidence. The reprice uses the RAM figure the preflight read rather than a fresh one, since by that point the weights are resident and a live reading is the pool minus the very model being priced.

The load-mode override is reported rather than reverted. Its argv was already spawned and force_pageable_load rewrites the shared child env in place, so the running server is memory-mapped whatever the message says; undoing it would mean another respawn on the recovery rung that exists because this model already failed to start once. A load whose only remaining news is that override now says exactly that.

load_cancel_event: Optional[threading.Event] = None,
) -> bool:
"""Start llama-server from one immutable load intent."""
self._begin_load_warnings()

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 Preserve the resident warning across rejected attempts

When an oversized model is already serving, any subsequent load_model attempt clears its warning before acquiring the serial scope or passing preflight. If that attempt is rejected while deliberately leaving the resident server untouched—for example by the update-in-progress check at line 16232 or the invalid Vulkan-pin check at lines 16469-16475—the old model remains active but its advisory is gone, so a later already_loaded response returns memory_warning: null. Reset the warning only once the attempt commits to replacing the resident process, or restore it on pre-teardown failures.

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.

Correct, fixed in fe2e832, and it reaches further than the two paths named. An AST enumeration of exits belonging to load_model itself finds fourteen above the Phase 1 teardown: returns at 16383, 16385, 16386, 16394, 16596 and raises at 16240, 16480, 16514, 16516, 16518, 16525, 16543, 16556, 16590. The sharpest is 16386, the duplicate-load fast path, which returns True with the resident child untouched and is exactly what the route answers already_loaded from.

Rather than restore on each rejected path, the reset moved down to the teardown, inside the Phase 1 lock alongside the _cpu_fallback_reason and _mmproj_fallback_reason resets, whose existing comment argues the identical invariant. That line is the boundary between the old child surviving and the old child being gone, so an early return added later is covered by construction with no bookkeeping of its own. Every _record_load_warning and _amend_load_warning call site is well below it, so moving the reset down cannot lose a warning belonging to the current attempt.

The regression test drives three distinct pre-teardown rejects against a resident oversized model: the update-in-progress refusal, a cancel before teardown, and the fast path above.

4096 is too short to be useful for chat once tools and a system prompt are in the
window, and the fit search would settle there rather than spilling weights it
could spill instead.

Four constants move together because tests pin them to each other: _FIT_MIN_CTX,
the min_ctx defaults on _fit_context_to_vram and _cap_ctx_to_per_device_reserve,
and _MMPROJ_FIT_FLOOR_CTX. _AUTO_OFFLOAD_CTX stays at 8192; the invariant that
matters, _AUTO_OFFLOAD_CTX >= _FIT_MIN_CTX, still holds, so the Auto offload
re-check can still only award residency below the floor.

This is deliberately NOT llama.cpp's own floor. common_params.fit_params_min_ctx
stays 4096 and Unsloth does not pass -fitc, so the child's own fit step can still
reduce an explicit -c below this. Recorded in the comment rather than left for a
reader to discover.

test_the_projector_residency_floor_is_the_fit_floor_and_not_the_offload_context
asserted _MMPROJ_FIT_FLOOR_CTX != _AUTO_OFFLOAD_CTX. That was a proxy for "do not
wire the projector floor to the offload fallback" and it only worked while the two
numbers differed; at 8192 both it would fail on a correct tree and pass on a wrong
one as soon as the fallback moved. It now asserts the assignment is not derived
from _AUTO_OFFLOAD_CTX, which is the mistake it exists to catch and holds whatever
the numbers are. Verified: wiring _MMPROJ_FIT_FLOOR_CTX = _AUTO_OFFLOAD_CTX fails
the new check and would have passed the old one.

@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: 38cdbb6ad2

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

else:
value, step = "", 1
normalized = value.strip().lower()
if normalized in _PAGEABLE_LOAD_MODE:

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 Strip shadowed mmap+mlock selectors during the rewrite

When --load-mode mmap+mlock --no-mmap is supplied, last-wins parsing makes the original launch unlocked and unmapped, but mmap+mlock is absent from _PAGEABLE_LOAD_MODE, so the rewrite removes only --no-mmap and resurrects the earlier lock; the same occurs with inherited LLAMA_ARG_LOAD_MODE=mmap+mlock followed by an argv --no-mmap. The resulting oversized mapping is page-locked into the RAM this override is intended to protect. Fresh evidence beyond the earlier shadowed-mlock finding is that the current fix covers bare --mlock and --load-mode mlock, but still leaves this mapped-lock spelling intact.

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.

Correct, fixed in 9e92efb. Measured before the fix, resolve_effective_memory_state reports mlock=False for both --load-mode mmap+mlock --no-mmap and an inherited LLAMA_ARG_LOAD_MODE=mmap+mlock with an argv --no-mmap, and mlock=True after the rewrite. The two spellings already covered stay False either way, so this was the same defect one spelling further on.

A mapped lock is now stripped in that shadowed state and in no other. On its own mmap+mlock already maps, holds no full unmapped copy and is not this override's business, so it comes back byte for byte with an empty override list, which a new control pins: without it, a launch that was always pageable would be reported as having been remapped.

The argv and env halves now share one _pageable_mode_replacement helper rather than each carrying their own copy of the mode table, since handling a mode in one and forgetting it in the other is exactly how this spelling was missed.

… projector

Two staleness bugs in the advisory this PR introduced.

The reset is moved to the teardown. `_begin_load_warnings()` ran on the first
line of `load_model`, but there are fourteen exits above the Phase 1 teardown
(the update-in-progress refusal, the duplicate-load fast path, a Vulkan pin, a
non-chat or diffusion refusal, several cancels) that leave the resident server
running. Clearing on the way past retired the advisory of a child that keeps
serving, so the next `already_loaded` answered `memory_warning: null` for an
oversized model that is still paging from disk. It now sits inside the Phase 1
lock next to the `_cpu_fallback_reason` and `_mmproj_fallback_reason` resets,
which are placed there for the same reason. That line separates "the old child
survives" from "the old child is gone", so early returns added later are covered
without per-site bookkeeping. Nothing above it records a warning.

The text-only fallback reprices the projector it dropped. The APU preflight
charges `model_size + _mmproj_pinned_bytes`, because a projector pinned to the
CPU lands in the same system RAM as the weights. When the projector then fails
to start and the retry strips `--mmproj`, the child that serves the session
never reads those bytes, so the advisory described a load nothing is running.
It is priced again once the text-only child is healthy, against the RAM figure
the preflight read rather than a fresh one: by that point the weights are
resident, so a live reading is the pool minus the model being priced and would
report a shortfall for a load that demonstrably just started.

The pageable-load override is reported, not reverted. Its argv was spawned and
`force_pageable_load` rewrote the shared child env in place, so the server is
memory-mapped whatever the message says; taking it back would mean another
respawn on the recovery rung that exists because this model already failed to
start once. A load whose only remaining news is that override now says so and
nothing else.

Tests: an APU oversized only by its pinned projector, in both the pageable and
unmapped shapes; the reprice reading the pool the preflight saw rather than the
one the model is now in; a control where the weights alone still overflow; and a
resident advisory surviving three distinct pre-teardown rejects, including the
`already_loaded` fast path the route reads for `memory_warning`.

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

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

self._memory_policy_active,
self._memory_mlock_applicable,
)
self._record_load_warning(_offload_msg)

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 Reprice the warning after a Vulkan CPU fallback

When the initially selected Vulkan GPU hard-crashes and _try_auto_vulkan_cpu_fallback successfully replays the model with --gpu-layers 0 --device none, this warning remains priced against the original GPU pool. A model that fit in VRAM but exceeds available system RAM therefore returns memory_warning: null even though the serving CPU process must page the entire model from disk; an existing warning can likewise describe GPU offload that the resident child no longer performs. Recompute the advisory for the CPU-only replay, as the architecture-fallback path already does when its effective placement changes.

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.

Correct, fixed in 9c6f21e. Verified before fixing: on the success path _try_auto_vulkan_cpu_fallback reassigns the intent, the memory state and every placement variable and returns True without ever touching _last_load_warning, while _cpu_isolated_replay appends --gpu-layers 0 --fit off --device none, so the serving child is credited no VRAM at all.

Repriced against the whole model in system RAM, reusing the existing shortfall wording rather than adding new strings, at the point the replay is known healthy rather than where it is chosen. A failed replay returns above the reprice and can still fall through to another argv, so nothing is priced against a placement about to be abandoned, and the argv read is _last_spawn_cmd rather than the prepared one, so an in-loop retry cannot leave the pricing describing a command that never ran.

The RAM figure is a snapshot taken before any spawn. By the time the replay is healthy the weights are resident, so a live reading would be the pool minus the very model being priced. The snapshot is taken only where a CPU replay is possible, so every other path keeps its previous behaviour.

The load-mode override is carried rather than reverted, and the reason is concrete: the replay is built from the already-rewritten argv, and the env vars the CPU fallback strips are placement only and name no mmap or load-mode setting, so the CPU child genuinely inherits it. The note is carried across verbatim and a test asserts it appears exactly once.

One nearby case checked and deliberately left alone: the arch-crash retry reprices with its own live read, which would misalign with this snapshot, but it is gated on HIP kernel-image markers while this path requires a Vulkan binary, so the two are not co-reachable.

Tests cover a model that fits VRAM but not RAM being warned only once it lands on CPU, a GPU-placement warning not surviving onto the CPU child, the override note carried without a revert, a pool that collapses after residency proving the snapshot is used, and a control that a Vulkan load which never falls back is unchanged. The harness runs the real fallback preparation, so the priced argv is the one the code builds.

danielhanchen and others added 2 commits August 27, 2026 09:00
`_try_auto_vulkan_cpu_fallback` replays an eligible signal crash with
`--gpu-layers 0 --fit off --device none`. On success it reassigns the intent,
the memory state and every placement variable, but it never touched
`_last_load_warning`, so the advisory still described the GPU placement that
died. Two ways that is wrong: a warning priced against VRAM survived onto a
child that holds none, and a model that FIT in VRAM but exceeds system RAM was
never warned at preflight even though the CPU-only child must now page all of it
from disk, so `memory_warning` was null in the case that needs it most.

Repriced against the whole model in system RAM, with no VRAM credited, reusing
the existing shortfall wording rather than adding new strings. Priced at the
point the replay is known HEALTHY, not where it is chosen: a failed replay
returns above the reprice and can still fall through to another argv, and the
argv read is `_last_spawn_cmd` rather than the prepared one, so an in-loop retry
cannot leave the pricing describing a command that did not run.

The RAM figure is a snapshot taken before any spawn, not a fresh reading. By the
time the replay is healthy the weights are resident, so a live reading is the
pool minus the very model being priced. The snapshot is taken only when a CPU
replay is possible, so every other path keeps the previous live-read behaviour.

The pageable-load override is carried, not reverted, and this time the reason is
concrete: the replay is built from the already-rewritten argv, and the env vars
the CPU fallback strips are placement only and name no mmap or load-mode
setting, so the CPU child really does inherit the override. The note is carried
across verbatim and a test asserts it appears exactly once.

The arch-crash retry re-prices with its own live read, which would misalign with
this snapshot, but it is gated on HIP kernel-image markers while the CPU
fallback requires a Vulkan binary, so the two are not co-reachable. Left alone.

Tests: a model that fits VRAM but not RAM, warned only once it lands on CPU; a
GPU-placement warning not surviving verbatim onto the CPU child; the override
note carried without a revert; a pool that collapses after residency, proving
the snapshot is used; and a control that a Vulkan load which never falls back is
unchanged. The harness runs the real fallback preparation so the priced argv is
the one the code builds.
@danielhanchen

Copy link
Copy Markdown
Member Author

The 51 backend failures here all come from one change, and it is not the one in the title.

Alongside the refusal-to-warning work, this PR raises _FIT_MIN_CTX 4096 -> 8192 in four places (llama_cpp.py:2847, _cap_ctx_to_per_device_reserve, _MMPROJ_FIT_FLOOR_CTX, _fit_context_to_vram). The slot re-fit block at llama_cpp.py:18829-18990 is not touched at all - the effect is entirely through the constant those lines read:

  1. _reduce_ctx (:18863) becomes min(effective_ctx, 8192), so the probe prices double the per-slot KV.
  2. _slots_that_fit_on_gpu then returns a truthy _uf_slots, and if not _uf_slots: (:18889) gates the entire reduction and re-fit body.
  3. _slots_hold never runs, include_requested=True is never passed, and the spy counter stays 0 - hence assert 0 > 0 on all nine GPU cells.

I do not think that is a CI problem to be fixed by updating the tests, for two reasons.

The rescue bands. Simulating the bump locally, TestTheReductionIsPricedAtTheFitFloor::test_a_load_the_reduction_can_rescue_never_offloads fails across the whole RESCUED band with a placeable load was handed to --fit offload. Those rows (10,900/11,000/11,100 hybrid and 9,800/10,000/10,500 dense) are documented in that file as launching --fit off before #9492 and --fit on after it, which is the ~3x decode collapse #6718 exists to avoid. Raising the floor gives them up again. That may be an acceptable trade - "do not sacrifice context below 8192 merely to keep weights resident" is a defensible policy - but it is a product decision, and the PR does not state it.

The coupling assertion. The bump makes _FIT_MIN_CTX == _AUTO_OFFLOAD_CTX, and the comment at llama_cpp.py:2856-2868 calls that invariant "not a style rule, a correctness one". This PR resolves the collision by deleting the assertion in test_auto_offload_ctx_fit_floor_coupling.py. If the two constants are now equal by design, the invariant needs restating rather than removing - otherwise the next person to move either one has nothing telling them the two are related.

Suggestion: split the fit-floor change into its own PR, so the refusal-to-warning half here can land on its own merits. The follow-up would need test_slot_refit_platform_matrix.py, test_slot_refit_ctx_checkpoints.py and test_slot_reduction_context_refit.py migrated (none are in this diff), and the #6718 trade-off stated explicitly.

Separately, I have opened #9845, which stops those three files spelling the floor as a literal and adds an anti-vacuity check that reports why the nine cells went dark instead of assert 0 > 0. It does not touch production code and does not paper over the RESCUED failures - those still fire, correctly. Rebasing on it once it lands should make the remaining failures here much easier to read.

danielhanchen and others added 2 commits August 27, 2026 09:33
… no fitter runs

Two ways the earlier commits left a load worse off than they found it.

A Vulkan launch that FITS in VRAM keeps a user's --no-mmap, correctly, because
nothing is oversized yet. When Vulkan then hard-crashes, the CPU fallback strips
only Unsloth's own fit-derived load modes, so that mode survives into a replay
carrying `--gpu-layers 0 --fit off --device none`, which holds the entire model
in host RAM unmapped. For a model larger than available RAM that is an OOM kill.
The reprice added a commit ago made this sharper rather than safer: it predicted
the shortfall, described the child as memory-mapped when the argv said
`--no-mmap`, and spawned it anyway.

The replay is now priced and rewritten inside `_prepare_cpu_fallback_launch`,
the one place both replay sites pass through, against its own footprint with no
VRAM credited rather than against a preflight verdict for a placement that no
longer exists. It shares a single RAM reading with the reprice, so the rewrite
and the advisory cannot reach opposite verdicts, and the override note follows
the same rules as the main path. UNSLOTH_ALLOW_HOST_OFFLOAD still silences the
warning and still does not license the OOM, which is what the main path does.

Metal's zero-context floor went to _FIT_MIN_CTX on the argument that 8192 is
safe to hand a Mac only because the child's --fit can still reduce it to 4096.
That argument fails where the user turned the fitter off: Manual GPU memory with
Auto layers plus a pass-through `--fit off` reaches the floor with the exemption
correctly withdrawn and emits 8192 with nothing able to bring it down, so a Mac
with room for 4096 but not 8192 fails at startup or decode.

The floor now hands over `_LLAMA_FIT_MIN_CTX`, a named constant for llama.cpp's
own `common_params.fit_params_min_ctx`, which is precisely the number the fitter
would have reduced to. The user's `--fit off` is not taken back: they typed that
flag, the context floor is one we invented, and this repo already keeps a
`--fit off` retry because llama.cpp's fit step has aborted on real hosts, so
re-arming it would trade a shorter context for a hard abort on the user's own
setting.

The `auto_fit` exemption's docstring claimed callers pass it only while --fit
will run. That was prose with nothing checking it, which is how this arm went
wrong. The conjunction now happens inside the function, `fitter_runs` also reads
LLAMA_ARG_FIT since llama.cpp applies it before argv, and a test walks the source
to assert every backend call states whether the fitter runs, failing with the
file, line and remedy rather than as a wrong-value assertion.

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

ℹ️ 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 +21397 to +21400
if _apu_ram_oversized or _offload_msg:
return True
if not self._host_offload_warning_opted_out():
return 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.

P1 Badge Price pinned unmapped loads against reachable VRAM

When a discrete multi-GPU host pins the child to only a subset of its cards, this predicate can leave --no-mmap or --load-mode none unchanged even though the launch cannot fit in RAM. _launch_host_shortfall_message computes free_vram_mib from every detected discrete GPU (lines 9083-9086), not the devices reachable through the pin, so a model may appear VRAM-resident only because unused cards were credited; the nonpageable child then allocates its actually offloaded weights in host RAM and can be OOM-killed. Fresh evidence beyond the earlier nonpageable-mode findings is this explicit-pin case: the new remapping decision reuses an intentionally placement-agnostic advisory. Price the safety rewrite using only the GPUs the finished launch can reach.

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.

Correct, fixed in ca4daa8. The preflight passed _detected_gpus, every card, while the arch-crash retry already priced against its own narrowed rows, so the preflight was the outlier rather than the design. Pinned to a subset, the hidden cards were credited, the spill priced out at zero and the unmapped request was left standing on a launch that cannot fit.

It now prices against the cards this launch pinned the child to, at both the advisory and the override decision, since the override reads the advisory and fixing only one of them would change nothing.

Worth recording how I got there, because my first attempt was wrong in a way the tests caught. I derived the reachable set by reading the visibility mask out of env, on the reasoning that every narrowing converges there. That double-counts: an inherited CUDA_VISIBLE_DEVICES has already been applied by the probe, which only ever reported the cards it left visible, so subtracting it again prices a single-card host as having none. It failed 36 tests. The pin is now tracked as the launch performs it, at the two sites that emit the mask, with None meaning nothing narrowed the launch rather than an empty pin.

Tests: an unmapped load pinned to one of two 24 GB cards with a 25 GB model, across all four unmapped spellings, which fail without the change; plus a control on the same pin where the model fits the card it got, so nothing is overridden. That control is also what fails if the reachable set is ever derived from an inherited mask again.

self._cleanup_cpu_fallback_runtime()
return False
replay, _spawn_cwd = prepared
replay, _spawn_cwd, _cpu_pageable_note = prepared

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 Carry the pageable override across failed CPU attempts

When an MTP-bearing Vulkan crash first tries a nonterminal CPU replay and the user's nonpageable mode comes only from an LLAMA_ARG_* environment variable, _prepare_cpu_fallback_launch removes that variable from the shared env in place and returns the disclosure in _cpu_pageable_note. If this drafter-bearing CPU spawn fails, the terminal=False branch returns without retaining the note; the subsequent drafterless replay sees an already-pageable environment, produces no new note, and can succeed. Its memory_warning then describes ordinary memory-mapped paging but never reports that Unsloth overrode the user's load mode. Preserve a per-attempt environment or carry the first override note into whichever replay succeeds.

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.

Correct, fixed in ca4daa8. The rewrite mutates the shared child env in place, so only the first replay that needs it produces a note; the terminal=False branch returned without carrying it, and the drafterless replay behind it then found an already-pageable env, produced no note of its own, and could come up reporting ordinary paging with no mention that the load mode had been overridden.

The note is now carried across attempts and handed to whichever replay succeeds, rather than trying to give each attempt its own environment: the env is deliberately shared so the rewrite happens once, and per-attempt copies would either repeat the rewrite or lose the fact that it already happened.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026
Two ways the override could still hand a child an OOM.

`_launch_host_shortfall_message` sums free VRAM over every row it is given,
which is right for an advisory about the host and wrong for a decision about one
launch. The preflight passed every detected GPU, so on a multi-GPU host that
pins the child to a subset the unreachable cards were credited, the spill priced
out at zero, and a `--no-mmap` request was left standing on a launch that cannot
fit. The child then allocates its offloaded weights in host RAM and is
OOM-killed, which is exactly what the override exists to prevent. The arch-crash
retry already priced against its own narrowed rows; the preflight was the
outlier. It now prices against the cards this launch pinned the child to.

The pin is tracked as the launch performs it rather than read back out of the
env. An inherited CUDA_VISIBLE_DEVICES is already applied by the probe, which
only reports the cards it left visible, so re-reading the mask here subtracts
the same pin twice: measured, that priced a single-card host as having none and
broke 36 tests. `_launch_pinned_ids` is set where the visibility mask is
emitted, by Unsloth's own selection and by the arch gate's survivors, and None
means nothing narrowed the launch, which is not the same as an empty pin.

The pageable rewrite mutates the shared child env in place, so only the first
CPU replay that needs it produces a disclosure note. A non-terminal replay
failure returned without that note, and the drafterless replay behind it then
found an already-pageable env, produced none of its own, and could succeed while
its memory_warning described ordinary paging and never said the user's load mode
had been overridden. The note is carried across attempts to whichever replay
comes up.

Tests: an unmapped load pinned to one of two cards, across all four unmapped
spellings, which now remaps instead of launching as asked; and a control on the
same pin where the model fits the card it got, so nothing is overridden and no
warning is invented. That control is also what fails if the reachable set is
ever derived from an inherited mask again.

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

ℹ️ 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 +21439 to +21442
if _apu_ram_oversized or _offload_msg:
return True
if not self._host_offload_warning_opted_out():
return 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.

P1 Badge Price non-mmap copies against host RAM alone

On a discrete-GPU host where the model fits in VRAM but is larger than available system RAM, this predicate returns false because _launch_host_shortfall_message subtracts reachable VRAM from the model size before testing RAM (offload_bytes at line 9109). However, --no-mmap, --load-mode none, and mlock require the full model-sized anonymous host allocation during loading, so the child can still be OOM-killed even though no weights ultimately spill from VRAM. Fresh evidence beyond the earlier non-pageable findings is that the current rewrite continues to credit even reachable VRAM for a load-time copy that must fit wholly in RAM; use a full-model host-RAM predicate when the effective mode is non-pageable.

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.

Checked this against llama.cpp's loader source rather than reasoning about it, and the premise does not hold, so no change here.

The claim is that --no-mmap needs a full model-sized anonymous host allocation during loading even for weights that end up in VRAM. In src/llama-model-loader.cpp, the non-mmap upload path is:

} else {
    read_buf.resize(n_size);
    file->seek(weight->offs, SEEK_SET);
    file->read_raw(read_buf.data(), n_size);
    ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);

with size_t n_size = ggml_nbytes(cur);, i.e. the size of the CURRENT tensor. read_buf is one std::vector resized per tensor and reused, so the peak host allocation for VRAM-resident weights is roughly the largest single tensor, not the model. The pinned-buffer path above it is likewise a small fixed set of staging buffers. What genuinely stays in host memory is the tensors that are not offloaded, which is exactly model_size - reachable_vram, the quantity the predicate already uses.

So requiring the whole model to fit host RAM whenever the mode is non-pageable would rewrite or warn on loads that run correctly today: a 40 GB model wholly resident on a 48 GB card with 16 GB of host RAM is fine, and this would call it an OOM. Under the strict bar that is a false positive rather than a fix.

I have taken the neighbouring point, that reachable VRAM is the right pool to credit rather than every detected card, and that landed in ca4daa8. If you have a specific build or a shape where the non-mmap path really does hold the full model on the host while the weights are GPU-resident, point me at it and I will reopen this.

Comment on lines +19193 to +19196
# No KV estimate: mirror the discrete file-size-only fallback
# and floor to 4096 rather than launch at native and over-commit.
max_available_ctx = min(4096, native_ctx_for_cap)
# and floor to _FIT_MIN_CTX rather than launch at native and
# over-commit.
max_available_ctx = min(_FIT_MIN_CTX, native_ctx_for_cap)

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 Keep the no-KV Metal fallback at the no-fitter floor

On Metal with Auto context, incomplete GGUF KV metadata, and a user-supplied --fit off (or equivalent environment setting), this now assigns a positive 8192-token context and therefore bypasses _metal_zero_ctx_floor, whose first condition returns for any positive effective_ctx. A Mac that could handle the former conservative 4096 fallback but not 8192 can consequently fail at startup or decode because no child fitter remains to reduce it. The fresh evidence beyond the earlier zero-context fix is this regular no-KV cap path: it never reaches that fix because line 19198 makes the raised floor positive before the helper runs.

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.

Correct, fixed in 9f4093a. My previous commit made the no-fitter distinction inside _metal_zero_ctx_floor, but as you say that helper returns immediately for any positive effective_ctx and the Apple cap assigns one before it runs, so the ordinary cap path never reached it.

The three cap assignments now take their floor from a value computed once at the top of the arm: _FIT_MIN_CTX while the fitter runs, llama.cpp's own fit_params_min_ctx when argv or LLAMA_ARG_FIT has turned it off.

One detail worth recording, because my first test passed without the fix and was therefore worthless. Only the DEFAULT memory mode reaches this path: Manual with Auto layers resolves an Auto request to 0 and takes the zero-context route the previous commit fixed. I had written the test with Manual plus Auto layers, so it exercised the already-fixed path. Retargeted to the default mode it fails without the change and passes with it, alongside a control that a launch which still has a fitter keeps the raised ceiling.

… context

Raising Metal to _FIT_MIN_CTX was justified by the child's own --fit being able
to come down from 8192 to llama.cpp's 4096. The previous commit made that true
in _metal_zero_ctx_floor, but that helper returns immediately for any positive
effective_ctx, and the Apple cap assigns a positive context before it runs. So
the ordinary Auto path with a context length in the GGUF and a user-supplied
--fit off still emitted 8192 with nothing able to reduce it, which is the same
Mac failure the previous commit set out to prevent.

The three cap assignments now take the floor from a value computed once at the
top of the arm: _FIT_MIN_CTX while the fitter runs, and llama.cpp's own
fit_params_min_ctx when argv or LLAMA_ARG_FIT has turned it off.

Only the default memory mode reaches this. Manual with Auto layers resolves an
Auto request to 0 and takes the zero-context path the previous commit fixed,
which is why the first version of the test passed without the change: it drove
the wrong mode. Retargeted, it fails without it.

Tests: the no-KV cap landing on llama.cpp's floor with the fitter off, and a
control that a launch which still has a fitter keeps the raised ceiling.

@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: 9f4093a73b

ℹ️ 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 same way the APU preflight's override reaches the message,
# and a no-op on a load whose warning the opt-out silenced, which
# keeps the log line as its only record.
self._amend_load_warning(_replay_pageable_note)

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 Reprice restored CPU fallbacks after startup

When a persisted cpu_fallback=True load is reconstructed while the Vulkan memory probe returns an empty pool, the initial host check abstains because _child_has_no_gpu only credits _cpu_only_zero_offload when _detected_gpus is nonempty. _prepare_cpu_fallback_launch then establishes a definitive CPU-only --device none replay and may even remap an oversized nonpageable mode, but this call can only append to an existing warning; it cannot create the missing CPU shortfall warning. A successful restored CPU session can therefore return memory_warning: null and omit the override disclosure even though the whole model exceeds host RAM. Fresh evidence beyond the generic empty-probe case is that this replay has proven CPU-only placement and _reprice_after_cpu_only_fallback already supports pricing it; invoke that repricing after this direct replay starts successfully.

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 49169c7. The prepare site that restores the CPU-only fallback now records the intent in _restored_cpu_reprice, and the reprice runs just before self._healthy = True, so a fallback restored after startup is priced against host RAM like one taken during the initial spawn. It carries the replayed pageable note through when there is one. Regression test drops the probe pool entirely rather than reporting a card with zero free, which is what makes it fail without the change.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026

@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: 74dae7fde6

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

# pinned away is not VRAM it can spend: crediting it prices the spill
# too low and leaves an unmapped oversized load unrewritten, which is
# an OOM rather than the slow load the override exists to produce.
_reachable_gpus = self._rows_the_child_can_reach(_detected_gpus, _launch_pinned_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 Apply Vulkan device pins to host-shortfall pricing

On a multi-GPU Vulkan host where the fitter narrows the launch to a subset, this still passes every detected GPU because _launch_pinned_ids remains None: Vulkan emits its pin as --device Vulkan… at line 20889, while _launch_pinned_ids is assigned only in the non-Vulkan visibility-mask branches. A 25 GiB model pinned to one 20 GiB-free card can therefore be priced against two cards, leaving an effective --no-mmap/load-mode none unchanged even when the host cannot hold the real spill, so the child can be OOM-killed. Fresh evidence beyond the prior pin finding is this Vulkan-specific omission in the current fix; propagate _vulkan_pin_ids into the reachable-card calculation.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 2c69e1d into main Aug 27, 2026
2 of 50 checks passed
@danielhanchen
danielhanchen deleted the host-ram-guard-warn-not-refuse branch August 27, 2026 12:39

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

ℹ️ 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 +21561 to +21563
_preflight_avail_mib = (
self._available_system_memory_mib() if _cpu_fallback_eligible else None
)

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 Snapshot RAM for restored CPU fallbacks

When a real persisted CPU fallback is reconstructed, its intent is normalized to gpu_memory_mode="manual" and gpu_layers=0, so the earlier _cpu_fallback_eligible call (which does not set allow_manual_cpu=True) is false and this stores None. The restored path later accepts that same intent with allow_manual_cpu=True, but after the CPU child becomes healthy it passes this None to _reprice_after_cpu_only_fallback; the helper consequently rereads available RAM after the model has occupied it and can emit a spurious shortfall for a model that fit before launch. Fresh evidence beyond the earlier restored-fallback report is that the newly deferred reprice exists, but its promised pre-spawn snapshot is excluded specifically for the manual/0 intent that restoration produces; capture RAM for that eligible restored path as well.

Useful? React with 👍 / 👎.

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