How to beginner · 3 min read

How to save and load FAISS index

Quick answer
Use FAISS's write_index method to save an index to disk and read_index to load it back into memory. This preserves your vector search index for reuse without rebuilding it every time.

PREREQUISITES

  • Python 3.8+
  • pip install faiss-cpu
  • Basic knowledge of vector search and FAISS

Setup

Install the FAISS library using pip if you haven't already. This example uses the CPU version, which works on most systems.

bash
pip install faiss-cpu

Step by step

This example creates a FAISS index, adds vectors, saves it to disk, then loads it back and performs a search.

python
import numpy as np
import faiss

# Create a FAISS index for 128-dimensional vectors
index = faiss.IndexFlatL2(128)

# Generate some random vectors
vectors = np.random.random((1000, 128)).astype('float32')

# Add vectors to the index
index.add(vectors)

# Save the index to disk
faiss.write_index(index, 'faiss.index')

# Load the index from disk
loaded_index = faiss.read_index('faiss.index')

# Search for the 5 nearest neighbors of a random query vector
query = np.random.random((1, 128)).astype('float32')
D, I = loaded_index.search(query, 5)
print('Distances:', D)
print('Indices:', I)
output
Distances: [[...]]
Indices: [[...]]

Common variations

You can save/load GPU indices by transferring them to CPU first. For persistent storage in cloud or databases, save the index file and upload/download as needed. Also, use IndexIVFFlat or other FAISS index types similarly.

python
import faiss

# For GPU index, transfer to CPU before saving
# gpu_index = faiss.index_cpu_to_gpu(res, 0, index)
# faiss.write_index(faiss.index_gpu_to_cpu(gpu_index), 'gpu_index.index')

# Load and transfer back to GPU if needed
# cpu_index = faiss.read_index('gpu_index.index')
# gpu_index = faiss.index_cpu_to_gpu(res, 0, cpu_index)

Troubleshooting

If you get errors loading the index, verify the file path and ensure the FAISS version used to save and load are compatible. Corrupted files or mismatched index types can cause failures.

Key Takeaways

  • Use faiss.write_index and faiss.read_index to persist FAISS indexes.
  • Always save CPU indices; convert GPU indices to CPU before saving.
  • Ensure FAISS versions match when saving and loading indexes to avoid compatibility issues.
Verified 2026-04
Verify ↗