Skip to content

studio: refuse a gguf that cannot fit in free vram plus available ram - #8883

Merged
Etherll merged 41 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-host-offload-ram-guard
Aug 18, 2026
Merged

Etherll merged 41 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-host-offload-ram-guard

Conversation

@mahiatlinux

@mahiatlinux mahiatlinux commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

An Ubuntu user reports Unsloth Desktop freezing and then dying with the machine.

--fit on places what it can in VRAM and spills the rest into host memory with
no ceiling of its own, and nothing upstream of llama-server prices that spill.
The weights are memory-mapped, so an oversized remainder does not fail an
allocation: the kernel evicts and re-reads the mapping every token until the
machine stops responding, and systemd-oomd then kills the whole app slice.

The reported session loaded a 13.3 GB gemma-4-26B-A4B-it-qat GGUF plus a
1.1 GB mmproj and a 1.8 GB KV cache onto a card with 4877 MiB free, leaving
about 11 GB to run from system RAM. The server log ends mid-poll with no
shutdown line and no parent_watchdog.parent_exited, which is what a SIGKILL of
the whole process group looks like.

llama_cpp.py already refuses this on Apple unified memory
(_apple_metal_memory_budget_bytes) and on AMD APUs
(_apu_ram_shortfall_message), but _amd_apu_wants_unified_memory is false for
a discrete card, so CUDA and ROCm hosts had no guard at all.

What it checks

refuse when  model_bytes - free_vram  >  available_ram - 2 GiB

Weights only, against the whole free VRAM pool, read from the finished argv so
the model path is the one the child opens. That is a strict lower bound on what
the launch must hold: the KV cache, projector, drafter and compute buffers all
add to residency, and a layer or device pin only narrows the VRAM actually
reachable.

Every term left out therefore moves the estimate down, never up, so no missing
term can turn an allowed load into a refused one. The guard models no placement
at all, which is what keeps it from having to track llama.cpp's placement
surface flag by flag. It abstains on an unsized model, an unprobed GPU pool, or
unknown available RAM.

Two signals take no VRAM credit on their own: the ROCm arch gate finding no
kernels for any card present, and a paravirtual Metal launch. Each names a device
that was seen and ruled out, so the empty pool beside it is the gate's own doing.
A launch masked off every device and a build shipping no GPU backend also take no
credit, but only where a pool was actually probed: neither says a device exists,
so on an empty pool they cannot separate a GPU-less host from a probe that threw.
An RPC launch abstains outright, since it places layers on remote devices this
cannot size.

UNSLOTH_ALLOW_HOST_OFFLOAD=1 abstains, and the refusal names it, so a user who
accepts the paging can still load a variant the picker offers. Same shape as
UNSLOTH_ALLOW_PARAVIRTUAL_METAL, the file's existing escape for a hard guard.

The guard reads the finished argv, so it cannot answer until after the route has
taken acquire_for(CHAT), evicted a resident Images/Video pipeline and cancelled
the running generations. host_offload_refusal_for_intent asks the same function
ahead of that handoff, crediting the ungated probe that every narrowing the launch
applies only shrinks, so it refuses a strict subset and fails open into the launch
copy. Same placement and same reason as non_chat_gguf_refusal_for_intent.

An earlier revision of this PR modelled the placement in full and was rewritten;
2220d79de and the comment above it record why.

Testing

test_host_offload_ram_guard.py covers the arithmetic. The placement suite
drives load_model end to end: the field case refuses, the same load on a large
RAM host launches, free VRAM offsets the charge, and each abstention holds. A
parametrised case asserts the floor property directly, that -ngl 0, --mlock,
--no-mmap, --device none and --no-kv-offload each move bytes onto the host
or narrow reachable VRAM and so can never produce a refusal the floor would not
already reach.

Every fix in this PR carries a regression test verified to fail against the code
before it, and each of the two probed-pool gates is pinned by its own arm: gating
only the build probe fails the zero-offload case, gating only zero-offload fails
the CPU-only-build case. 366 tests pass across the guard, placement, paravirtual,
arch-gate and preflight suites, 184 across the route suites, and the wide-sweep
failure set is identical to a clean tree.

