mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-14 14:17:08 +00:00
fix: chunk-budget blowups, FastEmbed built-ins, and re-embed gaps
Follow-up review pass over the embeddings branch. - Fold an oversized header back into the body, and drop header duplication when it would leave under a quarter of the chunk budget. A header at or over max_tokens collapsed the body budget to one token, so a document became one chunk per body token, each still over the cap: a 95 KB file produced 20k chunks of 2563 tokens against a 1250 cap. Also clamp max_tokens to at least 1, as the strategy chunkers already do. - Emit a header-only document as its own chunk. With no body piece to attach it to, splitting returned nothing and the document was dropped from the index with no error and no log line. - Skip add_custom_model for a repository FastEmbed already ships. It rejects a name it knows, so configuring any of its ~30 built-ins (MiniLM, bge, e5, gte, ...) failed every embed call and every query. - Decide "the user chose this model" by comparing against the field default rather than model_fields_set, which is true for anything read from .env. Every setup script has always written EMBEDDINGS_NAME, so an upgraded remote-embeddings install inherited mpnet's 384-token window and silently clipped ~80% off every chunk. - Cut tiktoken splits at character offsets instead of decoding each token window. A multi-byte character straddling a boundary decoded to U+FFFD on both sides, destroying one character at roughly one boundary in five on CJK text -- including at the default max_tokens of 2000. - Let the re-embed script open a FAISS index whose width does not match the configured model. That mismatch is the main reason to run it, and the error recommending the script was raised by the script itself, so the advice failed on every source. - Re-embed graph_nodes.name_embedding when GraphRAG is enabled. Those vectors seed every traversal and share the chunk vectors' width, so a same-width model swap left the graph retrieving from the old space with nothing to report it. - Prefetch the models before copying the application source, so editing any file no longer re-downloads ~780 MB of artifacts on every build. - Mirror the setup.sh embedding menu into setup.ps1: granite default, legacy mpnet as an explicit option, and both engine flows updated. Windows users were otherwise stranded on mpnet with no granite path. - Drop the unused EmbeddingsWrapper.tokenizer property.
This commit is contained in:
1 parent
25e07f5cee
commit
de22be5a21
16 files changed
+707
-54
No files matched your search
+11
-3
@@ -63,9 +63,6 @@ RUN groupadd -r appuser && \
|
||||
# Copy the virtual environment and model from the builder stage
|
||||
COPY --from=builder /venv /venv
|
||||
|
||||
# Copy your application code
|
||||
COPY . /app/application
|
||||
|
||||
# Pre-fetch the embedding models into FastEmbed's cache so a fresh container
|
||||
# does not download on first ingest and an air-gapped install works at all.
|
||||
# Both defaults are baked: an upgraded deployment keeps using mpnet until it
|
||||
@@ -76,9 +73,20 @@ COPY . /app/application
|
||||
# over the network on first ingest -- and fall back to cl100k when offline.
|
||||
ENV EMBEDDINGS_CACHE_DIR=/app/models \
|
||||
HF_HUB_CACHE=/app/models
|
||||
|
||||
# Only the modules the prefetch imports are copied first. It reaches nothing
|
||||
# beyond model_registry, which is stdlib-only, so keeping the full source copy
|
||||
# below this layer stops an unrelated edit from re-downloading ~780 MB of model
|
||||
# artifacts on every build.
|
||||
COPY __init__.py /app/application/__init__.py
|
||||
COPY scripts/__init__.py scripts/prefetch_models.py /app/application/scripts/
|
||||
COPY vectorstore/__init__.py vectorstore/model_registry.py /app/application/vectorstore/
|
||||
ARG EMBEDDINGS_PREFETCH=""
|
||||
RUN PYTHONPATH=/app /venv/bin/python -m application.scripts.prefetch_models ${EMBEDDINGS_PREFETCH}
|
||||
|
||||
# Copy your application code
|
||||
COPY . /app/application
|
||||
|
||||
# Change the ownership of the /app directory to the appuser
|
||||
|
||||
RUN mkdir -p /app/application/inputs/local
|
||||
|
||||
@@ -7,6 +7,13 @@ from application.parser.tokenization import get_token_counter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Smallest share of ``max_tokens`` a chunk must keep for body text when the
|
||||
# header is duplicated onto every chunk. A header that leaves less than this
|
||||
# makes each chunk mostly repeated header and multiplies the chunk count -- at
|
||||
# a budget of 32 out of 1250 a document splits into 39x more chunks than it
|
||||
# needs -- so duplication is dropped rather than honoured.
|
||||
_MIN_BODY_BUDGET_RATIO = 0.25
|
||||
|
||||
|
||||
class Chunker:
|
||||
"""Classic token-window chunker (registered as ``classic_chunk``).
|
||||
@@ -24,7 +31,9 @@ class Chunker:
|
||||
duplicate_headers: bool = False,
|
||||
):
|
||||
self.chunking_strategy = chunking_strategy
|
||||
self.max_tokens = max_tokens
|
||||
# A budget below 1 would ask for a chunk per token; the strategy
|
||||
# chunkers clamp the same way.
|
||||
self.max_tokens = max(1, int(max_tokens))
|
||||
self.min_tokens = min_tokens
|
||||
self.duplicate_headers = duplicate_headers
|
||||
# Counted in the embedding model's tokenizer, not cl100k: ``max_tokens``
|
||||
@@ -55,18 +64,51 @@ class Chunker:
|
||||
header, body = self.separate_header_and_body(doc.text)
|
||||
header_tokens = self.counter.count(header) if header else 0
|
||||
|
||||
if header and header_tokens >= self.max_tokens:
|
||||
# The header alone fills the budget, so no cut of the body can keep
|
||||
# a chunk within it and duplicating it would leave a one-token body
|
||||
# budget -- a chunk per body token. It is only the first three
|
||||
# lines, not something worth preserving at that cost, so it goes
|
||||
# back to being ordinary text and the document splits evenly.
|
||||
logger.warning(
|
||||
"Header of %s is %d token(s), at or over the %d-token chunk "
|
||||
"budget; treating it as body text.",
|
||||
doc.doc_id,
|
||||
header_tokens,
|
||||
self.max_tokens,
|
||||
)
|
||||
body = f"{header}{body}"
|
||||
header, header_tokens = "", 0
|
||||
|
||||
# A chunk carrying the header has that much less room for body text.
|
||||
with_header_budget = max(1, self.max_tokens - header_tokens)
|
||||
if self.duplicate_headers:
|
||||
duplicate_headers = self.duplicate_headers
|
||||
if duplicate_headers and with_header_budget < self.max_tokens * _MIN_BODY_BUDGET_RATIO:
|
||||
logger.warning(
|
||||
"Header of %s leaves only %d of %d tokens for body text; "
|
||||
"carrying it on the first chunk only.",
|
||||
doc.doc_id,
|
||||
with_header_budget,
|
||||
self.max_tokens,
|
||||
)
|
||||
duplicate_headers = False
|
||||
|
||||
if duplicate_headers:
|
||||
body_pieces = self.counter.split(body, with_header_budget)
|
||||
else:
|
||||
body_pieces = self.counter.split(
|
||||
body, self.max_tokens, first_max_tokens=with_header_budget
|
||||
)
|
||||
|
||||
if not body_pieces and header:
|
||||
# Nothing but a header: the loop below only ever emits the header
|
||||
# attached to a body piece, so without this the document is dropped
|
||||
# from the index entirely.
|
||||
body_pieces = [""]
|
||||
|
||||
split_docs = []
|
||||
for part_index, piece in enumerate(body_pieces):
|
||||
include_header = bool(header) and (self.duplicate_headers or part_index == 0)
|
||||
include_header = bool(header) and (duplicate_headers or part_index == 0)
|
||||
chunk_text = f"{header}{piece}" if include_header else piece
|
||||
split_docs.append(
|
||||
Document(
|
||||
|
||||
@@ -135,10 +135,34 @@ class TiktokenCounter(TokenCounter):
|
||||
tokens = self._encoding.encode_ordinary(text)
|
||||
if len(tokens) <= first:
|
||||
return [text]
|
||||
return [
|
||||
self._encoding.decode(tokens[start:end])
|
||||
for start, end in _windows(len(tokens), first, rest)
|
||||
]
|
||||
|
||||
# Cut the original string at the character offsets the tokenizer
|
||||
# reports, the way :class:`HuggingFaceCounter` does. Decoding each
|
||||
# window on its own instead splits any multi-byte character that
|
||||
# straddles a boundary across two byte sequences, and each half decodes
|
||||
# to U+FFFD -- roughly one boundary in five on CJK text, silently
|
||||
# destroying a character per cut.
|
||||
offsets = self._encoding.decode_with_offsets(tokens)[1]
|
||||
end_of_text = len(text)
|
||||
pieces: List[str] = []
|
||||
cursor = 0
|
||||
for _, end in _windows(len(tokens), first, rest):
|
||||
# Offsets index into the decoded string. ``encode_ordinary``
|
||||
# round-trips for anything cl100k can represent, so it is ``text``;
|
||||
# clamping keeps the cuts in range if it ever is not, and slicing
|
||||
# ``text`` monotonically keeps the pieces reassembling exactly
|
||||
# either way.
|
||||
end_char = end_of_text if end >= len(offsets) else min(offsets[end], end_of_text)
|
||||
if end_char <= cursor:
|
||||
continue
|
||||
pieces.append(text[cursor:end_char])
|
||||
cursor = end_char
|
||||
if cursor < end_of_text:
|
||||
if pieces:
|
||||
pieces[-1] = pieces[-1] + text[cursor:]
|
||||
else:
|
||||
pieces.append(text[cursor:])
|
||||
return pieces
|
||||
|
||||
|
||||
class HuggingFaceCounter(TokenCounter):
|
||||
|
||||
+120
-28
@@ -8,7 +8,9 @@ answers rather than as an error.
|
||||
|
||||
This script rebuilds the vectors from the chunk text already held in the store,
|
||||
so it never re-downloads, re-parses or re-chunks anything: no source files, no
|
||||
crawl, no docling. It works against pgvector and FAISS.
|
||||
crawl, no docling. It works against pgvector and FAISS. With ``GRAPHRAG_ENABLED``
|
||||
it also rewrites ``graph_nodes.name_embedding``, which seeds graph traversal and
|
||||
would otherwise be left behind in the previous model's space.
|
||||
|
||||
Usage::
|
||||
|
||||
@@ -122,6 +124,79 @@ def _faiss_source_ids() -> List[str]:
|
||||
return sorted(set(ids))
|
||||
|
||||
|
||||
def _graph_nodes_exist(conn) -> bool:
|
||||
"""True when the GraphRAG node table is present in this database."""
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute("SELECT to_regclass('public.graph_nodes')")
|
||||
row = cursor.fetchone()
|
||||
return bool(row and row[0])
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
|
||||
def reembed_graph_nodes(store, conn, source_id: str, batch_size: int, dry_run: bool) -> int:
|
||||
"""Rewrite one source's GraphRAG node name vectors.
|
||||
|
||||
``graph_nodes.name_embedding`` is what every graph traversal starts from:
|
||||
the retriever embeds the query and takes the nearest node names as seeds.
|
||||
It is written once at extraction time and never revisited, so re-embedding
|
||||
only the chunk table leaves the graph seeding against the previous model.
|
||||
Nothing errors -- mpnet and granite-311m are both 768-dimensional, so the
|
||||
column accepts the mismatch -- the graph just walks from the wrong nodes.
|
||||
|
||||
The embedded text is ``graph_nodes.name``, which is already stored, so this
|
||||
needs no LLM re-extraction.
|
||||
|
||||
Args:
|
||||
store: The pgvector store, for its embeddings client.
|
||||
conn: Open connection to the same database.
|
||||
source_id: Source whose nodes to re-embed.
|
||||
batch_size: Names per embed call and per transaction.
|
||||
dry_run: When true, count the work and change nothing.
|
||||
|
||||
Returns:
|
||||
Number of node rows seen (dry run) or rewritten.
|
||||
"""
|
||||
if not _graph_nodes_exist(conn):
|
||||
return 0
|
||||
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT id, name FROM graph_nodes "
|
||||
"WHERE source_id = %s AND name_embedding IS NOT NULL ORDER BY id",
|
||||
(source_id,),
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
if dry_run or not rows:
|
||||
return len(rows)
|
||||
|
||||
written = 0
|
||||
for batch in _batched(rows, batch_size):
|
||||
vectors = store._embedding.embed_documents([row[1] or "" for row in batch])
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.executemany(
|
||||
"UPDATE graph_nodes SET name_embedding = %s::vector WHERE id = %s",
|
||||
[
|
||||
(str(list(vector)), row[0])
|
||||
for vector, row in zip(vectors, batch)
|
||||
],
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
cursor.close()
|
||||
written += len(batch)
|
||||
return written
|
||||
|
||||
|
||||
def reembed_pgvector(source_id: str, batch_size: int, dry_run: bool) -> Tuple[int, int]:
|
||||
"""Rewrite one source's vectors in place.
|
||||
|
||||
@@ -152,35 +227,45 @@ def reembed_pgvector(source_id: str, batch_size: int, dry_run: bool) -> Tuple[in
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
if dry_run or not rows:
|
||||
store.close()
|
||||
return len(rows), 0
|
||||
|
||||
written = 0
|
||||
try:
|
||||
for batch in _batched(rows, batch_size):
|
||||
vectors = store._embedding.embed_documents([row[1] or "" for row in batch])
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.executemany(
|
||||
sql.SQL(
|
||||
"UPDATE {table} SET {column} = %s::vector WHERE id = %s"
|
||||
).format(
|
||||
table=sql.Identifier(table),
|
||||
column=sql.Identifier(vector_column),
|
||||
),
|
||||
[
|
||||
(str(list(vector)), row[0])
|
||||
for vector, row in zip(vectors, batch)
|
||||
],
|
||||
if not dry_run:
|
||||
for batch in _batched(rows, batch_size):
|
||||
vectors = store._embedding.embed_documents([row[1] or "" for row in batch])
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.executemany(
|
||||
sql.SQL(
|
||||
"UPDATE {table} SET {column} = %s::vector WHERE id = %s"
|
||||
).format(
|
||||
table=sql.Identifier(table),
|
||||
column=sql.Identifier(vector_column),
|
||||
),
|
||||
[
|
||||
(str(list(vector)), row[0])
|
||||
for vector, row in zip(vectors, batch)
|
||||
],
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
cursor.close()
|
||||
written += len(batch)
|
||||
|
||||
# The graph seeds every traversal from its own vectors, so leaving them
|
||||
# in the old model's space is the same silent mismatch this script
|
||||
# exists to remove -- and at equal widths nothing would report it.
|
||||
if getattr(settings, "GRAPHRAG_ENABLED", False):
|
||||
nodes = reembed_graph_nodes(store, conn, source_id, batch_size, dry_run)
|
||||
if nodes:
|
||||
logger.info(
|
||||
" %s: %d graph node name(s)%s",
|
||||
source_id,
|
||||
nodes,
|
||||
"" if dry_run else " re-embedded",
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
cursor.close()
|
||||
written += len(batch)
|
||||
finally:
|
||||
store.close()
|
||||
return len(rows), written
|
||||
@@ -201,8 +286,15 @@ def reembed_faiss(source_id: str, batch_size: int, dry_run: bool) -> Tuple[int,
|
||||
Returns:
|
||||
``(chunks_seen, chunks_written)``.
|
||||
"""
|
||||
# A width change is the main reason to run this, and it is exactly what
|
||||
# ``assert_embedding_dimensions`` refuses to open. The chunk text lives in
|
||||
# the sidecar rather than the index, so reading it needs no matching width,
|
||||
# and the index this reads is replaced below.
|
||||
store = VectorCreator.create_vectorstore(
|
||||
"faiss", source_id=source_id, embeddings_key=settings.EMBEDDINGS_KEY
|
||||
"faiss",
|
||||
source_id=source_id,
|
||||
embeddings_key=settings.EMBEDDINGS_KEY,
|
||||
skip_dimension_check=True,
|
||||
)
|
||||
chunks: List[Dict[str, Any]] = store.get_chunks() or []
|
||||
if dry_run or not chunks:
|
||||
|
||||
@@ -14,8 +14,21 @@ from application.vectorstore.model_registry import (
|
||||
|
||||
|
||||
def _embeddings_name_is_explicit() -> bool:
|
||||
"""True when ``EMBEDDINGS_NAME`` was configured rather than defaulted."""
|
||||
return "EMBEDDINGS_NAME" in getattr(settings, "model_fields_set", set())
|
||||
"""True when ``EMBEDDINGS_NAME`` names a model somebody actually chose.
|
||||
|
||||
Not ``model_fields_set``: pydantic marks a field as set for any value that
|
||||
reached it, including one read from ``.env``, and every setup script has
|
||||
always written ``EMBEDDINGS_NAME`` unconditionally. An install carrying the
|
||||
legacy name a script wrote years ago would read as a deliberate choice and
|
||||
lend a remote server that model's context window.
|
||||
"""
|
||||
fields = getattr(type(settings), "model_fields", None)
|
||||
if not isinstance(fields, dict):
|
||||
return False
|
||||
field = fields.get("EMBEDDINGS_NAME")
|
||||
if field is None:
|
||||
return False
|
||||
return settings.EMBEDDINGS_NAME != field.default
|
||||
|
||||
|
||||
class RemoteEmbeddings:
|
||||
|
||||
@@ -44,6 +44,17 @@ def _pooling_type(pooling: str):
|
||||
return {"cls": PoolingType.CLS, "mean": PoolingType.MEAN}[pooling]
|
||||
|
||||
|
||||
def _is_builtin(repo: str) -> bool:
|
||||
"""True when FastEmbed already ships a description for ``repo``."""
|
||||
from fastembed import TextEmbedding
|
||||
|
||||
lowered = repo.lower()
|
||||
return any(
|
||||
str(entry.get("model", "")).lower() == lowered
|
||||
for entry in TextEmbedding.list_supported_models()
|
||||
)
|
||||
|
||||
|
||||
def _register(model: EmbeddingModel) -> None:
|
||||
"""Teach FastEmbed about a model, exactly once per process."""
|
||||
from fastembed import TextEmbedding
|
||||
@@ -52,6 +63,14 @@ def _register(model: EmbeddingModel) -> None:
|
||||
with _register_lock:
|
||||
if model.repo in _registered:
|
||||
return
|
||||
if _is_builtin(model.repo):
|
||||
# ``add_custom_model`` refuses a name FastEmbed already ships, and
|
||||
# its own description carries the pooling, width and graph file we
|
||||
# would be supplying, so there is nothing to add. Without this,
|
||||
# configuring any of FastEmbed's ~30 built-in models (bge, e5,
|
||||
# MiniLM, gte, ...) fails every embed call.
|
||||
_registered.add(model.repo)
|
||||
return
|
||||
TextEmbedding.add_custom_model(
|
||||
model=model.repo,
|
||||
pooling=_pooling_type(model.pooling),
|
||||
@@ -162,11 +181,6 @@ class EmbeddingsWrapper:
|
||||
"""Determine the vector width of a model the registry does not describe."""
|
||||
return len(self.embed_query("dimension probe"))
|
||||
|
||||
@property
|
||||
def tokenizer(self):
|
||||
"""The model's own tokenizer, so chunking can count in its units."""
|
||||
return self.model.model.tokenizer
|
||||
|
||||
def embed_query(self, query: str) -> List[float]:
|
||||
"""Embed a single query string."""
|
||||
return self.embed_documents([query])[0]
|
||||
|
||||
@@ -88,7 +88,22 @@ class FaissStore(BaseVectorStore):
|
||||
docs_init=None,
|
||||
ids=None,
|
||||
batch_size=None,
|
||||
skip_dimension_check: bool = False,
|
||||
):
|
||||
"""Open or build one source's FAISS index.
|
||||
|
||||
Args:
|
||||
source_id: Source whose index to open.
|
||||
embeddings_key: API key handed to the embeddings provider.
|
||||
docs_init: Documents to build a fresh index from. Loads the stored
|
||||
index instead when omitted.
|
||||
ids: Chunk ids to keep when building. Generated when omitted.
|
||||
batch_size: Documents per embed call when building.
|
||||
skip_dimension_check: Open an index whose width does not match the
|
||||
configured model. Only for a caller that is about to replace
|
||||
that index, such as the re-embed script, which otherwise cannot
|
||||
read the chunks it needs to rebuild from.
|
||||
"""
|
||||
super().__init__()
|
||||
self.source_id = source_id
|
||||
self.path = get_vectorstore(source_id)
|
||||
@@ -107,7 +122,8 @@ class FaissStore(BaseVectorStore):
|
||||
except Exception as e:
|
||||
raise Exception(f"Error loading FAISS index: {str(e)}")
|
||||
|
||||
self.assert_embedding_dimensions(self.embeddings)
|
||||
if not skip_dimension_check:
|
||||
self.assert_embedding_dimensions(self.embeddings)
|
||||
|
||||
# -- Construction ----------------------------------------------------
|
||||
|
||||
|
||||
Reference in new issue
Block a user