Indexing y similarity search
4.14.3kata 3 de 4

HNSW Parameter Tuning

m, efConstruction, efSearch: recall vs latencia

HNSW tiene tres parámetros clave: (1) `m`: conexiones por nodo (default 16). Más m = mejor recall pero más RAM y tiempo de construcción. (2) `efConstruction`: tamaño del candidato pool al construir (default 64). Mayor valor = mejor índice pero construcción más lenta. (3) `efSearch`: parámetro de búsqueda (ajustable en runtime). Mayor efSearch = mejor recall, más latencia.

El trade-off fundamental: m y efConstruction son time-cost de construcción (offline, una sola vez); efSearch es time-cost de búsqueda (runtime, cada query). Para la mayoría de casos, deja m=16 y efConstruction=64, y ajusta efSearch en tiempo de ejecución según necesidades de recall.

Heurística: si necesitas recall > 95%, efSearch >= 64. Si toleras recall > 85%, efSearch = 32 es usualmente suficiente. Si necesitas máxima velocidad (p95 < 50ms), efSearch = 16. Mide en tus datos reales.

structure.txt
import faiss
import numpy as np

DIM = 1536
N = 1_000_000

# === Construcción: parámetros fijos ===
hnsw_index = faiss.IndexHNSWFlat(DIM, 32)  # m=32 (higher than default 16)
hnsw_index.hnsw.efConstruction = 200  # higher for better quality
hnsw_index.add(normalized_vecs)  # SLOWEST STEP (one time)

# === Búsqueda: efSearch es tunable ===
for ef in [16, 32, 64, 128, 256]:
    hnsw_index.hnsw.efSearch = ef
    distances, indices = hnsw_index.search(query.reshape(1, -1), k=10)
    recall = measure_recall_vs_flat(indices)  # compare with flat search
    latency = measure_latency(hnsw_index, query)
    print(f'efSearch={ef}: recall={recall:.3f}, latency={latency:.1f}ms')
# Choose ef that balances recall and latency

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # Low efConstruction at build time, then expect high recall at query time hnsw = faiss.IndexHNSWFlat(DIM, 16) hnsw.hnsw.efConstruction = 32 # too low hnsw.add(vecs) # Later: recall is poor, so increase efSearch hnsw.hnsw.efSearch = 256 # won't help — index was built poorly

  2. 02

    # High m increases RAM without proportional recall gain hnsw = faiss.IndexHNSWFlat(DIM, 64) # very high m hnsw.hnsw.efConstruction = 500 # very slow hnsw.add(vecs) # takes 10 minutes, RAM usage 2x higher

  3. 03

    # Assume efSearch is fixed; rebuild index to improve recall hnsw.hnsw.efSearch = 16 # can't seem to get good recall # Rebuild with higher m? hnsw = faiss.IndexHNSWFlat(DIM, 64) # expensive