Also run end to end against the real llama-server (b10360, Darwin arm64) with
a real GGUF, simulating only free VRAM and MemAvailable. Each cell is a real
spawn, health wait and HTTP completion: a shortfall refuses and names the escape,
the escape starts the server and serves, an empty pool with a CPU-only build and
an empty pool with manual zero-offload both abstain and serve, and a probed pool
with a CPU-only build still refuses. A separate cell reproduces the Apple Silicon
false refusal with nothing about the GPU simulated, real _get_gpu_memory()
returning []: refused before this change, served after.

`--fit on` places what it can in VRAM and spills the rest into host memory with
no ceiling of its own, and nothing upstream of llama-server prices that spill.
The weights are memory-mapped, so an oversized remainder does not fail an
allocation: the kernel evicts and re-reads the mapping every token until the
machine stops responding, and systemd-oomd then kills the whole app slice.

llama_cpp.py already refuses this on Apple unified memory and on AMD APUs, but
_amd_apu_wants_unified_memory is false for a discrete card, so CUDA and ROCm
hosts had no guard. _host_offload_shortfall_message adds the same ceiling,
priced on the spill rather than on the whole model.

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

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

… guard

Three cases where the host-offload guard read a footprint the launch does not
produce.

Manual + Auto layers omits -c and leaves effective_ctx at 0, so _kv_bytes(0)
returned zero while the launch still floors --fit-ctx at 8192 and allocates that
KV. Price the floor, now a shared _AUTO_FIT_MIN_CTX so the guard and the emitted
flag cannot drift.

The Model Memory page-lock setting emits mmap+mlock for a --fit on launch, which
pins the whole mapping in host RAM including the layers copied to the GPU.
Subtracting free VRAM there under-prices by the GPU-resident portion, so charge
the whole mapping when should_mlock() is set.

A Vulkan iGPU reports shared system RAM as its free VRAM and total 0. Subtracting
it and then charging the remainder against that same RAM counts the pool twice,
so a 20 GB model on a 14 GB host read as a 6 GB requirement. Exclude a total-0
Vulkan device from the VRAM offset.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 20369b674b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

