Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio RAG: count chunking tokens in batches (#16265)

Daniel Han9c7571070d08
diff --git a/studio/backend/core/rag/chunking.py b/studio/backend/core/rag/chunking.py
index 26e8c59ae58..7715704169d 100644
--- a/studio/backend/core/rag/chunking.py
+++ b/studio/backend/core/rag/chunking.py
@@ -6,7 +6,7 @@ page_char_start/page_char_end and source_page_index for locator highlights."""
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Callable
from .parsers import Page
@@ -67,6 +67,63 @@ def _split(
return [_Piece(part, count(part)) for j in range(0, len(text), n) if (part := text[j : j + n])]
+def _count_all(count: TokenCounter, texts: list[str]) -> list[int] | None:
+ many = getattr(count, "many", None)
+ if many is None:
+ return None
+ counts = list(many(texts))
+ if len(counts) != len(texts):
+ raise ValueError(f"token counter returned {len(counts)} counts for {len(texts)} texts")
+ return counts
+
+
+def _split_all(
+ texts: list[str],
+ token_counts: list[int],
+ seps: tuple[str, ...],
+ max_tokens: int,
+ count: TokenCounter,
+) -> list[list[_Piece]]:
+ """``_split`` per text, with every part cut at the same depth counted in one batch."""
+ out: list[list[_Piece] | None] = [None] * len(texts)
+ levels: dict[int, list[tuple[int, list[str]]]] = {}
+ sliced: list[tuple[int, list[str]]] = []
+ for idx, (text, token_count) in enumerate(zip(texts, token_counts)):
+ if token_count <= max_tokens:
+ out[idx] = [_Piece(text, token_count)]
+ continue
+ for i, sep in enumerate(seps):
+ parts = list(text) if sep == "" else text.split(sep)
+ if len(parts) <= 1:
+ continue
+ if sep:
+ parts = [p + sep for p in parts[:-1]] + parts[-1:]
+ levels.setdefault(i, []).append((idx, [p for p in parts if p]))
+ break
+ else:
+ n = max(1, max_tokens * 4)
+ sliced.append(
+ (idx, [part for j in range(0, len(text), n) if (part := text[j : j + n])])
+ )
+ if sliced:
+ counts = _count_all(count, [part for _, parts in sliced for part in parts])
+ k = 0
+ for idx, parts in sliced:
+ out[idx] = [_Piece(part, counts[k + j]) for j, part in enumerate(parts)]
+ k += len(parts)
+ for i, members in levels.items():
+ flat = [part for _, parts in members for part in parts]
+ children = _split_all(flat, _count_all(count, flat), seps[i + 1 :], max_tokens, count)
+ k = 0
+ for idx, parts in members:
+ pieces: list[_Piece] = []
+ for child in children[k : k + len(parts)]:
+ pieces.extend(child)
+ out[idx] = pieces
+ k += len(parts)
+ return out
+
+
def _merge(
pieces: list[_Piece], starts: list[int], max_tokens: int, overlap: int
) -> list[tuple[str, int, int]]:
@@ -116,9 +173,17 @@ def chunk_pages(
pages: list[Page], *, max_tokens: int, overlap: int, count: TokenCounter
) -> list[Chunk]:
"""Split each page into overlapping chunks, tracking per-page char offsets."""
+ page_counts = _count_all(count, [page.text for page in pages])
+ batched = page_counts is not None
+ split = (
+ _split_all([page.text for page in pages], page_counts, SEPARATORS, max_tokens, count)
+ if batched
+ else None
+ )
out: list[Chunk] = []
+ owed: list[tuple[int, str]] = []
for page_index, page in enumerate(pages):
- pieces = _split(page.text, SEPARATORS, max_tokens, count)
+ pieces = split[page_index] if batched else _split(page.text, SEPARATORS, max_tokens, count)
# _split preserves offsets, so a running cursor gives exact ones.
starts: list[int] = []
cursor = 0
@@ -127,9 +192,16 @@ def chunk_pages(
cursor += len(piece.text)
previous_end = 0
for text, char_start, char_end in _merge(pieces, starts, max_tokens, overlap):
- token_count = count(text)
+ token_count = -1 if batched else count(text)
overlap_chars = min(len(text), max(0, previous_end - char_start))
unique_text = text[overlap_chars:].lstrip("\r\n")
+ if unique_text == text:
+ whole = token_count
+ elif batched:
+ whole = -1
+ owed.append((len(out), unique_text))
+ else:
+ whole = count(unique_text)
out.append(
Chunk(
text = text,
@@ -139,10 +211,19 @@ def chunk_pages(
chunk_index = len(out),
page_char_start = char_start,
page_char_end = char_end,
- whole_document_token_count = (
- token_count if unique_text == text else count(unique_text)
- ),
+ whole_document_token_count = whole,
)
)
previous_end = max(previous_end, char_end)
- return out
+ if not batched or not out:
+ return out
+ token_counts = _count_all(count, [chunk.text for chunk in out])
+ whole_counts = dict(zip((k for k, _ in owed), _count_all(count, [t for _, t in owed]) or ()))
+ return [
+ replace(
+ chunk,
+ token_count = token_counts[k],
+ whole_document_token_count = whole_counts.get(k, token_counts[k]),
+ )
+ for k, chunk in enumerate(out)
+ ]
diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.py
index 8c31ec08aca..c64d433e31e 100644
--- a/studio/backend/core/rag/embeddings.py
+++ b/studio/backend/core/rag/embeddings.py
@@ -730,37 +730,78 @@ def _st_token_counter(model_name: str | None = None) -> Callable[[str], int]:
counts: dict[str, int] = {}
counted_by: list = [None]
- def _count(t: str) -> int:
- with _compute_lock:
- tok = _get(model_name).tokenizer
- owner = counted_by[0]
- if owner is None or owner() is not tok:
- counts.clear()
+ def _count_many(texts) -> list[int]:
+ texts = list(texts)
+ out = [0] * len(texts)
+ # The lock is released between batches so a query encode never waits out a whole document.
+ for start in range(0, len(texts), _ST_COUNT_BATCH):
+ with _compute_lock:
+ tok = _get(model_name).tokenizer
+ owner = counted_by[0]
+ if owner is None or owner() is not tok:
+ counts.clear()
+ try:
+ counted_by[0] = weakref.ref(tok)
+ except TypeError:
+ counted_by[0] = None
+ memoize = counted_by[0] is not None
+ misses: dict[str, list[int]] = {}
+ loose: list[int] = []
+ for i in range(start, min(start + _ST_COUNT_BATCH, len(texts))):
+ t = texts[i]
+ memo = memoize and type(t) is str
+ known = counts.get(t) if memo else None
+ if known is not None:
+ out[i] = known
+ elif memo:
+ misses.setdefault(t, []).append(i)
+ else:
+ loose.append(i)
+ if not misses and not loose:
+ # Leave the environment a tokenize would.
+ if os.environ.get("TOKENIZERS_PARALLELISM") != "false":
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ continue
+ keys = list(misses)
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
try:
- counted_by[0] = weakref.ref(tok)
- except TypeError:
- counted_by[0] = None
- memo = counted_by[0] is not None and type(t) is str
- known = counts.get(t) if memo else None
- if known is not None:
- # Leave the environment a tokenize would.
- if os.environ.get("TOKENIZERS_PARALLELISM") != "false":
+ lengths = _encoded_lengths(tok, keys + [texts[i] for i in loose])
+ finally:
os.environ["TOKENIZERS_PARALLELISM"] = "false"
- return known
- os.environ["TOKENIZERS_PARALLELISM"] = "true"
- try:
- n = len(tok.encode(t, add_special_tokens = False))
- finally:
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
- if memo:
- if len(counts) >= _ST_COUNT_CACHE_SIZE:
- counts.pop(next(iter(counts)))
- counts[t] = n
- return n
+ for key, n in zip(keys, lengths):
+ for i in misses[key]:
+ out[i] = n
+ if len(counts) >= _ST_COUNT_CACHE_SIZE:
+ counts.pop(next(iter(counts)))
+ counts[key] = n
+ for i, n in zip(loose, lengths[len(keys) :]):
+ out[i] = n
+ return out
+ def _count(t: str) -> int:
+ return _count_many((t,))[0]
+
+ _count.many = _count_many
return _count
+_ST_COUNT_BATCH = 256
+
+
+def _encoded_lengths(tok, texts: list) -> list[int]:
+ """``len(tok.encode(t, add_special_tokens=False))`` per text; a fast tokenizer's batch call is the path encode wraps."""
+ if len(texts) > 1 and getattr(tok, "is_fast", False) is True:
+ ids = tok(
+ texts,
+ add_special_tokens = False,
+ return_attention_mask = False,
+ return_token_type_ids = False,
+ )["input_ids"]
+ if len(ids) == len(texts):
+ return [len(row) for row in ids]
+ return [len(tok.encode(t, add_special_tokens = False)) for t in texts]
+
+
def _release_st_model() -> bool:
"""Drop the module-level SentenceTransformer without racing an encode."""
global _model, _name
@@ -1459,11 +1500,11 @@ def token_counter(model_name: str | None = None) -> Callable[[str], int]:
state = (backend, backend.token_counter(model_name = model_name))
counter_lock = threading.Lock()
- def _count(text: str) -> int:
+ def _served(use):
nonlocal state
served_backend, served_count = state
try:
- return served_count(text)
+ return use(served_count)
except RuntimeError:
if not (
_is_llama_backend(served_backend) and getattr(served_backend, "_closed", False)
@@ -1480,6 +1521,21 @@ def token_counter(model_name: str | None = None) -> Callable[[str], int]:
replacement.token_counter(model_name = model_name),
)
retry = state[1]
- return retry(text)
+ return use(retry)
+
+ def _count(text: str) -> int:
+ return _served(lambda count: count(text))
+
+ def _count_many(texts) -> list[int]:
+ texts = list(texts)
+ return _served(lambda count: _many(count, texts))
+ # Only a batching backend (sentence-transformers) changes how chunking asks for counts.
+ if getattr(state[1], "many", None) is not None:
+ _count.many = _count_many
return _count
+
+
+def _many(count, texts: list) -> list[int]:
+ many = getattr(count, "many", None)
+ return list(many(texts)) if many is not None else [count(t) for t in texts]
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.py
index 577e3c0f987..0a8fcd61af0 100644
--- a/studio/backend/core/rag/store.py
+++ b/studio/backend/core/rag/store.py
@@ -403,6 +403,11 @@ def add_chunks(
"""Incrementally index one document's chunks into chunks + FTS5 + vec0.
``vectors`` parallels ``chunks``; optional ``regions`` (also parallel) holds
per-chunk PDF highlight rects, stored as JSON."""
+ if len(vectors) != len(chunks):
+ # zip() below would silently drop the unpaired chunks from all three indexes.
+ raise ValueError(
+ f"{len(chunks)} chunks but {len(vectors)} vectors for document {document_id}"
+ )
if len(vectors):
rag_db.ensure_vec(conn, len(vectors[0]), document_id)
epoch_before = vec_cache.read_epoch(conn, scope) if vec_cache.enabled() else None
diff --git a/studio/backend/tests/test_rag_batched_token_counts.py b/studio/backend/tests/test_rag_batched_token_counts.py
new file mode 100644
index 00000000000..7e302ff8f3e
--- /dev/null
+++ b/studio/backend/tests/test_rag_batched_token_counts.py
@@ -0,0 +1,304 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Chunking asks a sentence-transformers counter for token counts in batches. The stored rows must be
+exactly those of one-at-a-time counting, with far fewer tokenizer calls."""
+
+import os
+import random
+import threading
+import time
+
+import pytest
+
+from core.rag import chunking, embeddings, ingestion, store
+from core.rag.chunking import chunk_pages
+from core.rag.parsers import Page
+from storage import rag_db
+
+import sqlite3
+
+# Same gate as the rag_conn fixture (the macos-15 runner's sqlite3 cannot load extensions).
+needs_sqlite_vec = pytest.mark.skipif(
+ not rag_db.RAG_AVAILABLE or not hasattr(sqlite3.Connection, "enable_load_extension"),
+ reason = "sqlite-vec cannot be loaded by this Python's sqlite3",
+)
+
+_REAL_TOKEN_COUNTER = embeddings.token_counter
+
+
+class _Tok:
+ """Fast-tokenizer stand-in whose counts are not additive over concatenation, like real BPE."""
+
+ is_fast = True
+
+ def __init__(self):
+ self.encodes = 0
+ self.batches = 0
+
+ @staticmethod
+ def _ids(text):
+ return [0] * (len(text.split()) + len(text) % 3 + text.count("##"))
+
+ def encode(
+ self,
+ text,
+ add_special_tokens = False,
+ ):
+ self.encodes += 1
+ return self._ids(text)
+
+ def __call__(
+ self,
+ texts,
+ add_special_tokens = False,
+ **kwargs,
+ ):
+ self.batches += 1
+ return {"input_ids": [self._ids(t) for t in texts]}
+
+
+class _Model:
+ def __init__(self, tok):
+ self.tokenizer = tok
+
+
+def _one_at_a_time(count):
+ """The same counter without its batch form, so chunking takes the per-text path."""
+ return lambda text: count(text)
+
+
+def _document(seed = 7, pages = 12):
+ rng = random.Random(seed)
+ words = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"]
+
+ def sentence():
+ return " ".join(rng.choice(words) for _ in range(rng.randint(3, 30))) + ". "
+
+ out = []
+ for n in range(pages):
+ parts = [f"# Section {n}\n"]
+ for _ in range(rng.randint(1, 6)):
+ parts.append("## Sub\n" if rng.random() < 0.3 else "")
+ parts.append("".join(sentence() for _ in range(rng.randint(1, 12))) + "\n\n")
+ # Unbroken runs reach the character and fixed-slice levels.
+ parts.append("x" * rng.randint(0, 400) + "\n")
+ parts.append(" \n\r\n" if rng.random() < 0.3 else "")
+ out.append(Page(text = "".join(parts), page_number = n + 1, char_count = 0))
+ return out
+
+
[email protected]("max_tokens,overlap", [(8, 0), (24, 6), (64, 16), (500, 64)])
+def test_batched_chunks_equal_one_at_a_time_chunks(monkeypatch, max_tokens, overlap):
+ monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _Model(_Tok()))
+ pages = _document()
+ batched = chunk_pages(
+ pages,
+ max_tokens = max_tokens,
+ overlap = overlap,
+ count = embeddings._st_token_counter("org/embedder"),
+ )
+ serial = chunk_pages(
+ pages,
+ max_tokens = max_tokens,
+ overlap = overlap,
+ count = _one_at_a_time(embeddings._st_token_counter("org/embedder")),
+ )
+ assert batched == serial
+ assert len(batched) > len(pages)
+
+
+def test_batched_count_matches_single_counts_and_memo(monkeypatch):
+ tok = _Tok()
+ monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _Model(tok))
+ count = embeddings._st_token_counter("org/embedder")
+ texts = ["a b c", "d e", "a b c", "", "f g h i j"] * 200
+ assert count.many(texts) == [len(_Tok._ids(t)) for t in texts]
+ encodes = tok.encodes
+ batches = tok.batches
+ assert count.many(["a b c", "d e"]) == [5, 2]
+ assert count("f g h i j") == 5
+ assert (tok.encodes, tok.batches) == (encodes, batches)
+ assert count.many([]) == []
+
+
+def test_batched_count_leaves_the_same_environment(monkeypatch):
+ monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _Model(_Tok()))
+ monkeypatch.setenv("TOKENIZERS_PARALLELISM", "true")
+ count = embeddings._st_token_counter("org/embedder")
+ count.many(["x y", "z"])
+ assert os.environ["TOKENIZERS_PARALLELISM"] == "false"
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
+ count.many(["x y", "z"])
+ assert os.environ["TOKENIZERS_PARALLELISM"] == "false"
+
+
+def test_a_backend_without_a_batch_form_is_counted_one_text_at_a_time(monkeypatch):
+ seen = []
+
+ class _Backend:
+ def token_counter(self, *, model_name = None):
+ return lambda text: seen.append(text) or len(text.split())
+
+ monkeypatch.setattr(embeddings, "_get_backend", lambda model_name = None: _Backend())
+ count = _REAL_TOKEN_COUNTER("org/embedder")
+ assert not hasattr(count, "many")
+ pages = _document(pages = 3)
+ chunk_pages(pages, max_tokens = 16, overlap = 4, count = count)
+ serial_order = list(seen)
+ seen.clear()
+ chunk_pages(pages, max_tokens = 16, overlap = 4, count = _one_at_a_time(count))
+ assert seen == serial_order
+
+
+def _ingest_with(monkeypatch, tmp_path, counter_factory, name):
+ path = tmp_path / name
+ path.write_text("\n\n".join(p.text for p in _document(seed = 11, pages = 40)), encoding = "utf-8")
+ monkeypatch.setattr(embeddings, "token_counter", counter_factory)
+ monkeypatch.setattr(embeddings, "chunk_tokens", lambda model_name = None: 32)
+ scope = store.kb_scope("K1")
+ doc_id, job_id = ingestion.start_ingestion(scope, "K1", None, name, str(path), background = False)
+ assert ingestion.get_job_status(job_id)["status"] == "completed"
+ conn = rag_db.get_connection()
+ try:
+ chunks = [
+ tuple(r)[1:]
+ for r in conn.execute(
+ "SELECT id, chunk_index, text, page_number, source_page_index, page_char_start, "
+ "page_char_end, token_count, whole_document_token_count, kind, pdf_regions_json "
+ "FROM chunks WHERE document_id=? ORDER BY chunk_index",
+ (doc_id,),
+ )
+ ]
+ fts = [
+ (r["text"], r["chunk_id"].replace(doc_id, "D"))
+ for r in conn.execute(
+ "SELECT text, chunk_id FROM chunks_fts WHERE chunk_id LIKE ? ORDER BY rowid",
+ (f"{doc_id}:%",),
+ )
+ ]
+ vectors = [
+ (r["chunk_id"].replace(doc_id, "D"), bytes(r["embedding"]))
+ for r in conn.execute(
+ "SELECT chunk_id, embedding FROM chunks_vec WHERE chunk_id LIKE ? ORDER BY rowid",
+ (f"{doc_id}:%",),
+ )
+ ]
+ store.delete_document(conn, doc_id)
+ finally:
+ conn.close()
+ return chunks, fts, vectors
+
+
+@needs_sqlite_vec
+def test_ingestion_stores_the_same_rows_batched_or_not(
+ rag_home, stub_embeddings, tmp_path, monkeypatch
+):
+ tok = _Tok()
+ monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _Model(tok))
+ batched = _ingest_with(
+ monkeypatch,
+ tmp_path,
+ lambda model_name = None: embeddings._st_token_counter(model_name),
+ "batched.md",
+ )
+ batched_calls = tok.encodes + tok.batches
+ tok.encodes = tok.batches = 0
+ serial = _ingest_with(
+ monkeypatch,
+ tmp_path,
+ lambda model_name = None: _one_at_a_time(embeddings._st_token_counter(model_name)),
+ "serial.md",
+ )
+ serial_calls = tok.encodes + tok.batches
+ assert batched == serial
+ assert len(batched[0]) > 100 and len(batched[1]) == len(batched[2]) == len(batched[0])
+ assert batched_calls * 10 < serial_calls
+ assert batched_calls < 40
+
+
+@needs_sqlite_vec
+def test_ingestion_tokenizes_a_document_in_few_calls(
+ rag_home, stub_embeddings, tmp_path, monkeypatch
+):
+ """Fails on a per-piece counter: through the real token_counter, a 40-page document costs a handful
+ of tokenizer calls (each with one environment swap) instead of one per piece."""
+ tok = _Tok()
+ monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _Model(tok))
+ monkeypatch.setattr(
+ embeddings,
+ "_get_backend",
+ lambda model_name = None: embeddings._SentenceTransformersBackend(),
+ )
+ chunks, _, _ = _ingest_with(monkeypatch, tmp_path, _REAL_TOKEN_COUNTER, "doc.md")
+ assert len(chunks) > 100
+ assert tok.encodes + tok.batches < 40
+
+
+@needs_sqlite_vec
+def test_delete_during_batched_chunking_cancels_and_stores_nothing(
+ rag_home, stub_embeddings, tmp_path, monkeypatch
+):
+ tok = _Tok()
+ monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _Model(tok))
+ monkeypatch.setattr(
+ embeddings, "token_counter", lambda model_name = None: embeddings._st_token_counter(None)
+ )
+ path = tmp_path / "doc.md"
+ path.write_text("\n\n".join(p.text for p in _document(pages = 20)), encoding = "utf-8")
+ scope = store.kb_scope("K1")
+ known = {}
+ doc_id_known = threading.Event()
+ real_chunk_pages = chunking.chunk_pages
+
+ def delete_while_chunking(*args, **kwargs):
+ assert hasattr(kwargs["count"], "many")
+ out = real_chunk_pages(*args, **kwargs)
+ doc_id_known.wait(30)
+ conn = rag_db.get_connection()
+ try:
+ store.delete_document(conn, known["id"])
+ finally:
+ conn.close()
+ return out
+
+ monkeypatch.setattr(chunking, "chunk_pages", delete_while_chunking)
+ doc_id, job_id = ingestion.start_ingestion(scope, "K1", None, "doc.md", str(path))
+ known["id"] = doc_id
+ doc_id_known.set()
+ deadline = time.time() + 30
+ while time.time() < deadline:
+ status = ingestion.get_job_status(job_id)
+ if status and status["status"] in {"completed", "failed", "cancelled"}:
+ break
+ time.sleep(0.05)
+ assert status["status"] == "cancelled"
+ conn = rag_db.get_connection()
+ try:
+ assert store.get_document(conn, doc_id) is None
+ assert conn.execute("SELECT count(*) FROM chunks").fetchone()[0] == 0
+ assert conn.execute("SELECT count(*) FROM chunks_fts").fetchone()[0] == 0
+ finally:
+ conn.close()
+
+
+def test_add_chunks_refuses_unpaired_vectors(rag_conn):
+ from core.rag.chunking import Chunk
+
+ chunks = [
+ Chunk(
+ text = f"alpha {i}",
+ token_count = 2,
+ page_number = None,
+ source_page_index = 0,
+ chunk_index = i,
+ page_char_start = 0,
+ page_char_end = 7,
+ )
+ for i in range(3)
+ ]
+ with pytest.raises(ValueError, match = "3 chunks but 2 vectors"):
+ store.add_chunks(rag_conn, "kb_x", "doc", chunks, [[0.1, 0.2], [0.3, 0.4]])
+ rag_conn.rollback()
+ assert rag_conn.execute("SELECT count(*) FROM chunks").fetchone()[0] == 0
+ assert rag_conn.execute("SELECT count(*) FROM chunks_fts").fetchone()[0] == 0