Skip to content

Studio backend tests: settle the real loggers package in conftest for repo-root pytest runs - #11028

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
deepspace28:fix/loggers-stub-collection
Sep 16, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
deepspace28:fix/loggers-stub-collection

Conversation

@deepspace28

Copy link
Copy Markdown
Contributor

Fixes #10995.

What

studio/backend/tests/conftest.py now imports the real loggers package right after the backend-root sys.path insert, before any test module is collected.

Why

~83 test files install a bare ModuleType("loggers") stub with sys.modules.setdefault. A bare module has no __path__, so once it takes the slot any later from loggers.media_progress import ... (routes/inference.py:57, at module level) fails collection with 'loggers' is not a package. Invisible under the repo's own CI (pytest runs from studio/backend, the real package imports first), but it broke every repo-root invocation with PYTHONPATH=studio/backend — e.g. the cross-platform staging run for #10439. Importing the real package in conftest makes every later setdefault a no-op under any launch directory, which is what the individual stubs already assume; the package is thin (structlog + one shared util).

Verification

On unmodified main, collection of the issue's three-file repro errors out with exactly No module named 'loggers.media_progress'; 'loggers' is not a package. With this change:

  • repo root, PYTHONPATH=studio/backend: the three repro files go 1 failed / 137 passed — the single failure (test_preview_routes.py::test_page_escapes_title) is a pre-existing Windows issue (a<b is an invalid directory name) and reproduces on unpatched main run from studio/backend too; repo CI runs Linux
  • studio/backend (the CI layout): same three files 137 passed / the same pre-existing Windows failure
  • tests/test_backend_tests_stub_heavy_imports.py (the guard over the stub pattern): 6 passed from the CI layout

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the bug this fixes is real, and pushed a small change to keep Source lint green.

The bug reproduces

From the repo root with PYTHONPATH=studio/backend, collecting a stub-first file ahead of an inference-routes one, on main:

studio/backend/routes/inference.py:57: in <module>
    from loggers.media_progress import (
E   ModuleNotFoundError: No module named 'loggers.media_progress'; 'loggers' is not a package
ERROR studio/backend/tests/test_preview_routes.py

With this branch's conftest, the same command collects 59 tests. 84 files under studio/backend/tests/ install the bare ModuleType("loggers") stub, so the description's account is accurate.

What I changed

Source lint was failing on the one real hunk here:

[BLOCKER] studio/backend/tests/conftest.py: HOISTED-IMPORT-UNUSED 'loggers' (['import:loggers']) added but unused

verify_import_hoist.py is right to flag it. A module-level import that binds a name nothing loads is exactly the shape of a botched hoist, and the tool cannot tell that apart from a deliberate side-effect import by reading the AST. Its only exemptions are __future__ and __all__ in a package __init__, both narrow on purpose: the file notes that a broader one "disables rename-clash detection ... one of the two bugs this tool exists to catch". So widening it for this line would be the wrong trade.

Instead the import is now used, by checking the thing the failure is actually about:

assert hasattr(loggers, "__path__"), (
    f"the 'loggers' slot holds a non-package ({loggers!r}); a ModuleType stub from some test "
    "module got there first, so `from loggers.media_progress import ...` will still fail"
)

That keeps the hoist signal on this file rather than suppressing it, and it upgrades the failure mode: if a stub ever wins the slot again, collection stops here naming the cause instead of dying twelve frames deep in routes/inference.py.

Mutation-tested, so it is not vacuous: pre-installing the stub before pytest.main makes it fire with that message, and it passes with the real package.

Locally verify_import_hoist.py --before <merge base> --after HEAD studio/backend/tests/conftest.py now reports CLEAN.

I also merged main in. The hunks here in test_diffusers_prewarm.py, torch_warmup.py and test_amd_extras_contract.py were the same formatting main was missing, which #11019 has since landed, so the merge resolves them to no-ops and conftest.py is the only real change left.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@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-16T00:06:28.822091Z 957471e 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1a20a863ba

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

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

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 957471e739

ℹ️ 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 48b0831 into unslothai:main Sep 16, 2026
31 of 34 checks passed
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 16, 2026
…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 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.
danielhanchen added a commit that referenced this pull request Sep 17, 2026
…tion plan (#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 #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.

* 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
… repo-root pytest runs (unslothai#11028)

84 test files stub `loggers` with a bare `ModuleType`, which has no `__path__` and so is not a package. Once one wins the slot, `from loggers.media_progress import ...` (routes/inference.py, at module level) dies with "'loggers' is not a package". It only bites when pytest is invoked from the repo root, which is why the repo's own CI, run from studio/backend, never saw it.

Reproduced before and after: without the preload, collecting a stub-first file ahead of an inference-routes file from the repo root gives 1 collection error; with it, 59 tests collect.

The preload is conditional. `loggers.handlers` imports structlog, and some tests stub structlog to stay runnable without it; where it is missing, the import this protects would die on structlog anyway. With structlog hidden, test_model_picker_regression.py still collects 38 tests.

The `__path__` assertion keeps the import used, so scripts/verify_import_hoist.py keeps its rename-clash signal on this file rather than having it suppressed, and it upgrades the failure mode: a stub winning the slot now stops collection naming the cause instead of dying twelve frames deep.
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio backend tests: the non-package loggers stub breaks collection when pytest runs from the repo root

2 participants