Comment on lines +14883 to +14887
_offload_msg = self._host_offload_shortfall_message(
model_size
+ _guard_kv_bytes
+ _mtp_reserve_bytes
- _fit_vram_mib * 1024 * 1024,

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 Include GPU compute allocations in the spill estimate

For a --fit on load at a large context or across multiple GPUs, _compute_buffer_pipeline, the context-linear _cc_bytes(...), and _soft_overhead consume VRAM before weights can be placed; the placement logic includes these terms in model_size_fit at line 14326. This calculation instead subtracts all raw free VRAM from only the model, KV, and MTP sizes, so every omitted buffer byte can displace another weight byte into host RAM. Once those buffers exceed the fixed 2 GiB headroom, a load whose real spill is larger than available RAM can still pass this preflight and enter the paging/OOM failure being guarded against.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor 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 guard's documented contract is to under-state the spill so that only an unambiguous shortfall refuses: it subtracts raw free VRAM with no margin removed, which already omits llama.cpp's own 1024 MiB --fit-target. Folding in _compute_buffer_pipeline, _cc_bytes and _soft_overhead would turn a deliberate floor into an exact predictor built on estimates, and every one of those terms overshooting refuses a load that would have run. The miss you describe needs the real spill to land inside a narrow band between the 2 GiB headroom and the buffer total; a false refusal costs a user a model that works. Staying conservative.

Comment on lines +14858 to +14864
if (
not _guard_kv_bytes
and effective_ctx <= 0
and gpu_memory_mode == "manual"
and (gpu_layers or 0) < 0
):
_guard_kv_bytes = _kv_bytes(_AUTO_FIT_MIN_CTX)

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 KV memory for metadata-sparse fit loads

The remaining file-size-only placement path is not covered by the new zero-context fix: when _can_estimate_kv() is false, _estimate_kv_cache_bytes returns 0 even for a positive native or requested context, and this fallback is restricted to Manual + Auto with effective_ctx <= 0. Such metadata-sparse GGUFs are deliberately supported by the elif gpus file-size-only branch, but their launched server still allocates a KV cache; at a large context that unpriced cache can push the host spill past available RAM while this guard allows the load.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor 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. When _can_estimate_kv() is false the GGUF is missing the layer, head and embedding metadata the estimate is built from, so there is no principled reserve to apply, only an invented constant. That is why the file-size-only branch exists at all. Guessing high refuses exactly the metadata-sparse models that branch is there to support, and guessing low buys nothing. Leaving the KV term at zero there is the same under-statement the guard is documented to make.

Comment on lines +14851 to +14854
use_fit
and model_size is not None
and kv_cache_bytes is not None
and not self._amd_apu_wants_unified_memory(gpu_indices)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the RAM guard active on placement fallback

If any exception occurs after the model size or GPU pool is known but before the final kv_cache_bytes = _kv_bytes(effective_ctx) assignment, the broad handler at line 14772 deliberately falls back to use_fit = True while leaving kv_cache_bytes as None. This condition then skips the RAM guard entirely, so an estimator, capability, or GPU-selection error sends a potentially oversized model into llama.cpp's fitter with no host ceiling at all. Apply the guard to the known model and GPU data on this fallback, using a conservative or zero KV term when no estimate survived, rather than using KV completion as the sentinel for whether to check RAM.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor 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, and the sentinel is not really about KV. That handler runs when the GPU probe or selection threw, and _detected_gpus is initialized to [] before the try, so on most of those paths the pool never enumerated. Pricing a spill against an empty pool charges the whole model to host RAM and refuses loads that would have run fine on the GPU the probe failed to read. The fallback is deliberately fail-open: an error in our own estimator must not become a refusal for the user. kv_cache_bytes is the sentinel because it is assigned last, so it is the one value that proves the whole block completed.

Manual mode with an explicit layer count emits --gpu-layers N --fit off, but that
only clears use_fit while the command is built, long after the guard reads the
seeded True. At 0 layers the GPUs hold nothing, so subtracting their free VRAM
under-priced the whole model; a positive count cannot be sized per layer here, so
the guard abstains instead of pricing a placement it cannot compute.

--no-kv-offload keeps the whole KV cache in host RAM, where it is not fungible
with weights the GPUs can take. Charge it after the VRAM subtraction rather than
inside it, so 12 GB of weights that fit the card no longer absorb an 8 GB
CPU-resident cache.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: fc14be3ac0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

_kv_on_host = not _kv_offload_from_args(extra_args)
_host_bytes = (
model_size
+ _mtp_reserve_bytes

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drop an automatic drafter before refusing the target load

When speculative mode is Auto and the target itself needs some CPU offload, _spec_dropped_no_vram does not remove the optional drafter because that fallback only runs when the target fits fully on a GPU subset. Adding _mtp_reserve_bytes here can therefore make the RAM guard reject a target whose spill fits by itself—for example, a 4 GiB target spill on a host with 7 GiB available passes the 2 GiB headroom check, but a 2 GiB automatic MTP reserve turns it into a refusal. Since the existing placement policy explicitly drops Auto speculative decoding rather than sacrifice a viable target load, retry this host check with the automatic drafter disabled before raising.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor 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. Skipping _mtp_reserve_bytes in the arithmetic alone would pass a load whose drafter then loads anyway and takes the memory, which is worse than the refusal: the guard would be pricing a placement the launch does not build. Making it right means actually dropping the drafter, which is _spec_dropped_no_vram's job in the speculative fallback, not a RAM preflight's. Charging what the launch will really load is the correct behaviour here. If Auto should also drop the drafter when the target needs CPU offload, that belongs in the fallback that owns the decision, and this guard will price whatever it settles on.

…check

On a mixed ROCm host the arch gate can leave gpu_indices None while pinning the
launch to a discrete card. _amd_apu_wants_unified_memory then saw the whole
physical set, read the unsupported APU as unified memory and skipped this guard,
while the APU guard above had already cleared its own refusal for the same
placement. Ask about the devices the launch will pin instead.

A drafter pinned with --spec-draft-ngl 0 leaves the VRAM budget but keeps its
weights in host RAM, and nothing was charging them. Size it before the CPU
nulling and add it to the host figure.

Both need the spill clamped at zero before host-pinned bytes are added, or spare
VRAM absorbs them: a 4 GB target on a 14 GB card was cancelling an 8 GB CPU
drafter to a negative footprint.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 89a93adf63

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

… guard

With both Model Memory toggles off, apply_model_memory_policy preserves a
caller's --mlock or --no-mmap, so the launch keeps a full host copy while
should_mlock() reports false. Ask resolve_effective_memory_state, which already
answers for argv and env together, instead of the setting alone.

A --device naming no GPU leaves the child nothing to offload onto, so its free
VRAM is credit the launch never gets. _device_selection_is_cpu now zeroes the
offset, alongside the paravirtual and arch-gate cases already there.

A CPU-pinned drafter's KV cache was dropped with its weights when
_mtp_draft_for_budget is nulled; size both before that and charge them to the
host.

_available_system_memory_mib now caps its reading by _cgroup_free_bytes. Inside a
container or systemd scope the binding memory.max is what the OOM killer
enforces, and the host MemAvailable can be tens of GiB above it. The APU guard
reads the same helper and gains the ceiling too.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 83cebc7a3d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

A CPU device override now triggers the host check on its own. A successful fit
clears use_fit, so gating the whole guard on it skipped a retained --device none
that still loads the model on the CPU.

resolve_effective_memory_state gets the launch environment, not just argv.
scrub_memory_env keeps an inherited LLAMA_ARG_MLOCK or a reserving
LLAMA_ARG_LOAD_MODE when both toggles are off, and argv alone cannot see them.

The CPU drafter's KV is sized at the fit floor, matching the main KV term:
Manual + Auto leaves the context at 0, where _mtp_draft_kv_bytes returns None
while the launch still emits --fit-ctx.

The cgroup reading goes through _shared_policy instead of importing
unsloth.dataset_num_proc directly, which would run the package __init__ and load
the model stack in the middle of a llama.cpp load.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 704eb779cb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

…will run at

Three ways the previous rounds' fixes over-charged a viable load.

An explicit gpu_ids pick strips the device arguments in the command builder, so a
stale --device none no longer zeroes the VRAM credit for a launch that does use
the GPUs.

Page-locking duplicates the weight mapping in host RAM, not the KV cache. The
mlock branch charged the whole combined footprint, so a partially offloaded model
could be refused over a KV cache that never leaves the card. Charge the mapping
and let the GPU pool still cover the GPU-resident KV and MTP terms.

"Don't reserve system RAM" strips --mlock and --no-mmap in
apply_model_memory_policy, so resolving the raw flags claimed a full host copy the
child never keeps. Read both settings and let no-reserve win, as should_mlock does.

Alongside those, the guard context now honours a pass-through --fit-ctx instead of
assuming the 8192 floor, the MTP reserve is recomputed at that same context, and
the CPU drafter's KV is sized with the cache types, SWA, unified and ubatch
options the GPU-side call already passes.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 49e8215518

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

… the charge

An -ngl 0 in the extras is appended after Studio's own flags and wins, so it now
counts as a CPU-only placement alongside --device none. A device override also
beats the positive-manual exemption: that exemption exists because a partial
split cannot be sized, which stops being true once the launch reaches no GPU.

Manual mode at 0 layers leaves the weights in host RAM but a companion-visible
launch still holds its KV and drafter on the card. Zeroing the whole VRAM credit
there charged those to RAM and could refuse a CPU model that fits, so it now
shares the page-lock treatment: the weight mapping goes to host, the GPU pool
still covers the GPU-resident terms.

The auto-fit floor is priced only when the build supports --fit-ctx, since
_ctx_integrity_flags omits the flag otherwise and the fitter may choose less.

_available_system_memory_mib adds back the cgroup's reclaimable inactive_file.
memory.current charges the GGUF's own page cache, which the kernel reclaims
rather than OOM on, so subtracting it counted those pages twice.
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 516a8bd8fa

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

pre-commit-ci Bot and others added 2 commits August 17, 2026 05:31
The preflight probed free VRAM, which still counts the resident llama-server,
Unsloth model and Images/Video pipeline that acquire_for(CHAT) and load_model go
on to reclaim. A 13.3 GB switch on a 24 GB card holding 900 MiB free was refused
with a 400 against memory that was about to come back, so switching models on a
busy GPU stopped working.

Each device's physical total is the ceiling on what the launch can ever see, and
every narrowing the launch applies to the pool only shrinks it further, so the
preflight still charges no more than the launch copy. What survives is the pick
no reclaim can rescue, which is the one worth catching before the teardown. A
device reporting total 0, an iGPU or a MIG/vGPU line, leaves the ceiling unknown
and abstains.

Reported by Codex.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

1 similar comment
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 5658aff7ea

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

Comment thread studio/backend/routes/inference.py Resolved
The VRAM side was fixed for the reclaim the handoff performs; the host side had
the same defect. A resident llama-server holds RAM through its host KV cache,
CPU-offloaded weights and locked mappings, and an active Unsloth model holds more,
all of it released by the route at inference.py:8550 and by load_model's kill of
the previous server. Reading MemAvailable before any of that charged a spill
against memory that was about to come back, so a 30 GB target with 6.7 GB on the
host was refused with a 400 on a machine holding 3 GB free and 64 GB total.

_total_system_memory_mib reads MemTotal, the ceiling MemAvailable can never
exceed, and _launch_host_shortfall_message takes it through a new avail_mib
override so the launch keeps reading what is actually available. Unreadable total
RAM abstains, as an unreadable available figure already did.

Reported by Codex.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

1 similar comment
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 977de468ab

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

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

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

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

Etherll commented Aug 17, 2026

Copy link
Copy Markdown
Collaborator

Fixed both high-risk RAM-accounting gaps in be5bd3416:

  • Vulkan integrated GPUs no longer contribute their shared-memory free_mib as separate dedicated VRAM. The simulated 20 GiB model on a 14 GiB unified pool now refuses instead of counting the same pool twice.
  • Host availability is now capped by the tightest active cgroup v2/v1 remainder (limit - current usage), walking ancestor slices and pairing each limit with its own usage. A 64 GiB host view under an enforcing 12 GiB cgroup remainder now refuses correctly.

The existing fixed 2 GiB host reserve is unchanged.

Validation:

  • 71 passed: complete host-offload guard + llama.cpp placement files
  • 1 passed: focused arch-crash narrowed-pool retry
  • Python compilation, Ruff, and git diff --check passed

No model was downloaded or run.

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

ℹ️ 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 +6861 to +6862
used = _integer(_first_line(os.path.join(directory, "memory.current")))
remaining.append(limit if used is None else limit - used)

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 Discount reclaimable cache from cgroup usage

In a cgroup-limited container, memory.current includes reclaimable file-backed page cache, so treating all of it as unavailable RAM can falsely reject viable loads. This is especially likely immediately after downloading or inspecting a large GGUF: its pages may already be charged to the cgroup, and the guard then effectively charges those same mmap-backed weights again. Account for reclaimable cache from memory.stat (and likewise for the v1 path) before using the remainder as a hard refusal threshold.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fixed in 827f564. The cgroup cap now discounts v2 inactive_file and v1 hierarchical total_inactive_file before computing remaining capacity, while staying conservative when memory.stat is unreadable. Added v1 and v2 regression coverage for the 16 GiB limit, 12 GiB current usage, and 8 GiB inactive cache case, including launch admission. This follows the Linux cgroup v2 and v1 memory accounting documentation and the cAdvisor working-set implementation: https://docs.kernel.org/admin-guide/cgroup-v2.html#memory-interface-files https://docs.kernel.org/admin-guide/cgroup-v1/memory.html#stat-file https://github.com/google/cadvisor/blob/6a0c4f2539a8b1c11215804dee404c06fe3e0218/lib/container/libcontainer/handler.go#L876-L899. The 73 guard and placement tests plus the retry-path test pass.

@Etherll

Etherll commented Aug 17, 2026

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@Etherll

Etherll commented Aug 17, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 827f564206

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

Etherll pushed a commit to Etherll/unsloth that referenced this pull request Aug 17, 2026
Etherll pushed a commit to Etherll/unsloth that referenced this pull request Aug 17, 2026

@Etherll Etherll left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM !

@Etherll
Etherll merged commit ee68d9e into unslothai:main Aug 18, 2026
41 of 44 checks passed
danielhanchen added a commit that referenced this pull request Aug 18, 2026
* Unblock Mac Studio GGUF CI, red on every main run since #8883

Mac Studio GGUF CI has failed on every main run from ee68d9e onward, the merge
of #8883 (refuse a gguf that cannot fit in free vram plus available ram). Bisected
over 90 completed main runs: green through 31c42e8, red from ee68d9e, no
recovery since.

The guard is not wrong. From the failing run's own server log:

  Metal device looks virtualised (Apple Paravirtual device) ... GGUF inference
  will run on CPU
  Forcing gpu_layers=0 for gemma-4-E2B-it-UD-Q4_K_XL.gguf
  Error loading model: About 3 GB of this model does not fit in GPU memory and
  would run from system RAM. Only about 4 GB is available and 2 GB of that is
  kept free for the rest of the system, leaving about 2 GB usable.

GitHub's macOS runners expose a paravirtual Metal device, and Unsloth already
refuses to offload to one because paravirtual Apple GPUs return corrupt output.
So the launch is --gpu-layers 0 --device none and the WHOLE model is a host
mapping, not the partial spill the guard was written to price. It then measures
honestly: gemma-4-E2B UD-Q4_K_XL (~2.4 GB) plus mmproj-F16 (~780 MB) does not fit
in 2 GB usable. The load returns HTTP 400 and the phase fails several layers away
from the cause.

The workflow is what was wrong. It had been getting away with a model the runner
cannot hold because the prompts are tiny and the mapping is paged, which is
exactly the gamble the guard stops taking on a user's machine. CI now takes it
knowingly with UNSLOTH_ALLOW_HOST_OFFLOAD, the escape hatch the refusal names,
rather than silently swapping in a smaller model and quietly changing what mac
vision inference is tested against.

Set at job level, not on the vision phase: every phase there is CPU-only for the
same reason, so a runner image with slightly less free RAM would take out the
tool-calling phase next.

tests/studio/test_mac_host_offload_optin.py keeps the blast radius honest. The
opt-out disables a real safety net, so it asserts the reason stays written down
next to it, that the Linux and Windows GGUF workflows never acquire it -- there a
silenced guard would let a genuine host-offload regression pass green -- and that
the guard keeps its own unit tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Run the host-offload guard on workflow-only PRs, and check workflow-level env

The guard rejects a PR that removes UNSLOTH_ALLOW_HOST_OFFLOAD from the macOS GGUF job or
adds it to the Linux or Windows one. Such a PR edits a workflow and nothing else, which
Backend CI's paths filter does not match, so the assertion was never collected for the one
change it exists to reject. Wired into workflow-trigger-lint, which carries no paths filter
and already hosts the other workflow invariants for this reason.

The blast-radius check also read only job and step env. GitHub propagates a top-level env
to every job, so one line at the top of the Linux or Windows workflow would have disabled
the guard across all of them while this test stayed green.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@mahiatlinux
mahiatlinux deleted the fix/studio-host-offload-ram-guard branch September 25, 2026 05:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants