From a2d3625f2a624b2a2e374753d45e0f7195297376 Mon Sep 17 00:00:00 2001 From: jze9 Date: Tue, 11 Aug 2026 16:57:03 +0500 Subject: [PATCH] =?UTF-8?q?refactor(gpu):=20=D1=83=D0=B1=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BC=D1=91=D1=80=D1=82=D0=B2=D1=8B=D0=B9=20=5Frevers?= =?UTF-8?q?e=5Fmap/=5Fuse=5Fgpu=20=D0=B8=D0=B7=20FAISSManager?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _reverse_map был identity-map (faiss_id == doc_id для IndexIDMap2) — использовался только как doc.faiss_id = _reverse_map[doc_id], т.е. = doc_id. Убрал поле, метод _rebuild_reverse_map и его обслуживание в 5 местах; _use_gpu нигде не читался. -30 строк, функционал тот же. Co-Authored-By: Claude Opus 4.8 --- services/worker-gpu/app/faiss_manager.py | 42 ++------------------- services/worker-gpu/app/tasks/plagiarism.py | 6 +-- 2 files changed, 7 insertions(+), 41 deletions(-) diff --git a/services/worker-gpu/app/faiss_manager.py b/services/worker-gpu/app/faiss_manager.py index 90356bd..7500b02 100644 --- a/services/worker-gpu/app/faiss_manager.py +++ b/services/worker-gpu/app/faiss_manager.py @@ -27,10 +27,6 @@ class FAISSManager: """Singleton для управления FAISS индексом (IndexIDMap2 поверх IndexFlatIP).""" _index = None - # doc_id -> faiss_id. Для IDMap2 faiss_id == doc_id, но маппинг сохраняем - # для совместимости с вызывающим кодом (plagiarism.embed_documents). - _reverse_map: dict[int, int] = {} - _use_gpu: bool = False @classmethod def _new_index(cls): @@ -51,34 +47,19 @@ class FAISSManager: import faiss index_path = settings.FAISS_INDEX_PATH - if os.path.exists(index_path): try: loaded = faiss.read_index(index_path) if hasattr(loaded, "id_map"): cls._index = loaded - cls._rebuild_reverse_map() - logger.info( - f"Загрузка FAISS индекса из {index_path} " - f"({cls._index.ntotal} векторов)" - ) - else: - logger.warning( - "На диске несовместимый FAISS индекс (без id_map) — " - "пересоздаём как IndexIDMap2(IndexFlatIP)" - ) - cls._index = cls._new_index() - cls._reverse_map = {} + logger.info(f"Загрузка FAISS индекса из {index_path} ({loaded.ntotal} векторов)") + return + logger.warning("На диске несовместимый FAISS индекс (без id_map) — пересоздаём") except Exception as e: logger.warning(f"Не удалось загрузить FAISS индекс ({e}) — создаём новый") - cls._index = cls._new_index() - cls._reverse_map = {} else: logger.info("Создание нового FAISS индекса IndexIDMap2(IndexFlatIP)...") - cls._index = cls._new_index() - cls._reverse_map = {} - - cls._use_gpu = False # FlatIP на CPU достаточно быстр для целевого масштаба + cls._index = cls._new_index() @classmethod def _ensure(cls) -> None: @@ -86,18 +67,6 @@ class FAISSManager: if cls._index is None: cls.load_or_create() - @classmethod - def _rebuild_reverse_map(cls) -> None: - """Восстановить _reverse_map из id, хранящихся внутри загруженного индекса.""" - import faiss - - try: - ids = faiss.vector_to_array(cls._index.id_map) - cls._reverse_map = {int(i): int(i) for i in ids} - except Exception as e: - logger.warning(f"Не удалось восстановить reverse_map из индекса: {e}") - cls._reverse_map = {} - @classmethod def search(cls, query_vector: np.ndarray, k: int = 20) -> list[tuple[int, float]]: """Поиск k ближайших векторов. @@ -157,9 +126,6 @@ class FAISSManager: pass cls._index.add_with_ids(vectors, ids) - for doc_id in doc_ids: - cls._reverse_map[int(doc_id)] = int(doc_id) - logger.info(f"Добавлено {len(doc_ids)} векторов в FAISS. Всего: {cls._index.ntotal}") @classmethod diff --git a/services/worker-gpu/app/tasks/plagiarism.py b/services/worker-gpu/app/tasks/plagiarism.py index 75dd1fe..199918d 100644 --- a/services/worker-gpu/app/tasks/plagiarism.py +++ b/services/worker-gpu/app/tasks/plagiarism.py @@ -254,12 +254,12 @@ def embed_documents(doc_ids: list[int]) -> dict[str, Any]: FAISSManager.add_vectors(vectors, ids) FAISSManager.save() - # Обновить faiss_id в PostgreSQL + # Обновить faiss_id в PostgreSQL (для IDMap2 faiss_id == doc_id) with db_session() as session: for doc_id in ids: doc = session.get(Document, doc_id) - if doc and doc_id in FAISSManager._reverse_map: - doc.faiss_id = FAISSManager._reverse_map[doc_id] + if doc: + doc.faiss_id = doc_id session.commit() logger.info(f"Встроено и проиндексировано {len(ids)} документов")