Spaces:
Build error
Build error
File size: 10,256 Bytes
09feb6f 4ab183b 09feb6f 25bc88e 09feb6f 25bc88e 09feb6f 3560dd8 09feb6f 3560dd8 09feb6f 4ab183b 09feb6f 3560dd8 09feb6f 3560dd8 09feb6f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Migrate the RAG corpus to a different embedding model.
Embeddings are only comparable to other embeddings from the SAME model, so
changing models means re-embedding everything. There is no partial state worth
having: a corpus half in one vector space and half in another returns
confident nonsense with no error anywhere.
What this does, in order:
1. Verify the configured remote model really returns EMBED_DIMENSIONS.
2. Drop the HNSW indexes (ALTER TYPE cannot rewrite an indexed vector column).
3. ALTER every *.embedding column to the new width, clearing old vectors.
4. Re-embed every chunk through the configured provider.
5. Rebuild the HNSW indexes.
6. Report anything left unembedded.
Run with --dry-run first. Documents whose chunks cannot be re-embedded are
left with NULL vectors and reported; they are invisible to retrieval until
re-ingested, which is the honest outcome β better than a silently half-indexed
corpus.
python app_tools/migrate_embedding_model.py --dry-run
python app_tools/migrate_embedding_model.py --apply
"""
from __future__ import annotations
import argparse
import asyncio
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import httpx
from sqlalchemy import text as sql
from app.config import get_settings
from app.database import get_rag_session, init_db
from app.services.embed import EmbedService
logging.basicConfig(level=logging.INFO, format="%(levelname)-7s %(message)s")
logger = logging.getLogger("migrate")
# Every table holding vectors that must move together.
# rag_topics carries topic embeddings β it must move with the others, or topic
# lookup silently compares vectors from two different models.
VECTOR_TABLES = ("rag_chunks", "element_embeddings", "rag_topics")
# (index name, table, column) β dropped before the ALTER, rebuilt after.
HNSW_INDEXES = (
("idx_rag_chunks_hnsw", "rag_chunks", "embedding"),
("idx_element_embeddings_hnsw", "element_embeddings", "embedding"),
)
async def verify_provider(settings) -> int:
"""Confirm the configured model returns the width we are about to commit to."""
svc = EmbedService()
async with httpx.AsyncClient(timeout=60) as client:
result = (await svc._embed_remote_batch(["ΩΨΨ΅ Ψ§ΩΨ£Ψ¨ΨΉΨ§Ψ―"], client=client))[0]
dims = len(result.embedding)
logger.info("Provider %s returned %d dims", settings.EMBED_REMOTE_MODEL, dims)
if dims != settings.EMBED_DIMENSIONS:
raise SystemExit(
f"ABORT: provider returns {dims} dims but EMBED_DIMENSIONS is "
f"{settings.EMBED_DIMENSIONS}. Fix the config before migrating."
)
return dims
async def current_state(session) -> None:
rows = (await session.execute(sql("""
SELECT c.relname, a.atttypmod
FROM pg_attribute a
JOIN pg_class c ON c.oid = a.attrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname='public' AND a.attname='embedding'
AND c.relkind='r' AND a.attnum > 0
"""))).fetchall()
for r in rows:
logger.info(" %-22s vector(%s)", r[0], r[1])
for table in VECTOR_TABLES:
n = (await session.execute(sql(f"SELECT count(*) FROM {table}"))).scalar()
logger.info(" %-22s %d rows", table, n)
async def migrate(dims: int, apply: bool) -> None:
settings = get_settings()
await init_db()
async with get_rag_session() as session:
logger.info("Current state:")
await current_state(session)
if not apply:
logger.info("DRY RUN β nothing changed. Re-run with --apply.")
return
logger.info("Dropping HNSW indexes β¦")
for name, _table, _col in HNSW_INDEXES:
await session.execute(sql(f"DROP INDEX IF EXISTS {name}"))
logger.info("Altering vector columns to vector(%d) β¦", dims)
for table in VECTOR_TABLES:
# Old vectors are unusable in the new space; clearing them first
# makes the ALTER cheap and the "not yet re-embedded" state explicit.
await session.execute(sql(f"UPDATE {table} SET embedding = NULL"))
await session.execute(sql(
f"ALTER TABLE {table} ALTER COLUMN embedding TYPE vector({dims})"
))
await session.commit()
logger.info("Columns migrated.")
# ββ Re-embed ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
svc = EmbedService()
async with httpx.AsyncClient(timeout=settings.EMBED_REMOTE_TIMEOUT * 2) as client:
async with get_rag_session() as session:
rows = (await session.execute(sql(
"SELECT id, content FROM rag_chunks "
"WHERE embedding IS NULL AND content <> '' ORDER BY document_id, chunk_index"
))).fetchall()
logger.info("Re-embedding %d chunks β¦", len(rows))
done = failed = 0
# Taken from the results themselves rather than config, so the
# stored label always names the weights that produced the vectors.
model_name = settings.EMBED_REMOTE_MODEL
batch = svc._batch_max_items
for start in range(0, len(rows), batch):
window = rows[start:start + batch]
results = await svc.embed_batch([r.content for r in window], client=client)
for row, res in zip(window, results):
if res is None:
failed += 1
continue
model_name = res.model # ground truth, not configuration
await session.execute(
sql("UPDATE rag_chunks SET embedding = CAST(:v AS vector) WHERE id = :id"),
{"v": EmbedService.to_vector_literal(res.embedding), "id": row.id},
)
done += 1
await session.commit()
logger.info(" %d/%d", min(start + batch, len(rows)), len(rows))
# Topics are few (~100 per document) but must move in the same pass:
# a topic embedded under the old model would be compared against
# chunks embedded under the new one, which returns confident
# nonsense rather than an error.
topic_rows = (await session.execute(sql(
"SELECT id, title, summary FROM rag_topics WHERE embedding IS NULL"
))).fetchall()
if topic_rows:
logger.info("Re-embedding %d topics β¦", len(topic_rows))
texts = [
f"{r.title} β {r.summary}" if r.summary else r.title
for r in topic_rows
]
results = await svc.embed_batch(texts, client=client)
for row, res in zip(topic_rows, results):
if res is None:
failed += 1
continue
await session.execute(
sql("UPDATE rag_topics SET embedding = CAST(:v AS vector), "
"embedding_model = :m WHERE id = :id"),
{"v": EmbedService.to_vector_literal(res.embedding),
"m": res.model, "id": row.id},
)
done += 1
await session.commit()
async with get_rag_session() as session:
logger.info("Rebuilding HNSW indexes β¦")
for name, table, col in HNSW_INDEXES:
await session.execute(sql(
f"CREATE INDEX IF NOT EXISTS {name} ON {table} "
f"USING hnsw ({col} vector_cosine_ops)"
))
# Re-label the documents. Leaving rag_documents.embedding_model on the
# OLD model after re-embedding is worse than leaving it blank: that
# column is exactly what you consult to decide whether a document needs
# migrating, so a stale value makes an already-migrated corpus look
# unmigrated (and vice versa). Only documents that actually have
# vectors are relabelled β anything left stranded keeps its old label
# so it still reads as needing attention.
relabelled = (await session.execute(sql("""
UPDATE rag_documents SET embedding_model = :model
WHERE id IN (
SELECT DISTINCT document_id FROM rag_chunks WHERE embedding IS NOT NULL
)
"""), {"model": model_name})).rowcount
await session.commit()
logger.info("Re-labelled %d documents as embedded with %s", relabelled, model_name)
stranded = (await session.execute(sql(
"SELECT count(*) FROM rag_chunks WHERE embedding IS NULL AND content <> ''"
))).scalar()
logger.info("Re-embedded %d chunks, %d failed.", done, failed)
if stranded:
logger.error(
"%d chunks still have no vector β they are invisible to retrieval. "
"Re-ingest those documents.", stranded,
)
else:
logger.info("Every chunk has a vector. Migration complete.")
logger.info(
"NOTE: element_embeddings were cleared but are NOT re-embedded here β "
"they are regenerated by the document-graph stage on re-ingest."
)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--apply", action="store_true", help="actually perform the migration")
ap.add_argument("--dry-run", action="store_true", help="show current state only")
args = ap.parse_args()
if not args.apply and not args.dry_run:
ap.error("pass --dry-run or --apply")
settings = get_settings()
logger.info("Target model : %s", settings.EMBED_REMOTE_MODEL)
logger.info("Target dims : %d", settings.EMBED_DIMENSIONS)
logger.info("Local backend: %s", "enabled" if settings.EMBED_LOCAL_ENABLED else "DISABLED (cloud-only)")
dims = asyncio.run(verify_provider(settings))
asyncio.run(migrate(dims, apply=args.apply))
if __name__ == "__main__":
main()
|