Skip to content

Studio: serve /v1/embeddings from the configured embedding model when the loaded GGUF cannot - #10315

Merged
danielhanchen merged 41 commits into
unslothai:mainfrom
NilayYadav:fix-embeddings-api-fallback
Sep 6, 2026
Merged

danielhanchen merged 41 commits into
unslothai:mainfrom
NilayYadav:fix-embeddings-api-fallback

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

/v1/embeddings only ever talked to the model in the chat slot. With nothing loaded it returned 503, and with a chat model loaded llama-server returned 501. Meanwhile Studio's own embedding model from Settings was already running next to the chat model for document search, and the API had no way to reach it.

Now, if an embedding GGUF is loaded it is used exactly as before. Otherwise the request goes to the Settings embedding model. Chat and embeddings work at the same time, which is what #8535 asked for and what #9128 reported as broken.

Naming the Settings embedding model in the request works too, by its name, its GGUF repo, or the identity the response reports. Any other model name goes through the normal auto-switch logic first, as on every other route.

The fallback returns the normal OpenAI response shape and supports float and base64. Input longer than the model allows gets a 400 instead of being cut short. The limit comes from the model itself on both embedder backends, the sentence-transformers max length or the GGUF context length, minus the special tokens the tokenizer adds. It runs under a small concurrency limit and never touches the chat model or its unload gate, so nothing that works today changes.

The response reports the embedding model that actually produced the vectors, including which backend ran it, so a client can tell if the space changed.

Tested on a real Studio: the same requests that return 503 and 501 on main return 200 here, with chat completions still working while embeddings are served. Boundary checked on the GGUF embedder: 510 tokens pass, 511 is rejected.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 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-06T17:41:24.515535Z 15b4065 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[bot]

This comment was marked as resolved.

@NilayYadav

NilayYadav commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

GitHub Actions reproduction

Reproduced the defect and verified the fix on real ubuntu-latest runners. Both branches are built from the same fresh upstream main and run a byte-identical harness and probe; they differ only in the four files this PR changes. The probe boots unsloth studio through the repo's own boot-studio-api-only.sh and drives the HTTP API — no mocks.

  • Fresh upstream main 49dac87ab — defect run: nothing loaded → 503 "No GGUF model loaded. Load a GGUF model first."; with unsloth/gemma-3-270m-it-GGUF resident → 501 "This server does not support embeddings. Start it with --embeddings".
  • Same base + this PR f0155e549 — passing run: both cases → 200 with a 384-dim vector from unsloth/bge-small-en-v1.5, and POST /v1/chat/completions still 200 immediately after, so chat and embeddings really are served at the same time.

Probe result lines, verbatim:

BEFORE {"chat_after":200,"chat_loaded":501,"chat_loaded_dim":0,"load":200,"no_model":503,"no_model_dim":0}
AFTER  {"chat_after":200,"chat_loaded":200,"chat_loaded_dim":384,"load":200,"no_model":200,"no_model_dim":384}

PR 10315 GitHub Actions before/after

Review findings fixed on this branch

Each was reproduced before it was fixed, and each carries a regression test that fails before the change and passes after:

  1. e662b70c1 — the fallback claimed the llama keep-warm slot. /v1/embeddings is an _INFERENCE_SUFFIXES path that is not in _NON_LLM_SLOT_SUFFIXES, so returning 200 without llama-server running made the middleware clear preview ownership for a request that never touched llama.cpp, hold the in-flight count for the whole encode, and refresh the idle-unload TTL. Now untrack_current_request runs first, matching the external-provider chat branch.
  2. f0155e549 — cancelled requests leaked admission permits. to_thread cannot cancel its worker, so releasing the permit on cancellation admitted the next batch while the old threads were still embedding. The test reports peak=8 against the cap of 4 before the change and peak=4 after.
  3. e662b70c1 — API monitor context gauge. _monitor_openai_chunk's third argument is context_length, and api_monitor divides the batch-summed prompt_tokens by it, so passing the per-text limit pinned any multi-input request at 100%. It is now passed only for a single input.

Notes

  • The runner has no GPU, so _resolve_auto() selects the llama-server embedding backend. As of 88ac612 that backend reads the GGUF context length for max_tokens(), so the over-length 400 applies there too (checked live: 510 tokens pass, 511 is rejected).
  • With auto-switch on, a model name that resolves to a downloaded chat GGUF still goes through the existing switch logic before the fallback, as described in the PR body.

Update for the review fixes

Same harness, staged on fresh upstream main + this PR at 6ed62117e with #10320 on top (run 33927795576), with a chat GGUF (unsloth/gemma-3-270m-it-GGUF) resident and the llama-server embedder selected (no GPU on the runner):

Probe before these fixes now
POST /v1/embeddings with model unsloth/bge-small-en-v1.5 while a chat GGUF is loaded 404 "not downloaded on this server" 200, 384-dim
same with model unsloth/bge-small-en-v1.5-GGUF 404 200
700-word input 502 400 "'input' exceeds the 510-token limit"
510-word input 502 200
511-word input 502 400
POST /v1/chat/completions afterwards 200 200

The 510 is the GGUF's 512 context minus the two special tokens the server adds, read from the model instead of assumed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ning context and default prompt, hide local model paths
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4354283699

ℹ️ 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 thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…disconnect, match aliases without probing and keep redacted local names unique
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d6efec00bf

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

# encode: a 2xx would otherwise claim the llama slot, block a preview swap for the whole
# encode, and stamp the idle-unload TTL for a model that did no work.
_scope = getattr(request, "scope", None)
untrack_current_request(_scope)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep fallback embeddings visible to training admission

