Harrison/save faiss (#916)

Co-authored-by: Shrey Joshi <shreyjoshi2004@gmail.com>
makefile-update-1
Harrison Chase 1 year ago committed by GitHub
parent 6bd1529cb7
commit 1e56879d38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -16,7 +16,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 1,
"id": "965eecee",
"metadata": {
"pycharm": {
@ -32,7 +32,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 2,
"id": "68481687",
"metadata": {
"pycharm": {
@ -51,7 +51,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 3,
"id": "015f4ff5",
"metadata": {
"pycharm": {
@ -210,39 +210,27 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 4,
"id": "b58b3955",
"metadata": {},
"outputs": [],
"source": [
"import pickle"
"docsearch.save_local(\"faiss_index\")"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "1897e23d",
"metadata": {},
"outputs": [],
"source": [
"with open(\"foo.pkl\", 'wb') as f:\n",
" pickle.dump(docsearch, f)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "bf3732f1",
"execution_count": 5,
"id": "ca72c650",
"metadata": {},
"outputs": [],
"source": [
"with open(\"foo.pkl\", 'rb') as f:\n",
" new_docsearch = pickle.load(f)"
"new_docsearch = FAISS.load_local(\"faiss_index\", embeddings)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 6,
"id": "5bf2ee24",
"metadata": {},
"outputs": [],
@ -252,7 +240,7 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 7,
"id": "edc2aad1",
"metadata": {},
"outputs": [
@ -262,7 +250,7 @@
"Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while youre at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, Id like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nations top legal minds, who will continue Justice Breyers legacy of excellence.', lookup_str='', metadata={}, lookup_index=0)"
]
},
"execution_count": 18,
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}

@ -1,7 +1,9 @@
"""Wrapper around FAISS vector database."""
from __future__ import annotations
import pickle
import uuid
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
@ -201,20 +203,39 @@ class FAISS(VectorStore):
)
return cls(embedding.embed_query, index, docstore, index_to_id)
def save_local(self, path: str) -> None:
"""Save FAISS index to disk.
def save_local(self, folder_path: str) -> None:
"""Save FAISS index, docstore, and index_to_docstore_id to disk.
Args:
path: Path to save FAISS index to.
folder_path: folder path to save index, docstore,
and index_to_docstore_id to.
"""
path = Path(folder_path)
path.mkdir(exist_ok=True, parents=True)
# save index separately since it is not picklable
faiss = dependable_faiss_import()
faiss.write_index(self.index, path)
faiss.write_index(self.index, str(path / "index.faiss"))
# save docstore and index_to_docstore_id
with open(path / "index.pkl", "wb") as f:
pickle.dump((self.docstore, self.index_to_docstore_id), f)
def load_local(self, path: str) -> None:
"""Load FAISS index from disk.
@classmethod
def load_local(cls, folder_path: str, embeddings: Embeddings) -> FAISS:
"""Load FAISS index, docstore, and index_to_docstore_id to disk.
Args:
path: Path to load FAISS index from.
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries
"""
path = Path(folder_path)
# load index separately since it is not picklable
faiss = dependable_faiss_import()
self.index = faiss.read_index(path)
index = faiss.read_index(str(path / "index.faiss"))
# load docstore and index_to_docstore_id
with open(path / "index.pkl", "rb") as f:
docstore, index_to_docstore_id = pickle.load(f)
return cls(embeddings.embed_query, index, docstore, index_to_docstore_id)

@ -85,6 +85,5 @@ def test_faiss_local_save_load() -> None:
with tempfile.NamedTemporaryFile() as temp_file:
docsearch.save_local(temp_file.name)
docsearch.index = None
docsearch.load_local(temp_file.name)
assert docsearch.index is not None
new_docsearch = FAISS.load_local(temp_file.name, FakeEmbeddings())
assert new_docsearch.index is not None

Loading…
Cancel
Save