An empty document can outrank a real one. Give a search query two candidates, one pointing in the opposite direction and one filled with zeros. A dot-product ranker scores them −1 and 0. The empty document wins. Put those same rows in a pgvector cosine index and the empty document disappears.
Both symptoms start with a small decision in the ingestion code. Someone needed to keep a batch the right shape when a document had no embedding, so they filled a row with zeros. That choice traveled into systems with different ideas about what a zero means.
Here’s how to catch it with a two-document test, keep the right document IDs after filtering, and count which source records can actually participate in search. You can run the Python examples on a CPU without downloading a model.
Reproduce the false match with two documents
Imagine a help center with a searchable article and a scanned attachment whose text extraction failed. For a test, assign the article a vector opposite to the query. This gives the valid article the lowest possible cosine similarity. It also makes a surprisingly good check for a placeholder that slips into a ranking.
import torch
query = torch.tensor([1.0, 0.0])
docs = torch.tensor([[-1.0, 0.0], [0.0, 0.0]])
ids = ["help-article", "empty-attachment"]
scores = docs @ query
assert scores.tolist() == [-1.0, 0.0]
assert ids[scores.argmax().item()] == "empty-attachment"
A dot product equals cosine similarity when both inputs have unit length. The article and query meet that condition. The placeholder has length zero and therefore has no direction. Zero is also a perfectly legitimate score for a different document whose vector is perpendicular to the query. By the time all three cases are just numbers on a results page, a score of zero tells you little.
This is why a test corpus full of good matches can miss the bug. A strong positive match beats the placeholder, so the first result looks fine. Reduce the candidate pool to one customer, one language, or one product line and the best valid score might be negative. Whether to show that weak result is a relevance decision. Whether the empty attachment gets to compete is an input decision. Test each separately.
Find where FP16 normalization loses the row
A Sentence Transformers contributor found a related failure in community detection. A saved matrix contained two matching embeddings and one zero placeholder. On the affected code path, the placeholder took the place of a matching member. The merged fix preserves a zero row when the dense FP16 normalization helper encounters one. The upstream report includes the input, the incorrect IDs, and the expected IDs. Sentence Transformers regression and fix
There are two decisions buried in that example. The library needs to return a sensible tensor for its caller. Your application needs to decide which records have a usable embedding. A row of finite zeros can satisfy the first requirement and still fail the second.
PyTorch’s functional normalization divides a vector by the larger of its norm and an epsilon. Its default epsilon is 1e-12. In a calculation that represents this floor in FP16, it rounds to zero. A zero row divided by that denominator produces NaNs. You can inspect the precision issue directly with torch.tensor(1e-12, dtype=torch.float16).item(), which returns 0.0. Record the dtype at the normalization step when debugging. A model running in mixed precision can pass tensors of several types between operations. PyTorch normalization reference
Capture the first bad representation
Pick a failing source ID and inspect it at three points. Was there usable content after extraction? Did pooling return a finite, nonzero row? Did that row survive the conversion to the storage dtype? Log the ID, model revision, dtype, and norm at each available boundary. You can usually distinguish these cases without logging the text or the vector itself.
| What you observe | What to inspect next |
|---|---|
| Extraction returns no text and the stored row is zero | The branch that fills missing batch slots |
| Pooled output is finite and nonzero, stored FP16 row is all zeros | The cast and the range of component values before storage |
| The row already contains NaN before normalization | The encoder or pooling operation that first produced it |
| A finite, nonzero vector survives, but an answer near the end of the document is missing | The tokenizer and model input limit |
The last case has its own diagnostic. A valid vector can faithfully encode just the beginning of a chunk. If lowering precision changed nothing and the missing details sit near the tail, compare the tokenized input with the stored text. Test what the embedding model actually sees
Keep document IDs attached when you filter embeddings
Here’s an admission check for dense, two-dimensional FP16 batches. It promotes the values before taking their norms, accepts finite rows with positive length, and returns their original positions. The caller can hold rejected records for inspection while sending valid neighbors onward. Run this block after the first one.
def cosine_candidates(rows, expected_dim):
if rows.dtype != torch.float16 or rows.ndim != 2:
raise ValueError("expected a dense FP16 matrix")
if expected_dim < 1 or rows.shape[1] != expected_dim:
raise ValueError("embedding dimension mismatch")
wide = rows.float()
finite = torch.isfinite(wide).all(dim=1)
norms = torch.linalg.vector_norm(wide, dim=1)
keep = finite & torch.isfinite(norms) & (norms > 0)
positions = torch.where(keep)[0]
unit = wide[keep] / norms[keep, None]
return positions, unit
ids = ["empty-attachment", "help-article", "bad-export", "side-topic"]
rows = torch.tensor([[0, 0], [-3, 0], [float("nan"), 1], [0, 4]],
dtype=torch.float16)
positions, unit = cosine_candidates(rows, expected_dim=2)
kept_ids = [ids[i] for i in positions.tolist()]
assert kept_ids == ["help-article", "side-topic"]
assert (unit @ query).tolist() == [-1.0, 0.0]
assert kept_ids[(unit @ query).argmax().item()] == "side-topic"
Notice where the empty attachment sits in this batch. It comes first. If you zip the two surviving vectors with the first two original IDs, you silently assign the help article’s direction to the empty attachment. A check for unit norms would pass. The assertion on the actual IDs catches the mistake. In a service, verify the ID count matches the batch length before you call the helper, and carry the same selection through revision numbers and any other row metadata.
The check deliberately keeps the perpendicular document. Dropping rows with a zero score would lose a valid candidate. It also keeps tiny but representable nonzero FP16 vectors. If a particular encoder produces unreliable directions below a certain norm, choose a floor using labeled examples from that encoder. A single exact-zero test answers a numerical question. A model-specific quality floor answers an empirical one.
Give an invalid query its own outcome
Apply the same check on the query side before calling search. If a one-row query yields no surviving position, a nearest-neighbor call cannot supply a meaningful ordering. For a user who entered an exact invoice number, a permission-scoped lookup by that number may still work. For a blank search box, the useful response might simply be a request for a search term.
Keep that outcome distinct from a valid query that found no relevant documents. The two can look identical in a UI with a single empty state. During an incident, however, they send you to different owners. The first belongs to the query encoder or input path. The second may reflect a gap in the corpus, an overly strict filter, or a relevance threshold that needs tuning.
Audit which source records can enter a pgvector cosine index
Postgres can hold a finite zero vector in a vector column. pgvector documents that its approximate indexes skip null vectors and, for cosine distance, zero vectors. A successful insert therefore tells you less than you might expect. Increasing the HNSW candidate list cannot recover a row that never entered that index. pgvector index troubleshooting
Start the audit from the inventory of chunks that should have embeddings. Starting from the embeddings table hides every chunk whose worker failed before it wrote a row. The query below assumes one current revision per chunk in expected_chunks and at most one embedding per chunk, revision, and model in chunk_embeddings. It uses the pgvector vector type. Replace the model identifier with the one serving traffic.
WITH coverage AS (
SELECT c.chunk_id,
CASE
WHEN e.chunk_id IS NULL THEN 'missing row'
WHEN e.embedding IS NULL THEN 'null embedding'
WHEN vector_norm(e.embedding) = 0 THEN 'zero embedding'
ELSE 'eligible'
END AS state
FROM expected_chunks AS c
LEFT JOIN chunk_embeddings AS e
ON e.chunk_id = c.chunk_id
AND e.revision = c.revision
AND e.model_id = 'help-search-v1'
)
SELECT state, count(*) AS chunks
FROM coverage
GROUP BY state
ORDER BY state;
Keep the model predicate in the join condition. Moving it to a WHERE clause drops unmatched rows, which are exactly the evidence you came to find. Joining on revision matters for a similar reason. A vector for the previous edition of a refund policy can make a current document look covered while search still points readers at an obsolete answer.
For a small acceptance test, seed four current chunks. Give one a valid embedding, one a zero vector, and one a null. Give the last chunk an embedding only for its previous revision. The expected output is one row in each state. Three current embedding records exist, yet only one of the four intended chunks is eligible. That fraction describes this fixture. Your production denominator should reflect your own indexing policy, including deliberate exclusions such as attachments without searchable text.
Check the query plan when a manual search disagrees
A developer investigating those four chunks might run a distance query against the table and see more rows than the application returns. Check the query plan before interpreting that result. A sequential scan can visit stored rows that a cosine index omits. On a tiny fixture, the planner has good reason to choose a table scan. Even a query with the same distance operator and limit can take a different path on a larger corpus.
To isolate index membership, inspect the plan for an index scan using the intended cosine index. In a disposable test session you can discourage sequential scans, run the query with a valid vector and a limit larger than the fixture, and inspect the IDs returned. In the four-chunk example, the old revision still has a valid direction. An unfiltered index scan can return that stale row as well as the current help article. Adding the revision constraint is what makes the result meaningful to the application.
That extra observation gives you a sharper incident report. “Search skipped two files” leaves a teammate guessing about recall settings. “The scan returned one current revision and one obsolete revision, and the current attachment has a zero embedding” identifies two repairs with different owners. One belongs in the read path and the other in ingestion.
Decide what to repair before changing search settings
Suppose a help center releases a batch of updated manuals. The dashboard reports successful embedding jobs, but support agents can only retrieve the old troubleshooting steps. Split coverage by source type and revision. If the missing current rows all came from scanned manuals, changing the search index will spend time on documents it cannot see. Replay one scan through extraction and check the first stage that loses its content.
A retry makes sense after a temporary inference timeout. Repeatedly embedding an empty text extraction with identical settings spends compute without supplying the missing text. Save the source revision and failure reason, fix the extraction step, and then retry that revision. Check again before activating the repaired vector in case a newer version arrived during the backfill.
For a release check, keep two numbers side by side. One measures how many intended chunks have an eligible current vector. The other measures how often search retrieves the right result among eligible candidates. A team can improve the second number by accidentally dropping difficult records. Watching the first number makes that trade visible. If valid records compete at equal distances near your cutoff, score those ties explicitly. Measure vector search recall when distances tie
A useful incident ticket includes one searchable control from the same import. If both the control and the failing chunk vanish, inspect the shared model ID or revision filter first. If the control survives and the attachment fails on every replay, send the document owner the extraction result and the affected revision. That single control can save a database engineer from rebuilding an index that is doing exactly what its inputs allow.
For each expected chunk, can you name its current revision, show its search eligibility, and explain the first step that failed?
FAQ
Is cosine similarity with a zero vector equal to zero?
The mathematical expression divides by both vector lengths, so a zero length makes the result undefined. Some implementations use a denominator floor and return a finite value. Treat that value as a library convention. To test for an orthogonal match, use two nonzero vectors pointing at right angles.
Can I solve FP16 normalization NaNs by increasing epsilon?
A floor representable in the calculation’s dtype can prevent division by zero. It also changes the scaling of every nonzero row whose norm falls below the floor. Test a small valid row alongside an exact zero. Decide separately whether each row belongs in the candidate pool.
Should I store a null or a zero for a failed embedding?
If the schema permits it, a null plus an explicit processing state lets you distinguish pending, failed, and deliberately skipped work. A missing embedding row can work too if you maintain a source inventory. Either design lets you retry a specific revision and report the gap.
Will converting an FP16 embedding back to FP32 recover it?
Widening preserves the values you still have. If every component already rounded to zero, the direction is gone. Retrieve the higher-precision output from before the cast or re-encode the source. Compare both at the storage boundary before deciding whether to change the model.
What should happen if every row in a batch fails?
Keep the batch’s source IDs and record a failure or exclusion reason for each one. The example returns an empty matrix with the expected column count. Skip the search-index write for that batch and make the rejected count visible. An empty write acknowledged as a full indexing success can hide a broken import for a long time.
Top comments (0)