When the configured embedder is GPU-backed and an API-key client starts training during a fallback embedding request, this call removes the request from _inflight for the entire encode, including while a cancellation leaves its worker thread running. Both training entrypoints use other_inference_request_count(current_request_counted = False) as their active-inference guard (routes/training.py:1184-1189 and 2714-2719), while their VRAM cleanup does not unload or wait for core.rag.embeddings, so training can begin allocating the GPU concurrently with the embedder and fail the request or training run with an OOM. Keep this work counted until the worker finishes and use a separate scope marker to suppress only the llama-slot claim.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one. The mechanism is described correctly - the untrack does drop the request from _inflight, and other_inference_request_count(current_request_counted = False) is what both training entrypoints read - but the OOM it is aimed at does not depend on that window.

Neither embedder holds its VRAM only for the duration of an encode. The llama-server backend runs in a subprocess that lives until process exit (atexit.register(self._shutdown), embed_llama_server.py:168); its VRAM is resident before the request arrives and after it returns. The in-process torch backend defaults to CPU (_device(), embeddings.py:58, and the auto note at config.py:226), and under RAG_EMBED_DEVICE=gpu its first allocation creates a CUDA primary context that, per that same docstring, no amount of unloading returns. So keeping the request counted for the worker's lifetime would gate training on a window that does not determine whether the embedder is on the GPU.

It also would not close the gap it names. core/rag/ingestion.py:121, conversation_archive.py:413, web_rank.py:100 and retrieval.py:63 drive the same embedder from background work that has never been in _inflight, on main as much as here - a folder sync is far heavier than one memory-search batch and stays invisible to training admission either way.

Against that, keeping it counted has a real cost: the guard 409s training-over-API whenever any inference request is in flight, and an agent that runs memory search each turn would make training effectively unstartable.

The broader point that GPU-resident embedder VRAM is not represented to training admission is fair, but it is pre-existing, it covers every embedder caller rather than this one route, and the fix belongs where the embedder acquires the GPU, not in this request's tracking scope.

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

Copy link
Copy Markdown
Member

@codex review

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 158f51e527

ℹ️ 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 +563 to +565
if prompt and tokenizer is not None:
reserved += len(tokenizer.encode(prompt, add_special_tokens = False))
return max(1, int(limit) - reserved)

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 Count the default prompt and input in one tokenization

For SentenceTransformer models with a default prompt and a boundary-sensitive tokenizer such as BPE, token counts are not additive across concatenation: encode() tokenizes prompt + text, while this computes a fixed prompt reservation and the route separately tokenizes text. Near max_seq_length, boundary merges can therefore make the endpoint reject a valid input or, worse, admit an input that encode() silently truncates. Count each prompted input as the model actually tokenizes it rather than subtracting the independently tokenized prompt.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The tokenizer semantics are right, but this does not clear the bar for a change here.

The branch only fires when the model declares a non-null default_prompt_name; per the sentence-transformers docs, if it is not set no prompt is applied at all. Surveying the models this setting realistically holds, every one has default_prompt_name: null - bge-small-en-v1.5 (the default, and WordPiece), bge-m3, nomic-embed-text-v1.5, mxbai-embed-large-v1, snowflake-arctic-embed-m-v2.0 and Qwen3-Embedding-0.6B all ship prompts at most as named entries a caller must select.

I measured the non-additivity rather than assuming it. Over 8000 random inputs per model, comparing len(enc(p + t)) against len(enc(p)) + len(enc(t)): Qwen3-Embedding-0.6B (BPE) ranges -1 to +1; snowflake-arctic-embed-m-v2.0 (Unigram) and bge-small-en-v1.5 (WordPiece) are exactly 0 in every case. So the boundary effect is real on BPE but bounded at one token, and the reservation already subtracts num_special_tokens_to_add() on top, which is the larger term.

The remedy also has a cost outside this route. token_counter is the same callable chunking holds for a whole document, where the passage side is not what a default query prompt would be prepended to; folding a prompt into it would resize chunks everywhere to buy back one token at the limit.

Leaving it as a conservative reservation.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 270e7c405d

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

# setting, mixing one model's limit and dimension with another's vectors.
limit = rag_embeddings.max_tokens(model_name)
count = rag_embeddings.token_counter(model_name)
token_counts = [count(text) for text in texts]

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 Avoid one tokenize request per batch item

When the configured fallback uses LlamaServerBackend and the input contains many distinct strings, this comprehension invokes the counter's synchronous /tokenize POST once per item; those calls are serialized by the backend's serve lock before embedding begins. A valid maximum-size batch therefore makes 2,048 local HTTP round trips versus roughly 32 embedding requests at the default batch size, causing severe latency and likely client timeouts. Count the batch in one operation or impose a substantially smaller limit for this backend.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The per-item round trip is real - _post takes _serve_lock, so the counts are serialized - but I do not think it clears the bar, and the suggested remedy is not available.

llama.cpp's /tokenize takes a single content string; the documented options are content, add_special and parse_special, with no array form. There is no way to count a batch in one operation against this server.

I measured the transport rather than guess at it: 2048 sequential localhost POSTs through the same httpx client take 2.10s, about 1.0ms each. That is against embedding the same 2048 texts, which on the CPU path this backend defaults to runs at roughly 445 chunks/s - about 4.6s. So the counting adds well under half of a request that was already seconds long, and the counter is lru_cache(maxsize = 4096), so repeat text within and across batches is free.

A smaller cap for this backend would be a real behavior change - the same 2048 is what the ST path serves - to buy back a fraction of a request nobody has reported timing out. If a batch that size does turn out to be a problem in practice it is the embedding, not the tokenizing, that has to get cheaper.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 6, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

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

Reviewed commit: 15b4065348

ℹ️ 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 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 6, 2026
@danielhanchen
danielhanchen merged commit b8d120a into unslothai:main Sep 6, 2026
47 of 48 checks passed
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