mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-13 12:14:00 +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
+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:
|
||||
|
||||
Reference in new issue
Block a user