Skip to content

Studio: stop the idle RAG embedder from holding inference VRAM and slowing generation - #6744

Closed
oobabooga wants to merge 15 commits into
unslothai:mainfrom
oobabooga:studio-rag-embedder-vram
Closed

oobabooga wants to merge 15 commits into
unslothai:mainfrom
oobabooga:studio-rag-embedder-vram

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Follow-up to the Studio slowdown I flagged on #6718. There I measured the 90624 auto-pick running ~18% slower through Studio than on a bare llama-server and couldn't pin it in that thread. Root cause found and fixed here.

Cause

Studio warms the RAG embedder (bge-small, sentence-transformers) onto the inference GPU at startup, holding a ~336 MB CUDA context in the backend process for the whole session, even when RAG is never used. When a GGUF model then loads, llama-server allocates its KV and compute buffers with ~336 MB less free VRAM (the embedder is holding it). On a tight card (24 GB 3090) the large auto-pick (90624) drops free VRAM below the NVIDIA driver's system-memory spill threshold (~1.5 GB), so part of the allocation lands in host RAM and decode runs ~18% slower (GPU util 72% vs 91%).

It is not the engine and not the reserve PRs. A bare llama-server with the same pick runs at full speed. It is Studio holding inference-GPU VRAM for a model it is not using.

Fix

  • Don't warm the embedder at startup; load it lazily on first RAG use.
  • Free it (embeddings.unload()) in load_model, right before the GGUF GPU-memory probe, so the model always sizes and allocates with the embedder gone. It reloads lazily on the next RAG use, after the model's memory is placed (a context added after allocation does not move it, so the model stays fast).

The embedder still uses the GPU for ingestion, so bulk indexing keeps its speed; it just is not resident while a GGUF model is being placed.

Measured

24 GB 3090, Qwen3.6-27B-MTP UD-Q4_K_XL + mmproj-F16, q8_0 KV, 90624 auto-pick, 5-run average:

backend CUDA context at boot 90624 tok/s GPU util
before python 336 MB 47 72%
after none 54 90%

That matches the bare-engine baseline (~55 tok/s). The 66560 pick was already unaffected (enough headroom either way).

Tests

  • Live: Studio boots with no CUDA context; loads 90624 at 54 tok/s and ~90% util; unload() frees the embedder and it re-encodes correctly afterward; the "use RAG, then load a model" order also runs at full speed.
  • Unit: the RAG suites (embeddings, ingestion, retrieval) and the llama_cpp load / context-fit suites pass.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes VRAM usage by transitioning the RAG embedder to load lazily on first use rather than warming at startup. It also introduces an unload() function in embeddings.py to release GPU memory before loading a GGUF model in llama_cpp.py. The reviewer suggests refactoring this unload() mechanism to be backend-agnostic by defining it on the backend classes (such as _SentenceTransformersBackend and LlamaServerBackend) to ensure VRAM is freed properly regardless of the configured RAG backend.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread studio/backend/core/rag/embeddings.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0fdd70991d

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread studio/backend/core/rag/embeddings.py Resolved
Comment thread studio/backend/core/rag/embeddings.py Resolved
Comment thread studio/backend/core/rag/embeddings.py Resolved
@oobabooga
oobabooga requested a review from danielhanchen as a code owner June 29, 2026 14:09

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8a83d8f82e

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread studio/backend/core/rag/embeddings.py Resolved
@oobabooga

Copy link
Copy Markdown
Member Author

Thanks both. Went through every Codex and Gemini point and tested the result. Item by item.

Changed in the latest commit

  • Backend-agnostic unload (Gemini; Codex "stop the llama-server embedder before probing"): embeddings.unload() dispatches to the active backend. The llama-server embedder kills its subprocess, ST drops its model. So the llama-server path now frees everything, not just the ST case.
  • Clear the XPU cache too (Codex "clear XPU cache when unloading ST"): right, _st_unload only cleared CUDA. On an XPU host the model loads on xpu, so it now empties the cache for the device it actually ran on.
  • Block respawn during unload (Codex "block embedder respawns during unload"): an in-flight llama-server encode whose POST fails on the kill would call _restart() and bring the embedder back before sizing. Added an _unloading guard: _ensure_ready refuses to respawn while a load is unloading us, and the next deliberate encode clears it.
  • Wait for VRAM to settle (Codex "wait for RAG VRAM to settle"): unload() now returns whether it killed a GPU subprocess. When it did, load_model calls _wait_for_vram_settle() before probing, since the driver reclaims a dead process asynchronously.

Corrected, because testing proved Codex right

  • empty_cache cannot free the CUDA context (Codex): you were right and my earlier note was wrong. I measured it on a 24 GB 3090 with the reporter's 27B at the 90624 pick. With the ST embedder warmed by prior RAG use, unload() frees the weights but not torch's ~336 MB CUDA context, which empty_cache cannot release. That residual pushes ~209 MB of the model into host RAM. Generation drops to 46 tok/s at 77% util, versus 56 at 97% when the embedder never loaded. So "still runs at full speed" was false.

    What it means for the PR: the primary fix (no startup warm) fully resolves the reported case, since the embedder is no longer resident unless RAG was actually used. The unload() path is a partial reclaim for ST: it frees the weights, not the context. Fully reclaiming the context needs the ST embedder in a killable subprocess, the shape the llama-server backend already has. That is a separate, larger change, so I am flagging it rather than shipping it untested.

