To incorporate FAISS (Facebook AI Similarity Search) for the similarity search steps after the initial embedding, you need to adjust the approach. The initial text embedding would be performed using your retrieval model as before. For subsequent steps, where earlier we were re-encoding texts and computing similarities directly, you would use FAISS to efficiently search for the nearest neighbors.
FAISS is particularly suited for large-scale similarity searches and can significantly speed up the retrieval process, especially for high-dimensional vectors.
First, ensure you have FAISS installed:
pip install faiss-cpu # or faiss-gpu for GPU version
Here's how you could adjust the function to use FAISS for the similarity search after the initial embedding:
import numpy as np
import faiss
import pandas as pd
def setup_faiss_index(embeddings):
"""
Setup the FAISS index for given embeddings.
"""
dimension = embeddings.shape[1]
faiss_index = faiss.IndexFlatL2(dimension) # Using L2 distance for similarity
faiss_index.add(embeddings) # Adding the data to the index
return faiss_index
def get_most_similar_question_faiss(userText, history, new_df, retrieval_model):
print(userText)
# Step 1: Embed user text with the retrieval model
inp_emb = retrieval_model.encode([userText])
# For the sake of example, let's say data_emb has been populated with embeddings of your dataset
# data_emb is numpy array of shape (num_texts, embedding_dim)
# Initialize FAISS index with dataset embeddings
faiss_index = setup_faiss_index(data_emb)
# SEARCH PHASES
# Step 2: First refinement with FAISS - Get top 30
top_30_distances, top_30_indices = faiss_index.search(inp_emb, 30)
# Further refinement steps will use embeddings from previous steps,
# so we create FAISS indices for each step dynamically
# Note: This assumes embeddings are recalculated for narrowed down texts, which might not be needed with FAISS
# For this example, we simulate retrieving embeddings for top results in each step from 'data_emb'
# In practice, you might directly work with large precomputed embedding matrices or recalculate as needed
# Top 30
top_30_embeddings = data_emb[top_30_indices[0]]
faiss_index_top30 = setup_faiss_index(top_30_embeddings)
# Step 3: Narrow to top 20
top_20_distances, top_20_indices = faiss_index_top30.search(inp_emb, 20)
# Top 20
top_20_embeddings = top_30_embeddings[top_20_indices[0]]
faiss_index_top20 = setup_faiss_index(top_20_embeddings)
# Step 4: Narrow to top 10
top_10_distances, top_10_indices = faiss_index_top20.search(inp_emb, 10)
# Top 10
top_10_embeddings = top_20_embeddings[top_10_indices[0]]
faiss_index_top10 = setup_faiss_index(top_10_embeddings)
# Step 5: Narrow to top 5
top_5_distances, top_5_indices = faiss_index_top10.search(inp_emb, 5)
# Step 6: Determine the most similar
_, top_1_indices = faiss_index_top10.search(inp_emb, 1)
top_1_index = top_1_indices[0][0]
if top_5_distances[0][0] < 0.7: # Assuming a distance threshold, adjust according to your similarity metric
# If the most similar item is not similar enough, call predict
return predict(userText, history)
else:
# Find the corresponding original index and return as HTML
final_idx = top_30_indices[0][top_20_indices[0][top_10_indices[0][top_5_indices[0][top_1_index]]]]
n_data = new_df.iloc[[final_idx], [1]] # Assuming text is in column 1
df_html_with_sql = n_data.to_html(index=False)
return df_html_with_sql
Key Adjustments:
- Initial Encoding: Performed once using the retrieval model.
- FAISS Indexes: For each refinement step, a new FAISS index is set up with the embeddings of the currently considered subset. This mimics the narrowing down but uses efficient nearest neighbor search instead.
- Distance and Indices Retrieval:
faiss_index.search provides both distances (which we use as a similarity metric in this example) and the indices of the found neighbors. The distance check (if top_5_distances[0][0] < 0.7) is exemplary; adjust it based on your similarity metric and scale.
Note: The actual performance and efficiency gain need to be balanced with the overhead of setting up indices for very small sets of embeddings. For the smallest sets (like top 20 to top 5), the benefit over simple numpy operations might be negligible or even negative due to overhead. Additionally, the similarity threshold check is placed hypothetically and might need adjustments based on the specifics of your embeddings and similarity metric.