Repository navigation
Studio: probe the GPU once per embedding backend, not on every encode - #11142
danielhanchen merged 3 commits into
Conversation
|
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
|
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? |
|
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. VerifiedI ran your guard test against 12 extra probes over 12 calls, and green on your branch. Collateral, cherry-picking your commit onto current
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 doingThe formatting churn in 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 So: drop Two notes on the change, neither blocking
It is one dead object in one slot, cleared by the next auto probe or by The other is that Happy to merge once the bot commit is dropped and the branch is rebased. |
|
Ran a full simulation pass on this: not just "does the fix work" but "what else moved". Summary first, then the evidence. 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 argumentStructural diff of The 3-term predicate you added, over every reachable combination of its terms:
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 ( 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, The win, measuredReal Warm, 6 threads, 12,000 hot calls after the backend exists:
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
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, The finding: the guards are thinI broke the fix five ways and ran your two tests against each:
M4 and M5 are not harmless. Under M5 the resident tuple becomes M2 is an equivalent mutant, not a gap: 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 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 NoneI 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 armsStaged on a disposable repo, counts read from the run logs rather than the tick, since the generated workflow has soft-fail logic:
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 What I could not proveNo real Vulkan host was exercised; the Vulkan branch was reached only by spoofing, so the 274-line Still blocking, unchanged from my earlier comment: drop |
|
@codex review |
|
@codex security review |
|
@codex review |
|
Thanks for taking the branch over. Checked at pre-commit.ci pushed 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
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
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. |
|
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
#11251: the product was wrong, the test was right. The contract comes from #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
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 On your changeNothing 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
The Vulkan probe logged the same "Vulkan GPU memory detected" line as the Under load, 8 threads by 5,000 rounds with another thread looping |
|
@codex review |
1 similar comment
|
@codex review |
8548cec to
b3bfa17
Compare
|
Rebased the branch and dropped the work that landed upstream while this was open. Head is now What came offI 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 What is on the branch
That last one: #11260 sat the notification rail flush in its corner and took the shadow gutter into an inline style, so Bisected to 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 Confirmed against the three regressions they exist for, each mutated into
On the reviewCodex never answered the two Staging CI is re-staged on the new head, scoped to this PR's own test files rather than advisory. Your changeUnchanged 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 |
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)
b3bfa17 to
91a3bba
Compare
…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]>
Summary
With
RAG_EMBED_BACKEND=auto(the default), everyencode,token_counter,dimandembedding_identitycall re-runs the GPU probe, and the probe starts a process each time:_vulkan_probe.pyon a Vulkan llama.cpp build,nvidia-smiotherwise. A linked-folder sync of ten documents probed 31 times. Thetauri.logattached 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
autoasks 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_backendresolves 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:_resolve_auto_for_modelends in_resolve_auto, which callsLlamaCppBackend._get_gpu_free_memory(). The docstring above still says "autodetection runs only on a miss", andstub_embeddingsintests/conftest.pyalready pinned the backend because "auto" reprobes the hardware (nvidia-smi) on every use.The probe is a process start, not a lookup.
_run_vulkan_proberuns_vulkan_probe.pyundersys.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._get_gpu_memoryrunsnvidia-smifirst, with no memo.Changes
studio/backend/core/rag/embeddings.py_resolve_auto's answer is kept with the backend_get_backendbuilt (_resident_hardware), and read back only while that backend is the one published._resolve_autonow has one caller, so every path that resolvesauto(_get_backend,resolved_backend_for_model,_current_backend_key,active_backend_is_llama,_identity_backend_is_llama) goes through it._resolve_auto_for_modelstill 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._get_backenditself 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's91a3bba9c).release_backendand_reset_backenddrop the kept answer. With the published-object check, that is two ends, so neither alone is load-bearing.studio/backend/tests/conftest.pystub_embeddingscomment now reads "probes the hardware (nvidia-smi) for each backend it builds". The pin itself stays.On 09-18 Daniel rebased the branch onto
mainated91ec211. 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.encodex5dimx540b4702cd, the parent of #9739be9e5aada, #9739ed91ec211, this branch's baseOn
ed91ec211,encode,token_counter,dimandembedding_identityeach 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.ed91ec211With the Vulkan branch taken and
subprocess.runcounted, five resolutions start five_vulkan_probe.pyprocesses and log these two lines each time:The
tauri.logattached to #10390 (desktopv0.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_probereturns[]for any non-zero exit, exception or 15 s timeout; on any other build,nvidia-smi, NVML,amd-smiand torch all have to come back empty._resolve_autoreads[]as no GPU and picks llama-server. Measured with_resolve_autorunning for real, the probe's answers scripted and both backends faked, four batches for one model (the review suggested adding this):ed91ec211st, st, llama, st: two embedding spaces, the ST model released and rebuilt, llama-server built and shut downstx4, one probellama, st, st, st: two embedding spacesllamax4, thenstafterrelease_backend40b4702cd, before #9739, serves both rows the way this branch does.Daniel measured the real cost in review, with
unslothai/llama.cppprebuilts and 20 warm calls once a backend exists: about 0.5 s per call on a Vulkan build, about 0.1 s wherenvidia-smiruns, and two process starts per call wherenvidia-smiis missing, against none with this change. Daniel's comment on this PR has the table.Compatibility
RAG_EMBED_BACKEND=sentence-transformersorllama-serverautois never resolvedtest_a_saved_backend_still_replaces_a_resident_auto_backendautofor a plain modeltest_a_replaced_backend_asks_the_hardware_againtest_a_resolution_that_never_asked_the_hardware_keeps_nothing_switch_to_llama_fallbackafter an ST encode failureautoresolution asks again: the published backend is no longer the one the answer was kept forrelease_backend)test_auto_asks_the_hardware_once_for_the_backend_it_builtmainautountil the embedder is unloaded or Studio restarts, as before #9739Tests
studio/backend/tests/test_rag_embeddings.py, 4 new tests. The last two are Daniel's, from review.test_auto_asks_the_hardware_once_for_the_backend_it_builtencode,token_counter,dimandembedding_identity, and a new probe afterrelease_backended91ec211test_a_saved_backend_still_replaces_a_resident_auto_backendautobackend, as #9739 intendedtest_a_replaced_backend_asks_the_hardware_againautofrom the replaced backend's probetest_a_resolution_that_never_asked_the_hardware_keeps_nothingactive_backend_is_llamaprobes outside the lock, a build that never asked keeps nothing_resident_hardwaredoes not exist oned91ec211(AttributeError); guards M3r and M5Mutation table. Each perturbation applied to this branch's
embeddings.py, the file run, then restored:embeddings.pyas oned91ec211test_auto_asks_the_hardware_once_for_the_backend_it_builtandtest_a_resolution_that_never_asked_the_hardware_keeps_nothingautobackend is returned even when the stored backend changedtest_a_saved_backend_still_replaces_a_resident_auto_backendandtest_a_replaced_backend_asks_the_hardware_againrelease_backendkeeps the answerrelease_backendalso unpublishes the backend, so the published-object check already refuses the old answer_reset_backendkeeps the answertest_a_resolution_that_never_asked_the_hardware_keeps_nothing, through the answer the previous test leaves behind (the autouse fixture resets with_reset_backend)test_a_replaced_backend_asks_the_hardware_againtest_a_replaced_backend_asks_the_hardware_againandtest_a_resolution_that_never_asked_the_hardware_keeps_nothingtest_auto_asks_the_hardware_once_for_the_backend_it_builtandtest_a_replaced_backend_asks_the_hardware_againThe 59 test files that touch the RAG embedding code (57 under
studio/backend/tests, plusstudio/backend/hub/tests/test_model_services.pyandtests/studio/install/test_rocm_support.py), run with Backend CI's selection (-n 4 --dist loadgroupand its-kdeselect) oned91ec211and on this branch at91a3bba9c, then compared by test id:ed91ec211studio/backend/tests(57 files)hub/tests/test_model_services.pytests/studio/install/test_rocm_support.pyThe 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
mainatbe95e417b: 773 passed and 28 failed, then 777 and 28. The 28 are the same test ids on both (26 intest_rag_embed_llama_server.py, one each intest_openai_embeddings_studio_fallback.pyandtest_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
autountil 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.mainswitches back to sentence-transformers on the next call and splits the space.40b4702cdbehaves like this branch.embedding_identity(_identity_backend_is_llama, thenactive_backend_is_llama) and from the build: 3 probes for the first document, then none.