RAG vector search on DGX Spark: validate dimensions and metrics

RAG vector search on DGX Spark: validate dimensions and metrics

RAG vector search on DGX Spark: validate dimensions and metrics

A RAG endpoint may answer questions while its retrieval layer consistently selects the wrong passages: document vectors are normalized but query vectors are not, or the index returns distances while the application sorts them in descending order as if they were scores. A generative model can turn the wrong context into a fluent answer, so release validation should start without generation, checking vectors, rankings, and document IDs separately.

DGX Spark has 128 GB of LPDDR5x unified memory shared by the CPU and GPU, plus 4 TB of NVMe storage for models and retrieval data. That capacity does not establish whether retrieval is correct. The following procedure uses the Python standard library on NVIDIA DGX OS to build an exact baseline for a small sample. It does not depend on a particular vector database or require a complete question-answering service to be deployed first.

1. Define the embedding-space contract first

Whenever you generate document vectors, save a manifest and release it alongside the index. At a minimum, record the model weights revision, tokenizer revision, pooling method, output dimensions, numeric type, whether normalization is applied, and the respective query and document prefixes.

Also record the text-chunking rules, maximum input length, truncation direction, and index distance metric. Different chunking or truncation can produce vectors with different meanings from the same text. Recording the model name alone is not enough to reproduce the results.

Queries and documents may use different prefixes when the model explicitly requires them, but both must follow the same contract. Do not replace them with identical strings merely to make the configuration look consistent.

Matching output dimensions only mean that the arrays have the same length, not that two models share a semantic space. After changing the weights or pooling strategy, you cannot send new query vectors directly to the old index.

For validation, choose short passages without sensitive content that cover clear matches, synonymous wording, unrelated content, and empty input. Assign each passage a stable ID and retain the final text passed to the encoder so that chunking errors are not mistaken for index problems.

2. Distinguish similarity from distance

Cosine similarity compares direction, the inner product depends on both direction and magnitude, and Euclidean distance measures the separation between two points. The first two are usually maximized, while distance is usually minimized. Check the actual API field semantics rather than inferring them from a name such as score.

When both query and document vectors are L2-normalized, their inner product equals their cosine similarity, and their squared Euclidean distance equals two minus twice the inner product. All three therefore produce the same ranking. Without normalization, vectors with larger magnitudes may dominate an inner-product ranking.

For example, take the query [1, 0], document A as [1, 0], and document B as [2, 2]. The inner product ranks B ahead of A, whereas cosine similarity selects A. This two-dimensional example is useful for checking ranking adapter code; it does not represent a real model’s semantic performance.

If the API returns negative distances, squared distances, or transformed similarities, make the conversion explicit in the adapter layer. Also use a fixed tie-breaking rule when comparing rankings. Otherwise, identical results may be reported as mismatches simply because their IDs appear in a different order.

3. Build an executable exact-retrieval baseline

Export vectors.json from the actual encoding pipeline in the following format. The two-dimensional data is only for checking the script initially. For formal validation, replace it with a real query vector and the vectors for the same document set, keeping their IDs unchanged.

{
  "query": [1, 0],
  "documents": [
    {"id": "a", "vector": [1, 0]},
    {"id": "b", "vector": [2, 2]},
    {"id": "c", "vector": [0, 1]}
  ]
}

Save the following as check_vectors.py. The script rejects empty arrays, dimension mismatches, duplicate IDs, non-finite values, and zero vectors, then outputs an exact ranking by cosine similarity. Normalization is performed only for the local calculation; the original file is not modified.

import json
import math
import sys

def unit(values, dimension=None):
    if not isinstance(values, list) or not values:
        raise ValueError("Expected a nonempty vector")
    if dimension is not None and len(values) != dimension:
        raise ValueError("Dimension mismatch")
    if any(type(x) not in (int, float) for x in values):
        raise ValueError("Expected numeric components")
    vector = [float(x) for x in values]
    if not all(math.isfinite(x) for x in vector):
        raise ValueError("Non-finite component")
    norm = math.hypot(*vector)
    if norm == 0 or not math.isfinite(norm):
        raise ValueError("Invalid vector norm")
    return [x / norm for x in vector], norm

