蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

本机索引、度量和持久化对照

PYTHONCPython 3.12.14、NumPy 2.5.4、Faiss 1.16.0、Chroma 1.5.9、Qdrant Client 1.20.0。CPU、本机文件及自编向量。index_lab.py
index_lab.py156 行

"""Run native Faiss indexes and local Qdrant with original vector fixtures."""
from contextlib import closing
import socket
from importlib.metadata import version
from unittest.mock import patch

import faiss
import numpy as np
from qdrant_client import QdrantClient, models

from lab_tools import run_exercise


def recall_at_k(approximate, reference):
    return sum(len(set(result) & set(expected)) for result, expected in zip(approximate, reference, strict=True)) / reference.size


def native_faiss(checks, workspace):
    faiss.omp_set_num_threads(1)
    metric_demo = faiss.IndexFlatL2(2)
    metric_demo.add(np.array([[1,0],[1,2]],dtype="float32"))
    distances, ids = metric_demo.search(np.array([[1,0]],dtype="float32"),2)
    checks.expect("vector_db_faiss_squared", [[1,0],[1,2]], "Compare native L2 index IDs and squared distances",
                  [[[0,1]],[[0.,4.]]],[ids.tolist(),distances.tolist()])

    rng = np.random.default_rng(17)
    centers = np.eye(4,8,dtype="float32")*6
    vectors = np.concatenate([center + rng.normal(0,1,(96,8)) for center in centers]).astype("float32")
    queries = vectors[[3,97,200,300]].copy()
    flat = faiss.IndexFlatL2(8)
    flat.add(vectors)
    _, baseline = flat.search(queries,5)
    expected_ids = [3,97,200,300]
    checks.expect("vector_db_faiss_flat", expected_ids, "Search four inserted vectors against all 384 points",
                  [expected_ids,384],[baseline[:,0].tolist(),flat.ntotal])

    ivf = faiss.IndexIVFFlat(faiss.IndexFlatL2(8),8,4,faiss.METRIC_L2)
    ivf.train(vectors)
    ivf.add(vectors)
    ivf.nprobe = 1
    _, nearest = ivf.quantizer.search(queries,1)
    narrow_candidates = [ivf.invlists.list_size(int(row[0])) for row in nearest]
    _, narrow = ivf.search(queries,5)
    assignments = ivf.quantizer.assign(vectors,1).ravel()
    candidate_rankings = []
    for query,bucket in zip(queries,nearest.ravel(),strict=True):
        candidate_ids = np.flatnonzero(assignments==bucket)
        squared = ((vectors[candidate_ids]-query)**2).sum(axis=1)
        candidate_rankings.append(candidate_ids[np.argsort(squared)[:5]])
    ivf.nprobe = 4
    distances, wide = ivf.search(queries,5)
    checks.expect("vector_db_faiss_ivf",[1,4,4],"Train centroids, compare candidate sizes and search all lists against exact ranking",
                  [True,True,1.0,expected_ids,True],
                  [ivf.is_trained,all(0<n<flat.ntotal for n in narrow_candidates),
                   recall_at_k(wide,baseline),wide[:,0].tolist(),np.array_equal(narrow,candidate_rankings)])
    checks.expect("vector_db_faiss_ivf_recall",[1,4],"Measure top-five recall on four queries against exact ranking",
                  [recall_at_k(candidate_rankings,baseline),1.0],
                  [recall_at_k(narrow,baseline),recall_at_k(wide,baseline)])
    checks.expect("vector_db_faiss_ivf_lists",4,"Count native inverted-list entries after training and adding",
                  384,sum(ivf.invlists.list_size(i) for i in range(ivf.nlist)))

    boundary = faiss.IndexIVFFlat(faiss.IndexFlatL2(1),1,2,faiss.METRIC_L2)
    boundary.train(np.repeat(np.array([[0.],[10.]],dtype="float32"),80,axis=0))
    boundary.add(np.array([[0.],[4.5],[5.1],[10.]],dtype="float32"))
    boundary_query = np.array([[4.99]],dtype="float32")
    observed = []
    for probes in (1,2):
        boundary.nprobe = probes
        values, found = boundary.search(boundary_query,1)
        observed.append([int(found[0,0]),round(float(values[0,0]),6)])
    checks.expect("vector_db_ivf_boundary", [4.99,[1,2]],
                  "Query near the boundary and recover the exact nearest point by probing both lists",
                  [[1,0.2401],[2,0.0121]],observed)

    graph = faiss.IndexHNSWFlat(8,8)
    graph.hnsw.efConstruction = 40
    graph.add(vectors)
    graph.hnsw.efSearch = 8
    _, low = graph.search(queries,5)
    graph.hnsw.efSearch = 64
    _, high = graph.search(queries,5)
    checks.expect("vector_db_faiss_hnsw", [8,40,[8,64]], "Build a native graph and compare searches to the same exact index",
                  [expected_ids,expected_ids,True,True],
                  [low[:,0].tolist(),high[:,0].tolist(),
                   recall_at_k(low,baseline)>=0.8,recall_at_k(high,baseline)>=0.95])

    pq = faiss.IndexIVFPQ(faiss.IndexFlatL2(8),8,4,2,2)
    pq.train(vectors)
    pq.add(vectors)
    pq.nprobe = 4
    pq_distances,pq_ids = pq.search(queries,5)
    checks.expect("vector_db_faiss_pq", [8,2,2], "Train compressed index and observe bytes per code and finite approximate distances",
                  [True,1,[4,5],True,True],
                  [pq.is_trained,pq.code_size,list(pq_ids.shape),bool(np.isfinite(pq_distances).all()),
                   not np.allclose(pq_distances,distances)])
    index_file = workspace/"ivf.bin"
    faiss.write_index(ivf,str(index_file))
    restored = faiss.read_index(str(index_file))
    restored.nprobe=4
    reopened_distances,reopened_ids=restored.search(queries,5)
    restored.add(np.array([[22]*8],dtype="float32"))
    _, added_ids = restored.search(np.array([[22]*8],dtype="float32"),1)
    checks.expect("vector_db_faiss_reload",index_file.name,"Write, reopen and append one vector without changing the original index",
                  [True,True,384,385,[[384]]],
                  [np.array_equal(reopened_ids,wide),np.allclose(reopened_distances,distances),ivf.ntotal,
                   restored.ntotal,added_ids.tolist()])