Left as a follow-up, not fixed here

  • Preserve the embedder for existing vectors (Codex): real edge. The unload plus lazy reload makes the pre-existing OOM to llama-server fallback more reachable, since the embedder now reloads under the new model's VRAM budget. Both sides are the same bge-small model, so a fallback yields near-identical vectors, but the silent cross-space switch is a genuine concern. Making the fallback space-aware (reindex, or fail visibly) belongs to the RAG fallback path, not this VRAM fix.
  • In-flight encode (Codex): for the llama-server embedder this is now covered by the respawn guard above. For ST, an in-flight encode holds its own reference, but that is the least of it: the context residual dominates, and it self-corrects on the next load.

Tests green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 57d58a7e1e

ℹ️ About Codex in GitHub

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

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

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

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 06087afa8a

ℹ️ About Codex in GitHub

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

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

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

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

wedges a request); a fresh server unsticks both."""
last_exc: Exception | None = None
for attempt in range(2):
epoch = self._unload_epoch

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recheck the unload epoch before respawning

If a RAG request is already entering _post when load_model calls LlamaServerBackend.unload(), it can read the old epoch here, then the unload kills the GPU child, and the unconditional _ensure_ready() immediately respawns it before the model fit probe. The later epoch check only runs for transport errors from post, so this pre-post race still lets an in-flight /tokenize or /v1/embeddings request put the embedder back into VRAM while llama_cpp.py is waiting/probing; recheck the epoch after _ensure_ready() or suppress ready/spawn during unloading before posting.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The ordering is real but both paths serialize on _lifecycle_lock, so there is no double process or corruption, only the throughput optimization not applying for that one load and self-correcting on the next. Rechecking the epoch inside _ensure_ready would regress the deliberate path: token_counter()'s /tokenize after an unload must respawn (covered by test_llama_deliberate_post_works_after_unload), which is exactly why the epoch guard is scoped to the error-retry path.

Comment thread studio/backend/main.py

_start_helper_precache_if_enabled()
threading.Thread(target = _warm_rag_embedder, daemon = True, name = "rag-embedder-warm").start()
# The RAG embedder is loaded lazily on first use, not warmed here: warming it

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Pin the embedder for existing KBs before lazy loading

Fresh evidence beyond the prior unload path is that this line now keeps _backend uninitialized until first RAG use. On a restart with an existing sentence-transformers-backed chunks_vec, if the user loads a large GGUF before querying RAG, embeddings.unload() is a no-op because no backend exists; the first dense/hybrid query then builds ST under the chat model's VRAM and _SentenceTransformersBackend.encode can fall back to llama-server, while retrieval.retrieve_dense still searches the persisted ST vectors. That silently mixes embedding spaces for existing KBs; initialize/pin the backend from the KB metadata or fail instead of falling back for persisted indexes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same pre-existing fallback as the one flagged on the load path: the mixing is in #5910's _switch_to_llama_fallback, untouched here. Lazy loading only changes the probability, and store.search_dense gating on model name rather than backend is a pre-existing limitation from #5910. Pinning per-KB backends from metadata is out of scope for a VRAM fix.

# Conflicts:
#	studio/backend/core/rag/embed_llama_server.py
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 8, 2026
@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 17222a8e79

ℹ️ About Codex in GitHub

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

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

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

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c96b6084d9

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +474 to +477
if attempt == 0 and self._unload_epoch == epoch:
self._restart()
continue
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve in-flight RAG requests during model loads

When a GPU-backed llama-server embedding request overlaps load_model, unload() increments the epoch and terminates the child, so the resulting transport error takes this break path and _post() raises instead of retrying. Dense searches therefore fail, and ingestion has no batch retry and marks the entire job failed (ingestion._run). Fresh evidence after the earlier respawn finding is that the new epoch guard suppresses the respawn without adding coordination or a higher-level retry; defer the active request or retry it after model placement rather than surfacing an unload-induced failure.

Useful? React with 👍 / 👎.

Comment on lines +6400 to +6401
if _rag_embeddings.unload():
self._wait_for_vram_settle(since_kill = time.monotonic())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the GPU embedder for CPU-only chat loads

When a GPU host deliberately loads a chat model with gpu_memory_mode="manual" and gpu_layers=0, this unconditional call still kills the GPU RAG server even though the launched chat server is explicitly classified as _deliberate_cpu_only and consumes no VRAM. An idle embedder then incurs an unnecessary cold respawn on the next RAG use, with no memory benefit for model placement; skip the unload for the zero-offload configuration, as is already done when other cleanup paths detect CPU-only servers.

Useful? React with 👍 / 👎.

Comment on lines +6398 to +6401
try:
from core.rag import embeddings as _rag_embeddings
if _rag_embeddings.unload():
self._wait_for_vram_settle(since_kill = time.monotonic())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Unload RAG before diffusion auto-sizing

When a GPU RAG embedder is resident and the selected GGUF is DiffusionGemma, load_model returns through _start_diffusion_server at the earlier diffusion branch, so it never reaches this new unload block. That runner passes --maxtok 0 by default and explicitly auto-sizes its context from currently free VRAM, leaving the embedder's allocation to reduce the image model's context or make startup fail—the same resource contention this change fixes for llama-server-backed GGUFs. Move the unload before the diffusion branch, while retaining the CPU-only safeguards.

Useful? React with 👍 / 👎.

@oobabooga

Copy link
Copy Markdown
Member Author

Closing because #6718's fully GPU-resident --fit off placement superseded the throughput fix this PR was created for. On current Studio, removing the startup embedder warm saves only roughly 90 MiB, while sentence-transformers unload reclaims roughly 58 MiB and leaves the PyTorch CUDA context resident. The remaining unload lifecycle complexity and concurrency edge cases are not justified by that residual benefit. We can revisit lazy embedder startup separately if the smaller idle-VRAM saving is worth the first-use latency tradeoff.

@oobabooga oobabooga closed this Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants