Skip to content

Studio: probe the GPU once per embedding backend, not on every encode - #11142

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
Sletch:fix/10390-auto-embedding-probes-hardware-once
Sep 18, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
Sletch:fix/10390-auto-embedding-probes-hardware-once

Conversation

@Sletch

@Sletch Sletch commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

With RAG_EMBED_BACKEND=auto (the default), every encode, token_counter, dim and embedding_identity call re-runs the GPU probe, and the probe starts a process each time: _vulkan_probe.py on a Vulkan llama.cpp build, nvidia-smi otherwise. A linked-folder sync of ten documents probed 31 times. The tauri.log attached to #10390 shows the Vulkan probe's two log lines 274 times in 186 seconds.

The hardware answer is now kept with the backend that was built from it, so auto asks once per built backend, as it did before #9739. That also keeps an ingestion in one embedding space when a probe comes back empty part-way through. Refs #10390; it does not close it (see Known limitations).

Root cause

#9739 moved the resolution ahead of the cache check. _get_backend resolves the backend for the model before it looks at the one it already built, so that saving a model that needs the other backend rebuilds:

key = forced or (_resolve_auto_for_model(model) if raw in _AUTO_ALIASES else raw)
if _backend is not None and _backend_key == _backend_cache_key(raw, key):
    return _backend

_resolve_auto_for_model ends in _resolve_auto, which calls LlamaCppBackend._get_gpu_free_memory(). The docstring above still says "auto detection runs only on a miss", and stub_embeddings in tests/conftest.py already pinned the backend because "auto" reprobes the hardware (nvidia-smi) on every use.

The probe is a process start, not a lookup.

  • On a Vulkan llama.cpp build, _run_vulkan_probe runs _vulkan_probe.py under sys.executable (timeout 15 s), which loads ggml's Vulkan backend to read device memory. It is memoised only inside _load_probe_memo_scope, which a llama.cpp model load opens.
  • Otherwise _get_gpu_memory runs nvidia-smi first, with no memo.

Changes