def qdrant_local(checks, workspace):
    directory=workspace/"qdrant"
    collection="inspection"
    with closing(QdrantClient(path=str(directory))) as client:
        client.create_collection(collection_name=collection,vectors_config=models.VectorParams(size=2,distance=models.Distance.COSINE))
        rows=[(10,[1.,0.],"staff"),(20,[0.8,0.6],"public"),(30,[0.,1.],"public")]
        client.upsert(collection,points=[models.PointStruct(id=i,vector=v,payload={"group":g}) for i,v,g in rows],wait=True)
        filtered=models.Filter(must=[models.FieldCondition(key="group",match=models.MatchValue(value="public"))])
        result=client.query_points(collection,query=[1.,0.],query_filter=filtered,limit=2,with_payload=True).points
        checks.expect("vector_db_qdrant_filter", [1.,0.], "Upsert local points and retrieve only eligible payloads",
                      [[20,30],[0.8,0.],["public","public"]],
                      [[r.id for r in result],[round(r.score,6) for r in result],[r.payload["group"] for r in result]])
        client.upsert(collection,points=[models.PointStruct(id=30,vector=[1.,0.],payload={"group":"public"})],wait=True)
    with closing(QdrantClient(path=str(directory))) as client:
        result=client.query_points(collection,query=[1.,0.],query_filter=filtered,limit=2).points
        checks.expect("vector_db_qdrant_reopen", "closed local client", "Reopen the path and inspect updated ranking and row count",
                      [[30,20],3], [[r.id for r in result],client.count(collection,exact=True).count])


def forbid_network(*_args,**_kwargs):
    raise AssertionError("these index fixtures use only local files")


def exercise(checks,workspace):
    names=["faiss-cpu","qdrant-client","numpy"]
    installed=[version(name) for name in names]
    checks.expect("vector_db_native_versions", names,"Read versions from installed package metadata",
                  ["1.16.0","1.20.0","2.5.4"],installed)
    sizes = [10_000,1_000_000,10_000_000,100_000_000,1_000_000_000]
    checks.expect("vector_db_raw_budget", [sizes,128,4], "Calculate raw FP32 bytes without the index",
                  [5120000,512000000,5120000000,51200000000,512000000000],[n*128*4 for n in sizes])
    query = "水泵 维保"
    candidates = [("log","维修 水泵"),("manual","水泵 维保 手册"),("form","水泵 维保 维保 表单")]
    def score(text):
        return len(set(query.split()) & set(text.split())) + (2 if query in text else 0)
    reordered = sorted(candidates,key=lambda row:(-score(row[1]),row[0]))
    checks.expect("vector_db_candidate_rerank", [query,candidates],
                  "Rescore only the candidate documents by term overlap and phrase match",
                  [["form",4],["manual",4],["log",1]],[[name,score(text)] for name,text in reordered])
    native_faiss(checks,workspace)
    with patch.object(socket.socket,"connect",forbid_network),patch.object(socket.socket,"connect_ex",forbid_network):
        qdrant_local(checks,workspace)


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12.14、NumPy 2.5.4、Faiss 1.16.0、Chroma 1.5.9、Qdrant Client 1.20.0。CPU、本机文件及自编向量。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12.14、NumPy 2.5.4、Faiss 1.16.0、Chroma 1.5.9、Qdrant Client 1.20.0。CPU、本机文件及自编向量。

入口文件:projects/ai-vector-database/index_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 index_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12.14、NumPy 2.5.4、Faiss 1.16.0、Chroma 1.5.9、Qdrant Client 1.20.0。CPU、本机文件及自编向量。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a30.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习