Skip to content

Studio RAG: embed the documents of one ingest together instead of one call per document - #16727

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
debojyoti-dev:fix/shared-embed-batch-16715
Nov 7, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
debojyoti-dev:fix/shared-embed-batch-16715

Conversation

@debojyoti-dev

Copy link
Copy Markdown
Contributor

Fixes #16715.

RAG ingestion embedded one document at a time: _embed_all ran per document, so _EMBED_BATCH only ever batched chunks inside one file. A corpus of small files — notes, docs, a wiki — therefore ran entirely on the batch-of-1 path, paying a whole encode call for each one-chunk file.

What changed

  • Ingestion shares an embed queue. Chunks from the documents being ingested at the same time are encoded in the same _EMBED_BATCH slice.
  • Each document keeps what it had: its own embedding identity (a backend swap part way still restarts only that document's pass), its own progress, and its own failure, since a failed shared batch is retried per document before anything is reported as failed.
  • A batch holds one account's texts for one model, because the encode runs as whichever caller took the batch, with that account's token, model path and device.
  • A linked-folder sync keeps more small files in flight. Only the parse workers hold a stage slot; a document with less than a batch of chunks gives its slot up while it waits, so files still being parsed can join its batch. Files above RAG_FOLDER_INGEST_BATCH_FILE_BYTES (1 MB) stay within the worker count, so a folder of large documents holds no more snapshots or parsed chunks at once than before.
  • No new thread: a waiting caller encodes the next batch for everyone, so the encode still runs on an ingestion thread bound to the right account. New settings are RAG_FOLDER_INGEST_IN_FLIGHT (16) and RAG_FOLDER_INGEST_BATCH_FILE_BYTES.

Measurements

A 400-note vault (median 1.5 KB, mostly one chunk each), unsloth/bge-small-en-v1.5, Ryzen 5600H + RTX 3050, real files through a real linked-folder sync:

embedder encode calls time inside the embedder sync wall
GPU 400 → 193–236 11.2 s → 7.8–9.3 s 44–50 s, unchanged
CPU 400 → 90 compute bound, see below 75.5 s → 68.0 s

Per-chunk encode cost on the same machine, a batch of 1 against a batch of 32:

batch 1 batch 32
GPU, 300-token chunks 14.9 ms 2.94 ms
GPU, 40-token chunks 14.1 ms 0.67 ms
CPU, 40-token chunks 25.6 ms 11.3 ms
CPU, 300-token chunks 92.5 ms 81.3 ms

Two notes on the numbers, since they are smaller than the issue estimates. On this CPU a 300-token chunk is compute bound, so batching cannot shorten it; the sync still gains because the per-file work overlaps. And once the embedder is this much faster than the pipeline feeding it, batches fill only as fast as files are parsed, which is why the GPU wall time is flat while the embedding work falls by about a third. The batch-of-1 path itself is gone either way, and the gain grows with a slower embedder or a faster parse stage.

Tests

  • New studio/backend/tests/test_rag_shared_embed_batch.py: documents sharing one encode call, each document's vectors landing on its own chunks (checked against chunks_vec), one failing document not failing its batch mates, different models and different accounts never sharing a batch, a full-batch document not waiting, a waiting document still reporting embedding progress, a backend swap inside a shared batch still re-embedding that document, and nothing left in the queue after a failure.
  • New linked-folder tests: a folder of small files embedding across documents, and large files staying within the parse workers.
  • 407 passed, 5 skipped across the RAG ingestion, linked-folder, embedding-identity, re-embed and upload suites. The 10 failures in the Office/OCR suites and the 37 in test_rag_embed_llama_server.py are identical on clean main on this Windows box (symlink privilege and local Office/OCR tooling).

… call per document

A corpus of small files was ingested entirely on the batch-of-1 embedding path: _embed_all ran
per document, so _EMBED_BATCH only ever batched chunks within one file, and a vault of one-chunk
notes paid a whole encode call for each one.

Ingestion now shares an embed queue. Chunks from the documents being ingested at the same time
are encoded in the same _EMBED_BATCH slice, while each document keeps what it had before: its own
embedding identity (a backend swap part way still restarts only that document's pass), its own
progress and its own failure, since a failed shared batch is retried per document. Batches hold
one account's texts for one model, because the encode runs as the caller that took the batch.

A linked-folder sync also keeps more small files in flight. Only the parse workers hold a stage
slot; a document with less than a batch of chunks gives its slot up to wait, so files that are
still parsing can join its batch. Files above RAG_FOLDER_INGEST_BATCH_FILE_BYTES stay within the
worker count, so a folder of large documents holds no more snapshots or chunks than before.

Measured on a 400-note vault (median 1.5 KB, mostly one chunk) with unsloth/bge-small-en-v1.5:

  embedder   encode calls      embedding time     sync wall
  GPU        400 -> 193-236    11.2s -> 7.8-9.3s  unchanged
  CPU        400 -> 90         (see below)        75.5s -> 68.0s

Per-chunk encode cost on the same machine, batch of 1 against a batch of 32: 14.9 -> 2.9 ms on
the GPU for 300-token chunks, 14.1 -> 0.67 ms for short ones, 25.6 -> 11.3 ms on the CPU for
short ones. CPU time for 300-token chunks is compute bound, so batching does not shorten it; the
sync still gains because the per-file work overlaps.
@debojyoti-dev
debojyoti-dev force-pushed the fix/shared-embed-batch-16715 branch from b03a208 to 02b8128 Compare November 5, 2026 03:23
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-07T11:12:44.054332Z 48ae1d5 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 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: 4437fa20cb

ℹ️ 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 +280 to +282
if on_progress is not None and request.filled > reported:
reported = request.filled
on_progress(reported, len(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 Keep cancellation checks active before a request's first slice

When a linked-folder file queues behind a large upload under the same account/model, _take keeps selecting the older request until all of its chunks are scheduled, but this guard suppresses the queued file's on_progress until its own first slice lands. The unlink check lives in _progress, so folder_sync.delete_folder() can wait for the unrelated upload's entire embedding pass while the folder-sync lease continues renewing. Check cancellation and lease ownership while waiting or encoding other requests, or schedule requests fairly, so unlinking remains bounded by a batch rather than another document's size.

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.

Fixed in 761f6dc: each shared batch now takes a share from every waiting request, so a small file's progress and unlink check run every batch instead of after a large document's whole pass.

Comment thread studio/backend/core/rag/ingestion.py Outdated

def _linger(self, key) -> None:
deadline = time.monotonic() + _EMBED_LINGER_SECONDS
while self._expected > 0 and self._queued(key) < _EMBED_BATCH:

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 Scope expected arrivals to the batch's account and model

When a long parse/OCR is active for another account or model, the process-global _expected remains positive even though those documents cannot join this key's batch. This particularly affects reembed._run, which embeds documents serially through _embed_all: every short document waits the full 200 ms even if no same-key ingestion is in progress, adding 20 seconds of idle time across 100 notes while the unrelated parse remains active. Track expected arrivals per account/model and consult only the current key here.

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.

Fixed in 761f6dc: parsing documents are counted per account and model, so a batch only lingers for documents that can join it.

…U, share batches fairly, count parsing documents per model

Padding a shared batch to its longest text cost more on CPU than the calls it saved
(400-note vault on 4 CPUs: 67-73 s per sync before, 92-98 s with shared batches).
Accelerators and llama-server keep the shared queue. A large document no longer
holds back the others' progress and unlink checks for its whole pass, and a parse
under another account or model no longer makes a batch linger.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 761f6dc6f6

ℹ️ About Codex in GitHub

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

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

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

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

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: defe37cfdf

ℹ️ 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/core/rag/embeddings.py Outdated
def batches_across_documents(model_name: str | None = None) -> bool:
"""Whether concurrent documents should share encode calls (#16715). Not for sentence-transformers on
CPU: it pads each batch to its longest text, and on CPU that padding costs more than the calls saved."""
return active_backend_is_llama(model_name) or _device() != "cpu"

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 Use the actual ST device for the cross-document batching gate

When sentence-transformers has GPU selected but _load_device() degrades to CPU, or _get() retries a failed GPU load on CPU, _device() still reports cuda/xpu. This predicate therefore enables cross-document batching for the CPU model instead of taking the per-document CPU path. Mixed-length notes then incur the CPU batch-padding slowdown that this exception is intended to prevent, regressing indexing performance compared with the previous per-document encodes. Base the gate on the model's actual execution device, including CPU fallbacks, rather than only the preferred device.

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.

Fixed in 7654063: the gate reads the loaded model's device, so a GPU choice that fell back to CPU keeps per-document calls.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 48ae1d5bce

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

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.

RAG ingest embeds one document at a time: ~99 ms/chunk on the batch-of-1 path vs 2.07 ms batched

2 participants