studio/backend/core/rag/embeddings.py

  • _resolve_auto's answer is kept with the backend _get_backend built (_resident_hardware), and read back only while that backend is the one published. _resolve_auto now has one caller, so every path that resolves auto (_get_backend, resolved_backend_for_model, _current_backend_key, active_backend_is_llama, _identity_backend_is_llama) goes through it.
  • The per-model checks in _resolve_auto_for_model still run on every call, ahead of the hardware: a local GGUF, a stored backend, a GGUF repo name. Saving a model that needs the other backend still rebuilds.
  • Only a probe made while _get_backend itself resolves is kept: it is recorded per thread and cleared at the start of each resolution. The callers outside the lock write that record too, so the clear is load-bearing, as the comment above it now says (Daniel's 91a3bba9c).
  • release_backend and _reset_backend drop the kept answer. With the published-object check, that is two ends, so neither alone is load-bearing.
  • Calls made before any backend exists still probe, as before. Every call signature is unchanged.

studio/backend/tests/conftest.py

  • The stub_embeddings comment now reads "probes the hardware (nvidia-smi) for each backend it builds". The pin itself stays.

On 09-18 Daniel rebased the branch onto main at ed91ec211. It is three commits: this change, and two of Daniel's from review, the two tests credited below (42c7c17a0) and the comment on the clear (91a3bba9c).

Evidence

The probe is counted and the embedder is a fake, so no GPU is needed. Measured 2026-09-18 on 91a3bba9c: the first two rows below on Windows, everything else in this section in the Linux container.

tree encode x5 then dim x5
40b4702cd, the parent of #9739 1 probe 0
be9e5aada, #9739 5 5
ed91ec211, this branch's base 5 5
this branch 1 0

On ed91ec211, encode, token_counter, dim and embedding_identity each probe once per call (5, 5, 5, 5 for five calls each), while the backend is built once. On this branch: 1, 0, 0, 0.

one linked-folder sync, 10 new documents (325 chunks, 10 encode batches) ed91ec211 this branch
probes for the sync 31 3
probes per document, in ingestion order 4, 3, 3, 3, 3 3, 0, 0, 0, 0
probes for a second sync with nothing changed 0 0

With the Vulkan branch taken and subprocess.run counted, five resolutions start five _vulkan_probe.py processes and log these two lines each time:

Vulkan device VK0 is an integrated GPU sharing system RAM; reserving 1024MiB host headroom (...)
Vulkan GPU memory detected: VK0=...MiB, VK1=...MiB

The tauri.log attached to #10390 (desktop v0.1.808-beta, package 2026.9.4, Vulkan llama.cpp build) shows the same pair 274 times in 186 seconds, a median 0.3 s apart. It starts as the embedding model loads and the tokenizer warns about a 4828-token text, and runs until the log ends.

One empty probe answer. On a Vulkan build, _run_vulkan_probe returns [] for any non-zero exit, exception or 15 s timeout; on any other build, nvidia-smi, NVML, amd-smi and torch all have to come back empty. _resolve_auto reads [] as no GPU and picks llama-server. Measured with _resolve_auto running for real, the probe's answers scripted and both backends faked, four batches for one model (the review suggested adding this):

one empty answer ed91ec211 this branch
mid-ingestion st, st, llama, st: two embedding spaces, the ST model released and rebuilt, llama-server built and shut down st x4, one probe
at the first build llama, st, st, st: two embedding spaces llama x4, then st after release_backend

40b4702cd, before #9739, serves both rows the way this branch does.

Daniel measured the real cost in review, with unslothai/llama.cpp prebuilts and 20 warm calls once a backend exists: about 0.5 s per call on a Vulkan build, about 0.1 s where nvidia-smi runs, and two process starts per call where nvidia-smi is missing, against none with this change. Daniel's comment on this PR has the table.

Compatibility

corner result
RAG_EMBED_BACKEND=sentence-transformers or llama-server unchanged, auto is never resolved
saving a model whose stored backend differs from the resident one still rebuilds, test_a_saved_backend_still_replaces_a_resident_auto_backend
a local GGUF path, or a model name that is a GGUF repo unchanged, checked on every call before the hardware
a backend rebuilt without a probe, then auto for a plain model asks again, test_a_replaced_backend_asks_the_hardware_again
a build that never asked, after a caller outside the lock probed keeps nothing, test_a_resolution_that_never_asked_the_hardware_keeps_nothing
_switch_to_llama_fallback after an ST encode failure the next auto resolution asks again: the published backend is no longer the one the answer was kept for
unload (release_backend) the next backend asks again, test_auto_asks_the_hardware_once_for_the_backend_it_built
an empty probe answer while a backend is resident not asked, so the backend and the embedding space stay (see Evidence)
an empty probe answer at the first build llama-server until an unload (see Known limitations)
a call before any backend exists probes, as on main
a hardware change during a session not seen by auto until the embedder is unloaded or Studio restarts, as before #9739

Tests

studio/backend/tests/test_rag_embeddings.py, 4 new tests. The last two are Daniel's, from review.

test pins fails without the change
test_auto_asks_the_hardware_once_for_the_backend_it_built one probe per built backend across encode, token_counter, dim and embedding_identity, and a new probe after release_backend yes: 12 extra probes over 12 calls on ed91ec211
test_a_saved_backend_still_replaces_a_resident_auto_backend a stored backend for the model still replaces the resident auto backend, as #9739 intended no, parity guard
test_a_replaced_backend_asks_the_hardware_again a backend rebuilt without a probe (a GGUF repo name) does not answer auto from the replaced backend's probe no, guards this change (M2, M4, M5 below)
test_a_resolution_that_never_asked_the_hardware_keeps_nothing after active_backend_is_llama probes outside the lock, a build that never asked keeps nothing yes, but only because _resident_hardware does not exist on ed91ec211 (AttributeError); guards M3r and M5
studio/backend$ python -m pytest tests/test_rag_embeddings.py        (Linux container)
ed91ec211's embeddings.py, this branch's tests:  2 failed, 56 passed
this branch:                                     58 passed

Mutation table. Each perturbation applied to this branch's embeddings.py, the file run, then restored:

# Perturbation Result
M1 embeddings.py as on ed91ec211 RED, test_auto_asks_the_hardware_once_for_the_backend_it_built and test_a_resolution_that_never_asked_the_hardware_keeps_nothing
M2 a resident auto backend is returned even when the stored backend changed RED, test_a_saved_backend_still_replaces_a_resident_auto_backend and test_a_replaced_backend_asks_the_hardware_again
M3 release_backend keeps the answer green: release_backend also unpublishes the backend, so the published-object check already refuses the old answer
M3r _reset_backend keeps the answer RED, test_a_resolution_that_never_asked_the_hardware_keeps_nothing, through the answer the previous test leaves behind (the autouse fixture resets with _reset_backend)
M4 drop the published-object check RED, test_a_replaced_backend_asks_the_hardware_again
M5 do not clear the per-thread record at the start of a resolution RED, test_a_replaced_backend_asks_the_hardware_again and test_a_resolution_that_never_asked_the_hardware_keeps_nothing
M3 + M4 both ends removed RED, test_auto_asks_the_hardware_once_for_the_backend_it_built and test_a_replaced_backend_asks_the_hardware_again

The 59 test files that touch the RAG embedding code (57 under studio/backend/tests, plus studio/backend/hub/tests/test_model_services.py and tests/studio/install/test_rocm_support.py), run with Backend CI's selection (-n 4 --dist loadgroup and its -k deselect) on ed91ec211 and on this branch at 91a3bba9c, then compared by test id:

Linux container, Python 3.12 ed91ec211 this branch
studio/backend/tests (57 files) 2,683 passed, 26 skipped 2,687 passed, 26 skipped
hub/tests/test_model_services.py 292 passed 292 passed
tests/studio/install/test_rocm_support.py 614 passed, 17 skipped 614 passed, 17 skipped

The only test ids that differ are the four new tests, all passing.

On Windows (Python 3.13), one pytest per file for the 11 files closest to the embedder, measured earlier on 09-18 on this branch before its rebase (the same added and removed lines) against main at be95e417b: 773 passed and 28 failed, then 777 and 28. The 28 are the same test ids on both (26 in test_rag_embed_llama_server.py, one each in test_openai_embeddings_studio_fallback.py and test_checkpoint_compaction.py), and all 28 pass in the Linux run above. Again the only ids that differ are the four new tests.

Known limitations

  • A hardware change during a session no longer reaches auto until the embedder is unloaded or Studio restarts, for example a GPU that appears, or a llama.cpp build switched from CUDA to Vulkan. That was the behaviour before Studio: embedding model picker searches the Hub and downloads what you pick #9739.
  • An empty probe answer at the first build keeps llama-server until an unload, where main switches back to sentence-transformers on the next call and splits the space. 40b4702cd behaves like this branch.
  • A backend replaced without a probe stays referenced. A stored backend, a GGUF repo name or the runtime fallback publishes a backend without asking, and the kept answer goes on holding the backend it replaced, already disposed, until the next probe or an unload. It is never read back for the wrong backend. A one-commit fix is offered in the thread.
  • Probes before the first backend. A document ingested before any backend exists still probes from embedding_identity (_identity_backend_is_llama, then active_backend_is_llama) and from the build: 3 probes for the first document, then none.
  • The rest of Constant CPU usage #10390. The issue was opened during a session whose log shows no embedding model load, and a later session ran for 10 minutes before indexing started, with no log lines. This change does not explain the CPU use in those periods.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the auto resolution in studio/backend/core/rag/embeddings.py runs ahead of the cached-backend check, so each encode, dim and token_counter starts a fresh GPU probe process, and caching it per built backend looks like the right fix. Could you drop the unrelated formatting churn in studio/backend/main.py, test_bootstrap_banner_password_visibility.py and tests/studio/playwright_queue_localization.py so the branch is just the embeddings change?

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the auto resolution in studio/backend/core/rag/embeddings.py runs ahead of the cached-backend check, so each encode, dim and token_counter starts a fresh GPU probe process, and caching it per built backend looks like the right fix. Could you drop the unrelated formatting churn in studio/backend/main.py, test_bootstrap_banner_password_visibility.py and tests/studio/playwright_queue_localization.py so the branch is just the embeddings change?

@danielhanchen danielhanchen self-assigned this Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed and reproduced the whole thing. The defect is real, the fix is the right shape, and the change itself is ready. What is blocking is the branch state, not the code.

Verified

I ran your guard test against main directly. It reproduces exactly what you reported:

FAILED test_auto_asks_the_hardware_once_for_the_backend_it_built
E   AssertionError: assert ['probe', 'probe', ... ] == ['probe']
E     Left contains 12 more items, first extra item: 'probe'

12 extra probes over 12 calls, and green on your branch. test_a_saved_backend_still_replaces_a_resident_auto_backend passes on both, so the #9739 parity guard is doing what you said it does.

Collateral, cherry-picking your commit onto current main and running the embeddings suites on both trees:

tree passed failed errors
main 290 11 5
your commit on main 292 11 5

Identical failure sets by name (they are environment gaps in my container, sqlite-vec missing), and exactly the two extra passes you claimed.

What needs doing

The formatting churn in main.py, test_bootstrap_banner_password_visibility.py and playwright_queue_localization.py is not yours, it came from the [pre-commit.ci] auto fixes commit f1a3c528b on top of your work. Your own commit 463f05cc6 is already clean, just the three embeddings files.

Dropping that bot commit is worth doing for a second reason: it is also the only thing making this PR conflict. The single conflicting file against main is tests/studio/playwright_queue_localization.py, one of the churn files. With f1a3c528b gone the branch merges clean, and cherry-picking 463f05cc6 onto current main applies with no conflict and passes scripts/enforce_kwargs_spacing.py.

So: drop f1a3c528b and rebase on current main. The base b80239946 is old enough that most of the red here is staleness rather than your change. I checked the one failure that sits in your area, test_the_residency_probe_does_not_wait_on_a_model_load in the l-r shard, and it is not yours: it asserts on the module-level _model after _reset_backend(), which this PR never touches, and running your two new tests immediately before it in one process leaves it green. The rest (test_windows_amd_gpu_scan_fallback, test_cache_budget_discipline, test_playwright_suites_run_in_ci, test_pwsh_calls_use_the_shared_runner, the composer selftest) are all guards main grew after your base.

Two notes on the change, neither blocking

_resident_hardware holds a strong reference to the backend it was kept for, and on the paths where _resolve_auto_for_model short-circuits before reaching _resident_hardware_choice (a local GGUF, a stored backend, a GGUF repo name) _keep_hardware_choice no-ops, so the tuple goes on pointing at the backend that was just replaced and disposed. Confirmed:

SECOND is published: True
RESIDENT still holds the REPLACED backend: True

It is one dead object in one slot, cleared by the next auto probe or by release_backend, and for the ST backend the weights live in module-level _model anyway, so the cost is small. Storing the choice alone rather than the pair, or clearing the slot on the _backend = new path, would close it.

The other is that _resident_hardware_choice writes _hardware_probe.choice even when it is reached from the callers outside the lock (resolved_backend_for_model, _current_backend_key, active_backend_is_llama, _identity_backend_is_llama). That is safe today only because _get_backend clears the thread-local before resolving, which is exactly what the line at the top of the lock is for. Worth a word in _keep_hardware_choice's docstring saying the clear is load-bearing, so nobody calls it from a second site later.

Happy to merge once the bot commit is dropped and the branch is rebased.

@danielhanchen

Copy link
Copy Markdown
Member

Ran a full simulation pass on this: not just "does the fix work" but "what else moved". Summary first, then the evidence.

issue: REAL | PR as submitted: CORRECT, 0 defects found in the code | merge: YES AFTER f1a3c528b is dropped and the branch is rebased

The code is right. I found no defect in it. The one substantive finding is about the tests, not the fix, and I have written the two that close it.

Nothing else moved, by enumeration rather than by argument

Structural diff of embeddings.py, base vs head: +2 predicates, 0 removed, 0 except handlers added, 0 bare excepts, +2 functions, 0 renamed or retyped.

The 3-term predicate you added, over every reachable combination of its terms:

held _backend identity outcome
None None n/a PROBE
set None n/a PROBE
set set mismatch PROBE
set set match CACHE HIT

The new branch is taken in exactly one cell; every other input reaches main's behaviour, so it fails safe.

Full input space of the resolve path, 240 cells (raw x local-GGUF x stored backend x GGUF-repo name x forced pin x hardware answer), 12 routing fields compared per cell:

cells: 240   routing-identical: 240   routing VIOLATIONS: 0
cells where head probes MORE: 0   unchanged: 236   fewer: 4  (8 -> 3)

236 cells identical in routing and in probe count, so for those users the path is provably unchanged. The 4 that improve are exactly the default configuration.

Platform matrix, [Windows, Linux, WSL, Mac] x [NVIDIA, AMD, CPU-only, no-binary] x [healthy, empty, raises, timeout], 64 cells per tree, one subprocess per cell, spoofing the real probe surface rather than _resolve_auto: 64/64 routing-identical, 0 worse, 32 improved. The raises and timeout rows show no gain because an exception leaves the thread-local unset, but that row is not reachable: _get_gpu_memory and _run_vulkan_probe both catch everything and return [], which is the empty row, improved 16 of 16.

The win, measured

Real nvidia-smi on this host: median 112.5 ms, range 93.9 to 316.3 ms, n=10.

Warm, 6 threads, 12,000 hot calls after the backend exists:

base this PR
probes 9,000 0
consistency violations 0 0

Modelled 10-document sync, 5 repeats: base 221 probes / 24,891 ms, head 3 probes / 295 ms. The 3 matches your own "3 probes for the first document, then none". My 221 is not your 31; my workload is a model of the call pattern, so only the ratio is comparable.

The guard itself costs about 0.02 us per call (0.232 to 0.254 us, 5 x 20,000) against the ~100 ms probe it removes.

One thing your PR fixes that it does not claim

_get_gpu_memory catches everything and returns [], so a busy nvidia-smi reads as "no GPU". On main, one such hiccup mid-ingestion:

TREE=base
during_hiccup=llama  rebuilt=True
vectors_split_across_two_spaces=True

main tears down the ST backend, builds llama-server, embeds that batch into a different vector space, then rebuilds ST on the next call. With this PR, rebuilt=False, vectors_split_across_two_spaces=False. Worth adding to the description.

The finding: the guards are thin

I broke the fix five ways and ran your two tests against each:

mutant what it breaks your tests
M1 no cache at all the whole fix caught
M2 release_backend does not clear nothing (see below) green
M3 _reset_backend does not clear leaks the answer across a reset green
M4 drop held[0] is _backend a replaced backend answers from the old probe green
M5 drop _hardware_probe.choice = None a build that never asked the hardware publishes an earlier call's answer green

M4 and M5 are not harmless. Under M5 the resident tuple becomes (<LlamaBackend>, 'llama-server'), a hardware answer committed by a path that never asked the hardware. Under M4 a rebuild stops re-asking. Those are the two mechanisms your description calls "Tied to the published object" and they had no test.

M2 is an equivalent mutant, not a gap: release_backend sets _backend = None, which already defeats the guard, so that clear is redundant defence. Worth knowing that your test's "a new probe after release_backend" assertion passes via the _backend is not None term rather than via the clear it looks like it is testing.

Two tests take the mutation score from 1 of 5 to 4 of 5. Being straight about them: the second fails on main, the first passes on main and earns its place by killing M3 and M4 on head, the same way your test_a_saved_backend_still_replaces_a_resident_auto_backend does. Both pass alone, in the full file, and three times in one process.

def test_a_replaced_backend_asks_the_hardware_again(monkeypatch):
    """The kept answer is tied to the object it was kept for, and that tie is what makes a
    rebuild re-ask. Without it the tuple answers for a backend that is no longer published,
    so a host whose hardware moved keeps being told what it had before the rebuild."""
    asked = _resolve_auto_for(monkeypatch)
    _patch_llama_backend(monkeypatch, binary = "/fake/llama-server")

    first = embeddings._get_backend("org/embedder")
    assert asked == ["probe"]

    # A GGUF repo name resolves without the hardware, so the rebuild caches nothing of its own.
    monkeypatch.setattr(embeddings, "_model_names_gguf_repo", lambda _model: True)
    second = embeddings._get_backend("org/embedder")
    assert second is not first
    assert asked == ["probe"]

    # Back to a plain model: the published backend is no longer the one the answer was kept
    # for, so auto must go and ask rather than answer from the replaced backend's probe.
    monkeypatch.setattr(embeddings, "_model_names_gguf_repo", lambda _model: False)
    assert embeddings._resolve_auto_for_model("org/embedder") == "sentence-transformers"
    assert asked == ["probe", "probe"]


def test_a_resolution_that_never_asked_the_hardware_keeps_nothing(monkeypatch):
    """``_get_backend`` clears the per-thread answer before resolving, and that clear is
    load-bearing: the identity and active-backend probes also resolve ``auto`` outside the
    lock, so without it a build that short-circuited the hardware would publish the answer
    an earlier, unrelated call had left behind."""
    asked = _resolve_auto_for(monkeypatch)
    _patch_llama_backend(monkeypatch, binary = "/fake/llama-server")

    # An out-of-lock caller resolves auto first, with no backend published yet.
    embeddings.active_backend_is_llama("org/embedder")
    assert asked == ["probe"]

    # Now build for a model that never reaches the hardware question.
    monkeypatch.setattr(embeddings, "_model_names_gguf_repo", lambda _model: True)
    built = embeddings._get_backend("org/embedder")
    assert isinstance(built, _SentinelLlamaBackend)

    # Nothing was kept, because this build asked the hardware nothing.
    assert embeddings._resident_hardware is None

I have not pushed these, since the branch needs your rebase first and I did not want to add to what you have to sort out. Take them or leave them.

Cross-platform, both arms

Staged on a disposable repo, counts read from the run logs rather than the tick, since the generated workflow has soft-fail logic:

leg base head
macos-15 (Apple Silicon) 65 passed, 0 failed 67 passed, 0 failed
windows-latest 65 passed, 0 failed 67 passed, 0 failed
ubuntu-latest did not leave the queue 67 passed, 0 failed

Exactly +2 on the platforms that ran both arms, which are the platforms this PR does not touch.

Whole backend suite on both trees: base 701 failed / 46,252 passed, head 700 / 46,253. Three names differ, none a regression: two were my own harness scripts left in the base worktree and caught by a repo-hygiene test, and test_concurrent_sizings_cannot_all_claim_the_same_free_ram passed 5 of 5 in isolation on both trees, so it is a load flake from my running two 50-minute suites side by side.

What I could not prove

No real Vulkan host was exercised; the Vulkan branch was reached only by spoofing, so the 274-line tauri.log in #10390 remains the only evidence for the real probe path. No real Studio ingestion was run. The ubuntu-latest base arm never started. windows-11-arm, ARM64 Linux and Intel macOS did not run, and the WSL cells are a platform.system spoof on a Linux box, not a real WSL kernel.

Still blocking, unchanged from my earlier comment: drop f1a3c528b and rebase. It is also the only thing making this conflict.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@Sletch

Sletch commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for taking the branch over. Checked at 4b5935d07: test_rag_embeddings.py is 58 passed, your two tests included.

pre-commit.ci pushed 5363469b1 on top at 13:00 UTC. It changes tests/studio/install/test_dependency_pass_skips.py and tests/studio/install/test_mlx_install.py, which this PR does not touch. Both were byte-identical to main b7d4a62d6 on the branch, and the hooks make exactly that change to main's copies (the debt came in with #11080). main at e00e8bb7f already has the same change from #11122, so merging main again takes both files back out of the diff. I have not touched the branch.

The strong-reference note from your earlier review is not on the branch yet. It is ready as one commit on top of the current head, with no force push, +41 −4 over embeddings.py and the test file:

  • _get_backend drops the kept answer when it publishes a backend with no probe of its own to keep (a local GGUF, a stored backend, a GGUF repo name).
  • _switch_to_llama_fallback drops it when it swaps in llama-server.
  • test_a_replaced_backend_is_not_held_by_the_answer_kept_for_it holds a weak reference to the replaced backend on both routes. Both cases fail on 4b5935d07, and each clear is pinned by its own case.

Should I push it here, or send it as a follow-up once this merges? Whichever is easier for you.

On the empty-probe point, reproduced with _resolve_auto running for real, the probe's answers scripted and both backends faked, four batches for one model:

one empty answer main b7d4a62d6 4b5935d07
mid-ingestion st, st, llama, st: two spaces, the ST model released and rebuilt, llama-server built and shut down st x4, one probe
at the first build llama, st, st, st: two spaces llama x4, then st after release_backend

So the branch keeps one space per backend in both cases. The second row is the cost: an empty answer at the first build holds llama-server until an unload. 40b4702cd, before #9739, serves both rows the way the branch does. I will put both rows in the description. On a Vulkan build, _run_vulkan_probe returns [] for any non-zero exit, exception or 15 s timeout. On any other build, nvidia-smi, NVML, amd-smi and torch all have to come back empty.

@danielhanchen

Copy link
Copy Markdown
Member

Pushed two things to this branch: the rebase onto current main, and a commit that fixes the two jobs that were red here but are not yours.

The red was main's, not this PR's

Repo tests (CPU, studio) and Repo tests (CPU, python) both reproduce on a clean origin/main worktree with this branch nowhere in the picture. Walking main's last 20 commits:

be95e417b  1 failed  Use Unsloth branding in remaining user-facing text (#11254)
3c89dd64b  1 failed  Studio: keep the find query readable when nothing matches (#11252)
6803a826e  1 failed  Studio: fix some user-facing strings (#11251)
45002962c  1 passed  Studio: shared pill selector in settings toggles, plus queue...

test_desktop_surfaces_do_not_restore_studio_branding broke at #11251, and test_restore_without_a_legacy_dir_or_an_app_dir_says_which_image_to_use broke at #11254. They needed opposite fixes.

#11251: the product was wrong, the test was right. The contract comes from aa4e6af1a, "Rebrand Tauri desktop app as Unsloth (#7608)", and exists to stop that branding coming back. #11251 was right that a bare "Studio" is not a product name, but replaced it with "Unsloth Studio" on surfaces the desktop app displays itself on. The clearest sign is inside the file it changed: the Windows branch of process.rs already said plain "Unsloth", so only the POSIX branch moved and one file ended up naming the same lock two ways. studio/frontend/src is loaded by Tauri and served to browsers by the same backend, so its copy uses the name that is right on both. Prose naming a remote Studio server keeps "Unsloth Studio" and is already exempt by key, and the backend strings #11251 changed are left alone.

#11254: the test was wrong, the product was right. Docker is Unsloth Studio, so the reword stands. #11254 updated five test files to match and missed this assertion.

Robustified, and each guard mutation tested

guard mutation result
sweep now covers native_file_dialogs.rs reintroduce "Unsloth Studio" in a locale value 1 failed, 8 passed
locale values reject a bare "Studio" put a bare "Studio" in a locale value 1 failed, 8 passed
restore test asserts meaning, not the sentence revert studio_home.sh to the old wording 1 failed, 31 passed
same delete the actionable guidance entirely 1 failed, 31 passed

The bare-"Studio" pattern is a negative lookbehind, the kind of guard that passes by matching nothing, so the coverage test asks it to fire and to hold its fire on "Unsloth Studio" and on "LM Studio", which is a different product. The assertion now names the rule, so the next person reads what to write instead of guessing.

The log-export sentinel moved on both sides in one commit. No cargo here, so I reproduced the assertion native_file_dialogs.rs makes against debug-logs.ts in Python and it passes; the Rust job runs the real one. npm run i18n:check passes all 12 overlays. installer.nsi, staged_update.rs and #11251's backend files are untouched.

On your change

Nothing has changed in my read of it: the defect is real, the fix is right, and I found no defect in the code. Since the last round I also measured the arms I had only reasoned about, using the prebuilts from unslothai/llama.cpp, counting real subprocess.run starts over 20 warm calls once a backend exists:

host shape probe that runs main this PR
Vulkan, linux-x64-vulkan _vulkan_probe.py loading libggml-vulkan.so 20 starts, 9,868 ms (493 ms/call) 0
CUDA, linux-x64-cuda12-legacy nvidia-smi 20 starts, 2,154 ms (108 ms/call) 0
no nvidia-smi on PATH, the ROCm shape failed exec, then the NVML child 40 starts, 3,075 ms (154 ms/call) 0

The Vulkan probe logged the same "Vulkan GPU memory detected" line as the tauri.log on #10390. This was never Vulkan specific: _resolve_auto sits above the whole _get_gpu_memory chain, so every backend repeats, and the ROCm shape starts two processes per call rather than one. I could not run the amd-smi leg, having no AMD hardware to hand.

Under load, 8 threads by 5,000 rounds with another thread looping release_backend(): 160,025 probes on main against 87 here, 0 consistency violations and 0 deadlocks on both. Routing matrix of 216 cells: 0 routing differences, 0 cells probing more.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 18, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 18, 2026
@Sletch Sletch changed the title studio: probe the GPU once per embedding backend, not on every encode Studio: probe the GPU once per embedding backend, not on every encode Sep 18, 2026
@danielhanchen
danielhanchen force-pushed the fix/10390-auto-embedding-probes-hardware-once branch from 8548cec to b3bfa17 Compare September 18, 2026 13:24
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 18, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Rebased the branch and dropped the work that landed upstream while this was open. Head is now b3bfa17f0, four commits on current main, force-pushed. SHAs your description cites (627d5ec98, c47f0a486) no longer exist.

What came off

I had put a branding fix and a docker test fix on this branch, for two jobs that were red here but were never yours. Both were fixed upstream in parallel, so both are gone from here:

I should have checked for existing work before writing either. The only thing still needed is the overlay rail matchers, which main is red on right now.

What is on the branch

commit author
6a7c842cc studio: probe the GPU once per embedding backend, not on every encode Sletch
be3ba6fcd Cover the two invariants that keep the hardware answer honest danielhanchen
9124db862 Name the clear in _get_backend as load-bearing danielhanchen
b3bfa17f0 Stop the overlay rail matchers spelling values that moved danielhanchen

That last one: #11260 sat the notification rail flush in its corner and took the shadow gutter into an inline style, so right-4 became right-0 and the cap went from calc(100dvh - 8px) to 100dvh. It updated the two frontend tests that measure the gutter, but four checks in tests/studio match the rail by its class literal. With no rail matched they report "a rail left its bottom-right corner" and "the bottom-right overlay stack is gone" while the rail sits exactly where #11260 put it.

Bisected to 2485a8fd9 over be95e417b..b902425d7, and confirmed on current main with nothing else in the tree: 4 failed.

The matchers now assert what the tests claim. The corner is asserted, the right step is not. The cap is asserted to be viewport-relative, the arithmetic inside it is not, since that is decided and checked in overlay-shadow-gutter.test.ts. Both are exercised on a rail and on a non-rail, the way this file already tests its class matchers, because failing by matching nothing is the one failure a matcher cannot report about itself.

Confirmed against the three regressions they exist for, each mutated into provider.tsx one at a time:

mutation result
a rail moved out of the bottom-right corner 4 failed, 193 passed
a rail loses its viewport cap 3 failed, 194 passed
a rail hard-codes a z-index over the named layer 3 failed, 194 passed
restored 197 passed

On the review

Codex never answered the two @codex review triggers here, and it was not going to: the head lives on a fork, so the connector has nothing to run against. The review is happening on a mirror of this branch instead, replayed commit by commit onto current main with authorship intact. Nothing lands from there; fixes come back here.

Staging CI is re-staged on the new head, scoped to this PR's own test files rather than advisory.

Your change

Unchanged in my read, and now the only thing in the diff. The defect is real, the fix is right, and I found no defect in the code across the routing matrix (216 cells, 0 routing differences, 0 cells probing more), the concurrency run (8 threads x 5,000 rounds against a thread looping release_backend(): 160,025 probes on base against 87, 0 consistency violations, 0 deadlocks on both), and the real prebuilt probes from unslothai/llama.cpp: Vulkan 493 ms/call, CUDA 108 ms/call, the no-nvidia-smi shape 154 ms/call and two processes per call, all to zero.

Sletch and others added 3 commits September 18, 2026 14:01
With RAG_EMBED_BACKEND=auto, _get_backend resolves the backend for the model
before it looks at the one it already built, and that resolution ends in
_resolve_auto, which calls LlamaCppBackend._get_gpu_free_memory. unslothai#9739 moved the
resolution ahead of the cache check so that saving a model rebuilds, and the
docstring still says auto detection runs only on a miss. So every encode,
token_counter, dim and embedding_identity call probed the GPU again. On a Vulkan
llama.cpp build the probe is a new Python process running _vulkan_probe.py, which
creates a Vulkan instance; otherwise it is nvidia-smi. Neither is memoised outside
a model load.

Measured with the probe counted and a fake embedder: the parent of unslothai#9739 asks once
across five encode calls and not at all across five dim calls; unslothai#9739 and main ask
five times for each. A linked-folder sync of ten new documents asked 31 times. The
tauri.log attached to unslothai#10390 shows it on a user's machine: 274 "Vulkan GPU memory
detected" pairs in 186 seconds while a linked folder was indexing.

The answer is now kept with the backend that was built from it, and read back while
that backend is published. The per-model checks in _resolve_auto_for_model (a local
GGUF, a stored backend, a GGUF repo name) still run on every call, so saving a model
that needs the other backend still rebuilds. release_backend and _reset_backend drop
the kept answer, and calls made before any backend exists still probe.

One consequence worth naming: a hardware change during a session, such as a GPU
appearing or a llama.cpp build switched, no longer reaches auto until the embedder
is unloaded or Studio restarts. That was the behaviour before unslothai#9739.

test_auto_asks_the_hardware_once_for_the_backend_it_built pins one probe per built
backend across all four calls, and a fresh probe after an unload; on main it sees
twelve extra probes. test_a_saved_backend_still_replaces_a_resident_auto_backend is a
parity guard for the rebuild unslothai#9739 added. The stub_embeddings comment that said auto
reprobes on every use now says what it does.

Refs unslothai#10390. That report also shows CPU use in sessions where no embedding model
loaded; this change does not address that part.

(cherry picked from commit 463f05c)
(cherry picked from commit 6a7c842)
A mutation pass over the existing guards caught only the cache itself: dropping the tie
to the published backend, or the per-thread clear in _get_backend, both changed behaviour
with every test still green. These pin the two mechanisms the change relies on.

(cherry picked from commit 76e7ad9)
(cherry picked from commit be3ba6f)
(cherry picked from commit 4b5935d)
(cherry picked from commit 9124db8)
@danielhanchen
danielhanchen force-pushed the fix/10390-auto-embedding-probes-hardware-once branch from b3bfa17 to 91a3bba Compare September 18, 2026 14:01
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 18, 2026
@danielhanchen
danielhanchen merged commit dd25fe1 into unslothai:main Sep 18, 2026
5 of 40 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…unslothai#11142)

* studio: probe the GPU once per embedding backend, not on every encode

With RAG_EMBED_BACKEND=auto, _get_backend resolves the backend for the model
before it looks at the one it already built, and that resolution ends in
_resolve_auto, which calls LlamaCppBackend._get_gpu_free_memory. unslothai#9739 moved the
resolution ahead of the cache check so that saving a model rebuilds, and the
docstring still says auto detection runs only on a miss. So every encode,
token_counter, dim and embedding_identity call probed the GPU again. On a Vulkan
llama.cpp build the probe is a new Python process running _vulkan_probe.py, which
creates a Vulkan instance; otherwise it is nvidia-smi. Neither is memoised outside
a model load.

Measured with the probe counted and a fake embedder: the parent of unslothai#9739 asks once
across five encode calls and not at all across five dim calls; unslothai#9739 and main ask
five times for each. A linked-folder sync of ten new documents asked 31 times. The
tauri.log attached to unslothai#10390 shows it on a user's machine: 274 "Vulkan GPU memory
detected" pairs in 186 seconds while a linked folder was indexing.

The answer is now kept with the backend that was built from it, and read back while
that backend is published. The per-model checks in _resolve_auto_for_model (a local
GGUF, a stored backend, a GGUF repo name) still run on every call, so saving a model
that needs the other backend still rebuilds. release_backend and _reset_backend drop
the kept answer, and calls made before any backend exists still probe.

One consequence worth naming: a hardware change during a session, such as a GPU
appearing or a llama.cpp build switched, no longer reaches auto until the embedder
is unloaded or Studio restarts. That was the behaviour before unslothai#9739.

test_auto_asks_the_hardware_once_for_the_backend_it_built pins one probe per built
backend across all four calls, and a fresh probe after an unload; on main it sees
twelve extra probes. test_a_saved_backend_still_replaces_a_resident_auto_backend is a
parity guard for the rebuild unslothai#9739 added. The stub_embeddings comment that said auto
reprobes on every use now says what it does.

Refs unslothai#10390. That report also shows CPU use in sessions where no embedding model
loaded; this change does not address that part.

(cherry picked from commit 463f05c)
(cherry picked from commit 6a7c842)

* Cover the two invariants that keep the hardware answer honest

A mutation pass over the existing guards caught only the cache itself: dropping the tie
to the published backend, or the per-thread clear in _get_backend, both changed behaviour
with every test still green. These pin the two mechanisms the change relies on.

(cherry picked from commit 76e7ad9)
(cherry picked from commit be3ba6f)

* Name the clear in _get_backend as load-bearing

(cherry picked from commit 4b5935d)
(cherry picked from commit 9124db8)

---------

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

Development

Successfully merging this pull request may close these issues.

2 participants