[Bug] FAISS retrieval can return the last corpus passage for a missing candidate
What happened?
When a FAISS search has fewer hits than the number of candidate slots requested, it fills the unused ID slots with -1. Embeddings currently treats those IDs as corpus positions during exact reranking. In Python and NumPy, -1 selects the last element, so a missing hit can turn into the last passage in the corpus. The passage may then be returned with index -1 and a score computed from that unrelated passage's embedding.
A caller of Embeddings.forward() can receive a passage that the index did not find. EmbeddingsWithScores shares the same reranking method, so its returned score and passage lists can contain that phantom candidate too.
Steps to reproduce
The controlled index below returns the same missing-ID shape as FAISS. Using it avoids training a large IVF index just to show what the retriever does with -1; the candidate handling and reranking are the real DSPy methods.
import numpy as np
from dspy.retrievers.embeddings import Embeddings
vectors = {"cat": [1, 0, 0], "dog": [0, 1, 0], "bird": [0, 0, 1]}
def embedder(texts):
return np.asarray([vectors[text] for text in texts], dtype=np.float32)
class Index:
def search(self, queries, count):
print("requested:", count)
return None, np.array([[0, -1, -1]])
retriever = Embeddings(["cat", "dog", "bird"], embedder, k=2)
retriever.index = Index()
print("result:", retriever._batch_forward(["cat"]))On main at 9c900c7:
requested: 20
result: [(['cat', 'bird'], [0, -1], [1.0, 0.0])]Only corpus ID 0 was supplied as a hit. bird appears solely because the missing ID -1 indexes the last corpus element. The expected result is result: [(['cat'], [0], [1.0])]. Returning fewer than k passages is the honest outcome when fewer than k valid candidates exist. The candidate request can also be capped at the three entries actually in this corpus, rather than asking an index of three items for twenty slots.
Why this happens
_batch_forward always asks FAISS for k * 10 candidates. _rerank_and_predict then reads self.corpus_embeddings[candidate_indices] without checking the IDs, sorts the resulting scores, and finally reads self.corpus[idx] for each selected ID. Both indexing operations give -1 a valid meaning that is wrong for a FAISS missing-hit marker.
Capping the request to corpus size removes avoidable empty slots. It does not, by itself, guarantee that an approximate index fills every slot, so the IDs also need to be validated before reranking and removed before constructing returned passages, indices, and scores. PR #10524 implements both parts and tests a batch where one query has fewer than k valid candidates while another has two valid candidates to rerank.
Environment
- DSPy
3.4.0, repositorymainat9c900c7 - Reproduced with Python 3.11 on Windows; the minimal case uses a FAISS-shaped index response and requires no FAISS training or network access
Source: stanfordnlp/dspy