with open(sys.argv[1], encoding="utf-8") as stream:
    data = json.load(stream)

query, query_norm = unit(data["query"])
documents = data["documents"]
if not documents:
    raise ValueError("Expected documents")

seen = set()
ranking = []
for document in documents:
    identifier = document["id"]
    if not isinstance(identifier, str) or not identifier:
        raise ValueError("Invalid document identifier")
    if identifier in seen:
        raise ValueError("Duplicate document identifier")
    seen.add(identifier)
    vector, norm = unit(document["vector"], len(query))
    score = math.fsum(a * b for a, b in zip(query, vector))
    ranking.append((identifier, score, norm))

ranking.sort(key=lambda row: (-row[1], row[0]))
print(json.dumps({
    "dimension": len(query),
    "query_norm": query_norm,
    "ranking": [
        {"id": identifier, "cosine": score, "original_norm": norm}
        for identifier, score, norm in ranking
    ]
}, ensure_ascii=False, indent=2))
python3 check_vectors.py vectors.json > exact-result.json

The example should return A, B, and C in that order. Then run separate tests with one document changed to a zero vector, shortened by one dimension, and given a duplicate ID. Confirm that the command exits with a nonzero status in each case. These negative tests establish that the checks actually work, rather than merely showing that a valid sample runs successfully.

4. Use the same data to isolate index discrepancies

Insert the exported document vectors unchanged into an isolated test index and submit the query vector directly from the file, initially bypassing online text encoding. Disable reranking, metadata filtering, and hybrid search so that the comparison covers only the vector retrieval stage.

If the index supports exact search, enable it first and compare the complete sequence of IDs. Scores can be compared when the index uses cosine similarity. For other equivalent metrics, convert them first rather than subtracting the raw values. Set floating-point tolerances according to the actual numeric precision, and examine near-ties separately.

Reconnect text encoding

Once direct vector submission passes, run the production encoder on the same query text. If the ranking changes at this point, check prefixes, truncation, pooling, model revisions, and normalization before tuning index parameters.

Approximate search cannot be expected to reproduce the exact ranking on every run. Use a fixed query set, take the exact top K IDs as the reference, and calculate the size of the intersection with the returned set divided by K. The reference document set must contain at least K documents, and ties at the cutoff need a separate rule. Then adjust search parameters one at a time and record the changes in recall. A single query is not enough to declare validation successful.

5. Require evidence before switching models

For every change, retain the manifest, text samples, raw vectors, exact results, index results, and execution-environment records. On ARM64, dependency versions and numeric precision may change the computation path, so run the same sample set after environment upgrades as well.

If a change affects the vector space, create a new index and re-encode every document rather than updating only new passages. During the switch, release the query encoder and index version as a pair. Keep the old pair available for rollback, and prevent the new encoder from querying old vectors.

Final validation has two parts: verifying that the numeric and ranking contract is correct, and confirming that manually labeled relevant passages are retrieved. Passing the first does not establish acceptable semantic performance; occasional success in the second does not excuse incorrect dimensions or distance settings. Only after both forms of evidence are available should you connect the generative model and evaluate answer quality.

Frequently asked questions

Can an embedding model be replaced without rebuilding the index if dimensions match?

Matching dimensions do not establish compatibility. Changes to weights, tokenization, pooling, query prefixes or text preparation can change the vector space. Without demonstrated compatibility, regenerate document embeddings and build a new index.

Do cosine similarity, inner product and Euclidean distance produce the same ranking?

They do when both query and document vectors are L2-normalized: maximizing inner product or cosine similarity is equivalent to minimizing Euclidean distance. This equivalence does not generally hold without normalization.

Dedicated AMD EPYC 7543P server from $467/month

Choose a dedicated server configuration to match the workload

Check memory and storage first, then choose the operating system and access method.