Skip to content

Studio: honour an unmeasured context request and price the real attention plan - #11025

Merged
danielhanchen merged 30 commits into
mainfrom
pr/studio-context-unmeasured
Sep 17, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
pr/studio-context-unmeasured

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Three context and memory numbers Studio reports were computed for a load other than the one
about to start. This fixes the two causes behind them.

  • A context nobody could measure no longer overrules a context the user typed, and is no
    longer published as "the largest that fits". A 256k selection came back as 4,096.
  • The estimate and the launch now share one resolved flash-attention state, so KV cache
    quantization moves the available context instead of being priced away.
  • GET /api/models/kv-cache-estimate can be asked about the plan a launch will really run,
    and resolves it the way the launch does when it is not told.

Root cause

The unmeasurable context (#9653). When a GGUF carries no attention dimensions,
_can_estimate_kv() is False and nothing can price the cache. Two arms fall back to a short
context there: _plan_tensor_parallel (a bare 4096, now named _TP_UNMEASURED_CTX) and the
Metal unified-memory arm (_metal_floor_ctx). Both applied that fallback to an explicit
request and published it as max_context_length, so selecting 262,144 produced

{"context_length": 4096, "max_context_length": 4096, "native_context_length": 262144}

with the context slider then reporting that nothing longer fits, on a model llama.cpp opens
at a useful context when driven directly. The fallback is a guess, which cuts both ways and
is already written down in _metal_context_overcommit_message: it will not refuse against
that number, because refusing on a guess blocks loads that work today. Equally, a guess may
not silently overrule a context the user asked for, and may not be published as a measured
ceiling once the load has run above it.

The attention plan (#9697, #10489). load_model pinned planned_flash_attn = False
unconditionally, as a pre-emptive reserve for the crash recovery that may relaunch a plan
with flash attention off, and then emitted --flash-attn on on every launch whose build has
the flag. The estimator is not indifferent to that state: with flash attention off it floors
the V axis at f16 and pads variable-width V tensors to the model-wide maximum. Measured on
Qwen3's shape at 262,144 tokens:

KV cache priced with flash attention on priced with it off ratio
f16 30,064,771,072 30,064,771,072 1.00x
q8_0 15,971,909,632 23,018,340,352 1.44x
q4_0 8,455,716,864 19,260,243,968 2.28x

In tensor mode --fit is a no-op, so that inflated cache is the only cap and becomes the
published ceiling: q8_0 was selectable but the available context came out sized as though the
cache were fp16. The same pessimistic ceiling is what the context warning compares against
while the memory panel prices the optimistic one, and GET /api/models/kv-cache-estimate had
no parameter for any of it, so one model and one cache type produced three different numbers.

Changes

studio/backend/core/inference/llama_cpp.py

  • _planned_flash_attn_state resolves the flash-attention state a launch will really run at,
    once, and every sizing call takes it: the build's capability, LLAMA_ARG_FLASH_ATTN, a
    last-wins -fa in the extras, and a quantized V cache, which forces it on because llama.cpp
    turns it on itself. An explicit auto is not an answer and is sized as the load that may not
    get it: llama.cpp decides auto at load time and decides against flash attention whenever the
    backend, the model or the cache pair cannot take it, silently, which is a 1.44x KV cache at
    q8_0 and 2.28x at q4_0. Unsloth emits --flash-attn on rather than auto, so only a user's
    extra arguments or an inherited environment variable reach that arm.
  • _TP_UNMEASURED_CTX, beside the other context floors, for the one arm the _FIT_MIN_CTX
    paragraph already excluded: with no KV metadata nothing can prove a safe cap.
  • _plan_tensor_parallel takes explicit_ctx (default False, so every existing caller keeps
    its behaviour). It is read only when the KV cache cannot be sized: the fallback then
    honours the request and publishes a ceiling the launch does not contradict. With a real KV
    estimate the cap is a measurement and still binds, which is what --fit being a no-op in
    tensor mode requires of it.
  • The Metal arm marks the no-estimate verdict and publishes what ran rather than the floor.
    Its measured verdicts, including the refusal, are untouched.
  • _unmeasured_context_notice, recorded on last_load_warning by both arms, so the load says
    once that the reported maximum is the request rather than a measured ceiling. Auto is not
    told anything: it made no request, and it keeps the conservative fallback.
  • _planned_flash_attn_state resolves the state a launch will really run at from the build's
    capability, LLAMA_ARG_FLASH_ATTN, a last-wins -fa in the extra arguments, and the
    quantized-V rule llama.cpp applies itself. load_model uses it in place of the pin, so one
    answer feeds every sizing call and the argv.

studio/backend/routes/inference.py

  • _gguf_runtime_bytes resolves through the same helper. That also closes a gap its own
    two-step form had: a quantized V forced flash attention on even on a build with no
    --flash-attn to emit, where the launch rewrites the V cache to f16 instead and the padded
    price is the right one.

studio/backend/routes/models.py

  • GET /api/models/kv-cache-estimate accepts flash_attn, kv_unified, swa_full and
    no_mmproj_offload, all optional. An asked-for value is expressed as the extra argument a
    load would carry and resolved by the same helpers, so the route cannot answer for a launch
    that cannot happen. Omitted, they resolve the way the launch resolves them. The same plan is
    handed to the planner half of the response, so kv_bytes and gpu_bytes in one answer
    cannot describe two different loads. The response shape is unchanged.

The pre-emptive flash-attention reserve is not replaced by anything, because two mechanisms
already provide what it was for. Tensor mode cannot take the flash-attention-off recovery at
all (llama.cpp requires flash attention for SPLIT_MODE_TENSOR, which
test_tensor_quant_kv_platform_matrix.py already pins), and elsewhere the no-flash respawn
re-enters _spawn_and_wait, whose own rung hands placement back to llama.cpp with --fit on
when a forced --fit off crashes at startup, beside the strip of the fit's --load-mode none
that exists for the same "the footprint changed" reason.

Compatibility

What changes for an input that already succeeded

This change is not confined to the unmeasurable case it was written for, and the
body should not imply that it is. A load that already succeeded can now receive a
different context argument, because the flash-attention state is resolved once and
every KV estimate taken during that load sees the same resolved state, rather than
each estimate assuming its own.

An earlier version of this section claimed that only a build supporting neither
--flash-attn nor --kv-unified moves. That is measurably too narrow, and it is
corrected below, because it is the paragraph a reviewer uses to size the blast
radius. Everything that moves, moves toward what the launch emits.

GET /api/models/kv-cache-estimate with no plan named, driven in process against a
ragged-SWA GGUF at 32,768 tokens, merge base versus head:

build / environment slots base kv_bytes head kv_bytes delta
both flags 1 9,709,813,760 9,709,813,760 0
both flags 4 30,471,618,560 30,471,618,560 0
both flags, inherited LLAMA_ARG_FLASH_ATTN=off 1 9,709,813,760 9,709,813,760 0
--flash-attn only 4 9,709,813,760 9,709,813,760 0
--kv-unified only 4 30,471,618,560 44,365,250,560 +13,893,632,000
neither flag 4 9,709,813,760 13,222,543,360 +3,512,729,600
both flags, inherited LLAMA_ARG_SWA_FULL=1 1 9,709,813,760 9,395,240,960 -314,572,800
capability probe unreadable 4 30,471,618,560 30,786,191,360 +314,572,800

So three states that are not "neither flag" move:

  • --kv-unified only. The flash-attention axis is independent of the unified one,
    so a build missing only --flash-attn prices the padded V. This is the correction
    the PR is for; the old boundary simply excluded it.
  • An inherited LLAMA_ARG_SWA_FULL. Now honoured, which zeroes the checkpoint
    share and grows the live cache. The launch will run --swa-full, so pricing it is
    right.
  • An unreadable capability probe with more than one slot. supports_kv_unified
    fails closed, so the cache resolves non-unified where the estimator's own default
    was unified. This matches the loader, which emits --kv-unified only when the
    probe says it is supported. Same delta at ctx_checkpoints 0, 8 and unset, so it
    is the stream layout rather than the checkpoint share. On a ragged-SWA shape the
    published figure rises by up to 37.9% at four slots.

On the load path the same thing is true and larger. Driving the real argv
construction, 36-layer 8-KV-head shape, native 262,144, modern build, the only
argv token that ever differs is the -c value:

load base -c head -c
q8_0, Auto context, no user arguments 112,640 159,488 +41.6%
q4_0, Auto context, no user arguments 133,632 262,144 +96.2%
q8_0, tensor-parallel, explicit 262,144 64,512 89,600 +38.9%
f16, any of the above unchanged unchanged f16 is flash-attention-insensitive
--fit off, or -ngl N, or LLAMA_ARG_FIT=off, or LLAMA_ARG_N_GPU_LAYERS=N 112,640 71,936 -36.2%
-fa auto in the extras, f16 89,600 61,696 -31.1%
manual placement 262,144 262,144 unchanged
build with no --flash-attn, or Grok, or an explicit --flash-attn off unchanged unchanged

The two rows that move down are the deliberate part, and they are worth stating
plainly because nothing else in this PR costs a user anything. _reserved_flash_attn_state
holds the plan at off for the two placements the flash-attention-off respawn cannot be
re-placed out of, a user's own --fit off and a fixed layer count, and head prices the
compute buffer from that same held-down state. The merge base held only the KV cache down
and priced the compute buffer for the launch, which is a reserve that covers the respawn's
cache but not its mask. Completing it costs 36% of the context on those paths and buys a
respawn that does not OOM with no fitter left to absorb it. The compute buffer is far more
flash-attention-sensitive than the cache the risk table above quotes: 14x on this shape at
q8_0 and 66x at f16, against 1.44x and 1.00x for the cache.

Restricting the change to the unmeasurable case would reinstate the panel/loader
disagreement that #10489 was about, where the panel priced a cache the loader did
not use. The wider scope is intentional and is the point of the PR.

Corner What ran Result
Python 3.13, Studio requirements (studio/backend/requirements/studio.txt), torch 2.11.0+cu130, Linux x86_64, NVIDIA B200 full studio/backend/tests, 12 workers 45,492 passed, 13 failed, 15 errors, 296 skipped, against 45,430 passed, 13 failed, 15 errors on the merge base with the same command. The failures are host-dependent and flip members between runs: they want a live server, real transformers architectures, Landlock, or a specific CPU count, and each passes in isolation
Same, single-worker the new suites plus every existing file that imports the modules touched 2,286 passed, 56 skipped, 1 known host-dependent failure that also fails on the merge base
Live Studio on Linux/CUDA, unsloth/gemma-4-12b-it-GGUF UD-IQ2_M loaded at 262,144 published context_length, max_context_length, native_context_length 262,144 / 262,144 / 262,144 on both builds: a measurable load's published context does not move
Live Studio, same model, GET /api/models/kv-cache-estimate with no plan named kv_bytes, gpu_bytes, total_bytes byte-identical on both builds
Tensor-parallel arm, two GPUs not run: this host has one visible card covered by the pure-planner suite, which needs no GPU
Metal unified-memory arm, Apple Silicon not run on hardware covered by the platform seam the Metal suites use (a non-zero unified-memory budget with an empty GPU probe) and by the macOS CI leg

Cross-platform staging CI (Linux, Apple Silicon macOS, Windows, with Playwright) is recorded
in the PR comments.

Tests

studio/backend/tests/test_unmeasured_context_ceiling.py (24 tests), the unmeasurable
fallback: an explicit request honoured, Auto still floored, a measured cap still binding an
explicit request, the flag defaulting off for existing callers, the notice's wording, and the
Metal arm through the real load_model (published ceiling, the advisory, Auto untouched, and
a measured ceiling still refusing).

studio/backend/tests/test_resolved_flash_attn_plan.py (23 tests), the resolver and the
launch: the managed default, a build without the flag, every argv spelling of an explicit
off, last-wins, the environment, a quantized V forcing it on, and the one case the route's own
earlier form got wrong. Then through the real load_model: a tensor plan for a q8_0 cache
lands above what a flash-attention-off cache prices, the published ceiling is that same
number, every KV estimate the load takes sees the resolved state, and an explicit off in the
extras is priced off.

studio/backend/tests/test_kv_cache_estimate_attention_plan.py (12 tests), the route: each
knob as an input, resolution when omitted, a quantized V not priced without flash attention,
the checkpoint share under --swa-full, the parameters all optional, the response key set
unchanged, and an unnamed plan not moving the answer for a plain model.

All 59 fail on the merge base and pass here. Commands and logs are in the report beside this
body.

One existing pin was made less brittle rather than worked around:
test_the_no_flash_rung_recomputes_the_memory_record sliced load_model's source from the
first mention of _drop_fit_load_mode_for_no_flash, which is now a comment explaining why a
plan may be sized for the launch rather than for that respawn. It now anchors on the
definition, as the sibling pin in the same file already did.

Evidence

Two isolated Studios, installed from the merge base and from this branch into their own
UNSLOTH_STUDIO_HOME, each on its own port with its own login, reading their own HF cache
containing the #10489 model. Both were driven through the picker, both loaded
unsloth/gemma-4-12b-it-GGUF UD-IQ2_M live at 262,144 with a q8_0 KV cache, and both were
photographed on the same three surfaces. Screenshots, composites, GIFs and the machine
readable facts are in the report's media directory.

  • The estimate for the plan a launch would run (swa_full=true): merge base
    kv_bytes 3,083,862,016 and gpu_bytes 11,450,519,974, unchanged from its default answer
    because it cannot be told; this branch 47,915,728,896 and 56,282,386,854, which is what that
    launch reserves.
  • The estimate with nothing named: identical on both.
  • The /v1/models payload the report quotes its numbers from: identical on both.

What this evidence cannot show: #9653's published context needs an arm where the KV cache
cannot be measured, which is the tensor-parallel planner (two GPUs) or the Metal arm (Apple
Silicon). Neither is reachable on a single-card Linux host, so that half rests on the unit
suites and the macOS CI leg.

The number on screen, before and after

Two isolated Studios, one installed from this PR's merge base and one from the branch, each
built by the PR's own install.sh --local into its own UNSLOTH_STUDIO_HOME on its own
port with its own login. Both loaded unsloth/gemma-4-12b-it-GGUF UD-IQ2_M live with a
q8_0 KV cache at Auto context, on the same card held at about 20 GiB free so the fit
actually binds. The chat header's context chip is where the ceiling reaches the user:

context chip, before and after

241 / 234.2k on the merge base, 241 / 262.1k here. /v1/models agrees:

merge base this branch
context_length 234,240 262,144
max_context_length 234,240 262,144
native_context_length 262,144 262,144
free VRAM at the load 20,916 MiB 20,768 MiB

The same 27,904 tokens the merge base could not offer are the f16 V-axis floor it charged a
cache the child allocates at q8_0. native_context_length is identical, which is the control:
only the measured ceiling moves.

full chat surface, before and after

Two things about the pair itself. The greeting line differs because it rotates at random, not
because of this change. And the free-VRAM row is not decoration: a first attempt held the card
with a topping-up ballast, which reclaimed what the BEFORE side released and left the two
halves measuring 1,572 MiB and 21,316 MiB, so that pair was discarded rather than posted.

Known limitations

  • A launch that asks for flash attention ON and has it dropped inside llama.cpp anyway is still
    priced as on. Only an explicit auto is treated as undecided, because no probe short of
    launching can answer the other case.
  • The three knobs are now answerable, but nothing in the UI asks about them yet: the memory
    bar still abstains when a KV-shaping flag is in the extra arguments rather than pricing it.
    Forwarding the extras the panel already holds is a small follow-up, and it is what makes
    this visible to a user rather than to a client.
  • The notice is an advisory, not a refusal, and deliberately so. On the tensor arm there is no
    --fit valve behind it, so a request nothing could check is launched as asked.
  • _plan_tensor_parallel keeps its four-tuple return; the unmeasured verdict is re-derived by
    the caller from the same _can_estimate_kv() it plans on, rather than widening a contract
    eleven test modules unpack positionally.
  • On Apple Silicon one class of load moves from refused to allowed. Simulated through the
    Metal seam with a 24 GiB budget, the merge base refuses an explicit 262,144 naming 183,296
    as the largest that fits, because it priced the cache without flash attention; head
    launches it, since 14.9 GiB of cache at flash attention on plus 4 GiB of weights does fit.
    A --flash-attn off respawn would want 25.4 GiB of that 24 GiB budget, and the only thing
    standing behind it is llama.cpp's own Metal fitter, which head does arm (--fit on is in
    the argv) but whose free-memory report is exactly what the Metal guard exists to distrust.
    The same cell on a build with no --flash-attn still refuses, so this is not a blanket
    relaxation. Not testable off a real Mac.
  • The unmeasurable path that emits --fit on, a single pool with no tensor split and no
    unified-memory budget, still says nothing: the notice is recorded only at the two arms that
    publish a guessed ceiling. Unchanged from the merge base, and the fitter is the backstop
    there, but the contract "a context nobody could measure is not a ceiling" does not cover it
    yet.
  • load_model can still emit --split-mode tensor with no --flash-attn flag, a pair
    llama.cpp refuses. The new _tensor_split_can_launch guard refuses to price it on the
    route side only. Unchanged from the merge base.

Fixes #9653
Fixes #9697
Fixes #10489

What the change looks like

Two isolated installs of this repository, merge base 128659085 and head ae0ef489e,
each with its own Studio home and its own password, driven by one Playwright scene
against both. The model is the one #10489 reports, unsloth/gemma-4-12b-it-GGUF at
UD-IQ2_M, priced at its native 262,144 context with a q8_0 KV cache and 4 serving
slots. The shot is the server's own answer to
GET /api/models/kv-cache-estimate for the launch plan that will really run.

kv-cache estimate for the named launch plan, before and after

field before after
kv_bytes 3,083,862,016 47,915,728,896
gpu_bytes 17,226,534,142 61,924,707,582
total_bytes 17,226,534,142 61,924,707,582
weights_bytes 4,213,353,280 4,213,353,280
compute_bytes 9,085,353,983 9,085,353,983
native_context 262,144 262,144

Before, the route has no parameter for the launch plan, so naming it changes nothing: the
compact sliding-window cache is priced for a load that would open a full-context one, and
the quote is 17.2 GB for a launch that reserves 61.9 GB. After, the named plan is priced,
and the KV cache is what that launch actually takes.

The run also shoots two controls, and both are expected to match. The published context of
a load whose KV cache CAN be measured does not move, and the estimate for an UNNAMED plan
is byte-identical on both sides, which is the point: this adds an answer for a question the
route could not be asked before rather than changing the one it already gave. The third
pair being identical is the control passing, not the scene failing.


The host-pinned projector, and a test that had never run

test_a_host_pinned_projector_is_not_charged_to_the_card has not passed once since it was
added in d44cb0c9c on this branch. It was written calling _call_route(..., no_mmproj_offload = ...), and _call_route neither takes that argument nor forwards it, so
every run raised TypeError: _call_route() got an unexpected keyword argument 'no_mmproj_offload' at the call and the route was never exercised. That is fixed here by
threading the four launch knobs the route resolves for itself through the helper. The route
itself is unchanged.

What the product half of d44cb0c9c fixes is worth stating plainly, because the failing
test hid it. --no-mmproj-offload keeps vision ON and puts the projector in HOST memory.
The loader has assumed that since #5825, which measured a context dropping 9,984 to 4,096
from charging those bytes to the card. This route was the last place still itemising
projector_bytes for that case, and the frontend adds it straight onto its GPU weights
segment (use-model-memory.ts, weightsBytes + projectorBytes), which is what draws the
memory bar and raises the "exceeds memory" warning. So a projector the user had explicitly
pinned off the card was charged against VRAM anyway, and at _MMPROJ_VRAM_SAFETY (1.4x)
rather than even at its file size.

Measured against the real mmproj files on the Hub:

model mmproj file size charged to the VRAM bar
unsloth/gemma-3-27b-it-GGUF mmproj-F16.gguf 0.858 GB 1.20 GB
unsloth/Qwen2.5-VL-7B-Instruct-GGUF mmproj-F16.gguf 1.354 GB 1.90 GB
unsloth/Qwen2.5-VL-7B-Instruct-GGUF mmproj-F32.gguf 2.703 GB 3.79 GB

The direction is an OVER-estimate, not an under-estimate. Studio refuses, or warns against,
a load that would have fit; it never accepts one that will OOM. On a 16 GB card the
Qwen2.5-VL F32 case is 3.79 GB of phantom VRAM, 24 percent of the card, against memory
nothing on the GPU occupies. Reverting the route's if _asked_no_mmproj: projector = None
now turns the test red on the assertion it was written for, which it could not do before.

The same commit also makes test_kv_cache_estimate_route.py collectable on its own. The
shared loggers stub in test_kv_cache_estimation.py was a bare ModuleType, which
shadows the whole package rather than just its __init__, so from loggers.media_progress import ... in routes/inference.py died with "'loggers' is not a package" and this file
could not be imported at all from the repo root (measured on 205771c44). Giving the stub
a __path__, the same fix as #10995, removes the ordering dependence at its source, and the
local try/except band-aid this branch added to test_kv_cache_estimate_attention_plan.py is
removed with it. tests/conftest.py masks this today (#11028) but skips itself whenever
import loggers raises, so test_the_shared_loggers_stub_is_still_a_package asserts
against the stub object rather than the sys.modules slot: deleting the __path__ line
turns it red in an ordinary run, guard and all.

This is not a product import-order bug. Nothing outside the test suite writes a bare module
into that slot, and all four orderings of loggers, routes.models and routes.inference
import cleanly against the real package.

…tion plan

Two context numbers were wrong for the same underlying reason: a figure that
described a load other than the one about to start.

When a GGUF carries no attention dimensions, _can_estimate_kv() is False and
two arms fall back to a short context: _plan_tensor_parallel (a bare 4096, now
_TP_UNMEASURED_CTX) and the Metal unified-memory arm (_metal_floor_ctx). Both
applied that fallback to an explicit request and published it as
max_context_length, so a 262,144-token selection came back as 4,096 with the
slider reporting that nothing longer fits. The fallback is a guess, which is
why _metal_context_overcommit_message already refuses to refuse against it; a
guess equally may not overrule a context the user typed, nor be published as
"the largest that fits" once the load has run above it. Auto keeps the
conservative fallback, and both arms now record why the ceiling is unmeasured.

load_model also pinned planned_flash_attn = False unconditionally while every
launch emits --flash-attn on. The estimator is not indifferent: with flash
attention off it floors the V axis at f16 and pads variable-width V tensors, so
a q8_0 cache at 262,144 was priced at 23.0 GB against the 16.0 GB the launch
allocates, and q4_0 at 19.3 GB against 8.5 GB. In tensor mode --fit is a no-op,
so that inflated cache became the published ceiling: KV quantization did not
move the available context. Resolve the state once, from the build's
capability, the environment, the extra arguments and the quantized-V rule that
llama.cpp applies itself, and thread that one answer through the estimate and
the argv. The pre-emptive reserve is not needed: tensor mode cannot take the
flash-attention-off recovery at all, and elsewhere the no-flash respawn already
re-enters _spawn_and_wait, whose own rung hands placement back to llama.cpp
with --fit on.

GET /api/models/kv-cache-estimate took the estimator's defaults for the three
knobs that decide the cache layout and had no way to be told otherwise, which
is how the memory panel, the loader's log and the context warning ended up
quoting three different numbers for one model. It now accepts flash_attn,
kv_unified, swa_full and no_mmproj_offload, resolves them the way the launch
does when they are omitted, and hands the same plan to the planner half of its
own answer.
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T13:14:41.652803Z fb8d8fc Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Cross-platform CI for this branch, run on a staging repo so the org queue is untouched. Linux, Windows, Apple Silicon macOS and a live Studio Playwright leg, all off the same head.

Leg Result Test summary from the job log
ubuntu-latest success 1713 passed, 32 skipped
windows-latest 1 pre-existing failure 1 failed, 1712 passed, 32 skipped
macos-15 (Apple Silicon) still queued, no runner assigned not available yet
studio-playwright success Studio installed and launched, Chromium driven through the UI smoke, screenshot and video captured

Counts are read out of each job's pytest summary line rather than from the job's own conclusion, since the generated workflow deliberately treats "no tests ran" and a dependency-only collection failure as a pass.

The Windows failure is test_load_mode_fit_matrix.py::test_the_fit_prices_pass_through_adapter_weights, which asserts _verdict(["--lora-scaled=<path>:0.5"]) is None and gets 'none'. It is a Windows-only problem in the test's own fixture: the adapter path carries a drive letter, so splitting that value on : picks a different last field than it does on POSIX. This branch changes no LoRA or adapter line (git diff main..HEAD over studio/backend has no hit for either), so it is not from this change and no fix for it is included here.

macos-15 is the only leg that can execute the Metal arm on real hardware; it had not been given a runner at the last check, so that arm still rests on the platform seam the existing Metal suites use. I will add the counts here when it lands.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
The resolver folds llama.cpp's auto into on, and auto is llama.cpp saying it will
decide at load time. It decides against flash attention whenever the backend, the
model or the cache pair cannot take it, with no error and no log line, so an estimate
that reads auto as on prices a cache that can turn out 1.44x larger at q8_0 and 2.28x
at q4_0. Studio emits flash attention on rather than auto, so only a user's extra
arguments or an inherited LLAMA_ARG_FLASH_ATTN reach this, and there the sizing that
survives either answer is the padded one. A quantized V cache still forces it on,
since llama.cpp turns it on itself, and last wins as before.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Second pass over this one. One gap found in the new resolver and fixed on the branch.

_planned_flash_attn_state folded llama.cpp's auto into "on". Auto is llama.cpp saying it will decide at load time, and it decides against flash attention whenever the backend, the model or the cache pair cannot take it, with no error and no log line: reported on ROCm for several quantized caches, on Metal for a mixed quantized pair, and on Vulkan. Sizing that reads auto as on therefore prices a cache that can turn out 1.44x larger at q8_0 and 2.28x at q4_0, on exactly the hosts least able to absorb it. Unsloth's own launch emits --flash-attn on rather than auto, so only a user's extra arguments or an inherited LLAMA_ARG_FLASH_ATTN reach that arm, and there the sizing that survives either answer is the padded one.

Fixed in 359d66a: an explicit auto, from the extras or from the environment, prices the padded f16-floored cache. Last wins is preserved in both directions, a quantized V cache still forces flash attention on because llama.cpp turns it on itself, and the managed launch is untouched. Five tests added.

Also checked:

  • The headline behaviour at the function level, on both sides: with an unmeasurable header and a typed 262,144, _plan_tensor_parallel returns 4,096 for both the launch and the ceiling on main, and 262,144 for both on this branch, while Auto still takes the conservative 4,096 on both and a measurable header is capped identically on both.
  • The claim that dropping the unconditional planned_flash_attn = False does not leave the no-flash respawn unprotected. It holds in the code: a tensor-split abort is latched and raised to the route's layer fallback before the flash-attn-off retry is reachable, and on the layer path that retry goes back through _spawn_and_wait and strips the fit's --load-mode none because the footprint changed.
  • Settings written by an older Studio. A home created by the merge base with llama_extra_args = ["-fa", "off", "--swa-full"] opens on this branch with the entry verbatim, and the new resolver prices that model with flash attention off, which is the point of resolving it once.
  • Fifteen spellings of the flag and five of the environment variable, including a bare -fa from older builds and last-wins pairs.
  • The route's four new parameters are optional and the response shape does not move, and the frontend sends none of them, so nothing in the UI changes shape.
  • The whole Studio backend suite: 45499 passed, no failure this branch introduces.
  • Cross-platform staging CI: Linux, Apple Silicon macOS and the live Studio Playwright leg green; Windows is 1 failed and 1755 passed, and that one failure is test_the_fit_prices_pass_through_adapter_weights, a Windows drive-letter colon inside that test's own --lora-scaled fixture, which this PR touches no line of and which failed the same way before this pass.

…pinned projector to VRAM

load_model appends a managed --flash-attn on and llama.cpp reads
LLAMA_ARG_FLASH_ATTN before argv, so with no user -fa the child runs with flash
attention whatever the environment said, while the estimate priced the padded
f16-floored cache and published a lower context ceiling.

--no-mmproj-offload keeps vision on and puts the projector in host memory, but
the route still itemised projector_bytes and the frontend adds it straight onto
its GPU weights segment.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: d44cb0c9ce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen danielhanchen self-assigned this Sep 16, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
Delete-first pass over the blocks this PR adds and the tests it brings with
it: collapse multi-line rationale to one line, drop measured numbers and
restatements of the code. Comments, docstrings and whitespace only, AST
gated; no behaviour change.
A blank --ctx-checkpoints now resolves to llama.cpp's default rather than zero, and
--swa-full zeroes the checkpoint share, so the totals move the other way while the
attention cache itself still grows.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 655e0009bb

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

…epending on import order

test_a_host_pinned_projector_is_not_charged_to_the_card has never passed. It was
added in d44cb0c passing no_mmproj_offload to _call_route, which does not take
that argument and does not forward it, so the test raised TypeError at the call
rather than exercising the route. The product half of that commit is correct and
is unchanged here: --no-mmproj-offload keeps vision on and puts the projector in
host memory, which is what load_model has assumed since #5825, and the route was
the last place still itemising projector_bytes for it. _call_route now takes and
forwards all four launch knobs the route resolves itself. Passed by name and as
real None on purpose: a direct call leaves an omitted parameter holding its
fastapi Query sentinel, which the route survives only because of an
isinstance(..., bool) guard, and a helper that never names the argument cannot
notice when a new one is added. With the argument threaded through, the test
passes; reverting the route's `if _asked_no_mmproj: projector = None` turns it
red on the assertion it was written for.

The second half is the loggers stub. test_kv_cache_estimation installs a bare
ModuleType into sys.modules["loggers"], and a bare module shadows the whole
package rather than just its __init__, so `from loggers.media_progress import
...` in routes/inference.py (reached at import time through routes/__init__.py)
dies with "'loggers' is not a package". That made
test_kv_cache_estimate_route.py uncollectable on its own from the repo root,
measured on 205771c. tests/conftest.py settles the real package first (#11028)
and currently masks it, but that guard skips itself whenever `import loggers`
raises, which is any runner where structlog is stubbed away. Give the stub a
__path__ instead, the same fix and the same reason as test_preview_routes.py
(#10995), and the ordering stops mattering in every case. The local
try/except band-aid this branch added to test_kv_cache_estimate_attention_plan.py
is then dead weight and is removed.

test_the_shared_loggers_stub_is_still_a_package keeps that honest. It asserts
against the stub object rather than the sys.modules slot, because the conftest
guard usually wins the slot with the real package and a check on the slot would
pass with the stub broken. Deleting the __path__ line turns it red in an
ordinary run, guard and all.

This is a product import-order question only in appearance. Nothing outside the
test suite writes a bare module into that slot, and all four orderings of
loggers, routes.models and routes.inference import cleanly against the real
package. A caller reaching for studio.backend.routes.inference fails earlier and
for an unrelated reason, on `No module named 'routes'` in routes/__init__.py,
because the backend is a flat-layout app that wants studio/backend on sys.path.
@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 Sep 17, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 17, 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: 996d419105

ℹ️ 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 +28191 to +28194
if any(
_flag_name(str(token)) in {"-fit", "--fit"} for token in (extra_args or ())
):
return fa_cmd

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 inherited fit-off on no-flash retries

When LLAMA_ARG_FIT=off is inherited and an automatically placed launch crashes into the no-flash recovery, this guard only checks extra_args, so _enable_managed_fit_for_no_flash rewrites Studio's --fit off to --fit on and the CLI overrides the inherited setting. This contradicts _user_fit_disabled, which explicitly treats the environment value as user-disabled and reserves the larger no-flash cache for that case; the retry can therefore unexpectedly reduce GPU offload or context despite already having a safe fixed placement. Include the inherited fit setting in this skip condition.

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 fixed in be7406b. LLAMA_ARG_FIT is only scrubbed from the child env under gpu_memory_mode == "manual" (_clear_manual_placement_env), and the no-flash retry is an auto-placement path, so outside manual an inherited off reached llama-server and the flip then beat it on the CLI. The skip now goes through _user_fit_disabled(extra_args, env = env), the same helper that already reserved the padded V cache for that load, so the respawn lands on a placement priced for the larger cache and has nothing to re-place. A user's own --fit token still skips whatever the environment says. Pinned by test_an_inherited_fit_off_survives_the_no_flash_retry, which fails without the guard.

…aths

Comment and docstring text only, no behaviour change. Collapses the multi-line
rationales added by this PR to their load-bearing facts, drops restatements of
the code, the repeated re-price notes at each tensor-mode downgrade, and the
section banners in the new test modules.
The retry's fit flip skipped a user's own --fit token but not the environment
spelling of it, which only manual mode scrubs, so outside manual the flip put
--fit on on the CLI and beat the inherited off. _user_fit_disabled reads that
variable and had already reserved the padded V cache for the load, so the
respawn lands on a placement priced for it and needs no re-place.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 17, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: be7406b65a

ℹ️ 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 reserve read planned_flash_attn through a default argument, so it held
whatever the plan said where the closure was written, above the four tensor
downgrades that re-plan it. The KV cache and compute buffer beside it already
re-read the plan at call time, so after a downgrade one total was assembled
from two attention plans: the cache priced the layer split's padded, f16
floored V while the draft reserve still priced the tensor plan's unpadded one.

A hybrid SWA draft head prices 4.5x larger with flash attention off, 3.5 GB at
262,144 tokens on a four layer shape, so the shortfall is an OOM at startup on
a total the placement called safe, and a user --fit off, which is one of the
states that makes the downgrade resolve attention off in the first place, takes
away the re-placement that would have absorbed it.

The other captures in that closure settle with the load and are left alone.
@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: 2f5b96d878

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

flash_attn = _planned_flash_attn(
# Shared with load_model so the estimate and the launch cannot answer differently
# (#9697, #10489).
flash_attn = _planned_flash_attn_state(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the no-flash reserve in the admission estimate

When training is active and an Auto GGUF load has --fit off (or inherits LLAMA_ARG_FIT=off), this runtime estimate prices the flash-attention-on cache, while load_model deliberately passes the same plan through _reserved_flash_attn_state and prices the larger no-flash recovery because that retry cannot be re-placed. _estimate_gguf_kv_gb feeds this result into the active-training admission guard, so the guard can approve a load based on the smaller cache and then let a no-flash retry consume more VRAM than was admitted, potentially OOMing the training process. Apply the same reserve adjustment here for placements whose fitter is disabled.

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 fixed in fb8d8fc. _estimate_gguf_kv_gb does feed the active-training admission guard, and load_model holds the reading down through _reserved_flash_attn_state for exactly the two placements you name, so resolving only the plan here admitted a load against the smaller cache that the same placement then reserves the larger one for. Measured on a ragged-SWA shape at 32,768 tokens with --fit off in the extras: admitted 9,709,813,760 against a reserve of 13,222,543,360, a 3.5 GB gap the guard would have approved.

Applied on the guard path only, via a reserve_no_flash_respawn keyword that _estimate_gguf_kv_gb passes and the panel does not. Putting it in _gguf_runtime_bytes unconditionally was my first attempt and it broke test_memory_estimate::test_an_auto_load_with_an_extras_ngl_is_not_fully_resident, which pins that an extras -ngl moves bytes between host and device without changing the total: the panel means what the launch uses, the guard means the worst the placement can reach. Tensor mode stays exempt on both paths, since there is no flash-attention-off respawn under SPLIT_MODE_TENSOR to reserve for.

Covered by test_the_admission_estimate_keeps_the_no_flash_reserve, which also pins the panel's totals unmoved. A ragged-SWA fixture because the axis is invisible otherwise: a quantized V forces flash attention on, and an equal-width f16 cache does not move with the state, so the control could not have failed on either.

_record_load_warning is first-notice-wins with one slot, and both arms that raise
an unmeasured ceiling decide it long before the host-RAM and offload advisories
run. Recording the notice there took the slot, so a load that is told it will page
from disk heard only that its ceiling was unmeasured, on the one path that also
raises the launched context from the fallback to the full request.

Held in _unmeasured_ctx_notice and flushed past both advisories, appending when one
spoke and recording when none did. Measured on the tensor arm with an unsizeable KV
cache and an explicit 262,144: the host advisory survives and the notice follows it,
where before only the notice was left.
_estimate_gguf_kv_gb feeds the active-training admission guard, and load_model
holds the flash-attention reading down through _reserved_flash_attn_state for the
two placements a flash-attention-off respawn cannot be re-placed out of: a user's
own --fit off, and a fixed layer count. The route resolved only the plan, so the
guard admitted a load against the smaller cache that the same placement then
reserves the larger one for, and the respawn could take VRAM the guard never
admitted and the training run with it. Measured on a ragged-SWA shape at 32,768
tokens with --fit off: admitted 9,709,813,760 against a reserve of 13,222,543,360.

Asked for by keyword rather than applied in _gguf_runtime_bytes, because the panel
means the other thing. It shows what the launch uses, and its total is
placement-independent -- test_memory_estimate pins that an extras -ngl moves bytes
between host and device without changing the total, which a reserve keyed on
placement would break.

Tensor mode stays exempt on both paths: llama.cpp has no flash-attention-off
respawn under SPLIT_MODE_TENSOR to reserve for.
@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 Sep 17, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 17, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 17, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fb8d8fcf43

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 6d93827 into main Sep 17, 2026
4 of 50 checks passed
@danielhanchen
danielhanchen deleted the pr/studio-context-unmeasured branch September 17, 2026 13:22
danielhanchen added a commit that referenced this pull request Sep 17, 2026
…tted (#11207)

#11025, #10533 and #11067 each landed today with a blank line the
ruff-format-with-kwargs hook removes or adds, so `pre-commit run --all-files`
is red on main. Every open PR inherits that: pre-commit.ci evaluates the PR
merged with main, finds files to rewrite that the PR never touched, and pushes
them onto the PR branch, which is how unrelated files end up in a diff. On a
branch too far behind main to apply, it fails outright instead.

Output of the repo's own hook, with the pinned ruff 0.6.9. Blank lines only.

Co-authored-by: danielhanchen <[email protected]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…tion plan (unslothai#11025)

* Studio: honour an unmeasured context request and price the real attention plan

Two context numbers were wrong for the same underlying reason: a figure that
described a load other than the one about to start.

When a GGUF carries no attention dimensions, _can_estimate_kv() is False and
two arms fall back to a short context: _plan_tensor_parallel (a bare 4096, now
_TP_UNMEASURED_CTX) and the Metal unified-memory arm (_metal_floor_ctx). Both
applied that fallback to an explicit request and published it as
max_context_length, so a 262,144-token selection came back as 4,096 with the
slider reporting that nothing longer fits. The fallback is a guess, which is
why _metal_context_overcommit_message already refuses to refuse against it; a
guess equally may not overrule a context the user typed, nor be published as
"the largest that fits" once the load has run above it. Auto keeps the
conservative fallback, and both arms now record why the ceiling is unmeasured.

load_model also pinned planned_flash_attn = False unconditionally while every
launch emits --flash-attn on. The estimator is not indifferent: with flash
attention off it floors the V axis at f16 and pads variable-width V tensors, so
a q8_0 cache at 262,144 was priced at 23.0 GB against the 16.0 GB the launch
allocates, and q4_0 at 19.3 GB against 8.5 GB. In tensor mode --fit is a no-op,
so that inflated cache became the published ceiling: KV quantization did not
move the available context. Resolve the state once, from the build's
capability, the environment, the extra arguments and the quantized-V rule that
llama.cpp applies itself, and thread that one answer through the estimate and
the argv. The pre-emptive reserve is not needed: tensor mode cannot take the
flash-attention-off recovery at all, and elsewhere the no-flash respawn already
re-enters _spawn_and_wait, whose own rung hands placement back to llama.cpp
with --fit on.

GET /api/models/kv-cache-estimate took the estimator's defaults for the three
knobs that decide the cache layout and had no way to be told otherwise, which
is how the memory panel, the loader's log and the context warning ended up
quoting three different numbers for one model. It now accepts flash_attn,
kv_unified, swa_full and no_mmproj_offload, resolves them the way the launch
does when they are omitted, and hands the same plan to the planner half of its
own answer.

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

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

* Size a flash-attention auto request as the load that may not get it

The resolver folds llama.cpp's auto into on, and auto is llama.cpp saying it will
decide at load time. It decides against flash attention whenever the backend, the
model or the cache pair cannot take it, with no error and no log line, so an estimate
that reads auto as on prices a cache that can turn out 1.44x larger at q8_0 and 2.28x
at q4_0. Studio emits flash attention on rather than auto, so only a user's extra
arguments or an inherited LLAMA_ARG_FLASH_ATTN reach this, and there the sizing that
survives either answer is the padded one. A quantized V cache still forces it on,
since llama.cpp turns it on itself, and last wins as before.

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

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

* Size flash attention as the launch runs it, and stop charging a host-pinned projector to VRAM

load_model appends a managed --flash-attn on and llama.cpp reads
LLAMA_ARG_FLASH_ATTN before argv, so with no user -fa the child runs with flash
attention whatever the environment said, while the estimate priced the padded
f16-floored cache and published a lower context ceiling.

--no-mmproj-offload keeps vision on and puts the projector in host memory, but
the route still itemised projector_bytes and the frontend adds it straight onto
its GPU weights segment.

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

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

* Trim the comments in the files this PR touches

Delete-first pass over the blocks this PR adds and the tests it brings with
it: collapse multi-line rationale to one line, drop measured numbers and
restatements of the code. Comments, docstrings and whitespace only, AST
gated; no behaviour change.

* Cut the remaining comments to the facts the code does not state

* Compare the attention cache net of the checkpoint share

A blank --ctx-checkpoints now resolves to llama.cpp's default rather than zero, and
--swa-full zeroes the checkpoint share, so the totals move the other way while the
attention cache itself still grows.

* Make the kv-cache-estimate route tests run, and stop the collection depending on import order

test_a_host_pinned_projector_is_not_charged_to_the_card has never passed. It was
added in d44cb0c passing no_mmproj_offload to _call_route, which does not take
that argument and does not forward it, so the test raised TypeError at the call
rather than exercising the route. The product half of that commit is correct and
is unchanged here: --no-mmproj-offload keeps vision on and puts the projector in
host memory, which is what load_model has assumed since unslothai#5825, and the route was
the last place still itemising projector_bytes for it. _call_route now takes and
forwards all four launch knobs the route resolves itself. Passed by name and as
real None on purpose: a direct call leaves an omitted parameter holding its
fastapi Query sentinel, which the route survives only because of an
isinstance(..., bool) guard, and a helper that never names the argument cannot
notice when a new one is added. With the argument threaded through, the test
passes; reverting the route's `if _asked_no_mmproj: projector = None` turns it
red on the assertion it was written for.

The second half is the loggers stub. test_kv_cache_estimation installs a bare
ModuleType into sys.modules["loggers"], and a bare module shadows the whole
package rather than just its __init__, so `from loggers.media_progress import
...` in routes/inference.py (reached at import time through routes/__init__.py)
dies with "'loggers' is not a package". That made
test_kv_cache_estimate_route.py uncollectable on its own from the repo root,
measured on 205771c. tests/conftest.py settles the real package first (unslothai#11028)
and currently masks it, but that guard skips itself whenever `import loggers`
raises, which is any runner where structlog is stubbed away. Give the stub a
__path__ instead, the same fix and the same reason as test_preview_routes.py
(unslothai#10995), and the ordering stops mattering in every case. The local
try/except band-aid this branch added to test_kv_cache_estimate_attention_plan.py
is then dead weight and is removed.

test_the_shared_loggers_stub_is_still_a_package keeps that honest. It asserts
against the stub object rather than the sys.modules slot, because the conftest
guard usually wins the slot with the real package and a check on the slot would
pass with the stub broken. Deleting the __path__ line turns it red in an
ordinary run, guard and all.

This is a product import-order question only in appearance. Nothing outside the
test suite writes a bare module into that slot, and all four orderings of
loggers, routes.models and routes.inference import cleanly against the real
package. A caller reaching for studio.backend.routes.inference fails earlier and
for an unrelated reason, on `No module named 'routes'` in routes/__init__.py,
because the backend is a flat-layout app that wants studio/backend on sys.path.

* Itemize the projector by where the launch will actually put it

* Let tensor split decide auto flash attention the way llama.cpp does

* Price the split the launch can actually take

* Price the resolved layer split in the KV cache estimate

When the tensor split cannot launch, the estimate downgraded the planner
devices but still handed the raw request toggle and the untouched extras to
both memory breakdown calls, so the breakdown re-resolved tensor mode and
priced a split the launch would not take.

* Re-plan the attention after a tensor-mode downgrade

llama.cpp requires flash attention under SPLIT_MODE_TENSOR, so AUTO is planned
ON whenever the split resolves to tensor. The plan was made once near the top of
the load and never revisited, so the six later points that drop tensor mode left
the KV and compute estimates budgeting an unpadded V that the layer split with
AUTO attention off does not get.

* Re-plan the attention after the early manual tensor downgrades too

The three manual guards drop the toggle without touching the extras, so they
were not covered by the re-plan on the strip sites. Manual placement runs with
--fit off, so a plan that still says flash attention is on under-prices the V
layout of a model that grows without it and the child can OOM at startup on a
total the estimate called safe. The test now walks every downgrade after the
plan is made rather than only the ones that strip a split mode.

* Keep the no-flash reserve when the user turned the fitter off

The planned state is what the first process runs with, and the argument for
reserving only for it is that a hard-crash respawn without flash attention is
re-placed by llama.cpp's fitter. A user's own --fit off wins by last-arg over
the token that retry rewrites, so there is no re-placement: the padded,
f16-floored V cache lands on a placement chosen for the smaller one and the
recovery OOMs at startup on a total the estimate called safe. Tensor mode is
excluded, since it cannot take that recovery at all.

* Re-plan the attention against the environment the child will see

Tensor mode can arrive through an inherited LLAMA_ARG_SPLIT_MODE, and the
helper resolves the split from the extras, the toggle and that variable, so a
re-plan carrying a downgraded False met a tensor answer inside it and priced the
unpadded V of a load that decides the question again under a layer split. The
launch clears that variable (and its paired tensor split) before spawning for
exactly this reason, so the re-plan now resolves against the same scrubbed
environment.

* Re-enable the fitter for the no-flash retry

An auto placement that fits appends a managed --fit off, the --flash-attn off
respawn inherits it, and _fit_off_retry_eligible refuses to enable fitting for
any command naming the flag, so the retry re-lands on the placement priced with
flash attention on while running the padded f16 V cache. Flip Unsloth's own
token back to on for both no-flash respawns; a user's --fit is left alone, since
theirs wins by last-arg and the reserve already holds down for it.

* Keep the reserve for a placement the fitter will not move

Manual mode emits --gpu-layers N --fit off, which is token for token what an
auto placement that fits emits, so the no-flash retry flipped it back on and the
reserve priced a re-placement that cannot happen: common_params_fit_impl throws
on any count but llama.cpp's own -1 default and the caller downgrades it to a
warning, so the retry keeps the fixed placement. A fixed count now skips the
flip and holds the reserve down, the same way a user's own --fit off does.

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

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

* Say only what the resolver's own order guarantees

The docstring claimed this helper mirrors llama.cpp's branch order end to end. It
mirrors the one branch it has to: llama_init_from_model forces flash attention off for
LLM_ARCH_GROK above both of llama.cpp's own upgrades, so the architecture is read
before anything else here too. The quantized-V branch below it is not in that order and
does not need to be.

* Tighten comments in the flash-attention plan and unmeasured-context paths

Comment and docstring text only, no behaviour change. Collapses the multi-line
rationales added by this PR to their load-bearing facts, drops restatements of
the code, the repeated re-price notes at each tensor-mode downgrade, and the
section banners in the new test modules.

* Honour an inherited LLAMA_ARG_FIT=off on the no-flash retry

The retry's fit flip skipped a user's own --fit token but not the environment
spelling of it, which only manual mode scrubs, so outside manual the flip put
--fit on on the CLI and beat the inherited off. _user_fit_disabled reads that
variable and had already reserved the padded V cache for the load, so the
respawn lands on a placement priced for it and needs no re-place.

* Price the MTP draft reserve with the attention the downgrade re-planned

The reserve read planned_flash_attn through a default argument, so it held
whatever the plan said where the closure was written, above the four tensor
downgrades that re-plan it. The KV cache and compute buffer beside it already
re-read the plan at call time, so after a downgrade one total was assembled
from two attention plans: the cache priced the layer split's padded, f16
floored V while the draft reserve still priced the tensor plan's unpadded one.

A hybrid SWA draft head prices 4.5x larger with flash attention off, 3.5 GB at
262,144 tokens on a four layer shape, so the shortfall is an OOM at startup on
a total the placement called safe, and a user --fit off, which is one of the
states that makes the downgrade resolve attention off in the first place, takes
away the re-placement that would have absorbed it.

The other captures in that closure settle with the load and are left alone.

* Say the ceiling was a guess without spending the memory warning

_record_load_warning is first-notice-wins with one slot, and both arms that raise
an unmeasured ceiling decide it long before the host-RAM and offload advisories
run. Recording the notice there took the slot, so a load that is told it will page
from disk heard only that its ceiling was unmeasured, on the one path that also
raises the launched context from the fallback to the full request.

Held in _unmeasured_ctx_notice and flushed past both advisories, appending when one
spoke and recording when none did. Measured on the tensor arm with an unsizeable KV
cache and an explicit 262,144: the host advisory survives and the notice follows it,
where before only the notice was left.

* Admit a GGUF beside training against the reserve, not the plan

_estimate_gguf_kv_gb feeds the active-training admission guard, and load_model
holds the flash-attention reading down through _reserved_flash_attn_state for the
two placements a flash-attention-off respawn cannot be re-placed out of: a user's
own --fit off, and a fixed layer count. The route resolved only the plan, so the
guard admitted a load against the smaller cache that the same placement then
reserves the larger one for, and the respawn could take VRAM the guard never
admitted and the training run with it. Measured on a ragged-SWA shape at 32,768
tokens with --fit off: admitted 9,709,813,760 against a reserve of 13,222,543,360.

Asked for by keyword rather than applied in _gguf_runtime_bytes, because the panel
means the other thing. It shows what the launch uses, and its total is
placement-independent -- test_memory_estimate pins that an extras -ngl moves bytes
between host and device without changing the total, which a reserve keyed on
placement would break.

Tensor mode stays exempt on both paths: llama.cpp has no flash-attention-off
respawn under SPLIT_MODE_TENSOR to reserve for.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…tted (unslothai#11207)

unslothai#11025, unslothai#10533 and unslothai#11067 each landed today with a blank line the
ruff-format-with-kwargs hook removes or adds, so `pre-commit run --all-files`
is red on main. Every open PR inherits that: pre-commit.ci evaluates the PR
merged with main, finds files to rewrite that the PR never touched, and pushes
them onto the PR branch, which is how unrelated files end up in a diff. On a
branch too far behind main to apply, it fails outright instead.

Output of the repo's own hook, with the pinned ruff 0.6.9. Blank lines only.

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

2 participants