diff --git a/09_vector_retrieval/PurplePulse/.clang-format b/09_vector_retrieval/PurplePulse/.clang-format new file mode 100644 index 00000000..75295958 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/.clang-format @@ -0,0 +1,4 @@ +BasedOnStyle: Google +ColumnLimit: 80 +IndentWidth: 2 +SortIncludes: CaseSensitive diff --git a/09_vector_retrieval/PurplePulse/.gitattributes b/09_vector_retrieval/PurplePulse/.gitattributes new file mode 100644 index 00000000..99316f64 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/.gitattributes @@ -0,0 +1,6 @@ +*.csv text eol=lf +*.md text eol=lf +*.cpp text eol=lf +*.cu text eol=lf +*.h text eol=lf +*.py text eol=lf diff --git a/09_vector_retrieval/PurplePulse/.gitignore b/09_vector_retrieval/PurplePulse/.gitignore new file mode 100644 index 00000000..e87d3f18 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/.gitignore @@ -0,0 +1,63 @@ +/build/ +/data/ +/tmp/ +/results/* +!/results/figures/ +/results/figures/* +!/results/figures/*.svg +!/results/million/ +/results/million/* +!/results/million/*.csv +!/results/memory_100k/ +/results/memory_100k/* +!/results/memory_100k/source1_compare.csv +!/results/exact_fused/ +/results/exact_fused/* +!/results/exact_fused/million_compare.csv +!/results/formal_100k15/ +/results/formal_100k15/* +!/results/formal_100k15/*.csv +!/results/formal_4090d_20260908/ +/results/formal_4090d_20260908/* +!/results/formal_4090d_20260908/*.csv +!/results/real/ +/results/real/* +!/results/real/*/ +/results/real/*/* +!/results/real/*/*.csv +!/results/real/*/*.json +!/results/real/*/*.jsonl +!/results/real/*/figures/ +/results/real/*/figures/* +!/results/real/*/figures/*.svg +!/results/stage7_exact_profile/ +/results/stage7_exact_profile/* +!/results/stage7_exact_profile/*/ +/results/stage7_exact_profile/*/* +!/results/stage7_exact_profile/*/*.csv +!/results/stage7_exact_profile/cosine_norm_ab/ +/results/stage7_exact_profile/cosine_norm_ab/* +!/results/stage7_exact_profile/cosine_norm_ab/*/ +/results/stage7_exact_profile/cosine_norm_ab/*/* +!/results/stage7_exact_profile/cosine_norm_ab/*/*.csv +!/results/stage7_exact_query_tile/ +/results/stage7_exact_query_tile/* +!/results/stage7_exact_query_tile/*/ +/results/stage7_exact_query_tile/*/* +!/results/stage7_exact_query_tile/*/*/ +/results/stage7_exact_query_tile/*/*/* +!/results/stage7_exact_query_tile/*/*/*.csv +!/results/stage7_exact_block_tile/ +/results/stage7_exact_block_tile/* +!/results/stage7_exact_block_tile/*/ +/results/stage7_exact_block_tile/*/* +!/results/stage7_exact_block_tile/*/*/ +/results/stage7_exact_block_tile/*/*/* +!/results/stage7_exact_block_tile/*/*/*.csv +!/results/stage8_stability/ +/results/stage8_stability/* +!/results/stage8_stability/*.csv +*.bin +*.ncu-rep +*.nsys-rep +__pycache__/ diff --git a/09_vector_retrieval/PurplePulse/CMakeLists.txt b/09_vector_retrieval/PurplePulse/CMakeLists.txt new file mode 100644 index 00000000..6a7cac41 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/CMakeLists.txt @@ -0,0 +1,83 @@ +cmake_minimum_required(VERSION 3.24) + +# 必须在 project() 之前设置,否则 CMake 可能先缓存一个旧架构默认值。 +if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) + set(CMAKE_CUDA_ARCHITECTURES native CACHE STRING "CUDA GPU architectures") +endif() + +project(purplepulse_vector_retrieval LANGUAGES CXX CUDA) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CUDA_STANDARD 17) +set(CMAKE_CUDA_STANDARD_REQUIRED ON) + +add_library(vector_engine + src/file_io.cpp + src/cpu_search.cpp + src/ivf_flat.cpp + src/gpu_ivf_flat.cu + src/gpu_search.cu +) +target_include_directories(vector_engine PUBLIC include) +target_compile_options(vector_engine PRIVATE + $<$:-Wall;-Wextra;-Wpedantic;-march=native> + $<$:--extended-lambda> +) + +add_executable(vector_search src/main.cpp) +target_link_libraries(vector_search PRIVATE vector_engine) + +add_executable(ivf_build src/build_ivf.cpp) +target_link_libraries(ivf_build PRIVATE vector_engine) + +add_executable(ivf_search src/search_ivf.cpp) +target_link_libraries(ivf_search PRIVATE vector_engine) + +add_executable(unit_tests tests/unit_tests.cpp) +target_link_libraries(unit_tests PRIVATE vector_engine) + +add_executable(file_io_tests tests/file_io_tests.cpp src/file_io.cpp) +target_include_directories(file_io_tests PRIVATE include) +target_compile_options(file_io_tests PRIVATE -Wall -Wextra -Wpedantic) + +add_executable(ivf_flat_tests tests/ivf_flat_tests.cpp) +target_link_libraries(ivf_flat_tests PRIVATE vector_engine) + +add_executable(stability_tests tests/stability_tests.cpp) +target_link_libraries(stability_tests PRIVATE vector_engine) + +enable_testing() +add_test(NAME unit_tests COMMAND unit_tests) +add_test(NAME file_io_tests COMMAND file_io_tests) +add_test(NAME ivf_flat_tests COMMAND ivf_flat_tests) +add_test(NAME stability_tests COMMAND stability_tests) +add_test(NAME vector_search_help COMMAND vector_search --help) +add_test(NAME ivf_build_help COMMAND ivf_build --help) +add_test(NAME ivf_search_help COMMAND ivf_search --help) + +find_package(Python3 COMPONENTS Interpreter) +if(Python3_Interpreter_FOUND) + add_test(NAME benchmark_faiss_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_benchmark_faiss.py) + add_test(NAME benchmark_ivf_sweep_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_benchmark_ivf_sweep.py) + add_test(NAME benchmark_adaptive_nprobe_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_benchmark_adaptive_nprobe.py) + add_test(NAME import_mnist_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_import_mnist.py) + add_test(NAME import_sift1m_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_import_sift1m.py) + add_test(NAME import_ann_benchmarks_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_import_ann_benchmarks.py) + add_test(NAME plot_results_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_plot_results.py) + add_test(NAME stage6_tools_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_stage6_tools.py) + add_test(NAME benchmark_exact_breakdown_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_benchmark_exact_breakdown.py) + add_test(NAME benchmark_exact_query_tile_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_benchmark_exact_query_tile.py) + add_test(NAME stage9_tools_tests + COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/test_stage9_tools.py) +endif() diff --git a/09_vector_retrieval/PurplePulse/README.md b/09_vector_retrieval/PurplePulse/README.md new file mode 100644 index 00000000..66723ee6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/README.md @@ -0,0 +1,490 @@ +# WarpFusion:GPU Exact 与 IVF-Flat 向量检索引擎 + +这是 2026 夏季训练营 CUDA 方向“GPU 向量检索引擎”项目的独立实现。 + +项目从容易理解、结果正确的精确检索 baseline 逐步演进到 GPU Top-K、 +IVF-Flat、多轮性能优化、并行索引构建和真实数据评测。 + +![WarpFusion 系统架构](results/figures/architecture.svg) + +## 当前功能 + +- FP32/FP16 向量库与查询文件读写 +- FP16 在 GPU 上保持 16 位存储,距离计算使用 FP32 累加 +- L2、内积和余弦相似度 +- CPU 精确检索参考实现 +- CUDA 精确距离计算 baseline +- 四种 GPU Top-K:simple、block、two-stage,以及不生成完整距离矩阵的 + fused 路径 +- 精确检索与 IVF 均支持 K = 1、10、50、100(也支持其他 K≤100) +- 批量查询 +- GPU 数据库和工作区常驻显存,区分一次性初始化与稳定查询性能 +- CPU/GPU 结果自动对比测试 +- IVF-Flat CPU baseline:采样 k-means、连续倒排桶、索引保存/加载、固定 + `nprobe` 查询和 recall@K +- L2 使用普通 k-means;内积和余弦使用归一化中心的球面 k-means,避免 + 相似度聚类因中心模长造成严重桶倾斜 +- GPU IVF:中心、桶 offsets 和索引向量常驻显存,GPU 完成中心选择、 + 每桶 block 并行扫描、局部 Top-K 与最终归并;支持 scalar、2/4/8-warp + 和按 K 自动选择并发度的 compact 扫描路径 +- 实验性 `score_mass` 自适应 nprobe:依据每个 query 的中心分数分布选择 + probe 前缀,支持实际 probe 明细导出和 masked/grouped 调度 A/B +- 可选实验扩展:GPU 元数据过滤与融合评分 + +IVF-Flat 的索引、CPU 正确性基线、全 GPU 查询路径、K=1/10/50/100 以及 +100k/百万规模参数扫描、桶扫描优化、FAISS CPU/GPU 对照和首轮自适应 +nprobe 实验已经完成;提交结论与最新数字以 `docs/FINAL_REPORT.md` 为准。 + +## 正式结果与报告 + +完整方法、实验口径、负结果和复现命令见 +[`docs/FINAL_REPORT.md`](docs/FINAL_REPORT.md);本轮正式环境、训练差异、 +数据/索引校验和、完整命令和延迟定义见 +[`docs/REPRODUCIBILITY.md`](docs/REPRODUCIBILITY.md)。提交前可按 +[`docs/SUBMISSION_CHECKLIST.md`](docs/SUBMISSION_CHECKLIST.md) 逐项核验。 +第八阶段的维度/dtype/metric/batch/K 覆盖与安全回退规则见 +[`docs/STABILITY_MATRIX.md`](docs/STABILITY_MATRIX.md);CLI 和常驻执行器示例见 +[`docs/API.md`](docs/API.md)。 +图表由原始 CSV 直接生成: + +![Recall–QPS](results/figures/recall-qps.svg) + +![Batch–QPS](results/figures/batch-qps.svg) + +重新生成全部图表: + +```bash +python3 scripts/plot_results.py \ + --results-dir results/formal_100k15 \ + --batch-results-dir results/million \ + --output-dir results/figures +``` + +## 编译 + +```bash +export PATH=/usr/local/cuda/bin:$PATH +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_ARCHITECTURES=native +cmake --build build +ctest --test-dir build --output-on-failure +``` + +`native` 会在配置时检测当前 GPU,因此切换 GPU 型号时不需要修改 +README。如果要生成能在多种 GPU 上运行的二进制,可显式传入用分号分隔的 +多个架构编号。切换设备后建议删除旧 `build/` 或使用新的构建目录, +避免复用 CMake 缓存中的旧架构。 + +## 一条命令复现 + +在已安装 CUDA、CMake、Ninja、Python 依赖和 GPU 版 FAISS 的 Linux 主机上, +以下命令依次执行干净构建、CTest、公开数据准备、WarpFusion/FAISS 正式实验、 +绘图、PDF 报告生成和发布校验。长任务应由 `nohup` 托管;每一步的日志与断点 +状态都会立即写到结果目录: + +```bash +mkdir -p results/real/reproducibility/logs +nohup python3 scripts/reproduce.py --project-root "$PWD" --resume \ + > results/real/reproducibility/nohup.log 2>&1 & +``` + +若数据已准备好,可加 `--skip-download`;若索引已完成,可再加 +`--skip-index-build`。只查看将执行的命令而不改变状态: + +```bash +python3 scripts/reproduce.py --project-root "$PWD" --dry-run +``` + +断点文件为 `results/real/reproducibility/checkpoint.json`。更换源码、配置或数据后 +应使用新的结果目录,避免把旧断点误认为新实验已完成。 + +## 推荐起点 + +这些值是正式单卡实验的起点,不是跨数据和跨 GPU 的通用最优参数: + +| 场景 | 默认/推荐值 | 说明 | +|---|---|---| +| Exact | `warp + fused`, batch 64 | K≤100;未验证 query tile 自动回退 tile1 | +| SIFT1M / Yahoo IVF | nlist 1024, batch 64 | 建库 100k 样本、15 轮、seed 2026 | +| IVF K=10 | `bucket_major` | 扫描 nprobe 后按目标 recall 选点 | +| IVF K=50 | 完整 heap 回退 | 真实数据上分区路径未稳定获益 | +| IVF K=100 | `bucket_major_partitioned` | 4×40 局部候选后最终归并 | +| 基准计时 | warmup 1, repeat 5 | 报告稳定查询 QPS,另列一次性 H2D | + +RTX 4090 D 上公开真实数据的代表点如下,完整曲线和同预算 FAISS 对照以原始 +CSV 与最终报告为准: + +| 数据集 | 查询 | K | nprobe | Recall@K | QPS | +|---|---|---:|---:|---:|---:| +| SIFT1M | Exact fused | 10 | — | 1.0000 | 7,038 | +| SIFT1M | IVF-Flat | 10 | 160 | 0.99987 | 24,579 | +| Yahoo MiniLM 384 | Exact fused | 10 | — | 1.0000 | 3,610 | +| Yahoo MiniLM 384 | IVF-Flat | 10 | 160 | 0.9939 | 15,733 | + +## 已知限制 + +- 单进程、单 GPU、内存内静态索引;无在线增删、压缩、超显存分片或多 GPU。 +- 正式性能只在 RTX 4090 D 上验证;更换维度、分布、K 或 GPU 必须重新扫参。 +- Exact fused 仍落后于 FAISS GPU Flat;当前强项是可解释、可验证的 IVF 路径。 +- IVF recall 依赖训练样本和数据分布;固定 nprobe 不保证逐 query 的最低 recall。 +- 当前交付提供源码级 API,不承诺稳定 ABI,也未提供并发服务层。 + +## 生成测试数据 + +```bash +python3 scripts/generate_data.py \ + --database data/database.bin \ + --queries data/queries.bin \ + --num-vectors 10000 \ + --num-queries 20 \ + --dim 128 \ + --dtype fp32 \ + --metric l2 \ + --seed 2026 +``` + +## 执行检索 + +```bash +./build/vector_search \ + --database data/database.bin \ + --queries data/queries.bin \ + --params configs/exact_l2.conf \ + --backend gpu \ + --output results/exact_l2.txt +``` + +结果文件中每一行依次为 `query_id vector_id score`。 + +### 融合 Exact 路径 + +设置 `distance_mode=warp`、`topk_mode=fused` 后,每个 warp 在计算距离时 +直接维护局部 Top-K,每个 query/chunk 只写回 K 个候选,再由一个小型 kernel +完成最终归并。该路径不再物化 `batch_size × num_vectors` 的完整距离矩阵。 +K=10/50/100 的参考配置分别为 +`configs/exact_million_k{10,50,100}_fused_batch64.conf`。 + +第七阶段增加 `exact_query_tile=2/4/8` 和 `exact_fused_blocks=N` 以复用跨 query +数据库读取。`exact_fused_layout=block_tile` 是保留的负实验入口;默认值始终为 +`warp_query`,不应把 block-tile 用作推荐配置。选择依据与完整 A/B 数字见 +`docs/REPRODUCIBILITY.md`。 + +百万条 FP32、128 维、1000 queries、Cosine、batch=64、预热 1 次并重复 5 次 +的当前测试结果如下;旧 matrix 路径保留用于 A/B: + +| K | matrix QPS | fused QPS | 加速 | matrix / fused 缓冲区 | +|---:|---:|---:|---:|---:| +| 10 | 1775.10 | 5563.72 | 3.13× | 734.34 / 488.44 MiB | +| 50 | 715.87 | 5123.32 | 7.16× | 732.49 / 488.94 MiB | +| 100 | 443.78 | 4700.80 | 10.59× | 732.53 / 489.56 MiB | + +所有成对结果的 Top-K ID 集合一致,记录的最大分数误差为 0。原始数据见 +`results/exact_fused/million_compare.csv`,可重新运行: + +```bash +python3 scripts/benchmark_exact_fused.py \ + --search-binary ./build/vector_search \ + --database data/exact_million/cosine_db.bin \ + --queries data/exact_million/cosine_q.bin \ + --baseline-configs configs/exact_l2_batch64.conf,configs/exact_million_k50_batch64.conf,configs/exact_million_k100_batch64.conf \ + --fused-configs configs/exact_million_k10_fused_batch64.conf,configs/exact_million_k50_fused_batch64.conf,configs/exact_million_k100_fused_batch64.conf \ + --output-dir results/exact_fused/million_outputs \ + --csv results/exact_fused/million_compare.csv \ + --warmup 1 --repeat 5 +``` + +## IVF-Flat baseline + +先构建可持久化索引: + +```bash +./build/ivf_build \ + --database data/database.bin \ + --output data/database.ivf \ + --nlist 1024 \ + --iterations 15 \ + --training-samples 100000 \ + --threads 16 +``` + +再运行 CPU IVF 正确性/质量基线;`--nprobe` 可覆盖配置文件,便于扫描: + +```bash +./build/ivf_search \ + --index data/database.ivf \ + --queries data/queries.bin \ + --params configs/ivf_flat.conf \ + --nprobe 16 \ + --backend gpu \ + --warmup 1 \ + --repeat 5 \ + --output results/ivf_flat.txt + +python3 scripts/evaluate_recall.py \ + --exact results/exact_l2.txt \ + --approximate results/ivf_flat.txt +``` + +输出同时包含 recall、最低单 query recall,以及按名次计算的平均/最大绝对 +分数误差。 + +`configs/ivf_flat_100k_{balanced,high_recall,exact_check}.conf` 是 +100k × 128、K=10 实验的三档参考配置。`nlist` 必须与索引构建参数一致; +迁移到百万级或不同数据分布时,应重新扫描 `nlist/nprobe`,不要直接把这组 +参数当成通用最优值。`ivf_flat_100k_scalar_baseline.conf` 保留旧的 +thread-per-vector 桶扫描,用于和默认 warp 协作版本做 A/B 对照。 +`nprobe` 可取 `1..nlist`;使用 `nprobe=nlist` 可作为结果完整性校验,但 +近似检索应根据目标 recall 和延迟选取更小的值。 + +百万规模 K=10 初测提供四档配置: + +- `ivf_flat_million_fast.conf`:偏吞吐。 +- `ivf_flat_million_balanced.conf`:约 0.87 recall 的平衡档。 +- `ivf_flat_million_high_recall.conf`:约 0.97 recall。 +- `ivf_flat_million_near_exact.conf`:约 0.99 recall。 + +大 K 使用独立模板实例和 warp 共享内存堆;`warp_compact` 在 K≤10、 +11≤K≤50、K>50 时分别使用 8、2、1 个 warp。K=100 的单 warp 路径在 +RTX 4090 D 上比旧两 warp 路径快 9.7%–15.1%。局部 heap 进一步缓存根节点、 +以空穴下沉替代逐层交换,并让单 warp 直接写回有序结果;nprobe=160 的正式 +A/B 提升 2.40%,与 bucket-major 组合后累计提升 3.65%。K=100 的推荐配置 +进一步使用 `bucket_major_partitioned`:4 个 warp 各维护 40 项局部候选,再 +合并为 Top-100。`nprobe=160` 的 100 次 A/B 从 5503.11 提高到 7204.54 QPS, +提升 30.92%;输出逐字一致,recall@100 保持 0.91758,Compute Sanitizer 为 +0 errors。推荐从 +`ivf_flat_million_k50.conf` 或 +`ivf_flat_million_k100.conf` 开始;新平台实测默认 batch 分别为 40 和 64,并提供 +batch=8/32/64/128 以及 warp1/2/4/8 的 A/B 配置。百万级 K10 的 nlist=256 +三档配置默认 batch=64。切换数据、维度或 GPU 后仍应重新扫参。 + +K=50 先启用 `bucket_major`:GPU 将已选 probe 任务按中心桶分组,以 +提高同一 batch 内的 L2 复用。nprobe=160、batch=40 的 100 次 A/B 从 +6009.22 提高到 6964.16 QPS,提升 15.89%,recall@50 保持 0.92482。 +低 nprobe 时收益较小;原始 probe-major 基线可使用 +`ivf_flat_million_k50_warp_compact_batch40.conf`。完整扫描见 +`results/formal_4090d_20260908/k50_bucket_major_sweep.csv`。 +当前 `bucket_major` 和 `bucket_major_partitioned` 只支持固定 nprobe; +score-mass 自适应策略继续使用 +`warp_compact`。 + +K=50 默认配置在 bucket-major 上继续使用 4×16 分区局部 Top-K。固定 +batch=40、nprobe=160、预热 5 次并重复 100 次,完整 heap 为 7165.23 QPS, +4×16 为 7934.10 QPS,提升 10.73%,输出逐字一致,Compute Sanitizer 为 +0 errors。FAISS GPU IVF-Flat 为 8328.11 QPS / 0.92312 recall@50; +WarpFusion 为 7934.10 QPS / 0.92482 recall@50,吞吐差距为 4.97%。原始结果 +见 `results/formal_4090d_20260908/k50_partitioned_tight/` 和 +`results/formal_4090d_20260908/faiss_gpu_batch40.csv`。 + +### MNIST 真实数据验证 + +除百万规模合成数据外,项目提供 MNIST 转换脚本。训练图像作为数据库,测试 +图像作为查询,像素展开为 784 维 FP32 向量并使用 L2: + +```bash +python3 scripts/import_mnist.py \ + --input data/mnist/mnist.npz \ + --database data/mnist/database.bin \ + --queries data/mnist/queries.bin +``` + +RTX 4090 D 上,60k 数据库和 10k queries 的 Exact K=10 为 23.1k QPS; +IVF nprobe=8 达到 0.9784 recall@10 和 197.7k QPS,nprobe=32 达到 +0.9991 recall@10 和 76.6k QPS。原始数据见 +`results/formal_4090d_20260908/mnist_ivf.csv`。 + +这些 recall 只对应固定随机种子生成的测试数据。可用脚本在新数据或新 GPU +上重新生成 CSV,而不是沿用旧机器的结论: + +```bash +python3 scripts/benchmark_ivf_sweep.py \ + --search-binary ./build/ivf_search \ + --index data/million/inner_fp32_nlist256_spherical_100k15.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_batch64.conf \ + --exact results/million/inner_exact_gpu_k10.txt \ + --output-dir results/million/sweep_n256 \ + --csv results/million/sweep_n256.csv \ + --nlist 256 \ + --nprobes 64,128,160,192,224,256 \ + --training-samples 100000 \ + --training-iterations 15 +``` + +### 第六阶段公开真实数据 + +正式外部验证使用两套互补数据:TexMex SIFT1M(1,000,000 × 128,L2)和 +VIBE `yahoo-minilm-384-normalized`(677,305 × 384,文本 embedding, +cosine)。两者都带公开 Top-100 ground truth。准备脚本固定并验证公开文件 +校验和:SIFT archive MD5 为 `b23d1b3b2ee8469d819b61ca900ef0ed`,VIBE +HDF5 SHA-256 为 +`8b0519850249d7ea4aea258eb43ae837dca1bb2f7a85ee0a5145afdb699c4136`。 +VIBE 文件的 `distance=normalized` 会先经过逐块单位范数检查,再明确映射到 +WarpFusion cosine;不会把它静默当作普通 L2 数据。 + +```bash +python3 scripts/prepare_real_datasets.py \ + --dataset all \ + --raw-dir data/real/raw \ + --output-dir data/real +``` + +数据准备需要 NumPy 和 `h5py`。转换后的每套数据都包含 `database.bin`、 +`queries.bin`、`groundtruth.ivecs` 和记录输入/输出 SHA-256 的 +`manifest.json`。完整 K/nprobe 矩阵可用一条命令运行: + +```bash +python3 scripts/run_real_benchmarks.py \ + --dataset sift1m \ + --nlist 1024 \ + --nprobes 32,64,128,160,192,224 \ + --warmup 1 --repeat 5 + +python3 scripts/run_real_benchmarks.py \ + --dataset yahoo-minilm-384 \ + --nlist 1024 \ + --nprobes 32,64,128,160,192,224 \ + --warmup 1 --repeat 5 +``` + +2026-09-10 的 RTX 4090 D 正式结果已经完成。下表固定 `batch=64`、 +`nprobe=160`,同时列出各自独立训练、相同训练预算下的 FAISS GPU IVF-Flat: + +| 数据集 | K | WarpFusion recall / QPS | FAISS recall / QPS | 吞吐比 | +|---|---:|---:|---:|---:| +| SIFT1M | 10 | 0.999870 / 24579 | 0.999120 / 13617 | 1.81× | +| SIFT1M | 50 | 0.999706 / 19237 | 0.999516 / 13443 | 1.43× | +| SIFT1M | 100 | 0.999565 / 17362 | 0.999457 / 13102 | 1.33× | +| Yahoo MiniLM 384 | 10 | 0.993900 / 15733 | 0.995300 / 6216 | 2.53× | +| Yahoo MiniLM 384 | 50 | 0.991520 / 14950 | 0.991280 / 6157 | 2.43× | +| Yahoo MiniLM 384 | 100 | 0.989230 / 14196 | 0.989080 / 6060 | 2.34× | + +K=50 的 4×16 分区路径在 SIFT1M 和 Yahoo 上分别损失 0.000326 和 +0.000980 recall,均超过 `1e-4` 安全阈值,因此正式曲线自动采用完整 heap。 +K=100 的 4×40 路径在两套数据上均为零 recall 损失,`nprobe=160` 下相对 +完整 heap 分别加速 1.38× 和 1.72×。可提交的 CSV、验证 JSON 和 SVG 位于 +`results/real/`;原始 Top-K 输出和日志按数据集保留在实验机 `/data`。 + +该命令依次记录自研 IVF 建库、Exact K=10/50/100、公开 ground truth +交叉验证、自研与 FAISS GPU IVF 扫描、QPS、run/batch P50/P99、显存和图表。 +K=50/100 会同时运行分区局部 Top-K 与完整 heap;若任一 nprobe 的 recall +损失超过 `1e-4`,最终曲线自动回退到完整 heap,同时保留两套原始 CSV 和 +`partitioned_topk_validation.json`。结果写入 `results/real//`。 + +## FAISS 公平对照 + +`scripts/benchmark_faiss.py` 直接读取相同的项目数据文件,支持 +FAISS CPU/GPU、Flat/IVF-Flat、多个 K/nprobe,并把索引构建/加载、GPU +转移、稳定查询 QPS、run/batch P50/P99 及其样本数、recall、平均/最大绝对 +分数误差和 FAISS GPU 内存分类写入 CSV。 +运行它的 Python 环境需要 NumPy 和与当前 CUDA 环境兼容的 FAISS 包。 + +```bash +python3 scripts/benchmark_faiss.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --reference-results results/million/inner_exact_gpu_k100.txt \ + --index-dir data/million/faiss \ + --output-dir results/million/faiss_gpu \ + --csv results/million/faiss_gpu.csv \ + --backends gpu \ + --index-types flat,ivf_flat \ + --top-ks 10,50,100 \ + --nlist 256 \ + --nprobes 128,160,192,224 \ + --batch-size 64 \ + --train-samples 100000 \ + --iterations 15 \ + --seed 2026 \ + --warmup 1 \ + --repeat 5 +``` + +脚本默认将 FAISS CPU 线程数固定为 1;可用 `--cpu-threads` 显式改变。 +FAISS Flat 会先与 WarpFusion exact 结果交叉验证,候选 ID 不一致时终止。 +长矩阵每完成一项都会立即更新 CSV,中断时不会丢失已经完成的行。 + +## 实验性自适应 nprobe + +固定策略仍是默认。设置 `nprobe_policy=score_mass` 后,`nprobe` 表示允许的 +最大值;策略将排序后的中心分数转换为相对概率质量,并在 +`adaptive_nprobe_min..nprobe` 内按 `adaptive_nprobe_step` 选择每个 query +的实际 probe 数。`adaptive_temperature` 使用当前 query 的中心分数跨度归一化, +因此不依赖绝对分数尺度。 + +```bash +python3 scripts/benchmark_adaptive_nprobe.py \ + --search-binary ./build/ivf_search \ + --index data/million/inner_fp32_nlist256_spherical.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_adaptive_k10.conf \ + --exact results/million/inner_exact_gpu_k10.txt \ + --output-dir results/million/adaptive_k10 \ + --csv results/million/adaptive_k10.csv \ + --max-nprobe 224 --min-nprobe 64 --step 16 \ + --temperature 0.2 --target-masses 0.80,0.90,0.93,0.97,0.99 +``` + +百万级均匀合成数据上的首轮实验没有超过相同平均 probe 的固定策略:平均 +151.632 probes 的代表点在 K10/K50/K100 上分别慢约 1.0%/2.6%/3.6%, +recall 也略低。因此配置和脚本用于研究与复现,尚不作为推荐生产默认值。 +切换到更异质的真实查询分布后应重新校准并重新判断是否保留。 + +## 可选扩展:Agent 记忆检索 + +本节不属于当前课程项目主报告,只保留已经实现的实验接口。 + +元数据文件按原始向量 ID 保存 `timestamp`、`importance`、`session_id` 和 +`source_type`。`fused` 在桶扫描读取向量前执行过滤,并在局部 Top-K 前融合 +语义分数、重要性和指数时间衰减;`rerank` 先取语义 Top-(K×factor),再由 +独立 GPU kernel 过滤和重排,作为 A/B baseline。L2 仍保持分数越低越好, +内积和 Cosine 保持越高越好。 + +```bash +python3 scripts/generate_memory_metadata.py \ + --output data/memory.bin --num-vectors 100000 --seed 2026 + +./build/ivf_search \ + --index data/database.ivf --queries data/queries.bin \ + --params configs/ivf_flat_memory_fused.conf \ + --memory-metadata data/memory.bin --memory-mode fused \ + --filter-session-id any --filter-source-type 1 \ + --backend gpu --warmup 2 --repeat 5 \ + --output results/memory_fused.txt +``` + +使用 `scripts/benchmark_memory_modes.py` 可在完全相同的过滤、评分和批量参数 +下运行 fused/rerank 并保存 CSV。`any` 表示不限制对应的离散元数据字段; +若过滤后不足 K 个候选,输出会诚实返回少于 K 条,而不会写入伪造 ID。 + +索引使用版本化二进制格式,保存 FP32 聚类中心、桶 offsets、原始向量 ID +以及按桶连续排列的 FP32/FP16 原始向量。GPU backend 会将这些索引数据 +常驻显存;每批只上传 queries,中心选择、桶扫描和 Top-K 均在 GPU 完成。 + +GPU backend 会先创建常驻检索引擎,数据库只上传一次,然后让 +`--warmup` 和 `--repeat` 的每轮查询复用同一份 GPU 数据和工作区。 +程序分别输出: + +- GPU 一次性初始化和数据库 H2D 时间。 +- 估算冷启动端到端时间。 +- 数据库常驻后的查询时间和 QPS。 +- 引擎显式分配的 GPU 缓冲区总量。 +- query H2D、距离 kernel、Top-K kernel 和结果 D2H 分段时间。 + +`configs/exact_l2_batch*.conf` 保留生成完整距离矩阵的历史 batch 扫描配置。 +新实验推荐以 fused batch=64 配置为起点;融合路径会根据 batch size 调整每个 +query 的 chunk 数,使总并发块数维持在合理范围,同时避免产生过多局部候选。 +切换数据规模、维度或 GPU 后仍应重新扫描 batch size。 + +第七阶段新增 `exact_query_tile=2/4/8`,用于在同一 block 内跨 query 复用数据库 +读取;`exact_fused_blocks=N` 可固定 `grid.x` 做受控 sweep,省略时使用并行度 +启发式。RTX 4090 D、batch=64 的已验证选择为:K=10/128 维使用 tile4, +K=10/384 维使用 tile8/160 blocks,K=50/384 维使用 tile4;128 维 K=50 和 +全部 K=100 继续使用 tile1 baseline。切换维度、metric、batch 或 GPU 时必须 +重新运行 `scripts/benchmark_exact_query_tile.py`,不能直接套用该表。 + +## 项目原则 + +1. 正确性优先,每个 GPU 版本都和 CPU 参考答案比较。 +2. 先实现简单版本,再逐步优化;不直接堆叠难以解释的 CUDA 技巧。 +3. 每次优化都保存测试环境、参数和优化前后的性能数据。 +4. 扩展实验不得替代 Exact、IVF、FAISS 对照和真实数据主线。 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k100_batch64_querytile2.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k100_batch64_querytile2.conf new file mode 100644 index 00000000..4106adca --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k100_batch64_querytile2.conf @@ -0,0 +1,6 @@ +top_k = 100 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 2 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k100_batch64_querytile4.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k100_batch64_querytile4.conf new file mode 100644 index 00000000..6cb36a75 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k100_batch64_querytile4.conf @@ -0,0 +1,6 @@ +top_k = 100 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks128.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks128.conf new file mode 100644 index 00000000..25c741f5 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks128.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_layout = block_tile +exact_fused_blocks = 128 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks160.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks160.conf new file mode 100644 index 00000000..828aea18 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks160.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_layout = block_tile +exact_fused_blocks = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks192.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks192.conf new file mode 100644 index 00000000..7c9f80e7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks192.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_layout = block_tile +exact_fused_blocks = 192 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks64.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks64.conf new file mode 100644 index 00000000..fa43f2ac --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks64.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_layout = block_tile +exact_fused_blocks = 64 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks96.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks96.conf new file mode 100644 index 00000000..d005799d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_blocktile8_blocks96.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_layout = block_tile +exact_fused_blocks = 96 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile2.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile2.conf new file mode 100644 index 00000000..dbbec7c7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile2.conf @@ -0,0 +1,6 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 2 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4.conf new file mode 100644 index 00000000..ff75ac6f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4.conf @@ -0,0 +1,6 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks128.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks128.conf new file mode 100644 index 00000000..7c8f5a4d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks128.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 +exact_fused_blocks = 128 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks48.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks48.conf new file mode 100644 index 00000000..7d31b56b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks48.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 +exact_fused_blocks = 48 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks64.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks64.conf new file mode 100644 index 00000000..dead2159 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks64.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 +exact_fused_blocks = 64 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks80.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks80.conf new file mode 100644 index 00000000..0fbeedb9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks80.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 +exact_fused_blocks = 80 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks96.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks96.conf new file mode 100644 index 00000000..f54b17d1 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile4_blocks96.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 +exact_fused_blocks = 96 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8.conf new file mode 100644 index 00000000..a2f7d7b0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8.conf @@ -0,0 +1,6 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks128.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks128.conf new file mode 100644 index 00000000..9601480b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks128.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_blocks = 128 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks160.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks160.conf new file mode 100644 index 00000000..3b6c4f4f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks160.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_blocks = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks192.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks192.conf new file mode 100644 index 00000000..5efcd3ef --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks192.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_blocks = 192 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks96.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks96.conf new file mode 100644 index 00000000..c2acc8b3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k10_batch64_querytile8_blocks96.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 8 +exact_fused_blocks = 96 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k50_batch64_querytile2.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k50_batch64_querytile2.conf new file mode 100644 index 00000000..5c48d95b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k50_batch64_querytile2.conf @@ -0,0 +1,6 @@ +top_k = 50 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 2 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_fused_k50_batch64_querytile4.conf b/09_vector_retrieval/PurplePulse/configs/exact_fused_k50_batch64_querytile4.conf new file mode 100644 index 00000000..6ca99247 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_fused_k50_batch64_querytile4.conf @@ -0,0 +1,6 @@ +top_k = 50 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused +exact_query_tile = 4 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2.conf new file mode 100644 index 00000000..8fb50ceb --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 4096 +nprobe = 16 +pq_m = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_batch1.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch1.conf new file mode 100644 index 00000000..07d72bc7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch1.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 1 +distance_mode = warp +topk_mode = two_stage diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_batch128.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch128.conf new file mode 100644 index 00000000..083f5d34 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch128.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 128 +distance_mode = warp +topk_mode = two_stage diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_batch16.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch16.conf new file mode 100644 index 00000000..04c6fdec --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch16.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 16 +distance_mode = warp +topk_mode = two_stage diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_batch32.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch32.conf new file mode 100644 index 00000000..204df4d7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch32.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 32 +distance_mode = warp +topk_mode = two_stage diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_batch4.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch4.conf new file mode 100644 index 00000000..453bd98a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch4.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 4 +distance_mode = warp +topk_mode = two_stage diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_batch64.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch64.conf new file mode 100644 index 00000000..01b38e5e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_batch64.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = two_stage diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_block.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_block.conf new file mode 100644 index 00000000..514eb6ff --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_block.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 8 +distance_mode = simple +topk_mode = block +nlist = 4096 +nprobe = 16 +pq_m = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_k1.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_k1.conf new file mode 100644 index 00000000..bbb63d56 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_k1.conf @@ -0,0 +1,8 @@ +top_k = 1 +search_mode = exact +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 4096 +nprobe = 16 +pq_m = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_k100.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_k100.conf new file mode 100644 index 00000000..40924ce3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_k100.conf @@ -0,0 +1,8 @@ +top_k = 100 +search_mode = exact +batch_size = 8 +distance_mode = warp +topk_mode = block +nlist = 4096 +nprobe = 16 +pq_m = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_k50.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_k50.conf new file mode 100644 index 00000000..f3a67f82 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_k50.conf @@ -0,0 +1,8 @@ +top_k = 50 +search_mode = exact +batch_size = 8 +distance_mode = warp +topk_mode = block +nlist = 4096 +nprobe = 16 +pq_m = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_l2_simple.conf b/09_vector_retrieval/PurplePulse/configs/exact_l2_simple.conf new file mode 100644 index 00000000..3198d354 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_l2_simple.conf @@ -0,0 +1,8 @@ +top_k = 10 +search_mode = exact +batch_size = 8 +distance_mode = simple +topk_mode = simple +nlist = 4096 +nprobe = 16 +pq_m = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_million_k100_batch64.conf b/09_vector_retrieval/PurplePulse/configs/exact_million_k100_batch64.conf new file mode 100644 index 00000000..d9e10c47 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_million_k100_batch64.conf @@ -0,0 +1,5 @@ +top_k = 100 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = block diff --git a/09_vector_retrieval/PurplePulse/configs/exact_million_k100_fused_batch64.conf b/09_vector_retrieval/PurplePulse/configs/exact_million_k100_fused_batch64.conf new file mode 100644 index 00000000..e1038bf2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_million_k100_fused_batch64.conf @@ -0,0 +1,5 @@ +top_k = 100 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused diff --git a/09_vector_retrieval/PurplePulse/configs/exact_million_k10_fused_batch64.conf b/09_vector_retrieval/PurplePulse/configs/exact_million_k10_fused_batch64.conf new file mode 100644 index 00000000..a325885d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_million_k10_fused_batch64.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused diff --git a/09_vector_retrieval/PurplePulse/configs/exact_million_k1_batch128.conf b/09_vector_retrieval/PurplePulse/configs/exact_million_k1_batch128.conf new file mode 100644 index 00000000..ee839d09 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_million_k1_batch128.conf @@ -0,0 +1,7 @@ +top_k = 1 +search_mode = exact +batch_size = 128 +distance_mode = warp +topk_mode = two_stage +nlist = 1024 +nprobe = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/exact_million_k50_batch64.conf b/09_vector_retrieval/PurplePulse/configs/exact_million_k50_batch64.conf new file mode 100644 index 00000000..435ffa28 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_million_k50_batch64.conf @@ -0,0 +1,5 @@ +top_k = 50 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = block diff --git a/09_vector_retrieval/PurplePulse/configs/exact_million_k50_fused_batch64.conf b/09_vector_retrieval/PurplePulse/configs/exact_million_k50_fused_batch64.conf new file mode 100644 index 00000000..a7e5abdf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/exact_million_k50_fused_batch64.conf @@ -0,0 +1,5 @@ +top_k = 50 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat.conf new file mode 100644 index 00000000..b583256c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 1024 +nprobe = 16 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_balanced.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_balanced.conf new file mode 100644 index 00000000..951e0f09 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_balanced.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 64 +nprobe = 40 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_exact_check.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_exact_check.conf new file mode 100644 index 00000000..d2811b7e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_exact_check.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 64 +nprobe = 64 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_high_recall.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_high_recall.conf new file mode 100644 index 00000000..b31489bf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_high_recall.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 64 +nprobe = 56 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_scalar_baseline.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_scalar_baseline.conf new file mode 100644 index 00000000..518994ca --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_100k_scalar_baseline.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 8 +distance_mode = simple +topk_mode = two_stage +nlist = 64 +nprobe = 40 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_memory_fused.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_memory_fused.conf new file mode 100644 index 00000000..1a4b6911 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_memory_fused.conf @@ -0,0 +1,20 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp_compact +nlist = 256 +nprobe = 160 +nprobe_policy = fixed + +# Combined score keeps the native metric direction: lower is better for L2, +# higher is better for inner-product/cosine. +memory_mode = fused +memory_semantic_weight = 1.0 +memory_importance_weight = 0.15 +memory_recency_weight = 0.10 +memory_time_scale = 604800 +memory_now = 1702592000 +filter_min_timestamp = 0 +filter_session_id = any +filter_source_type = any +memory_rerank_factor = 4 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_memory_rerank.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_memory_rerank.conf new file mode 100644 index 00000000..27b4985e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_memory_rerank.conf @@ -0,0 +1,18 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp_compact +nlist = 256 +nprobe = 160 +nprobe_policy = fixed + +memory_mode = rerank +memory_semantic_weight = 1.0 +memory_importance_weight = 0.15 +memory_recency_weight = 0.10 +memory_time_scale = 604800 +memory_now = 1702592000 +filter_min_timestamp = 0 +filter_session_id = any +filter_source_type = any +memory_rerank_factor = 4 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k10.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k10.conf new file mode 100644 index 00000000..3e640f0d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k10.conf @@ -0,0 +1,13 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 224 +nprobe_policy = score_mass +adaptive_execution = masked +adaptive_nprobe_min = 64 +adaptive_nprobe_step = 16 +adaptive_target_mass = 0.93 +adaptive_temperature = 0.2 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k100.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k100.conf new file mode 100644 index 00000000..ec05a96f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k100.conf @@ -0,0 +1,13 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 224 +nprobe_policy = score_mass +adaptive_execution = masked +adaptive_nprobe_min = 64 +adaptive_nprobe_step = 16 +adaptive_target_mass = 0.93 +adaptive_temperature = 0.2 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k50.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k50.conf new file mode 100644 index 00000000..5515ed54 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_adaptive_k50.conf @@ -0,0 +1,13 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 32 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 224 +nprobe_policy = score_mass +adaptive_execution = masked +adaptive_nprobe_min = 64 +adaptive_nprobe_step = 16 +adaptive_target_mass = 0.93 +adaptive_temperature = 0.2 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_balanced.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_balanced.conf new file mode 100644 index 00000000..6d5be5dd --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_balanced.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 128 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch1.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch1.conf new file mode 100644 index 00000000..7eb1a2d8 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch1.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 1 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch128.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch128.conf new file mode 100644 index 00000000..00a295c0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch128.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 128 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch16.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch16.conf new file mode 100644 index 00000000..93742a69 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch16.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 16 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch32.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch32.conf new file mode 100644 index 00000000..5915b9a5 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch32.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 32 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch64.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch64.conf new file mode 100644 index 00000000..17bbf0b4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch64.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch8.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch8.conf new file mode 100644 index 00000000..e2bbe468 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_batch8.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_fast.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_fast.conf new file mode 100644 index 00000000..a07d9c3e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_fast.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 16 +distance_mode = warp +topk_mode = two_stage +nlist = 512 +nprobe = 128 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_high_recall.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_high_recall.conf new file mode 100644 index 00000000..fb359f37 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_high_recall.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 192 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k1.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k1.conf new file mode 100644 index 00000000..1fb218d0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k1.conf @@ -0,0 +1,7 @@ +top_k = 1 +search_mode = ivf_flat +batch_size = 16 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100.conf new file mode 100644 index 00000000..80ea98e4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major_partitioned +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch128.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch128.conf new file mode 100644 index 00000000..095aa291 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch128.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 128 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch32.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch32.conf new file mode 100644 index 00000000..ad358310 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch32.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 32 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch64.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch64.conf new file mode 100644 index 00000000..60fb1c9e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch64.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch8.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch8.conf new file mode 100644 index 00000000..67f9b1a7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_batch8.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_bucket_major.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_bucket_major.conf new file mode 100644 index 00000000..793978f4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_bucket_major.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_partitioned.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_partitioned.conf new file mode 100644 index 00000000..80ea98e4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_partitioned.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major_partitioned +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp1.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp1.conf new file mode 100644 index 00000000..85650101 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp1.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp1 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp2.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp2.conf new file mode 100644 index 00000000..8be75cbe --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp2.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp2 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp4.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp4.conf new file mode 100644 index 00000000..af38607d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp4.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp4 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp8.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp8.conf new file mode 100644 index 00000000..411acdec --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k100_warp8.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp8 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50.conf new file mode 100644 index 00000000..ea85ffdf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = bucket_major_partitioned4x16 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch128.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch128.conf new file mode 100644 index 00000000..b044c307 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch128.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 128 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch32.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch32.conf new file mode 100644 index 00000000..903fc1c2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch32.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 32 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch64.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch64.conf new file mode 100644 index 00000000..7a3526bc --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch64.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch8.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch8.conf new file mode 100644 index 00000000..d29500b6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_batch8.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 8 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_bucket_major.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_bucket_major.conf new file mode 100644 index 00000000..1814c11b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_bucket_major.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = bucket_major +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_2x32.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_2x32.conf new file mode 100644 index 00000000..43d17367 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_2x32.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = bucket_major_partitioned2 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_4x16.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_4x16.conf new file mode 100644 index 00000000..ea85ffdf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_4x16.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = bucket_major_partitioned4x16 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_4x20.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_4x20.conf new file mode 100644 index 00000000..35266f7b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_4x20.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = bucket_major_partitioned +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_8x8.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_8x8.conf new file mode 100644 index 00000000..a93741ea --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_partitioned_8x8.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = bucket_major_partitioned8x8 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp1.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp1.conf new file mode 100644 index 00000000..deeffcd8 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp1.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp1 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp2.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp2.conf new file mode 100644 index 00000000..46493326 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp2.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp2 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp4.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp4.conf new file mode 100644 index 00000000..7c41fc93 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp4.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp4 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp8.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp8.conf new file mode 100644 index 00000000..ae2d3f30 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp8.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp8 +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp_compact_batch40.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp_compact_batch40.conf new file mode 100644 index 00000000..0fb56e3c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_k50_warp_compact_batch40.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 40 +distance_mode = warp_compact +topk_mode = two_stage +nlist = 256 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_near_exact.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_near_exact.conf new file mode 100644 index 00000000..993e0235 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_million_near_exact.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 224 diff --git a/09_vector_retrieval/PurplePulse/configs/ivf_flat_mnist.conf b/09_vector_retrieval/PurplePulse/configs/ivf_flat_mnist.conf new file mode 100644 index 00000000..41f41723 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/ivf_flat_mnist.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 128 +distance_mode = warp +topk_mode = two_stage +nlist = 256 +nprobe = 32 diff --git a/09_vector_retrieval/PurplePulse/configs/real_exact_k10.conf b/09_vector_retrieval/PurplePulse/configs/real_exact_k10.conf new file mode 100644 index 00000000..a325885d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_exact_k10.conf @@ -0,0 +1,5 @@ +top_k = 10 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused diff --git a/09_vector_retrieval/PurplePulse/configs/real_exact_k100.conf b/09_vector_retrieval/PurplePulse/configs/real_exact_k100.conf new file mode 100644 index 00000000..e1038bf2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_exact_k100.conf @@ -0,0 +1,5 @@ +top_k = 100 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused diff --git a/09_vector_retrieval/PurplePulse/configs/real_exact_k50.conf b/09_vector_retrieval/PurplePulse/configs/real_exact_k50.conf new file mode 100644 index 00000000..a7e5abdf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_exact_k50.conf @@ -0,0 +1,5 @@ +top_k = 50 +search_mode = exact +batch_size = 64 +distance_mode = warp +topk_mode = fused diff --git a/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k10.conf b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k10.conf new file mode 100644 index 00000000..59b8b5b4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k10.conf @@ -0,0 +1,7 @@ +top_k = 10 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major +topk_mode = two_stage +nlist = 1024 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k100.conf b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k100.conf new file mode 100644 index 00000000..a3d9dff7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k100.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major_partitioned +topk_mode = two_stage +nlist = 1024 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k100_safe.conf b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k100_safe.conf new file mode 100644 index 00000000..f825ea00 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k100_safe.conf @@ -0,0 +1,7 @@ +top_k = 100 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major +topk_mode = two_stage +nlist = 1024 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k50.conf b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k50.conf new file mode 100644 index 00000000..bbfb2abb --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k50.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major_partitioned4x16 +topk_mode = two_stage +nlist = 1024 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k50_safe.conf b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k50_safe.conf new file mode 100644 index 00000000..6aa8e5b3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/configs/real_ivf_nlist1024_k50_safe.conf @@ -0,0 +1,7 @@ +top_k = 50 +search_mode = ivf_flat +batch_size = 64 +distance_mode = bucket_major +topk_mode = two_stage +nlist = 1024 +nprobe = 160 diff --git a/09_vector_retrieval/PurplePulse/docs/API.md b/09_vector_retrieval/PurplePulse/docs/API.md new file mode 100644 index 00000000..51a27cd4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/API.md @@ -0,0 +1,127 @@ +# WarpFusion CLI 与 C++ API + +本文给出面向使用者的最小稳定接口。二进制向量格式、完整参数和正式实验口径见 +[`REPRODUCIBILITY.md`](REPRODUCIBILITY.md);性能结论见 +[`FINAL_REPORT.md`](FINAL_REPORT.md)。 + +## CLI + +### Exact 查询 + +```bash +./build/vector_search \ + --database data/database.bin \ + --queries data/queries.bin \ + --params configs/real_exact_k10.conf \ + --backend gpu \ + --warmup 1 \ + --repeat 5 \ + --output results/exact.txt +``` + +`--backend` 可取 `cpu` 或 `gpu`。GPU 路径在进程内常驻数据库和工作区, +`--warmup` 不计入正式测量,`--repeat` 的各轮共享同一个执行器。输出每行是 +`query_id vector_id score`;同一 query 内按最好到最差排序,相同分数按较小 +vector ID 排序。 + +### IVF-Flat 建库与查询 + +```bash +./build/ivf_build \ + --database data/database.bin \ + --output data/database.ivf \ + --nlist 1024 \ + --iterations 15 \ + --training-samples 100000 \ + --threads 16 + +./build/ivf_search \ + --index data/database.ivf \ + --queries data/queries.bin \ + --params configs/real_ivf_nlist1024_k10.conf \ + --nprobe 160 \ + --backend gpu \ + --warmup 1 \ + --repeat 5 \ + --output results/ivf.txt +``` + +建库和查询的 `nlist` 必须一致;`nprobe` 的合法范围是 `1..nlist`。CLI 的 +`--nprobe` 会覆盖配置文件,便于扫描质量—吞吐曲线。`nprobe=nlist` 可用于 +完整性检查,不代表推荐的近似检索配置。 + +所有 CLI 在参数缺失、输入格式不合法、维度/dtype/metric 不匹配或配置越界时 +返回非零退出码并向标准错误输出原因。上层服务应检查退出码,不应只判断输出 +文件是否存在。 + +## C++ API + +公开头文件位于 `include/`,命名空间保持为空以兼容现有 CLI。调用者负责保证 +数据库、查询和参数在执行器生命周期内语义一致;执行器不可复制但可移动。 + +### 常驻 Exact 执行器 + +```cpp +#include "file_io.h" +#include "search.h" + +VectorDatabase database = readVectorDatabase("data/database.bin"); +QuerySet initial = readQuerySet("data/queries.bin"); +SearchParams params = readSearchParams("configs/real_exact_k10.conf"); +validateInputs(database, initial, params); + +GpuExactSearchEngine engine(database, initial, params); +SearchStats stats; +SearchResults neighbors = engine.search(initial, &stats); + +double one_time_upload_ms = engine.databaseH2DMilliseconds(); +std::size_t resident_bytes = engine.deviceBytes(); +``` + +构造函数完成数据库上传与工作区分配;后续 `search()` 只上传 queries 并复用 +常驻状态。`SearchStats` 分离 query H2D、距离/局部 Top-K、最终归并、结果 D2H +和 batch 延迟。只需一次查询时也可以调用 `gpuExactSearch()`;CPU 参考为 +`cpuExactSearch()`。 + +### 常驻 IVF-Flat 执行器 + +```cpp +#include "file_io.h" +#include "ivf_flat.h" + +IvfFlatIndex index = readIvfFlatIndex("data/database.ivf"); +QuerySet queries = readQuerySet("data/queries.bin"); +SearchParams params = readSearchParams("configs/real_ivf_nlist1024_k10.conf"); + +GpuIvfFlatSearchEngine engine(index, queries, params); +SearchStats stats; +SearchResults neighbors = engine.search(queries, &stats); + +double one_time_upload_ms = engine.indexH2DMilliseconds(); +std::size_t resident_bytes = engine.deviceBytes(); +``` + +索引也可通过 `buildIvfFlatIndex()` 在进程内构建,并用 +`writeIvfFlatIndex()`/`readIvfFlatIndex()` 持久化。`cpuIvfFlatSearch()` 是 +正确性参考;`recallAtK(exact, approximate)` 计算候选 ID 集合 recall。 + +### 数据与结果对象 + +- `VectorDatabase`/`QuerySet` 支持 FP32 和 FP16 存储;计算使用 FP32 累加。 +- `Metric` 支持 L2、inner product 和 cosine;L2 分数越小越好,另外两种越大 + 越好。 +- `SearchResults` 是按 query 分组的 `Neighbor{id, score}` 列表。 +- `resultsMatch()` 用候选 ID 与分数容差比较两组 Exact 结果。 +- `SearchStats` 中所有时间字段单位为毫秒;一次性数据库/索引上传不计入稳定 + 查询 QPS。 + +## 默认选择与适用范围 + +Exact 默认使用 `distance_mode=warp`。正式大规模配置使用 +`topk_mode=fused`;未经当前维度、K 和 GPU 验证的 query tile 会安全回退到 +`exact_query_tile=1`。IVF 默认使用固定 `nprobe`;`score_mass` 是实验接口, +不是通用默认值。完整的 K/维度选择表与回退规则见 +[`STABILITY_MATRIX.md`](STABILITY_MATRIX.md)。 + +当前 API 是单进程、单 GPU、内存内静态索引接口;不提供 ABI 稳定承诺、并发 +请求调度、增量增删、压缩索引、超显存分片或多 GPU 协调。 diff --git a/09_vector_retrieval/PurplePulse/docs/BASELINE_RESULTS.md b/09_vector_retrieval/PurplePulse/docs/BASELINE_RESULTS.md new file mode 100644 index 00000000..8ff9e65b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/BASELINE_RESULTS.md @@ -0,0 +1,856 @@ +# Baseline 实验记录 + +> 本文记录开发过程中的初步结果,不是最终提交数据。最终实验需要预热、重复运行, +> 并分别统计数据传输、距离 kernel 和 Top-K kernel 时间。 + +## 环境 + +- GPU:NVIDIA GeForce RTX 5090,32607 MiB +- Compute Capability:12.0 +- CUDA Toolkit:13.3 +- CUDA 架构参数:`CMAKE_CUDA_ARCHITECTURES=120` +- C++:GCC 13.3 + +## 2026-08-28:精确检索第一轮 + +参数: + +- 数据库:100,000 个 FP32 向量 +- 维度:128 +- 查询数:100 +- metric:L2(输出平方 L2 距离) +- K:10 +- batch size:8 + +| 实现 | 总时间(ms) | QPS | 说明 | +|---|---:|---:|---| +| CPU reference | 770.509 | 129.784 | `nth_element` 后排序 Top-K | +| GPU 距离 + CPU Top-K | 432.908 | 230.996 | 会把完整距离矩阵复制回 CPU | +| GPU + 单线程 Top-K,sm_120 | 715.431 | 139.776 | 每个 query 只有一个线程选 Top-K | +| GPU + block Top-K,sm_120 | 288.316 | 346.841 | 256 个线程共同归约,重复 K 轮 | + +正确性:100 个 query 的 Top-10 ID 与 CPU reference 全部相同;由于 CPU/GPU +浮点指令顺序不同,观察到的最大分数误差约为 `1.14e-5`。 + +## 初步结论 + +1. 把代码放到 GPU 上不代表更快。单线程 GPU Top-K 成为明显瓶颈。 +2. block 内线程协作使端到端时间相对单线程 Top-K 降低约 59.7%。 +3. 当前 block Top-K 会重复扫描距离数组 K 次。K=50/100 时预计会成为新瓶颈, + 后续需要分块候选和两阶段归并,但应先完成正式的分段计时。 +4. 最初构建缓存错误使用 `sm_75`;RTX 5090 必须显式使用 `sm_120`,否则实验不公平。 + +## 2026-08-28:预热与分段计时 + +在同一 `100,000 × 128` 数据集上,预热 1 次并重复 5 次,block Top-10 的结果为: + +- 平均总时间:约 14.04 ms +- QPS:约 7,123 +- 数据库 H2D:约 2.37 ms +- 距离 kernel:约 2.98 ms +- Top-K kernel:约 7.67 ms + +这说明首次运行中的约 200 ms CUDA Runtime 初始化不能计入稳定吞吐,且 Top-K 已超过 +距离计算,成为主要 kernel 瓶颈。 + +### K 对性能的影响 + +数据规模仍为 100,000 个向量、100 queries,预热后重复测量: + +| K | 平均总时间(ms) | QPS | 距离 kernel(ms) | Top-K kernel(ms) | +|---:|---:|---:|---:|---:| +| 1 | 7.28 | 13,737 | 2.98 | 0.80 | +| 10 | 14.04 | 7,123 | 2.98 | 7.67 | +| 50 | 46.13 | 2,168 | 3.01 | 38.19 | +| 100 | 83.43 | 1,199 | 3.01 | 76.45 | + +重复扫描版本的 Top-K 时间近似随 K 线性增加,因此不能作为最终 Top-K 方案。 + +## 2026-08-28:两阶段 Top-K + +新版本先让 256 个线程各自保留局部 Top-K,再只对 `256 × K` 个候选进行最终归并。 + +| 数据规模 | 旧 block Top-K(ms) | 两阶段 Top-K(ms) | Top-K 降幅 | +|---|---:|---:|---:| +| 100k vectors,100 queries | 7.67 | 5.08 | 33.8% | +| 1M vectors,1000 queries | 826.07 | 424.09 | 48.7% | + +官方规模初测(1M vectors、dim=128、1000 queries、K=10、batch=8): + +- 平均端到端时间:950.26 ms +- QPS:1,052.34 +- 距离 kernel:427.00 ms +- 两阶段 Top-K:424.09 ms +- batch P50/P99:6.84 / 6.88 ms + +百万级完整 GPU 运行已经通过。另取相同数据库的前 10 个 query 与单线程 CPU reference +逐项比较,Top-10 ID、分数和顺序完全一致。 + +当前 QPS 仍包含每次调用重新分配显存和上传约 489 MiB 数据库的时间;最终报告需要同时给出 +冷启动端到端性能和数据库常驻显存后的查询性能。 + +## 2026-08-28:warp 协作距离计算 + +原始距离 kernel 由一个线程串行计算一个 128 维距离。优化版由一个 warp 共同处理一个向量, +不同 lane 读取相邻维度,并使用 shuffle 完成归约。 + +| 数据规模 | simple 距离 kernel(ms) | warp 距离 kernel(ms) | 距离计算降幅 | +|---|---:|---:|---:| +| 100k vectors,100 queries | 3.00 | 1.09 | 63.6% | +| 1M vectors,1000 queries | 427.00 | 305.65 | 28.4% | + +在官方规模上,平均端到端时间由约 950.26 ms 降到 825.05 ms,QPS 从约 1,052 +提升到 1,212。由于 warp 归约改变了 FP32 加法顺序,10-query 全库验证中的最大距离误差为 +`2.29e-5`,Top-10 ID 集合和顺序不变。 + +当前最大 kernel 瓶颈再次变为 Top-K(约 424 ms),下一阶段应改进局部候选的选择方法, +而不是继续微调距离 kernel。 + +## 2026-08-28:新 GPU 迁移与 FP16 验证 + +新环境: + +- GPU:NVIDIA GeForce RTX 4090 D,24564 MiB +- Compute Capability:8.9 +- Driver:570.124.06 +- CUDA Toolkit:12.8.93 +- 编译架构:`sm_89` + +完整 CUDA 编译和 CTest 通过,`compute-sanitizer --tool memcheck` +报告 0 个错误。测试同时覆盖 FP32/FP16、L2/内积/Cosine 和 +simple/block/two-stage Top-K。 + +### FP16 存储与性能 + +FP16 文件在 CPU 和 GPU 都保持 binary16 存储,距离 kernel 加载后 +转 FP32 累加。在 `1M × 128`、1000 queries、K=10、batch=8、预热 1 次、 +重复 5 次的冒烟测试中: + +| dtype | 总时间(ms) | QPS | 数据库 H2D(ms) | 距离 kernel(ms) | Top-K(ms) | +|---|---:|---:|---:|---:|---:| +| FP32 | 1018.70 | 981.64 | 101.64 | 539.06 | 367.91 | +| FP16 | 692.42 | 1444.21 | 42.48 | 273.15 | 368.06 | + +FP16 的 QPS 相对 FP32 提高约 47.1%,数据库文件和显存存储减半。 +Top-K 时间基本不变,符合它仍使用 FP32 分数矩阵的实现。 + +正确性验证使用同一百万向量库的前 10 个 query 做 CPU/GPU 全库对照: +FP32 最大分数误差约 `2.29e-5`,FP16 约 `3.43e-5`;两者的 +Top-10 ID 集合和顺序均完全一致。K=100 也已对 FP32/FP16 做 CPU/GPU +对照,候选集合和顺序一致,最大分数误差约 `4.58e-5`。因此验证 +脚本默认绝对容差调整为 `5e-5`。 + +> 以上仍是功能与迁移冒烟测试,不是最终成绩。正式对比还需固定频率、 +> 拆分冷启动/常驻数据库路径,并进行更多次重复。 + +## 2026-08-28:数据库常驻 GPU + +新增 `GpuExactSearchEngine`,在初始化时一次性分配 GPU 工作区并上传数据库。 +预热和每轮重复查询只传输 query 和 Top-K 结果,不再重复分配显存或 +上传数据库。原有 `gpuExactSearch` 一次性 API 仍保留。 + +环境和数据与上一节一致:`1M × 128`、1000 queries、K=10、batch=8, +预热 1 次、重复 5 次。 + +| dtype | 初始化(ms) | 一次性 DB H2D(ms) | 常驻查询(ms) | 常驻 QPS | 估算冷启动(ms) | +|---|---:|---:|---:|---:|---:| +| FP32 | 157.62 | 52.57 | 912.23 | 1096.22 | 1069.84 | +| FP16 | 115.39 | 23.45 | 645.90 | 1548.23 | 761.28 | + +与改造前每轮重新创建 GPU 缓冲区和上传数据库的口径相比: + +- FP32:约 1018.70 ms / 981.64 QPS → 912.23 ms / 1096.22 QPS。 +- FP16:约 692.42 ms / 1444.21 QPS → 645.90 ms / 1548.23 QPS。 + +新旧路径的 1000-query Top-K ID 和分数逐值完全一致。CTest 增加同一 +常驻引擎连续查询两次的确定性检查,compute-sanitizer 仍为 0 个错误。 + +当前稳定查询的主要耗时已清晰拆分为距离 kernel 和 Top-K kernel; +下一步可以在不受重复 H2D 干扰的口径下优化 Top-K,并进行 ncu/nsys 分析。 + +## 2026-08-28:nsys 分析与局部 Top-K 优化 + +Nsight Compute 2025.1 可执行,但平台禁止访问 GPU performance counters, +返回 `ERR_NVGPUCTRPERM`。该权限需宿主机管理员开启,容器内无法解决。 +因此改用 Nsight Systems 2024.6.2 获取 CUDA 时间线,并用 +`cuobjdump --dump-resource-usage` 检查 kernel 资源。 + +### 瓶颈证据 + +在 `100k × 128`、100 queries、K=10、batch=8 上,时间线同时覆盖 +预热和测量各 1 次,共 26 个 batch kernel 实例: + +| kernel | 优化前总时间(ms) | 优化前单次(µs) | kernel 时间占比 | +|---|---:|---:|---:| +| 局部候选 | 11.039 | 424.58 | 76.0% | +| warp 距离 | 3.099 | 119.21 | 21.3% | +| 最终 block 归并 | 0.383 | 14.72 | 2.6% | + +瓶颈不在最终归并,而在局部候选。原实现对每个候选从最优位置开始 +扫描 K 个已排序槽位,即使候选无法进入 Top-K,也通常需要 K 次比较。 + +### 优化方法 + +1. 局部 Top-K 改为无序数组,只记录当前最差槽位。 +2. 普通候选只比较一次;真正替换最差项时,才扫描 K 项重算最差槽位。 +3. 最终 block 归并本来就不依赖局部有序,因此不改变结果语义。 +4. 为常用 K=1/10 生成编译期特化 kernel,其他 K 保留通用路径。 + +无序候选版 nsys 复测中,局部候选 kernel 单次平均降至 +`205.95 µs`,相比 `424.58 µs` 降低约 51.5%。最终归并仍为 +约 `14.70 µs`。K=10 模板特化在百万规模上又将 Top-K 从约 +183.85 ms 降到 178.81 ms。K=1 特化 kernel 的 thread stack 从通用路径的 +128 字节降为 0。 + +### 百万规模收益 + +数据、参数和 RTX 4090 D 环境与前一节相同: + +| dtype | 常驻查询优化前(ms) | 优化后(ms) | Top-K 优化前(ms) | 优化后(ms) | QPS 优化前 | 优化后 | +|---|---:|---:|---:|---:|---:|---:| +| FP32 | 912.23 | 722.21 | 368.23 | 178.81 | 1096.22 | 1384.64 | +| FP16 | 645.90 | 456.00 | 368.11 | 178.87 | 1548.23 | 2193.01 | + +Top-K 阶段降低约 51.4%。端到端常驻查询中,FP32 QPS 提高约 +26.3%,FP16 QPS 提高约 41.6%。优化前后 1000-query 的 Top-K ID +和分数逐值完全一致;FP32/FP16 的 CPU/GPU 测试、K=1/10 测试和 +compute-sanitizer 均通过。 + +优化后 FP32 的主要瓶颈转为距离 kernel(约 539 ms);FP16 中距离 +kernel 约 273 ms,Top-K 约 179 ms。后续 Top-K 继续优化的边际收益已降低, +应先完成 batch size 扫描和距离 kernel 分析,再决定是否继续专项调优。 + +## 2026-08-28:batch size 扫描 + +固定 `1M × 128`、1000 queries、K=10、warp 距离、优化后 two-stage Top-K, +预热 1 次并重复 5 次。扫描 batch=1/4/8/16/32/64/128: + +### FP32 + +| batch | 常驻时间(ms) | QPS | 距离(ms) | Top-K(ms) | batch P50(ms) | batch P99(ms) | +|---:|---:|---:|---:|---:|---:|---:| +| 1 | 1910.51 | 523.42 | 545.33 | 1332.02 | 1.90 | 1.92 | +| 4 | 902.93 | 1107.51 | 539.36 | 354.78 | 3.60 | 3.63 | +| 8 | 722.68 | 1383.75 | 538.94 | 178.86 | 5.77 | 5.79 | +| 16 | 632.31 | 1581.49 | 538.73 | 90.73 | 10.09 | 10.14 | +| 32 | 587.26 | 1702.83 | 538.58 | 47.24 | 18.74 | 18.78 | +| 64 | 563.47 | 1774.73 | 538.49 | 23.71 | 35.98 | 37.91 | +| 128 | 552.09 | 1811.28 | 538.46 | 12.49 | 70.54 | 72.96 | + +### FP16 + +| batch | 常驻时间(ms) | QPS | 距离(ms) | Top-K(ms) | batch P50(ms) | batch P99(ms) | +|---:|---:|---:|---:|---:|---:|---:| +| 1 | 1577.50 | 633.91 | 277.02 | 1269.03 | 1.57 | 1.59 | +| 4 | 637.30 | 1569.11 | 274.05 | 354.86 | 2.54 | 2.56 | +| 8 | 456.53 | 2190.44 | 273.06 | 179.00 | 3.64 | 3.66 | +| 16 | 365.82 | 2733.60 | 272.74 | 90.96 | 5.83 | 5.85 | +| 32 | 320.96 | 3115.70 | 272.49 | 47.24 | 10.22 | 10.25 | +| 64 | 296.98 | 3367.19 | 272.44 | 23.78 | 18.95 | 18.99 | +| 128 | 285.39 | 3503.96 | 272.40 | 12.54 | 36.48 | 36.51 | + +距离 kernel 的总时间从 batch=4 起几乎不变;Top-K 总时间随 batch +增大快速下降,主要是更少的 kernel 启动和更多同时处理的 query。 +batch=128 时,FP32 已达到仅由距离 kernel 时间估算的最大吞吐的约 +97.5%,FP16 约 95.4%;继续增大 batch 的吞吐空间很小,却会继续增加 +工作区显存和单 batch 延迟。 + +建议保留三档: + +- batch=8:低延迟。 +- batch=32:平衡吞吐和延迟。 +- batch=128:离线最大吞吐。 + +batch=1 和 batch=128 的 FP32/FP16 结果逐值完全一致。 + +## 2026-08-31:切换实例后的边界与三度量复验 + +在新的 GPU 实例上从干净构建目录重新配置 `sm_89` Release 版本。CTest +全部通过,`compute-sanitizer --tool memcheck` 报告 0 个错误。测试覆盖: + +- FP32/FP16 与 L2、内积、Cosine 三种度量。 +- simple/warp 两种距离 kernel,以及 simple/block/two-stage 三种 Top-K。 +- Cosine 零向量语义、相同分数按较小 ID 打破平局。 +- `top_k = num_vectors`、查询数不能被 batch size 整除的尾批。 +- `top_k=0`、`batch_size=0`、空输入、元数据长度不一致。 +- 错误 magic/version、截断文件和额外尾部字节。 + +中等规模复验使用 `100,000 × 128` FP32 数据库、101 queries、K=10、 +batch=8;GPU 预热 1 次并重复 5 次: + +| metric | CPU(ms) | GPU 常驻(ms) | GPU QPS | 距离 kernel(ms) | Top-K(ms) | 最大分数误差 | +|---|---:|---:|---:|---:|---:|---:| +| inner product | 1872.35 | 5.480 | 18431.9 | 2.324 | 2.698 | `9.6e-6` | +| cosine | 3461.35 | 5.480 | 18429.5 | 2.341 | 2.707 | `2.68e-7` | + +两种度量的 GPU Top-10 候选集合和排序均与 CPU reference 一致,101 +queries 也实际经过最后一个非满 batch。这里的结果用于迁移和正确性复验, +不替代前面的百万规模吞吐实验。 + +## 2026-08-31:IVF-Flat CPU 正确性基线 + +完成确定性采样 k-means、连续倒排桶布局、版本化索引保存/加载、固定 +`nprobe` 查询与 recall@K 工具。单元测试覆盖 FP32/FP16 与三种 metric; +`nprobe=nlist` 的结果与 exact reference 逐值一致。 + +首轮真实数据使用 100,000 × 128 FP32 inner-product 数据库、101 queries、 +K=10。索引参数为 nlist=64、训练样本 10,000、8 次迭代: + +- 构建时间:1264.19 ms;保存时间:28.05 ms。 +- 索引文件:52,033,320 bytes。 +- 桶大小 min/avg/max:1426 / 1562.5 / 1718;空桶为 0。 + +CPU 查询预热 1 次、重复 3 次: + +| nprobe | 平均查询(ms) | QPS | recall@10 | 最低单 query recall | +|---:|---:|---:|---:|---:| +| 1 | 29.50 | 3423.99 | 0.0782 | 0.0 | +| 2 | 54.74 | 1845.23 | 0.1406 | 0.0 | +| 4 | 108.05 | 934.79 | 0.2327 | 0.0 | +| 8 | 216.44 | 466.65 | 0.3614 | 0.0 | +| 16 | 431.13 | 234.27 | 0.5455 | 0.2 | +| 32 | 862.91 | 117.05 | 0.8119 | 0.4 | +| 64 | 1734.85 | 58.22 | 1.0000 | 1.0 | + +这是 CPU 算法与质量基线,不是最终 IVF 性能。下一步将索引常驻 GPU, +并把中心选择、候选距离和 Top-K 移到 GPU 后重新绘制 recall—QPS 曲线。 + +## 2026-08-31:GPU IVF-Flat 第一版与 block 并行 + +第一版将索引向量和原始 ID 常驻显存,CPU 根据聚类中心选择探测桶并上传 +候选位置,GPU 融合执行候选距离和 Top-K。教学 baseline 每个 query 仅使用 +一个 CUDA 线程;nprobe=16 时耗时 905.79 ms,其中 kernel 888.03 ms, +比 CPU IVF 更慢。 + +优化版改为每个 query 一个 256-thread block。各线程并行扫描候选,使用 +“无序局部 Top-K + 当前最差槽位”保留局部结果,再通过共享内存归约最终 +Top-K。nprobe=16 降到 27.17 ms,相对单线程 GPU 版本加速约 33.3 倍, +相对同 recall 的 CPU IVF(431.13 ms)加速约 15.9 倍。 + +数据、索引和质量口径与上一节相同,GPU 预热 1 次、重复 5 次: + +| nprobe | GPU 查询(ms) | GPU QPS | recall@10 | CPU IVF(ms) | +|---:|---:|---:|---:|---:| +| 1 | 3.79 | 26623.0 | 0.0782 | 29.50 | +| 2 | 5.34 | 18906.2 | 0.1406 | 54.74 | +| 4 | 8.45 | 11950.9 | 0.2327 | 108.05 | +| 8 | 14.69 | 6876.6 | 0.3614 | 216.44 | +| 16 | 27.17 | 3717.8 | 0.5455 | 431.13 | +| 32 | 63.43 | 1592.4 | 0.8119 | 862.91 | +| 64 | 127.17 | 794.2 | 1.0000 | 1734.85 | + +所有 nprobe 的候选集合、顺序和分数均与 CPU IVF 一致;FP32/FP16、 +三种 metric 的自动测试通过,compute-sanitizer 报告 0 个错误。 + +当前版本仍不是最终 GPU IVF:nprobe=64 全探测明显慢于优化后的 exact GPU。 +分段计时显示 nprobe=32 时 CPU 桶选择约 18.91 ms、候选位置 H2D 约 +3.03 ms、GPU 扫描约 34.57 ms。下一步应把中心选择和桶展开迁到 GPU, +并用多个 block/warp 共同处理一个 query,而不是继续优化单 block 内细节。 + +## 2026-08-31:全 GPU 中心选择与每桶 block 扫描 + +第二版把 centers 和 bucket offsets 也常驻显存。查询流水线变为: + +1. GPU 计算 query 与全部中心的分数并选择 `nprobe`。 +2. 每个 `query × probe` 桶启动一个 256-thread block。 +3. block 内并行扫描连续桶数据并产生桶内 Top-K。 +4. 每个 query 再用一个 block 合并 `nprobe × K` 个候选。 + +每批现在只上传 query,不再执行 CPU 中心/桶选择,也不上传候选位置。 +nprobe=16 从上一版单 block 的 27.17 ms 降到 4.19 ms,再加速约 6.5 倍; +相对最初单线程 GPU 版累计加速约 216 倍。 + +同一 100k × 128、101 queries、inner-product、nlist=64 实验: + +| nprobe | 全 GPU 查询(ms) | QPS | recall@10 | 上一版 GPU(ms) | +|---:|---:|---:|---:|---:| +| 1 | 2.65 | 38107.8 | 0.0782 | 3.79 | +| 2 | 2.68 | 37617.6 | 0.1406 | 5.34 | +| 4 | 2.78 | 36327.6 | 0.2327 | 8.45 | +| 8 | 2.94 | 34348.9 | 0.3614 | 14.69 | +| 16 | 4.19 | 24131.4 | 0.5455 | 27.17 | +| 32 | 5.85 | 17267.3 | 0.8119 | 63.43 | +| 64 | 10.29 | 9814.3 | 1.0000 | 127.17 | + +nprobe=16 的平均分段时间为:query H2D 0.10 ms、GPU 中心选择 +0.68 ms、桶扫描与局部 Top-K 2.55 ms、最终归并 0.17 ms、结果 D2H +0.21 ms。所有 nprobe 的 recall 与 CPU 基线一致;nprobe=16 的结果与 +CPU IVF 分数逐值一致。FP32/FP16 与三种 metric 自动测试通过, +compute-sanitizer 报告 0 个错误。 + +在该中等规模上,nprobe=16 的 24.1k QPS 已高于 exact GPU 的约 18.4k +QPS,但 recall 仅为 0.5455;nprobe=32 的 recall 提升至 0.8119,QPS +约 17.3k。下一步应提高聚类质量、扩大 nlist,并进行 nlist × nprobe +质量—性能扫描,而不能只追求低 nprobe 的高吞吐。 + +## 2026-08-31:球面 k-means 与 nlist × nprobe 扫描 + +inner-product 使用普通均值更新中心时,中心模长会影响分桶。nlist=512 的 +桶大小达到 min/avg/max = 2/195.3/5243,最大的桶会破坏并行扫描的 +负载均衡。现在对 inner-product 和 cosine 的初始中心与每轮更新中心做 +L2 归一化,L2 度量仍保持普通 k-means。相同 nlist=512 索引的桶大小变为 +147/195.3/240,且没有空桶。 + +同时把 GPU 中心选择从“每个 query 一个线程维护有序 nprobe”改为 +256-thread block 归约。以 nlist=512、nprobe=128 为例,中心选择从 +30.43 ms 降到 1.24 ms,查询总时间从 33.69 ms 降到 4.53 ms;结果与 +优化前逐值一致。 + +首轮扫描继续使用 100k × 128 FP32 inner-product、101 queries、K=10、 +batch=8、预热 1 次并重复 5 次。下表列出具有代表性的质量—吞吐点: + +| nlist | nprobe | 查询(ms) | QPS | recall@10 | 最低单 query recall | +|---:|---:|---:|---:|---:|---:| +| 256 | 64 | 3.607 | 28001.4 | 0.6257 | 0.1 | +| 64 | 32 | 5.032 | 20073.3 | 0.8267 | 0.6 | +| 64 | 40 | 5.097 | 19816.9 | 0.8931 | 0.7 | +| 64 | 48 | 6.764 | 14931.4 | 0.9465 | 0.7 | +| 64 | 56 | 7.415 | 13620.3 | 0.9822 | 0.8 | +| 64 | 64 | 8.898 | 11350.9 | 1.0000 | 1.0 | + +在这份 100k 数据上,nlist=64 的中高召回点构成更实用的性能前沿: + +- `64/40`:约 19.8k QPS、0.893 recall,作为平衡档。 +- `64/56`:约 13.6k QPS、0.982 recall,作为高召回档。 +- `64/64`:全桶校验档,recall=1,结果与 exact ground truth 一致。 + +这些配置只代表当前数据规模和分布,不直接外推到百万规模。下一轮应在 +百万库上联动扫描 batch size 与 K,并记录显存和 query 延迟。 + +## 2026-09-01:IVF 桶内 warp 协作扫描 + +原桶扫描虽然每个 probe 使用 256-thread block,但每个线程串行计算一个 +完整向量。行主序布局下,相邻线程同一时刻访问相隔 `dim` 的地址,无法形成 +理想的连续读取。新实现让每个 warp 协作计算一个候选:lane 读取相邻维度, +用 shuffle 归约距离,再由 lane 0 维护该 warp 的局部 Top-K。每个 block 的 +8 个 warp 最后在共享内存中归并。 + +`distance_mode=simple` 保留旧 thread-per-vector 内核;默认 `warp` 选择 +新路径。自动测试对 FP32/FP16、L2/inner-product/cosine 同时比较 CPU、 +scalar GPU 与 warp GPU。CTest 3/3 通过,compute-sanitizer memcheck 为 +0 errors。 + +在同一 100k × 128、101-query、inner-product、nlist=64 实验中: + +| nprobe | 实现 | 总查询(ms) | 桶扫描(ms) | QPS | recall@10 | +|---:|---|---:|---:|---:|---:| +| 40 | scalar | 5.121 | 3.711 | 19723.8 | 0.8931 | +| 40 | warp | 4.094 | 2.566 | 24671.0 | 0.8931 | +| 56 | scalar | 7.438 | 5.917 | 13578.2 | 0.9822 | +| 56 | warp | 4.632 | 3.158 | 21807.2 | 0.9822 | + +nprobe=40 的总查询加速约 1.25 倍;nprobe=56 约 1.61 倍。两种内核输出的 +Top-K ID 和顺序完全一致,最大分数误差为 `9.6e-6`,来自 FP32 warp 归约 +顺序变化。全桶 nprobe=64 的 warp 查询为 5.342 ms、18.9k QPS,recall=1, +并与 exact ground truth 候选一致。 + +资源用量也更健康:FP32/FP16 warp kernel 均为 40 registers、0-byte stack、 +1060-byte shared memory;scalar kernel 为 40 registers、128-byte stack、 +3072-byte shared memory。 + +warp 优化后的代表性质量—吞吐前沿为: + +| nlist/nprobe | QPS | recall@10 | 说明 | +|---:|---:|---:|---| +| 256/64 | 32186.3 | 0.6257 | 最大吞吐参考点 | +| 128/64 | 26146.1 | 0.8327 | 吞吐—质量档 | +| 64/40 | 24671.0 | 0.8931 | 平衡档 | +| 64/48 | 21952.2 | 0.9465 | 高召回档 | +| 64/56 | 21807.2 | 0.9822 | 近精确档 | +| 64/64 | 18907.4 | 1.0000 | 全桶校验档 | + +下一阶段不再继续微调 100k 参数,而是在百万规模检查桶大小、GPU 显存、 +batch size 和 K 对这一布局的影响。 + +## 2026-09-01:百万规模 IVF 联合参数扫描 + +数据固定为 1,000,000 × 128 FP32 inner-product 数据库、1000 queries, +随机种子 2026。K=10 exact GPU ground truth 使用 batch=128、预热 1 次、 +重复 5 次:551.85 ms、1812.1 QPS,显式 GPU 缓冲区 980.39 MiB。 + +球面 k-means 使用 50,000 个训练样本和 8 次迭代: + +| nlist | 构建(ms) | 桶 min/avg/max | 空桶 | 索引 bytes | +|---:|---:|---:|---:|---:| +| 256 | 39401 | 3599/3906.25/4177 | 0 | 520133160 | +| 512 | 78075 | 1809/1953.12/2147 | 0 | 520266280 | +| 1024 | 155191 | 858/976.56/1088 | 0 | 520532520 | + +构建时间近似随 nlist 线性增加,桶保持均衡。当前 CPU 训练和全库分配已经 +成为离线阶段主要成本,后续可考虑 GPU k-means/assignment,但不影响查询 +性能结论。 + +### nlist × nprobe 前沿 + +下表统一使用 batch=16、K=10、预热 1 次、重复 5 次: + +| nlist/nprobe | 查询(ms) | QPS | recall@10 | 最低 query recall | +|---:|---:|---:|---:|---:| +| 1024/64 | 40.77 | 24526.0 | 0.3611 | 0.0 | +| 512/64 | 59.50 | 16808.1 | 0.4900 | 0.0 | +| 1024/128 | 67.03 | 14919.4 | 0.5293 | 0.1 | +| 256/64 | 92.32 | 10832.5 | 0.6613 | 0.2 | +| 512/128 | 96.45 | 10367.7 | 0.6897 | 0.2 | +| 1024/256 | 128.83 | 7762.4 | 0.7287 | 0.3 | +| 256/128 | 160.59 | 6227.0 | 0.8716 | 0.4 | +| 256/160 | 198.70 | 5032.8 | 0.9332 | 0.5 | +| 256/192 | 245.34 | 4076.0 | 0.9708 | 0.7 | +| 256/224 | 287.90 | 3473.5 | 0.9929 | 0.8 | +| 256/256 | 323.78 | 3088.5 | 1.0000 | 1.0 | + +更大的 nlist 在低召回区间提供更高吞吐,但中心选择和更多小桶 block 的 +开销使其在高召回区间被 nlist=256 支配。代表性预设因此选择: + +- fast:512/128,约 10.4k QPS、0.690 recall。 +- balanced:256/128,约 6.23k QPS、0.872 recall。 +- high recall:256/192,约 4.08k QPS、0.971 recall。 +- near exact:256/224,约 3.47k QPS、0.993 recall。 + +256/256 的 recall=1,候选与 exact ground truth 一致;其 3089 QPS 仍为 +当前 exact 路径的约 1.70 倍,因为分桶布局直接产生每桶 Top-K,不需要写出 +完整 `batch × database` 分数矩阵。 + +### batch size + +固定 256/160、K=10: + +| batch | 查询(ms) | QPS | batch P50/P99(ms) | +|---:|---:|---:|---:| +| 1 | 657.69 | 1520.5 | 0.643/0.659 | +| 8 | 207.40 | 4821.7 | 1.606/1.678 | +| 16 | 198.11 | 5047.7 | 3.076/3.222 | +| 32 | 205.95 | 4855.6 | 6.407/6.766 | +| 64 | 223.71 | 4470.1 | 14.016/15.705 | +| 128 | 250.74 | 3988.2 | 31.813/32.537 | + +batch=16 是当前吞吐峰值。batch 太小时启动和中心选择开销占比高;太大时 +单次提交的 `query × probe` blocks 过多,桶扫描总时间反而增加。这与 exact +search 在 batch=128 达到最高吞吐的结论不同。 + +### K 与显存 + +固定 256/160、batch=16:K=1 为 176.16 ms、5676.7 QPS、recall@1=0.943; +K=10 为约 198.70 ms、5032.8 QPS、recall@10=0.933。下一步需要用模板化 +局部候选和分层归并扩展 K=50/100,避免扩大运行时数组拖慢 K=10。 + +显存现在由程序直接统计显式 CUDA 缓冲区:exact batch128/K10 为 +980.39 MiB,IVF 256/160/b16/K10 为 496.37 MiB,降低约 49.4%。IVF 不保留 +完整距离矩阵是主要原因。CTest 3/3、compute-sanitizer 0 errors;新增 +`benchmark_ivf_sweep.py` 已实测可自动输出性能、显存、recall 和分段时间 CSV。 + +## 2026-09-01:IVF K=50/100 与 warp heap + +为避免 K100 拖慢 K10,桶扫描分别实例化 MaximumK=10/50/100。第一版仍用 +无序局部数组跟踪最差槽位,并在每个 probe 输出阶段重复扫描数组;虽然结果 +正确,但输出有序 K 项产生 O(K²) 工作。nlist=256、nprobe=160、batch=16 +时,K50/K100 分别为 502.36/1392.80 ms。 + +优化版让每个 warp 在共享内存维护“最差项在根”的 heap:候选替换从 O(K) +降为 O(log K),扫描完成后原地 heap sort 一次,再对 8 个 warp 的有序列表 +做 k-way merge。跨 probe 的最终归并也改为维护每个 probe 的当前 rank, +每轮只归约各列表头,不再给每个线程分配大型局部 Top-K。 + +资源用量证明 K10 未被大 K 拖累: + +| kernel | K | registers | stack | static shared | +|---|---:|---:|---:|---:| +| warp bucket scan | 10 | 40 | 0 | 1072 B | +| warp bucket scan | 50 | 40 | 0 | 4912 B | +| warp bucket scan | 100 | 40 | 0 | 9712 B | +| probe k-way merge | runtime | 18 | 0 | 4096 B | + +merge 另使用 `nprobe × 4` bytes 动态共享内存保存游标。GPU IVF 将 nprobe +限制为 8192,因此静态与动态共享内存保持在普通单 block 上限内。 + +### 优化收益 + +固定 1M×128、1000 queries、inner-product、256/160、batch=16: + +| K | heap 前(ms) | heap 后(ms) | 加速 | heap 后 QPS | recall@K | +|---:|---:|---:|---:|---:|---:| +| 10 | 198.70 | 188.31 | 1.06× | 5310.6 | 0.9332 | +| 50 | 502.36 | 268.38 | 1.87× | 3726.1 | 0.9224 | +| 100 | 1392.80 | 338.42 | 4.12× | 2954.9 | 0.9163 | + +优化前后 K10/50/100 的候选、顺序和分数逐值相同。256/256 全桶查询也与 +exact K50/K100 ground truth 逐项一致,最大分数误差为 0。 + +最终 probe merge 只占很小比例:上述 K10/50/100 分别约 +0.67/2.45/4.98 ms;主要成本仍是每个桶内的候选距离和局部 heap。 + +### 大 K batch 与高召回点 + +固定 256/160 时,大 K 的最佳 batch 高于 K10: + +| K | batch | 查询(ms) | QPS | batch P50/P99(ms) | +|---:|---:|---:|---:|---:| +| 50 | 8 | 278.40 | 3591.9 | 2.182/2.211 | +| 50 | 32 | 264.15 | 3785.7 | 8.273/8.713 | +| 50 | 64 | 257.25 | 3887.2 | 16.123/16.845 | +| 50 | 128 | 264.16 | 3785.6 | 33.161/35.268 | +| 100 | 8 | 364.51 | 2743.4 | 2.861/2.891 | +| 100 | 32 | 326.04 | 3067.1 | 10.234/10.489 | +| 100 | 64 | 319.40 | 3130.9 | 20.035/20.548 | +| 100 | 128 | 316.88 | 3155.8 | 39.689/40.778 | + +K50 的吞吐峰值为 batch64。K100 的 batch128 只比 64 高约 0.8%,延迟却 +接近翻倍,因此默认仍选择 batch64。 + +使用 batch64 的质量—吞吐点: + +| K | nprobe | QPS | recall@K | 最低 query recall | +|---:|---:|---:|---:|---:| +| 50 | 160 | 3887.2 | 0.9224 | 0.80 | +| 50 | 192 | 3185.5 | 0.9636 | 0.86 | +| 50 | 224 | 2629.3 | 0.9904 | 0.92 | +| 100 | 160 | 3130.9 | 0.9163 | 0.83 | +| 100 | 192 | 2576.5 | 0.9611 | 0.90 | +| 100 | 224 | 2201.2 | 0.9890 | 0.94 | + +旧 exact block ground truth 的 K50/K100 吞吐分别约 254/138 QPS;近似 IVF +在 0.92 左右 recall 下分别约快 15.3×/22.7×。自动测试覆盖 +FP32/FP16 × L2/IP/cosine × K50/K100;CTest 3/3,compute-sanitizer +0 errors。 + +## 2026-09-01:FAISS CPU/GPU 公平对照 + +本轮固定使用同一份 1,000,000 × 128 FP32 inner-product 数据库、1000 +queries、batch=64、随机种子 2026。FAISS 版本为 1.14.1(CUDA 12 wheel), +运行环境为 RTX 4090 D、driver 570.124.06、CUDA 12.8。GPU 查询均完整预热 +1 轮并重复 5 轮;FAISS CPU 使用单线程。FAISS IVF 使用 nlist=256、 +100,000 个训练样本、15 次聚类迭代,并和自研 IVF 扫描完全相同的 nprobe。 + +FAISS Flat K100 和 WarpFusion exact K100 的全部候选 ID 完全一致, +recall@100=1、最低单 query recall=1。FAISS IVF 使用自己训练的聚类中心, +因此不是复用自研索引;比较口径是相同算法参数与实际达到的 recall,而不是 +强行要求两个索引访问相同桶。 + +### Exact / Flat + +| K | WarpFusion GPU QPS | FAISS GPU QPS | FAISS 加速 | FAISS CPU QPS | WarpFusion/FAISS batch P99(ms) | +|---:|---:|---:|---:|---:|---:| +| 10 | 1774.9 | 20583.6 | 11.60× | 75.92 | 36.046 / 3.232 | +| 50 | 715.9 | 20611.3 | 28.79× | 75.71 | 88.177 / 3.150 | +| 100 | 444.6 | 19906.4 | 44.77× | 73.06 | 141.487 / 3.754 | + +这里的 WarpFusion Exact 也重新统一为 batch64、预热 1 次、重复 5 次。 +差距主要来自当前 exact 路径仍写回完整距离矩阵,且 block Top-K 随 K 增大 +迅速变慢。FAISS Flat 的 K10/50/100 吞吐接近,表明其距离扫描与选择融合程度 +明显更高。自研 IVF 仍是项目性能主线,Exact 主要保留作正确性 ground truth。 + +### IVF-Flat 质量—吞吐 + +下表给出平衡档 nprobe=160;两个实现的 recall 非常接近: + +| K | WarpFusion QPS / recall | FAISS QPS / recall | WarpFusion/FAISS QPS | batch P99 WarpFusion/FAISS(ms) | +|---:|---:|---:|---:|---:| +| 10 | 4771.1 / 0.9332 | 4756.1 / 0.9369 | 1.003× | 14.495 / 19.408 | +| 50 | 3879.4 / 0.9224 | 8721.0 / 0.9231 | 0.445× | 17.032 / 11.133 | +| 100 | 3111.3 / 0.9163 | 7896.0 / 0.9163 | 0.394× | 20.663 / 8.296 | + +近精确档 nprobe=224: + +| K | WarpFusion QPS / recall | FAISS QPS / recall | WarpFusion/FAISS QPS | batch P99 WarpFusion/FAISS(ms) | +|---:|---:|---:|---:|---:| +| 10 | 3314.1 / 0.9929 | 3049.7 / 0.9930 | 1.087× | 19.961 / 23.000 | +| 50 | 2647.5 / 0.9904 | 6553.5 / 0.9899 | 0.404× | 24.621 / 9.946 | +| 100 | 2192.1 / 0.9890 | 5620.9 / 0.9888 | 0.390× | 30.712 / 11.475 | + +K10 在 nprobe=160 基本持平,在 192/224 分别比 FAISS 快约 5.4%/8.7%; +说明中心选择、warp 协作距离计算和 K10 路径已经具备竞争力。K50/K100 则 +稳定落后约 2.25--2.56 倍,且 P99 同样较高。结合 kernel 分段时间,最终 +probe merge 只占约 0.7--1.4 ms,下一优化目标应是桶内大 K 候选选择,而 +不是中心选择或最终归并。 + +FAISS GPU IVF 的 K10 路径在这组环境中稳定慢于 K50;完整 query-set 预热 +后复测仍然如此,因此保留实测结果,不用推测值修正。CPU 代表点 +IVF K10/nprobe128 为 43.57 QPS、recall=0.8795,反而慢于单线程 Flat 的 +75.92 QPS,故没有继续浪费时间扫描 CPU IVF 的所有 K/nprobe 组合。 + +### 构建、加载与显存口径 + +- FAISS IVF 首次 CPU 建索引约 7.02 s;持久化索引加载约 286.6 ms,GPU + 转移约 414.6 ms。后续基准复用保存的 CPU 索引。 +- FAISS Flat/IVF 的 GPU 索引数据分别约 492.10/497.98 MiB; + `StandardGpuResources` 默认另保留 1536 MiB 临时工作区。 +- WarpFusion IVF 显式缓冲区随 K/nprobe 约 497--513 MiB。这个数不包含 + CUDA context 或第三方库保留区,因此不能直接和 FAISS 的“索引 + 临时 + 工作区”相减后宣称节省比例。 +- 原始数据保存在 `results/million/faiss_gpu_formal_v3.csv`、 + `faiss_cpu_flat.csv`、`faiss_cpu_ivf_rep.csv` 和 + `purplepulse_faiss_compare_k{10,50,100}_v2.csv`。两个 sweep 脚本现在都会 + 保存 run/batch P50/P99、初始化、H2D、QPS、recall 和内存字段,并在每个 + FAISS 配置完成后立即落盘。 + +本阶段结论不是“全面超过 FAISS”:K10 IVF 在高召回区已经可竞争,但大 K +选择以及 Exact 路径仍有明显工程差距。这个结果为下一轮优化给出了清晰、 +可量化的目标。 + +## 2026-09-01:IVF 桶扫描第二轮优化 + +本轮只改变 GPU 桶扫描实现,不改变索引、访问的桶或排序规则。优化包含: + +1. 将 L2、inner-product、cosine 作为模板参数实例化,去掉候选内层循环的 + 运行时 metric 分支。 +2. 每个候选只执行当前 metric 所需的 warp 归约;例如 inner-product 不再 + 对恒为 0 的 L2 累加器执行 5 次 shuffle。 +3. 维度数据不超过 8 KiB 时,将 query 缓存在 block 动态共享内存;拷贝与 + heap 初始化共用原有 barrier。 +4. 新增 2/4/8-warp A/B 路径。`warp_compact` 对 K50/K100 使用 2-warp + block,降低每个 probe block 的 heap 共享内存并允许更多 block 驻留; + K10 保持 8 warps。 + +曾测试在距离维循环加入 `#pragma unroll 4`,K10/K50/K100 分别回退到约 +5684/5732/5049 QPS,因此撤销该改动。保留失败实验可以避免后续将“更多 +展开”误当成必然优化。 + +### 逐步 A/B + +固定 1M×128、1000 queries、inner-product、nlist/nprobe=256/160、 +batch=64。下表使用同一批量口径隔离 kernel 改动: + +| 实现阶段 | K10 QPS | K50 QPS | K100 QPS | +|---|---:|---:|---:| +| 上轮正式基线 | 4771.1 | 3879.4 | 3111.3 | +| compact heap + 删除无效归约 | 5776.0 | 5275.6 | 4637.4 | +| metric 编译期特化 | 6309.8 | 5812.1 | 5101.3 | +| query 共享内存缓存 | 7000.1 | 6441.3 | 5390.5 | + +核心路径相对上轮基线分别提升约 46.7%、66.0%、73.2%。资源检查中 +inner-product/cosine 使用 38/40 个寄存器,stack=0;compact K50/K100 +静态共享内存为 1232/2432 B。旧 8-warp K50/K100 路径需要 4928/9728 B。 + +### 最终质量—吞吐 + +优化后重新扫描 nprobe;K10/K100 使用 batch64,K50 根据新 batch sweep +使用 batch32: + +| K | nprobe | 查询(ms) | QPS | recall@K | 最低 query recall | batch P99(ms) | +|---:|---:|---:|---:|---:|---:|---:| +| 10 | 128 | 114.49 | 8734.3 | 0.8716 | 0.40 | 7.278 | +| 10 | 160 | 142.81 | 7002.2 | 0.9332 | 0.50 | 9.368 | +| 10 | 192 | 172.77 | 5788.1 | 0.9708 | 0.70 | 11.411 | +| 10 | 224 | 199.94 | 5001.5 | 0.9929 | 0.80 | 13.255 | +| 50 | 128 | 124.92 | 8005.3 | 0.8576 | 0.68 | 4.028 | +| 50 | 160 | 149.80 | 6675.4 | 0.9224 | 0.80 | 4.853 | +| 50 | 192 | 192.87 | 5184.9 | 0.9636 | 0.86 | 6.260 | +| 50 | 224 | 215.97 | 4630.2 | 0.9904 | 0.92 | 7.037 | +| 100 | 128 | 145.74 | 6861.7 | 0.8496 | 0.73 | 9.266 | +| 100 | 160 | 186.16 | 5371.8 | 0.9163 | 0.83 | 12.128 | +| 100 | 192 | 226.51 | 4414.9 | 0.9611 | 0.90 | 14.712 | +| 100 | 224 | 266.67 | 3749.9 | 0.9890 | 0.94 | 17.482 | + +推荐配置在 nprobe=160 相对上轮正式基线提升:K10 46.8%、K50 72.1%、 +K100 72.7%。与同口径 FAISS GPU IVF 相比,WarpFusion K10 快约 1.47×; +FAISS K50/K100 分别仍快约 1.31×/1.47×,但差距已从 2.25--2.54× 明显缩小。 + +### 优化后的 batch 选择 + +固定 nprobe=160,吞吐峰值分别是 K10/batch64、K50/batch32、 +K100/batch64: + +| K | 推荐 batch | QPS | batch P50/P99(ms) | +|---:|---:|---:|---:| +| 10 | 64 | 6973.0 | 8.897/9.395 | +| 50 | 32 | 6635.6 | 4.670/4.877 | +| 100 | 64 | 5359.2 | 11.548/12.163 | + +最终 K10/K50/K100 与优化前结果文件逐字节一致。自动测试还覆盖 +FP32/FP16 × L2/IP/cosine × K50/K100 × warp2/4/8/compact,CTest 5/5; +`compute-sanitizer --tool memcheck` 报告 0 errors。原始扫描结果保存在 +`optimized_v1_k10.csv`、`optimized_v1_k50_b32.csv`、 +`optimized_v1_k100.csv` 和 `optimized_v1_batch_sweep.csv`。 + +## 2026-09-02:score-mass 自适应 nprobe + +### 实现 + +GPU 中心选择现在可额外保留排序后的前 `max_nprobe` 个分数。每个 query 将 +中心分数按 top-1 到最后一个候选中心的跨度归一化,再用 softmax 风格质量 +选择达到 `target_mass` 的最短 probe 前缀。策略支持 min/max/step 和无量纲 +temperature;L2 使用负距离作为 utility,IP/cosine 使用原相似度。 + +桶扫描和最终归并都读取每个 query 的实际 nprobe。CLI 会报告 +min/avg/max,并可用 `--probe-counts-output` 保存逐 query 明细;新增 +`benchmark_adaptive_nprobe.py` 可扫描 target mass,逐项落盘结果和 CSV。 + +实现了两种执行方式: + +- `masked`:保持一个最大网格,超过该 query 实际 nprobe 的 block 立即退出。 +- `grouped`:取回每批 probe 计数、按 tier 压紧 query,再为每个 tier 启动 + 精确大小的扫描网格。 + +两条路径的候选 ID、顺序和分数逐值一致。K100、平均 151.632 probes 的正式 +A/B 中,masked 为 183.852 ms / 5439.2 QPS,grouped 为 204.680 ms / +4885.7 QPS;grouped 虽消除了空 block,但多个较小网格降低并行度并增加 +launch 开销,最终慢约 11.3%,因此配置默认使用 masked。 + +### target mass 前沿 + +固定 max=224、min=64、step=16、temperature=0.2。三种 K 得到相同的实际 +probe 分布;下表列出 K10 的完整前沿: + +| target mass | 实际平均 nprobe | QPS | recall@10 | 最低 query recall | +|---:|---:|---:|---:|---:| +| 0.80 | 92.720 | 11748.6 | 0.7753 | 0.30 | +| 0.85 | 110.544 | 9879.3 | 0.8275 | 0.30 | +| 0.90 | 133.648 | 8239.5 | 0.8837 | 0.40 | +| 0.93 | 151.632 | 7233.8 | 0.9201 | 0.50 | +| 0.95 | 166.736 | 6641.8 | 0.9416 | 0.50 | +| 0.97 | 186.096 | 5923.8 | 0.9654 | 0.70 | +| 0.99 | 210.128 | 5306.2 | 0.9860 | 0.80 | + +### 同计算预算公平对照 + +代表点 target_mass=0.93 的平均值为 151.632,与固定 nprobe=152 对照。 +两者使用相同数据、batch、预热 1 次、重复 5 次: + +| K | 策略 | 实际平均 nprobe | QPS | recall@K | batch P99(ms) | +|---:|---|---:|---:|---:|---:| +| 10 | fixed | 152.000 | 7307.7 | 0.92120 | 8.693 | +| 10 | score-mass | 151.632 | 7233.8 | 0.92010 | 8.947 | +| 50 | fixed | 152.000 | 6954.4 | 0.90874 | 4.573 | +| 50 | score-mass | 151.632 | 6773.0 | 0.90742 | 4.775 | +| 100 | fixed | 152.000 | 5642.5 | 0.90179 | 11.583 | +| 100 | score-mass | 151.632 | 5439.2 | 0.89993 | 11.955 | + +按实际 probe 分组分析表明,策略分配更多 probes 的 query 在固定预算下确实 +更难,说明难度信号不是随机的;但相关性太弱,无法提高总体 recall,而且 +变长工作量使 GPU 批处理略慢。结论是:在当前均匀合成查询上不应替换固定 +nprobe。配置、代码和原始结果保留,等待更异质的真实 Agent 查询分布复验。 + +固定路径与此前输出逐字节一致,masked/grouped 自适应输出也逐字节一致; +CTest 6/6、compute-sanitizer memcheck 0 errors。原始数据保存在 +`adaptive_k{10,50,100}_t02.csv`、`adaptive_formal_k{10,50,100}.csv`、 +`adaptive_grouped_formal_k100.csv`、`fixed_k{10,50,100}_matched.csv` 和 +`adaptive_vs_fixed_n152.csv`。 + +## 2026-09-03:GPU 元数据过滤与记忆评分 + +### 实现与正确性 + +新增版本化 `PPMETA01` 元数据文件,按原始向量 ID 保存时间戳、重要性、 +会话 ID 和来源类型。fused 路径在桶扫描中先检查时间、会话和来源过滤条件, +通过后才读取向量,并在局部 Top-K 前加入重要性与指数时间衰减。独立 rerank +路径先执行语义 Top-(K×factor),再用第二个 GPU kernel 过滤和重排。 + +CPU baseline 与 GPU fused/rerank 已覆盖 FP32/FP16、L2/IP/Cosine;新 GPU +环境使用 CUDA 12.8、计算能力 8.9,CTest 6/6。20k 端到端文件链路中,CPU +与 GPU 两条模式的候选集合相同,最大分数误差为 7.6e-6。正式结果中的 +source_type 过滤违规数为 0;`compute-sanitizer --tool memcheck` 报告 0 errors。 + +### fused 与独立重排 A/B + +固定 100k×128、1000 queries、Cosine、nlist/nprobe=64/64、K=10、 +batch=64、source_type=1、预热 2 次、重复 5 次。两种模式使用相同评分权重; +rerank 从语义 Top-100 开始,fused 直接在完整扫描候选中融合。 + +| 模式 | 查询(ms) | QPS | batch P99(ms) | 扫描(ms) | 重排(ms) | GPU 缓冲区(MiB) | recall@10 vs fused | +|---|---:|---:|---:|---:|---:|---:|---:| +| fused | 20.8149 | 48042.6 | 1.29066 | 18.6603 | 0 | 52.0687 | 1.000 | +| rerank Top-100 | 46.3539 | 21573.2 | 2.96419 | 42.4594 | 0.8408 | 56.3534 | 0.507 | + +fused 吞吐是独立重排的约 2.23×,显式缓冲区少约 4.28 MiB。独立重排的 +最低单 query recall 只有 0.1:语义 Top-100 在过滤和记忆加权之前已经截断, +无法恢复被丢弃的高重要性或近期记忆。因此 fused 同时改善了性能和该评分定义 +下的结果质量。原始结果与汇总位于 `results/memory_100k/`。 diff --git a/09_vector_retrieval/PurplePulse/docs/DEVELOPMENT_PLAN.md b/09_vector_retrieval/PurplePulse/docs/DEVELOPMENT_PLAN.md new file mode 100644 index 00000000..3c236df0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/DEVELOPMENT_PLAN.md @@ -0,0 +1,252 @@ +# 开发计划 + +## 第一阶段:正确性地基 + +- [x] 定义带版本号的二进制文件格式 +- [x] 实现数据生成、读取和检查 +- [x] 实现 CPU 精确检索参考答案 +- [x] 实现容易理解的 CUDA 距离计算 baseline +- [x] 建立自动正确性与边界测试 +- [x] 在中等规模上复验 L2、内积和 Cosine 的 CPU/GPU 一致性 + +## 第二阶段:精确检索性能 + +- [x] 将 Top-K 从 CPU 移到 GPU +- [x] 实现分块与两阶段 Top-K +- [x] 将局部 Top-K 从有序插入改为无序候选 + 最差项跟踪 +- [x] 为 K=1/10 增加编译期模板特化 +- [x] 实现 FP16 输入、GPU 16 位存储和 FP32 累加 +- [x] 扫描 batch=1/4/8/16/32/64/128 的吞吐与延迟 +- [x] 融合 Exact 距离计算与局部 Top-K,删除完整距离矩阵写回 +- [x] 用 nsys 记录 Top-K 优化前后的 kernel 时间线 +- [x] 完成 ncu 可用性诊断;确认赛事平台宿主权限限制并在报告中记录,不虚构计数器数据 + +## 第三阶段:IVF-Flat + +- [x] 用确定性采样 k-means 训练聚类中心并构建倒排表 +- [x] 使用连续桶布局保存和加载版本化索引 +- [x] 实现 CPU 固定 nprobe 正确性基线 +- [x] 对比 exact search 的 recall@K +- [x] 实现第一版 GPU 常驻索引、候选扫描和 Top-K +- [x] 将中心选择迁到 GPU,并消除候选位置 H2D +- [x] 使用每个 probe 一个 block 提高单 query 候选扫描并行度 +- [x] 对相似度度量使用球面 k-means,修复大 nlist 下的桶倾斜 +- [x] 使用 block 归约并行选择中心,替代单线程有序插入 +- [x] 完成 100k × 128、K=10 的首轮 nlist × nprobe 扫描 +- [x] 使用 warp 协作改善桶内向量读取与距离计算,并保留 scalar A/B 基线 +- [x] 百万规模扫描 nlist=256/512/1024 与对应 nprobe +- [x] 在百万规模扫描 IVF batch=1/8/16/32/64/128 +- [x] 对 K=1/10 完成首轮质量与吞吐对比 +- [x] CLI 报告 exact/IVF 显式 GPU 缓冲区,并提供自动 CSV sweep 脚本 +- [x] 使用 K=10/50/100 模板化 warp heap 扩展 IVF 局部 Top-K +- [x] 使用 probe 有序列表 k-way merge 高效归并 K=50/100 +- [x] 百万规模完成 K50/K100 的 batch 与 nprobe 首轮扫描 +- [x] 将 metric 编译期特化,并删除每候选无效的 warp shuffle 归约 +- [x] 将小于等于 8 KiB 的 query 缓存到 block 共享内存 +- [x] 为大 K 使用 compact 2-warp block,保留 warp2/4/8 A/B 路径 +- [x] 优化后重新扫描 K10/K50/K100 的 batch 与 nprobe +- [x] 实现 GPU bucket-major 任务分组,验证高 nprobe 下的跨 query L2 复用 +- [x] 缓存单 warp heap 根节点,以空穴下沉减少插入与排序的共享内存写入 +- [x] 为单 warp probe 删除多 warp 合并同步并直接写回有序 Top-K +- [x] 评估分布式寄存器 Top-K、8 候选缓冲和 warp bitonic sort;依据 + +0.43%、-22.68% 和 -18.72% 的 A/B 结果拒绝替换稳定实现 + +## 第四阶段:Agent 场景创新 + +- [x] 根据归一化中心分数质量为每个 query 自适应选择 nprobe +- [x] 实现 masked/grouped 两种变长 GPU 调度并完成 A/B +- [x] 与相同平均 probe 的固定 nprobe 完成百万级公平实验 +- [x] 根据负结果保留实验接口但不替换固定策略默认值 +- [x] 在 GPU 候选扫描中融合元数据过滤和记忆评分 +- [x] 与分离重排序方案进行公平实验 + +## 第五阶段:正式实验与报告 + +- [x] 百万向量、128 维、1000 queries 固定数据集 +- [x] 记录 QPS、run/batch P50/P99、显存和 recall@K +- [x] 完成 FAISS CPU/GPU Flat/IVF-Flat 与自研引擎首轮公平对照 +- [x] 补齐 K=50、batch=40 的 FAISS GPU 同批次 100 次正式对照 +- [x] 保存 FAISS 与自研 nprobe 扫描原始 CSV +- [x] 输出 recall-latency、recall-QPS 和 batch-QPS 曲线图 +- [x] 记录赛事平台无法开放 ncu 计数器的原因、影响范围和替代证据 +- [x] 完成最终总结报告与复现说明 + +Synthetic-1M 最终结果中,WarpFusion K10 在 nprobe=160 下比同口径 FAISS +GPU IVF 快 1.20 倍。K50 经 batch=40、bucket-major 和 4×16 分区局部 Top-K +优化后达到 7934 QPS,与 FAISS 的差距缩小到 4.97%;K100 使用 4×40 分区 +局部 Top-K 达到 7205 QPS,差距缩小到 9.64%。Exact fused 在百万规模 +K10/K50/K100 上相对矩阵路径分别加速约 3.13×/7.16×/10.59×,显式 GPU +缓冲区减少约 33%,但仍比 FAISS GPU Flat 慢 3.18--3.71 倍。上述结果已经 +通过正式 A/B、输出一致性检查、CTest 和 Compute Sanitizer 验证。 + +## 第六阶段:真实公开数据验证(已完成) + +目标是验证 WarpFusion 的优化能否从 Synthetic-1M 推广到真实向量分布。 +继续使用当前 RTX 4090,不以更换硬件作为达标条件。 + +- [x] 接入 SIFT1M,并保留公开数据校验和、转换命令和 ground truth。 +- [x] 接入至少一套 384 或 768 维公开文本 embedding 数据。 +- [x] 在两套真实数据上完整评测 K=10/50/100 与 + nprobe=32/64/128/160/192/224。 +- [x] 同时报告 WarpFusion、FAISS GPU IVF-Flat 和 Exact ground truth 的 + QPS、P50/P99、recall、显存与建库时间。 +- [x] 验证分区局部 Top-K 的外部有效性;若产生不可接受的 recall 损失,提供 + 自动回退到完整 heap 的安全路径。 + +验收门槛:真实数据上输出正确,实验可以一条命令复现,并形成至少两张完整的 +recall-QPS 曲线。WarpFusion 在相近 recall 下保持接近 FAISS 的竞争力,而非 +只在 Synthetic-1M 上成立。 + +验收结果(2026-09-10):通过。SIFT1M 与 384 维 Yahoo MiniLM 的完整矩阵、 +公开 ground truth 交叉验证、FAISS GPU 对照和四张曲线均已落盘。在 +`nprobe=160` 下,WarpFusion 在六组 K/数据集组合中达到 FAISS GPU IVF-Flat +的 1.33--2.53 倍吞吐。K=50 分区路径在两套真实数据上触发 recall 安全回退, +K=100 分区路径保持零 recall 损失并分别加速 1.38 倍和 1.72 倍,证明自动回退 +是必要的,而不是只保留未验证的快速路径。 + +## 第七阶段:Exact fused 性能冲刺(已完成) + +- [x] 分离距离计算、局部选择和最终归并耗时,确定 K=10/50/100 的真实瓶颈。 + 2026-09-10 的 differential profile 显示:Synthetic-1M 的距离阶段占 + 80.72%--98.26%,Yahoo MiniLM 384 占 89.58%--98.73%;最终归并最多 + 1.03%,不是当前主瓶颈。局部 Top-K 使用 `fused - distance-only` 估算, + 不是硬件计数器的独立时间线。 +- [x] 比较当前 heap、分层 Warp/Block Top-K、候选缓冲后归并以及块级 + radix/select 方案。当前 fused 本身采用 8 个 warp 局部 heap + block 归并; + 已实测的 matrix K=10 候选缓冲后归并、K=50/100 block 反复选择路径慢 + 3.13--10.59 倍且多用约 33% buffer。 + 全量 radix/select 若保持精确语义,只能物化 score 或重复距离扫描,违反本阶段 + fused 约束,故在设计审查后不实现;不将其写成 GPU 实测结果。 +- [x] 对不同 K 独立选择实现,不要求一套 kernel 覆盖所有场景。首轮 + query-tiling 结果选择 K=10/128 维 tile4、K=10/384 维 tile8、K=50/384 维 + tile4;K=50/128 维和 K=100 回退原 fused heap。 +- [x] 保持融合路径不写回完整距离矩阵,且候选 ID 与精确参考逐项一致。 + query tile 的全部 smoke 与正式 A/B 均通过逐 query、逐 rank ID/score 校验, + Compute Sanitizer 报告 0 errors。 + +验收门槛:在 Synthetic-1M 和至少一套真实数据上,WarpFusion Exact 相对 +FAISS GPU Flat 的吞吐差距缩小到 2 倍以内;若未达到,必须用可复现 profile +明确剩余瓶颈,并记录被否决方案和原因。 + +阶段进展(2026-09-10):跨 query 复用数据库读取的 tiled fused kernel 已完成 +实现和三数据集正式验证。Synthetic-1M/SIFT1M K=10 分别提升 37.3%/33.0%; +Yahoo K=10 使用 tile8/160 blocks 提升 88.7%,K=50 使用 tile4 提升 21.1%。 +128 维 K=50 和全部 K=100 路径退化,已记录并回退。优化后相对 FAISS GPU +Flat 的 K=10 差距仍为 Synthetic 2.30 倍、SIFT1M 2.24 倍、Yahoo 3.15 倍, +尚未达到本阶段 2 倍门槛。后续 block 级数据库 tile 在 Synthetic/Yahoo 的 +最佳值分别为 9050/4794 QPS,均低于已接纳的 warp-query 9265/6989 QPS, +因此记录为负实验且未扩展到正式长跑。K 专用选择结构的最终裁决见上方清单与 +复现说明:保留当前分层 heap,不引入需要完整 score 物化或重复扫描的方案。 + +验收结论(2026-09-10):按计划的失败分支完成。吞吐差距未缩小到 2 倍以内, +但已有可复现 differential profile 明确显示距离/数据库读取占 80.72%--98.73%, +且 cosine 范数预计算与 block-tile 两条候选均保存负结果和原因。选择结构比较 +确认完整候选物化、重复距离扫描和全量 radix/select 不能在保持 fused 约束下 +解决主瓶颈;已接纳的 query-tile 逐 K 回退,默认行为不扩大到退化组合。 + +## 第八阶段:稳定性与适用范围(已完成) + +- [x] 覆盖维度 64/128/384/768,batch 1/8/32/40/64/128,以及 + K=1/10/50/100。 +- [x] 覆盖 FP32/FP16、L2/inner-product/cosine、空桶、倾斜桶、重复向量、 + 相同距离和非整 warp 维度。 +- [x] 所有默认模式通过 CTest、Python 回归测试和 Compute Sanitizer。 +- [x] 给出按 K、维度和 GPU 资源选择实现的规则,并为非推荐组合提供安全回退。 + +验收结果(2026-09-10):通过。新增独立 `stability_tests`,完成 576 组 Exact +交叉矩阵、6 组满 batch + 尾 batch、6 组 65 维 dtype/metric 组合、3 组已接纳 +query-tile 和 2 组 fail-closed 回退。另构造 8 桶中 4 个空桶、最大桶占 +125/128 的病理 IVF 索引,完成 48 组 warp/bucket-major CPU/GPU 对照。 +远端 CTest 14/14 通过,稳定性矩阵 Compute Sanitizer 报告 0 errors;选择规则 +和边界记录在 `docs/STABILITY_MATRIX.md`,原始摘要位于 +`results/stage8_stability/coverage.csv`。 + +## 第九阶段:工程化与报告定稿(已完成) + +- [x] 提供稳定的构建、建库、查询和 benchmark CLI,减少与本机目录绑定的配置。 +- [x] 提供一条命令完成数据准备、测试、FAISS 对照、绘图和报告数据校验。 +- [x] 将真实数据结果、Exact 新实现、负实验和适用边界写入技术报告。 +- [x] 补充 API 示例、默认配置表、架构图、性能表和已知限制。 +- [x] 发布前在一套干净 Linux + CUDA 环境完成从零构建和最小查询验证。 + +验收门槛:四个技术阶段的代码、实验、原始 CSV、图表、报告和复现说明相互 +对应;课程提交版本与后续开源候选共用同一套可追溯证据。 + +验收结果(2026-09-11):通过。新增项目根目录无关的 `scripts/reproduce.py`, +串联构建、18 项 CTest、两套公开数据准备、WarpFusion/FAISS 实验、绘图、PDF +和发布校验,并以原子 checkpoint 支持 `--resume`。`scripts/validate_release.py` +校验正式 CSV、Stage 8 覆盖、SVG、核心文档和 PDF;`docs/API.md` 与 README +补齐 CLI/C++ 示例、默认配置、代表性能和限制。RTX 4090 D 的 CUDA 12.8 干净 +构建通过 18/18 CTest,257×65、13 queries 的 Exact/IVF CPU/GPU 最小查询均 +通过候选与分数校验;摘要证据位于 `evidence/2026-09-11/stage9/`。 + +## 第十阶段:开源发布冲刺(条件阶段) + +只有第六至第九阶段全部通过验收后,才启动本阶段。目标是把完成验证的工程 +整理为可公开发布、可独立复现的 GPU 向量检索研究原型,而不是先发布再补证据。 + +- [ ] 完成面向外部使用者的 README、快速开始、贡献指南和变更记录。 +- [ ] 清理提交历史中的凭据、机器地址、临时文件和不可公开数据。 +- [ ] 选择并加入开源许可证,列清第三方依赖及其许可证。 +- [ ] 发布版本必须绑定源码提交、配置、数据校验和和原始 CSV,确保报告数字可追溯。 +- [ ] 建立公开 issue 模板、版本标签和最小持续集成检查。 + +完成第六至第十阶段后,才将仓库标记为 WarpFusion 的首个公开版本候选。 +建议版本号为 `v0.1.0`,定位为“单卡、内存内、Exact 与 IVF-Flat GPU 向量 +检索研究原型”,不宣称生产级服务能力。 + +## 第十一阶段:Agent 应用方向(暂停,不纳入当前提交) + +> 本节以下内容属于 Agent 应用方向,不改变项目主体。本项目仍是一套 +> 可独立构建、运行和评测的 C++/CUDA GPU 向量检索引擎;Agent 是用于验证 +> 元数据融合检索价值的真实工作负载,Pi 只是首个轻量客户端。 + +### 11.1 范围与边界 + +- GPU 检索核心继续负责 Exact、IVF-Flat、GPU Top-K、常驻索引、批量 + 查询、元数据前置过滤以及语义/时间/重要性融合评分。 +- Agent 侧只负责提取记忆、生成 query、调用检索接口和组装上下文,不在 + 检索引擎内嵌 LLM,也不让 Agent 框架接管索引与排序逻辑。 +- 第一版采用 session 结束后的批量摄取和下一 session 的在线检索;暂不实现 + 实时增量索引、分布式服务、多 Agent 编排或 Web UI。 +- 接口保持框架无关,Pi adapter 放在 `clients/pi/`,后续可以增加其他 Agent + 客户端而无需修改 CUDA 核心。 + +### 11.2 最小可交付链路 + +- [ ] 定义 Agent Memory JSONL 格式,包含 content、memory_type、project_id、 + session_id、timestamp、importance 和 source_type。 +- [ ] 实现 session ingestion,将事实、经历、成功步骤和失败教训映射到文本、 + embedding 与现有项目 metadata 文件。 +- [ ] 增加 embedding provider 抽象;演示实现可替换,不把具体模型写死在 + 检索引擎中。 +- [ ] 保存 `vector_id -> content/provenance` 映射,使 GPU Top-K ID 能恢复成 + 可注入 Agent 上下文的记忆文本。 +- [ ] 提供最小常驻查询接口,复用已加载的 IVF 索引和 GPU 工作区,避免每个 + Agent tool call 都重新初始化 GPU。 +- [ ] 实现框架无关的 `memory_search` 与 `memory_record` 客户端协议。 +- [ ] 实现 Pi adapter:`memory_search` 工具、session 结束记忆记录和带来源的 + context builder。 +- [ ] 建立双 session CUDA 开发演示:后一 session 在空上下文下召回前一 + session 的成功方案或失败教训。 + +### 11.3 评测与验收 + +- [ ] 对比 No Memory、纯语义检索和本项目 fused memory 三组方案。 +- [ ] 记录记忆 Recall@K/MRR、错误重复率、任务成功率和注入 token 数。 +- [ ] 记录检索 QPS、P50/P99、GPU kernel 时间、显存以及错误 project/session + 的过滤泄漏率。 +- [ ] 验证 Agent adapter 关闭后,原有 CTest、百万规模 benchmark 和 CLI + 行为完全不变。 +- [ ] 在 README 中先展示 GPU 引擎架构与性能,再将 Agent Memory 作为应用 + 案例;Agent 内容不覆盖或替代 Exact/IVF/FAISS 主线。 + +### 11.4 本阶段明确不做 + +- MiniDeepSeek 或其他小模型训练。 +- MoE、GRPO、DPO 或 learned retrieval policy。 +- Base/Delta 在线索引、后台 compaction 和分布式多租户调度。 +- 完整 RAG、复杂网页、多个 Agent 框架同时适配。 + +完成上述最小链路后再根据时间评估在线增量索引;任何扩展不得降低 +GPU 检索核心测试、性能复现和代码可解释性。 diff --git a/09_vector_retrieval/PurplePulse/docs/FINAL_REPORT.md b/09_vector_retrieval/PurplePulse/docs/FINAL_REPORT.md new file mode 100644 index 00000000..d3adc140 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/FINAL_REPORT.md @@ -0,0 +1,286 @@ +# WarpFusion:面向大规模向量检索的 CUDA 并行设计与性能优化 + +**作者:花生  学员 ID:PurplePulse** + +## 摘要 + +面向百万级高维向量的近邻检索,系统需要同时承担距离计算、候选筛选、索引访问和批量调度等开销。仅优化单个距离计算核函数,通常难以显著改善完整检索流程的吞吐和延迟。本文设计并实现了单 GPU 向量检索系统 WarpFusion。系统提供精确检索(Exact Search)和基于倒排文件的 IVF-Flat 近似检索两条路径,支持 FP32 与 FP16 数据,以及 L2 距离、内积和余弦相似度三种度量方式。 + +在精确检索中,本文将距离计算与局部 Top-K 选择合并执行,避免生成规模为查询数乘以数据库向量数的完整距离矩阵。在 IVF-Flat 路径中,针对不同 K 值下的候选维护开销,设计了按桶任务调度和分区局部 Top-K 两项优化,并以结果一致性和召回率阈值决定是否启用优化。系统还配套实现了索引持久化、CPU 参考计算、异常输入检查、稳定性测试和实验复现流程,用于验证功能正确性和性能结果。 + +在 NVIDIA GeForce RTX 4090 D 上,Exact 融合路径相较距离矩阵基线的加速比为 3.13× 至 10.59×,并将显式 GPU 缓冲区减少约三分之一。在 SIFT1M 与 Yahoo MiniLM 两个公开数据集上,当训练样本数、聚类轮数、批大小和 `nprobe` 保持一致时,WarpFusion IVF-Flat 在六组 K 值实验中的吞吐为 FAISS GPU IVF-Flat 的 1.33× 至 2.53×。除 Yahoo MiniLM 的 K=10 配置外,其余五组实验的召回率均不低于 FAISS;在该例外配置中,WarpFusion 的 Recall@10 低 0.14 个百分点。实验还表明,分区候选结构在 K=50 和 K=100 时具有不同的适用性,因此候选容量需要结合真实数据分布验证,不能仅依据合成数据确定。 + +**关键词:** GPU 向量检索;CUDA;IVF-Flat;Top-K 选择;并行调度;近似最近邻 + +## 1 研究背景与目标 + +向量检索广泛应用于图像匹配、语义搜索、推荐系统和检索增强生成等任务。给定查询向量,系统需要从数据库中返回距离最近或相似度最高的 K 个向量。随着数据库规模和向量维度增加,检索过程不仅包含大规模距离计算,还需要持续维护候选集合并完成跨线程结果归并。对于百万规模数据,系统瓶颈往往由显存访问、Top-K 更新和任务调度共同决定。 + +精确检索需要比较查询与数据库中的全部向量。若查询数为 Q、数据库规模为 N、向量维度为 D,其计算复杂度约为 O(QND)。朴素 GPU 实现通常先生成大小为 Q×N 的距离矩阵,再执行 Top-K 选择。该方法结构清晰,适合作为正确性与性能基线,但会产生大量中间结果读写。IVF-Flat 则通过聚类将数据库划分为多个倒排桶,查询时只扫描与查询最相关的部分桶,从而以一定的召回率损失换取更高吞吐。FAISS 等成熟向量检索系统也采用了这类 GPU 并行检索方法[1]。 + +本文的目标不是构建完整的在线向量数据库,而是研究单机单卡、数据常驻显存条件下的 CUDA 向量检索实现与优化。具体目标包括: + +1. 实现从数据读取、索引构建、GPU 查询到结果输出的完整检索流程; +2. 支持 Exact 与 IVF-Flat 两种检索方式、FP32 与 FP16 两种数据类型、三种距离度量,并支持 K 分别取 1、10、50 和 100; +3. 对距离计算、候选筛选和任务调度进行协同优化,而非仅比较孤立核函数; +4. 通过 CPU 参考计算、公开数据的标准近邻集合和 FAISS 对照验证正确性与性能; +5. 保留原始实验数据、未采用方案和复现脚本,明确结论的适用范围。 + +本文的主要工作可概括为三点。第一,构建了可执行、可测试的单 GPU 检索系统,并统一了不同计算路径的排序规则和错误处理方式。第二,针对完整距离矩阵和大 K 候选维护的开销,分别实现融合 Exact、按桶调度和分区局部 Top-K。第三,在合成数据与三个真实数据集上进行端到端评估,并结合召回率、延迟、显存占用和稳定性分析性能收益。 + +## 2 系统架构与检索流程 + +![WarpFusion 系统架构](../results/figures/report-architecture.svg) + +**图 1.** WarpFusion 的系统组成与数据流。CPU 端负责输入校验、索引构建与参考计算,GPU 端执行主要检索流程,最终输出查询结果及性能、正确性记录。 + +### 2.1 数据组织与接口语义 + +向量数据库和查询文件采用带版本号的二进制格式。文件头记录数据形状、数值类型和距离度量;加载阶段检查文件标识、版本、维度及数据长度,避免程序在未报错的情况下接受截断文件或类型不匹配的数据。索引文件保存聚类中心、桶边界、原始向量 ID 以及按桶连续排列的向量。训练和分桶完成后,系统可以直接加载索引,无需在每次查询前重新聚类。 + +系统支持 L2 距离、内积和余弦相似度。L2 距离采用普通 k-means 训练中心;内积和余弦相似度采用中心归一化的球面 k-means,以减轻中心模长差异造成的桶规模失衡。不同计算路径均遵循统一排序规则:首先比较距离或相似度分数,分数相同时优先返回较小的原始向量 ID。该规则用于减少并行执行顺序不同造成的结果歧义。 + +### 2.2 Exact 检索路径 + +距离矩阵基线包含两个主要阶段:首先计算全部 Q×N 个距离或相似度分数并写入全局显存;随后逐查询读取矩阵并选择 Top-K。虽然该实现便于验证,但中间矩阵的写回与再次读取会增加显存流量,其空间开销也随 Q×N 线性增长。 + +WarpFusion 的融合 Exact 路径将距离计算与局部候选筛选合并。一个 CUDA 线程束(warp)负责扫描数据库中的连续区域,距离计算完成后立即更新线程束内部的局部 Top-K 缓冲区,仅将少量候选写入全局显存。随后由第二个规模较小的 GPU 核函数归并各局部结果。该方法没有改变精确检索的计算范围,但将中间数据量从完整距离矩阵缩减为与局部候选数量相关的缓冲区,因而主要收益来自减少全局显存读写。 + +### 2.3 IVF-Flat 检索路径 + +IVF-Flat 的建库阶段将数据库划分为 `nlist` 个聚类桶。查询阶段首先计算查询与全部聚类中心的分数,再选择最相关的 `nprobe` 个桶,仅扫描这些桶中的原始向量。与乘积量化方法[2]不同,IVF-Flat 不压缩桶内向量,因此已扫描候选的距离仍按原始精度计算;它的近似性来自只扫描部分倒排桶,而非扫描整个数据库。 + +单批查询的 GPU 流程包括以下五个阶段: + +1. 计算查询向量与聚类中心的距离或相似度; +2. 选择每个查询对应的 `nprobe` 个倒排桶; +3. 将“查询-桶”组合转换为可并行执行的扫描任务; +4. 扫描桶内向量并维护局部 Top-K 候选; +5. 合并同一查询的局部候选,输出最终 ID 与分数。 + +数据库向量、聚类中心和主要工作区在查询期间常驻显存。每批查询只传输查询向量与最终结果,因此稳定查询性能不包含数据库重复上传成本。索引加载和数据库上传作为一次性开销单独记录。 + +### 2.4 评价指标 + +本文使用以下指标评价正确性、性能与资源占用。 + +| 指标 | 定义与用途 | +|---|---| +| QPS | 每秒完成的查询数量,用于评价系统吞吐 | +| Recall@K | 近似 Top-K 与精确 Top-K 的平均重合比例,用于评价检索精度 | +| P50 / P99 | 延迟分布的第 50 / 99 百分位数;本文分别对整轮延迟和批次延迟进行统计 | +| 显式 GPU 缓冲区 | 程序可直接统计的索引与工作区内存,不包含驱动和运行时内部保留 | +| nlist | 建库阶段的聚类中心数量,决定倒排索引粒度 | +| nprobe | 单次查询扫描的桶数量,通常越大召回率越高、计算量也越大 | + +## 3 CUDA 并行设计与优化 + +### 3.1 面向不同 K 值的候选维护 + +候选维护开销与 K 密切相关。K 较小时,局部 Top-K 缓冲区较小,可以为同一桶分配更多线程束以提高扫描并行度;K 增大后,复制多份候选缓冲区会增加共享内存占用、候选更新和最终归并成本。WarpFusion 因此按照 K 的范围调整每个桶的线程束数量,并对 K=50 与 K=100 分别评估更细的候选结构。 + +| K 范围 | 基础并行方式 | 设计依据 | +|---:|---|---| +| 1-10 | 每个桶 8 个局部候选缓冲区 | 候选集合较小,可通过增加扫描并行度提高吞吐 | +| 11-50 | 每个桶 2 个局部候选缓冲区 | 在扫描并行度与归并开销之间折中 | +| 51-100 | 每个桶 1 个完整候选缓冲区 | 限制大候选集合的复制与维护成本 | +| K=50/100 优化 | 多个容量受限的分区候选缓冲区 | 降低单个大候选结构的更新成本 | + +该策略的核心不是预设某种数据结构一定更优,而是针对不同 K 值控制局部状态规模和并行任务数量。所有候选结构均以端到端查询时间和最终输出正确性为验收依据。 + +### 3.2 分区局部 Top-K + +当 K 较大时,单个完整候选缓冲区的更新与排序开销逐渐增加。分区局部 Top-K 将同一扫描任务分配给多个线程束,每个线程束只保留一定数量的局部候选,最后再归并全部局部结果。下文以“4×40”表示 4 个线程束各保留 40 项候选;例如 K=100 时,系统最终从 160 个中间候选中选出 100 项。类似地,“4×16”表示 4 个线程束各保留 16 项候选。 + +该方法以较小的局部状态换取更高并行度,但局部容量不足可能在归并前丢弃真实 Top-K 元素。因此本文不将吞吐提升作为唯一启用条件,而是同时运行完整候选路径进行对照。若任一 `nprobe` 配置的召回率损失超过 1 × 10^(-4),该数据集的正式结果自动回退到完整候选路径。这一机制使优化策略与正确性约束保持一致。 + +### 3.3 按桶任务调度 + +常规任务顺序以查询为主:完成一个查询的多个桶任务后,再处理下一个查询。该顺序实现简单,但来自不同查询、访问同一倒排桶的任务在时间上可能相距较远。WarpFusion 增加按桶调度方式,对一个批次内的“查询-桶”任务重新排序,使访问相同或相邻桶的任务更集中地提交给 GPU。 + +任务重排不减少距离计算次数,也不改变候选集合及最终输出。其潜在收益来自相邻任务对相同桶向量的重复访问,从而提高缓存数据被再次使用的机会。由于当前实验环境无法获取 Nsight Compute 的缓存命中率等硬件计数器,本文将缓存复用作为基于访问模式和计时结果的机制解释,而不将其表述为已经直接测量的硬件结论。 + +### 3.4 多线程索引构建 + +IVF 建库主要包含训练样本到中心的分配,以及全部数据库向量到倒排桶的分配。两部分均采用固定连续区间的 CPU 多线程并行方式:各线程维护局部统计,完成后再按固定次序合并。与共享计数器上的细粒度同步相比,该设计减少了锁竞争,同时保持建库结果和桶内布局的确定性。 + +## 4 实验设计 + +### 4.1 实验平台与数据集 + +正式 GPU 实验运行在 NVIDIA GeForce RTX 4090 D 上,显存容量为 24,564 MiB,CUDA 计算能力为 8.9,CUDA 工具链版本为 12.8.61。CPU 平台为双路 Intel Xeon Platinum 8358P,共 64 个物理核心。程序采用 Release 模式,并针对当前 GPU 架构编译。 + +实验使用一组合成数据和三个真实数据集,以覆盖参数分析、公开基准、文本向量和非均匀数据分布。 + +| 数据集 | 数据规模与维度 | 查询数 | 距离度量 | 主要用途 | +|---|---:|---:|---|---| +| Synthetic-1M | 1,000,000 × 128 | 1,000 | 内积 | 参数扫描与优化消融 | +| MNIST | 60,000 × 784 | 10,000 | L2 | 非均匀真实分布检查 | +| SIFT1M | 1,000,000 × 128 | 10,000 | L2 | 公开标准近邻集合与 FAISS 对照 | +| Yahoo MiniLM | 677,305 × 384 | 1,000 | 余弦 | 文本嵌入数据与 FAISS 对照 | + +SIFT1M 和 Yahoo MiniLM 均提供预先计算的 Top-100 标准近邻集合(ground truth)[3]。数据准备阶段检查公开文件的校验和,并记录格式转换后文件的 SHA-256,以降低数据版本差异对结果的影响。 + +### 4.2 对照设置与计时方法 + +WarpFusion 与 FAISS 使用相同的数据集、K、批大小、`nlist`、`nprobe`、训练样本数和训练轮数。两套系统分别训练聚类中心,因此本文比较的是相同训练与搜索预算下的端到端系统表现,而不是共享同一索引后单个 CUDA 核函数的速度。 + +不同实验采用与其目的相匹配的重复设置。图 2 的距离矩阵与融合路径成对 A/B 实验预热 1 次并重复 5 次;Synthetic-1M 后续正式参数对照预热 5 次并重复 100 次;公开数据实验预热 1 次并重复 5 次。QPS 根据查询总数和整轮平均时间计算;整轮延迟和批次延迟均分别统计 P50 与 P99。索引加载和数据库上传不计入稳定查询 QPS,但相关耗时和显存占用仍保留在原始结果中。进行优化前后对照时,除被考察因素外,其余输入和运行参数均保持一致。 + +### 4.3 正确性与优化验收标准 + +Exact 路径逐查询比较 Top-K 向量 ID 和分数。IVF 路径报告 Recall@K、最低单查询召回率和分数误差。对于距离完全相同但 ID 不同的候选,系统重新计算原始分数,以区分数值或排序错误与等价近邻的不同选择。 + +任何优化在出现以下情况之一时均不进入默认路径:Exact 输出集合不一致;分数误差超过预设容差;IVF 召回率损失超过设定阈值;或 Compute Sanitizer 检测到越界访问。该验收规则用于避免以正确性退化换取表面性能提升。 + +## 5 实验结果与分析 + +### 5.1 正确性与稳定性 + +发布验证在全新构建目录中完成 CTest 18/18。稳定性测试覆盖 FP32/FP16、L2/内积/余弦、64/128/384/768 维、批大小 1/8/32/40/64/128,以及 K=1/10/50/100。边界场景包括 65 维非对齐输入、查询数不足一个完整批次、空桶、倾斜桶、重复向量和全零查询。 + +完整测试矩阵包含 576 组 Exact CPU/GPU 对照和 48 组 IVF 极端桶分布对照。`compute-sanitizer --tool memcheck` 对稳定性测试报告 0 个错误。在发布前的最小 GPU 查询测试中,Exact 与全桶 IVF 均与 CPU 候选集合一致,平均绝对分数误差为 3.04 × 10^(-6),最大分数误差为 9.6 × 10^(-6)。这些结果表明,后续性能比较所采用的实现已经通过边界条件和内存安全检查。 + +### 5.2 Exact 融合路径 + +![Exact 融合路径吞吐](../results/figures/report-exact-fused.svg) + +**图 2.** Synthetic-1M 上距离矩阵基线与融合 Exact 路径的吞吐对比。随着 K 增大,距离矩阵路径的二次读取与 Top-K 选择开销更为显著。 + +| K | 距离矩阵 QPS | 融合路径 QPS | 加速比 | 显式 GPU 缓冲区(基线 / 融合) | +|---:|---:|---:|---:|---:| +| 10 | 1,775 | 5,564 | 3.13× | 734 / 488 MiB | +| 50 | 716 | 5,123 | 7.16× | 732 / 489 MiB | +| 100 | 444 | 4,701 | 10.59× | 733 / 490 MiB | + +两条路径返回的 Top-K 候选集合完全一致,记录的最大分数误差为 0。融合路径的吞吐优势随 K 增大而扩大:K=10 时加速比为 3.13×,K=100 时达到 10.59×。这一趋势说明,基线的主要额外成本不仅是距离矩阵写回,还包括随后针对更大 K 执行的矩阵读取和候选选择。融合实现同时将显式 GPU 缓冲区从约 733 MiB 降至约 490 MiB,减少约三分之一。 + +为验证 GPU 实现相对 CPU 精确检索的实际收益,本文在相同的 Synthetic-1M、FP32、内积和批大小 64 条件下,将 WarpFusion Exact 与单线程 FAISS CPU Flat 进行对照。GPU 结果预热 5 次并重复 100 次,CPU 结果重复 20 次;两者均执行完整精确检索,不涉及召回率损失。 + +| K | FAISS CPU Flat QPS | WarpFusion Exact QPS | GPU / CPU 加速比 | +|---:|---:|---:|---:| +| 10 | 76.45 | 6,678 | 87.35× | +| 50 | 76.45 | 5,974 | 78.15× | +| 100 | 73.55 | 5,406 | 73.51× | + +该对照表明,WarpFusion Exact 在百万规模数据上相对单线程 CPU 基线取得 73.51× 至 87.35× 的吞吐提升,满足主要计算由 GPU 加速的项目目标。表中数据来自独立的正式重复实验,因此不与图 2 中专门用于比较两条 GPU 路径的成对 A/B 数据混用。 + +上述结果证明融合设计优于项目内部基线,但不能据此得出 Exact 已超过成熟库的结论。在 SIFT1M 上,WarpFusion Exact 仍比 FAISS GPU Flat 慢 2.94 至 3.51 倍;在 384 维 Yahoo MiniLM 上慢 5.88 至 6.25 倍。为进一步定位内部耗时,本文拆分了融合路径的 GPU 执行阶段。 + +![Exact 耗时构成](../results/figures/report-exact-breakdown.svg) + +**图 3.** Exact 融合路径的 GPU 执行时间分解。距离计算及数据库读取占总核函数时间的 80.7% 至 98.7%,最终候选归并占比较低。 + +在 128 维、K=100 的配置中,局部候选维护约占 18.3%,说明大 K 已使 Top-K 更新成为不可忽略的成本;在 384 维数据上,距离计算和数据库读取仍占绝对主导。由此可见,仅继续缩短最终归并阶段难以显著提高整体吞吐。更有价值的方向包括跨查询复用数据库读取,以及为 K=50/100 设计更低开销的候选选择结构。 + +Nsight Systems 2024.6.2 的代表性采样进一步验证了这一判断。在 Synthetic-1M、K=10、批大小 64 的运行中,融合距离计算与局部 Top-K 核函数占 GPU 核函数总时间约 99.9%,最终归并核函数约占 0.1%。程序内部阶段计时得到的结果与之相符:融合核函数平均耗时 144.49 ms,最终归并平均耗时 0.21 ms。由此可以确认,当前 Exact 路径的主要优化对象是数据库读取、距离计算和局部候选维护,而不是最终归并。该分析使用 Nsight Systems 的时间线和核函数统计;由于平台未开放性能计数器,本文不据此推断缓存命中率或实际显存带宽。 + +### 5.3 K=50 条件下的按桶调度 + +![K=50 按桶调度](../results/figures/report-k50-scheduling.svg) + +**图 4.** Synthetic-1M、批大小 40、K=50 时,按查询顺序与按桶顺序调度的吞吐对比。随着 `nprobe` 增加,按桶调度的相对收益逐步扩大。 + +在 `nprobe=160` 的 100 次正式对照中,原始任务顺序达到 6,009 QPS,按桶调度达到 6,964 QPS,提升 15.89%;整轮 P99 从 169.04 ms 降至 145.53 ms,且输出逐项一致。该结果说明,在计算量和候选集合不变的条件下,改变任务访问顺序即可改善吞吐与尾部延迟。 + +在按桶调度基础上采用 4×16 分区候选后,吞吐进一步提高至 7,934 QPS,相较完整候选路径提高 10.73%。同为批大小 40、`nprobe=160` 时,FAISS GPU IVF-Flat 达到 8,328 QPS、Recall@50 为 0.92312;WarpFusion 达到 7,934 QPS、Recall@50 为 0.92482。以 WarpFusion 为基准,FAISS 的吞吐高 4.97%。 + +但 4×16 分区候选在两套公开数据上分别产生 0.000326 和 0.000980 的召回率损失,即 0.0326 和 0.0980 个百分点,均超过 1 × 10^(-4) 的验收阈值。因此,公开数据的 K=50 正式结果使用完整候选路径。该结果表明,合成数据上的输出一致不能替代真实数据上的召回率验证,局部候选容量需要随数据分布重新评估。 + +### 5.4 K=100 条件下的分区候选结构 + +![K=100 分区候选](../results/figures/report-k100-partitioned.svg) + +**图 5.** SIFT1M 上 K=100 的完整候选路径与 4×40 分区候选路径。两条路径在全部测试 `nprobe` 点上取得相同 Recall@100。 + +与 K=50 不同,K=100 的 4×40 分区候选在两套公开数据上均通过召回率检查。在 `nprobe=160` 时,SIFT1M 的吞吐从 12,591 QPS 提高到 17,362 QPS,加速比为 1.38×;Yahoo MiniLM 从 8,261 QPS 提高到 14,196 QPS,加速比为 1.72×。两套数据的全部六个 `nprobe` 点均未观测到召回率下降,因此 K=100 的正式路径保留分区候选优化。 + +K=50 与 K=100 使用相似的分区思路,却在公开数据上表现出不同的可靠性。这说明分区数量和局部容量之间不存在仅由 K 决定的通用配置;候选分布、桶规模和数据相似度结构都会影响局部截断风险。因此,每个数据集和参数点都需要用完整候选路径复核,不能将合成数据上的最优配置直接视为通用配置。 + +### 5.5 公开数据集上的 FAISS 对照 + +![公开数据 Recall-QPS 权衡](../results/figures/report-recall-qps.svg) + +**图 6.** SIFT1M 与 Yahoo MiniLM 在 K=10 时的 Recall-QPS 曲线。每条曲线包含 `nprobe=32/64/128/160/192/224` 六个实测点,展示增加搜索桶数量后召回率提高、吞吐下降的完整变化过程。 + +在 SIFT1M 的六个 `nprobe` 点上,WarpFusion 的 Recall@10 均略高于 FAISS,吞吐比从 1.05× 增加到 1.95×。在 Yahoo MiniLM 上,`nprobe=32` 时两者召回率几乎相同,WarpFusion 的吞吐比为 1.21×;随着 `nprobe` 增加到 224,吞吐比提高到 2.70×,但 Recall@10 低 0.05 个百分点。由于两套系统分别训练聚类中心,曲线不能视为共享索引条件下的核函数对照,但它表明下表所选的 `nprobe=160` 并非孤立的有利参数点。 + +![公开数据对比](../results/figures/report-real-comparison.svg) + +**图 7.** SIFT1M 与 Yahoo MiniLM 在 `nprobe=160`、批大小 64 条件下的端到端吞吐。柱顶给出 WarpFusion 相对 FAISS 的吞吐比,柱下给出两者 Recall@K。 + +| 数据集 | K | WarpFusion Recall / QPS | FAISS GPU Recall / QPS | 吞吐比 | +|---|---:|---:|---:|---:| +| SIFT1M | 10 | 0.999870 / 24,579 | 0.999120 / 13,617 | 1.81× | +| SIFT1M | 50 | 0.999706 / 19,237 | 0.999516 / 13,443 | 1.43× | +| SIFT1M | 100 | 0.999565 / 17,362 | 0.999457 / 13,102 | 1.33× | +| Yahoo MiniLM | 10 | 0.993900 / 15,733 | 0.995300 / 6,216 | 2.53× | +| Yahoo MiniLM | 50 | 0.991520 / 14,950 | 0.991280 / 6,157 | 2.43× | +| Yahoo MiniLM | 100 | 0.989230 / 14,196 | 0.989080 / 6,060 | 2.34× | + +在 SIFT1M 上,WarpFusion 的三组 Recall@K 均略高于 FAISS,对应吞吐比为 1.33× 至 1.81×。在 Yahoo MiniLM 上,K=50 和 K=100 的召回率与 FAISS 接近,吞吐比分别为 2.43× 和 2.34×;K=10 的吞吐比为 2.53×,但 Recall@10 低 0.0014,即低 0.14 个百分点。因而 Yahoo K=10 的结果应理解为较高吞吐下的轻微精度差异,而不能只报告速度优势。 + +两套系统分别训练聚类中心,因此倒排桶及候选集合并不完全相同。这组对照反映的是在相同训练参数和搜索预算下,完整 IVF-Flat 流程的系统表现,而不是单个 GPU 核函数之间的直接速度比较。公开标准近邻集合与 WarpFusion Exact 结果之间存在极少数分数相同但 ID 不同的情况;重新计算原始分数后,两套数据按分数判断的等价查询比例均为 1.0。SIFT1M 的名次和分数误差均为 0,Yahoo 的最大分数误差为 2.98 × 10^(-7),说明召回率结果没有因 Exact 参考结果错误而被系统性抬高。 + +### 5.6 延迟、显存与索引构建 + +在 Synthetic-1M 的 IVF-Flat 推荐配置上,K=10/50/100 分别达到 5,697、7,934 和 7,205 QPS,整轮 P99 分别为 176.8、127.8 和 140.6 ms,显式 GPU 缓冲区约为 497 至 508 MiB。K=50 的吞吐高于 K=10 并不表示更大的 K 天然更快,而是因为不同 K 使用了不同批大小、并行配置和候选路径,结果应在各自推荐配置内解释。 + +公开数据 `nprobe=160` 时,WarpFusion IVF 的显式 GPU 缓冲区在 SIFT1M 上为 498 至 509 MiB,在 Yahoo MiniLM 上为 1,000 至 1,011 MiB。FAISS 分别报告 504 MiB 和 1,022 MiB 的索引显存,并额外预留 1,536 MiB 临时显存。由于两套系统的内存统计口径并非完全相同,本文仅将其作为资源规模参考,不据此宣称确定的显存优势。 + +Synthetic-1M 的索引构建时间从单线程 67.53 秒降至 16 线程 6.48 秒,加速 10.43 倍。继续增加到 32 或 64 线程后性能反而下降,表明该双路 CPU 平台已受到同步、归并和 NUMA 访问开销影响。因此默认线程上限设为 16,而不是简单使用全部逻辑核心。 + +### 5.7 MNIST 补充实验 + +MNIST 的规模小于两套百万级数据,但其分布与均匀随机向量存在明显差异。Exact K=10 达到约 23,100 QPS;IVF 在 `nprobe=8` 时取得 Recall@10=0.9784 和约 197,700 QPS,在 `nprobe=32` 时取得 Recall@10=0.9991 和约 76,600 QPS。该实验一方面说明实现并非只在均匀合成数据上有效,另一方面展示了 IVF 的基本精度-性能权衡:增加搜索桶数量可以提高召回率,但会增加扫描工作量并降低吞吐。 + +## 6 未采用方案及原因分析 + +为了避免仅保留正向结果,本文同时记录未进入默认实现的优化方案。 + +1. **预计算余弦范数。** 该方案在 Yahoo K=100 上提高约 2.5%,但在其他配置中下降 1% 至 2.6%。收益缺乏一致性,因此未作为默认路径。 +2. **线程块级数据库分块。** 该实现优于项目早期基线,但仍比最终采用的跨查询线程束方案慢 2.3% 至 31.4%。其额外同步与数据搬运未能抵消局部复用收益,故仅保留为实验入口。 +3. **自适应 `nprobe`。** 在当前 Synthetic-1M 上,该方案相较相同平均搜索桶数的固定策略慢 1.0% 至 3.6%,召回率也略低。由于合成查询的难度差异有限,自适应决策成本没有转化为有效收益。 + +这些负向结果进一步明确了潜在优化方向。Exact 路径的首要问题仍是数据库读取与高维距离计算;大 K 场景需要更高效且具有安全容量约束的候选结构;自适应搜索则更适合在查询难度差异显著的数据集上重新评估。 + +## 7 适用范围、局限与复现 + +### 7.1 结论适用范围 + +本文实验结论受以下条件约束: + +1. 正式 GPU 数据来自单张 RTX 4090 D,不能直接外推至 T4、A100、H100、Blackwell 或其他架构; +2. 系统面向单进程、单 GPU、数据常驻显存的静态 IVF-Flat,不包含 PQ/SQ 压缩、动态增删、超显存分块和多 GPU 执行; +3. Exact 融合路径虽然显著优于内部距离矩阵基线,但仍明显落后 FAISS GPU Flat;当前性能优势主要出现在本文测试的 IVF-Flat 配置中; +4. IVF 参数与分区候选容量依赖数据分布、维度和硬件,更换平台或数据后需要重新扫描并执行召回率回退检查。 + +### 7.2 硬件分析的限制 + +当前实验环境无法读取 Nsight Compute 的硬件计数器,因此本文未直接报告 GPU 占用率(occupancy)、实际显存带宽、缓存命中率和线程停顿原因。关于按桶调度改善缓存复用、Exact 主要受数据库读取限制等判断,来自对访问模式、阶段计时和性能趋势的综合分析,尚未得到硬件计数器的直接验证。该限制不影响吞吐和正确性结果本身,但使本文暂时无法对底层原因作进一步的定量归因。 + +### 7.3 参数迁移要求 + +IVF 的最优 `nlist`、`nprobe`、批大小和候选分区容量与数据分布、向量维度及 GPU 架构相关。本文给出的推荐配置仅代表 RTX 4090 D 和当前数据集上的测量结果。迁移至其他数据或硬件时,应重新执行吞吐-召回率扫描,并以完整候选路径复核分区候选结构,避免直接沿用参数导致精度或性能退化。 + +### 7.4 实验复现与材料组织 + +`scripts/reproduce.py` 将全新构建、CTest、公开数据准备、WarpFusion 与 FAISS 基准测试、绘图、PDF 生成和发布校验组织为连续流程。各阶段分别保存日志,并通过检查点(checkpoint)支持中断后继续执行。发布校验会检查公开数据 CSV 字段、稳定性矩阵、SVG 图表和最终 PDF。 + +仓库保留原始 CSV、运行环境快照、数据校验和、标准近邻集合检查结果以及 Compute Sanitizer 日志。公开数据的完整实验命令见 `docs/REPRODUCIBILITY.md`,命令行参数和错误处理规则见 `docs/API.md`。这些材料用于支持结果核验和实验复现,是保证实验结论可信的重要依据。 + +## 8 结论与可扩展方向 + +本文完成了 WarpFusion 单 GPU 向量检索系统的设计、实现与评估。系统覆盖数据格式、索引构建、CPU 参考计算、GPU Exact、GPU IVF-Flat、结果验证和性能记录,重点研究距离计算、候选维护和任务调度之间的协同优化。 + +实验结果表明,融合距离计算与局部 Top-K 可以避免完整距离矩阵的中间读写,使 Exact 路径相较内部基线的加速比达到 3.13× 至 10.59×,相对单线程 FAISS CPU Flat 的加速比达到 73.51× 至 87.35×。K=50 时,按桶任务调度使吞吐提高 15.89%;分区候选在合成数据上又提高 10.73%,但未通过公开数据的召回率门槛。K=100 时,4×40 分区候选在两套公开数据上均未降低召回率,内部加速比为 1.38× 至 1.72×。在相同训练参数和搜索预算下,WarpFusion IVF-Flat 在 SIFT1M 和 Yahoo MiniLM 六组实验中的吞吐为 FAISS GPU IVF-Flat 的 1.33× 至 2.53×。 + +上述结果说明,GPU 向量检索性能不能仅依靠距离计算核函数优化,还取决于中间结果规模、候选结构和任务访问顺序。实验也表明,合成数据上的最优策略未必能够安全应用于真实数据,因此性能优化必须与正确性和召回率检查共同进行。 + +在现有工作基础上,系统仍可从三个方向进一步扩展:利用 Nsight Compute 对显存访问与缓存行为进行定量分析;研究面向 K=50/100 的低开销、可证明容量安全的候选选择结构;在不同 GPU 架构和更大规模数据上重新评估参数与性能,以判断当前优化的硬件适用范围。上述方向超出本文的实验范围,不影响当前系统实现、正确性验证与性能结论的完整性。 + +## 参考文献 + +1. J. Johnson, M. Douze, and H. Jégou. Billion-scale similarity search with GPUs. IEEE Transactions on Big Data, 2019. +2. H. Jégou, M. Douze, and C. Schmid. Product quantization for nearest neighbor search. IEEE Transactions on Pattern Analysis and Machine Intelligence, 2011. +3. M. Aumüller, E. Bernhardsson, and A. Faithfull. ANN-Benchmarks: A benchmarking tool for approximate nearest neighbor algorithms. Information Systems, 2020. diff --git a/09_vector_retrieval/PurplePulse/docs/REPRODUCIBILITY.md b/09_vector_retrieval/PurplePulse/docs/REPRODUCIBILITY.md new file mode 100644 index 00000000..e1a0f3af --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/REPRODUCIBILITY.md @@ -0,0 +1,514 @@ +# WarpFusion 正式实验复现记录 + +## 2026-09-11 第九阶段工程化入口 + +统一入口为: + +```bash +mkdir -p results/real/reproducibility/logs +nohup python3 scripts/reproduce.py --project-root "$PWD" --resume \ + > results/real/reproducibility/nohup.log 2>&1 & +``` + +默认流水线包含 CMake/Ninja Release 构建、完整 CTest、SIFT1M 与 Yahoo MiniLM +384 维数据准备、WarpFusion/FAISS Exact 与 IVF-Flat 对照、两套图表、技术报告 +PDF 和发布校验。`--dataset` 可只选择一套数据,`--skip-download` 与 +`--skip-index-build` 用于复用已核验产物,`--dry-run` 输出完整绝对路径计划而不 +执行。每个阶段写独立日志,完成一步后原子更新 +`results/real/reproducibility/checkpoint.json`;中断后 `--resume` 不重复已经成功 +的步骤。 + +发布校验器: + +```bash +python3 scripts/validate_release.py \ + --project-root "$PWD" \ + --report output/pdf/WarpFusion_Technical_Report.pdf \ + --json-output evidence/2026-09-11/stage9/release-validation.json +``` + +它检查两套公开数据的 10 个正式 CSV、Stage 8 覆盖矩阵、架构/性能 SVG、核心 +文档标记和 PDF 完整性。它不会启动长实验,因此适合作为复现流水线的最后一道 +fail-closed 检查。 + +干净 Linux + CUDA 验证使用 CUDA 12.8、GCC 13.3、RTX 4090 D 和全新构建目录, +并以 257 vectors、65 维、13 queries 的 FP32/L2 数据运行 Exact CPU/GPU 与 +IVF CPU/GPU。IVF 使用 nlist=16、nprobe=16,确保最小查询同时校验索引读写和 +全 probe CPU/GPU 等价。CTest 18/18 通过;Exact 与 IVF 各输出 130 行,候选 +集合相同,平均绝对分数误差 3.039×10⁻⁶,最大误差 9.6×10⁻⁶,无近似并列换位。 + +远端 `nohup` 任务结果位于 +`/data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/`,阶段状态、 +单项日志、摘要和输出校验和均分阶段落盘。仓库仅保留小型证据: +`evidence/2026-09-11/stage9/`。首次配置因非登录 shell 的 `PATH` 不含 +`/usr/local/cuda/bin` 而 fail-closed;修正 PATH 后使用新的 `-v2` 目录重跑, +没有删除或复用失败构建,也没有重复已经完成的 SIFT1M 或 Yahoo MiniLM 长实验。 + +## 2026-09-10 第八阶段稳定性矩阵 + +新增 `stability_tests`,使用包含重复向量与全零 query 的确定性、FP16 可精确 +表示数据。Exact 主矩阵覆盖 64/128/384/768 维、batch +1/8/32/40/64/128、K=1/10/50/100、FP32/FP16 和 L2/IP/cosine,共 576 组; +另用 65 维覆盖非整 warp 和每种 `batch+1` query 的满 batch + 尾 batch。 + +IVF 测试人工构造 8 个桶:4 个空桶,最大桶包含 125/128 个向量。在 65 维、 +K=1/10/50/100、FP32/FP16、三种 metric 下分别运行 warp 与 bucket-major, +共 48 组。所有 GPU 结果均按 query/rank 比较 ID 与 score;相同分数验证较小 +ID 优先,而不是只比较 recall 或结果数量。 + +远端任务与结果: + +- `stage8-stability-build-20260910`:nohup 构建和完整 CTest,状态 0,14/14。 +- `stage8-stability-sanitizer-20260910`:先落盘覆盖摘要,再运行 + `compute-sanitizer --tool memcheck`,状态 0、0 errors。 +- 结果目录:`/data/purplepulse-work/PurplePulse/results/stage8_stability/`;仓库 + 保存 `../results/stage8_stability/coverage.csv`,大日志继续只留在 `/data`。 + +保守的 Exact/IVF 实现选择、GPU 适用范围和 fail-closed 回退规则见 +`STABILITY_MATRIX.md`。FP16、非 batch64、64/768 维或其他 GPU 虽已验证正确性, +但没有被错误标记为已有正式性能调优;这些组合默认回退到完整 warp-query heap。 + +## 2026-09-10 第七阶段 Exact fused 剖析 + +新增 `--profile-breakdown 1 --profile-repeat N` 和 +`scripts/benchmark_exact_breakdown.py`。剖析器使用与 fused 路径相同的网格、 +query cache 和距离归约运行一个 distance-only kernel;该 kernel 每个 warp +仅写一个 checksum,以阻止编译器删除计算。最终归并由 CUDA event 直接计时, +局部 Top-K 则定义为 `fused kernel - distance-only kernel`。因此它是可复现的 +differential estimate,不应解释为三个硬件计数器区间的严格可加时间线。 + +正式运行使用 RTX 4090 D、batch=64、预热 5 次、查询重复 20 次、剖析重复 +20 次。正式基线先完成候选集合与分数校验;随后同一基线在 A/B 复测中使用加严 +后的驱动,按 query、rank、候选 ID 和分数与既有 Exact 参考逐项比较。结果如下。 + +| 数据集 | K | QPS | distance-only | 局部 Top-K 估算 | 最终归并 | 占比(距离 / 局部 / 归并) | +|---|---:|---:|---:|---:|---:|---:| +| Synthetic-1M | 10 | 6743 | 144.94 ms | 2.38 ms | 0.19 ms | 98.26% / 1.61% / 0.13% | +| Synthetic-1M | 50 | 6083 | 145.53 ms | 17.13 ms | 0.83 ms | 89.02% / 10.48% / 0.51% | +| Synthetic-1M | 100 | 5484 | 146.29 ms | 33.08 ms | 1.86 ms | 80.72% / 18.25% / 1.03% | +| Yahoo MiniLM 384 | 10 | 3525 | 279.28 ms | 3.40 ms | 0.19 ms | 98.73% / 1.20% / 0.07% | +| Yahoo MiniLM 384 | 50 | 3366 | 280.78 ms | 13.61 ms | 0.88 ms | 95.09% / 4.61% / 0.30% | +| Yahoo MiniLM 384 | 100 | 3172 | 281.07 ms | 30.70 ms | 2.00 ms | 89.58% / 9.79% / 0.64% | + +完整 CSV 位于 `../results/stage7_exact_profile/`。这组结果把后续优先级指向 +数据库读取与跨 query 数据复用;只优化最终 merge 不可能达到阶段目标。 + +### 已否决:cosine 范数预计算 + +第一项 A/B 尝试在建库时预计算数据库范数,并在每批预计算 query 范数,避免 +cosine fused kernel 重复归约范数。基线和候选版本在同一任务中顺序运行,均 +预热 5 次、重复 20 次,并通过逐 query、逐 rank 的 ID/score 校验。 + +| 数据集 | K | 基线 QPS | 候选 QPS | 候选 / 基线 | +|---|---:|---:|---:|---:| +| Synthetic-1M | 10 | 6741 | 6628 | 0.983× | +| Synthetic-1M | 50 | 6067 | 5993 | 0.988× | +| Synthetic-1M | 100 | 5478 | 5425 | 0.990× | +| Yahoo MiniLM 384 | 10 | 3497 | 3407 | 0.974× | +| Yahoo MiniLM 384 | 50 | 3341 | 3330 | 0.997× | +| Yahoo MiniLM 384 | 100 | 3160 | 3240 | 1.025× | + +该方案只在 Yahoo K=100 提升 2.5%,Yahoo K=10 下降 2.6%,Synthetic 全部 +下降 1%--2%,因此未进入默认代码。候选版本源码已撤回,基线与候选 CSV、 +二进制/源码校验和、恢复后的当前源码校验和及可重放脚本保存在 +`../results/stage7_exact_profile/cosine_norm_ab/` 与 +`../evidence/2026-09-10/stage7/`。撤回后在远端重新构建,CTest 12/12 通过。 + +### 已保留:跨 query 数据库读取复用 + +`exact_query_tile=2/4/8` 让一个 fused block 对同一向量 chunk 同时计算多个 +query,每个数据库分量只从全局显存读取一次,再用于 tile 内所有 query。 +`exact_fused_blocks=N` 可固定 `grid.x`;默认值 0 使用并行度启发式。初版直接 +减少 `grid.y` 导致并行度下降,修订版按 query tile 放大 `grid.x`,使总 block +数维持在约 1024。两版 smoke 均保留在结果目录,避免只报告成功版本。 + +正式项统一预热 5 次、重复 20 次,驱动在每个 variant 后 checkpoint CSV,并 +按 query、rank、ID 和 score 与第六阶段 Exact 参考逐项校验。 + +| 数据集 | K | 基线 QPS | 最佳配置 | 最佳 QPS | 加速 | +|---|---:|---:|---|---:|---:| +| Synthetic-1M | 10 | 6739 | tile4 / 64 blocks | 9250 | 1.373× | +| SIFT1M | 10 | 6940 | tile4 / 64 blocks | 9228 | 1.330× | +| Yahoo MiniLM 384 | 10 | 3577 | tile8 / 160 blocks | 6747 | 1.887× | +| Yahoo MiniLM 384 | 50 | 3363 | tile4 / 64 blocks | 4074 | 1.211× | + +Synthetic/SIFT K=50 的最佳策略仍是 baseline;tile2 分别为 0.986×/0.962×, +tile4 为 0.917×/0.890×。K=100 smoke 中 tile2/tile4 在 Synthetic 仅为 +0.684×/0.567×,Yahoo 为 0.712×/0.698×,因此没有继续正式长跑。K=10 的 +最终归并仍低于 0.3 ms;Yahoo 最佳配置相对 baseline 只增加约 1.06 MiB +显式 buffer。完整 CSV 位于 `../results/stage7_exact_query_tile/`,源码与配置 +校验和位于 `../evidence/2026-09-10/stage7/query_tile_source.sha256`。 + +优化后的 K=10 相对 FAISS GPU Flat 差距为 Synthetic 2.30 倍、SIFT1M +2.24 倍、Yahoo 3.15 倍,尚未达到 2 倍阶段门槛。后续应改用 block 级数据库 +tile 保持 query 并行度,或针对 K=50/100 比较专用选择结构,而不是继续扩大 +同一 warp 内的 query tile。 + +### 已否决:block 级数据库 tile + +`exact_fused_layout=block_tile` 让一个 block 的 8 个 warp 各自负责一个 query, +并通过共享内存复用 8 个数据库向量,目的是避免 query-tile 中单 warp 串行维护 +多个 query heap。筛选统一使用 batch=64、K=10、预热 1 次、重复 3 次,扫描 +`grid.x=64/96/128/160/192`;每个 variant 均与既有 Exact 参考逐 query、逐 rank +比较 ID 和 score。CSV 在每个 variant 完成后落盘。 + +| 数据集 | baseline QPS | warp-query 最优 | block-tile 最优 | block / warp | +|---|---:|---:|---:|---:| +| Synthetic-1M | 6929 | 9265(tile4/64) | 9050(tile8/128) | 0.977× | +| Yahoo MiniLM 384 | 3620 | 6989(tile8/160) | 4794(tile8/128) | 0.686× | + +block-tile 虽分别比未 tiled baseline 快 30.6% 和 32.5%,但没有超过已经接纳的 +warp-query;Yahoo 还退化 31.4%。同步与共享内存中转成本抵消了保留 query +并行度的收益,因此不再运行 SIFT 或 20 次正式长跑。该路径保留为显式 opt-in +负实验,默认 `exact_fused_layout=warp_query` 不变;原始筛选 CSV 位于 +`../results/stage7_exact_block_tile/smoke/`。 + +### 选择结构裁决与阶段验收 + +当前 Exact fused 并非单线程 heap:每个 block 的 8 个 warp 分别维护局部 heap, +块内先合并成 `K` 项,再由第二个 kernel 归并各 chunk,已经是分层 +Warp/Block Top-K。实际运行过的候选物化对照是旧 matrix 路径:它先写回 +`batch × N` score;K=10 使用每线程候选缓冲后归并,K=50/100 使用 block +反复选择。Synthetic-1M K=10/50/100 +分别只有 1775/716/444 QPS,而对应 fused 为 5564/5123/4701 QPS,慢 +3.13--10.59 倍且显式 buffer 多约 33%。 + +对全量 block radix/select 的裁决属于设计边界,不冒充实测:若只保留少量局部 +候选,它仍需先使用 heap/selection 得到这些候选;若要对全部精确 score 做 +radix/select,则必须物化 `batch × N` score,或为每个 radix pass 重算距离。 +前者回到已否决 matrix 路径,后者破坏单遍扫描并放大已经占 80.72%--98.73% +的主瓶颈,因此没有为“列齐算法名称”而实现不可接纳路径。第七阶段最终未达到 +2 倍硬目标,但满足计划规定的失败分支:保存可复现 profile、严格正确性结果、 +被否决方案、默认回退和原因。 + +## 2026-09-10 第六阶段公开数据 + +第六阶段使用 SIFT1M 与 VIBE `yahoo-minilm-384-normalized`。数据准备、校验、 +转换和完整基准入口分别为 `scripts/prepare_real_datasets.py` 与 +`scripts/run_real_benchmarks.py`。公开源与固定校验和如下: + +| 数据集 | 公开源 | 规模 | 校验和 | +|---|---|---:|---| +| SIFT1M | `ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz` | 1M × 128 | MD5 `b23d1b3b2ee8469d819b61ca900ef0ed` | +| yahoo-minilm-384-normalized | `https://huggingface.co/datasets/vector-index-bench/vibe` | 677,305 × 384 | SHA-256 `8b0519850249d7ea4aea258eb43ae837dca1bb2f7a85ee0a5145afdb699c4136` | + +正式矩阵统一使用 nlist=1024、训练样本 100,000、15 次迭代、seed 2026、 +batch=64,以及 K=10/50/100、nprobe=32/64/128/160/192/224。完整命令见 +README 的“第六阶段公开真实数据”。每套结果目录已包含 `build.csv`、 +`exact_gpu.csv`、三份有效 IVF CSV、FAISS GPU CSV、公开 ground truth 验证、 +分区 Top-K 回退判定、环境快照、原始输出和 recall-QPS/latency 图。 + +### 正式结果摘要 + +正式运行使用 RTX 4090 D、CUDA 12.8.61、`batch=64`、预热 1 次和重复 5 次。 +下表固定 `nprobe=160`;两套系统使用相同的 nlist、训练样本、迭代次数、K、 +nprobe 和 batch,但各自训练聚类中心。 + +| 数据集 | K | WarpFusion recall / QPS | FAISS GPU recall / QPS | WF / FAISS | +|---|---:|---:|---:|---:| +| SIFT1M | 10 | 0.999870 / 24579.1 | 0.999120 / 13616.6 | 1.81× | +| SIFT1M | 50 | 0.999706 / 19236.8 | 0.999516 / 13442.7 | 1.43× | +| SIFT1M | 100 | 0.999565 / 17362.2 | 0.999457 / 13102.4 | 1.33× | +| Yahoo MiniLM 384 | 10 | 0.993900 / 15733.2 | 0.995300 / 6216.2 | 2.53× | +| Yahoo MiniLM 384 | 50 | 0.991520 / 14949.7 | 0.991280 / 6157.2 | 2.43× | +| Yahoo MiniLM 384 | 100 | 0.989230 / 14196.2 | 0.989080 / 6059.8 | 2.34× | + +WarpFusion/FAISS IVF 建库时间分别为 SIFT1M 25.47/31.69 秒、Yahoo +87.54/77.89 秒。WarpFusion Exact K=10/50/100 吞吐为 SIFT1M +7038/6337/5622 QPS、Yahoo 3610/3471/3286 QPS。Exact 与公开 ground truth +存在极少数同分 ID 选择差异,但两套数据的 score-equivalent query fraction +均为 1.0;SIFT 的 rank/report score error 为 0,Yahoo 的最大报告分数误差为 +`2.98e-7`。 + +K=50 的分区路径在 SIFT1M 和 Yahoo 上分别损失 0.000326 和 0.000980 recall, +超过预设 `1e-4` 阈值,`ivf_k50.csv` 因此自动复制完整 heap 结果。K=100 在 +两套数据的全部六个 nprobe 点上均保持零 recall 损失,正式结果保留分区路径; +`nprobe=160` 下相对完整 heap 分别快 1.38 倍和 1.72 倍。提交仓库保存 +`results/real/` 下的 CSV、JSON 和 SVG;原始 Top-K 输出与日志保留在实验机 +`/data/purplepulse-work/PurplePulse/results/real/`。 + +## 2026-09-08 增量实验 + +新 GPU 实例仍为 RTX 4090 D / CUDA 12.8,但从空工作目录重新同步源码、配置 +并构建。CTest 8/8 通过,Compute Sanitizer 报告 0 errors。环境、测试与数据 +校验和位于 `../evidence/2026-09-08/`。 + +本轮增加六组结果:K=50 batch 调优、缓存感知桶任务调度、K=100 单 warp +正式 A/B、K=100 分区局部 Top-K、IVF 多线程建库和 MNIST 真实数据。原始 CSV 位于 +`../results/formal_4090d_20260908/`。百万数据并行建库: + +```bash +./build/ivf_build \ + --database data/million/inner_fp32_db.bin \ + --output data/million/inner_fp32_nlist256.ivf \ + --nlist 256 --iterations 15 --training-samples 100000 --threads 16 +``` + +K=50 在 nprobe=160 下先以 10 次重复扫描 batch=8/32/36/40/44/48/56/64/ +80/96/128,再对 batch=40 和 batch=64 各预热 1 次、正式重复 100 次: + +```bash +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_warp_compact_batch40.conf \ + --output results/k50_batch40.txt \ + --backend gpu --warmup 1 --repeat 100 + +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_batch64.conf \ + --output results/k50_batch64.txt \ + --backend gpu --warmup 1 --repeat 100 + +python3 scripts/evaluate_recall.py \ + --exact results/new_gpu/exact_k50.txt \ + --approximate results/k50_batch40.txt +``` + +batch=40 的正式结果为 6019.91 QPS、run P50/P99=166.303/168.097 ms、 +recall@50=0.92482;同实例 batch=64 对照为 5737.20 QPS,严格 A/B 提升 +4.93%。筛选表、warp 对照和原始日志分别位于 +`../results/formal_4090d_20260908/` 与 `../evidence/2026-09-08/`。 + +缓存感知调度使用相同索引、K、batch、nprobe 和输出语义,仅改变 probe block +的执行顺序。正式 A/B 命令为: + +```bash +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_warp_compact_batch40.conf \ + --output results/k50_probe_major.txt \ + --backend gpu --warmup 5 --repeat 100 + +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_bucket_major.conf \ + --output results/k50_bucket_major.txt \ + --backend gpu --warmup 5 --repeat 100 + +cmp results/k50_probe_major.txt results/k50_bucket_major.txt +``` + +K=50 的正式结果为 6009.22 与 6964.16 QPS,提升 15.89%;两份输出完全 +一致。nprobe=32/64/96/128/160/192/224 的扫描结果位于 +`k50_bucket_major_sweep.csv`。K=100 单独启用 bucket-major 提升 2.00%;加入 +heap 根节点寄存器缓存、空穴下沉和单 warp 直写后,同轮 100 次 A/B 从 +5298.37 提高到 5425.61 QPS,再与 bucket-major 组合达到 5491.76 QPS,累计 +提升 3.65%。三条路径的输出逐字一致,该组合构成后续分区实验的完整 heap +基线。 + +K=50 的分区候选筛选包含 2×32、4×20、4×16 与 8×8。未接纳的 2×32、4×20 +和 8×8 分别取得 7.37%、9.51% 与 2.88% 的增益;4×16 是唯一超过 10% 接纳线的 +配置。正式命令为: + +```bash +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_partitioned_4x16.conf \ + --output results/k50_partitioned_4x16.txt \ + --backend gpu --warmup 5 --repeat 100 +``` + +同一二进制的完整 heap 基线为 7165.23 QPS,4×16 为 7934.10 QPS,提升 +10.73%;输出逐字一致,recall@50 均为 0.92482。七个 nprobe 点的增益范围为 +6.04% 至 22.86%,均保持输出一致。原始 CSV、输出和 memcheck 日志位于 +`../results/formal_4090d_20260908/k50_partitioned_tight/`;2×32 与 4×20 记录 +位于 `../results/formal_4090d_20260908/k50_partitioned/`。 + +K=100 的分区局部 Top-K 使用 4 个 warp、每个 warp 40 项局部候选。正式复测 +保持同一二进制、索引、`batch=64` 和 `nprobe=160`: + +```bash +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k100_partitioned.conf \ + --output results/k100_partitioned.txt \ + --backend gpu --warmup 5 --repeat 100 +``` + +完整 heap 基线为 5503.11 QPS,分区路径为 7204.54 QPS,提升 30.92%;两份 +输出逐字一致,recall@100 均为 0.91758。`nprobe=128/160/192/224` 的 10 次 +扫描分别提升 26.49%/31.28%/34.32%/36.80%。原始 CSV、结果文件与 memcheck +日志位于 `../results/formal_4090d_20260908/k100_partitioned/`。 + +三项未采用的 K=100 选择或排序实验记录在 +`results/formal_4090d_20260908/k100_selection_negative.csv`。分布式寄存器 +Top-K 重复 100 次,仅提升 0.43%;buffer-8 快速重复 10 次后退化 22.68%, +因此按停止规则未进入 100 次阶段。原始摘要、资源用量和回退校验见 +`evidence/2026-09-08/k100_selection_negative.log`。 +warp bitonic sort 也在 10 次快速 A/B 中退化 18.72%,输出逐字一致,因而 +同样按停止规则终止。 + +K=50 的 FAISS 同批次补测固定 batch=40、nprobe=160、预热 5 次、重复 100 次。 +隔离环境使用 Python 3.12.3、FAISS GPU 1.14.1 和 NumPy 2.2.6,并复用主机 +CUDA 12.8 的 runtime/cuBLAS。FAISS Flat 与 WarpFusion Exact 的候选 ID +完全一致。FAISS IVF-Flat 为 8328.11 QPS、0.92312 recall@50;WarpFusion +最终 4×16 路径为 7934.10 QPS、0.92482 recall@50,FAISS 吞吐高 4.97%。完整命令见 +`../evidence/2026-09-08/commands.md`,原始 CSV 为 +`../results/formal_4090d_20260908/faiss_gpu_batch40.csv`。 + +MNIST 归档来自 Keras 公共数据地址 +`https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz`。转换、 +建库与扫描命令为: + +```bash +python3 scripts/import_mnist.py \ + --input data/mnist/mnist.npz \ + --database data/mnist/database.bin \ + --queries data/mnist/queries.bin + +./build/ivf_build \ + --database data/mnist/database.bin --output data/mnist/nlist256.ivf \ + --nlist 256 --iterations 15 --training-samples 60000 --threads 16 + +python3 scripts/benchmark_ivf_sweep.py \ + --search-binary ./build/ivf_search \ + --index data/mnist/nlist256.ivf --queries data/mnist/queries.bin \ + --params configs/ivf_flat_mnist.conf \ + --exact results/mnist_exact_k10.txt \ + --output-dir results/mnist_ivf --csv results/mnist_ivf.csv \ + --nlist 256 --nprobes 8,16,32,64,96,128 \ + --training-samples 60000 --training-iterations 15 \ + --warmup 2 --repeat 10 +``` + +下文保留 2026-09-04 的主 FAISS 对照口径。 + +本文固定本轮正式结果的数据、训练、延迟和环境口径。公开结果文件不包含原始 +数据与索引;二者通过生成命令和 SHA-256 校验和审计。 + +## 1. 环境 + +- GPU:NVIDIA GeForce RTX 4090 D,24,564 MiB,compute capability 8.9。 +- Driver:570.124.06。 +- OS:Ubuntu 24.04.1 LTS。 +- CUDA Toolkit / NVCC:12.8 / 12.8.61。 +- CMake / Ninja / GCC:3.31.4 / 1.11.1 / 13.3.0。 +- FAISS 专用 venv:FAISS 1.14.1 GPU,NumPy 2.2.6,Python 3.12.3;CPU + 对照固定 1 线程。系统 Python 不含 FAISS,不用于 FAISS 正式实验。 +- 构建类型:Release,`CMAKE_CUDA_ARCHITECTURES=native`。 + +GPU 机上的部署目录不是 Git checkout。正式实验前,核心源码和本地基准提交 +`fea41f6` 的 SHA-256 逐文件一致;随后新增的评测字段不改变检索 kernel。 +完整环境输出、测试与 profiler 摘要保存在 `../evidence/2026-09-04/`。 + +## 2. 数据与索引 + +```bash +python3 scripts/generate_data.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --num-vectors 1000000 \ + --num-queries 1000 \ + --dim 128 \ + --dtype fp32 \ + --metric inner_product \ + --seed 2026 +``` + +| 文件 | SHA-256 | +|---|---| +| `inner_fp32_db.bin` | `d4dde1418ea7626e5226e594e592f9ae5ffbe4c412c326395d96388f95df9800` | +| `inner_fp32_q.bin` | `a58ebe43fce865b71a2a651791286fa0bd1567348e07d6c0601b69beaebceb45` | +| `inner_fp32_nlist256_spherical_100k15.ivf` | `f5bd87fcc72d37164fa931436e5bfd293dfb7f953d09cb28169a77c7cdadc415` | +| FAISS Flat index | `760e3a94f24c5becfa21e89a57f67395013d5ad5375c20eb3f5d5cfb4c3720a1` | +| FAISS IVF-Flat index(100k/15/seed 2026) | `a66a63bb28ed9e70ae83c042f57a8ca79de3ee01a6414377452a7610738431b1` | + +WarpFusion 正式索引的构建命令为: + +```bash +./build/ivf_build \ + --database data/million/inner_fp32_db.bin \ + --output data/million/inner_fp32_nlist256_spherical_100k15.ivf \ + --nlist 256 \ + --iterations 15 \ + --training-samples 100000 +``` + +构建耗时 67,678 ms,桶大小 min/avg/max 为 +3734/3906.25/4091,无空桶,索引大小 520,133,160 bytes。 + +两种实现都使用 100,000 个训练向量和 15 次迭代,但不强制共享中心: + +- WarpFusion 从全库等间距、确定性抽取训练样本,初始中心也等间距选择; + 当前实现没有单独的训练随机种子。 +- FAISS 用 NumPy `default_rng(2026)` 无放回抽样,并把聚类 seed 设为 2026。 + +所以这是相同训练预算和检索参数下的端到端系统比较,不是相同桶扫描比较。 + +## 3. 正式查询命令 + +Exact 的 K=10/50/100 均使用 batch=64、预热 5 次、正式重复 100 次: + +```bash +for k in 10 50 100; do + ./build/vector_search \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --params configs/exact_million_k${k}_fused_batch64.conf \ + --backend gpu \ + --output results/formal_100k15/exact_k${k}.txt \ + --warmup 5 --repeat 100 +done +``` + +IVF 对 nprobe=128/160/192/224 扫描。K=10 的示例为: + +```bash +python3 scripts/benchmark_ivf_sweep.py \ + --search-binary ./build/ivf_search \ + --index data/million/inner_fp32_nlist256_spherical_100k15.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_batch64.conf \ + --exact results/formal_100k15/exact_k10.txt \ + --output-dir results/formal_100k15/ivf_k10 \ + --csv results/formal_100k15/ivf_k10.csv \ + --nlist 256 --nprobes 128,160,192,224 \ + --training-samples 100000 --training-iterations 15 \ + --warmup 5 --repeat 100 +``` + +K=50/100 分别替换为对应的 batch64 配置和 Exact 文件。FAISS 使用同一数据、 +K、batch、nlist、nprobe、训练预算、预热和重复次数;完整命令保存在 +`../evidence/2026-09-04/commands.md`。 + +## 4. 延迟与质量定义 + +- `run P50/P99`:一次处理全部 1000 queries 的端到端稳定查询时间。 +- `batch P50/P99`:每个 batch 的 GPU 时间,从 query H2D 开始,到 Top-K + ID/score D2H 完成为止;包含 H2D、所有检索 kernel 和 D2H。 +- 稳定查询不包含数据库/索引的一次性加载、一次性 H2D 和引擎初始化;这些 + 时间另列,不能混入常驻 QPS。 +- GPU 正式项每个 run 有 16 个 batch;100 次重复共产生 1600 个 batch 延迟 + 样本。单线程 CPU Flat 重复 20 次,共 320 个 batch 延迟样本。 +- `recall@K` 是返回 ID 集合与 Exact Top-K 的交集比例。 +- `mean/max absolute score error` 按名次比较近似 Top-K 与 Exact Top-K 的 + 分数绝对差;它衡量漏召回造成的分数质量损失,不等同于同 ID 数值误差。 + Exact kernel A/B 的分数误差则按相同候选 ID 比较。 + +## 5. 自动验证 + +```bash +ctest --test-dir build --output-on-failure +compute-sanitizer --tool memcheck --error-exitcode 99 ./build/unit_tests +``` + +本轮 CTest 8/8 通过,`compute-sanitizer` 报告 0 errors。Nsight Systems 的 +Exact K10 代表性采样显示 fused 距离+局部 Top-K kernel 占 GPU kernel 时间 +约 99.9%;文本摘要已入库,原始 `.nsys-rep` 因体积和机器相关性不提交。 + +新增评测字段和两处样本数日志上传后,GPU 端已再次完成增量编译,CTest 仍为 +8/8。新版 IVF 和 FAISS 脚本分别完成百万数据 smoke test,确认训练元数据、 +run/batch 样本数与平均/最大分数误差均能写入 CSV;对应日志文件名包含 +`after_instrumentation`。 + +为排除构建目录、数据文件和历史结果造成的隐式依赖,另将源码排除 +`build/`、`data/`、`results/`、`evidence/` 和 `.git/` 后解压到新目录,从零 +执行 CMake、编译和 CTest,8/8 通过。输出见 +`../evidence/2026-09-08/submit_audit_ctest.log`。 diff --git a/09_vector_retrieval/PurplePulse/docs/STABILITY_MATRIX.md b/09_vector_retrieval/PurplePulse/docs/STABILITY_MATRIX.md new file mode 100644 index 00000000..135ae6f2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/STABILITY_MATRIX.md @@ -0,0 +1,57 @@ +# 稳定性矩阵与实现选择规则 + +## 第八阶段覆盖 + +`stability_tests` 使用可被 FP16 精确表示的确定性数据,并为数据库加入重复向量、 +为查询加入全零向量,使相同分数必须按较小 ID 排序。GPU 结果按候选 ID、名次和 +score 与 CPU Exact/IVF 参考比较,而不是只检查结果数量。 + +| 类别 | 覆盖 | +|---|---| +| Exact 主矩阵 | 64/128/384/768 维 × batch 1/8/32/40/64/128 × K 1/10/50/100 × FP32/FP16 × L2/IP/cosine,共 576 组 | +| batch 边界 | 65 维,每个 batch 使用 `batch+1` 个 query,覆盖一个满 batch 和尾 batch | +| 非整 warp 维度 | 65 维 × FP32/FP16 × L2/IP/cosine,K=100 | +| Exact 推荐路径 | 128/K10/tile4/64 blocks、384/K10/tile8/160 blocks、384/K50/tile4/64 blocks | +| Exact 安全回退 | 不支持的 FP32 768 维 block-tile 与 K50/tile8 均 fail closed;改用 warp-query/tile1 后通过 | +| IVF 病理桶 | 65 维,8 桶中 4 个空桶、最大桶 125/128;K 1/10/50/100 × FP32/FP16 × 三 metric × warp/bucket-major,共 48 组 | + +原始摘要位于 `../results/stage8_stability/coverage.csv`。远端完整 CTest 14/14 +通过;`compute-sanitizer --tool memcheck` 对整个 `stability_tests` 报告 +`ERROR SUMMARY: 0 errors`。 + +## Exact 选择规则 + +下表中的优化项只适用于已有正式 A/B 的 RTX 4090 D、FP32、batch=64 组合。 +规则刻意保守:正确性测试通过不等于在未测组合上已有性能证据。 + +| K | 维度/metric | 推荐 layout | query tile / blocks | 其他情况 | +|---:|---|---|---|---| +| 10 | 128,L2 或 inner product | warp-query | 4 / 64 | 回退 1 / 0 | +| 10 | 384,cosine | warp-query | 8 / 160 | 回退 1 / 0 | +| 50 | 384,cosine | warp-query | 4 / 64 | 回退 1 / 0 | +| 1、100 | 任意已测维度 | warp-query | 1 / 0 | 同左 | +| 任意 | 64、768、FP16、非 batch64 或其他 GPU | warp-query | 1 / 0 | 同左 | + +其中 `blocks=0` 表示使用稳定的并行度启发式。`block_tile` 在 Synthetic/Yahoo +均未超过 warp-query,不进入任何推荐组合。显式请求不支持的实验组合时,参数 +验证会拒绝启动 kernel;调用方必须改回 +`exact_fused_layout=warp_query, exact_query_tile=1, exact_fused_blocks=0`。 +这是一种 fail-closed 回退,不会静默运行未经验证的近似路径。 + +## IVF 选择与回退 + +- K=10、固定 nprobe:使用完整候选的 `bucket_major`。 +- K=50/100:未做数据集级 recall 验证时使用完整 heap 的 `bucket_major`。 +- 分区 K=50/100 只作为候选运行。`scripts/run_real_benchmarks.py` 会将其与完整 + heap 的全部 nprobe 点比较;任一点 recall 损失超过 `1e-4`,最终 CSV 自动 + 回退到 `*_safe.conf` 的完整 heap 结果。 +- 自适应 nprobe 或 memory scoring 不使用分区模式;参数验证会拒绝不兼容组合。 +- 空桶、严重倾斜桶、重复向量、相同分数和 65 维均已验证完整 heap 路径;这些 + 场景不会自动切换到分区候选。 + +## 适用边界 + +本阶段证明的是单卡、内存内、K≤100、维度≤768 的已列组合正确且无 memcheck +错误,不代表其他 GPU 上的最优性能选择。切换 GPU 架构、batch、dtype 或数据 +分布时,先使用安全 baseline,再按第六/七阶段的严格 ID/score 或 recall 门槛 +重新接纳优化配置。 diff --git a/09_vector_retrieval/PurplePulse/docs/SUBMISSION_CHECKLIST.md b/09_vector_retrieval/PurplePulse/docs/SUBMISSION_CHECKLIST.md new file mode 100644 index 00000000..528fcf98 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/docs/SUBMISSION_CHECKLIST.md @@ -0,0 +1,28 @@ +# GPU 向量检索项目提交核对表 + +本表只用于提交前核验。项目方法、结果和局限以 `FINAL_REPORT.md` 为准。 + +| 课程要求 | 实现与证据 | 状态 | +|---|---|---:| +| 二进制向量库、查询与参数输入 | `src/file_io.cpp`、`src/main.cpp`、`src/search_ivf.cpp` | 通过 | +| 有序 Top-K 输出 | Exact 与 IVF CLI 均输出 ID 和分数;相同分数按较小 ID 排序 | 通过 | +| CPU 正确性参考 | `src/cpu_search.cpp`、`tests/unit_tests.cpp` | 通过 | +| GPU 精确检索 | matrix 与 fused 两条路径,候选集合一致 | 通过 | +| 至少一种近似检索 | GPU IVF-Flat、索引保存与加载、recall@K 评测 | 通过 | +| K=1/10/50/100 | Exact 与 IVF 自动测试覆盖 | 通过 | +| 百万规模、128 维、1000 queries | Synthetic-1M 正式实验与原始 CSV | 通过 | +| 性能超过 CPU 同级实现 | Exact 相对单线程 FAISS CPU Flat 加速 73.5–87.3 倍 | 通过 | +| 查询性能与质量报告 | QPS、run/batch P50/P99、显存、recall 和误差 | 通过 | +| 平均距离/分数误差 | nprobe 扫描 CSV 与报告正确性章节均给出 rank 对齐 MAE | 通过 | +| FAISS 对照 | 同数据、K、batch、nlist、nprobe 和训练预算 | 通过 | +| 真实分布实验 | MNIST 60k 数据库、10k queries | 通过 | +| 自动测试与内存安全 | 新平台 CTest 18/18;Compute Sanitizer 0 errors | 通过 | +| 独立源码构建 | CUDA 12.8 全新目录从零构建,CTest 18/18,Exact/IVF 最小 GPU 查询通过 | 通过 | +| 可复现材料 | 固定随机种子、环境、命令、校验和、CSV 和图表 | 通过 | + +提交目录应保留源码、头文件、测试、配置、脚本、报告、CSV 和 SVG;不提交 +`build/`、原始数据、二进制索引、检索输出、profiler 二进制文件或远端凭据。 +Agent 相关内容属于可选扩展,不纳入本次报告结论。 + +提交前仍需人工确认仓库路径满足课程规定的 `/<选题>/<学员 ID>/`。当前目录名 +为 `PurplePulse`;该字符串仅表示学员 ID,在未获得目标 PR 路径前不做自动重命名。 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/commands.md b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/commands.md new file mode 100644 index 00000000..2866e458 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/commands.md @@ -0,0 +1,115 @@ +# 2026-09-04 正式验收命令 + +所有命令均在项目根目录执行。登录信息、主机地址和密码不属于实验口径,未写入 +证据文件。 + +## 构建与测试 + +```bash +export PATH=/usr/local/cuda/bin:$PATH +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_ARCHITECTURES=native +cmake --build build +ctest --test-dir build --output-on-failure +compute-sanitizer --tool memcheck --error-exitcode 99 ./build/unit_tests +``` + +## 数据与自研索引 + +```bash +python3 scripts/generate_data.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --num-vectors 1000000 --num-queries 1000 --dim 128 \ + --dtype fp32 --metric inner_product --seed 2026 + +sha256sum data/million/inner_fp32_db.bin data/million/inner_fp32_q.bin + +./build/ivf_build \ + --database data/million/inner_fp32_db.bin \ + --output data/million/inner_fp32_nlist256_spherical_100k15.ivf \ + --nlist 256 --iterations 15 --training-samples 100000 + +sha256sum data/million/inner_fp32_nlist256_spherical_100k15.ivf +``` + +## PurplePulse Exact + +```bash +for k in 10 50 100; do + ./build/vector_search \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --params configs/exact_million_k${k}_fused_batch64.conf \ + --backend gpu \ + --output results/formal_100k15/exact_k${k}.txt \ + --warmup 5 --repeat 100 +done +``` + +## PurplePulse IVF + +K=10/50/100 分别使用 +`ivf_flat_million_batch64.conf`、`ivf_flat_million_k50_batch64.conf` 和 +`ivf_flat_million_k100_batch64.conf`。以下是 K=10 命令,其余两项只替换 +配置、Exact 文件、输出目录和 CSV 名称。 + +```bash +python3 scripts/benchmark_ivf_sweep.py \ + --search-binary ./build/ivf_search \ + --index data/million/inner_fp32_nlist256_spherical_100k15.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_batch64.conf \ + --exact results/formal_100k15/exact_k10.txt \ + --output-dir results/formal_100k15/ivf_k10 \ + --csv results/formal_100k15/ivf_k10.csv \ + --nlist 256 --nprobes 128,160,192,224 \ + --training-samples 100000 --training-iterations 15 \ + --warmup 5 --repeat 100 +``` + +## FAISS GPU + +```bash +OMP_NUM_THREADS=1 python3 scripts/benchmark_faiss.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --reference-results results/formal_100k15/exact_k100.txt \ + --index-dir data/million/faiss_formal_100k15 \ + --output-dir results/formal_100k15/faiss_gpu \ + --csv results/formal_100k15/faiss_gpu.csv \ + --backends gpu --index-types flat,ivf_flat \ + --top-ks 10,50,100 --nlist 256 --nprobes 128,160,192,224 \ + --batch-size 64 --train-samples 100000 --iterations 15 --seed 2026 \ + --warmup 5 --repeat 100 --cpu-threads 1 --rebuild +``` + +## FAISS CPU Exact + +```bash +OMP_NUM_THREADS=1 python3 scripts/benchmark_faiss.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --reference-results results/formal_100k15/exact_k100.txt \ + --index-dir data/million/faiss_formal_100k15 \ + --output-dir results/formal_100k15/faiss_cpu \ + --csv results/formal_100k15/faiss_cpu_flat_repeat20.csv \ + --backends cpu --index-types flat --top-ks 10,50,100 \ + --nlist 256 --nprobes 160 --batch-size 64 \ + --train-samples 100000 --iterations 15 --seed 2026 \ + --warmup 1 --repeat 20 --cpu-threads 1 +``` + +## Nsight Systems 代表性采样 + +```bash +nsys profile --force-overwrite true --stats=true \ + -o results/evidence/exact_k10_nsys \ + ./build/vector_search \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --params configs/exact_million_k10_fused_batch64.conf \ + --backend gpu \ + --output results/formal_100k15/exact_k10_nsys.txt \ + --warmup 1 --repeat 5 +``` diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/compute_sanitizer_unit_tests.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/compute_sanitizer_unit_tests.txt new file mode 100644 index 00000000..55289ea6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/compute_sanitizer_unit_tests.txt @@ -0,0 +1,3 @@ +========= COMPUTE-SANITIZER +FP32/FP16 的 CPU/GPU 正确性与边界测试通过 +========= ERROR SUMMARY: 0 errors diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ctest.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ctest.txt new file mode 100644 index 00000000..6b0187f9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ctest.txt @@ -0,0 +1,20 @@ +Internal ctest changing into directory: /root/PurplePulse/build +Test project /root/PurplePulse/build + Start 1: unit_tests +1/7 Test #1: unit_tests ........................ Passed 0.24 sec + Start 2: file_io_tests +2/7 Test #2: file_io_tests ..................... Passed 0.01 sec + Start 3: ivf_flat_tests +3/7 Test #3: ivf_flat_tests .................... Passed 0.23 sec + Start 4: benchmark_faiss_tests +4/7 Test #4: benchmark_faiss_tests ............. Passed 0.93 sec + Start 5: benchmark_ivf_sweep_tests +5/7 Test #5: benchmark_ivf_sweep_tests ......... Passed 0.07 sec + Start 6: benchmark_adaptive_nprobe_tests +6/7 Test #6: benchmark_adaptive_nprobe_tests ... Passed 0.07 sec + Start 7: plot_results_smoke +7/7 Test #7: plot_results_smoke ................ Passed 0.06 sec + +100% tests passed, 0 tests failed out of 7 + +Total Test time (real) = 1.60 sec diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ctest_after_instrumentation.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ctest_after_instrumentation.txt new file mode 100644 index 00000000..7e2f4457 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ctest_after_instrumentation.txt @@ -0,0 +1,20 @@ +Internal ctest changing into directory: /root/PurplePulse/build +Test project /root/PurplePulse/build + Start 1: unit_tests +1/7 Test #1: unit_tests ........................ Passed 0.24 sec + Start 2: file_io_tests +2/7 Test #2: file_io_tests ..................... Passed 0.01 sec + Start 3: ivf_flat_tests +3/7 Test #3: ivf_flat_tests .................... Passed 0.22 sec + Start 4: benchmark_faiss_tests +4/7 Test #4: benchmark_faiss_tests ............. Passed 1.46 sec + Start 5: benchmark_ivf_sweep_tests +5/7 Test #5: benchmark_ivf_sweep_tests ......... Passed 0.07 sec + Start 6: benchmark_adaptive_nprobe_tests +6/7 Test #6: benchmark_adaptive_nprobe_tests ... Passed 0.07 sec + Start 7: plot_results_smoke +7/7 Test #7: plot_results_smoke ................ Passed 0.06 sec + +100% tests passed, 0 tests failed out of 7 + +Total Test time (real) = 2.14 sec diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/data_million_sha256.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/data_million_sha256.txt new file mode 100644 index 00000000..c3ec1f0e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/data_million_sha256.txt @@ -0,0 +1,2 @@ +d4dde1418ea7626e5226e594e592f9ae5ffbe4c412c326395d96388f95df9800 data/million/inner_fp32_db.bin +a58ebe43fce865b71a2a651791286fa0bd1567348e07d6c0601b69beaebceb45 data/million/inner_fp32_q.bin diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/environment.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/environment.txt new file mode 100644 index 00000000..200635b8 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/environment.txt @@ -0,0 +1,35 @@ +2026-09-04T07:42:26,935679805+00:00 +Linux 2a615599b24c 5.4.0-196-generic #216-Ubuntu SMP Thu Aug 29 13:26:53 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux +PRETTY_NAME="Ubuntu 24.04.1 LTS" +NAME="Ubuntu" +VERSION_ID="24.04" +VERSION="24.04.1 LTS (Noble Numbat)" +VERSION_CODENAME=noble +ID=ubuntu +ID_LIKE=debian +HOME_URL="https://www.ubuntu.com/" +SUPPORT_URL="https://help.ubuntu.com/" +BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" +PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" +UBUNTU_CODENAME=noble +LOGO=ubuntu-logo +NVIDIA GeForce RTX 4090 D, 570.124.06, 24564 MiB, 8.9 +nvcc: NVIDIA (R) Cuda compiler driver +Copyright (c) 2005-2025 NVIDIA Corporation +Built on Wed_Jan_15_19:20:09_PST_2025 +Cuda compilation tools, release 12.8, V12.8.61 +Build cuda_12.8.r12.8/compiler.35404655_0 +cmake version 3.31.4 + +CMake suite maintained and supported by Kitware (kitware.com/cmake). +1.11.1.git.kitware.jobserver-1 +gcc (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 +Python 3.12.3 +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'faiss' +numpy 1.26.4 +faiss-python 3.12.3 +faiss-numpy 2.2.6 +faiss 1.14.1 +faiss-gpus 1 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k100_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k100_repeat100.txt new file mode 100644 index 00000000..b032c0c7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k100_repeat100.txt @@ -0,0 +1,25 @@ +向量库: 1000000 x 128 +查询数: 1000 +dtype: fp32 +metric: inner_product +top_k: 100 +batch_size: 64 +distance_mode: warp +topk_mode: fused +warmup/repeat: 5/100 +backend: gpu +GPU 一次性初始化总时间: 172.278 ms +数据库一次性 H2D: 48.5765 ms +GPU 缓冲区: 489.558 MiB +估算冷启动端到端: 357.244 ms +平均常驻查询时间: 184.966 ms +run P50: 185.035 ms +run P99: 187.947 ms +常驻 QPS: 5406.4 +结果: "results/formal_100k15/exact_k100.txt" +平均查询 H2D: 0.232269 ms +平均融合距离+局部 Top-K kernel: 181.896 ms +平均最终 Top-K kernel: 1.88726 ms +平均结果 D2H: 0.492971 ms +batch P50: 11.7263 ms +batch P99: 12.1334 ms diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k10_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k10_repeat100.txt new file mode 100644 index 00000000..b6ee64f3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k10_repeat100.txt @@ -0,0 +1,25 @@ +向量库: 1000000 x 128 +查询数: 1000 +dtype: fp32 +metric: inner_product +top_k: 10 +batch_size: 64 +distance_mode: warp +topk_mode: fused +warmup/repeat: 5/100 +backend: gpu +GPU 一次性初始化总时间: 200.701 ms +数据库一次性 H2D: 48.602 ms +GPU 缓冲区: 488.437 MiB +估算冷启动端到端: 350.456 ms +平均常驻查询时间: 149.755 ms +run P50: 150.025 ms +run P99: 151.143 ms +常驻 QPS: 6677.57 +结果: "results/formal_100k15/exact_k10.txt" +平均查询 H2D: 0.22932 ms +平均融合距离+局部 Top-K kernel: 148.772 ms +平均最终 Top-K kernel: 0.187956 ms +平均结果 D2H: 0.363535 ms +batch P50: 9.53296 ms +batch P99: 9.64477 ms diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k50_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k50_repeat100.txt new file mode 100644 index 00000000..61251dcc --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/exact_k50_repeat100.txt @@ -0,0 +1,25 @@ +向量库: 1000000 x 128 +查询数: 1000 +dtype: fp32 +metric: inner_product +top_k: 50 +batch_size: 64 +distance_mode: warp +topk_mode: fused +warmup/repeat: 5/100 +backend: gpu +GPU 一次性初始化总时间: 173.011 ms +数据库一次性 H2D: 49.114 ms +GPU 缓冲区: 488.935 MiB +估算冷启动端到端: 340.398 ms +平均常驻查询时间: 167.387 ms +run P50: 167.671 ms +run P99: 169.027 ms +常驻 QPS: 5974.19 +结果: "results/formal_100k15/exact_k50.txt" +平均查询 H2D: 0.232645 ms +平均融合距离+局部 Top-K kernel: 165.594 ms +平均最终 Top-K kernel: 0.844275 ms +平均结果 D2H: 0.411974 ms +batch P50: 10.6347 ms +batch P99: 10.8679 ms diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_cpu_flat_repeat20.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_cpu_flat_repeat20.txt new file mode 100644 index 00000000..8782ef73 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_cpu_flat_repeat20.txt @@ -0,0 +1,5 @@ +FAISS Flat vs PurplePulse exact recall@100: 1.000000000, min=1.000000000 +{"implementation": "faiss-1.14.1", "backend": "cpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "build_ms": 0.0, "load_ms": 325.0962197780609, "gpu_transfer_ms": 0.0, "gpu_index_mib": 0.0, "gpu_temp_mib": 0.0, "average_query_ms": 13079.959641397, "qps": 76.45283528513971, "batch_p50_ms": 834.8349779844284, "batch_p99_ms": 846.3362380862236, "recall_at_k": 1.0, "min_query_recall": 1.0} +{"implementation": "faiss-1.14.1", "backend": "cpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 50, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "build_ms": 0.0, "load_ms": 325.0962197780609, "gpu_transfer_ms": 0.0, "gpu_index_mib": 0.0, "gpu_temp_mib": 0.0, "average_query_ms": 13080.880285799503, "qps": 76.44745446417637, "batch_p50_ms": 835.1001441478729, "batch_p99_ms": 847.1395075321198, "recall_at_k": 1.0, "min_query_recall": 1.0} +{"implementation": "faiss-1.14.1", "backend": "cpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 100, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "build_ms": 0.0, "load_ms": 325.0962197780609, "gpu_transfer_ms": 0.0, "gpu_index_mib": 0.0, "gpu_temp_mib": 0.0, "average_query_ms": 13596.499814093113, "qps": 73.54834065186945, "batch_p50_ms": 867.8400814533234, "batch_p99_ms": 881.017416715622, "recall_at_k": 1.0, "min_query_recall": 1.0} +CSV: results/formal_100k15/faiss_cpu_flat_repeat20_raw.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_gpu_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_gpu_repeat100.txt new file mode 100644 index 00000000..0e0d5cd7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_gpu_repeat100.txt @@ -0,0 +1,17 @@ +FAISS Flat vs PurplePulse exact recall@100: 1.000000000, min=1.000000000 +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "build_ms": 261.927954852581, "load_ms": 0.0, "gpu_transfer_ms": 338.9444574713707, "gpu_index_mib": 492.095947265625, "gpu_temp_mib": 1536.0, "average_query_ms": 47.11136355996132, "qps": 21226.301351419028, "batch_p50_ms": 2.9594004154205322, "batch_p99_ms": 2.972230315208435, "recall_at_k": 1.0, "min_query_recall": 1.0} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 50, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "build_ms": 261.927954852581, "load_ms": 0.0, "gpu_transfer_ms": 338.9444574713707, "gpu_index_mib": 492.095947265625, "gpu_temp_mib": 1536.0, "average_query_ms": 48.20252262055874, "qps": 20745.802203586176, "batch_p50_ms": 3.023482859134674, "batch_p99_ms": 3.048732876777649, "recall_at_k": 1.0, "min_query_recall": 1.0} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 100, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "build_ms": 261.927954852581, "load_ms": 0.0, "gpu_transfer_ms": 338.9444574713707, "gpu_index_mib": 492.095947265625, "gpu_temp_mib": 1536.0, "average_query_ms": 49.90370690822601, "qps": 20038.591558719705, "batch_p50_ms": 3.1260475516319275, "batch_p99_ms": 3.1578615307807922, "recall_at_k": 1.0, "min_query_recall": 1.0} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 256, "nprobe": 128, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 145.7934482395649, "qps": 6859.01878359321, "batch_p50_ms": 9.360350668430328, "batch_p99_ms": 10.512225329875946, "recall_at_k": 0.8795000000000001, "min_query_recall": 0.5} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 50, "batch_size": 64, "nlist": 256, "nprobe": 128, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 90.35561479628086, "qps": 11067.380840190588, "batch_p50_ms": 5.7607293128967285, "batch_p99_ms": 5.909278988838196, "recall_at_k": 0.85972, "min_query_recall": 0.68} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 100, "batch_size": 64, "nlist": 256, "nprobe": 128, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 100.42996548116207, "qps": 9957.187530723317, "batch_p50_ms": 6.3972026109695435, "batch_p99_ms": 6.478957831859589, "recall_at_k": 0.8490999999999999, "min_query_recall": 0.7} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 256, "nprobe": 160, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 209.93292428553104, "qps": 4763.42623913481, "batch_p50_ms": 13.52139562368393, "batch_p99_ms": 14.626868069171906, "recall_at_k": 0.9369000000000001, "min_query_recall": 0.7} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 50, "batch_size": 64, "nlist": 256, "nprobe": 160, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 113.9417802542448, "qps": 8776.411933959984, "batch_p50_ms": 7.0451050996780396, "batch_p99_ms": 11.37205958366394, "recall_at_k": 0.92312, "min_query_recall": 0.8} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 100, "batch_size": 64, "nlist": 256, "nprobe": 160, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 126.59424863755703, "qps": 7899.253013168305, "batch_p50_ms": 8.060820400714874, "batch_p99_ms": 8.196607232093811, "recall_at_k": 0.9163399999999999, "min_query_recall": 0.8} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 256, "nprobe": 192, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 268.18819120526314, "qps": 3728.724950587515, "batch_p50_ms": 17.25468784570694, "batch_p99_ms": 19.591324031352997, "recall_at_k": 0.9722000000000001, "min_query_recall": 0.7} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 50, "batch_size": 64, "nlist": 256, "nprobe": 192, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 134.80234675109386, "qps": 7418.268480492054, "batch_p50_ms": 8.60326737165451, "batch_p99_ms": 8.92588496208191, "recall_at_k": 0.96408, "min_query_recall": 0.84} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 100, "batch_size": 64, "nlist": 256, "nprobe": 192, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 152.11867079138756, "qps": 6573.815001127506, "batch_p50_ms": 9.70180332660675, "batch_p99_ms": 9.853780269622803, "recall_at_k": 0.96127, "min_query_recall": 0.88} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 256, "nprobe": 224, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 327.7342140674591, "qps": 3051.252988173414, "batch_p50_ms": 21.058037877082825, "batch_p99_ms": 22.79273420572281, "recall_at_k": 0.993, "min_query_recall": 0.8} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 50, "batch_size": 64, "nlist": 256, "nprobe": 224, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 152.58803740143776, "qps": 6553.593696006064, "batch_p50_ms": 9.723648428916931, "batch_p99_ms": 9.950794279575348, "recall_at_k": 0.9898800000000001, "min_query_recall": 0.92} +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "ivf_flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 100, "batch_size": 64, "nlist": 256, "nprobe": 224, "train_samples": 100000, "build_ms": 6923.940047621727, "load_ms": 0.0, "gpu_transfer_ms": 784.832239151001, "gpu_index_mib": 497.984375, "gpu_temp_mib": 1536.0, "average_query_ms": 177.92695373296738, "qps": 5620.283936860961, "batch_p50_ms": 11.344268918037415, "batch_p99_ms": 11.505231261253357, "recall_at_k": 0.9887900000000001, "min_query_recall": 0.95} +CSV: results/formal_100k15/faiss_gpu_raw.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_index_sha256.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_index_sha256.txt new file mode 100644 index 00000000..c2efd7e6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_index_sha256.txt @@ -0,0 +1,2 @@ +760e3a94f24c5becfa21e89a57f67395013d5ad5375c20eb3f5d5cfb4c3720a1 data/million/faiss_formal_100k15/faiss_flat_ip_1000000x128_nlist256.index +a66a63bb28ed9e70ae83c042f57a8ca79de3ee01a6414377452a7610738431b1 data/million/faiss_formal_100k15/faiss_ivf_flat_ip_1000000x128_nlist256.index diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_script_after_instrumentation.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_script_after_instrumentation.txt new file mode 100644 index 00000000..f3271a0a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/faiss_script_after_instrumentation.txt @@ -0,0 +1,3 @@ +FAISS Flat vs PurplePulse exact recall@10: 1.000000000, min=1.000000000, mean_score_error=2.1645546e-06, max_score_error=1.14440918e-05 +{"implementation": "faiss-1.14.1", "backend": "gpu", "index_type": "flat", "metric": "inner_product", "num_vectors": 1000000, "num_queries": 1000, "dim": 128, "dtype": "fp32", "cpu_threads": 1, "top_k": 10, "batch_size": 64, "nlist": 0, "nprobe": 0, "train_samples": 0, "training_iterations": 0, "training_seed": 0, "build_ms": 0.0, "load_ms": 296.24930024147034, "gpu_transfer_ms": 668.2284846901894, "gpu_index_mib": 492.095947265625, "gpu_temp_mib": 1536.0, "average_query_ms": 48.66527020931244, "qps": 20548.534831902423, "run_p50_ms": 48.66527020931244, "run_p99_ms": 48.66527020931244, "run_samples": 1, "batch_p50_ms": 3.057025372982025, "batch_p99_ms": 3.069080412387848, "batch_latency_samples": 16, "recall_at_k": 1.0, "min_query_recall": 1.0, "mean_absolute_score_error": 2.152252197265625e-06, "max_absolute_score_error": 1.1444091796875e-05} +CSV: results/validation_after_instrumentation/faiss_gpu.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/gpu_snapshot_after_benchmarks.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/gpu_snapshot_after_benchmarks.txt new file mode 100644 index 00000000..55c78f31 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/gpu_snapshot_after_benchmarks.txt @@ -0,0 +1 @@ +2026/09/04 08:05:44.331, NVIDIA GeForce RTX 4090 D, 32, 22.39 W, 210 MHz, 405 MHz diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/index_100k15_sha256.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/index_100k15_sha256.txt new file mode 100644 index 00000000..3971a8e3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/index_100k15_sha256.txt @@ -0,0 +1 @@ +f5bd87fcc72d37164fa931436e5bfd293dfb7f953d09cb28169a77c7cdadc415 data/million/inner_fp32_nlist256_spherical_100k15.ivf diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_build_100k15.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_build_100k15.txt new file mode 100644 index 00000000..98fa2c56 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_build_100k15.txt @@ -0,0 +1,11 @@ +IVF-Flat 索引构建完成 +向量库: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist: 256 +迭代/训练样本: 15/100000 +构建时间: 67678 ms +保存时间: 201.959 ms +桶大小 min/avg/max: 3734/3906.25/4091 +空桶: 0 +索引大小: 520133160 bytes +输出: "data/million/inner_fp32_nlist256_spherical_100k15.ivf" diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k100_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k100_repeat100.txt new file mode 100644 index 00000000..68f8926e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k100_repeat100.txt @@ -0,0 +1,101 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/128/100 +nprobe policy: fixed +memory mode: disabled +索引加载: 353.542 ms +GPU 初始化: 222.296557 ms +索引 H2D: 51.038208 ms +GPU 缓冲区: 505.610847 MiB +平均查询: 164.37 ms +run P50/P99: 164.701/166.278 ms +QPS: 6083.83 +输出: "results/formal_100k15/ivf_k100_raw/nlist256_nprobe128.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.230585 ms +平均 GPU 中心选择: 1.42848 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 156.251 ms +平均 GPU 最终 Top-K 归并: 1.33227 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.526344 ms +batch P50/P99: 10.2194/10.4293 ms +实际 nprobe min/avg/max: 128/128/128 +recall@100=0.851910, min_query_recall=0.700000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/100 +nprobe policy: fixed +memory mode: disabled +索引加载: 348.273 ms +GPU 初始化: 177.593285 ms +索引 H2D: 49.840225 ms +GPU 缓冲区: 507.962410 MiB +平均查询: 211.3 ms +run P50/P99: 211.196/213.17 ms +QPS: 4732.6 +输出: "results/formal_100k15/ivf_k100_raw/nlist256_nprobe160.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.230195 ms +平均 GPU 中心选择: 1.71171 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 202.791 ms +平均 GPU 最终 Top-K 归并: 1.36999 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.538248 ms +batch P50/P99: 13.2468/13.5739 ms +实际 nprobe min/avg/max: 160/160/160 +recall@100=0.917580, min_query_recall=0.830000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/192/100 +nprobe policy: fixed +memory mode: disabled +索引加载: 349.271 ms +GPU 初始化: 184.404243 ms +索引 H2D: 50.775040 ms +GPU 缓冲区: 510.313972 MiB +平均查询: 262.99 ms +run P50/P99: 263.133/264.838 ms +QPS: 3802.43 +输出: "results/formal_100k15/ivf_k100_raw/nlist256_nprobe192.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.234722 ms +平均 GPU 中心选择: 1.99681 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 254.169 ms +平均 GPU 最终 Top-K 归并: 1.38832 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.53602 ms +batch P50/P99: 16.5511/16.997 ms +实际 nprobe min/avg/max: 192/192/192 +recall@100=0.962280, min_query_recall=0.900000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/224/100 +nprobe policy: fixed +memory mode: disabled +索引加载: 345.818 ms +GPU 初始化: 177.716485 ms +索引 H2D: 49.881088 ms +GPU 缓冲区: 512.665535 MiB +平均查询: 315.231 ms +run P50/P99: 315.293/317.578 ms +QPS: 3172.27 +输出: "results/formal_100k15/ivf_k100_raw/nlist256_nprobe224.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.234026 ms +平均 GPU 中心选择: 2.27418 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 306.111 ms +平均 GPU 最终 Top-K 归并: 1.42648 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.514689 ms +batch P50/P99: 19.943/20.4702 ms +实际 nprobe min/avg/max: 224/224/224 +recall@100=0.989200, min_query_recall=0.930000 +CSV: results/formal_100k15/ivf_k100_raw.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k10_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k10_repeat100.txt new file mode 100644 index 00000000..5598c9f3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k10_repeat100.txt @@ -0,0 +1,101 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/128/10 +nprobe policy: fixed +memory mode: disabled +索引加载: 362.111 ms +GPU 初始化: 249.238430 ms +索引 H2D: 50.082817 ms +GPU 缓冲区: 497.107430 MiB +平均查询: 142.972 ms +run P50/P99: 143.046/144.389 ms +QPS: 6994.35 +输出: "results/formal_100k15/ivf_k10_raw/nlist256_nprobe128.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.226118 ms +平均 GPU 中心选择: 1.4063 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 136.9 ms +平均 GPU 最终 Top-K 归并: 0.177871 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.35093 ms +batch P50/P99: 8.91104/8.99946 ms +实际 nprobe min/avg/max: 128/128/128 +recall@10=0.887600, min_query_recall=0.400000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/10 +nprobe policy: fixed +memory mode: disabled +索引加载: 349.508 ms +GPU 初始化: 187.561331 ms +索引 H2D: 52.624416 ms +GPU 缓冲区: 497.349617 MiB +平均查询: 175.542 ms +run P50/P99: 175.499/176.839 ms +QPS: 5696.66 +输出: "results/formal_100k15/ivf_k10_raw/nlist256_nprobe160.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.2292 ms +平均 GPU 中心选择: 1.71734 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 169.143 ms +平均 GPU 最终 Top-K 归并: 0.183409 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.35601 ms +batch P50/P99: 10.9579/11.1168 ms +实际 nprobe min/avg/max: 160/160/160 +recall@10=0.940900, min_query_recall=0.600000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/192/10 +nprobe policy: fixed +memory mode: disabled +索引加载: 338.971 ms +GPU 初始化: 178.590357 ms +索引 H2D: 50.026463 ms +GPU 缓冲区: 497.591805 MiB +平均查询: 213.302 ms +run P50/P99: 213.26/214.714 ms +QPS: 4688.19 +输出: "results/formal_100k15/ivf_k10_raw/nlist256_nprobe192.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.227254 ms +平均 GPU 中心选择: 2.00364 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 206.648 ms +平均 GPU 最终 Top-K 归并: 0.187812 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.311597 ms +batch P50/P99: 13.3933/13.5356 ms +实际 nprobe min/avg/max: 192/192/192 +recall@10=0.973400, min_query_recall=0.700000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/224/10 +nprobe policy: fixed +memory mode: disabled +索引加载: 348.109 ms +GPU 初始化: 179.173165 ms +索引 H2D: 50.736130 ms +GPU 缓冲区: 497.833992 MiB +平均查询: 250.392 ms +run P50/P99: 250.245/252.798 ms +QPS: 3993.74 +输出: "results/formal_100k15/ivf_k10_raw/nlist256_nprobe224.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.234291 ms +平均 GPU 中心选择: 2.28967 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 243.249 ms +平均 GPU 最终 Top-K 归并: 0.190981 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.33933 ms +batch P50/P99: 15.7794/15.9556 ms +实际 nprobe min/avg/max: 224/224/224 +recall@10=0.993100, min_query_recall=0.800000 +CSV: results/formal_100k15/ivf_k10_raw.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k50_repeat100.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k50_repeat100.txt new file mode 100644 index 00000000..292b24eb --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_k50_repeat100.txt @@ -0,0 +1,101 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/128/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 349.347 ms +GPU 初始化: 219.744959 ms +索引 H2D: 51.002369 ms +GPU 缓冲区: 500.886726 MiB +平均查询: 137.089 ms +run P50/P99: 137.215/139.576 ms +QPS: 7294.52 +输出: "results/formal_100k15/ivf_k50_raw/nlist256_nprobe128.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.23926 ms +平均 GPU 中心选择: 1.43383 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 129.996 ms +平均 GPU 最终 Top-K 归并: 0.649493 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.471183 ms +batch P50/P99: 8.49632/8.70291 ms +实际 nprobe min/avg/max: 128/128/128 +recall@50=0.862480, min_query_recall=0.700000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 328.392 ms +GPU 初始化: 175.771099 ms +索引 H2D: 48.182274 ms +GPU 缓冲区: 502.066414 MiB +平均查询: 178.399 ms +run P50/P99: 178.397/180.654 ms +QPS: 5605.41 +输出: "results/formal_100k15/ivf_k50_raw/nlist256_nprobe160.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.213315 ms +平均 GPU 中心选择: 1.73579 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 171.117 ms +平均 GPU 最终 Top-K 归并: 0.716433 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.416466 ms +batch P50/P99: 11.18/11.4261 ms +实际 nprobe min/avg/max: 160/160/160 +recall@50=0.924820, min_query_recall=0.800000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/192/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 310.692 ms +GPU 初始化: 176.079546 ms +索引 H2D: 48.196609 ms +GPU 缓冲区: 503.246101 MiB +平均查询: 223.565 ms +run P50/P99: 223.664/226.713 ms +QPS: 4472.96 +输出: "results/formal_100k15/ivf_k50_raw/nlist256_nprobe192.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.213812 ms +平均 GPU 中心选择: 2.00779 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 215.991 ms +平均 GPU 最终 Top-K 归并: 0.727207 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.404718 ms +batch P50/P99: 14.0604/14.5124 ms +实际 nprobe min/avg/max: 192/192/192 +recall@50=0.965800, min_query_recall=0.820000 +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/224/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 313.004 ms +GPU 初始化: 177.229013 ms +索引 H2D: 49.465343 ms +GPU 缓冲区: 504.425789 MiB +平均查询: 273.458 ms +run P50/P99: 273.591/276.441 ms +QPS: 3656.87 +输出: "results/formal_100k15/ivf_k50_raw/nlist256_nprobe224.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.217707 ms +平均 GPU 中心选择: 2.27946 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 265.604 ms +平均 GPU 最终 Top-K 归并: 0.743718 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.379669 ms +batch P50/P99: 17.2885/17.7533 ms +实际 nprobe min/avg/max: 224/224/224 +recall@50=0.990540, min_query_recall=0.920000 +CSV: results/formal_100k15/ivf_k50_raw.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_script_after_instrumentation.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_script_after_instrumentation.txt new file mode 100644 index 00000000..4dcea24f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/ivf_script_after_instrumentation.txt @@ -0,0 +1,28 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/10 +nprobe policy: fixed +memory mode: disabled +索引加载: 335.638 ms +GPU 初始化: 299.387560 ms +索引 H2D: 48.644096 ms +GPU 缓冲区: 497.349617 MiB +平均查询: 171.168 ms +run P50/P99: 171.168/171.168 ms +run samples: 1 +QPS: 5842.22 +输出: "results/validation_after_instrumentation/ivf_k10/nlist256_nprobe160.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.266208 ms +平均 GPU 中心选择: 1.62509 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 164.851 ms +平均 GPU 最终 Top-K 归并: 0.178112 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.30512 ms +batch P50/P99: 10.6724/10.7368 ms +batch samples: 16 +实际 nprobe min/avg/max: 160/160/160 +recall@10=0.940900, min_query_recall=0.600000, mean_absolute_score_error=0.042425712, max_absolute_score_error=3.1734657 +CSV: results/validation_after_instrumentation/ivf_k10.csv diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/nsys_exact_k10.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/nsys_exact_k10.txt new file mode 100644 index 00000000..41759a4d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/nsys_exact_k10.txt @@ -0,0 +1,100 @@ +向量库: 1000000 x 128 +查询数: 1000 +dtype: fp32 +metric: inner_product +top_k: 10 +batch_size: 64 +distance_mode: warp +topk_mode: fused +warmup/repeat: 1/5 +backend: gpu +GPU 一次性初始化总时间: 387.492 ms +数据库一次性 H2D: 49.1047 ms +GPU 缓冲区: 488.437 MiB +估算冷启动端到端: 533.198 ms +平均常驻查询时间: 145.706 ms +run P50: 145.789 ms +run P99: 146.261 ms +常驻 QPS: 6863.12 +结果: "results/formal_100k15/exact_k10_nsys.txt" +平均查询 H2D: 0.33273 ms +平均融合距离+局部 Top-K kernel: 144.491 ms +平均最终 Top-K kernel: 0.209363 ms +平均结果 D2H: 0.399002 ms +batch P50: 9.25331 ms +batch P99: 9.6127 ms +Collecting data... +Generating '/tmp/nsys-report-450f.qdstrm' +[1/8] [0% ] exact_k10_nsys.nsys-rep[1/8] [0% ] exact_k10_nsys.nsys-rep[1/8] [==================76% ] exact_k10_nsys.nsys-rep[1/8] [========================100%] exact_k10_nsys.nsys-rep[1/8] [========================100%] exact_k10_nsys.nsys-rep +[2/8] [0% ] exact_k10_nsys.sqlite[2/8] [1% ] exact_k10_nsys.sqlite[2/8] [2% ] exact_k10_nsys.sqlite[2/8] [3% ] exact_k10_nsys.sqlite[2/8] [4% ] exact_k10_nsys.sqlite[2/8] [5% ] exact_k10_nsys.sqlite[2/8] [6% ] exact_k10_nsys.sqlite[2/8] [7% ] exact_k10_nsys.sqlite[2/8] [8% ] exact_k10_nsys.sqlite[2/8] [9% ] exact_k10_nsys.sqlite[2/8] [10% ] exact_k10_nsys.sqlite[2/8] [11% ] exact_k10_nsys.sqlite[2/8] [12% ] exact_k10_nsys.sqlite[2/8] [13% ] exact_k10_nsys.sqlite[2/8] [14% ] exact_k10_nsys.sqlite[2/8] [=15% ] exact_k10_nsys.sqlite[2/8] [=16% ] exact_k10_nsys.sqlite[2/8] [=17% ] exact_k10_nsys.sqlite[2/8] [==18% ] exact_k10_nsys.sqlite[2/8] [==19% ] exact_k10_nsys.sqlite[2/8] [==20% ] exact_k10_nsys.sqlite[2/8] [==21% ] exact_k10_nsys.sqlite[2/8] [===22% ] exact_k10_nsys.sqlite[2/8] [===23% ] exact_k10_nsys.sqlite[2/8] [===24% ] exact_k10_nsys.sqlite[2/8] [====25% ] exact_k10_nsys.sqlite[2/8] [====26% ] exact_k10_nsys.sqlite[2/8] [====27% ] exact_k10_nsys.sqlite[2/8] [====28% ] exact_k10_nsys.sqlite[2/8] [=====29% ] exact_k10_nsys.sqlite[2/8] [=====30% ] exact_k10_nsys.sqlite[2/8] [=====31% ] exact_k10_nsys.sqlite[2/8] [=====32% ] exact_k10_nsys.sqlite[2/8] [======33% ] exact_k10_nsys.sqlite[2/8] [======34% ] exact_k10_nsys.sqlite[2/8] [======35% ] exact_k10_nsys.sqlite[2/8] [=======36% ] exact_k10_nsys.sqlite[2/8] [=======37% ] exact_k10_nsys.sqlite[2/8] [=======38% ] exact_k10_nsys.sqlite[2/8] [=======39% ] exact_k10_nsys.sqlite[2/8] [========40% ] exact_k10_nsys.sqlite[2/8] [========41% ] exact_k10_nsys.sqlite[2/8] [========42% ] exact_k10_nsys.sqlite[2/8] [=========43% ] exact_k10_nsys.sqlite[2/8] [=========44% ] exact_k10_nsys.sqlite[2/8] [=========45% ] exact_k10_nsys.sqlite[2/8] [=========46% ] exact_k10_nsys.sqlite[2/8] [==========47% ] exact_k10_nsys.sqlite[2/8] [==========48% ] exact_k10_nsys.sqlite[2/8] [==========49% ] exact_k10_nsys.sqlite[2/8] [===========50% ] exact_k10_nsys.sqlite[2/8] [===========51% ] exact_k10_nsys.sqlite[2/8] [===========52% ] exact_k10_nsys.sqlite[2/8] [===========53% ] exact_k10_nsys.sqlite[2/8] [============54% ] exact_k10_nsys.sqlite[2/8] [============55% ] exact_k10_nsys.sqlite[2/8] [============56% ] exact_k10_nsys.sqlite[2/8] [============57% ] exact_k10_nsys.sqlite[2/8] [=============58% ] exact_k10_nsys.sqlite[2/8] [=============59% ] exact_k10_nsys.sqlite[2/8] [=============60% ] exact_k10_nsys.sqlite[2/8] [==============61% ] exact_k10_nsys.sqlite[2/8] [==============62% ] exact_k10_nsys.sqlite[2/8] [==============63% ] exact_k10_nsys.sqlite[2/8] [==============64% ] exact_k10_nsys.sqlite[2/8] [===============65% ] exact_k10_nsys.sqlite[2/8] [===============66% ] exact_k10_nsys.sqlite[2/8] [===============67% ] exact_k10_nsys.sqlite[2/8] [================68% ] exact_k10_nsys.sqlite[2/8] [================69% ] exact_k10_nsys.sqlite[2/8] [================70% ] exact_k10_nsys.sqlite[2/8] [================71% ] exact_k10_nsys.sqlite[2/8] [=================72% ] exact_k10_nsys.sqlite[2/8] [=================73% ] exact_k10_nsys.sqlite[2/8] [=================74% ] exact_k10_nsys.sqlite[2/8] [==================75% ] exact_k10_nsys.sqlite[2/8] [==================76% ] exact_k10_nsys.sqlite[2/8] [==================77% ] exact_k10_nsys.sqlite[2/8] [==================78% ] exact_k10_nsys.sqlite[2/8] [===================79% ] exact_k10_nsys.sqlite[2/8] [===================80% ] exact_k10_nsys.sqlite[2/8] [===================81% ] exact_k10_nsys.sqlite[2/8] [===================82% ] exact_k10_nsys.sqlite[2/8] [====================83% ] exact_k10_nsys.sqlite[2/8] [====================84% ] exact_k10_nsys.sqlite[2/8] [====================85% ] exact_k10_nsys.sqlite[2/8] [=====================86% ] exact_k10_nsys.sqlite[2/8] [=====================87% ] exact_k10_nsys.sqlite[2/8] [=====================88% ] exact_k10_nsys.sqlite[2/8] [=====================89% ] exact_k10_nsys.sqlite[2/8] [======================90% ] exact_k10_nsys.sqlite[2/8] [======================91% ] exact_k10_nsys.sqlite[2/8] [======================92% ] exact_k10_nsys.sqlite[2/8] [=======================93% ] exact_k10_nsys.sqlite[2/8] [=======================94% ] exact_k10_nsys.sqlite[2/8] [=======================95% ] exact_k10_nsys.sqlite[2/8] [=======================96% ] exact_k10_nsys.sqlite[2/8] [========================97% ] exact_k10_nsys.sqlite[2/8] [========================98% ] exact_k10_nsys.sqlite[2/8] [========================99% ] exact_k10_nsys.sqlite[2/8] [========================100%] exact_k10_nsys.sqlite[2/8] [========================100%] exact_k10_nsys.sqlite +SKIPPED: /root/PurplePulse/results/evidence/exact_k10_nsys.sqlite does not contain NV Tools Extension (NVTX) data. +[3/8] Executing 'nvtx_sum' stats report +[4/8] Executing 'osrt_sum' stats report + + Time (%) Total Time (ns) Num Calls Avg (ns) Med (ns) Min (ns) Max (ns) StdDev (ns) Name + -------- --------------- --------- ----------- ----------- --------- --------- ----------- ---------------------- + 50.5 1229257719 21 58536081.9 41666582.0 4009 227645472 60313247.0 poll + 41.1 1000173936 2 500086968.0 500086968.0 500085280 500088656 2387.2 pthread_cond_timedwait + 4.5 108441993 19 5707473.3 2347.0 1028 108319891 24848738.0 read + 3.8 92281614 552 167176.8 15264.5 1034 16349452 834161.2 ioctl + 0.1 1445352 25 57814.1 4230.0 2799 1135032 225138.3 mmap64 + 0.0 458294 9 50921.6 47450.0 44364 69199 8896.6 sem_timedwait + 0.0 308424 75 4112.3 1614.0 1244 60791 7551.7 fopen + 0.0 199870 43 4648.1 3864.0 1716 10003 1941.4 open64 + 0.0 141161 1 141161.0 141161.0 141161 141161 0.0 pthread_cond_wait + 0.0 122397 26 4707.6 3610.0 3177 15967 3203.3 writev + 0.0 110603 3 36867.7 35896.0 27886 46821 9504.8 pthread_create + 0.0 88462 13 6804.8 2546.0 1350 36082 9437.1 mmap + 0.0 46148 11 4195.3 3895.0 1685 7795 1879.7 write + 0.0 41415 11 3765.0 1962.0 1010 10948 3549.7 fclose + 0.0 39814 1 39814.0 39814.0 39814 39814 0.0 fgets + 0.0 25760 3 8586.7 4555.0 1766 19439 9501.3 pipe2 + 0.0 25583 6 4263.8 4722.0 1795 6360 1915.0 open + 0.0 20692 6 3448.7 3280.5 1891 5558 1403.1 munmap + 0.0 20296 3 6765.3 4667.0 4282 11347 3972.5 pthread_cond_broadcast + 0.0 15064 3 5021.3 2905.0 2787 9372 3768.2 stat + 0.0 13074 2 6537.0 6537.0 4600 8474 2739.3 socket + 0.0 8873 1 8873.0 8873.0 8873 8873 0.0 connect + 0.0 6874 3 2291.3 2418.0 1040 3416 1193.1 fwrite + 0.0 2770 1 2770.0 2770.0 2770 2770 0.0 bind + 0.0 1234 1 1234.0 1234.0 1234 1234 0.0 listen + 0.0 1156 1 1156.0 1156.0 1156 1156 0.0 fcntl + +[5/8] Executing 'cuda_api_sum' stats report + + Time (%) Total Time (ns) Num Calls Avg (ns) Med (ns) Min (ns) Max (ns) StdDev (ns) Name + -------- --------------- --------- ---------- -------- -------- -------- ----------- ---------------------- + 89.9 919006727 289 3179954.1 13477.0 9090 49083340 5059558.9 cudaMemcpy + 9.7 99655891 6 16609315.2 3164.5 1521 99579244 40646806.2 cudaMalloc + 0.2 1653566 482 3430.6 3266.5 2894 23561 1083.3 cudaEventRecord + 0.2 1584689 192 8253.6 3812.0 3165 815332 58578.6 cudaLaunchKernel + 0.1 608876 6 101479.3 23387.0 2171 376971 151258.0 cudaFree + 0.0 253967 97 2618.2 2630.0 1364 3568 259.8 cudaEventSynchronize + 0.0 31958 32 998.7 520.0 403 7999 1462.2 cudaEventCreate + 0.0 16409 32 512.8 355.5 288 1888 375.6 cudaEventDestroy + 0.0 1284 1 1284.0 1284.0 1284 1284 0.0 cuModuleGetLoadingMode + +[6/8] Executing 'cuda_gpu_kern_sum' stats report + + Time (%) Total Time (ns) Instances Avg (ns) Med (ns) Min (ns) Max (ns) StdDev (ns) Name + -------- --------------- --------- --------- --------- -------- -------- ----------- ---------------------------------------------------------------------------------------------------- + 99.9 866184910 96 9022759.5 9188328.0 6364230 9554682 668168.8 void exactFusedWarpTopKKernel(const T1 *, const T1 *, float *, … + 0.1 877669 96 9142.4 9120.0 8992 9696 104.0 blockTopKKernel(float *, const unsigned long *, float *, unsigned long *, unsigned long, unsigned i… + +[7/8] Executing 'cuda_gpu_mem_time_sum' stats report + + Time (%) Total Time (ns) Count Avg (ns) Med (ns) Min (ns) Max (ns) StdDev (ns) Operation + -------- --------------- ----- -------- -------- -------- -------- ----------- ---------------------------- + 99.5 49358062 97 508846.0 3936.0 2688 48983659 4973141.1 [CUDA memcpy Host-to-Device] + 0.5 241888 192 1259.8 1280.0 1184 1728 73.5 [CUDA memcpy Device-to-Host] + +[8/8] Executing 'cuda_gpu_mem_size_sum' stats report + + Total (MB) Count Avg (MB) Med (MB) Min (MB) Max (MB) StdDev (MB) Operation + ---------- ----- -------- -------- -------- -------- ----------- ---------------------------- + 515.072 97 5.310 0.033 0.020 512.000 51.982 [CUDA memcpy Host-to-Device] + 0.720 192 0.004 0.003 0.002 0.005 0.001 [CUDA memcpy Device-to-Host] + +Generated: + /root/PurplePulse/results/evidence/exact_k10_nsys.nsys-rep + /root/PurplePulse/results/evidence/exact_k10_nsys.sqlite diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/rebuild_after_instrumentation.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/rebuild_after_instrumentation.txt new file mode 100644 index 00000000..6e5fda3c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/rebuild_after_instrumentation.txt @@ -0,0 +1,4 @@ +[1/4] Building CXX object CMakeFiles/vector_search.dir/src/main.cpp.o +[2/4] Linking CXX executable vector_search +[3/4] Building CXX object CMakeFiles/ivf_search.dir/src/search_ivf.cpp.o +[4/4] Linking CXX executable ivf_search diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-04/source_sha256_before_instrumentation.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/source_sha256_before_instrumentation.txt new file mode 100644 index 00000000..83cd8927 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-04/source_sha256_before_instrumentation.txt @@ -0,0 +1,7 @@ +eeeffc41d9f0ab84e28aaa6f880724fff4c8d5705865802cbc0b33d289743630 CMakeLists.txt +32ed6b1be004536f50253595156d16546337c7da1919ed913e268e5a70af78b4 README.md +2e0b17c978b82dbe7ce893054cd0bea7ce69b8c30d7a460c63307161d56c8802 docs/FINAL_REPORT.md +6407c1299670abfc45b8dc6b3236d3c3ceeafac0f8b66dc6a525d00db6a499db docs/BASELINE_RESULTS.md +52fc4696718ca42a34210c5c708d3356c3d2cb4b43bc0deadccef4aac0b49bfe src/gpu_search.cu +fb547bdb955d692ef5b727741e56af0e10bba2078213f427a703159a6fc05d33 src/gpu_ivf_flat.cu +f9015d3923c57610548234da66e80781989a88da05309320d8aedc0339cfe915 scripts/evaluate_recall.py diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/bucket_major_compute_sanitizer.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/bucket_major_compute_sanitizer.log new file mode 100644 index 00000000..317a6b81 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/bucket_major_compute_sanitizer.log @@ -0,0 +1,3 @@ +========= COMPUTE-SANITIZER +IVF-Flat 建库、持久化、查询与 recall 测试通过 +========= ERROR SUMMARY: 0 errors diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/commands.md b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/commands.md new file mode 100644 index 00000000..bd6a1b12 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/commands.md @@ -0,0 +1,176 @@ +# 2026-09-08 validation commands + +The remote host address and credentials are intentionally not recorded. + +```bash +export PATH=/usr/local/cuda/bin:$PATH +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_ARCHITECTURES=native +cmake --build build -j 8 +ctest --test-dir build --output-on-failure +compute-sanitizer --tool memcheck --error-exitcode 99 ./build/unit_tests +compute-sanitizer --tool memcheck --error-exitcode 99 ./build/ivf_flat_tests +``` + +```bash +python3 scripts/generate_data.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --num-vectors 1000000 --num-queries 1000 --dim 128 \ + --dtype fp32 --metric inner_product --seed 2026 + +./build/ivf_build \ + --database data/million/inner_fp32_db.bin \ + --output data/million/inner_fp32_nlist256.ivf \ + --nlist 256 --iterations 15 --training-samples 100000 --threads 16 + +python3 scripts/benchmark_ivf_sweep.py \ + --search-binary ./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k100_batch64.conf \ + --exact results/exact_k100.txt \ + --output-dir results/k100_formal --csv results/k100_formal.csv \ + --nlist 256 --nprobes 128,160,192,224 \ + --training-samples 100000 --training-iterations 15 \ + --warmup 5 --repeat 100 +``` + +```bash +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_warp_compact_batch40.conf \ + --output results/k50_batch40.txt \ + --backend gpu --warmup 1 --repeat 100 + +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_batch64.conf \ + --output results/k50_batch64.txt \ + --backend gpu --warmup 1 --repeat 100 + +python3 scripts/evaluate_recall.py \ + --exact results/new_gpu/exact_k50.txt \ + --approximate results/k50_batch40.txt +``` + +```bash +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_warp_compact_batch40.conf \ + --output results/k50_probe_major.txt \ + --backend gpu --warmup 5 --repeat 100 + +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k50_bucket_major.conf \ + --output results/k50_bucket_major.txt \ + --backend gpu --warmup 5 --repeat 100 + +cmp results/k50_probe_major.txt results/k50_bucket_major.txt +compute-sanitizer --tool memcheck --error-exitcode 99 \ + ./build/ivf_flat_tests +``` + +K=100 heap and combined bucket-major A/B used the retained pre-optimization +binary and the rebuilt binary on the same host: + +```bash +./build/ivf_search_pre_k100_heap \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k100_warp1.conf \ + --output results/k100_pre_heap.txt \ + --backend gpu --warmup 5 --repeat 100 + +./build/ivf_search \ + --index data/million/inner_fp32_nlist256.ivf \ + --queries data/million/inner_fp32_q.bin \ + --params configs/ivf_flat_million_k100_bucket_major.conf \ + --output results/k100_heap_bucket_major.txt \ + --backend gpu --warmup 5 --repeat 100 + +cmp results/k100_pre_heap.txt results/k100_heap_bucket_major.txt +``` + +Rejected K=100 selection prototypes were tested against the retained stable +binary on the same host. The buffer-8 prototype was stopped after 10 repeats +because its QPS regression exceeded 20%. Kernel resources were inspected from +the compiled object before restoring the retained source. + +```bash +/usr/local/cuda/bin/cuobjdump --dump-resource-usage \ + build/CMakeFiles/vector_engine.dir/src/gpu_ivf_flat.cu.o + +sha256sum src/gpu_ivf_flat.cu +cmake --build build -j 8 +ctest --test-dir build --output-on-failure +``` + +The same-batch FAISS comparison reused the host CUDA 12.8 libraries. The venv +contained FAISS 1.14.1 and NumPy 2.2.6; disabling wheel preloading avoids +installing a second copy of CUDA runtime and cuBLAS. + +```bash +export _FAISS_WHEEL_DISABLE_CUDA_PRELOAD=1 +export LD_LIBRARY_PATH=/usr/local/cuda/lib64 + +/data/purplepulse-faiss-system-venv/bin/python scripts/benchmark_faiss.py \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --output-dir results/faiss_batch40 \ + --csv results/faiss_batch40.csv \ + --index-dir /data/purplepulse-faiss-indexes \ + --reference-results results/new_gpu/exact_k50.txt \ + --backends gpu --index-types ivf_flat \ + --top-ks 50 --nprobes 160 --nlist 256 --batch-size 40 \ + --train-samples 100000 --iterations 15 --seed 2026 \ + --warmup 5 --repeat 100 --cpu-threads 1 +``` + +```bash +python3 scripts/import_mnist.py \ + --input data/mnist/mnist.npz \ + --database data/mnist/database.bin \ + --queries data/mnist/queries.bin + +./build/ivf_build \ + --database data/mnist/database.bin --output data/mnist/nlist256.ivf \ + --nlist 256 --iterations 15 --training-samples 60000 --threads 16 + +./build/vector_search \ + --database data/mnist/database.bin --queries data/mnist/queries.bin \ + --params configs/exact_million_k10_fused_batch64.conf --backend gpu \ + --output results/mnist_exact_k10.txt --warmup 2 --repeat 10 + +python3 scripts/benchmark_ivf_sweep.py \ + --search-binary ./build/ivf_search \ + --index data/mnist/nlist256.ivf --queries data/mnist/queries.bin \ + --params configs/ivf_flat_mnist.conf \ + --exact results/mnist_exact_k10.txt \ + --output-dir results/mnist_ivf --csv results/mnist_ivf.csv \ + --nlist 256 --nprobes 8,16,32,64,96,128 \ + --training-samples 60000 --training-iterations 15 \ + --warmup 2 --repeat 10 +``` + +The final source-only audit excluded generated artifacts before configuring a new +directory: + +```bash +tar --exclude='./build' --exclude='./data' --exclude='./results' \ + --exclude='./evidence' --exclude='./.git' \ + -cf /data/purplepulse-submit-audit.tar . +mkdir /data/purplepulse-submit-audit +tar -xf /data/purplepulse-submit-audit.tar \ + -C /data/purplepulse-submit-audit +cmake -S /data/purplepulse-submit-audit \ + -B /data/purplepulse-submit-audit/build -G Ninja \ + -DCMAKE_BUILD_TYPE=Release +cmake --build /data/purplepulse-submit-audit/build -j 16 +ctest --test-dir /data/purplepulse-submit-audit/build --output-on-failure +``` diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/compute_sanitizer.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/compute_sanitizer.txt new file mode 100644 index 00000000..55289ea6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/compute_sanitizer.txt @@ -0,0 +1,3 @@ +========= COMPUTE-SANITIZER +FP32/FP16 的 CPU/GPU 正确性与边界测试通过 +========= ERROR SUMMARY: 0 errors diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/compute_sanitizer_ivf.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/compute_sanitizer_ivf.txt new file mode 100644 index 00000000..317a6b81 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/compute_sanitizer_ivf.txt @@ -0,0 +1,3 @@ +========= COMPUTE-SANITIZER +IVF-Flat 建库、持久化、查询与 recall 测试通过 +========= ERROR SUMMARY: 0 errors diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/ctest.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/ctest.txt new file mode 100644 index 00000000..af1690c9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/ctest.txt @@ -0,0 +1,22 @@ +Internal ctest changing into directory: /data/purplepulse-work/PurplePulse/build +Test project /data/purplepulse-work/PurplePulse/build + Start 1: unit_tests +1/8 Test #1: unit_tests ........................ Passed 0.26 sec + Start 2: file_io_tests +2/8 Test #2: file_io_tests ..................... Passed 0.01 sec + Start 3: ivf_flat_tests +3/8 Test #3: ivf_flat_tests .................... Passed 0.24 sec + Start 4: benchmark_faiss_tests +4/8 Test #4: benchmark_faiss_tests ............. Passed 0.87 sec + Start 5: benchmark_ivf_sweep_tests +5/8 Test #5: benchmark_ivf_sweep_tests ......... Passed 0.07 sec + Start 6: benchmark_adaptive_nprobe_tests +6/8 Test #6: benchmark_adaptive_nprobe_tests ... Passed 0.07 sec + Start 7: import_mnist_tests +7/8 Test #7: import_mnist_tests ................ Passed 0.28 sec + Start 8: plot_results_tests +8/8 Test #8: plot_results_tests ................ Passed 0.06 sec + +100% tests passed, 0 tests failed out of 8 + +Total Test time (real) = 1.86 sec diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/ctest_final.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/ctest_final.txt new file mode 100644 index 00000000..704f4b73 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/ctest_final.txt @@ -0,0 +1,22 @@ +Internal ctest changing into directory: /data/purplepulse-work/PurplePulse/build +Test project /data/purplepulse-work/PurplePulse/build + Start 1: unit_tests +1/8 Test #1: unit_tests ........................ Passed 0.22 sec + Start 2: file_io_tests +2/8 Test #2: file_io_tests ..................... Passed 0.01 sec + Start 3: ivf_flat_tests +3/8 Test #3: ivf_flat_tests .................... Passed 0.24 sec + Start 4: benchmark_faiss_tests +4/8 Test #4: benchmark_faiss_tests ............. Passed 0.27 sec + Start 5: benchmark_ivf_sweep_tests +5/8 Test #5: benchmark_ivf_sweep_tests ......... Passed 0.07 sec + Start 6: benchmark_adaptive_nprobe_tests +6/8 Test #6: benchmark_adaptive_nprobe_tests ... Passed 0.07 sec + Start 7: import_mnist_tests +7/8 Test #7: import_mnist_tests ................ Passed 0.25 sec + Start 8: plot_results_tests +8/8 Test #8: plot_results_tests ................ Passed 0.06 sec + +100% tests passed, 0 tests failed out of 8 + +Total Test time (real) = 1.18 sec diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/data_sha256.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/data_sha256.txt new file mode 100644 index 00000000..fb3e430b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/data_sha256.txt @@ -0,0 +1,7 @@ +d4dde1418ea7626e5226e594e592f9ae5ffbe4c412c326395d96388f95df9800 data/million/inner_fp32_db.bin +a58ebe43fce865b71a2a651791286fa0bd1567348e07d6c0601b69beaebceb45 data/million/inner_fp32_q.bin +f5bd87fcc72d37164fa931436e5bfd293dfb7f953d09cb28169a77c7cdadc415 data/million/inner_fp32_nlist256.ivf +731c5ac602752760c8e48fbffcf8c3b850d9dc2a2aedcf2cc48468fc17b673d1 data/mnist/mnist.npz +12e47ef4a46843d3bda71db30dd2163eb86b33c7404fa5c7f04e52e4f7c77007 data/mnist/database.bin +12725522c337401372be0a80ba95204578ec693b133472cd7251848e365ab3be data/mnist/queries.bin +b5290c789c8f28a6f2bc2f691c2b1a9c008ccda6b7d98600d022d05f08e8d479 data/mnist/nlist256.ivf diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/environment.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/environment.txt new file mode 100644 index 00000000..72c65f99 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/environment.txt @@ -0,0 +1,18 @@ +2026-09-08T08:02:37+00:00 +NVIDIA GeForce RTX 4090 D, 24564 MiB, 8.9, 570.124.06 +nvcc: NVIDIA (R) Cuda compiler driver +Copyright (c) 2005-2025 NVIDIA Corporation +Built on Wed_Jan_15_19:20:09_PST_2025 +Cuda compilation tools, release 12.8, V12.8.61 +Build cuda_12.8.r12.8/compiler.35404655_0 +cmake version 3.31.4 +1.11.1.git.kitware.jobserver-1 +g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 +CPU(s): 128 +Model name: Intel(R) Xeon(R) Platinum 8358P CPU @ 2.60GHz +Thread(s) per core: 2 +Core(s) per socket: 32 +Socket(s): 2 +NUMA node(s): 2 +NUMA node0 CPU(s): 0-31,64-95 +NUMA node1 CPU(s): 32-63,96-127 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/exact_k100.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/exact_k100.log new file mode 100644 index 00000000..bc3fe74e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/exact_k100.log @@ -0,0 +1,27 @@ +向量库: 1000000 x 128 +查询数: 1000 +dtype: fp32 +metric: inner_product +top_k: 100 +batch_size: 64 +distance_mode: warp +topk_mode: fused +warmup/repeat: 2/10 +backend: gpu +GPU 一次性初始化总时间: 171.032 ms +数据库一次性 H2D: 48.3343 ms +GPU 缓冲区: 489.558 MiB +估算冷启动端到端: 351.168 ms +平均常驻查询时间: 180.136 ms +run P50: 178.79 ms +run P99: 183.509 ms +run samples: 10 +常驻 QPS: 5551.36 +结果: "results/new_gpu/exact_k100.txt" +平均查询 H2D: 0.255754 ms +平均融合距离+局部 Top-K kernel: 176.98 ms +平均最终 Top-K kernel: 1.8362 ms +平均结果 D2H: 0.583744 ms +batch P50: 11.3988 ms +batch P99: 11.7988 ms +batch samples: 160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/faiss_batch40.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/faiss_batch40.log new file mode 100644 index 00000000..dfc01463 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/faiss_batch40.log @@ -0,0 +1,31 @@ +FAISS same-batch comparison, RTX 4090 D +FAISS 1.14.1 GPU; NumPy 2.2.6; Python 3.12.3 +K=50, nlist=256, nprobe=160, batch=40 +Training samples=100000, iterations=15, seed=2026 +Warmup: 5 full query sets; repeat: 100 + +FAISS Flat vs PurplePulse Exact: +recall@50=1.000000000 +minimum_query_recall=1.000000000 +mean_score_error=1.9556427e-06 +max_score_error=1.33514404e-05 + +FAISS GPU IVF-Flat: +average_query_ms=120.07527381181717 +qps=8328.109262255002 +run_p50_ms=119.6761205792427 +run_p99_ms=126.95340067148209 +batch_p50_ms=4.623956978321075 +batch_p99_ms=5.8260709047317505 +run_samples=100 +batch_latency_samples=2500 +recall_at_50=0.92312 +minimum_query_recall=0.8 + +PurplePulse bucket-major, same K/nprobe/batch/repeat: +average_query_ms=144.077 +qps=6940.71 +run_p99_ms=146.137 +recall_at_50=0.92482 + +FAISS/PurplePulse QPS ratio=1.1999x. diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_bucket_major_formal.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_bucket_major_formal.log new file mode 100644 index 00000000..ff8bc4c3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_bucket_major_formal.log @@ -0,0 +1,26 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/100 +nprobe policy: fixed +memory mode: disabled +索引加载: 297.36 ms +GPU 初始化: 205.505429 ms +索引 H2D: 49.871902 ms +GPU 缓冲区: 508.042488 MiB +平均查询: 185.624 ms +run P50/P99: 185.513/187.381 ms +run samples: 100 +QPS: 5387.23 +输出: "results/new_gpu/bucket_major/k100_bucket_major_formal.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.233426 ms +平均 GPU 中心选择: 1.62975 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 177.212 ms +平均 GPU 最终 Top-K 归并: 1.30388 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.537924 ms +batch P50/P99: 11.4996/11.5487 ms +batch samples: 1600 +实际 nprobe min/avg/max: 160/160/160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_heap_formal.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_heap_formal.log new file mode 100644 index 00000000..8af8fcc7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_heap_formal.log @@ -0,0 +1,38 @@ +K=100 heap optimization, RTX 4090 D, nprobe=160, batch=64 +Warmup: 5 full query sets; repeat: 100; queries per run: 1000 + +warp1_pre_heap +average_query_ms=188.737 +qps=5298.37 +run_p50_ms=188.738 +run_p99_ms=190.409 +batch_p50_ms=11.6936 +batch_p99_ms=11.8875 +scan_ms=180.438 +merge_ms=1.30079 + +warp1_heap_hole +average_query_ms=184.311 +qps=5425.61 +run_p50_ms=184.179 +run_p99_ms=185.741 +batch_p50_ms=11.3594 +batch_p99_ms=11.6603 +scan_ms=175.945 +merge_ms=1.30443 +speedup_vs_pre_heap=2.4015% + +bucket_major_heap_hole +average_query_ms=182.091 +qps=5491.76 +run_p50_ms=181.988 +run_p99_ms=184.321 +batch_p50_ms=11.2720 +batch_p99_ms=11.3244 +scan_ms=173.743 +merge_ms=1.30183 +speedup_vs_pre_heap=3.6500% + +All three result files were compared byte for byte with cmp: equal. +CTest: 8/8 passed. +Compute Sanitizer ivf_flat_tests: ERROR SUMMARY: 0 errors. diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_selection_negative.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_selection_negative.log new file mode 100644 index 00000000..ae2bd569 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_selection_negative.log @@ -0,0 +1,46 @@ +K=100 selection experiments rejected after same-host A/B +Platform: NVIDIA GeForce RTX 4090 D +Dataset: Synthetic-1M, 128-dimensional FP32, inner product +Index: IVF-Flat, nlist=256, nprobe=160 +Batch size: 64 + +distributed_register_topk + baseline: 5483.49 QPS, average 182.366 ms, P99 183.618 ms, scan 174.026 ms + variant: 5507.23 QPS, average 181.579 ms, P99 183.087 ms, scan 173.294 ms + change: +0.4329% + repeat: 100 after warm-up + output: byte-identical + decision: reject; below the predeclared 1% acceptance threshold + +candidate_buffer_8 + baseline: 5508.19 QPS, average 181.548 ms, P99 182.597 ms, scan 173.114 ms + variant: 4258.85 QPS, average 234.805 ms, P99 239.191 ms, scan 225.342 ms + change: -22.6815% + repeat: 10 after warm-up; stopped before the 100-run formal phase + output: byte-identical + CTest: 8/8 passed + Compute Sanitizer: 0 errors + resource diagnostic for K=100, one-warp, inner-product, bucket-major kernel: + stable: REG 48, STACK 0 B, SHARED 1200 B, LOCAL 0 B + buffer8: REG 48, STACK 96 B, SHARED 1200 B, LOCAL 0 B + decision: reject; per-thread candidate arrays spill to a 96-byte stack and the + best-first flush adds extra selection work + +warp_bitonic_sort_128 + baseline: 5496.78 QPS, average 181.925 ms, P99 182.873 ms, scan 173.398 ms + variant: 4467.83 QPS, average 223.822 ms, P99 229.924 ms, scan 214.114 ms + change: -18.7191% + repeat: 10 after warm-up; stopped before the 100-run formal phase + output: byte-identical + CTest: 8/8 passed + Compute Sanitizer: 0 errors + resource diagnostic for K=100, one-warp, inner-product, bucket-major kernel: + stable: REG 48, STACK 0 B, SHARED 1200 B, LOCAL 0 B + bitonic: REG 56, STACK 0 B, SHARED 1536 B, LOCAL 0 B + decision: reject; the fixed 28-stage sorting network, synchronization, and + extra comparisons cost more than parallel lane participation saves + +After each experiment, local and remote source were restored to the retained +stable baseline: + sha256 0a4dd5ddaaf7471893f3a2471908d2c9417f8f014c961e16153584f7ca6e45ac +Remote CTest after restoration: 8/8 passed. diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_warp1_formal_v2.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_warp1_formal_v2.log new file mode 100644 index 00000000..e76d0d55 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k100_warp1_formal_v2.log @@ -0,0 +1,26 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/100 +nprobe policy: fixed +memory mode: disabled +索引加载: 300.863 ms +GPU 初始化: 208.406499 ms +索引 H2D: 49.795135 ms +GPU 缓冲区: 507.962410 MiB +平均查询: 189.329 ms +run P50/P99: 189.296/190.881 ms +run samples: 100 +QPS: 5281.82 +输出: "results/new_gpu/bucket_major/k100_warp1_formal.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.229897 ms +平均 GPU 中心选择: 1.63722 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 180.957 ms +平均 GPU 最终 Top-K 归并: 1.30519 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.491604 ms +batch P50/P99: 11.7282/11.9142 ms +batch samples: 1600 +实际 nprobe min/avg/max: 160/160/160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_batch40_formal.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_batch40_formal.log new file mode 100644 index 00000000..fcc2efd9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_batch40_formal.log @@ -0,0 +1,26 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 318.318 ms +GPU 初始化: 227.746493 ms +索引 H2D: 63.280128 ms +GPU 缓冲区: 499.805611 MiB +平均查询: 166.116 ms +run P50/P99: 166.303/168.097 ms +run samples: 100 +QPS: 6019.91 +输出: "results/new_gpu/k50_tuning/batch40_formal.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.296211 ms +平均 GPU 中心选择: 2.65625 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 157.225 ms +平均 GPU 最终 Top-K 归并: 1.02493 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.641596 ms +batch P50/P99: 6.49126/6.62845 ms +batch samples: 2500 +实际 nprobe min/avg/max: 160/160/160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_batch64_formal.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_batch64_formal.log new file mode 100644 index 00000000..5e95fe41 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_batch64_formal.log @@ -0,0 +1,26 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 294.715 ms +GPU 初始化: 201.381904 ms +索引 H2D: 48.189442 ms +GPU 缓冲区: 502.066414 MiB +平均查询: 174.301 ms +run P50/P99: 174.55/176.348 ms +run samples: 100 +QPS: 5737.2 +输出: "results/new_gpu/k50_tuning/batch64_formal.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.229836 ms +平均 GPU 中心选择: 1.69307 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 166.943 ms +平均 GPU 最终 Top-K 归并: 0.699045 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.419959 ms +batch P50/P99: 10.9121/11.2116 ms +batch samples: 1600 +实际 nprobe min/avg/max: 160/160/160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_bucket_major_formal.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_bucket_major_formal.log new file mode 100644 index 00000000..4411f280 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_bucket_major_formal.log @@ -0,0 +1,26 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 287.3 ms +GPU 初始化: 200.789089 ms +索引 H2D: 50.339840 ms +GPU 缓冲区: 499.856392 MiB +平均查询: 143.592 ms +run P50/P99: 143.5/145.534 ms +run samples: 100 +QPS: 6964.16 +输出: "results/new_gpu/bucket_major/v2_bucket_major_formal.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.293489 ms +平均 GPU 中心选择: 2.54214 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 134.757 ms +平均 GPU 最终 Top-K 归并: 1.04728 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.60983 ms +batch P50/P99: 5.56659/5.62608 ms +batch samples: 2500 +实际 nprobe min/avg/max: 160/160/160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_warp_compact_formal.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_warp_compact_formal.log new file mode 100644 index 00000000..e6d41de1 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/k50_warp_compact_formal.log @@ -0,0 +1,26 @@ +IVF-Flat gpu 查询完成 +索引: 1000000 x 128 +dtype/metric: fp32/inner_product +nlist/nprobe/top_k: 256/160/50 +nprobe policy: fixed +memory mode: disabled +索引加载: 302.472 ms +GPU 初始化: 223.422613 ms +索引 H2D: 64.267265 ms +GPU 缓冲区: 499.805611 MiB +平均查询: 166.411 ms +run P50/P99: 166.384/169.04 ms +run samples: 100 +QPS: 6009.22 +输出: "results/new_gpu/bucket_major/v2_compact_formal.txt" +平均 CPU 中心/桶选择: 0 ms +平均 query H2D: 0.307637 ms +平均 GPU 中心选择: 2.65958 ms +平均自适应分层开销: 0 ms +平均 GPU 桶扫描+局部 Top-K: 157.329 ms +平均 GPU 最终 Top-K 归并: 1.02553 ms +平均记忆独立重排: 0 ms +平均结果 D2H: 0.66075 ms +batch P50/P99: 6.4944/6.62154 ms +batch samples: 2500 +实际 nprobe min/avg/max: 160/160/160 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/mnist_exact_k10.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/mnist_exact_k10.log new file mode 100644 index 00000000..cdc2251e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/mnist_exact_k10.log @@ -0,0 +1,27 @@ +向量库: 60000 x 784 +查询数: 10000 +dtype: fp32 +metric: l2 +top_k: 10 +batch_size: 64 +distance_mode: warp +topk_mode: fused +warmup/repeat: 2/10 +backend: gpu +GPU 一次性初始化总时间: 188.657 ms +数据库一次性 H2D: 23.2746 ms +GPU 缓冲区: 179.759 MiB +估算冷启动端到端: 621.072 ms +平均常驻查询时间: 432.415 ms +run P50: 430.865 ms +run P99: 437.408 ms +run samples: 10 +常驻 QPS: 23125.9 +结果: "results/new_gpu/mnist_exact_k10.txt" +平均查询 H2D: 6.91412 ms +平均融合距离+局部 Top-K kernel: 418.37 ms +平均最终 Top-K kernel: 1.67326 ms +平均结果 D2H: 3.2634 ms +batch P50: 2.74214 ms +batch P99: 2.81181 ms +batch samples: 1570 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-08/submit_audit_ctest.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/submit_audit_ctest.log new file mode 100644 index 00000000..3089980a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-08/submit_audit_ctest.log @@ -0,0 +1,22 @@ +Internal ctest changing into directory: /data/purplepulse-submit-audit/build +Test project /data/purplepulse-submit-audit/build + Start 1: unit_tests +1/8 Test #1: unit_tests ........................ Passed 0.24 sec + Start 2: file_io_tests +2/8 Test #2: file_io_tests ..................... Passed 0.01 sec + Start 3: ivf_flat_tests +3/8 Test #3: ivf_flat_tests .................... Passed 0.24 sec + Start 4: benchmark_faiss_tests +4/8 Test #4: benchmark_faiss_tests ............. Passed 2.55 sec + Start 5: benchmark_ivf_sweep_tests +5/8 Test #5: benchmark_ivf_sweep_tests ......... Passed 0.07 sec + Start 6: benchmark_adaptive_nprobe_tests +6/8 Test #6: benchmark_adaptive_nprobe_tests ... Passed 0.07 sec + Start 7: import_mnist_tests +7/8 Test #7: import_mnist_tests ................ Passed 0.26 sec + Start 8: plot_results_tests +8/8 Test #8: plot_results_tests ................ Passed 0.07 sec + +100% tests passed, 0 tests failed out of 8 + +Total Test time (real) = 3.50 sec diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/commands.md b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/commands.md new file mode 100644 index 00000000..47704d8e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/commands.md @@ -0,0 +1,150 @@ +# 2026-09-10 第六阶段公开数据命令 + +所有长任务在实验机项目目录执行并用 `nohup` 脱离 SSH。登录地址和凭据不记录 +在仓库中。原始数据、索引、Top-K 输出和日志保存在 `/data`;仓库只同步 CSV、 +JSON 和 SVG 摘要。 + +## 现有产物检查 + +启动 Yahoo 前先检查进程和两套结果目录。SIFT1M 已包含 `build.csv`、 +`exact_gpu.csv`、K=10/50/100 的完整 IVF 矩阵、21 行 FAISS 数据、ground truth +验证和图表,因此没有重复运行。Yahoo 数据已转换但结果目录为空。 + +```bash +pgrep -af 'prepare_real_datasets|run_real_benchmarks|ivf_build|ivf_search|vector_search|benchmark_faiss' +find results/real/sift1m -maxdepth 2 -type f -print +find results/real/yahoo-minilm-384 -maxdepth 2 -type f -print +sha256sum data/real/yahoo-minilm-384-normalized/manifest.json +``` + +Yahoo manifest 记录原始 HDF5 SHA-256 为 +`8b0519850249d7ea4aea258eb43ae837dca1bb2f7a85ee0a5145afdb699c4136`,转换结果为 +677,305 × 384、1,000 queries、cosine、Top-100 ground truth。 + +## Yahoo MiniLM 384 正式运行 + +任务信息写入 `/data/purplepulse-work/jobs/stage6-yahoo-minilm-384-20260910/`,结果 +写入 `/data/purplepulse-work/PurplePulse/results/real/yahoo-minilm-384/`。 + +```bash +cd /data/purplepulse-work/PurplePulse +job_dir=/data/purplepulse-work/jobs/stage6-yahoo-minilm-384-20260910 +mkdir -p "$job_dir" + +nohup env \ + PYTHONUNBUFFERED=1 \ + PATH=/usr/local/cuda/bin:$PATH \ + LD_LIBRARY_PATH=/usr/local/cuda/lib64 \ + _FAISS_WHEEL_DISABLE_CUDA_PRELOAD=1 \ + /data/purplepulse-faiss-system-venv/bin/python \ + scripts/run_real_benchmarks.py \ + --dataset yahoo-minilm-384 \ + --project-root /data/purplepulse-work/PurplePulse \ + --data-root data/real \ + --results-root results/real \ + --build-dir build \ + --nlist 1024 \ + --nprobes 32,64,128,160,192,224 \ + --training-samples 100000 \ + --iterations 15 \ + --threads 16 \ + --batch-size 64 \ + --warmup 1 \ + --repeat 5 \ + > "$job_dir/driver.log" 2>&1 < /dev/null & + +printf '%s\n' "$!" > "$job_dir/driver.pid" +``` + +驱动于 2026-09-10 11:55 UTC 完成。阶段结果由各 benchmark 脚本逐行更新 CSV, +即使 SSH 断开也不依赖终端缓冲。完整结果摘要与回退结论见 +`docs/REPRODUCIBILITY.md`,可提交证据位于 `results/real/`。 + +## 第七阶段 Exact fused 剖析 + +长任务仍通过 `nohup` 运行,状态、PID 和日志均位于 `/data`。正式剖析任务为 +`/data/purplepulse-work/jobs/stage7-exact-profile-formal-20260910/`,结果逐 K +checkpoint 到 `results/stage7_exact_profile/`。命令模板为: + +```bash +cd /data/purplepulse-work/PurplePulse +job_dir=/data/purplepulse-work/jobs/stage7-exact-profile-formal-20260910 +mkdir -p "$job_dir" +nohup bash -lc ' + cd /data/purplepulse-work/PurplePulse + python3 scripts/benchmark_exact_breakdown.py \ + --search-binary ./build/vector_search \ + --database data/million/inner_fp32_db.bin \ + --queries data/million/inner_fp32_q.bin \ + --configs 10:configs/exact_million_k10_fused_batch64.conf,50:configs/exact_million_k50_fused_batch64.conf,100:configs/exact_million_k100_fused_batch64.conf \ + --reference-results 10:results/new_gpu/exact_k10.txt,50:results/new_gpu/exact_k50.txt,100:results/new_gpu/exact_k100.txt \ + --output-dir results/stage7_exact_profile/synthetic1m/outputs \ + --csv results/stage7_exact_profile/synthetic1m/breakdown.csv \ + --warmup 5 --repeat 20 --profile-repeat 20 +' > "$job_dir/driver.log" 2>&1 < /dev/null & +printf '%s\n' "$!" > "$job_dir/driver.pid" +``` + +Yahoo 使用 `data/real/yahoo-minilm-384-normalized/{database,queries}.bin`、 +`configs/real_exact_k{10,50,100}.conf` 和第六阶段 Exact 输出作为逐 rank 参考。 +首项 cosine 范数预计算 A/B 的完整可执行脚本为 +`stage7/run_exact_profile_ab.sh`;对应 nohup 任务目录是 +`/data/purplepulse-work/jobs/stage7-cosine-norm-ab-20260910/`。实验否决并恢复 +baseline 后,`stage7-restore-profiler-baseline-20260910` 状态为 0,CTest +12/12 通过。 + +## 第七阶段 query tiling + +query-tile A/B 使用 `scripts/benchmark_exact_query_tile.py`。驱动接受多个 +`--variant label=K:config`,每完成一个 variant 就重写 checkpoint CSV,并用 +`--reference-results` 做逐 query、逐 rank 的 ID/score 校验。远端长任务全部 +通过 `nohup` 运行,主要目录如下: + +- `stage7-query-tile-formal-20260910`:Synthetic/Yahoo K=10、K=50 正式 A/B。 +- `stage7-query-tile-sift-formal-20260910`:只复测既有 SIFT1M 的 K=10/K=50。 +- `stage7-query-tile-grid-sweep-smoke-20260910`:固定 `grid.x` 的短筛选。 +- `stage7-query-tile-yahoo-grid-formal-20260910`:Yahoo K=10 的 20 次正式 + 96/160/192-block 对照。 +- `stage7-query-tile-sanitizer-20260910`:`compute-sanitizer --tool memcheck` + 执行 `unit_tests`,状态 0、0 errors。 + +所有 CSV 写入 +`/data/purplepulse-work/PurplePulse/results/stage7_exact_query_tile/`;仓库只同步 +CSV,不同步大型 Top-K 输出和日志。 + +## 第七阶段 block-tile 负实验 + +源码上传与构建任务分别位于 `stage7-block-tile-upload-20260910` 和 +`stage7-block-tile-build-20260910`;上传前保存了 query-tile 最佳二进制, +构建状态为 0,CTest 13/13。筛选任务 `stage7-block-tile-smoke-20260910` +通过 `nohup` 运行 Synthetic/Yahoo K=10 的 baseline、warp-query 最优项和 +block-tile 64/96/128/160/192 blocks。结果逐项 checkpoint 到 +`results/stage7_exact_block_tile/smoke/{synthetic,yahoo}/results.csv`,全部通过 +逐 query、逐 rank 的 ID/score 校验。候选未超过 warp-query,因此没有重复 +SIFT 已完成工作,也没有启动 20 次正式长跑。Compute Sanitizer 任务目录为 +`stage7-block-tile-sanitizer-20260910`。 + +## 第八阶段稳定性矩阵 + +上传任务目录为 `stage8-stability-upload-20260910`,其中保存上传前 CMake、测试 +文件(若存在)和 `vector_search` 二进制。构建与完整回归通过以下 nohup 任务 +执行,日志和状态均位于 `/data`: + +```bash +cd /data/purplepulse-work/PurplePulse +job_dir=/data/purplepulse-work/jobs/stage8-stability-build-20260910 +nohup bash -lc ' + cd /data/purplepulse-work/PurplePulse + export PATH=/usr/local/cuda/bin:$PATH + cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_ARCHITECTURES=native && + cmake --build build && + ctest --test-dir build --output-on-failure +' > "$job_dir/driver.log" 2>&1 < /dev/null & +``` + +CTest 14/14 通过。`stage8-stability-sanitizer-20260910` 先执行 +`build/stability_tests` 并把摘要写入 `results/stage8_stability/coverage.log`, +再以 `compute-sanitizer --tool memcheck --error-exitcode 99` 运行同一矩阵;两段 +状态均为 0,错误汇总为 0。大日志只保留在远端 `/data`,仓库保存小型 +`coverage.csv` 和校验和。 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/README.md b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/README.md new file mode 100644 index 00000000..f729185e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/README.md @@ -0,0 +1,35 @@ +# 第七阶段证据索引 + +- `gpu.txt`:正式实验 GPU 型号、驱动和显存。 +- `source.sha256`:首次正式分段剖析时的二进制、CUDA 源码和驱动脚本校验和。 +- `current_source.sha256`:加严逐 rank 校验并撤回负优化后的远端二进制、CUDA + 源码和驱动脚本校验和;恢复任务状态为 0,CTest 12/12 通过。 +- `cosine_norm_ab_source.sha256`:范数预计算 A/B 的基线/候选二进制、候选源码 + 与重放脚本校验和。 +- `run_exact_profile_ab.sh`:在远端 `/data` 项目目录重放四组严格 A/B 的脚本。 +- `query_tile_source.sha256`:query-tiled fused 最终二进制、源码、驱动和保留 + 配置的校验和,以及 CTest/Sanitizer 状态。 +- `block_tile_source.sha256`:block-tile 二进制、源码、配置、两份 smoke CSV + 的校验和,以及 CTest/Sanitizer 状态。 +- `../../../results/stage7_exact_profile/`:Synthetic-1M 与 Yahoo MiniLM 384 + 分段基线 CSV,以及范数预计算的四份 A/B CSV。 +- `../../../results/stage7_exact_query_tile/`:两轮 smoke、grid.x sweep,以及 + Synthetic/SIFT/Yahoo 的 20 次正式 A/B CSV。 +- `../../../results/stage7_exact_block_tile/smoke/`:Synthetic/Yahoo 的 + block-tile grid.x 筛选 CSV;该候选未超过 warp-query,未扩展正式长跑。 + +分段方法是 differential estimate:distance-only kernel 保留 fused 路径的 +网格、query cache 和距离归约,局部选择估算为两者差值;final merge 独立计时。 +首次正式基线做候选集合与分数校验;随后 A/B 复测加严为按 query、rank、ID +和分数比较。长任务使用 `nohup`,原始输出和日志仅保存在远端 +`/data/purplepulse-work/`。 + +query-tile 长任务目录以 `stage7-query-tile-` 开头。最终构建 CTest 13/13 +通过,`stage7-query-tile-sanitizer-20260910` 状态为 0,Compute Sanitizer +报告 0 errors。大日志和 Top-K 文本输出只保存在远端 `/data`。 + +block-tile 使用 `stage7-block-tile-build-20260910` 构建并通过 CTest 13/13; +筛选任务为 `stage7-block-tile-smoke-20260910`。默认 layout 仍是 +`warp_query`,block-tile 仅在配置显式请求时启用。 +`stage7-block-tile-sanitizer-20260910` 状态为 0,Compute Sanitizer 报告 +0 errors。 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/block_tile_source.sha256 b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/block_tile_source.sha256 new file mode 100644 index 00000000..30444823 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/block_tile_source.sha256 @@ -0,0 +1,20 @@ +bd61902328a23c815393ecdc324a66911c7248764460ef17d649bfc6ada30bda build/vector_search +012a421cae285d297207c8627c55fa69d41f804ad812195f522d80770cf13f4e src/gpu_search.cu +357cf1ed201e511508ba85985080b39bd66d2aed25ec6eb9b578b163be3637af src/file_io.cpp +04e0e9479adaf3f334246e9daeab2c4fcaabca469f30677d96315849dec4ef0b src/main.cpp +38d0a5a99bc6aae1875874c41d6c183482ea094e2c3ba9f67ff3b283ba80db3b include/vector_types.h +ff29350fcda815214c7a4b730ea5a9ea07f1ac335131f8813b343b23ed97aae3 scripts/benchmark_exact_query_tile.py +7ad6329dbb33264fe49ad23113aa26cef0f9d8beb41880231882c1d26879c645 tests/unit_tests.cpp +da20d6e976f16478ca0e61598944a31df2d009fbf53167ad2f4afd08b0f204a5 tests/file_io_tests.cpp +306093be152d295e2d9584a15cc6ef9c38ad333433b9c49d57180f86011417e1 tests/test_benchmark_exact_query_tile.py +1357bf04fa9c275e14983187fa1837cc5688923361846f536d398c74cefaed8a configs/exact_fused_k10_batch64_blocktile8_blocks64.conf +636780a393d0c59e8f604639b9ce367e138f1c8b3a56ef2608933761bd268ff5 configs/exact_fused_k10_batch64_blocktile8_blocks96.conf +1d0bb80086965acb08157dd3ff58ff738a050ff64fb47045c6ac65ad081d1301 configs/exact_fused_k10_batch64_blocktile8_blocks128.conf +eb2a045d50e2c16aacefc30efa12805ebd995123ebb8a33442a6b6fd0d0911f3 configs/exact_fused_k10_batch64_blocktile8_blocks160.conf +0c1e6d2d2243db09753b06146f4427d9b65046111ae46491b64222f5746fe419 configs/exact_fused_k10_batch64_blocktile8_blocks192.conf +3ef6ebf060a3efb4ba0e887cde3f2b51138e7579a48cee3caa62e42d01470c3b results/stage7_exact_block_tile/smoke/synthetic/results.csv +70dda44634311e029730f38ba894c28c223d8c98da6e3f6551a548d625521bff results/stage7_exact_block_tile/smoke/yahoo/results.csv +build_status=0 +ctest=13/13 +compute_sanitizer_status=0 +compute_sanitizer_error_summary=0 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/cosine_norm_ab_source.sha256 b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/cosine_norm_ab_source.sha256 new file mode 100644 index 00000000..47bcbe8c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/cosine_norm_ab_source.sha256 @@ -0,0 +1,4 @@ +6fab50001ddb98f11dd3227b06cf5488cb284196fe0c95acd18a9ed29470830b /data/purplepulse-work/jobs/stage7-cosine-norm-build-20260910/vector_search_baseline +58eb60f859bfc3a8287030ec77db1b75972e3215d2090b20e635ffe1dacaeb46 /data/purplepulse-work/PurplePulse/build/vector_search +4fc6144f72878808f558b9519f94497e8d37a2404095897d37afe84f69e79036 /data/purplepulse-work/PurplePulse/src/gpu_search.cu +b5127ce72cb5b57a70188558b3be33fc6148366224e01766960879d26577f445 /data/purplepulse-work/jobs/stage7-cosine-norm-ab-20260910/run.sh diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/current_source.sha256 b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/current_source.sha256 new file mode 100644 index 00000000..baa6b5d1 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/current_source.sha256 @@ -0,0 +1,3 @@ +f976c061e4cbd695635cb942e9a36b57a09033171b83ae6eed88b594c9d76cd9 build/vector_search +4ce613866f23cce5e9fc1aca0daaddba4cb1a628ed25bdfcc03d60722b1e28bc src/gpu_search.cu +4a05cac327565e0a901111e1780d164d163b6955dfc98669f8b3c8cdf588badc scripts/benchmark_exact_breakdown.py diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/gpu.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/gpu.txt new file mode 100644 index 00000000..d0955f10 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/gpu.txt @@ -0,0 +1 @@ +NVIDIA GeForce RTX 4090 D, 570.124.06, 24564 MiB diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/query_tile_source.sha256 b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/query_tile_source.sha256 new file mode 100644 index 00000000..b7b55a69 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/query_tile_source.sha256 @@ -0,0 +1,10 @@ +dce7c95fcb9bfe2610a765caba2e52a6100d468d8241e2aed7a2dca0199ffaca build/vector_search +892eccea7ce042c4323513bb94a919387d2e129d231fced56924cae82a532aec src/gpu_search.cu +d5dd5d78cb3169798654a267c8b94716716492b22cd555492657e365eadd6532 src/file_io.cpp +f713ac71d61f75dda851e22dc94d12125a1e336430b421c44ab2f10542fec7c1 include/vector_types.h +285dca96efd4597e183d7cd37931466d2ce8081a5a9804ab1f67ddf5a877938e scripts/benchmark_exact_query_tile.py +6f5008eeb95452f311300fc416d1cac2106bef6d2f7249166c95b5e8b93a6a89 configs/exact_fused_k10_batch64_querytile4.conf +7f26d004d22bafc5d24f0d2ef903f1778687bb8fc604e1f5bee95dd1c702e18d configs/exact_fused_k10_batch64_querytile8_blocks160.conf +e28a2874f8db9942038dd8834d222de3c8d3c4ffd084ab2d1c4f6e9a229228ec configs/exact_fused_k50_batch64_querytile4.conf +ctest_status=0 +compute_sanitizer_status=0 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/run_exact_profile_ab.sh b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/run_exact_profile_ab.sh new file mode 100755 index 00000000..13bfa972 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/run_exact_profile_ab.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=${1:-/data/purplepulse-work/PurplePulse} +baseline_binary=${2:-/data/purplepulse-work/jobs/stage7-cosine-norm-build-20260910/vector_search_baseline} +job_dir=${3:-/data/purplepulse-work/jobs/stage7-cosine-norm-ab-20260910} +results_root="$project_root/results/stage7_exact_profile/cosine_norm_ab" + +cd "$project_root" +mkdir -p \ + "$results_root/synthetic1m_baseline/outputs" \ + "$results_root/synthetic1m_optimized/outputs" \ + "$results_root/yahoo_baseline/outputs" \ + "$results_root/yahoo_optimized/outputs" + +synthetic_configs=10:configs/exact_million_k10_fused_batch64.conf,50:configs/exact_million_k50_fused_batch64.conf,100:configs/exact_million_k100_fused_batch64.conf +synthetic_references=10:results/new_gpu/exact_k10.txt,50:results/new_gpu/exact_k50.txt,100:results/new_gpu/exact_k100.txt +yahoo_configs=10:configs/real_exact_k10.conf,50:configs/real_exact_k50.conf,100:configs/real_exact_k100.conf +yahoo_references=10:results/real/yahoo-minilm-384/exact_outputs/exact_k10.txt,50:results/real/yahoo-minilm-384/exact_outputs/exact_k50.txt,100:results/real/yahoo-minilm-384/exact_outputs/exact_k100.txt + +run_profile() { + local binary=$1 + local database=$2 + local queries=$3 + local configs=$4 + local references=$5 + local output=$6 + python3 scripts/benchmark_exact_breakdown.py \ + --search-binary "$binary" \ + --database "$database" \ + --queries "$queries" \ + --configs "$configs" \ + --reference-results "$references" \ + --output-dir "$results_root/$output/outputs" \ + --csv "$results_root/$output/breakdown.csv" \ + --warmup 5 --repeat 20 --profile-repeat 20 +} + +run_profile "$baseline_binary" \ + data/million/inner_fp32_db.bin data/million/inner_fp32_q.bin \ + "$synthetic_configs" "$synthetic_references" synthetic1m_baseline +run_profile ./build/vector_search \ + data/million/inner_fp32_db.bin data/million/inner_fp32_q.bin \ + "$synthetic_configs" "$synthetic_references" synthetic1m_optimized +run_profile "$baseline_binary" \ + data/real/yahoo-minilm-384-normalized/database.bin \ + data/real/yahoo-minilm-384-normalized/queries.bin \ + "$yahoo_configs" "$yahoo_references" yahoo_baseline +run_profile ./build/vector_search \ + data/real/yahoo-minilm-384-normalized/database.bin \ + data/real/yahoo-minilm-384-normalized/queries.bin \ + "$yahoo_configs" "$yahoo_references" yahoo_optimized + +touch "$job_dir/complete" diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/source.sha256 b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/source.sha256 new file mode 100644 index 00000000..00670f5c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage7/source.sha256 @@ -0,0 +1,3 @@ +6fab50001ddb98f11dd3227b06cf5488cb284196fe0c95acd18a9ed29470830b build/vector_search +4ce613866f23cce5e9fc1aca0daaddba4cb1a628ed25bdfcc03d60722b1e28bc src/gpu_search.cu +5e231c55a3df94e83cb13f09b0dd7050d6da3ade6fa009cab7cf9c9fb57d0fc7 scripts/benchmark_exact_breakdown.py diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage8/README.md b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage8/README.md new file mode 100644 index 00000000..f322192c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage8/README.md @@ -0,0 +1,10 @@ +# 第八阶段证据索引 + +- `source.sha256`:CMake、稳定性测试、远端测试二进制、远端覆盖摘要和本地 + `coverage.csv` 的校验和,以及构建/CTest/Sanitizer 状态。 +- `../../../results/stage8_stability/coverage.csv`:覆盖类别、组合数和结果摘要。 +- `../../../docs/STABILITY_MATRIX.md`:Exact/IVF 实现选择、适用边界和安全回退。 + +远端长任务全部使用 nohup:`stage8-stability-build-20260910` 和 +`stage8-stability-sanitizer-20260910`。日志与逐任务状态保存在 +`/data/purplepulse-work/`;仓库不复制 sanitizer 大日志。 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage8/source.sha256 b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage8/source.sha256 new file mode 100644 index 00000000..cc2d7391 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-10/stage8/source.sha256 @@ -0,0 +1,15 @@ +0f969ab1acc2240ab6b52b02023282e3cf44a2b2120221e0ba247465a9e554c6 CMakeLists.txt +8db44443bf335387ff74c4fbd30dde9f0f94913fbae1f919fa0d1010913c34ab tests/stability_tests.cpp +fb2bc60f2d6cdb547b962260e830c2e07dd7b6dc50b0af53461ac0e3c07b24dd build/stability_tests +bd61902328a23c815393ecdc324a66911c7248764460ef17d649bfc6ada30bda build/vector_search +a8626c69c04eaad003f7bc0e3ec7e421f002da6f7acbd98341e3fa75f66e457d results/stage8_stability/coverage.log +9a271f2a916b0b6ee6cecb2426f0b3206ef074578be55d9bc94f6f3fe3ab86aa results/stage8_stability/coverage.status +9a271f2a916b0b6ee6cecb2426f0b3206ef074578be55d9bc94f6f3fe3ab86aa results/stage8_stability/sanitizer.status +2d1b4b722ea111df21243f4d81d02cf64393424f2ccc6e5d7c85e9440f56b0c8 results/stage8_stability/coverage.csv +build_status=0 +ctest=14/14 +compute_sanitizer_status=0 +compute_sanitizer_error_summary=0 +gpu=NVIDIA GeForce RTX 4090 D +compute_capability=8.9 +gpu_memory_mib=24564 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/README.md b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/README.md new file mode 100644 index 00000000..9f8703fc --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/README.md @@ -0,0 +1,18 @@ +# Stage 9 clean-build evidence + +Remote environment: RTX 4090 D, CUDA 12.8, GCC 13.3. The successful job was +started with `nohup` and wrote phased state to +`/data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/`. + +- `progress.tsv` and `status` show the phase sequence and terminal state. +- `logs/ctest.log` contains the 18/18 CTest summary. +- `logs/exact_verify.log` and `logs/ivf_verify.log` contain the CPU/GPU checks. +- `summary.txt` records row counts and SHA-256 hashes for the remote outputs. +- `reproduce-plan.json` is the machine-resolved Yahoo MiniLM dry-run plan. +- `release-validation.json` is the local release-artifact validator result. + +The first clean configure attempt wrote its failure state under the sibling remote +directory `stage9_clean_20260911`: the non-login shell did not include +`/usr/local/cuda/bin` in `PATH`, so CMake could not find `nvcc` and stopped before +compilation. The successful run used a new `-v2` build/result directory with that +PATH made explicit; no failed build directory was reused or deleted. diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/ctest.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/ctest.log new file mode 100644 index 00000000..0a6723cf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/ctest.log @@ -0,0 +1,42 @@ +Internal ctest changing into directory: /data/purplepulse-work/PurplePulse/build-stage9-clean-20260911-v2 +Test project /data/purplepulse-work/PurplePulse/build-stage9-clean-20260911-v2 + Start 1: unit_tests + 1/18 Test #1: unit_tests ......................... Passed 0.24 sec + Start 2: file_io_tests + 2/18 Test #2: file_io_tests ...................... Passed 0.01 sec + Start 3: ivf_flat_tests + 3/18 Test #3: ivf_flat_tests ..................... Passed 0.26 sec + Start 4: stability_tests + 4/18 Test #4: stability_tests .................... Passed 1.66 sec + Start 5: vector_search_help + 5/18 Test #5: vector_search_help ................. Passed 0.00 sec + Start 6: ivf_build_help + 6/18 Test #6: ivf_build_help ..................... Passed 0.00 sec + Start 7: ivf_search_help + 7/18 Test #7: ivf_search_help .................... Passed 0.00 sec + Start 8: benchmark_faiss_tests + 8/18 Test #8: benchmark_faiss_tests .............. Passed 1.66 sec + Start 9: benchmark_ivf_sweep_tests + 9/18 Test #9: benchmark_ivf_sweep_tests .......... Passed 0.07 sec + Start 10: benchmark_adaptive_nprobe_tests +10/18 Test #10: benchmark_adaptive_nprobe_tests .... Passed 0.07 sec + Start 11: import_mnist_tests +11/18 Test #11: import_mnist_tests ................. Passed 0.31 sec + Start 12: import_sift1m_tests +12/18 Test #12: import_sift1m_tests ................ Passed 0.31 sec + Start 13: import_ann_benchmarks_tests +13/18 Test #13: import_ann_benchmarks_tests ........ Passed 0.25 sec + Start 14: plot_results_tests +14/18 Test #14: plot_results_tests ................. Passed 0.07 sec + Start 15: stage6_tools_tests +15/18 Test #15: stage6_tools_tests ................. Passed 0.23 sec + Start 16: benchmark_exact_breakdown_tests +16/18 Test #16: benchmark_exact_breakdown_tests .... Passed 0.07 sec + Start 17: benchmark_exact_query_tile_tests +17/18 Test #17: benchmark_exact_query_tile_tests ... Passed 0.07 sec + Start 18: stage9_tools_tests +18/18 Test #18: stage9_tools_tests ................. Passed 0.08 sec + +100% tests passed, 0 tests failed out of 18 + +Total Test time (real) = 5.38 sec diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/exact_verify.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/exact_verify.log new file mode 100644 index 00000000..5d062456 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/exact_verify.log @@ -0,0 +1 @@ +通过:Top-K 候选集合相同,平均绝对分数误差=3.039230769056408e-06,最大分数误差=9.599999998499698e-06,近似并列换位数=0 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/ivf_verify.log b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/ivf_verify.log new file mode 100644 index 00000000..5d062456 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/logs/ivf_verify.log @@ -0,0 +1 @@ +通过:Top-K 候选集合相同,平均绝对分数误差=3.039230769056408e-06,最大分数误差=9.599999998499698e-06,近似并列换位数=0 diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/progress.tsv b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/progress.tsv new file mode 100644 index 00000000..c7581803 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/progress.tsv @@ -0,0 +1,24 @@ +2026-09-11T03:11:04Z running:preflight +2026-09-11T03:11:04Z running:configure +2026-09-11T03:11:12Z passed:configure +2026-09-11T03:11:12Z running:build +2026-09-11T03:11:44Z passed:build +2026-09-11T03:11:44Z running:ctest +2026-09-11T03:11:50Z passed:ctest +2026-09-11T03:11:50Z running:generate +2026-09-11T03:11:50Z passed:generate +2026-09-11T03:11:50Z running:exact_cpu +2026-09-11T03:11:50Z passed:exact_cpu +2026-09-11T03:11:50Z running:exact_gpu +2026-09-11T03:11:50Z passed:exact_gpu +2026-09-11T03:11:50Z running:ivf_build +2026-09-11T03:11:50Z passed:ivf_build +2026-09-11T03:11:50Z running:ivf_cpu +2026-09-11T03:11:50Z passed:ivf_cpu +2026-09-11T03:11:50Z running:ivf_gpu +2026-09-11T03:11:51Z passed:ivf_gpu +2026-09-11T03:11:51Z running:reproduce_dry_run +2026-09-11T03:11:51Z passed:reproduce_dry_run +2026-09-11T03:11:51Z running:summarize +2026-09-11T03:11:51Z passed:summarize +2026-09-11T03:11:51Z complete diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/release-validation.json b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/release-validation.json new file mode 100644 index 00000000..b145975d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/release-validation.json @@ -0,0 +1,20 @@ +{ + "status": "passed", + "project_root": "PurplePulse", + "validated_csv_rows": { + "results/real/sift1m/exact_gpu.csv": 3, + "results/real/sift1m/faiss_gpu.csv": 21, + "results/real/sift1m/ivf_k10.csv": 6, + "results/real/sift1m/ivf_k50.csv": 6, + "results/real/sift1m/ivf_k100.csv": 6, + "results/real/yahoo-minilm-384/exact_gpu.csv": 3, + "results/real/yahoo-minilm-384/faiss_gpu.csv": 21, + "results/real/yahoo-minilm-384/ivf_k10.csv": 6, + "results/real/yahoo-minilm-384/ivf_k50.csv": 6, + "results/real/yahoo-minilm-384/ivf_k100.csv": 6, + "results/formal_100k15/exact_gpu.csv": 3, + "results/formal_100k15/faiss_cpu_flat.csv": 3, + "results/stage8_stability/coverage.csv": 9 + }, + "report_bytes": 408735 +} diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/reproduce-plan.json b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/reproduce-plan.json new file mode 100644 index 00000000..5fdacb61 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/reproduce-plan.json @@ -0,0 +1,125 @@ +{ + "project_root": "/data/purplepulse-work/PurplePulse", + "steps": [ + { + "name": "configure", + "command": [ + "cmake", + "-S", + "/data/purplepulse-work/PurplePulse", + "-B", + "/data/purplepulse-work/PurplePulse/build-reproduce", + "-G", + "Ninja", + "-DCMAKE_BUILD_TYPE=Release", + "-DCMAKE_CUDA_ARCHITECTURES=native" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/configure.log" + }, + { + "name": "build", + "command": [ + "cmake", + "--build", + "/data/purplepulse-work/PurplePulse/build-reproduce" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/build.log" + }, + { + "name": "test", + "command": [ + "ctest", + "--test-dir", + "/data/purplepulse-work/PurplePulse/build-reproduce", + "--output-on-failure" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/ctest.log" + }, + { + "name": "prepare", + "command": [ + "/usr/bin/python3", + "/data/purplepulse-work/PurplePulse/scripts/prepare_real_datasets.py", + "--dataset", + "yahoo-minilm-384-normalized", + "--raw-dir", + "/data/purplepulse-work/PurplePulse/data/real/raw", + "--output-dir", + "/data/purplepulse-work/PurplePulse/data/real", + "--skip-download" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/prepare.log" + }, + { + "name": "benchmark:yahoo-minilm-384", + "command": [ + "/usr/bin/python3", + "/data/purplepulse-work/PurplePulse/scripts/run_real_benchmarks.py", + "--dataset", + "yahoo-minilm-384", + "--project-root", + "/data/purplepulse-work/PurplePulse", + "--data-root", + "/data/purplepulse-work/PurplePulse/data/real", + "--results-root", + "/data/purplepulse-work/PurplePulse/results/real", + "--build-dir", + "/data/purplepulse-work/PurplePulse/build-reproduce", + "--nlist", + "1024", + "--nprobes", + "32,64,128,160,192,224", + "--training-samples", + "100000", + "--iterations", + "15", + "--threads", + "16", + "--batch-size", + "64", + "--warmup", + "1", + "--repeat", + "5", + "--skip-index-build" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/benchmark-yahoo-minilm-384.log" + }, + { + "name": "plot:yahoo-minilm-384", + "command": [ + "/usr/bin/python3", + "/data/purplepulse-work/PurplePulse/scripts/plot_results.py", + "--results-dir", + "/data/purplepulse-work/PurplePulse/results/real/yahoo-minilm-384", + "--output-dir", + "/data/purplepulse-work/PurplePulse/results/real/yahoo-minilm-384/figures" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/plot-yahoo-minilm-384.log" + }, + { + "name": "report", + "command": [ + "/usr/bin/python3", + "/data/purplepulse-work/PurplePulse/scripts/build_final_report_pdf.py", + "--source", + "/data/purplepulse-work/PurplePulse/docs/FINAL_REPORT.md", + "--output", + "/data/purplepulse-work/PurplePulse/output/pdf/WarpFusion_Technical_Report.pdf" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/report.log" + }, + { + "name": "validate", + "command": [ + "/usr/bin/python3", + "/data/purplepulse-work/PurplePulse/scripts/validate_release.py", + "--project-root", + "/data/purplepulse-work/PurplePulse", + "--report", + "/data/purplepulse-work/PurplePulse/output/pdf/WarpFusion_Technical_Report.pdf" + ], + "log": "/data/purplepulse-work/PurplePulse/results/real/reproducibility/logs/validate.log" + } + ] +} diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/status b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/status new file mode 100644 index 00000000..c591978b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/status @@ -0,0 +1 @@ +complete diff --git a/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/summary.txt b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/summary.txt new file mode 100644 index 00000000..adc72ae7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/evidence/2026-09-11/stage9/summary.txt @@ -0,0 +1,11 @@ +100% tests passed, 0 tests failed out of 18 +Total Test time (real) = 5.38 sec +exact_rows=130 +ivf_rows=130 +exact_verify=通过:Top-K 候选集合相同,平均绝对分数误差=3.039230769056408e-06,最大分数误差=9.599999998499698e-06,近似并列换位数=0 +ivf_verify=通过:Top-K 候选集合相同,平均绝对分数误差=3.039230769056408e-06,最大分数误差=9.599999998499698e-06,近似并列换位数=0 +a5dcde0e5227b40cc04f0586be1bc80d9465a9f1c91c2e78c228933b1ad98fce /data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/exact_cpu.txt +7c9e01d52c60b3a80063ab51b48153d71632b43703aac1b92f1fe038785dcb1e /data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/exact_gpu.txt +a5dcde0e5227b40cc04f0586be1bc80d9465a9f1c91c2e78c228933b1ad98fce /data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/ivf_cpu.txt +7c9e01d52c60b3a80063ab51b48153d71632b43703aac1b92f1fe038785dcb1e /data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/ivf_gpu.txt +7d5b324cbce9475a4adec9eb54567db5ffc80a6867c939dd4b772004d5f749df /data/purplepulse-work/PurplePulse/results/stage9_clean_20260911_v2/reproduce-plan.json diff --git a/09_vector_retrieval/PurplePulse/include/file_io.h b/09_vector_retrieval/PurplePulse/include/file_io.h new file mode 100644 index 00000000..9512aff9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/include/file_io.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include "vector_types.h" + +VectorDatabase readVectorDatabase(const std::string& path); +QuerySet readQuerySet(const std::string& path); +MemoryMetadata readMemoryMetadata(const std::string& path); +void writeMemoryMetadata(const std::string& path, + const MemoryMetadata& metadata); +void validateMemoryMetadata(const MemoryMetadata& metadata, + std::uint64_t expected_vectors = 0); +SearchParams readSearchParams(const std::string& path); +void writeSearchResults(const std::string& path, const SearchResults& results); +void validateInputs(const VectorDatabase& database, const QuerySet& queries, + const SearchParams& params); diff --git a/09_vector_retrieval/PurplePulse/include/ivf_flat.h b/09_vector_retrieval/PurplePulse/include/ivf_flat.h new file mode 100644 index 00000000..a89c1899 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/include/ivf_flat.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "vector_types.h" + +IvfFlatIndex buildIvfFlatIndex(const VectorDatabase& database, + std::uint32_t nlist, + std::uint32_t iterations = 15, + std::uint64_t max_training_vectors = 100000, + std::uint32_t num_threads = 1); +void writeIvfFlatIndex(const std::string& path, const IvfFlatIndex& index); +IvfFlatIndex readIvfFlatIndex(const std::string& path); +void validateIvfFlatIndex(const IvfFlatIndex& index); + +std::vector> selectIvfCandidatePositions( + const IvfFlatIndex& index, const QuerySet& queries, std::uint32_t nprobe); + +SearchResults cpuIvfFlatSearch(const IvfFlatIndex& index, + const QuerySet& queries, + const SearchParams& params, + const MemoryMetadata* metadata = nullptr); + +// GPU IVF 执行器:中心、桶 offsets、索引向量和 ID 常驻显存;GPU 完成 +// 中心选择、各桶候选扫描、局部 Top-K 和最终归并。 +class GpuIvfFlatSearchEngine { + public: + GpuIvfFlatSearchEngine(const IvfFlatIndex& index, + const QuerySet& initial_queries, + const SearchParams& params, + const MemoryMetadata* metadata = nullptr); + ~GpuIvfFlatSearchEngine(); + + GpuIvfFlatSearchEngine(const GpuIvfFlatSearchEngine&) = delete; + GpuIvfFlatSearchEngine& operator=(const GpuIvfFlatSearchEngine&) = delete; + GpuIvfFlatSearchEngine(GpuIvfFlatSearchEngine&&) noexcept; + GpuIvfFlatSearchEngine& operator=(GpuIvfFlatSearchEngine&&) noexcept; + + SearchResults search(const QuerySet& queries, SearchStats* stats = nullptr); + double indexH2DMilliseconds() const; + std::size_t deviceBytes() const; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +SearchResults gpuIvfFlatSearch(const IvfFlatIndex& index, + const QuerySet& queries, + const SearchParams& params, + SearchStats* stats = nullptr, + const MemoryMetadata* metadata = nullptr); + +double recallAtK(const SearchResults& exact, const SearchResults& approximate); diff --git a/09_vector_retrieval/PurplePulse/include/search.h b/09_vector_retrieval/PurplePulse/include/search.h new file mode 100644 index 00000000..7f20aace --- /dev/null +++ b/09_vector_retrieval/PurplePulse/include/search.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +#include "vector_types.h" + +SearchResults cpuExactSearch(const VectorDatabase& database, + const QuerySet& queries, + const SearchParams& params); + +SearchResults gpuExactSearch(const VectorDatabase& database, + const QuerySet& queries, + const SearchParams& params, + SearchStats* stats = nullptr); + +// 将数据库和查询工作区常驻 GPU,适合预热、重复测量和服务化查询。 +class GpuExactSearchEngine { + public: + GpuExactSearchEngine(const VectorDatabase& database, + const QuerySet& initial_queries, + const SearchParams& params); + ~GpuExactSearchEngine(); + + GpuExactSearchEngine(const GpuExactSearchEngine&) = delete; + GpuExactSearchEngine& operator=(const GpuExactSearchEngine&) = delete; + GpuExactSearchEngine(GpuExactSearchEngine&&) noexcept; + GpuExactSearchEngine& operator=(GpuExactSearchEngine&&) noexcept; + + SearchResults search(const QuerySet& queries, SearchStats* stats = nullptr); + // Diagnostic differential probe for the fused path. It launches the same + // distance traversal without heap maintenance and returns the average GPU + // kernel time for a complete query set. Normal search timing is unaffected. + double profileDistanceOnlyMilliseconds(const QuerySet& queries, + std::uint32_t warmup, + std::uint32_t repeat); + double databaseH2DMilliseconds() const; + std::size_t deviceBytes() const; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +bool resultsMatch(const SearchResults& expected, const SearchResults& actual, + float absolute_tolerance, std::string* error_message); diff --git a/09_vector_retrieval/PurplePulse/include/vector_types.h b/09_vector_retrieval/PurplePulse/include/vector_types.h new file mode 100644 index 00000000..57036f41 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/include/vector_types.h @@ -0,0 +1,124 @@ +#pragma once + +#include +#include +#include + +enum class DataType : std::uint32_t { + kFloat32 = 1, + kFloat16 = 2, +}; + +enum class Metric : std::uint32_t { + kL2 = 1, + kInnerProduct = 2, + kCosine = 3, +}; + +struct VectorDatabase { + std::uint64_t num_vectors = 0; + std::uint32_t dim = 0; + DataType dtype = DataType::kFloat32; + Metric metric = Metric::kL2; + std::vector values; + std::vector half_values; +}; + +struct QuerySet { + std::uint64_t num_queries = 0; + std::uint32_t dim = 0; + DataType dtype = DataType::kFloat32; + std::vector values; + std::vector half_values; +}; + +// Agent memory metadata is kept in original vector-ID order. The IVF index +// may reorder vectors by bucket, so GPU kernels use index.ids[position] to +// address these columns without duplicating or rewriting the metadata file. +struct MemoryMetadata { + std::uint64_t num_vectors = 0; + std::vector timestamps; + std::vector importance; + std::vector session_ids; + std::vector source_types; +}; + +// IVF-Flat 在桶内保留原始向量,只改变排列顺序。聚类中心始终使用 FP32, +// 桶内向量仍保持输入 dtype。 +struct IvfFlatIndex { + std::uint64_t num_vectors = 0; + std::uint32_t dim = 0; + std::uint32_t nlist = 0; + DataType dtype = DataType::kFloat32; + Metric metric = Metric::kL2; + std::vector centers; + std::vector offsets; + std::vector ids; + std::vector values; + std::vector half_values; +}; + +struct SearchParams { + std::uint32_t top_k = 10; + std::string search_mode = "exact"; + std::uint32_t batch_size = 8; + std::string distance_mode = "warp"; + std::string topk_mode = "two_stage"; + // Exact fused experimental query tiling. A block reuses each database value + // across this many queries; 1 preserves the established kernel. + std::uint32_t exact_query_tile = 1; + // warp_query is the established/query-tiled warp layout; block_tile assigns + // one query per warp and reuses a shared database-vector tile. + std::string exact_fused_layout = "warp_query"; + // Zero selects the occupancy heuristic; a positive value pins grid.x for + // controlled Exact fused chunk-count sweeps. + std::uint32_t exact_fused_blocks = 0; + std::uint32_t nlist = 4096; + std::uint32_t nprobe = 16; + std::string nprobe_policy = "fixed"; + std::string adaptive_execution = "masked"; + std::uint32_t adaptive_nprobe_min = 1; + std::uint32_t adaptive_nprobe_step = 1; + float adaptive_target_mass = 0.9F; + float adaptive_temperature = 0.2F; + std::string memory_mode = "disabled"; + float memory_semantic_weight = 1.0F; + float memory_importance_weight = 0.0F; + float memory_recency_weight = 0.0F; + float memory_time_scale = 1.0F; + std::uint64_t memory_now = 0; + std::uint64_t filter_min_timestamp = 0; + std::uint32_t filter_session_id = UINT32_MAX; + std::uint32_t filter_source_type = UINT32_MAX; + std::uint32_t memory_rerank_factor = 4; + std::uint32_t pq_m = 16; +}; + +struct Neighbor { + std::uint64_t id = 0; + float score = 0.0F; +}; + +using SearchResults = std::vector>; + +struct SearchStats { + double host_selection_ms = 0.0; + double center_selection_ms = 0.0; + double adaptive_policy_ms = 0.0; + double database_h2d_ms = 0.0; + double query_h2d_ms = 0.0; + double distance_kernel_ms = 0.0; + double topk_kernel_ms = 0.0; + double memory_rerank_ms = 0.0; + double result_d2h_ms = 0.0; + std::vector batch_latency_ms; + std::uint64_t selected_probe_sum = 0; + std::uint64_t selected_probe_queries = 0; + std::uint32_t selected_probe_min = 0; + std::uint32_t selected_probe_max = 0; + std::vector selected_probe_counts; +}; + +const char* metricName(Metric metric); +const char* dataTypeName(DataType dtype); +Metric parseMetric(const std::string& text); diff --git a/09_vector_retrieval/PurplePulse/output/pdf/WarpFusion_Technical_Report.pdf b/09_vector_retrieval/PurplePulse/output/pdf/WarpFusion_Technical_Report.pdf new file mode 100644 index 00000000..8174ced3 Binary files /dev/null and b/09_vector_retrieval/PurplePulse/output/pdf/WarpFusion_Technical_Report.pdf differ diff --git a/09_vector_retrieval/PurplePulse/results/exact_fused/million_compare.csv b/09_vector_retrieval/PurplePulse/results/exact_fused/million_compare.csv new file mode 100644 index 00000000..5470c7bd --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/exact_fused/million_compare.csv @@ -0,0 +1,7 @@ +top_k,mode,average_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,initialization_ms,distance_or_fused_ms,final_topk_ms,maximum_score_error +10,matrix,563.347,1775.1,563.383,563.491,734.335,209.622,538.646,23.8401,0.0 +10,fused,179.736,5563.72,178.205,184.355,488.437,198.913,178.791,0.18313,0.0 +50,matrix,1396.89,715.874,1396.78,1397.28,732.49,180.337,538.588,857.022,0.0 +50,fused,195.186,5123.32,193.357,199.844,488.935,169.291,193.217,0.80857,0.0 +100,matrix,2253.36,443.781,2253.79,2254.14,732.526,175.024,538.601,1712.97,0.0 +100,fused,212.73,4700.8,210.322,217.367,489.558,172.003,209.586,1.80797,0.0 diff --git a/09_vector_retrieval/PurplePulse/results/figures/architecture.svg b/09_vector_retrieval/PurplePulse/results/figures/architecture.svg new file mode 100644 index 00000000..505a3ce3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/architecture.svg @@ -0,0 +1,84 @@ + + WarpFusion system architecture + Versioned inputs flow through host-side validation and index construction into resident GPU Exact and IVF pipelines, followed by strict correctness checks and reproducible artifacts. + + + WarpFusion: from versioned inputs to auditable results + + + Inputs + + Vector database + FP32 / FP16 + metric + + Queries + parameters + K, batch, nprobe, layout + + Public provenance + checksum + ground truth + + Versioned binary I/O + magic / shape / dtype + fail-closed validation + + + Host orchestration + + CPU Exact reference + stable score + ID ordering + + IVF index construction + deterministic k-means + continuous bucket layout + + Reproduction driver + build → test → datasets + benchmarks → plots → PDF + checkpoint + resume + + + Resident GPU engine + + Exact fused scan + query tile → warp heap + block merge; no score matrix + + IVF-Flat search + center selection → bucket tasks + warp scan → local heap + query-level k-way merge + + Persistent buffers + only queries/results transfer per batch + + + Evidence + + Correctness + ID + score + recall fallback + + Performance + QPS / P50 / P99 + GPU buffers + + Artifacts + CSV + JSON + SVG + PDF + + + + + + + + + Every optimization is accepted only after reproducible A/B and correctness checks + diff --git a/09_vector_retrieval/PurplePulse/results/figures/batch-qps.svg b/09_vector_retrieval/PurplePulse/results/figures/batch-qps.svg new file mode 100644 index 00000000..0aa35880 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/batch-qps.svg @@ -0,0 +1,53 @@ + +Batch size vs throughput +Benchmark curves generated from the checked-in raw CSV data. + + +Batch size vs throughput + +4049 + +4834 + +5619 + +6404 + +7190 + +8 + +16 + +32 + +64 + +128 + + +Batch size (queries) +Throughput (QPS) + +K=10 + + + + + + + +K=50 + + + + + + +K=100 + + + + + + diff --git a/09_vector_retrieval/PurplePulse/results/figures/recall-latency.svg b/09_vector_retrieval/PurplePulse/results/figures/recall-latency.svg new file mode 100644 index 00000000..2ee25924 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/recall-latency.svg @@ -0,0 +1,139 @@ + +Recall–latency frontier +Benchmark curves generated from the checked-in raw CSV data. + + +Recall–latency frontier + +WarpFusion + +FAISS GPU +K = 10 + +97 + +159 + +221 + +283 + +345 + +0.87 + +0.90 + +0.93 + +0.97 + +1.00 + + +Recall@K +1000-query latency (ms) + + +128 + +160 + +192 + +224 + + +128 + +160 + +192 + +224 +K = 50 + +78 + +123 + +168 + +214 + +259 + +0.85 + +0.89 + +0.92 + +0.96 + +1.00 + + +Recall@K + + +128 + +160 + +192 + +224 + + +128 + +160 + +192 + +224 +K = 100 + +88 + +136 + +184 + +232 + +280 + +0.84 + +0.88 + +0.92 + +0.96 + +0.99 + + +Recall@K + + +128 + +160 + +192 + +224 + + +128 + +160 + +192 + +224 +Matched batch=64 · point labels: nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/figures/recall-qps.svg b/09_vector_retrieval/PurplePulse/results/figures/recall-qps.svg new file mode 100644 index 00000000..93bc2dbc --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/recall-qps.svg @@ -0,0 +1,139 @@ + +Recall–throughput frontier +Benchmark curves generated from the checked-in raw CSV data. + + +Recall–throughput frontier + +WarpFusion + +FAISS GPU +K = 10 + +2595 + +4243 + +5892 + +7541 + +9189 + +0.87 + +0.90 + +0.93 + +0.97 + +1.00 + + +Recall@K +Throughput (QPS) + + +128 + +160 + +192 + +224 + + +128 + +160 + +192 + +224 +K = 50 + +3496 + +5529 + +7561 + +9594 + +11626 + +0.85 + +0.89 + +0.92 + +0.96 + +1.00 + + +Recall@K + + +128 + +160 + +192 + +224 + + +128 + +160 + +192 + +224 +K = 100 + +3260 + +5036 + +6811 + +8586 + +10362 + +0.84 + +0.88 + +0.92 + +0.96 + +0.99 + + +Recall@K + + +128 + +160 + +192 + +224 + + +128 + +160 + +192 + +224 +Matched batch=64 · point labels: nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-architecture.svg b/09_vector_retrieval/PurplePulse/results/figures/report-architecture.svg new file mode 100644 index 00000000..59c06608 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-architecture.svg @@ -0,0 +1,47 @@ + +WarpFusion 系统流程 +图中数据由仓库内原始 CSV 自动生成。 + + +WarpFusion 向量检索系统的组成与数据流 + +输入 + +向量库与查询 + +检索参数 + +公开数据校验和 + +CPU 端准备 + +格式与参数检查 + +精确结果参考 + +构建并保存 IVF 索引 + +GPU 常驻检索 + +Exact:边算距离边选 Top-K + +IVF:选桶、扫描、合并 + +每批只传查询与结果 + +输出证据 + +ID 与分数 + +召回率与延迟 + +CSV、图表、报告 + + + + + + + +每一次优化都要同时通过正确性检查和同输入 A/B 对照 + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-exact-breakdown.svg b/09_vector_retrieval/PurplePulse/results/figures/report-exact-breakdown.svg new file mode 100644 index 00000000..1f3f0ef7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-exact-breakdown.svg @@ -0,0 +1,48 @@ + +Exact 耗时分解 +图中数据由仓库内原始 CSV 自动生成。 + + +Exact 融合路径的 GPU 执行时间分解 + +距离与向量读取 + +局部 Top-K + +最终合并 +百万条 128 维合成数据 + + + +K=10 +98.3% + + + +K=50 +89.0% + + + +K=100 +80.7% + +67.7 万条 384 维文本向量 + + + +K=10 +98.7% + + + +K=50 +95.1% + + + +K=100 +89.6% + +柱顶数字表示“距离计算与向量读取”占 GPU 核函数流水的比例 + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-exact-fused.svg b/09_vector_retrieval/PurplePulse/results/figures/report-exact-fused.svg new file mode 100644 index 00000000..cec47e1c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-exact-fused.svg @@ -0,0 +1,44 @@ + +Exact 融合路径吞吐 +图中数据由仓库内原始 CSV 自动生成。 + + +Exact 融合路径与距离矩阵基线的吞吐对比 + +0 + +1,000 + +2,000 + +3,000 + +4,000 + +5,000 + +6,000 + + +1,775 + +5,564 +K=10 +加速比 3.13× + +716 + +5,123 +K=50 +加速比 7.16× + +444 + +4,701 +K=100 +加速比 10.59× + +先写距离矩阵 + +边计算边选 Top-K + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-k100-partitioned.svg b/09_vector_retrieval/PurplePulse/results/figures/report-k100-partitioned.svg new file mode 100644 index 00000000..e4b4e320 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-k100-partitioned.svg @@ -0,0 +1,51 @@ + +K=100 分区候选 +图中数据由仓库内原始 CSV 自动生成。 + + +K=100 条件下分区候选结构的性能影响 + +0 + +10,000 + +20,000 + +30,000 + +40,000 + +50,000 + +32 + +64 + +128 + +160 + +192 + +224 + + + + + + + + +完整大候选表 + + + + + + + + +4 个小候选表 +Recall@100 相同;加速比 1.38× +搜索桶数 nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-k50-scheduling.svg b/09_vector_retrieval/PurplePulse/results/figures/report-k50-scheduling.svg new file mode 100644 index 00000000..28a9568f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-k50-scheduling.svg @@ -0,0 +1,55 @@ + +K=50 任务调度 +图中数据由仓库内原始 CSV 自动生成。 + + +K=50 条件下按桶任务调度的性能影响 + +0 + +5,000 + +10,000 + +15,000 + +20,000 + +25,000 + +32 + +64 + +96 + +128 + +160 + +192 + +224 + + + + + + + + + +按查询顺序 + + + + + + + + + +按桶重排 ++24.8% +搜索桶数 nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-real-comparison.svg b/09_vector_retrieval/PurplePulse/results/figures/report-real-comparison.svg new file mode 100644 index 00000000..95e64b6c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-real-comparison.svg @@ -0,0 +1,46 @@ + +公开数据对比 +图中数据由仓库内原始 CSV 自动生成。 + + +公开数据集上的端到端吞吐对比(nprobe=160) +SIFT1M(图像特征) + + +1.81× +K=10 +召回 0.9999/0.9991 + + +1.43× +K=50 +召回 0.9997/0.9995 + + +1.33× +K=100 +召回 0.9996/0.9995 + +Yahoo MiniLM(文本向量) + + +2.53× +K=10 +召回 0.9939/0.9953 + + +2.43× +K=50 +召回 0.9915/0.9913 + + +2.34× +K=100 +召回 0.9892/0.9891 + + +WarpFusion + +FAISS GPU +召回数字依次为 WarpFusion / FAISS;两者各自训练聚类中心 + diff --git a/09_vector_retrieval/PurplePulse/results/figures/report-recall-qps.svg b/09_vector_retrieval/PurplePulse/results/figures/report-recall-qps.svg new file mode 100644 index 00000000..3d7b23ca --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/figures/report-recall-qps.svg @@ -0,0 +1,91 @@ + +召回率与吞吐权衡 +图中数据由仓库内原始 CSV 自动生成。 + + +公开数据集上的召回率与吞吐权衡(K=10) +SIFT1M(图像特征) + +97.5% + +0 + +98.1% + +19,613 + +98.7% + +39,225 + +99.4% + +58,838 + +100.0% + +78,450 + + + + + + + + + + + + + + +nprobe=32 +nprobe=224 + + +Yahoo MiniLM(文本向量) + +95.7% + +0 + +96.7% + +10,792 + +97.8% + +21,585 + +98.8% + +32,377 + +99.8% + +43,169 + + + + + + + + + + + + + + +nprobe=32 +nprobe=224 + + + +WarpFusion + +FAISS GPU +横轴为 Recall@10,纵轴为 QPS;每条曲线包含 nprobe=32、64、128、160、192、224 +越靠近右上方表示在相同召回率附近具有更高吞吐 + diff --git a/09_vector_retrieval/PurplePulse/results/formal_100k15/exact_gpu.csv b/09_vector_retrieval/PurplePulse/results/formal_100k15/exact_gpu.csv new file mode 100644 index 00000000..7b73c030 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_100k15/exact_gpu.csv @@ -0,0 +1,4 @@ +implementation,backend,metric,num_vectors,num_queries,dim,dtype,top_k,batch_size,warmup,run_samples,average_query_ms,qps,run_p50_ms,run_p99_ms,batch_latency_samples,batch_p50_ms,batch_p99_ms,gpu_initialization_ms,database_h2d_ms,gpu_buffer_mib,query_h2d_ms,fused_kernel_ms,final_topk_ms,result_d2h_ms +purplepulse,gpu,inner_product,1000000,1000,128,fp32,10,64,5,100,149.755,6677.57,150.025,151.143,1600,9.53296,9.64477,200.701,48.602,488.437,0.22932,148.772,0.187956,0.363535 +purplepulse,gpu,inner_product,1000000,1000,128,fp32,50,64,5,100,167.387,5974.19,167.671,169.027,1600,10.6347,10.8679,173.011,49.114,488.935,0.232645,165.594,0.844275,0.411974 +purplepulse,gpu,inner_product,1000000,1000,128,fp32,100,64,5,100,184.966,5406.4,185.035,187.947,1600,11.7263,12.1334,172.278,48.5765,489.558,0.232269,181.896,1.88726,0.492971 diff --git a/09_vector_retrieval/PurplePulse/results/formal_100k15/faiss_cpu_flat.csv b/09_vector_retrieval/PurplePulse/results/formal_100k15/faiss_cpu_flat.csv new file mode 100644 index 00000000..5f039ec3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_100k15/faiss_cpu_flat.csv @@ -0,0 +1,4 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,gpu_index_mib,gpu_temp_mib,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,training_iterations,training_seed,run_samples,batch_latency_samples,mean_absolute_score_error,max_absolute_score_error +faiss-1.14.1,cpu,flat,inner_product,1000000,1000,128,fp32,1,10,64,0,0,0,0.0,325.0962197780609,0.0,0.0,0.0,13079.959641397,76.45283528513971,834.8349779844284,846.3362380862236,1.0,1.0,0,0,20,320,2.16458e-06,1.15e-05 +faiss-1.14.1,cpu,flat,inner_product,1000000,1000,128,fp32,1,50,64,0,0,0,0.0,325.0962197780609,0.0,0.0,0.0,13080.880285799503,76.44745446417637,835.1001441478729,847.1395075321198,1.0,1.0,0,0,20,320,1.95558e-06,1.33e-05 +faiss-1.14.1,cpu,flat,inner_product,1000000,1000,128,fp32,1,100,64,0,0,0,0.0,325.0962197780609,0.0,0.0,0.0,13596.499814093113,73.54834065186945,867.8400814533234,881.017416715622,1.0,1.0,0,0,20,320,1.886558e-06,1.33e-05 diff --git a/09_vector_retrieval/PurplePulse/results/formal_100k15/faiss_gpu.csv b/09_vector_retrieval/PurplePulse/results/formal_100k15/faiss_gpu.csv new file mode 100644 index 00000000..e1985ca6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_100k15/faiss_gpu.csv @@ -0,0 +1,16 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,gpu_index_mib,gpu_temp_mib,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,training_iterations,training_seed,run_samples,batch_latency_samples,mean_absolute_score_error,max_absolute_score_error +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,10,64,0,0,0,261.927954852581,0.0,338.9444574713707,492.095947265625,1536.0,47.11136355996132,21226.301351419028,2.9594004154205322,2.972230315208435,1.0,1.0,0,0,100,1600,2.15207999999e-06,1.14999999994e-05 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,50,64,0,0,0,261.927954852581,0.0,338.9444574713707,492.095947265625,1536.0,48.20252262055874,20745.802203586176,3.023482859134674,3.048732876777649,1.0,1.0,0,0,100,1600,1.956738e-06,1.14999999994e-05 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,100,64,0,0,0,261.927954852581,0.0,338.9444574713707,492.095947265625,1536.0,49.90370690822601,20038.591558719705,3.1260475516319275,3.1578615307807922,1.0,1.0,0,0,100,1600,1.88528e-06,1.14999999994e-05 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,128,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,145.7934482395649,6859.01878359321,9.360350668430328,10.512225329875946,0.8795,0.5,15,2026,100,1600,0.09018460273,3.191515 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,128,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,90.35561479628086,11067.380840190588,5.7607293128967285,5.909278988838196,0.85972,0.68,15,2026,100,1600,0.11686476591,3.191515 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,128,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,100.42996548116207,9957.187530723317,6.3972026109695435,6.478957831859589,0.8491,0.7,15,2026,100,1600,0.132494336279,3.191515 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,160,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,209.93292428553104,4763.42623913481,13.52139562368393,14.626868069171906,0.9369,0.7,15,2026,100,1600,0.04626592506,1.8539982 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,160,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,113.9417802542448,8776.411933959984,7.0451050996780396,11.37205958366394,0.92312,0.8,15,2026,100,1600,0.060067846784,1.8539982 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,160,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,126.59424863755703,7899.253013168305,8.060820400714874,8.196607232093811,0.91634,0.8,15,2026,100,1600,0.069078025599,1.8539982 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,192,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,268.18819120526314,3728.724950587515,17.25468784570694,19.591324031352997,0.9722,0.7,15,2026,100,1600,0.0204540375,1.8539982 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,192,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,134.80234675109386,7418.268480492054,8.60326737165451,8.92588496208191,0.96408,0.84,15,2026,100,1600,0.026476802958,1.8539982 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,192,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,152.11867079138756,6573.815001127506,9.70180332660675,9.853780269622803,0.96127,0.88,15,2026,100,1600,0.030801589658,1.8539982 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,224,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,327.7342140674591,3051.252988173414,21.058037877082825,22.79273420572281,0.993,0.8,15,2026,100,1600,0.00526308172,0.8752346 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,224,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,152.58803740143776,6553.593696006064,9.723648428916931,9.950794279575348,0.98988,0.92,15,2026,100,1600,0.006967170764,0.8752346 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,224,100000,6923.940047621727,0.0,784.832239151001,497.984375,1536.0,177.92695373296738,5620.283936860961,11.344268918037415,11.505231261253357,0.98879,0.95,15,2026,100,1600,0.008430840391,0.8752346 diff --git a/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k10.csv b/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k10.csv new file mode 100644 index 00000000..a029865f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k10.csv @@ -0,0 +1,5 @@ +nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100000,15,0,10,142.972,6994.35,143.046,144.389,100,8.91104,8.99946,1600,0.8876,0.4,0.0854709033,3.3332901,362.111,249.23843,50.082817,497.10743,1.4063,136.9,0.177871 +256,160,100000,15,0,10,175.542,5696.66,175.499,176.839,100,10.9579,11.1168,1600,0.9409,0.6,0.042425712,3.1734657,349.508,187.561331,52.624416,497.349617,1.71734,169.143,0.183409 +256,192,100000,15,0,10,213.302,4688.19,213.26,214.714,100,13.3933,13.5356,1600,0.9734,0.7,0.0190803799,2.0794105,338.971,178.590357,50.026463,497.591805,2.00364,206.648,0.187812 +256,224,100000,15,0,10,250.392,3993.74,250.245,252.798,100,15.7794,15.9556,1600,0.9931,0.8,0.00587754848,2.0794105,348.109,179.173165,50.73613,497.833992,2.28967,243.249,0.190981 diff --git a/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k100.csv b/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k100.csv new file mode 100644 index 00000000..6cf20b1a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k100.csv @@ -0,0 +1,5 @@ +nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100000,15,0,100,149.901,6671.05,149.694,154.968,9.26218,9.39283,0.85191,0.7,0.129033640485,3.3332900999999993,100,1600,289.568,202.359561,48.876545,505.610847,1.36324,141.761,1.26084 +256,160,100000,15,0,100,189.384,5280.28,189.335,190.917,11.738,11.9248,0.9175800000000001,0.83,0.067447758554,3.1734657000000013,100,1600,321.707,176.778803,49.860607,507.96241,1.63587,181.098,1.30515 +256,192,100000,15,0,100,228.495,4376.47,228.377,229.989,14.3074,14.4852,0.96228,0.9,0.02965746239,2.0794105000000016,100,1600,321.716,176.690704,49.861534,510.313972,1.90256,219.933,1.32067 +256,224,100000,15,0,100,273.984,3649.85,273.844,275.722,17.1825,17.2907,0.9892000000000001,0.93,0.008260867503000001,2.0794105000000016,100,1600,316.19,174.228553,48.925697,512.665535,2.16944,265.061,1.36051 diff --git a/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k50.csv b/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k50.csv new file mode 100644 index 00000000..983b84aa --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_100k15/ivf_k50.csv @@ -0,0 +1,5 @@ +nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100000,15,0,50,137.089,7294.52,137.215,139.576,100,8.49632,8.70291,1600,0.86248,0.7,0.112961036,3.3332901,349.347,219.744959,51.002369,500.886726,1.43383,129.996,0.649493 +256,160,100000,15,0,50,178.399,5605.41,178.397,180.654,100,11.18,11.4261,1600,0.92482,0.8,0.0581850285,3.1734657,328.392,175.771099,48.182274,502.066414,1.73579,171.117,0.716433 +256,192,100000,15,0,50,223.565,4472.96,223.664,226.713,100,14.0604,14.5124,1600,0.9658,0.82,0.0254461265,2.0794105,310.692,176.079546,48.196609,503.246101,2.00779,215.991,0.727207 +256,224,100000,15,0,50,273.458,3656.87,273.591,276.441,100,17.2885,17.7533,1600,0.99054,0.92,0.00710551607,2.0794105,313.004,177.229013,49.465343,504.425789,2.27946,265.604,0.743718 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/bucket_major_formal.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/bucket_major_formal.csv new file mode 100644 index 00000000..96ce1d3d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/bucket_major_formal.csv @@ -0,0 +1,5 @@ +top_k,nprobe,batch_size,mode,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,scan_ms,merge_ms,recall_at_k,run_samples,speedup_percent +50,160,40,warp_compact,166.411,6009.22,166.384,169.040,6.49440,6.62154,157.329,1.02553,0.92482,100,0.0000 +50,160,40,bucket_major,143.592,6964.16,143.500,145.534,5.56659,5.62608,134.757,1.04728,0.92482,100,15.8912 +100,160,64,warp1,189.329,5281.82,189.296,190.881,11.72820,11.91420,180.957,1.30519,0.91758,100,0.0000 +100,160,64,bucket_major,185.624,5387.23,185.513,187.381,11.49960,11.54870,177.212,1.30388,0.91758,100,1.9957 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/build_threads.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/build_threads.csv new file mode 100644 index 00000000..ae47a2c6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/build_threads.csv @@ -0,0 +1,6 @@ +threads,build_ms,speedup_vs_single,bucket_min,bucket_average,bucket_max +1,67528.30,1.000,3734,3906.25,4091 +8,9179.44,7.356,3734,3906.25,4091 +16,6476.62,10.426,3734,3906.25,4091 +32,7472.99,9.036,3734,3906.25,4091 +64,10018.90,6.740,3734,3906.25,4091 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/faiss_gpu_batch40.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/faiss_gpu_batch40.csv new file mode 100644 index 00000000..0e258a18 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/faiss_gpu_batch40.csv @@ -0,0 +1,2 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,training_iterations,training_seed,build_ms,load_ms,gpu_transfer_ms,gpu_index_mib,gpu_temp_mib,average_query_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,40,256,160,100000,15,2026,0.0,311.1584857106209,417.3387736082077,497.984375,1536.0,120.07527381181717,8328.109262255002,119.6761205792427,126.95340067148209,100,4.623956978321075,5.8260709047317505,2500,0.92312,0.8,0.0600678468132019,1.8539981842041016 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_formal.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_formal.csv new file mode 100644 index 00000000..6cf20b1a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_formal.csv @@ -0,0 +1,5 @@ +nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100000,15,0,100,149.901,6671.05,149.694,154.968,9.26218,9.39283,0.85191,0.7,0.129033640485,3.3332900999999993,100,1600,289.568,202.359561,48.876545,505.610847,1.36324,141.761,1.26084 +256,160,100000,15,0,100,189.384,5280.28,189.335,190.917,11.738,11.9248,0.9175800000000001,0.83,0.067447758554,3.1734657000000013,100,1600,321.707,176.778803,49.860607,507.96241,1.63587,181.098,1.30515 +256,192,100000,15,0,100,228.495,4376.47,228.377,229.989,14.3074,14.4852,0.96228,0.9,0.02965746239,2.0794105000000016,100,1600,321.716,176.690704,49.861534,510.313972,1.90256,219.933,1.32067 +256,224,100000,15,0,100,273.984,3649.85,273.844,275.722,17.1825,17.2907,0.9892000000000001,0.93,0.008260867503000001,2.0794105000000016,100,1600,316.19,174.228553,48.925697,512.665535,2.16944,265.061,1.36051 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_heap_formal.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_heap_formal.csv new file mode 100644 index 00000000..0f7f5d3c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_heap_formal.csv @@ -0,0 +1,6 @@ +top_k,nprobe,batch_size,mode,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,scan_ms,merge_ms,recall_at_k,run_samples,speedup_percent,output_equal +100,160,64,warp1_pre_heap,188.737,5298.37,188.738,190.409,11.6936,11.8875,180.438,1.30079,0.91758,100,0.0000,true +100,160,64,warp1_heap_hole,184.311,5425.61,184.179,185.741,11.3594,11.6603,175.945,1.30443,0.91758,100,2.4015,true +100,160,64,bucket_major_heap_hole,182.091,5491.76,181.988,184.321,11.2720,11.3244,173.743,1.30183,0.91758,100,3.6500,true +50,160,40,bucket_major_pre_heap,143.912,6948.69,143.683,145.979,5.57686,5.64160,135.087,1.04701,0.92482,100,0.0000,true +50,160,40,bucket_major_heap_hole,144.077,6940.71,143.905,146.137,5.58560,5.63120,135.202,1.04671,0.92482,100,-0.1148,true diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_selection_negative.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_selection_negative.csv new file mode 100644 index 00000000..281fb5c5 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_selection_negative.csv @@ -0,0 +1,4 @@ +top_k,nprobe,batch_size,variant,baseline_qps,variant_qps,speedup_percent,baseline_average_ms,variant_average_ms,baseline_run_p99_ms,variant_run_p99_ms,baseline_scan_ms,variant_scan_ms,repeat,output_equal,accepted +100,160,64,distributed_register_topk,5483.49,5507.23,0.4329,182.366,181.579,183.618,183.087,174.026,173.294,100,true,false +100,160,64,candidate_buffer_8,5508.19,4258.85,-22.6815,181.548,234.805,182.597,239.191,173.114,225.342,10,true,false +100,160,64,warp_bitonic_sort_128,5496.78,4467.83,-18.7191,181.925,223.822,182.873,229.924,173.398,214.114,10,true,false diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_warp_ab.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_warp_ab.csv new file mode 100644 index 00000000..4ae4c393 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k100_warp_ab.csv @@ -0,0 +1,5 @@ +nprobe,recall_at_100,warp2_qps,warp1_qps,speedup +128,0.85191,6083.83,6671.05,1.0965 +160,0.91758,4732.60,5280.28,1.1157 +192,0.96228,3802.43,4376.47,1.1510 +224,0.98920,3172.27,3649.85,1.1505 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_batch_sweep.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_batch_sweep.csv new file mode 100644 index 00000000..9b975843 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_batch_sweep.csv @@ -0,0 +1,14 @@ +phase,batch_size,distance_mode,nprobe,repeat,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_50 +screen,8,warp_compact,160,10,221.035,4524.18,220.442,222.343,1.71549,1.82170,0.92482 +screen,32,warp_compact,160,10,176.682,5659.88,176.371,179.702,5.48048,5.68102,0.92482 +screen,36,warp_compact,160,10,165.588,6039.07,164.590,170.808,5.76765,6.05037,0.92482 +screen,40,warp_compact,160,10,164.127,6092.85,162.782,169.588,6.34922,6.58454,0.92482 +screen,44,warp_compact,160,10,179.752,5563.22,179.204,183.228,7.68848,7.96790,0.92482 +screen,48,warp_compact,160,10,169.576,5897.08,169.234,173.093,7.90368,8.23034,0.92482 +screen,56,warp_compact,160,10,170.855,5852.92,169.855,174.363,9.25526,9.65008,0.92482 +screen,64,warp_compact,160,10,172.609,5793.46,171.877,176.778,10.75470,11.28760,0.92482 +screen,80,warp_compact,160,10,179.003,5586.49,178.177,182.870,13.94200,14.62970,0.92482 +screen,96,warp_compact,160,10,186.759,5354.51,186.730,190.213,17.51390,18.33810,0.92482 +screen,128,warp_compact,160,10,204.907,4880.26,204.788,205.879,25.84200,26.50500,0.92482 +formal,64,warp_compact,160,100,174.301,5737.20,174.550,176.348,10.91210,11.21160,0.92482 +formal,40,warp_compact,160,100,166.116,6019.91,166.303,168.097,6.49126,6.62845,0.92482 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_bucket_major_sweep.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_bucket_major_sweep.csv new file mode 100644 index 00000000..0916ec76 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_bucket_major_sweep.csv @@ -0,0 +1,8 @@ +nprobe,recall_at_50,probe_major_qps,bucket_major_qps,speedup_percent,probe_major_scan_ms,bucket_major_scan_ms +32,0.43754,21263.50,21242.00,-0.1011,40.2078,40.2667 +64,0.64044,11394.10,12146.90,6.6069,80.2197,74.9906 +96,0.77072,9869.36,10646.10,7.8702,93.6169,86.2451 +128,0.86248,7075.94,7946.55,12.3038,133.1150,117.7040 +160,0.92482,6073.52,6968.55,14.7366,155.7970,134.7540 +192,0.96580,4834.77,5834.75,20.6831,197.5560,162.0160 +224,0.99054,4089.10,5103.30,24.8025,234.5500,186.3430 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_warp_sweep.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_warp_sweep.csv new file mode 100644 index 00000000..2c21e8a8 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/k50_warp_sweep.csv @@ -0,0 +1,5 @@ +distance_mode,batch_size,nprobe,repeat,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_50 +warp1,64,160,10,173.287,5770.77,173.122,174.171,10.71210,10.92040,0.92482 +warp2,64,160,10,172.888,5784.10,171.745,176.958,10.75100,11.21010,0.92482 +warp4,64,160,10,200.599,4985.06,199.023,204.347,12.51780,13.21600,0.92482 +warp8,64,160,10,249.540,4007.38,249.300,251.634,15.67670,16.00280,0.92482 diff --git a/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/mnist_ivf.csv b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/mnist_ivf.csv new file mode 100644 index 00000000..9b73583d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/formal_4090d_20260908/mnist_ivf.csv @@ -0,0 +1,7 @@ +nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,8,60000,15,0,10,50.5922,197659.0,50.5448,50.842,0.62016,0.686976,0.9784200000000001,0.2,0.070545293826,15.823303199999998,10,790,122.125,136.370596,17.868799,181.312263,8.89748,33.4003,0.838154 +256,16,60000,15,0,10,76.2134,131211.0,76.1832,76.4513,0.960512,1.04634,0.99471,0.5,0.016609592507,15.019317599999997,10,790,122.665,138.350996,17.955839,181.433357,9.23802,58.6378,0.842787 +256,32,60000,15,0,10,130.492,76632.9,130.419,130.974,1.64867,1.84045,0.9990899999999999,0.7,0.002338636801,5.184761099999999,10,790,117.358,134.273648,18.180096,181.675545,9.97351,111.809,0.855194 +256,64,60000,15,0,10,244.534,40894.1,243.641,252.355,3.10214,3.38707,0.9999100000000001,0.9,0.0002657260519999999,4.437892900000001,10,790,116.904,168.861066,17.852415,182.15992,11.3344,223.302,0.884618 +256,96,60000,15,0,10,383.836,26052.8,383.126,385.85,4.88115,5.24064,0.9999899999999999,0.9,2.0008849999999966e-06,0.20008849999999967,10,790,121.686,136.029167,17.821695,182.644295,12.7204,360.285,0.913581 +256,128,60000,15,0,10,561.745,17801.7,560.289,566.901,7.14714,7.54618,0.9999899999999999,0.9,2.0008849999999966e-06,0.20008849999999967,10,790,108.656,135.780264,17.857536,183.12867,14.1201,536.037,0.939718 diff --git a/09_vector_retrieval/PurplePulse/results/memory_100k/source1_compare.csv b/09_vector_retrieval/PurplePulse/results/memory_100k/source1_compare.csv new file mode 100644 index 00000000..219fcd27 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/memory_100k/source1_compare.csv @@ -0,0 +1,3 @@ +mode,nlist,nprobe,rerank_factor,session_id,source_type,average_ms,qps,batch_p50_ms,batch_p99_ms,scan_ms,merge_ms,rerank_ms,gpu_buffer_mib,recall_vs_fused,min_query_recall_vs_fused +fused,64,64,1,any,1,20.8149,48042.6,1.28106,1.29066,18.6603,0.164685,0.0,52.068733,1.0,1.0 +rerank,64,64,10,any,1,46.3539,21573.2,2.88906,2.96419,42.4594,1.10371,0.840845,56.353401,0.507,0.1 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k10.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k10.csv new file mode 100644 index 00000000..c110e883 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k10.csv @@ -0,0 +1,2 @@ +policy,execution,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,policy_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,masked,0.93,0.2,64,224,16,128.0,151.632,176.0,138.24,7233.8,8.59325,8.94669,0.9201,0.5,2.73393,0.0,130.854,0.180659,497.888924 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k100.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k100.csv new file mode 100644 index 00000000..14a3c907 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k100.csv @@ -0,0 +1,2 @@ +policy,execution,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,policy_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,masked,0.93,0.2,64,224,16,128.0,151.632,176.0,183.852,5439.17,11.4511,11.9546,0.8999299999999999,0.77,2.68297,0.0,174.929,1.30663,512.720467 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k50.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k50.csv new file mode 100644 index 00000000..27a67f0a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_formal_k50.csv @@ -0,0 +1,2 @@ +policy,execution,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,policy_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,masked,0.93,0.2,64,224,16,128.0,151.632,176.0,147.644,6773.04,4.57968,4.7751,0.90742,0.74,5.34852,0.0,135.713,1.29049,500.259163 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_grouped_formal_k100.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_grouped_formal_k100.csv new file mode 100644 index 00000000..01cc40c1 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_grouped_formal_k100.csv @@ -0,0 +1,2 @@ +policy,execution,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,policy_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,grouped,0.93,0.2,64,224,16,128.0,151.632,176.0,204.68,4885.68,12.3324,13.4839,0.8999299999999999,0.77,2.64728,0.155221,195.867,1.29021,512.720711 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_k100_t02.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_k100_t02.csv new file mode 100644 index 00000000..8194d8f2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_k100_t02.csv @@ -0,0 +1,6 @@ +policy,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,0.9,0.2,64,224,16,112.0,133.648,160.0,165.603,6038.55,10.3261,10.5847,0.86194,0.72,2.61127,156.707,1.27728,512.720467 +score_mass,0.93,0.2,64,224,16,128.0,151.632,176.0,184.14,5430.65,11.4747,11.8041,0.8999299999999999,0.77,2.65982,175.136,1.30286,512.720467 +score_mass,0.95,0.2,64,224,16,144.0,166.736,192.0,201.136,4971.77,12.5503,13.6421,0.9265399999999999,0.83,2.69391,192.094,1.3114,512.720467 +score_mass,0.97,0.2,64,224,16,160.0,186.096,208.0,225.922,4426.3,14.1753,14.9012,0.95353,0.87,2.73035,216.811,1.32234,512.720467 +score_mass,0.99,0.2,64,224,16,208.0,210.128,224.0,247.336,4043.08,15.4013,16.8479,0.97889,0.92,2.83173,238.087,1.37412,512.720467 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_k10_t02.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_k10_t02.csv new file mode 100644 index 00000000..ac167a5b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_k10_t02.csv @@ -0,0 +1,8 @@ +policy,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,0.8,0.2,64,224,16,80.0,92.72,112.0,85.1168,11748.6,5.18259,5.38298,0.7753,0.3,2.61823,77.8633,0.178816,497.888924 +score_mass,0.85,0.2,64,224,16,96.0,110.544,144.0,101.222,9879.26,6.22883,6.37872,0.8275,0.3,2.62646,93.9646,0.178214,497.888924 +score_mass,0.9,0.2,64,224,16,112.0,133.648,160.0,121.367,8239.49,7.51754,7.72566,0.8837,0.4,2.69535,114.027,0.179782,497.888924 +score_mass,0.93,0.2,64,224,16,128.0,151.632,176.0,137.663,7264.12,8.53437,8.85264,0.9201,0.5,2.73062,130.283,0.182208,497.888924 +score_mass,0.95,0.2,64,224,16,144.0,166.736,192.0,150.562,6641.78,9.35613,9.99891,0.9416,0.6,2.77469,143.094,0.182662,497.888924 +score_mass,0.97,0.2,64,224,16,160.0,186.096,208.0,168.812,5923.76,10.529,10.9825,0.9653999999999999,0.7,2.83329,161.33,0.186131,497.888924 +score_mass,0.99,0.2,64,224,16,208.0,210.128,224.0,188.458,5306.22,11.7034,12.3358,0.986,0.8,2.92934,180.494,0.189094,497.888924 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_k50_t02.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_k50_t02.csv new file mode 100644 index 00000000..7cafd04a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_k50_t02.csv @@ -0,0 +1,6 @@ +policy,target_mass,temperature,min_nprobe,max_nprobe,step,actual_nprobe_min,actual_nprobe_average,actual_nprobe_max,average_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,center_ms,scan_ms,merge_ms,gpu_buffer_mib +score_mass,0.9,0.2,64,224,16,112.0,133.648,160.0,133.11,7512.6,4.09942,4.43338,0.87076,0.68,5.20479,121.363,1.22873,500.259163 +score_mass,0.93,0.2,64,224,16,128.0,151.632,176.0,148.125,6751.06,4.59411,4.68419,0.90742,0.74,5.34125,136.162,1.28753,500.259163 +score_mass,0.95,0.2,64,224,16,144.0,166.736,192.0,172.805,5786.88,5.18554,5.90125,0.93202,0.8,5.34197,160.811,1.32697,500.259163 +score_mass,0.97,0.2,64,224,16,160.0,186.096,208.0,193.919,5156.8,6.06669,6.15334,0.95636,0.84,5.41334,181.8,1.35101,500.259163 +score_mass,0.99,0.2,64,224,16,208.0,210.128,224.0,205.788,4859.38,6.43651,6.56304,0.98078,0.9,5.60418,193.437,1.39775,500.259163 diff --git a/09_vector_retrieval/PurplePulse/results/million/adaptive_vs_fixed_n152.csv b/09_vector_retrieval/PurplePulse/results/million/adaptive_vs_fixed_n152.csv new file mode 100644 index 00000000..886506b1 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/adaptive_vs_fixed_n152.csv @@ -0,0 +1,7 @@ +top_k,policy,configured_max_nprobe,actual_nprobe_average,average_ms,qps,batch_p99_ms,recall_at_k,min_query_recall,gpu_buffer_mib +10,fixed,152,152.000,136.843,7307.65,8.69318,0.92120,0.50,497.289070 +10,score_mass_masked,224,151.632,138.240,7233.80,8.94669,0.92010,0.50,497.888924 +50,fixed,152,152.000,143.793,6954.42,4.57341,0.90874,0.76,498.904549 +50,score_mass_masked,224,151.632,147.644,6773.04,4.77510,0.90742,0.74,500.259163 +100,fixed,152,152.000,177.226,5642.53,11.5828,0.90179,0.80,507.374519 +100,score_mass_masked,224,151.632,183.852,5439.17,11.9546,0.89993,0.77,512.720467 diff --git a/09_vector_retrieval/PurplePulse/results/million/faiss_cpu_flat.csv b/09_vector_retrieval/PurplePulse/results/million/faiss_cpu_flat.csv new file mode 100644 index 00000000..79bcf46c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/faiss_cpu_flat.csv @@ -0,0 +1,4 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall +faiss-1.14.1,cpu,flat,inner_product,1000000,1000,128,fp32,1,10,64,0,0,0,0.0,287.047304213047,0.0,13172.113172709942,75.91796296374113,840.2729630470276,852.7840971946716,1.0,1.0 +faiss-1.14.1,cpu,flat,inner_product,1000000,1000,128,fp32,1,50,64,0,0,0,0.0,287.047304213047,0.0,13208.435845871767,75.70919158550822,842.0012220740318,853.2666340470314,1.0,1.0 +faiss-1.14.1,cpu,flat,inner_product,1000000,1000,128,fp32,1,100,64,0,0,0,0.0,287.047304213047,0.0,13687.985599040985,73.05676885502149,873.8687261939049,878.7985518574715,1.0,1.0 diff --git a/09_vector_retrieval/PurplePulse/results/million/faiss_cpu_ivf_rep.csv b/09_vector_retrieval/PurplePulse/results/million/faiss_cpu_ivf_rep.csv new file mode 100644 index 00000000..27133436 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/faiss_cpu_ivf_rep.csv @@ -0,0 +1,2 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall +faiss-1.14.1,cpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,128,100000,0.0,291.03782773017883,0.0,22949.28689301014,43.574338700022025,1464.3422737717628,1503.8493275642395,0.8795000000000001,0.5 diff --git a/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal.csv b/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal.csv new file mode 100644 index 00000000..3e191318 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal.csv @@ -0,0 +1,16 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,10,64,0,0,0,0.0,306.81489408016205,243.20194125175476,48.33947420120239,20687.026835205543,3.070421516895294,3.1209364533424377,1.0,1.0 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,50,64,0,0,0,0.0,306.81489408016205,243.20194125175476,48.48332405090332,20625.648500298495,3.0353665351867676,3.0637606978416443,1.0,1.0 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,100,64,0,0,0,0.0,306.81489408016205,243.20194125175476,50.514741241931915,19796.20157234236,3.131583333015442,4.262790083885193,1.0,1.0 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,128,100000,0.0,301.6926869750023,408.60651433467865,147.6534053683281,6772.617248518276,9.405627846717834,11.32049411535263,0.8795000000000001,0.5 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,128,100000,0.0,301.6926869750023,408.60651433467865,91.0657986998558,10981.07098687955,5.769222974777222,7.686242461204529,0.85972,0.68 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,128,100000,0.0,301.6926869750023,408.60651433467865,102.06692963838577,9797.492719168811,6.41188770532608,11.775985360145569,0.8490999999999999,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,160,100000,0.0,301.6926869750023,408.60651433467865,209.44822281599045,4774.449678088433,13.43446969985962,18.21625977754593,0.9369000000000001,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,160,100000,0.0,301.6926869750023,408.60651433467865,114.03494030237198,8769.242105519825,7.04357773065567,12.079395353794098,0.92312,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,160,100000,0.0,301.6926869750023,408.60651433467865,128.0077800154686,7812.025174400798,8.069895207881927,13.705261051654816,0.9163399999999999,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,192,100000,0.0,301.6926869750023,408.60651433467865,265.83249419927597,3761.7673603527574,17.10372418165207,18.838346004486084,0.9722000000000001,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,192,100000,0.0,301.6926869750023,408.60651433467865,136.0035389661789,7352.749844610133,8.596211671829224,14.135561883449554,0.96408,0.84 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,192,100000,0.0,301.6926869750023,408.60651433467865,152.1145612001419,6573.9926020906605,9.69243049621582,9.861893951892853,0.96127,0.88 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,224,100000,0.0,301.6926869750023,408.60651433467865,327.99044251441956,3048.8693278190162,21.03523164987564,23.185282945632935,0.993,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,224,100000,0.0,301.6926869750023,408.60651433467865,152.65787541866302,6550.5955539962015,9.729109704494476,9.92652028799057,0.9898800000000001,0.92 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,224,100000,0.0,301.6926869750023,408.60651433467865,178.12331765890121,5614.088111220557,11.344507336616516,11.540621519088745,0.9887900000000001,0.95 diff --git a/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal_v2.csv b/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal_v2.csv new file mode 100644 index 00000000..0e6d4825 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal_v2.csv @@ -0,0 +1,16 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,10,64,0,0,0,0.0,282.5198844075203,244.08532679080963,48.60575199127197,20573.69671349942,3.0652806162834167,3.078766167163849,1.0,1.0 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,50,64,0,0,0,0.0,282.5198844075203,244.08532679080963,48.42245727777481,20651.574831560338,3.0355453491210938,3.049500286579132,1.0,1.0 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,100,64,0,0,0,0.0,282.5198844075203,244.08532679080963,50.34593939781189,19862.575054930083,3.135010600090027,4.179045557975769,1.0,1.0 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,128,100000,0.0,297.7650985121727,769.0969333052635,147.0141589641571,6802.065916955698,9.391851723194122,12.21979409456253,0.8795000000000001,0.5 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,128,100000,0.0,297.7650985121727,769.0969333052635,90.75252562761307,11018.977081732392,5.763053894042969,6.491273641586304,0.85972,0.68 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,128,100000,0.0,297.7650985121727,769.0969333052635,102.74720638990402,9732.624712006384,6.406337022781372,16.36991649866104,0.8490999999999999,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,160,100000,0.0,297.7650985121727,769.0969333052635,210.92544347047806,4741.0117221821265,13.606108725070953,14.795109629631042,0.9369000000000001,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,160,100000,0.0,297.7650985121727,769.0969333052635,114.68802243471146,8719.306330085783,7.03873485326767,12.096747756004333,0.92312,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,160,100000,0.0,297.7650985121727,769.0969333052635,128.31582576036453,7793.270970858606,8.082374930381775,14.721490442752838,0.9163399999999999,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,192,100000,0.0,297.7650985121727,769.0969333052635,266.3765713572502,3754.0839079982475,17.110303044319153,19.420921802520752,0.9722000000000001,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,192,100000,0.0,297.7650985121727,769.0969333052635,134.9662497639656,7409.259735295604,8.605390787124634,9.006954729557037,0.96408,0.84 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,192,100000,0.0,297.7650985121727,769.0969333052635,152.0623043179512,6576.2517836706775,9.698398411273956,9.813271462917328,0.96127,0.88 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,224,100000,0.0,297.7650985121727,769.0969333052635,327.7781292796135,3050.844185967462,21.011285483837128,23.136727511882782,0.993,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,224,100000,0.0,297.7650985121727,769.0969333052635,154.548217356205,6470.472562586635,9.722404181957245,19.09337192773819,0.9898800000000001,0.92 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,224,100000,0.0,297.7650985121727,769.0969333052635,178.02205979824066,5617.281370260174,11.34926825761795,11.463411152362823,0.9887900000000001,0.95 diff --git a/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal_v3.csv b/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal_v3.csv new file mode 100644 index 00000000..fb3624fb --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/faiss_gpu_formal_v3.csv @@ -0,0 +1,16 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,gpu_index_mib,gpu_temp_mib,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,10,64,0,0,0,0.0,285.8908995985985,241.17807298898697,492.095947265625,1536.0,48.58236759901047,20583.599553109638,3.072679042816162,3.2324790954589844,1.0,1.0 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,50,64,0,0,0,0.0,285.8908995985985,241.17807298898697,492.095947265625,1536.0,48.51717799901962,20611.25649188019,3.0357763171195984,3.1501129269599915,1.0,1.0 +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,1,100,64,0,0,0,0.0,285.8908995985985,241.17807298898697,492.095947265625,1536.0,50.23513734340668,19906.385308833025,3.1277909874916077,3.754034638404846,1.0,1.0 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,128,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,145.5121487379074,6872.278422615924,9.345516562461853,10.649532079696655,0.8795000000000001,0.5 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,128,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,90.37265181541443,11065.294421618762,5.753464996814728,5.99844753742218,0.85972,0.68 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,128,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,101.29805654287338,9871.857705155084,6.404206156730652,9.461544454097748,0.8490999999999999,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,160,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,210.255828499794,4756.110720616621,13.41235637664795,19.407659769058228,0.9369000000000001,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,160,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,114.66595083475113,8720.98467522528,7.035769522190094,11.133134365081787,0.92312,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,160,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,126.64697766304016,7895.96418684876,8.061528205871582,8.296430110931396,0.9163399999999999,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,192,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,267.04441756010056,3744.69539238708,17.224609851837158,19.959919154644012,0.9722000000000001,0.7 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,192,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,134.86263751983643,7414.952120100082,8.609533309936523,8.816443383693695,0.96408,0.84 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,192,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,152.62544453144073,6551.987468865329,9.692922234535217,12.389101088047028,0.96127,0.88 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,10,64,256,224,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,327.8968617320061,3049.7394659949864,20.965807139873505,22.999733686447144,0.993,0.8 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,50,64,256,224,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,152.5898739695549,6553.5148171072115,9.715430438518524,9.946219623088837,0.9898800000000001,0.92 +faiss-1.14.1,gpu,ivf_flat,inner_product,1000000,1000,128,fp32,1,100,64,256,224,100000,0.0,286.5690514445305,414.5883098244667,497.984375,1536.0,177.9081165790558,5620.879020185889,11.339344084262848,11.475272476673126,0.9887900000000001,0.95 diff --git a/09_vector_retrieval/PurplePulse/results/million/faiss_smoke.csv b/09_vector_retrieval/PurplePulse/results/million/faiss_smoke.csv new file mode 100644 index 00000000..4e618673 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/faiss_smoke.csv @@ -0,0 +1,2 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,top_k,batch_size,nlist,nprobe,train_samples,build_ms,load_ms,gpu_transfer_ms,average_query_ms,qps,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall +faiss-1.14.1,gpu,flat,inner_product,1000000,1000,128,fp32,10,64,0,0,0,274.1727828979492,0.0,251.55793875455856,49.115635454654694,20360.115281888913,3.0778199434280396,3.120236098766327,1.0,1.0 diff --git a/09_vector_retrieval/PurplePulse/results/million/fixed_k100_matched.csv b/09_vector_retrieval/PurplePulse/results/million/fixed_k100_matched.csv new file mode 100644 index 00000000..dc15ccc9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/fixed_k100_matched.csv @@ -0,0 +1,6 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,134,100,158.268,6318.4,158.068,158.738,9.8616,10.0134,0.86378,0.74,344.942,208.431089,48.417759,506.051765,1.41524,150.679,1.26942 +256,152,100,176.19,5675.69,176.228,176.272,10.988,11.2054,0.90179,0.8,344.017,177.436624,50.082817,507.374519,1.5794,168.389,1.29674 +256,167,100,189.8,5268.7,190.014,190.136,11.8462,12.0964,0.92743,0.84,344.508,187.914744,50.082817,508.476814,1.71052,181.834,1.30818 +256,186,100,217.75,4592.41,217.776,218.191,13.6669,13.929,0.9538099999999999,0.88,336.696,181.442069,49.500095,509.873055,1.8641,209.622,1.32333 +256,210,100,241.183,4146.22,239.757,244.452,15.0537,15.7287,0.97908,0.92,344.602,178.693661,50.06739,511.636726,2.09754,232.831,1.3568 diff --git a/09_vector_retrieval/PurplePulse/results/million/fixed_k10_matched.csv b/09_vector_retrieval/PurplePulse/results/million/fixed_k10_matched.csv new file mode 100644 index 00000000..a85b50ab --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/fixed_k10_matched.csv @@ -0,0 +1,8 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,93,10,83.1175,12031.2,83.2045,83.3808,5.05821,5.22131,0.7783,0.3,312.033,216.239709,50.641918,496.842537,1.10461,77.4891,0.172749 +256,111,10,100.201,9979.94,100.283,100.514,6.16221,6.3735,0.8274,0.4,307.664,213.145584,49.911808,496.978767,1.25535,94.4129,0.175782 +256,134,10,120.456,8301.77,120.33,120.927,7.4625,7.63642,0.8841,0.4,309.589,178.642062,50.307072,497.15284,1.45938,114.445,0.176813 +256,152,10,137.41,7277.47,137.476,137.653,8.54922,8.78115,0.9212,0.5,306.14,178.288343,50.642944,497.28907,1.60839,131.26,0.178214 +256,167,10,149.536,6687.33,149.459,150.496,9.30378,9.62016,0.9424,0.5,309.172,178.600067,50.193409,497.402596,1.75187,143.246,0.182848 +256,186,10,168.075,5949.74,167.111,171.99,10.4939,11.012,0.9652999999999999,0.7,306.003,182.767851,49.24416,497.546394,1.92886,161.6,0.18425 +256,210,10,187.992,5319.39,187.114,192.062,11.6859,12.2507,0.9863,0.8,308.577,182.787988,50.119743,497.728035,2.1658,180.956,0.187187 diff --git a/09_vector_retrieval/PurplePulse/results/million/fixed_k50_matched.csv b/09_vector_retrieval/PurplePulse/results/million/fixed_k50_matched.csv new file mode 100644 index 00000000..f05dc6f4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/fixed_k50_matched.csv @@ -0,0 +1,6 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,134,50,131.16,7624.27,129.903,133.805,4.01434,4.20758,0.87142,0.72,322.803,204.905654,48.527359,498.572762,2.90965,121.589,1.24021 +256,152,50,143.03,6991.56,143.109,143.371,4.4273,4.52742,0.90874,0.76,341.521,175.386222,48.854015,498.904549,3.19151,133.51,1.25125 +256,167,50,156.838,6376.02,156.572,157.382,4.88458,4.98432,0.9325800000000001,0.8,338.704,175.705726,48.726082,499.181038,3.46049,146.904,1.36697 +256,186,50,189.449,5278.46,189.428,189.518,5.92461,6.01203,0.95666,0.86,341.27,178.056469,49.153023,499.531258,3.70864,179.291,1.36316 +256,210,50,202.336,4942.26,202.292,202.526,6.32573,6.4479,0.9809399999999999,0.9,339.97,175.408315,48.654335,499.97364,4.17606,191.626,1.38848 diff --git a/09_vector_retrieval/PurplePulse/results/million/optimized_v1_batch_sweep.csv b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_batch_sweep.csv new file mode 100644 index 00000000..9b5b0ff3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_batch_sweep.csv @@ -0,0 +1,14 @@ +top_k,nprobe,batch_size,average_ms,qps,batch_p50_ms,batch_p99_ms +10,160,8,163.117,6130.58,1.26016,1.28992 +10,160,16,150.854,6628.93,2.33667,2.38550 +10,160,32,146.206,6839.68,4.53709,4.65718 +10,160,64,143.411,6972.97,8.89664,9.39501 +10,160,128,151.117,6617.41,18.7522,20.2491 +50,160,8,208.800,4789.27,1.61629,1.71613 +50,160,32,150.702,6635.63,4.66973,4.87680 +50,160,64,156.270,6399.20,9.66397,11.6425 +50,160,128,186.526,5361.18,23.4392,24.0252 +100,160,8,234.454,4265.24,1.80531,2.00845 +100,160,32,188.907,5293.60,5.83405,6.11971 +100,160,64,186.597,5359.15,11.5481,12.1629 +100,160,128,187.932,5321.08,23.2395,24.5809 diff --git a/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k10.csv b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k10.csv new file mode 100644 index 00000000..9d7c9b84 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k10.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,10,114.492,8734.26,114.611,114.852,7.06685,7.2783,0.8716,0.4,313.585,201.295587,49.244289,497.10743,1.40868,108.51,0.177389 +256,160,10,142.813,7002.15,142.858,142.944,8.85901,9.36838,0.9332,0.5,342.995,182.53147,50.336769,497.349617,1.67885,136.636,0.178406 +256,192,10,172.767,5788.13,171.995,177.516,10.7552,11.4112,0.9708,0.7,339.737,177.759528,49.464321,497.591805,1.9772,166.288,0.182464 +256,224,10,199.941,5001.48,197.428,204.982,12.4952,13.2546,0.9929,0.8,349.578,187.077321,52.121601,497.833992,2.284,192.958,0.186739 diff --git a/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k100.csv b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k100.csv new file mode 100644 index 00000000..b52ff9de --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k100.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100,145.736,6861.72,145.666,146.163,9.03696,9.2657,0.84957,0.73,312.923,177.967054,50.384895,505.610847,1.38316,138.097,1.2993 +256,160,100,186.157,5371.81,184.604,191.066,11.5385,12.1275,0.9162899999999999,0.83,320.683,194.827955,65.00045,507.96241,1.67551,178.317,1.34738 +256,192,100,226.505,4414.92,225.136,230.609,14.1054,14.7119,0.96109,0.9,347.076,186.380337,48.910336,510.313972,1.95592,218.348,1.36909 +256,224,100,266.671,3749.94,265.185,271.297,16.6592,17.4817,0.98901,0.94,338.758,179.058335,50.358273,512.665535,2.23116,258.1,1.40443 diff --git a/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k50.csv b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k50.csv new file mode 100644 index 00000000..b32c6728 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k50.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,50,124.367,8040.72,124.425,124.588,7.71194,7.91891,0.85764,0.68,321.321,174.418505,49.756161,500.886726,1.39822,117.718,0.63879 +256,160,50,155.774,6419.56,155.123,158.704,9.6673,10.2908,0.9224399999999999,0.8,316.876,181.233274,48.408577,502.066414,1.68376,148.768,0.707846 +256,192,50,198.084,5048.36,196.159,202.343,12.3866,13.1108,0.96362,0.86,309.553,172.6877,49.701889,503.246101,1.95297,190.765,0.710074 +256,224,50,246.481,4057.12,247.034,249.947,15.5024,15.9968,0.99036,0.92,308.338,177.079955,50.042881,504.425789,2.20839,238.829,0.722426 diff --git a/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k50_b32.csv b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k50_b32.csv new file mode 100644 index 00000000..5e2e53c0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/optimized_v1_k50_b32.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,50,124.917,8005.3,124.63,126.174,3.83552,4.02794,0.85764,0.68,313.973,198.869566,48.350239,498.462166,2.72706,115.871,1.23165 +256,160,50,149.803,6675.43,149.619,151.027,4.64115,4.85293,0.9224399999999999,0.8,314.481,185.112281,53.036034,499.05201,3.31795,140.0,1.36364 +256,192,50,192.869,5184.87,191.486,196.276,5.99981,6.26022,0.96362,0.86,306.071,172.908014,49.908737,499.641853,3.85896,182.466,1.3929 +256,224,50,215.971,4630.24,213.406,220.59,6.712,7.03693,0.99036,0.92,304.8,180.173094,49.196033,500.231697,4.48155,204.91,1.44743 diff --git a/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k10.csv b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k10.csv new file mode 100644 index 00000000..5133f5a7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k10.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,recall_at_k,min_query_recall,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,10,163.146,6129.47,0.8716,0.4,497.10743,1.38557,157.214,0.174054 +256,160,10,208.906,4786.85,0.9332,0.5,497.349617,1.65597,202.667,0.176768 +256,192,10,254.128,3935.02,0.9708,0.7,497.591805,1.94223,247.62,0.181888 +256,224,10,302.84,3302.07,0.9929,0.8,497.833992,2.19123,296.028,0.182029 diff --git a/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k100.csv b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k100.csv new file mode 100644 index 00000000..12f04801 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k100.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,recall_at_k,min_query_recall,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100,256.457,3899.29,0.84957,0.73,505.610847,1.4057,248.785,1.31703 +256,160,100,321.382,3111.56,0.9162899999999999,0.83,507.96241,1.67763,313.296,1.34572 +256,192,100,390.036,2563.86,0.96109,0.9,510.313972,1.95847,381.672,1.36621 +256,224,100,456.162,2192.2,0.98901,0.94,512.665535,2.23994,447.389,1.40833 diff --git a/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k100_v2.csv b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k100_v2.csv new file mode 100644 index 00000000..46886e81 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k100_v2.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,100,255.924,3907.4,255.738,259.037,16.0383,16.4815,0.84957,0.73,333.052,180.812547,54.655998,505.610847,1.40155,248.179,1.31416 +256,160,100,321.41,3111.29,320.81,324.92,20.2298,20.6631,0.9162899999999999,0.83,336.804,180.254384,49.406975,507.96241,1.68063,313.259,1.34637 +256,192,100,389.844,2565.13,391.768,392.87,24.5921,25.0963,0.96109,0.9,331.437,175.987579,47.669247,510.313972,1.96227,381.331,1.37202 +256,224,100,456.191,2192.07,455.981,459.528,28.8079,30.7119,0.98901,0.94,331.743,175.22775,48.033791,512.665535,2.23484,447.087,1.40794 diff --git a/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k10_v2.csv b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k10_v2.csv new file mode 100644 index 00000000..962acdd5 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k10_v2.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,10,162.302,6161.37,161.765,165.397,10.1036,10.8613,0.8716,0.4,332.034,203.129712,48.421825,497.10743,1.37898,156.38,0.173862 +256,160,10,209.596,4771.09,206.716,215.386,13.0472,14.4953,0.9332,0.5,330.143,174.002704,48.356354,497.349617,1.65799,203.376,0.176749 +256,192,10,253.267,3948.4,252.499,260.228,15.8918,17.18,0.9708,0.7,328.531,175.200326,49.212418,497.591805,1.9384,246.704,0.179731 +256,224,10,301.739,3314.12,300.145,307.802,19.0054,19.9611,0.9929,0.8,341.581,179.865042,49.264641,497.833992,2.19372,294.926,0.181549 diff --git a/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k50.csv b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k50.csv new file mode 100644 index 00000000..726fc8c0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k50.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,recall_at_k,min_query_recall,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,50,204.712,4884.91,0.85764,0.68,500.886726,1.39819,198.059,0.638522 +256,160,50,258.077,3874.82,0.9224399999999999,0.8,502.066414,1.67948,250.966,0.702528 +256,192,50,315.27,3171.89,0.96362,0.86,503.246101,1.94605,307.915,0.705555 +256,224,50,378.974,2638.7,0.99036,0.92,504.425789,2.21338,371.29,0.725606 diff --git a/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k50_v2.csv b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k50_v2.csv new file mode 100644 index 00000000..5ec01024 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/purplepulse_faiss_compare_k50_v2.csv @@ -0,0 +1,5 @@ +nlist,nprobe,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,128,50,204.374,4892.99,202.363,208.238,12.7027,13.2948,0.85764,0.68,330.555,173.378368,47.857822,500.886726,1.39581,197.712,0.635014 +256,160,50,257.772,3879.4,256.8,261.436,16.1263,17.0315,0.9224399999999999,0.8,334.215,177.807709,49.944576,502.066414,1.67325,250.726,0.701837 +256,192,50,315.139,3173.2,313.446,319.739,19.7917,21.9328,0.96362,0.86,331.813,175.237001,48.2304,503.246101,1.94225,307.562,0.706618 +256,224,50,377.72,2647.47,377.203,379.404,23.8011,24.621,0.99036,0.92,334.021,177.086034,49.295296,504.425789,2.21521,370.053,0.726291 diff --git a/09_vector_retrieval/PurplePulse/results/million/sweep_smoke.csv b/09_vector_retrieval/PurplePulse/results/million/sweep_smoke.csv new file mode 100644 index 00000000..f6868835 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/million/sweep_smoke.csv @@ -0,0 +1,3 @@ +nlist,nprobe,top_k,average_ms,qps,recall_at_k,min_query_recall,gpu_buffer_mib,center_ms,scan_ms,merge_ms +256,64,10,94.8201,10546.3,0.6613,0.2,496.183968,3.40621,84.5987,0.9104 +256,128,10,159.119,6284.6,0.8716,0.4,496.305061,5.37437,146.86,0.964864 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/build.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/build.csv new file mode 100644 index 00000000..703131ab --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/build.csv @@ -0,0 +1,2 @@ +dataset,nlist,training_iterations,training_samples,threads,build_ms,save_ms,minimum_bucket,average_bucket,maximum_bucket,empty_buckets,index_bytes +sift1m,1024,15,100000,16,25467.3,286.4,188,976.562,3684,0,520532520 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/dataset_manifest.json b/09_vector_retrieval/PurplePulse/results/real/sift1m/dataset_manifest.json new file mode 100644 index 00000000..8131a38b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/dataset_manifest.json @@ -0,0 +1,58 @@ +{ + "dataset": "SIFT1M", + "source_url": "ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz", + "metric": "l2", + "database_rows": 1000000, + "query_rows": 10000, + "dim": 128, + "groundtruth_k": 100, + "inputs": { + "base": { + "path": "/data/real-datasets/raw/sift1m/extracted/sift/sift_base.fvecs", + "kind": "fvecs", + "rows": 1000000, + "dim": 128, + "bytes": 516000000, + "sha256": "21f66e2975057b5728ba56de1c825bac4f4d89d596609ae985741c6242631816" + }, + "queries": { + "path": "/data/real-datasets/raw/sift1m/extracted/sift/sift_query.fvecs", + "kind": "fvecs", + "rows": 10000, + "dim": 128, + "bytes": 5160000, + "sha256": "f7fc9be140accdfd64116c2fa2365ecdb69b8f084970c6b0532db5ff79ac8fdc" + }, + "groundtruth": { + "path": "/data/real-datasets/raw/sift1m/extracted/sift/sift_groundtruth.ivecs", + "kind": "ivecs", + "rows": 10000, + "dim": 100, + "bytes": 4040000, + "sha256": "2b71de0a8d5a83e6a84eec3e23fb8b611d8801dd9b3a6cd62f070ab65ea65f4f" + } + }, + "outputs": { + "database": { + "path": "data/real/sift1m/database.bin", + "bytes": 512000028, + "sha256": "c8e127794ab289f0e45c28440be05085b8961ca52907676dd313638d6fd4f861" + }, + "queries": { + "path": "data/real/sift1m/queries.bin", + "bytes": 5120024, + "sha256": "d75631c98e58a0f3e103db6490fd110be7a0881ad738ef979a4c512aebe2f032" + }, + "groundtruth": { + "path": "data/real/sift1m/groundtruth.ivecs", + "bytes": 4040000, + "sha256": "2b71de0a8d5a83e6a84eec3e23fb8b611d8801dd9b3a6cd62f070ab65ea65f4f" + } + }, + "archive": { + "path": "/data/real-datasets/raw/sift1m/sift.tar.gz", + "bytes": 168280445, + "md5": "b23d1b3b2ee8469d819b61ca900ef0ed", + "sha256": "92f1270c5e3a0cb46b89983e72b0511e4df065c31a9fa0276d8c9b1fca5bc81a" + } +} diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/environment.json b/09_vector_retrieval/PurplePulse/results/real/sift1m/environment.json new file mode 100644 index 00000000..7025574d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/environment.json @@ -0,0 +1,26 @@ +{ + "dataset": "sift1m", + "timestamp_utc": "2026-09-10T07:55:09.404971+00:00", + "git_commit": "fatal: not a git repository (or any parent up to mount point /)\nStopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", + "gpu": "NVIDIA GeForce RTX 4090 D, 570.124.06, 24564 MiB", + "nvcc": "nvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2025 NVIDIA Corporation\nBuilt on Wed_Jan_15_19:20:09_PST_2025\nCuda compilation tools, release 12.8, V12.8.61\nBuild cuda_12.8.r12.8/compiler.35404655_0", + "python": "3.12.3 (main, Nov 6 2024, 18:32:19) [GCC 13.2.0]", + "parameters": { + "dataset": "sift1m", + "project_root": "/data/purplepulse-work/PurplePulse", + "data_root": "data/real", + "results_root": "results/real", + "build_dir": "build", + "nlist": 1024, + "nprobes": "32,64,128,160,192,224", + "training_samples": 100000, + "iterations": 15, + "threads": 16, + "batch_size": 64, + "warmup": 1, + "repeat": 5, + "skip_index_build": false, + "skip_faiss": false, + "maximum_partition_recall_loss": 0.0001 + } +} diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/exact_gpu.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/exact_gpu.csv new file mode 100644 index 00000000..cb1d8c7c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/exact_gpu.csv @@ -0,0 +1,4 @@ +implementation,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,gpu_initialization_ms,database_h2d_ms,gpu_buffer_mib,query_h2d_ms,distance_and_local_topk_ms,final_topk_ms,result_d2h_ms,result_path +WarpFusion Exact fused,10,64,1420.77,7038.42,1420.44,1423.89,5,9.06992,9.17027,785,205.322,48.4529,488.437,3.58849,1409.55,1.7796,3.25878,/data/purplepulse-work/PurplePulse/results/real/sift1m/exact_outputs/exact_k10.txt +WarpFusion Exact fused,50,64,1578.08,6336.81,1577.67,1580.61,5,10.068,10.1572,785,172.465,47.9695,488.935,2.7779,1558.6,7.83877,3.75766,/data/purplepulse-work/PurplePulse/results/real/sift1m/exact_outputs/exact_k50.txt +WarpFusion Exact fused,100,64,1778.64,5622.28,1778.71,1780.42,5,11.3194,11.6274,785,177.354,48.4283,489.558,2.85445,1743.23,17.8673,5.33884,/data/purplepulse-work/PurplePulse/results/real/sift1m/exact_outputs/exact_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/faiss_gpu.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/faiss_gpu.csv new file mode 100644 index 00000000..2cc8ada0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/faiss_gpu.csv @@ -0,0 +1,22 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,training_iterations,training_seed,build_ms,load_ms,gpu_transfer_ms,gpu_index_mib,gpu_temp_mib,average_query_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error +faiss-1.14.1,gpu,flat,l2,1000000,10000,128,fp32,1,10,64,0,0,0,0,0,246.00856751203537,0.0,240.90760201215744,492.095947265625,1536.0,482.69662857055664,20716.94602386949,482.70057141780853,482.7524647116661,5,3.072179853916168,3.0867978930473328,785,0.99955,0.9,0.0,0.0 +faiss-1.14.1,gpu,flat,l2,1000000,10000,128,fp32,1,50,64,0,0,0,0,0,246.00856751203537,0.0,240.90760201215744,492.095947265625,1536.0,493.0823802947998,20280.586773393297,492.9155260324478,494.4283291697502,5,3.1305477023124695,3.1549036502838135,785,0.999776,0.98,0.0,0.0 +faiss-1.14.1,gpu,flat,l2,1000000,10000,128,fp32,1,100,64,0,0,0,0,0,246.00856751203537,0.0,240.90760201215744,492.095947265625,1536.0,507.0580542087555,19721.607648269415,506.7726969718933,508.07879865169525,5,3.217831254005432,3.245815634727478,785,0.999877,0.99,0.0,0.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,10,64,1024,32,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,145.0256809592247,68953.30491715872,145.078606903553,145.1914831995964,5,0.9266659617424011,1.011282205581665,785,0.97762,0.5,83.89023,35511.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,50,64,1024,32,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,151.96136981248856,65806.19806428051,151.97588503360748,152.06657350063324,5,0.9674057364463806,1.064293086528778,785,0.96454,0.54,151.144254,35511.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,100,64,1024,32,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,164.1660898923874,60913.91959542379,162.75090724229813,166.51777923107147,5,1.034475862979889,1.2471377849578857,785,0.955319,0.56,204.169815,35511.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,10,64,1024,64,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,285.0419953465462,35082.549811098106,285.0293591618538,285.17842292785645,5,1.823335886001587,1.9802674651145935,785,0.99511,0.7,16.27643,9002.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,50,64,1024,64,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,292.5386443734169,34183.51794655647,292.5541028380394,292.60001331567764,5,1.8706843256950378,2.030685544013977,785,0.992236,0.76,29.796736,9002.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,100,64,1024,64,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,305.8733895421028,32693.26571680575,305.97837269306183,306.770958006382,5,1.952625811100006,2.138972282409668,785,0.989512,0.78,42.427,9002.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,10,64,1024,128,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,579.1918680071831,17265.435777623836,579.1034325957298,579.5566886663437,5,3.7212222814559937,4.00301069021225,785,0.9989299999999999,0.8,1.32864,5480.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,50,64,1024,128,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,588.677728176117,16987.22326557641,588.556744158268,590.2841538190842,5,3.773339092731476,4.068478941917419,785,0.9990460000000001,0.88,2.733834,5480.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,100,64,1024,128,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,605.4432585835457,16516.824422812682,605.4337322711945,606.0454100370407,5,3.88181209564209,4.145830869674683,785,0.998775,0.91,4.259166,5480.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,10,64,1024,160,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,734.3974649906158,13616.604736139414,734.5470413565636,734.5698103308678,5,4.706636071205139,4.988819360733032,785,0.9991200000000001,0.9,0.70007,5251.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,50,64,1024,160,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,743.8984677195549,13442.694714314075,743.5071393847466,745.405986905098,5,4.7682300209999084,5.052067339420319,785,0.999516,0.94,1.140368,5251.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,100,64,1024,160,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,763.2167413830757,13102.437954752324,763.1471678614616,763.8469263911247,5,4.884809255599976,5.159102380275726,785,0.9994569999999999,0.95,1.665954,5251.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,10,64,1024,192,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,894.5333555340767,11179.012988318977,894.5060148835182,895.1161950826645,5,5.7231709361076355,6.028883159160614,785,0.9992,0.9,0.32828,5251.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,50,64,1024,192,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,904.1486114263535,11060.128693030172,903.9210975170135,905.0416499376297,5,5.783669650554657,6.090313196182251,785,0.999682,0.96,0.469276,5251.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,100,64,1024,192,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,928.1674966216087,10773.917462525362,927.5803938508034,932.3575720191002,5,5.919240415096283,6.227999925613403,785,0.9997090000000001,0.95,0.710559,5251.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,10,64,1024,224,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,1057.640977203846,9455.004311990302,1057.6919615268707,1058.4268048405647,5,6.769798696041107,7.08375871181488,785,0.9992700000000001,0.9,0.01325,578.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,50,64,1024,224,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,1068.3847710490227,9359.923756851409,1068.4531033039093,1068.631336092949,5,6.834805011749268,7.147148251533508,785,0.9997540000000001,0.96,0.133192,1078.0 +faiss-1.14.1,gpu,ivf_flat,l2,1000000,10000,128,fp32,1,100,64,1024,224,100000,15,2026,31694.970950484276,0.0,340.7115638256073,504.30078125,1536.0,1096.5277925133705,9119.695887578759,1096.0408672690392,1098.961740732193,5,7.007323205471039,7.347196340560913,785,0.999814,0.96,0.246457,1078.0 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/figures/recall-latency.svg b/09_vector_retrieval/PurplePulse/results/real/sift1m/figures/recall-latency.svg new file mode 100644 index 00000000..b63ca015 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/figures/recall-latency.svg @@ -0,0 +1,163 @@ + +Recall–latency frontier +Benchmark curves generated from the checked-in raw CSV data. + + +Recall–latency frontier + +WarpFusion + +FAISS GPU +K = 10 + +64 + +331 + +598 + +864 + +1131 + +0.98 + +0.98 + +0.99 + +0.99 + +1.00 + + +Recall@K +1000-query latency (ms) + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 50 + +79 + +344 + +610 + +876 + +1142 + +0.96 + +0.97 + +0.98 + +0.99 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 100 + +90 + +360 + +630 + +901 + +1171 + +0.95 + +0.97 + +0.98 + +0.99 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +Matched batch=64 · point labels: nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/figures/recall-qps.svg b/09_vector_retrieval/PurplePulse/results/real/sift1m/figures/recall-qps.svg new file mode 100644 index 00000000..10ab1f61 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/figures/recall-qps.svg @@ -0,0 +1,163 @@ + +Recall–throughput frontier +Benchmark curves generated from the checked-in raw CSV data. + + +Recall–throughput frontier + +WarpFusion + +FAISS GPU +K = 10 + +4400 + +22724 + +41047 + +59370 + +77694 + +0.98 + +0.98 + +0.99 + +0.99 + +1.00 + + +Recall@K +Throughput (QPS) + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 50 + +4844 + +21214 + +37583 + +53952 + +70322 + +0.96 + +0.97 + +0.98 + +0.99 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 100 + +4976 + +19996 + +35017 + +50037 + +65057 + +0.95 + +0.97 + +0.98 + +0.99 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +Matched batch=64 · point labels: nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/groundtruth_score_validation.jsonl b/09_vector_retrieval/PurplePulse/results/real/sift1m/groundtruth_score_validation.jsonl new file mode 100644 index 00000000..30a29462 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/groundtruth_score_validation.jsonl @@ -0,0 +1,3 @@ +{"exact_query_fraction": 0.9944, "max_rank_score_error": 0.0, "max_reported_score_error": 0.0, "mean_rank_score_error": 0.0, "mean_reported_score_error": 0.0, "metric": "l2", "min_query_recall": 0.9, "queries": 10000, "recall_at_k": 0.9994400000000001, "score_atol": 0.0001, "score_equivalent_query_fraction": 1.0, "score_rtol": 1e-05, "top_k": 10} +{"exact_query_fraction": 0.9898, "max_rank_score_error": 0.0, "max_reported_score_error": 0.0, "mean_rank_score_error": 0.0, "mean_reported_score_error": 0.0, "metric": "l2", "min_query_recall": 0.98, "queries": 10000, "recall_at_k": 0.9997960000000001, "score_atol": 0.0001, "score_equivalent_query_fraction": 1.0, "score_rtol": 1e-05, "top_k": 50} +{"exact_query_fraction": 0.9889, "max_rank_score_error": 0.0, "max_reported_score_error": 0.0, "mean_rank_score_error": 0.0, "mean_reported_score_error": 0.0, "metric": "l2", "min_query_recall": 0.99, "queries": 10000, "recall_at_k": 0.9998890000000001, "score_atol": 0.0001, "score_equivalent_query_fraction": 1.0, "score_rtol": 1e-05, "top_k": 100} diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/groundtruth_validation.json b/09_vector_retrieval/PurplePulse/results/real/sift1m/groundtruth_validation.json new file mode 100644 index 00000000..07a1d3b9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/groundtruth_validation.json @@ -0,0 +1,23 @@ +[ + { + "exact_query_fraction": 0.9944, + "min_query_recall": 0.9, + "queries": 10000, + "recall_at_k": 0.9994400000000001, + "top_k": 10 + }, + { + "exact_query_fraction": 0.9898, + "min_query_recall": 0.98, + "queries": 10000, + "recall_at_k": 0.9997960000000001, + "top_k": 50 + }, + { + "exact_query_fraction": 0.9889, + "min_query_recall": 0.99, + "queries": 10000, + "recall_at_k": 0.9998890000000001, + "top_k": 100 + } +] diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k10.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k10.csv new file mode 100644 index 00000000..32a957a3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k10.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,32,100000,15,2026,10,137.667,72639.1,136.666,141.631,0.844768,0.919616,0.97893,0.2,79.97344,33777.0,5,785,323.204,193.740457,49.689697,496.972664,10.2928,114.537,1.64833 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,64,100000,15,2026,10,199.05,50238.7,199.113,199.474,1.22992,1.30381,0.9957799999999999,0.6,14.64322,22403.0,5,785,332.983,175.210298,48.152576,497.230476,13.4793,172.77,1.67068 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,128,100000,15,2026,10,338.589,29534.3,338.737,340.325,2.11696,2.23069,0.9996700000000001,0.8,0.78821,3055.0,5,785,320.283,176.065727,48.905216,497.746101,20.0255,304.608,1.71103 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,160,100000,15,2026,10,406.849,24579.1,406.96,407.761,2.5561,2.67661,0.99987,0.9,0.23446,3055.0,5,785,322.505,184.066255,49.703007,498.003914,23.2551,370.073,1.7466 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,192,100000,15,2026,10,474.668,21067.4,474.156,476.9,2.98656,3.12528,0.99995,0.9,0.07875,1525.0,5,785,321.781,179.427563,49.660927,498.261726,26.5432,433.943,1.77025 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,224,100000,15,2026,10,542.219,18442.7,542.007,544.065,3.41907,3.56627,1.0,1.0,0.0,0.0,5,785,316.701,177.705606,49.788929,498.519539,29.7752,498.496,1.80524 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100.csv new file mode 100644 index 00000000..9aa67e03 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,32,100000,15,2026,100,197.7,50581.8,196.9,201.022,1.17728,1.27478,0.955644,0.57,202.235993,33777.0,5,785,318.913,199.390626,48.195457,499.147957,10.2146,155.665,11.3115 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,64,100000,15,2026,100,287.526,34779.5,285.984,292.142,1.73152,1.84867,0.9896149999999999,0.72,42.083326,22403.0,5,785,318.984,188.132779,48.891903,501.515144,13.4691,239.71,11.4772 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,128,100000,15,2026,100,478.162,20913.4,477.592,481.989,2.95587,3.07408,0.9988469999999999,0.87,4.317628,3201.0,5,785,319.94,188.279765,48.712704,506.249519,19.9136,423.282,12.6424 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,160,100000,15,2026,100,575.966,17362.2,575.245,579.948,3.57984,3.6977,0.9995649999999999,0.94,1.670581,3201.0,5,785,319.493,188.226338,48.700382,508.616707,23.2414,516.87,13.0008 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,192,100000,15,2026,100,672.357,14873.1,671.714,675.204,4.19066,4.33942,0.9998309999999999,0.96,0.666237,3201.0,5,785,323.998,201.666764,57.35117,510.983894,26.508,608.886,13.2047 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,224,100000,15,2026,100,775.442,12895.9,770.922,788.185,4.80515,4.93936,0.9999379999999999,0.96,0.256532,1754.0,5,785,315.571,187.56733,48.707584,513.351082,29.7979,700.814,13.5694 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100_full_heap.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100_full_heap.csv new file mode 100644 index 00000000..dab2d21e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100_full_heap.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,32,100000,15,2026,100,436.985,22884.1,436.115,440.615,2.71795,2.91997,0.955644,0.57,202.235993,33777.0,5,785,322.883,213.866939,58.734592,499.147957,10.1781,393.527,11.2142 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,64,100000,15,2026,100,545.796,18321.9,545.788,549.061,3.4225,3.68883,0.9896149999999999,0.72,42.083326,22403.0,5,785,320.381,193.838597,49.660801,501.515144,13.4119,497.891,11.4252 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,128,100000,15,2026,100,709.398,14096.5,709.035,712.222,4.43107,4.71782,0.9988469999999999,0.87,4.317628,3201.0,5,785,318.368,182.89103,48.803841,506.249519,19.9153,654.032,12.5987 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,160,100000,15,2026,100,794.208,12591.2,793.008,798.834,4.96826,5.28915,0.9995649999999999,0.94,1.670581,3201.0,5,785,321.814,204.20748,50.63168,508.616707,23.1448,735.464,12.9091 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,192,100000,15,2026,100,876.632,11407.3,877.072,880.335,5.48989,5.83808,0.9998309999999999,0.96,0.666237,3201.0,5,785,322.317,191.25412,49.747967,510.983894,26.3964,813.507,13.1192 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,224,100000,15,2026,100,957.07,10448.6,955.921,962.226,5.99789,6.38269,0.9999379999999999,0.96,0.256532,1754.0,5,785,329.588,199.467905,53.533695,513.351082,29.6314,889.532,13.4925 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100_partitioned.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100_partitioned.csv new file mode 100644 index 00000000..9aa67e03 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k100_partitioned.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,32,100000,15,2026,100,197.7,50581.8,196.9,201.022,1.17728,1.27478,0.955644,0.57,202.235993,33777.0,5,785,318.913,199.390626,48.195457,499.147957,10.2146,155.665,11.3115 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,64,100000,15,2026,100,287.526,34779.5,285.984,292.142,1.73152,1.84867,0.9896149999999999,0.72,42.083326,22403.0,5,785,318.984,188.132779,48.891903,501.515144,13.4691,239.71,11.4772 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,128,100000,15,2026,100,478.162,20913.4,477.592,481.989,2.95587,3.07408,0.9988469999999999,0.87,4.317628,3201.0,5,785,319.94,188.279765,48.712704,506.249519,19.9136,423.282,12.6424 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,160,100000,15,2026,100,575.966,17362.2,575.245,579.948,3.57984,3.6977,0.9995649999999999,0.94,1.670581,3201.0,5,785,319.493,188.226338,48.700382,508.616707,23.2414,516.87,13.0008 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,192,100000,15,2026,100,672.357,14873.1,671.714,675.204,4.19066,4.33942,0.9998309999999999,0.96,0.666237,3201.0,5,785,323.998,201.666764,57.35117,510.983894,26.508,608.886,13.2047 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned,1024,224,100000,15,2026,100,775.442,12895.9,770.922,788.185,4.80515,4.93936,0.9999379999999999,0.96,0.256532,1754.0,5,785,315.571,187.56733,48.707584,513.351082,29.7979,700.814,13.5694 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50.csv new file mode 100644 index 00000000..95eba584 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,32,100000,15,2026,50,229.621,43549.9,229.04,231.593,1.42186,1.5537,0.965052,0.48,148.988358,33777.0,5,785,321.818,220.079691,49.472607,497.939461,10.1987,198.142,5.8998 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,64,100000,15,2026,50,309.041,32358.1,309.69,310.375,1.91482,2.07626,0.9924219999999999,0.78,29.384078,22403.0,5,785,321.078,177.157338,49.529858,499.134773,13.5669,272.944,6.03525 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,128,100000,15,2026,50,449.871,22228.6,449.435,452.469,2.79856,2.98934,0.999224,0.9,2.673216,3201.0,5,785,321.842,179.021586,49.711105,501.525398,19.984,406.742,6.18315 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,160,100000,15,2026,50,519.838,19236.8,520.489,520.999,3.24864,3.43622,0.999706,0.92,1.05729,3201.0,5,785,318.684,175.394173,48.728191,502.720711,23.2292,473.323,6.74316 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,192,100000,15,2026,50,602.184,16606.2,601.594,604.995,3.75677,3.90189,0.999898,0.96,0.459158,3201.0,5,785,317.694,179.918136,48.764927,503.916023,26.5244,548.342,6.86728 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,224,100000,15,2026,50,677.719,14755.4,677.844,678.803,4.26278,4.40144,0.9999620000000001,0.96,0.172746,1754.0,5,785,321.349,181.939438,49.854465,505.111336,29.7551,623.967,7.04164 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50_full_heap.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50_full_heap.csv new file mode 100644 index 00000000..95eba584 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50_full_heap.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,32,100000,15,2026,50,229.621,43549.9,229.04,231.593,1.42186,1.5537,0.965052,0.48,148.988358,33777.0,5,785,321.818,220.079691,49.472607,497.939461,10.1987,198.142,5.8998 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,64,100000,15,2026,50,309.041,32358.1,309.69,310.375,1.91482,2.07626,0.9924219999999999,0.78,29.384078,22403.0,5,785,321.078,177.157338,49.529858,499.134773,13.5669,272.944,6.03525 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,128,100000,15,2026,50,449.871,22228.6,449.435,452.469,2.79856,2.98934,0.999224,0.9,2.673216,3201.0,5,785,321.842,179.021586,49.711105,501.525398,19.984,406.742,6.18315 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,160,100000,15,2026,50,519.838,19236.8,520.489,520.999,3.24864,3.43622,0.999706,0.92,1.05729,3201.0,5,785,318.684,175.394173,48.728191,502.720711,23.2292,473.323,6.74316 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,192,100000,15,2026,50,602.184,16606.2,601.594,604.995,3.75677,3.90189,0.999898,0.96,0.459158,3201.0,5,785,317.694,179.918136,48.764927,503.916023,26.5244,548.342,6.86728 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major,1024,224,100000,15,2026,50,677.719,14755.4,677.844,678.803,4.26278,4.40144,0.9999620000000001,0.96,0.172746,1754.0,5,785,321.349,181.939438,49.854465,505.111336,29.7551,623.967,7.04164 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50_partitioned.csv b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50_partitioned.csv new file mode 100644 index 00000000..b4ded49b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/ivf_k50_partitioned.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned4x16,1024,32,100000,15,2026,50,163.699,61087.6,163.231,166.021,1.00186,1.06045,0.964726,0.48,149.200156,33777.0,5,785,323.638,178.231923,49.849342,497.939461,10.2109,132.098,5.94147 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned4x16,1024,64,100000,15,2026,50,221.181,45211.8,220.699,223.219,1.35101,1.45536,0.9920959999999999,0.78,29.595786,22403.0,5,785,322.103,185.831212,50.363392,499.134773,13.4626,186.244,6.04764 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned4x16,1024,128,100000,15,2026,50,350.25,28551.0,349.978,352.581,2.1705,2.27488,0.998898,0.9,2.884924,3201.0,5,785,319.932,176.105079,48.959488,501.525398,19.9973,307.617,6.20828 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned4x16,1024,160,100000,15,2026,50,419.173,23856.5,418.995,421.675,2.6041,2.72541,0.9993799999999999,0.9,1.268998,3201.0,5,785,323.14,183.377534,49.666943,502.720711,23.2758,371.624,6.76509 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned4x16,1024,192,100000,15,2026,50,485.037,20617.0,484.752,487.521,3.02928,3.15424,0.9995719999999999,0.9,0.670866,3201.0,5,785,319.942,181.11161,49.281025,503.916023,26.5112,434.734,6.87158 +WarpFusion,gpu,1000000,10000,128,l2,64,bucket_major_partitioned4x16,1024,224,100000,15,2026,50,551.673,18126.7,551.729,552.486,3.45821,3.58438,0.9996360000000001,0.9,0.384454,2193.0,5,785,320.227,217.122509,50.38176,505.111336,29.7846,498.491,7.05448 diff --git a/09_vector_retrieval/PurplePulse/results/real/sift1m/partitioned_topk_validation.json b/09_vector_retrieval/PurplePulse/results/real/sift1m/partitioned_topk_validation.json new file mode 100644 index 00000000..73040506 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/sift1m/partitioned_topk_validation.json @@ -0,0 +1,110 @@ +{ + "50": { + "selected_mode": "full_heap", + "maximum_allowed_recall_loss": 0.0001, + "comparisons": [ + { + "nprobe": 32, + "partitioned_recall": 0.964726, + "full_heap_recall": 0.965052, + "partitioned_qps": 61087.6, + "full_heap_qps": 43549.9, + "recall_loss": 0.0003260000000000485 + }, + { + "nprobe": 64, + "partitioned_recall": 0.9920959999999999, + "full_heap_recall": 0.9924219999999999, + "partitioned_qps": 45211.8, + "full_heap_qps": 32358.1, + "recall_loss": 0.0003260000000000485 + }, + { + "nprobe": 128, + "partitioned_recall": 0.998898, + "full_heap_recall": 0.999224, + "partitioned_qps": 28551.0, + "full_heap_qps": 22228.6, + "recall_loss": 0.0003260000000000485 + }, + { + "nprobe": 160, + "partitioned_recall": 0.9993799999999999, + "full_heap_recall": 0.999706, + "partitioned_qps": 23856.5, + "full_heap_qps": 19236.8, + "recall_loss": 0.0003260000000000485 + }, + { + "nprobe": 192, + "partitioned_recall": 0.9995719999999999, + "full_heap_recall": 0.999898, + "partitioned_qps": 20617.0, + "full_heap_qps": 16606.2, + "recall_loss": 0.0003260000000000485 + }, + { + "nprobe": 224, + "partitioned_recall": 0.9996360000000001, + "full_heap_recall": 0.9999620000000001, + "partitioned_qps": 18126.7, + "full_heap_qps": 14755.4, + "recall_loss": 0.0003260000000000485 + } + ] + }, + "100": { + "selected_mode": "partitioned", + "maximum_allowed_recall_loss": 0.0001, + "comparisons": [ + { + "nprobe": 32, + "partitioned_recall": 0.955644, + "full_heap_recall": 0.955644, + "partitioned_qps": 50581.8, + "full_heap_qps": 22884.1, + "recall_loss": 0.0 + }, + { + "nprobe": 64, + "partitioned_recall": 0.9896149999999999, + "full_heap_recall": 0.9896149999999999, + "partitioned_qps": 34779.5, + "full_heap_qps": 18321.9, + "recall_loss": 0.0 + }, + { + "nprobe": 128, + "partitioned_recall": 0.9988469999999999, + "full_heap_recall": 0.9988469999999999, + "partitioned_qps": 20913.4, + "full_heap_qps": 14096.5, + "recall_loss": 0.0 + }, + { + "nprobe": 160, + "partitioned_recall": 0.9995649999999999, + "full_heap_recall": 0.9995649999999999, + "partitioned_qps": 17362.2, + "full_heap_qps": 12591.2, + "recall_loss": 0.0 + }, + { + "nprobe": 192, + "partitioned_recall": 0.9998309999999999, + "full_heap_recall": 0.9998309999999999, + "partitioned_qps": 14873.1, + "full_heap_qps": 11407.3, + "recall_loss": 0.0 + }, + { + "nprobe": 224, + "partitioned_recall": 0.9999379999999999, + "full_heap_recall": 0.9999379999999999, + "partitioned_qps": 12895.9, + "full_heap_qps": 10448.6, + "recall_loss": 0.0 + } + ] + } +} diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/build.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/build.csv new file mode 100644 index 00000000..64805273 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/build.csv @@ -0,0 +1,2 @@ +dataset,nlist,training_iterations,training_samples,threads,build_ms,save_ms,minimum_bucket,average_bucket,maximum_bucket,empty_buckets,index_bytes +yahoo-minilm-384,1024,15,100000,16,87542.6,543.356,55,661.431,1878,0,1047340016 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/dataset_manifest.json b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/dataset_manifest.json new file mode 100644 index 00000000..a6ea091a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/dataset_manifest.json @@ -0,0 +1,30 @@ +{ + "dataset": "yahoo-minilm-384-normalized", + "source_url": "https://huggingface.co/datasets/vector-index-bench/vibe/resolve/main/yahoo-minilm-384-normalized.hdf5", + "source_path": "/data/real-datasets/raw/vibe/yahoo-minilm-384-normalized.hdf5", + "source_bytes": 1043492672, + "source_sha256": "8b0519850249d7ea4aea258eb43ae837dca1bb2f7a85ee0a5145afdb699c4136", + "distance": "normalized", + "warpfusion_metric": "cosine", + "database_rows": 677305, + "query_rows": 1000, + "dim": 384, + "groundtruth_k": 100, + "outputs": { + "database": { + "path": "data/real/yahoo-minilm-384-normalized/database.bin", + "bytes": 1040340508, + "sha256": "867ab60b87ab69cb837825dc69b1d7c8b4d7c3a49e80e4a378292424f14a24d4" + }, + "queries": { + "path": "data/real/yahoo-minilm-384-normalized/queries.bin", + "bytes": 1536024, + "sha256": "aa822e4c811a8ac119a100cd6f252ec4d2d5e1a2b1eb6d2cff9fb3de2d1c26cf" + }, + "groundtruth": { + "path": "data/real/yahoo-minilm-384-normalized/groundtruth.ivecs", + "bytes": 404000, + "sha256": "cc9b1496e1bb9d1da67128bbe1e2ef4c70e9bce6fb654290a3be0af780511324" + } + } +} diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/environment.json b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/environment.json new file mode 100644 index 00000000..5e72e50f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/environment.json @@ -0,0 +1,35 @@ +{ + "dataset": "yahoo-minilm-384", + "timestamp_utc": "2026-09-10T11:55:25.088905+00:00", + "git_commit": "fatal: not a git repository (or any parent up to mount point /)\nStopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", + "source_sha256": { + "src/gpu_ivf_flat.cu": "1a53f5471c1ba2d9edc9f2752fc1dab43152db3d9cae511715f287fea217be91", + "src/gpu_search.cu": "52fc4696718ca42a34210c5c708d3356c3d2cb4b43bc0deadccef4aac0b49bfe", + "src/ivf_flat.cpp": "ea7854fc9597e66ff5d910f4a4ed5e91abf77d1457eea86d5406ca617bea79ea", + "scripts/run_real_benchmarks.py": "c4bf1a520f7392e48759ac64a388fdc25416ff28df92f577bbfe104b13996837", + "scripts/benchmark_exact.py": "a9f1e5754ecde98bd66cc0a333106c052c4488ea20076596a72f11d28f1d552a", + "scripts/benchmark_ivf_sweep.py": "bb454aee7a1276462f2ecef105ad23d9180a454e39e3043fae00884156f948da", + "scripts/benchmark_faiss.py": "0cd80ffcaacd191a7e8b68c40508d917ece3d3bbf2dbb58952f04fa2d0eaa969" + }, + "gpu": "NVIDIA GeForce RTX 4090 D, 570.124.06, 24564 MiB", + "nvcc": "nvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2025 NVIDIA Corporation\nBuilt on Wed_Jan_15_19:20:09_PST_2025\nCuda compilation tools, release 12.8, V12.8.61\nBuild cuda_12.8.r12.8/compiler.35404655_0", + "python": "3.12.3 (main, Nov 6 2024, 18:32:19) [GCC 13.2.0]", + "parameters": { + "dataset": "yahoo-minilm-384", + "project_root": "/data/purplepulse-work/PurplePulse", + "data_root": "data/real", + "results_root": "results/real", + "build_dir": "build", + "nlist": 1024, + "nprobes": "32,64,128,160,192,224", + "training_samples": 100000, + "iterations": 15, + "threads": 16, + "batch_size": 64, + "warmup": 1, + "repeat": 5, + "skip_index_build": false, + "skip_faiss": false, + "maximum_partition_recall_loss": 0.0001 + } +} diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/exact_gpu.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/exact_gpu.csv new file mode 100644 index 00000000..9fadda9d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/exact_gpu.csv @@ -0,0 +1,4 @@ +implementation,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,gpu_initialization_ms,database_h2d_ms,gpu_buffer_mib,query_h2d_ms,distance_and_local_topk_ms,final_topk_ms,result_d2h_ms,result_path +WarpFusion Exact fused,10,64,276.992,3610.22,276.461,282.893,5,17.6113,18.5666,80,256.683,103.47,992.364,0.358611,275.887,0.188109,0.330854,/data/purplepulse-work/PurplePulse/results/real/yahoo-minilm-384/exact_outputs/exact_k10.txt +WarpFusion Exact fused,50,64,288.082,3471.23,284.597,294.777,5,18.2826,19.5238,80,250.861,98.1649,992.862,0.349184,286.057,0.854976,0.423923,/data/purplepulse-work/PurplePulse/results/real/yahoo-minilm-384/exact_outputs/exact_k50.txt +WarpFusion Exact fused,100,64,304.328,3285.92,301.115,312.348,5,19.2952,20.0785,80,231.485,102.26,993.485,0.357984,300.941,1.92299,0.499981,/data/purplepulse-work/PurplePulse/results/real/yahoo-minilm-384/exact_outputs/exact_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/faiss_gpu.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/faiss_gpu.csv new file mode 100644 index 00000000..6ff91590 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/faiss_gpu.csv @@ -0,0 +1,22 @@ +implementation,backend,index_type,metric,num_vectors,num_queries,dim,dtype,cpu_threads,top_k,batch_size,nlist,nprobe,train_samples,training_iterations,training_seed,build_ms,load_ms,gpu_transfer_ms,gpu_index_mib,gpu_temp_mib,average_query_ms,qps,run_p50_ms,run_p99_ms,run_samples,batch_p50_ms,batch_p99_ms,batch_latency_samples,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error +faiss-1.14.1,gpu,flat,cosine,677305,1000,384,fp32,1,10,64,0,0,0,0,0,450.8100524544716,0.0,299.5612174272537,994.729736328125,1536.0,47.129690647125244,21218.04718573931,47.55561053752899,47.75427281856537,5,2.9764994978904724,2.999044954776764,80,1.0,1.0,1.4573633670806886e-07,8.344650268554688e-07 +faiss-1.14.1,gpu,flat,cosine,677305,1000,384,fp32,1,50,64,0,0,0,0,0,450.8100524544716,0.0,299.5612174272537,994.729736328125,1536.0,47.176842391490936,21196.840426530227,47.17285931110382,47.21493273973465,5,2.949640154838562,2.9679685831069946,80,1.0,1.0,1.2792527675628663e-07,8.344650268554688e-07 +faiss-1.14.1,gpu,flat,cosine,677305,1000,384,fp32,1,100,64,0,0,0,0,0,450.8100524544716,0.0,299.5612174272537,994.729736328125,1536.0,48.6848309636116,20540.278772815866,48.51270467042923,49.375757575035095,5,3.0298978090286255,3.2334327697753906,80,1.0,1.0,1.2031018733978273e-07,8.344650268554688e-07 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,10,64,1024,32,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,30.19937574863434,33113.2672517319,30.18796443939209,30.236780643463135,5,1.9363686442375183,2.031967043876648,80,0.9599,0.2,0.0015490862041711807,0.13176971673965454 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,50,64,1024,32,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,31.084707379341125,32170.159680016783,31.085841357707977,31.138867139816284,5,1.9916370511054993,2.074703574180603,80,0.9444000000000001,0.34,0.002021763826608658,0.13176971673965454 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,100,64,1024,32,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,32.6606884598732,30617.848157995697,32.656192779541016,32.72579610347748,5,2.067975699901581,2.176031470298767,80,0.93456,0.31,0.0023760333928465843,0.13176971673965454 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,10,64,1024,64,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,61.67723387479782,16213.43787936336,61.669930815696716,61.73589825630188,5,3.944084048271179,4.0833353996276855,80,0.9822000000000001,0.3,0.0006998934537172318,0.11930292844772339 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,50,64,1024,64,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,62.69751042127609,15949.5966152534,62.69342452287674,62.74265795946121,5,4.007898271083832,4.138417541980743,80,0.97208,0.4,0.0009457416796684265,0.11930292844772339 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,100,64,1024,64,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,64.59192037582397,15481.81249576671,64.58926200866699,64.62705135345459,5,4.12413477897644,4.209011793136597,80,0.9666200000000001,0.4,0.0011352579164505005,0.11930292844772339 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,10,64,1024,128,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,127.10106819868088,7867.754489968783,127.10943818092346,127.14478373527527,5,8.125759661197662,8.281677961349487,80,0.9933,0.6,0.00025944703221321105,0.1106138825416565 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,50,64,1024,128,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,128.5264492034912,7780.499704124998,128.52223217487335,128.5785660147667,5,8.207350969314575,8.37651640176773,80,0.98806,0.5,0.0003864972972869873,0.1106138825416565 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,100,64,1024,128,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,131.11717849969864,7626.765702575718,131.09293580055237,131.2248781323433,5,8.35118442773819,8.524872362613678,80,0.9850300000000001,0.53,0.00047720189005136487,0.1106138825416565 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,10,64,1024,160,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,160.87044924497604,6216.182056389886,160.87330132722855,160.94182431697845,5,10.255873203277588,10.470017790794373,80,0.9953,0.6,0.00018345237970352174,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,50,64,1024,160,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,162.41146624088287,6157.2007392435935,162.38412261009216,162.4923124909401,5,10.346010327339172,10.57722419500351,80,0.9912799999999999,0.52,0.00027075362503528594,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,100,64,1024,160,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,165.0216579437256,6059.810648254499,165.03334790468216,165.03560543060303,5,10.53435355424881,10.722257196903229,80,0.98908,0.57,0.0003443580350279808,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,10,64,1024,192,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,194.4973424077034,5141.458426222657,194.54151391983032,194.56788152456284,5,12.407995760440826,12.624137103557587,80,0.9966,0.6,0.0001404004067182541,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,50,64,1024,192,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,196.2209790945053,5096.295027242592,196.22181355953217,196.2629333138466,5,12.520894408226013,12.721635401248932,80,0.9933600000000001,0.52,0.00020388494014739991,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,100,64,1024,192,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,199.3123009800911,5017.251795712739,199.30288940668106,199.33469593524933,5,12.710973620414734,12.910954654216766,80,0.9917,0.58,0.00026132633090019227,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,10,64,1024,224,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,228.4289449453354,4377.728926775488,228.42742502689362,228.47234457731247,5,14.590464532375336,14.774948358535767,80,0.9972000000000001,0.6,0.00012997233867645264,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,50,64,1024,224,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,230.3800955414772,4340.652770586085,230.39449006319046,230.4425686597824,5,14.698363840579987,14.881014823913574,80,0.99466,0.54,0.00016983119666576387,0.07067233324050903 +faiss-1.14.1,gpu,ivf_flat,cosine,677305,1000,384,fp32,1,100,64,1024,224,100000,15,2026,77886.4715769887,0.0,682.7266216278076,1022.198486328125,1536.0,234.14455652236938,4270.86589093718,234.07414555549622,234.4672828912735,5,14.94162529706955,15.218183398246765,80,0.9933599999999999,0.61,0.0002106537815928459,0.07067233324050903 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/figures/recall-latency.svg b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/figures/recall-latency.svg new file mode 100644 index 00000000..050c3feb --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/figures/recall-latency.svg @@ -0,0 +1,163 @@ + +Recall–latency frontier +Benchmark curves generated from the checked-in raw CSV data. + + +Recall–latency frontier + +WarpFusion + +FAISS GPU +K = 10 + +9 + +68 + +127 + +186 + +245 + +0.96 + +0.97 + +0.98 + +0.99 + +1.00 + + +Recall@K +1000-query latency (ms) + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 50 + +15 + +73 + +131 + +189 + +246 + +0.94 + +0.96 + +0.97 + +0.98 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 100 + +11 + +71 + +131 + +191 + +251 + +0.93 + +0.95 + +0.96 + +0.98 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +Matched batch=64 · point labels: nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/figures/recall-qps.svg b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/figures/recall-qps.svg new file mode 100644 index 00000000..7ff37c8f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/figures/recall-qps.svg @@ -0,0 +1,163 @@ + +Recall–throughput frontier +Benchmark curves generated from the checked-in raw CSV data. + + +Recall–throughput frontier + +WarpFusion + +FAISS GPU +K = 10 + +1530 + +11852 + +22175 + +32497 + +42819 + +0.96 + +0.97 + +0.98 + +0.99 + +1.00 + + +Recall@K +Throughput (QPS) + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 50 + +2114 + +10185 + +18255 + +26326 + +34397 + +0.94 + +0.96 + +0.97 + +0.98 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +K = 100 + +1708 + +10997 + +20286 + +29575 + +38863 + +0.93 + +0.95 + +0.96 + +0.98 + +1.00 + + +Recall@K + + +32 + +64 + +128 + +160 + +192 + +224 + + +32 + +64 + +128 + +160 + +192 + +224 +Matched batch=64 · point labels: nprobe + diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/groundtruth_validation.json b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/groundtruth_validation.json new file mode 100644 index 00000000..9e640d86 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/groundtruth_validation.json @@ -0,0 +1,47 @@ +[ + { + "exact_query_fraction": 0.998, + "max_rank_score_error": 0.0, + "max_reported_score_error": 2.980232238769531e-07, + "mean_rank_score_error": 0.0, + "mean_reported_score_error": 5.479156970977783e-08, + "metric": "cosine", + "min_query_recall": 0.9, + "queries": 1000, + "recall_at_k": 0.9997999999999999, + "score_atol": 0.0001, + "score_equivalent_query_fraction": 1.0, + "score_rtol": 1e-05, + "top_k": 10 + }, + { + "exact_query_fraction": 1.0, + "max_rank_score_error": 0.0, + "max_reported_score_error": 2.980232238769531e-07, + "mean_rank_score_error": 0.0, + "mean_reported_score_error": 5.029141902923584e-08, + "metric": "cosine", + "min_query_recall": 1.0, + "queries": 1000, + "recall_at_k": 1.0, + "score_atol": 0.0001, + "score_equivalent_query_fraction": 1.0, + "score_rtol": 1e-05, + "top_k": 50 + }, + { + "exact_query_fraction": 1.0, + "max_rank_score_error": 0.0, + "max_reported_score_error": 2.980232238769531e-07, + "mean_rank_score_error": 0.0, + "mean_reported_score_error": 4.790693521499634e-08, + "metric": "cosine", + "min_query_recall": 1.0, + "queries": 1000, + "recall_at_k": 1.0, + "score_atol": 0.0001, + "score_equivalent_query_fraction": 1.0, + "score_rtol": 1e-05, + "top_k": 100 + } +] diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k10.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k10.csv new file mode 100644 index 00000000..1abab854 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k10.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,32,100000,15,2026,10,25.0177,39971.7,24.9527,25.2257,1.40381,1.45821,0.96,0.2,0.0015903574357999997,0.16803198999999996,5,80,615.32,253.841354,105.347069,999.437943,2.41437,19.017,0.175494 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,64,100000,15,2026,10,33.1919,30127.8,33.187,33.255,1.93594,1.95795,0.9795,0.4,0.0007539571803000002,0.11731612700000005,5,80,598.462,221.988553,99.067902,999.695755,2.59712,27.1201,0.169581 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,128,100000,15,2026,10,53.2645,18774.2,53.2607,53.3304,3.21763,3.25683,0.9907,0.5,0.00034863495470000005,0.074507355,5,80,583.333,228.371225,103.077888,1000.21138,3.2778,46.466,0.175968 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,160,100000,15,2026,10,63.5599,15733.2,63.5563,63.6589,3.8767,3.93107,0.9939,0.5,0.0002204378745000001,0.074507355,5,80,576.442,221.602178,99.047424,1000.469193,3.61023,56.4528,0.178182 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,192,100000,15,2026,10,74.1052,13494.3,74.0714,74.2573,4.55146,4.61754,0.9956,0.5,0.0001645866181000001,0.074507355,5,80,581.862,226.575909,103.015427,1000.727005,3.97519,66.6217,0.183008 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,224,100000,15,2026,10,84.5358,11829.3,84.4814,84.7255,5.2119,5.28419,0.9967,0.5,0.00013676807620000017,0.074507355,5,80,582.47,221.918123,98.994179,1000.984818,4.31267,76.7173,0.185715 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100.csv new file mode 100644 index 00000000..4dd1b25e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,32,100000,15,2026,100,27.5476,36300.8,27.4732,27.9229,1.51718,1.58736,0.937,0.35,0.00226213649931,0.16803198999999996,5,80,632.016,219.81129,96.653313,1001.613235,2.26611,19.967,1.14769 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,64,100000,15,2026,100,36.2878,27557.5,36.2143,36.6426,2.07827,2.16842,0.9675,0.44,0.00111137691699,0.11731612700000005,5,80,615.445,219.880745,97.542145,1003.980423,2.59802,28.3386,1.16737 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,128,100000,15,2026,100,59.1108,16917.4,59.0373,59.3614,3.54618,3.59792,0.9851599999999999,0.58,0.0004964717999000001,0.074507355,5,80,622.461,223.660037,97.46637,1008.714798,3.29774,50.2849,1.31774 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,160,100000,15,2026,100,70.4416,14196.2,70.4452,70.9362,4.27254,4.34474,0.98923,0.67,0.00034501102042000016,0.074507355,5,80,621.258,222.388821,96.962563,1011.081985,3.65519,61.2786,1.33953 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,192,100000,15,2026,100,82.0801,12183.2,82.0289,82.457,5.01482,5.08573,0.99185,0.68,0.0002647012558900001,0.074507355,5,80,634.804,221.601371,98.573311,1013.449173,4.01476,72.4373,1.37266 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,224,100000,15,2026,100,93.9092,10648.6,93.8809,94.1201,5.77248,5.8792,0.9936799999999999,0.75,0.0002082749046100001,0.074507355,5,80,616.427,220.378178,97.820671,1015.81636,4.37754,83.9071,1.41418 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100_full_heap.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100_full_heap.csv new file mode 100644 index 00000000..b6a4388b --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100_full_heap.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,32,100000,15,2026,100,69.145,14462.4,69.0678,69.5509,4.09882,4.34435,0.937,0.35,0.00226213649931,0.16803198999999996,5,80,624.728,224.893472,97.354752,1001.613235,2.26195,61.5402,1.1458 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,64,100000,15,2026,100,75.3244,13275.9,75.2989,75.787,4.49338,4.65229,0.9675,0.44,0.00111137691699,0.11731612700000005,5,80,626.195,229.177001,98.456573,1003.980423,2.59912,67.3547,1.16408 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,128,100000,15,2026,100,104.647,9555.98,104.555,104.995,6.41245,6.49898,0.9851599999999999,0.58,0.0004964717999000001,0.074507355,5,80,622.307,221.062987,97.443871,1008.714798,3.26175,95.8832,1.30049 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,160,100000,15,2026,100,121.055,8260.7,121.057,121.314,7.46528,7.55472,0.98923,0.67,0.00034501102042000016,0.074507355,5,80,633.156,226.854412,102.834175,1011.081985,3.59485,111.886,1.31443 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,192,100000,15,2026,100,136.881,7305.64,136.765,137.326,8.47526,8.57216,0.99185,0.68,0.0002647012558900001,0.074507355,5,80,623.851,230.293752,106.638306,1013.449173,3.92856,127.4,1.34267 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,224,100000,15,2026,100,153.724,6505.14,153.634,154.178,9.56003,9.63667,0.9936799999999999,0.75,0.0002082749046100001,0.074507355,5,80,630.281,223.004934,98.985985,1015.81636,4.26166,143.838,1.37277 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100_partitioned.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100_partitioned.csv new file mode 100644 index 00000000..4dd1b25e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k100_partitioned.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,32,100000,15,2026,100,27.5476,36300.8,27.4732,27.9229,1.51718,1.58736,0.937,0.35,0.00226213649931,0.16803198999999996,5,80,632.016,219.81129,96.653313,1001.613235,2.26611,19.967,1.14769 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,64,100000,15,2026,100,36.2878,27557.5,36.2143,36.6426,2.07827,2.16842,0.9675,0.44,0.00111137691699,0.11731612700000005,5,80,615.445,219.880745,97.542145,1003.980423,2.59802,28.3386,1.16737 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,128,100000,15,2026,100,59.1108,16917.4,59.0373,59.3614,3.54618,3.59792,0.9851599999999999,0.58,0.0004964717999000001,0.074507355,5,80,622.461,223.660037,97.46637,1008.714798,3.29774,50.2849,1.31774 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,160,100000,15,2026,100,70.4416,14196.2,70.4452,70.9362,4.27254,4.34474,0.98923,0.67,0.00034501102042000016,0.074507355,5,80,621.258,222.388821,96.962563,1011.081985,3.65519,61.2786,1.33953 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,192,100000,15,2026,100,82.0801,12183.2,82.0289,82.457,5.01482,5.08573,0.99185,0.68,0.0002647012558900001,0.074507355,5,80,634.804,221.601371,98.573311,1013.449173,4.01476,72.4373,1.37266 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned,1024,224,100000,15,2026,100,93.9092,10648.6,93.8809,94.1201,5.77248,5.8792,0.9936799999999999,0.75,0.0002082749046100001,0.074507355,5,80,616.427,220.378178,97.820671,1015.81636,4.37754,83.9071,1.41418 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50.csv new file mode 100644 index 00000000..6d42ef91 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,32,100000,15,2026,50,32.1664,31088.4,32.0637,32.3548,1.82246,1.90678,0.9469399999999999,0.32,0.00192249446772,0.16803198999999996,5,80,622.945,219.127451,96.250877,1000.404739,2.26944,25.5575,0.596019 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,64,100000,15,2026,50,38.3504,26075.4,38.2919,38.5666,2.2232,2.31315,0.97312,0.4,0.0009359371467000001,0.11731612700000005,5,80,623.44,221.35587,97.981346,1001.600052,2.59305,31.4994,0.612141 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,128,100000,15,2026,50,56.6138,17663.5,56.5905,56.8182,3.40432,3.53843,0.9881599999999999,0.54,0.0004134946768800001,0.074507355,5,80,621.404,218.141578,96.24678,1003.990677,3.27071,49.0523,0.630266 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,160,100000,15,2026,50,66.8911,14949.7,66.9044,67.0506,4.05846,4.18694,0.99152,0.66,0.00027749032166000015,0.074507355,5,80,626.545,227.419422,98.321411,1005.185989,3.62828,58.881,0.692832 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,192,100000,15,2026,50,77.1075,12968.9,77.1068,77.3744,4.71923,4.81955,0.99336,0.66,0.00021764280564000017,0.074507355,5,80,621.796,223.496225,96.375809,1006.381302,3.9801,68.7534,0.7072 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,224,100000,15,2026,50,87.4793,11431.3,87.4535,87.779,5.37523,5.5209,0.99482,0.76,0.00017535253728000015,0.074507355,5,80,628.405,224.773498,98.170883,1007.576614,4.34845,78.7322,0.729683 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50_full_heap.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50_full_heap.csv new file mode 100644 index 00000000..6d42ef91 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50_full_heap.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,32,100000,15,2026,50,32.1664,31088.4,32.0637,32.3548,1.82246,1.90678,0.9469399999999999,0.32,0.00192249446772,0.16803198999999996,5,80,622.945,219.127451,96.250877,1000.404739,2.26944,25.5575,0.596019 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,64,100000,15,2026,50,38.3504,26075.4,38.2919,38.5666,2.2232,2.31315,0.97312,0.4,0.0009359371467000001,0.11731612700000005,5,80,623.44,221.35587,97.981346,1001.600052,2.59305,31.4994,0.612141 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,128,100000,15,2026,50,56.6138,17663.5,56.5905,56.8182,3.40432,3.53843,0.9881599999999999,0.54,0.0004134946768800001,0.074507355,5,80,621.404,218.141578,96.24678,1003.990677,3.27071,49.0523,0.630266 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,160,100000,15,2026,50,66.8911,14949.7,66.9044,67.0506,4.05846,4.18694,0.99152,0.66,0.00027749032166000015,0.074507355,5,80,626.545,227.419422,98.321411,1005.185989,3.62828,58.881,0.692832 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,192,100000,15,2026,50,77.1075,12968.9,77.1068,77.3744,4.71923,4.81955,0.99336,0.66,0.00021764280564000017,0.074507355,5,80,621.796,223.496225,96.375809,1006.381302,3.9801,68.7534,0.7072 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major,1024,224,100000,15,2026,50,87.4793,11431.3,87.4535,87.779,5.37523,5.5209,0.99482,0.76,0.00017535253728000015,0.074507355,5,80,628.405,224.773498,98.170883,1007.576614,4.34845,78.7322,0.729683 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50_partitioned.csv b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50_partitioned.csv new file mode 100644 index 00000000..dcaa1174 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/ivf_k50_partitioned.csv @@ -0,0 +1,7 @@ +implementation,backend,num_vectors,num_queries,dim,metric,batch_size,distance_mode,nlist,nprobe,training_samples,training_iterations,training_seed,top_k,average_ms,qps,run_p50_ms,run_p99_ms,batch_p50_ms,batch_p99_ms,recall_at_k,min_query_recall,mean_absolute_score_error,max_absolute_score_error,run_samples,batch_latency_samples,index_load_ms,gpu_initialization_ms,index_h2d_ms,gpu_buffer_mib,center_ms,scan_ms,merge_ms +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned4x16,1024,32,100000,15,2026,50,29.3989,34014.9,29.2894,29.9744,1.64589,1.76723,0.94596,0.32,0.00193058893402,0.16803198999999996,5,80,592.455,228.222858,103.40966,1000.404739,2.29152,22.7084,0.603386 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned4x16,1024,64,100000,15,2026,50,37.2287,26861.0,37.1704,37.4512,2.16864,2.20826,0.97214,0.4,0.0009436211343000001,0.11731612700000005,5,80,650.679,228.574469,99.001343,1001.600052,2.59432,30.3215,0.611136 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned4x16,1024,128,100000,15,2026,50,57.793,17303.1,57.7763,57.9775,3.4871,3.52182,0.98718,0.54,0.00042093429500000015,0.074507355,5,80,624.675,224.919206,97.750015,1003.990677,3.26433,50.1918,0.629805 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned4x16,1024,160,100000,15,2026,50,67.8663,14734.8,67.8445,67.9957,4.12883,4.15885,0.99054,0.66,0.00028492993978000014,0.074507355,5,80,628.667,226.838536,99.302399,1005.185989,3.5943,59.8969,0.687155 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned4x16,1024,192,100000,15,2026,50,78.2938,12772.4,78.2749,78.4451,4.79248,4.85242,0.99238,0.66,0.00022508242376000016,0.074507355,5,80,625.165,219.83818,97.390755,1006.381302,3.92787,70.003,0.695942 +WarpFusion,gpu,677305,1000,384,cosine,64,bucket_major_partitioned4x16,1024,224,100000,15,2026,50,89.3739,11189.0,89.1604,90.7402,5.47133,5.56445,0.9938400000000001,0.76,0.00018279215540000014,0.074507355,5,80,629.193,222.462564,99.461121,1007.576614,4.27971,80.129,0.717869 diff --git a/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/partitioned_topk_validation.json b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/partitioned_topk_validation.json new file mode 100644 index 00000000..769e3860 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/real/yahoo-minilm-384/partitioned_topk_validation.json @@ -0,0 +1,110 @@ +{ + "50": { + "selected_mode": "full_heap", + "maximum_allowed_recall_loss": 0.0001, + "comparisons": [ + { + "nprobe": 32, + "partitioned_recall": 0.94596, + "full_heap_recall": 0.9469399999999999, + "partitioned_qps": 34014.9, + "full_heap_qps": 31088.4, + "recall_loss": 0.0009799999999998699 + }, + { + "nprobe": 64, + "partitioned_recall": 0.97214, + "full_heap_recall": 0.97312, + "partitioned_qps": 26861.0, + "full_heap_qps": 26075.4, + "recall_loss": 0.0009799999999999809 + }, + { + "nprobe": 128, + "partitioned_recall": 0.98718, + "full_heap_recall": 0.9881599999999999, + "partitioned_qps": 17303.1, + "full_heap_qps": 17663.5, + "recall_loss": 0.0009799999999999809 + }, + { + "nprobe": 160, + "partitioned_recall": 0.99054, + "full_heap_recall": 0.99152, + "partitioned_qps": 14734.8, + "full_heap_qps": 14949.7, + "recall_loss": 0.0009799999999999809 + }, + { + "nprobe": 192, + "partitioned_recall": 0.99238, + "full_heap_recall": 0.99336, + "partitioned_qps": 12772.4, + "full_heap_qps": 12968.9, + "recall_loss": 0.0009799999999999809 + }, + { + "nprobe": 224, + "partitioned_recall": 0.9938400000000001, + "full_heap_recall": 0.99482, + "partitioned_qps": 11189.0, + "full_heap_qps": 11431.3, + "recall_loss": 0.0009799999999999809 + } + ] + }, + "100": { + "selected_mode": "partitioned", + "maximum_allowed_recall_loss": 0.0001, + "comparisons": [ + { + "nprobe": 32, + "partitioned_recall": 0.937, + "full_heap_recall": 0.937, + "partitioned_qps": 36300.8, + "full_heap_qps": 14462.4, + "recall_loss": 0.0 + }, + { + "nprobe": 64, + "partitioned_recall": 0.9675, + "full_heap_recall": 0.9675, + "partitioned_qps": 27557.5, + "full_heap_qps": 13275.9, + "recall_loss": 0.0 + }, + { + "nprobe": 128, + "partitioned_recall": 0.9851599999999999, + "full_heap_recall": 0.9851599999999999, + "partitioned_qps": 16917.4, + "full_heap_qps": 9555.98, + "recall_loss": 0.0 + }, + { + "nprobe": 160, + "partitioned_recall": 0.98923, + "full_heap_recall": 0.98923, + "partitioned_qps": 14196.2, + "full_heap_qps": 8260.7, + "recall_loss": 0.0 + }, + { + "nprobe": 192, + "partitioned_recall": 0.99185, + "full_heap_recall": 0.99185, + "partitioned_qps": 12183.2, + "full_heap_qps": 7305.64, + "recall_loss": 0.0 + }, + { + "nprobe": 224, + "partitioned_recall": 0.9936799999999999, + "full_heap_recall": 0.9936799999999999, + "partitioned_qps": 10648.6, + "full_heap_qps": 6505.14, + "recall_loss": 0.0 + } + ] + } +} diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_block_tile/smoke/synthetic/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_block_tile/smoke/synthetic/results.csv new file mode 100644 index 00000000..f8835128 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_block_tile/smoke/synthetic/results.csv @@ -0,0 +1,8 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,exact_fused_layout,exact_fused_blocks,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,10,64,1,warp_query,0,144.318,6929.15,144.353,144.475,488.437,143.308,0.179403,results/stage7_exact_block_tile/smoke/synthetic/outputs/baseline/exact_k10.txt +warp_best,1000000,128,1000,10,64,4,warp_query,64,107.937,9264.65,107.945,107.978,488.789,106.992,0.193227,results/stage7_exact_block_tile/smoke/synthetic/outputs/warp_best/exact_k10.txt +block64,1000000,128,1000,10,64,8,block_tile,64,127.981,7813.64,127.983,128.028,488.789,126.986,0.19456,results/stage7_exact_block_tile/smoke/synthetic/outputs/block64/exact_k10.txt +block96,1000000,128,1000,10,64,8,block_tile,96,128.289,7794.89,128.276,128.338,489.023,127.271,0.209867,results/stage7_exact_block_tile/smoke/synthetic/outputs/block96/exact_k10.txt +block128,1000000,128,1000,10,64,8,block_tile,128,110.501,9049.68,110.525,110.587,489.257,109.478,0.222496,results/stage7_exact_block_tile/smoke/synthetic/outputs/block128/exact_k10.txt +block160,1000000,128,1000,10,64,8,block_tile,160,114.417,8739.97,114.366,114.544,489.492,113.375,0.247509,results/stage7_exact_block_tile/smoke/synthetic/outputs/block160/exact_k10.txt +block192,1000000,128,1000,10,64,8,block_tile,192,112.468,8891.39,112.471,112.568,489.726,111.306,0.261931,results/stage7_exact_block_tile/smoke/synthetic/outputs/block192/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_block_tile/smoke/yahoo/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_block_tile/smoke/yahoo/results.csv new file mode 100644 index 00000000..f3e4c174 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_block_tile/smoke/yahoo/results.csv @@ -0,0 +1,8 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,exact_fused_layout,exact_fused_blocks,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,warp_query,0,276.259,3619.8,273.933,282.329,992.364,275.211,0.187712,results/stage7_exact_block_tile/smoke/yahoo/outputs/baseline/exact_k10.txt +warp_best,677305,384,1000,10,64,8,warp_query,160,143.091,6988.56,143.01,143.254,993.419,142.032,0.248512,results/stage7_exact_block_tile/smoke/yahoo/outputs/warp_best/exact_k10.txt +block64,677305,384,1000,10,64,8,block_tile,64,267.849,3733.45,268.055,268.136,992.716,266.743,0.193952,results/stage7_exact_block_tile/smoke/yahoo/outputs/block64/exact_k10.txt +block96,677305,384,1000,10,64,8,block_tile,96,274.073,3648.66,274.36,274.45,992.95,272.968,0.209461,results/stage7_exact_block_tile/smoke/yahoo/outputs/block96/exact_k10.txt +block128,677305,384,1000,10,64,8,block_tile,128,208.578,4794.38,208.393,209.233,993.185,207.503,0.221515,results/stage7_exact_block_tile/smoke/yahoo/outputs/block128/exact_k10.txt +block160,677305,384,1000,10,64,8,block_tile,160,225.601,4432.61,225.549,225.791,993.419,224.466,0.248672,results/stage7_exact_block_tile/smoke/yahoo/outputs/block160/exact_k10.txt +block192,677305,384,1000,10,64,8,block_tile,192,233.273,4286.82,233.268,233.288,993.653,232.133,0.261152,results/stage7_exact_block_tile/smoke/yahoo/outputs/block192/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_baseline/breakdown.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_baseline/breakdown.csv new file mode 100644 index 00000000..f7cfd3c9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_baseline/breakdown.csv @@ -0,0 +1,4 @@ +num_vectors,dim,num_queries,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,distance_only_ms,local_topk_estimated_ms,fused_kernel_ms,final_merge_ms,kernel_pipeline_ms,distance_share,local_topk_share,final_merge_share,result_path +1000000,128,1000,10,64,148.343,6741.14,148.321,150.597,488.437,145.312,2.13207,147.444,0.18549,147.62948999999998,0.9843019846508989,0.01444203322791402,0.001256456281194225,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_baseline/outputs/exact_profile_k10.txt +1000000,128,1000,50,64,164.833,6066.75,165.297,166.813,488.935,146.071,16.8916,162.962,0.828016,163.79001599999998,0.8918187052378089,0.10312960711842169,0.005055350870714855,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_baseline/outputs/exact_profile_k50.txt +1000000,128,1000,100,64,182.551,5477.94,182.487,185.795,489.558,146.649,32.9103,179.559,1.86196,181.42096,0.808335486704513,0.1814029646850066,0.010263202223160984,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_baseline/outputs/exact_profile_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_optimized/breakdown.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_optimized/breakdown.csv new file mode 100644 index 00000000..94fb45be --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_optimized/breakdown.csv @@ -0,0 +1,4 @@ +num_vectors,dim,num_queries,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,distance_only_ms,local_topk_estimated_ms,fused_kernel_ms,final_merge_ms,kernel_pipeline_ms,distance_share,local_topk_share,final_merge_share,result_path +1000000,128,1000,10,64,150.884,6627.6,150.712,153.343,488.437,147.996,1.97462,149.97,0.187618,150.15761799999999,0.9856043401008134,0.013150315157503365,0.0012494737363241872,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_optimized/outputs/exact_profile_k10.txt +1000000,128,1000,50,64,166.862,5992.98,167.2,169.552,488.935,147.771,17.2596,165.03,0.838797,165.868797,0.890890888899375,0.10405573749956117,0.005056990917948238,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_optimized/outputs/exact_profile_k50.txt +1000000,128,1000,100,64,184.321,5425.31,184.607,187.837,489.558,147.835,33.4004,181.236,1.87907,183.11507,0.8073338802753919,0.18240115354787564,0.01026168954854453,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/synthetic1m_optimized/outputs/exact_profile_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_baseline/breakdown.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_baseline/breakdown.csv new file mode 100644 index 00000000..6c250dcc --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_baseline/breakdown.csv @@ -0,0 +1,4 @@ +num_vectors,dim,num_queries,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,distance_only_ms,local_topk_estimated_ms,fused_kernel_ms,final_merge_ms,kernel_pipeline_ms,distance_share,local_topk_share,final_merge_share,result_path +677305,384,1000,10,64,285.991,3496.61,286.103,289.843,992.364,282.23,2.68989,284.919,0.195202,285.114202,0.9898840465337466,0.009434430067429613,0.0006846449550064854,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_baseline/outputs/exact_profile_k10.txt +677305,384,1000,50,64,299.294,3341.2,299.837,305.487,992.862,284.014,12.8595,296.874,0.890322,297.76432200000005,0.9538214588381746,0.04318683955695672,0.0029900224245133027,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_baseline/outputs/exact_profile_k50.txt +677305,384,1000,100,64,316.414,3160.41,316.024,321.712,993.485,282.913,30.1593,313.072,2.01341,315.08541,0.8978930506493461,0.09571785631076983,0.006390045162675098,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_baseline/outputs/exact_profile_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_optimized/breakdown.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_optimized/breakdown.csv new file mode 100644 index 00000000..ffd5621d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_optimized/breakdown.csv @@ -0,0 +1,4 @@ +num_vectors,dim,num_queries,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,distance_only_ms,local_topk_estimated_ms,fused_kernel_ms,final_merge_ms,kernel_pipeline_ms,distance_share,local_topk_share,final_merge_share,result_path +677305,384,1000,10,64,293.485,3407.33,292.798,299.461,994.948,274.714,17.7212,292.435,0.185157,292.620157,0.9388075066886113,0.060560421338301716,0.0006327554530018245,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_optimized/outputs/exact_profile_k10.txt +677305,384,1000,50,64,300.28,3330.23,300.525,305.539,995.446,273.776,24.6115,298.388,0.846878,299.234878,0.9149200849507925,0.08224809943445162,0.002830144686542857,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_optimized/outputs/exact_profile_k50.txt +677305,384,1000,100,64,308.686,3239.53,308.944,313.71,996.069,274.059,31.3277,305.387,1.93324,307.32024,0.8917700962357703,0.10193829082002538,0.006290636763787507,/data/purplepulse-work/PurplePulse/results/stage7_exact_profile/cosine_norm_ab/yahoo_optimized/outputs/exact_profile_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/synthetic1m/breakdown.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/synthetic1m/breakdown.csv new file mode 100644 index 00000000..88e49ac8 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/synthetic1m/breakdown.csv @@ -0,0 +1,4 @@ +num_vectors,dim,num_queries,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,distance_only_ms,local_topk_estimated_ms,fused_kernel_ms,final_merge_ms,kernel_pipeline_ms,distance_share,local_topk_share,final_merge_share,result_path +1000000,128,1000,10,64,148.312,6742.53,149.409,150.703,488.437,144.937,2.37689,147.314,0.185445,147.49944499999998,0.9826274261574343,0.016114569109056648,0.0012572589679913713,results/stage7_exact_profile/synthetic1m/outputs/exact_profile_k10.txt +1000000,128,1000,50,64,164.39,6083.1,164.069,166.782,488.935,145.529,17.1322,162.661,0.826717,163.487717,0.8901524999581467,0.10479197039616132,0.005056752979185586,results/stage7_exact_profile/synthetic1m/outputs/exact_profile_k50.txt +1000000,128,1000,100,64,182.36,5483.66,182.359,185.6,489.558,146.286,33.0835,179.37,1.8608,181.23080000000002,0.8071806778980173,0.18254899277606235,0.01026757041297616,results/stage7_exact_profile/synthetic1m/outputs/exact_profile_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/yahoo-minilm-384/breakdown.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/yahoo-minilm-384/breakdown.csv new file mode 100644 index 00000000..f46787a3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_profile/yahoo-minilm-384/breakdown.csv @@ -0,0 +1,4 @@ +num_vectors,dim,num_queries,top_k,batch_size,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,distance_only_ms,local_topk_estimated_ms,fused_kernel_ms,final_merge_ms,kernel_pipeline_ms,distance_share,local_topk_share,final_merge_share,result_path +677305,384,1000,10,64,283.703,3524.81,283.749,287.772,992.364,279.28,3.3966,282.676,0.193875,282.869875,0.9873090939782824,0.012007641322710663,0.0006853858156511011,results/stage7_exact_profile/yahoo-minilm-384/outputs/exact_profile_k10.txt +677305,384,1000,50,64,297.128,3365.55,298.132,301.107,992.862,280.778,13.6133,294.391,0.883347,295.27434700000003,0.9509054980654991,0.04610390349961556,0.0029916144391642662,results/stage7_exact_profile/yahoo-minilm-384/outputs/exact_profile_k50.txt +677305,384,1000,100,64,315.293,3171.65,314.946,320.001,993.485,281.066,30.7045,311.77,2.00405,313.77405,0.8957592254681354,0.09785544725575618,0.0063869207794589765,results/stage7_exact_profile/yahoo-minilm-384/outputs/exact_profile_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/sift_k10/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/sift_k10/results.csv new file mode 100644 index 00000000..c08230db --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/sift_k10/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,10000,10,64,1,1440.91,6940.08,1442.63,1445.25,488.437,1431.54,1.80152,results/stage7_exact_query_tile/formal/sift_k10/outputs/baseline/exact_k10.txt +tile4,1000000,128,10000,10,64,4,1083.7,9227.65,1083.44,1085.15,488.789,1074.32,1.94307,results/stage7_exact_query_tile/formal/sift_k10/outputs/tile4/exact_k10.txt +tile8,1000000,128,10000,10,64,8,1249.66,8002.19,1249.55,1251.36,489.257,1240.05,2.22865,results/stage7_exact_query_tile/formal/sift_k10/outputs/tile8/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/sift_k50/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/sift_k50/results.csv new file mode 100644 index 00000000..e4c449f4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/sift_k50/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,10000,50,64,1,1614.64,6193.34,1613.93,1618.6,488.935,1596.65,8.04563,results/stage7_exact_query_tile/formal/sift_k50/outputs/baseline/exact_k50.txt +tile2,1000000,128,10000,50,64,2,1678.86,5956.41,1678.08,1682.58,489.521,1659.58,9.09063,results/stage7_exact_query_tile/formal/sift_k50/outputs/tile2/exact_k50.txt +tile4,1000000,128,10000,50,64,4,1815.17,5509.14,1815.15,1817.72,490.693,1792.9,12.0159,results/stage7_exact_query_tile/formal/sift_k50/outputs/tile4/exact_k50.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/synthetic_k10/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/synthetic_k10/results.csv new file mode 100644 index 00000000..07b7d5d9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/synthetic_k10/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,10,64,1,148.4,6738.55,148.281,150.72,488.437,147.509,0.185906,results/stage7_exact_query_tile/formal/synthetic_k10/outputs/baseline/exact_k10.txt +tile4,1000000,128,1000,10,64,4,108.113,9249.56,108.062,108.902,488.789,107.201,0.193621,results/stage7_exact_query_tile/formal/synthetic_k10/outputs/tile4/exact_k10.txt +tile8,1000000,128,1000,10,64,8,124.16,8054.13,124.14,124.527,489.257,123.258,0.222749,results/stage7_exact_query_tile/formal/synthetic_k10/outputs/tile8/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/synthetic_k50/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/synthetic_k50/results.csv new file mode 100644 index 00000000..02d07a40 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/synthetic_k50/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,50,64,1,165.038,6059.22,165.614,167.005,488.935,163.268,0.829941,results/stage7_exact_query_tile/formal/synthetic_k50/outputs/baseline/exact_k50.txt +tile2,1000000,128,1000,50,64,2,167.406,5973.5,167.385,167.861,489.521,165.643,0.91159,results/stage7_exact_query_tile/formal/synthetic_k50/outputs/tile2/exact_k50.txt +tile4,1000000,128,1000,50,64,4,179.957,5556.89,179.917,180.472,490.693,177.9,1.21166,results/stage7_exact_query_tile/formal/synthetic_k50/outputs/tile4/exact_k50.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k10/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k10/results.csv new file mode 100644 index 00000000..608235d0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k10/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,282.932,3534.41,283.266,287.692,992.364,281.68,0.193827,results/stage7_exact_query_tile/formal/yahoo_k10/outputs/baseline/exact_k10.txt +tile4,677305,384,1000,10,64,4,172.99,5780.69,172.903,173.936,992.716,171.953,0.195746,results/stage7_exact_query_tile/formal/yahoo_k10/outputs/tile4/exact_k10.txt +tile8,677305,384,1000,10,64,8,165.936,6026.44,165.689,167.77,993.185,164.89,0.227648,results/stage7_exact_query_tile/formal/yahoo_k10/outputs/tile8/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k10_grid/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k10_grid/results.csv new file mode 100644 index 00000000..0ac279ff --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k10_grid/results.csv @@ -0,0 +1,5 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,279.583,3576.76,279.976,282.94,992.364,278.604,0.189806,results/stage7_exact_query_tile/formal/yahoo_k10_grid/outputs/baseline/exact_k10.txt +tile8b96,677305,384,1000,10,64,8,155.005,6451.4,154.98,155.297,992.95,153.982,0.209971,results/stage7_exact_query_tile/formal/yahoo_k10_grid/outputs/tile8b96/exact_k10.txt +tile8b160,677305,384,1000,10,64,8,148.22,6746.74,148.701,150.207,993.419,147.163,0.258874,results/stage7_exact_query_tile/formal/yahoo_k10_grid/outputs/tile8b160/exact_k10.txt +tile8b192,677305,384,1000,10,64,8,161.791,6180.83,161.839,165.113,993.653,160.523,0.273869,results/stage7_exact_query_tile/formal/yahoo_k10_grid/outputs/tile8b192/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k50/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k50/results.csv new file mode 100644 index 00000000..28f87b5f --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/formal/yahoo_k50/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,50,64,1,297.321,3363.36,298.175,300.758,992.862,295.338,0.884942,results/stage7_exact_query_tile/formal/yahoo_k50/outputs/baseline/exact_k50.txt +tile2,677305,384,1000,50,64,2,282.258,3542.85,282.201,282.68,993.448,280.25,0.91304,results/stage7_exact_query_tile/formal/yahoo_k50/outputs/tile2/exact_k50.txt +tile4,677305,384,1000,50,64,4,245.484,4073.59,245.404,246.268,994.62,243.265,1.21372,results/stage7_exact_query_tile/formal/yahoo_k50/outputs/tile4/exact_k50.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/sift/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/sift/results.csv new file mode 100644 index 00000000..971f32ac --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/sift/results.csv @@ -0,0 +1,7 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,10000,10,64,1,1419.46,7044.92,1420.71,1420.97,488.437,1409.63,1.77203,results/stage7_exact_query_tile/grid_sweep_smoke/sift/outputs/baseline/exact_k10.txt +b48,1000000,128,10000,10,64,4,1401.5,7135.21,1400.22,1404.32,488.671,1391.46,1.83397,results/stage7_exact_query_tile/grid_sweep_smoke/sift/outputs/b48/exact_k10.txt +b64,1000000,128,10000,10,64,4,1081.66,9245.07,1082.62,1082.77,488.789,1069.38,1.93764,results/stage7_exact_query_tile/grid_sweep_smoke/sift/outputs/b64/exact_k10.txt +b80,1000000,128,10000,10,64,4,1165.8,8577.83,1165.78,1166.72,488.906,1156.29,2.0629,results/stage7_exact_query_tile/grid_sweep_smoke/sift/outputs/b80/exact_k10.txt +b96,1000000,128,10000,10,64,4,1167.56,8564.9,1167.57,1168.89,489.023,1157.08,2.09634,results/stage7_exact_query_tile/grid_sweep_smoke/sift/outputs/b96/exact_k10.txt +b128,1000000,128,10000,10,64,4,1108.76,9019.09,1108.76,1109.19,489.257,1098.89,2.2765,results/stage7_exact_query_tile/grid_sweep_smoke/sift/outputs/b128/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/results.csv new file mode 100644 index 00000000..5f13e51a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/results.csv @@ -0,0 +1,7 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,10,64,1,144.327,6928.73,144.353,144.507,488.437,143.409,0.180853,results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/outputs/baseline/exact_k10.txt +b48,1000000,128,1000,10,64,4,137.91,7251.11,137.898,137.98,488.671,136.996,0.182005,results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/outputs/b48/exact_k10.txt +b64,1000000,128,1000,10,64,4,108.217,9240.66,108.29,108.299,488.789,107.135,0.193525,results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/outputs/b64/exact_k10.txt +b80,1000000,128,1000,10,64,4,117.234,8529.92,117.126,117.468,488.906,116.217,0.209515,results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/outputs/b80/exact_k10.txt +b96,1000000,128,1000,10,64,4,115.928,8626.03,115.844,116.125,489.023,114.927,0.209259,results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/outputs/b96/exact_k10.txt +b128,1000000,128,1000,10,64,4,109.236,9154.46,109.204,109.376,489.257,108.28,0.227925,results/stage7_exact_query_tile/grid_sweep_smoke/synthetic/outputs/b128/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/results.csv new file mode 100644 index 00000000..a9c90c11 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/results.csv @@ -0,0 +1,7 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,281.815,3548.43,279.12,289.263,992.364,280.821,0.192853,results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/outputs/baseline/exact_k10.txt +tile4b64,677305,384,1000,10,64,4,172.696,5790.53,172.792,172.878,992.716,171.699,0.195808,results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/outputs/tile4b64/exact_k10.txt +tile8b96,677305,384,1000,10,64,8,154.405,6476.45,154.43,154.607,992.95,153.403,0.205579,results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/outputs/tile8b96/exact_k10.txt +tile8b128,677305,384,1000,10,64,8,164.453,6080.77,164.162,165.051,993.185,163.424,0.224533,results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/outputs/tile8b128/exact_k10.txt +tile8b160,677305,384,1000,10,64,8,145.189,6887.55,145.205,145.243,993.419,144.154,0.254208,results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/outputs/tile8b160/exact_k10.txt +tile8b192,677305,384,1000,10,64,8,158.742,6299.54,158.723,158.9,993.653,157.687,0.268971,results/stage7_exact_query_tile/grid_sweep_smoke/yahoo/outputs/tile8b192/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/results.csv new file mode 100644 index 00000000..eb66cd5e --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/results.csv @@ -0,0 +1,10 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,10,64,1,144.322,6928.96,144.326,144.484,488.437,143.405,0.181024,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/baseline/exact_k10.txt +baseline,1000000,128,1000,50,64,1,159.416,6272.88,159.487,159.83,488.935,157.621,0.799499,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/baseline/exact_k50.txt +baseline,1000000,128,1000,100,64,1,176.94,5651.64,177.059,177.241,489.558,173.815,1.80062,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/baseline/exact_k100.txt +tile2,1000000,128,1000,10,64,2,155.53,6429.62,155.525,155.568,488.554,154.618,0.179424,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/tile2/exact_k10.txt +tile2,1000000,128,1000,50,64,2,167.2,5980.88,167.148,167.354,489.521,165.295,0.909653,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/tile2/exact_k50.txt +tile2,1000000,128,1000,100,64,2,258.83,3863.53,258.864,258.93,490.729,255.229,2.29613,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/tile2/exact_k100.txt +tile4,1000000,128,1000,10,64,4,108.063,9253.86,108.035,108.12,488.789,107.147,0.193248,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/tile4/exact_k10.txt +tile4,1000000,128,1000,50,64,4,179.836,5560.61,179.889,179.969,490.693,177.511,1.20859,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/tile4/exact_k50.txt +tile4,1000000,128,1000,100,64,4,311.977,3205.37,311.897,312.184,493.073,303.926,6.71577,results/stage7_exact_query_tile/scaled_grid_smoke/synthetic1m/outputs/tile4/exact_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/results.csv new file mode 100644 index 00000000..48f8a757 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/results.csv @@ -0,0 +1,10 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,276.786,3612.9,273.801,283.9,992.364,275.793,0.186955,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/baseline/exact_k10.txt +baseline,677305,384,1000,50,64,1,287.502,3478.24,282.853,296.864,992.862,285.579,0.851019,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/baseline/exact_k50.txt +baseline,677305,384,1000,100,64,1,306.175,3266.11,303.427,314.989,993.485,302.749,1.93477,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/baseline/exact_k100.txt +tile2,677305,384,1000,10,64,2,273.55,3655.63,273.601,273.631,992.481,272.532,0.179893,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/tile2/exact_k10.txt +tile2,677305,384,1000,50,64,2,281.422,3553.38,281.261,281.774,993.448,279.484,0.907637,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/tile2/exact_k50.txt +tile2,677305,384,1000,100,64,2,430.109,2324.99,430.126,430.181,994.657,425.991,2.29615,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/tile2/exact_k100.txt +tile4,677305,384,1000,10,64,4,172.223,5806.42,172.072,172.564,992.716,171.208,0.195893,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/tile4/exact_k10.txt +tile4,677305,384,1000,50,64,4,244.817,4084.68,244.819,244.932,994.62,242.611,1.20675,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/tile4/exact_k50.txt +tile4,677305,384,1000,100,64,4,438.85,2278.68,438.846,439.097,997.0,430.492,6.69938,results/stage7_exact_query_tile/scaled_grid_smoke/yahoo/outputs/tile4/exact_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/smoke/synthetic1m/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/smoke/synthetic1m/results.csv new file mode 100644 index 00000000..4fbace69 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/smoke/synthetic1m/results.csv @@ -0,0 +1,10 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,10,64,1,144.492,6920.78,144.478,144.568,488.437,143.571,0.179381,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/baseline/exact_k10.txt +baseline,1000000,128,1000,50,64,1,159.407,6273.26,159.396,159.543,488.935,157.604,0.797781,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/baseline/exact_k50.txt +baseline,1000000,128,1000,100,64,1,176.951,5651.27,176.837,177.386,489.558,173.766,1.80062,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/baseline/exact_k100.txt +tile2,1000000,128,1000,10,64,2,157.074,6366.42,157.068,157.177,488.437,156.117,0.166123,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/tile2/exact_k10.txt +tile2,1000000,128,1000,50,64,2,162.361,6159.13,162.333,162.425,488.935,160.603,0.750944,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/tile2/exact_k50.txt +tile2,1000000,128,1000,100,64,2,317.018,3154.4,316.998,317.379,489.558,313.943,1.72026,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/tile2/exact_k100.txt +tile4,1000000,128,1000,10,64,4,183.473,5450.4,183.454,183.512,488.437,182.569,0.169333,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/tile4/exact_k10.txt +tile4,1000000,128,1000,50,64,4,190.591,5246.83,190.522,190.759,488.935,188.841,0.751019,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/tile4/exact_k50.txt +tile4,1000000,128,1000,100,64,4,388.451,2574.33,388.913,389.133,489.558,385.257,1.71516,results/stage7_exact_query_tile/smoke/synthetic1m/outputs/tile4/exact_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/smoke/yahoo/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/smoke/yahoo/results.csv new file mode 100644 index 00000000..72658165 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/smoke/yahoo/results.csv @@ -0,0 +1,10 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,276.616,3615.12,273.955,283.176,992.364,275.631,0.187733,results/stage7_exact_query_tile/smoke/yahoo/outputs/baseline/exact_k10.txt +baseline,677305,384,1000,50,64,1,287.947,3472.86,283.954,296.233,992.862,285.89,0.856,results/stage7_exact_query_tile/smoke/yahoo/outputs/baseline/exact_k50.txt +baseline,677305,384,1000,100,64,1,305.241,3276.09,301.596,314.124,993.485,301.766,1.92579,results/stage7_exact_query_tile/smoke/yahoo/outputs/baseline/exact_k100.txt +tile2,677305,384,1000,10,64,2,278.579,3589.64,278.699,278.702,992.364,277.589,0.167648,results/stage7_exact_query_tile/smoke/yahoo/outputs/tile2/exact_k10.txt +tile2,677305,384,1000,50,64,2,282.455,3540.39,282.456,282.583,992.862,280.639,0.755019,results/stage7_exact_query_tile/smoke/yahoo/outputs/tile2/exact_k50.txt +tile2,677305,384,1000,100,64,2,548.787,1822.2,548.469,550.376,993.485,544.814,1.72404,results/stage7_exact_query_tile/smoke/yahoo/outputs/tile2/exact_k100.txt +tile4,677305,384,1000,10,64,4,297.312,3363.47,297.352,297.41,992.364,296.289,0.169515,results/stage7_exact_query_tile/smoke/yahoo/outputs/tile4/exact_k10.txt +tile4,677305,384,1000,50,64,4,302.735,3303.22,302.704,303.015,992.862,300.718,0.755563,results/stage7_exact_query_tile/smoke/yahoo/outputs/tile4/exact_k50.txt +tile4,677305,384,1000,100,64,4,608.46,1643.49,608.515,608.763,993.485,604.992,1.72365,results/stage7_exact_query_tile/smoke/yahoo/outputs/tile4/exact_k100.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/tile8_smoke/synthetic1m/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/tile8_smoke/synthetic1m/results.csv new file mode 100644 index 00000000..764b6241 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/tile8_smoke/synthetic1m/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,1000000,128,1000,10,64,1,144.391,6925.65,144.49,144.516,488.437,143.458,0.180992,results/stage7_exact_query_tile/tile8_smoke/synthetic1m/outputs/baseline/exact_k10.txt +tile4,1000000,128,1000,10,64,4,108.02,9257.58,108.021,108.08,488.789,107.096,0.194528,results/stage7_exact_query_tile/tile8_smoke/synthetic1m/outputs/tile4/exact_k10.txt +tile8,1000000,128,1000,10,64,8,124.133,8055.87,124.209,124.216,489.257,123.157,0.222187,results/stage7_exact_query_tile/tile8_smoke/synthetic1m/outputs/tile8/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/tile8_smoke/yahoo/results.csv b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/tile8_smoke/yahoo/results.csv new file mode 100644 index 00000000..8f3fc037 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage7_exact_query_tile/tile8_smoke/yahoo/results.csv @@ -0,0 +1,4 @@ +variant,num_vectors,dim,num_queries,top_k,batch_size,exact_query_tile,average_query_ms,qps,run_p50_ms,run_p99_ms,gpu_buffer_mib,fused_kernel_ms,final_merge_ms,result_path +baseline,677305,384,1000,10,64,1,274.924,3637.37,272.243,281.643,992.364,273.935,0.186016,results/stage7_exact_query_tile/tile8_smoke/yahoo/outputs/baseline/exact_k10.txt +tile4,677305,384,1000,10,64,4,171.876,5818.16,171.869,172.108,992.716,170.885,0.193248,results/stage7_exact_query_tile/tile8_smoke/yahoo/outputs/tile4/exact_k10.txt +tile8,677305,384,1000,10,64,8,163.674,6109.69,163.62,163.812,993.185,162.632,0.22528,results/stage7_exact_query_tile/tile8_smoke/yahoo/outputs/tile8/exact_k10.txt diff --git a/09_vector_retrieval/PurplePulse/results/stage8_stability/coverage.csv b/09_vector_retrieval/PurplePulse/results/stage8_stability/coverage.csv new file mode 100644 index 00000000..4c739814 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/results/stage8_stability/coverage.csv @@ -0,0 +1,10 @@ +suite,cases,status,details +exact_cross_product,576,passed,"dim=64/128/384/768; batch=1/8/32/40/64/128; K=1/10/50/100; FP32/FP16; L2/IP/cosine" +exact_full_batch_boundary,6,passed,"dim=65; query_count=batch+1; batch=1/8/32/40/64/128" +exact_non_warp_dimension,6,passed,"dim=65; K=100; FP32/FP16; L2/IP/cosine" +exact_recommended_paths,3,passed,"128/K10/tile4/64; 384/K10/tile8/160; 384/K50/tile4/64" +exact_safe_fallback,2,passed,"FP32 dim768 block-tile rejected then warp-query passed; K50/tile8 rejected then tile1 passed" +ivf_empty_skewed_buckets,48,passed,"dim=65; 4 empty buckets; largest bucket=125/128; K=1/10/50/100; FP32/FP16; L2/IP/cosine; warp/bucket-major" +ctest,14,passed,"all project tests" +python_unittest,29,passed,"2 skipped because local h5py is unavailable" +compute_sanitizer,1,passed,"memcheck ERROR SUMMARY: 0 errors" diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_adaptive_nprobe.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_adaptive_nprobe.py new file mode 100644 index 00000000..62d19056 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_adaptive_nprobe.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""扫描 score-mass 自适应 nprobe 参数并输出质量、性能和实际 probe CSV。""" + +import argparse +import csv +import re +import subprocess +from pathlib import Path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--index", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument("--params", required=True) + parser.add_argument("--exact", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--csv", required=True) + parser.add_argument("--max-nprobe", type=int, required=True) + parser.add_argument("--min-nprobe", type=int, required=True) + parser.add_argument("--step", type=int, default=16) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--execution", choices=("masked", "grouped"), + default="masked") + parser.add_argument("--target-masses", required=True, + help="逗号分隔,例如 0.70,0.80,0.90") + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + return parser.parse_args() + + +def read_ids(path: Path) -> list[list[int]]: + rows: dict[int, list[int]] = {} + for line_number, line in enumerate(path.read_text().splitlines(), 1): + fields = line.split() + if len(fields) != 3: + raise ValueError(f"{path}:{line_number}: 结果行必须有三列") + query_id, vector_id = int(fields[0]), int(fields[1]) + rows.setdefault(query_id, []).append(vector_id) + return [rows[query_id] for query_id in sorted(rows)] + + +def recall(exact: list[list[int]], approximate: list[list[int]]) -> tuple[float, float]: + if len(exact) != len(approximate) or not exact: + raise ValueError("exact 与 approximate 的 query 数不一致或为空") + recalls = [] + for expected, actual in zip(exact, approximate): + if len(expected) != len(actual) or not expected: + raise ValueError("exact 与 approximate 的 K 不一致或为空") + recalls.append(len(set(expected) & set(actual)) / len(expected)) + return sum(recalls) / len(recalls), min(recalls) + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"无法从 ivf_search 输出解析字段: {pattern}") + return float(match.group(1)) + + +def extract_pair(text: str, pattern: str) -> tuple[float, float]: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"无法从 ivf_search 输出解析字段: {pattern}") + return float(match.group(1)), float(match.group(2)) + + +def extract_triple(text: str, pattern: str) -> tuple[float, float, float]: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"无法从 ivf_search 输出解析字段: {pattern}") + return float(match.group(1)), float(match.group(2)), float(match.group(3)) + + +def main() -> None: + args = parse_args() + masses = [float(value) for value in args.target_masses.split(",")] + if (not masses or any(value <= 0.0 or value > 1.0 for value in masses) or + args.min_nprobe <= 0 or args.min_nprobe > args.max_nprobe or + args.step <= 0 or args.temperature <= 0.0): + raise ValueError("自适应 nprobe 参数不合法") + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + csv_path = Path(args.csv) + csv_path.parent.mkdir(parents=True, exist_ok=True) + exact_ids = read_ids(Path(args.exact)) + rows = [] + for target_mass in masses: + label = f"{target_mass:.4f}".rstrip("0").rstrip(".").replace(".", "p") + result_path = output_dir / f"mass_{label}.txt" + counts_path = output_dir / f"mass_{label}_nprobes.txt" + command = [ + args.search_binary, + "--index", args.index, + "--queries", args.queries, + "--params", args.params, + "--nprobe", str(args.max_nprobe), + "--nprobe-policy", "score_mass", + "--adaptive-execution", args.execution, + "--adaptive-nprobe-min", str(args.min_nprobe), + "--adaptive-nprobe-step", str(args.step), + "--adaptive-target-mass", str(target_mass), + "--adaptive-temperature", str(args.temperature), + "--backend", "gpu", + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + "--output", str(result_path), + "--probe-counts-output", str(counts_path), + ] + completed = subprocess.run(command, check=True, text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + print(completed.stdout, end="") + approximate_ids = read_ids(result_path) + recall_at_k, minimum_recall = recall(exact_ids, approximate_ids) + actual_min, actual_average, actual_max = extract_triple( + completed.stdout, + r"实际 nprobe min/avg/max: ([0-9.eE+-]+)/([0-9.eE+-]+)/([0-9.eE+-]+)", + ) + batch_p50_ms, batch_p99_ms = extract_pair( + completed.stdout, r"batch P50/P99: ([0-9.eE+-]+)/([0-9.eE+-]+) ms" + ) + row = { + "policy": "score_mass", + "execution": args.execution, + "target_mass": target_mass, + "temperature": args.temperature, + "min_nprobe": args.min_nprobe, + "max_nprobe": args.max_nprobe, + "step": args.step, + "actual_nprobe_min": actual_min, + "actual_nprobe_average": actual_average, + "actual_nprobe_max": actual_max, + "average_ms": extract(completed.stdout, r"平均查询: ([0-9.eE+-]+) ms"), + "qps": extract(completed.stdout, r"QPS: ([0-9.eE+-]+)"), + "batch_p50_ms": batch_p50_ms, + "batch_p99_ms": batch_p99_ms, + "recall_at_k": recall_at_k, + "min_query_recall": minimum_recall, + "center_ms": extract( + completed.stdout, r"平均 GPU 中心选择: ([0-9.eE+-]+) ms" + ), + "policy_ms": extract( + completed.stdout, r"平均自适应分层开销: ([0-9.eE+-]+) ms" + ), + "scan_ms": extract( + completed.stdout, r"平均 GPU 桶扫描\+局部 Top-K: ([0-9.eE+-]+) ms" + ), + "merge_ms": extract( + completed.stdout, r"平均 GPU 最终 Top-K 归并: ([0-9.eE+-]+) ms" + ), + "gpu_buffer_mib": extract( + completed.stdout, r"GPU 缓冲区: ([0-9.eE+-]+) MiB" + ), + } + rows.append(row) + with csv_path.open("w", newline="") as csv_file: + writer = csv.DictWriter(csv_file, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + print(f"recall={recall_at_k:.6f}, actual_avg_nprobe={actual_average:.3f}") + print(f"CSV: {csv_path}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_exact.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact.py new file mode 100644 index 00000000..a077a9d4 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Benchmark WarpFusion Exact for several K values and write one stable CSV.""" + +from __future__ import annotations + +import argparse +import csv +import re +import subprocess +from pathlib import Path + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"cannot parse vector_search output: {pattern}") + return float(match.group(1)) + + +def parse_configs(text: str) -> list[tuple[int, Path]]: + result = [] + for item in text.split(","): + fields = item.split(":", 1) + if len(fields) != 2: + raise ValueError("configs must use K:path,K:path syntax") + top_k, path = int(fields[0]), Path(fields[1]) + if top_k <= 0 or not path.is_file(): + raise ValueError(f"invalid Exact config: {item}") + result.append((top_k, path)) + if not result: + raise ValueError("at least one Exact config is required") + return result + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="") as output: + writer = csv.DictWriter(output, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--database", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument("--configs", required=True, help="K:path,K:path") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--csv", type=Path, required=True) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + args = parser.parse_args() + if args.warmup < 0 or args.repeat <= 0: + raise ValueError("warmup must be non-negative and repeat must be positive") + + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for expected_k, config in parse_configs(args.configs): + result_path = args.output_dir / f"exact_k{expected_k}.txt" + command = [ + args.search_binary, + "--database", args.database, + "--queries", args.queries, + "--params", str(config), + "--backend", "gpu", + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + "--output", str(result_path), + ] + completed = subprocess.run( + command, + check=True, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + print(completed.stdout, end="") + top_k = int(extract(completed.stdout, r"top_k: (\d+)")) + if top_k != expected_k: + raise ValueError(f"config {config} produced K={top_k}, expected {expected_k}") + row: dict[str, object] = { + "implementation": "WarpFusion Exact fused", + "top_k": top_k, + "batch_size": int(extract(completed.stdout, r"batch_size: (\d+)")), + "average_query_ms": extract( + completed.stdout, r"平均常驻查询时间: ([0-9.eE+-]+) ms" + ), + "qps": extract(completed.stdout, r"常驻 QPS: ([0-9.eE+-]+)"), + "run_p50_ms": extract(completed.stdout, r"run P50: ([0-9.eE+-]+) ms"), + "run_p99_ms": extract(completed.stdout, r"run P99: ([0-9.eE+-]+) ms"), + "run_samples": int(extract(completed.stdout, r"run samples: (\d+)")), + "batch_p50_ms": extract(completed.stdout, r"batch P50: ([0-9.eE+-]+) ms"), + "batch_p99_ms": extract(completed.stdout, r"batch P99: ([0-9.eE+-]+) ms"), + "batch_latency_samples": int( + extract(completed.stdout, r"batch samples: (\d+)") + ), + "gpu_initialization_ms": extract( + completed.stdout, r"GPU 一次性初始化总时间: ([0-9.eE+-]+) ms" + ), + "database_h2d_ms": extract( + completed.stdout, r"数据库一次性 H2D: ([0-9.eE+-]+) ms" + ), + "gpu_buffer_mib": extract( + completed.stdout, r"GPU 缓冲区: ([0-9.eE+-]+) MiB" + ), + "query_h2d_ms": extract( + completed.stdout, r"平均查询 H2D: ([0-9.eE+-]+) ms" + ), + "distance_and_local_topk_ms": extract( + completed.stdout, + r"平均融合距离\+局部 Top-K kernel: ([0-9.eE+-]+) ms", + ), + "final_topk_ms": extract( + completed.stdout, r"平均最终 Top-K kernel: ([0-9.eE+-]+) ms" + ), + "result_d2h_ms": extract( + completed.stdout, r"平均结果 D2H: ([0-9.eE+-]+) ms" + ), + "result_path": str(result_path), + } + rows.append(row) + write_csv(args.csv, rows) + print(f"CSV: {args.csv}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_breakdown.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_breakdown.py new file mode 100644 index 00000000..5ad672f9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_breakdown.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Profile fused Exact distance, local selection, and final merge by K.""" + +from __future__ import annotations + +import argparse +import csv +import re +import subprocess +from pathlib import Path + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"cannot parse vector_search output: {pattern}") + return float(match.group(1)) + + +def parse_k_paths(text: str) -> list[tuple[int, Path]]: + result = [] + for item in text.split(","): + fields = item.split(":", 1) + if len(fields) != 2: + raise ValueError("paths must use K:path,K:path syntax") + top_k, path = int(fields[0]), Path(fields[1]) + if top_k <= 0 or not path.is_file(): + raise ValueError(f"invalid K:path item: {item}") + result.append((top_k, path)) + if not result: + raise ValueError("at least one K:path item is required") + return result + + +def read_results(path: Path) -> dict[int, list[tuple[int, float]]]: + queries: dict[int, list[tuple[int, float]]] = {} + for line_number, line in enumerate(path.read_text().splitlines(), 1): + fields = line.split() + if len(fields) != 3: + raise ValueError(f"{path}:{line_number}: expected three columns") + query_id, vector_id, score = int(fields[0]), int(fields[1]), float(fields[2]) + queries.setdefault(query_id, []).append((vector_id, score)) + return queries + + +def compare_results(expected_path: Path, actual_path: Path, tolerance: float) -> None: + expected = read_results(expected_path) + actual = read_results(actual_path) + if expected.keys() != actual.keys(): + raise ValueError("profile and reference query sets differ") + for query_id in expected: + if len(expected[query_id]) != len(actual[query_id]): + raise ValueError(f"query {query_id} Top-K lengths differ") + for rank, (expected_item, actual_item) in enumerate( + zip(expected[query_id], actual[query_id]) + ): + expected_id, expected_score = expected_item + actual_id, actual_score = actual_item + if expected_id != actual_id: + raise ValueError( + f"query {query_id} rank {rank} IDs differ: " + f"{expected_id} != {actual_id}" + ) + error = abs(expected_score - actual_score) + if error > tolerance: + raise ValueError( + f"query {query_id} rank {rank} score error {error} " + f"exceeds {tolerance}" + ) + + +def parse_profile_output(text: str) -> dict[str, object]: + fused_ms = extract(text, r"剖析融合 kernel: ([0-9.eE+-]+) ms") + distance_ms = extract(text, r"剖析距离-only kernel: ([0-9.eE+-]+) ms") + local_ms = extract(text, r"剖析局部 Top-K 估算: ([0-9.eE+-]+) ms") + merge_ms = extract(text, r"剖析最终归并 kernel: ([0-9.eE+-]+) ms") + pipeline_ms = fused_ms + merge_ms + return { + "num_vectors": int(extract(text, r"向量库: (\d+) x")), + "dim": int(extract(text, r"向量库: \d+ x (\d+)")), + "num_queries": int(extract(text, r"查询数: (\d+)")), + "top_k": int(extract(text, r"top_k: (\d+)")), + "batch_size": int(extract(text, r"batch_size: (\d+)")), + "average_query_ms": extract( + text, r"平均常驻查询时间: ([0-9.eE+-]+) ms" + ), + "qps": extract(text, r"常驻 QPS: ([0-9.eE+-]+)"), + "run_p50_ms": extract(text, r"run P50: ([0-9.eE+-]+) ms"), + "run_p99_ms": extract(text, r"run P99: ([0-9.eE+-]+) ms"), + "gpu_buffer_mib": extract(text, r"GPU 缓冲区: ([0-9.eE+-]+) MiB"), + "distance_only_ms": distance_ms, + "local_topk_estimated_ms": local_ms, + "fused_kernel_ms": fused_ms, + "final_merge_ms": merge_ms, + "kernel_pipeline_ms": pipeline_ms, + "distance_share": distance_ms / pipeline_ms if pipeline_ms else 0.0, + "local_topk_share": local_ms / pipeline_ms if pipeline_ms else 0.0, + "final_merge_share": merge_ms / pipeline_ms if pipeline_ms else 0.0, + } + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="") as output: + writer = csv.DictWriter(output, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--database", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument("--configs", required=True, help="K:path,K:path") + parser.add_argument("--reference-results", help="optional K:path,K:path") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--csv", type=Path, required=True) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--profile-repeat", type=int, default=5) + parser.add_argument("--tolerance", type=float, default=5e-5) + args = parser.parse_args() + if args.warmup < 0 or args.repeat <= 0 or args.profile_repeat <= 0: + raise ValueError("warmup must be non-negative and repeats must be positive") + + configs = parse_k_paths(args.configs) + references = ( + dict(parse_k_paths(args.reference_results)) + if args.reference_results + else {} + ) + if references and set(references) != {top_k for top_k, _ in configs}: + raise ValueError("reference-results must cover the same K values as configs") + + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for expected_k, config in configs: + result_path = args.output_dir / f"exact_profile_k{expected_k}.txt" + command = [ + args.search_binary, + "--database", args.database, + "--queries", args.queries, + "--params", str(config), + "--backend", "gpu", + "--output", str(result_path), + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + "--profile-breakdown", "1", + "--profile-repeat", str(args.profile_repeat), + ] + completed = subprocess.run( + command, + check=True, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + print(completed.stdout, end="") + row = parse_profile_output(completed.stdout) + if row["top_k"] != expected_k: + raise ValueError( + f"config {config} produced K={row['top_k']}, expected {expected_k}" + ) + if references: + compare_results(references[expected_k], result_path, args.tolerance) + row["result_path"] = str(result_path) + rows.append(row) + write_csv(args.csv, rows) + print(f"CSV: {args.csv}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_fused.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_fused.py new file mode 100644 index 00000000..a30e5cf0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_fused.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Compare matrix-based and fused exact-search modes and write a CSV.""" + +import argparse +import csv +import re +import subprocess +from pathlib import Path + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"无法解析字段: {pattern}") + return float(match.group(1)) + + +def read_results(path: Path) -> dict[int, dict[int, float]]: + queries: dict[int, dict[int, float]] = {} + for line_number, line in enumerate(path.read_text().splitlines(), 1): + fields = line.split() + if len(fields) != 3: + raise ValueError(f"{path}:{line_number}: 结果行必须有三列") + query_id, vector_id, score = int(fields[0]), int(fields[1]), float(fields[2]) + queries.setdefault(query_id, {})[vector_id] = score + return queries + + +def compare_results(expected_path: Path, actual_path: Path, + tolerance: float) -> tuple[float, float]: + expected = read_results(expected_path) + actual = read_results(actual_path) + if expected.keys() != actual.keys(): + raise ValueError("baseline 与 fused 的 query 集合不同") + maximum_error = 0.0 + error_sum = 0.0 + error_count = 0 + for query_id in expected: + if expected[query_id].keys() != actual[query_id].keys(): + raise ValueError(f"query {query_id} 的 Top-K 候选集合不同") + for vector_id, score in expected[query_id].items(): + error = abs(score - actual[query_id][vector_id]) + maximum_error = max(maximum_error, error) + error_sum += error + error_count += 1 + if maximum_error > tolerance: + raise ValueError( + f"最大分数误差 {maximum_error} 超过容差 {tolerance}" + ) + return error_sum / error_count if error_count else 0.0, maximum_error + + +def run_search(args: argparse.Namespace, config: str, output: Path) -> tuple[str, dict]: + command = [ + args.search_binary, + "--database", args.database, + "--queries", args.queries, + "--params", config, + "--backend", "gpu", + "--output", str(output), + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + ] + completed = subprocess.run( + command, check=True, text=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT + ) + text = completed.stdout + print(text, end="") + row = { + "top_k": int(extract(text, r"top_k: (\d+)")), + "average_ms": extract(text, r"平均常驻查询时间: ([0-9.eE+-]+) ms"), + "qps": extract(text, r"常驻 QPS: ([0-9.eE+-]+)"), + "run_p50_ms": extract(text, r"run P50: ([0-9.eE+-]+) ms"), + "run_p99_ms": extract(text, r"run P99: ([0-9.eE+-]+) ms"), + "run_samples": int(extract(text, r"run samples: (\d+)")), + "batch_latency_samples": int(extract(text, r"batch samples: (\d+)")), + "gpu_buffer_mib": extract(text, r"GPU 缓冲区: ([0-9.eE+-]+) MiB"), + "initialization_ms": extract( + text, r"GPU 一次性初始化总时间: ([0-9.eE+-]+) ms" + ), + "distance_or_fused_ms": extract( + text, + r"平均(?:距离|融合距离\+局部 Top-K) kernel: ([0-9.eE+-]+) ms", + ), + "final_topk_ms": extract( + text, r"平均最终 Top-K kernel: ([0-9.eE+-]+) ms" + ), + } + return text, row + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--database", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument("--baseline-configs", required=True) + parser.add_argument("--fused-configs", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--csv", required=True) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--tolerance", type=float, default=5e-5) + args = parser.parse_args() + + baseline_configs = args.baseline_configs.split(",") + fused_configs = args.fused_configs.split(",") + if len(baseline_configs) != len(fused_configs) or not baseline_configs: + parser.error("baseline-configs 与 fused-configs 必须是一一对应的非空列表") + + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for baseline_config, fused_config in zip(baseline_configs, fused_configs): + baseline_path = output_dir / f"baseline_{len(rows) // 2}.txt" + _, baseline = run_search(args, baseline_config, baseline_path) + baseline["mode"] = "matrix" + baseline["mean_absolute_score_error"] = 0.0 + baseline["maximum_score_error"] = 0.0 + + fused_path = output_dir / f"fused_{len(rows) // 2}.txt" + _, fused = run_search(args, fused_config, fused_path) + if baseline["top_k"] != fused["top_k"]: + raise ValueError("成对配置的 top_k 不一致") + fused["mode"] = "fused" + fused["mean_absolute_score_error"], fused["maximum_score_error"] = compare_results( + baseline_path, fused_path, args.tolerance + ) + rows.extend((baseline, fused)) + + csv_path = Path(args.csv) + csv_path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = [ + "top_k", "mode", "average_ms", "qps", "run_p50_ms", "run_p99_ms", + "run_samples", "batch_latency_samples", "gpu_buffer_mib", + "initialization_ms", "distance_or_fused_ms", "final_topk_ms", + "mean_absolute_score_error", "maximum_score_error", + ] + with csv_path.open("w", newline="") as csv_file: + writer = csv.DictWriter(csv_file, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + print(f"CSV: {csv_path}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_query_tile.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_query_tile.py new file mode 100644 index 00000000..bcca5e90 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_exact_query_tile.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Benchmark Exact fused query-tile variants with strict result validation.""" + +from __future__ import annotations + +import argparse +import csv +import re +import subprocess +from pathlib import Path + +from benchmark_exact_breakdown import compare_results, extract, parse_k_paths + + +def parse_variant(text: str) -> tuple[str, list[tuple[int, Path]]]: + fields = text.split("=", 1) + if len(fields) != 2 or not re.fullmatch(r"[A-Za-z0-9_-]+", fields[0]): + raise ValueError("variant must use label=K:path,K:path syntax") + return fields[0], parse_k_paths(fields[1]) + + +def parse_search_output(text: str, label: str) -> dict[str, object]: + layout = re.search(r"exact_fused_layout: ([A-Za-z0-9_-]+)", text) + if layout is None: + raise ValueError("cannot parse exact_fused_layout") + return { + "variant": label, + "num_vectors": int(extract(text, r"向量库: (\d+) x")), + "dim": int(extract(text, r"向量库: \d+ x (\d+)")), + "num_queries": int(extract(text, r"查询数: (\d+)")), + "top_k": int(extract(text, r"top_k: (\d+)")), + "batch_size": int(extract(text, r"batch_size: (\d+)")), + "exact_query_tile": int(extract(text, r"exact_query_tile: (\d+)")), + "exact_fused_layout": layout.group(1), + "exact_fused_blocks": int( + extract(text, r"exact_fused_blocks: (\d+)") + ), + "average_query_ms": extract( + text, r"平均常驻查询时间: ([0-9.eE+-]+) ms" + ), + "qps": extract(text, r"常驻 QPS: ([0-9.eE+-]+)"), + "run_p50_ms": extract(text, r"run P50: ([0-9.eE+-]+) ms"), + "run_p99_ms": extract(text, r"run P99: ([0-9.eE+-]+) ms"), + "gpu_buffer_mib": extract(text, r"GPU 缓冲区: ([0-9.eE+-]+) MiB"), + "fused_kernel_ms": extract( + text, r"平均融合距离\+局部 Top-K kernel: ([0-9.eE+-]+) ms" + ), + "final_merge_ms": extract( + text, r"平均最终 Top-K kernel: ([0-9.eE+-]+) ms" + ), + } + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="") as output: + writer = csv.DictWriter(output, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--database", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument( + "--variant", action="append", required=True, + help="repeat label=K:path,K:path for each A/B variant", + ) + parser.add_argument("--reference-results", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--csv", type=Path, required=True) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--tolerance", type=float, default=5e-5) + args = parser.parse_args() + if args.warmup < 0 or args.repeat <= 0: + raise ValueError("warmup must be non-negative and repeat positive") + + references = dict(parse_k_paths(args.reference_results)) + variants = [parse_variant(item) for item in args.variant] + expected_keys = set(references) + if any({top_k for top_k, _ in configs} != expected_keys + for _, configs in variants): + raise ValueError("every variant must cover the reference K values") + + rows: list[dict[str, object]] = [] + for label, configs in variants: + variant_dir = args.output_dir / label + variant_dir.mkdir(parents=True, exist_ok=True) + for expected_k, config in configs: + result_path = variant_dir / f"exact_k{expected_k}.txt" + command = [ + args.search_binary, + "--database", args.database, + "--queries", args.queries, + "--params", str(config), + "--backend", "gpu", + "--output", str(result_path), + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + ] + completed = subprocess.run( + command, + check=True, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + print(completed.stdout, end="") + row = parse_search_output(completed.stdout, label) + if row["top_k"] != expected_k: + raise ValueError( + f"config {config} produced K={row['top_k']}, " + f"expected {expected_k}" + ) + compare_results( + references[expected_k], result_path, args.tolerance + ) + row["result_path"] = str(result_path) + rows.append(row) + write_csv(args.csv, rows) + print(f"CSV: {args.csv}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_faiss.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_faiss.py new file mode 100644 index 00000000..2a9e818c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_faiss.py @@ -0,0 +1,506 @@ +#!/usr/bin/env python3 +"""在本项目自定义数据上运行可复现的 FAISS Flat/IVF-Flat 基准。""" + +from __future__ import annotations + +import argparse +import csv +import gc +import json +import os +import struct +import time +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Iterable + +# 固定 CPU 对照的线程口径;用户可在命令前显式覆盖。 +os.environ.setdefault("OMP_NUM_THREADS", "1") + +import numpy as np + + +DTYPES = {1: np.dtype(" np.memmap: + return np.memmap( + self.path, + dtype=DTYPES[self.dtype_code], + mode="r", + offset=self.header_bytes, + shape=(self.rows, self.dim), + ) + + +@dataclass +class BenchmarkRow: + implementation: str + backend: str + index_type: str + metric: str + num_vectors: int + num_queries: int + dim: int + dtype: str + cpu_threads: int + top_k: int + batch_size: int + nlist: int + nprobe: int + train_samples: int + training_iterations: int + training_seed: int + build_ms: float + load_ms: float + gpu_transfer_ms: float + gpu_index_mib: float + gpu_temp_mib: float + average_query_ms: float + qps: float + run_p50_ms: float + run_p99_ms: float + run_samples: int + batch_p50_ms: float + batch_p99_ms: float + batch_latency_samples: int + recall_at_k: float + min_query_recall: float + mean_absolute_score_error: float + max_absolute_score_error: float + + +def _read_header(path: Path, expected_magic: bytes) -> tuple[bytes, int]: + with path.open("rb") as source: + magic = source.read(8) + if magic != expected_magic: + raise ValueError(f"{path}: magic/version 不正确") + return magic, path.stat().st_size + + +def read_database(path: Path) -> VectorFile: + _, actual_size = _read_header(path, b"PPVEC001") + with path.open("rb") as source: + source.seek(8) + rows, dim, dtype_code, metric_code = struct.unpack(" VectorFile: + _, actual_size = _read_header(path, b"PPQRY001") + with path.open("rb") as source: + source.seek(8) + rows, dim, dtype_code = struct.unpack(" list[int]: + try: + values = [int(item.strip()) for item in text.split(",")] + except ValueError as error: + raise ValueError(f"{name} 必须是逗号分隔的正整数") from error + if not values or any(value <= 0 for value in values): + raise ValueError(f"{name} 必须是逗号分隔的正整数") + return values + + +def percentile(values: Iterable[float], fraction: float) -> float: + array = np.asarray(list(values), dtype=np.float64) + if array.size == 0: + return 0.0 + return float(np.percentile(array, fraction * 100.0, method="higher")) + + +def gpu_memory_mib(resource) -> tuple[float, float]: + """返回 FAISS GPU 的索引数据与临时工作区保留量。""" + if not hasattr(resource, "getMemoryInfo"): + return 0.0, 0.0 + index_bytes = 0 + temp_bytes = 0 + for categories in resource.getMemoryInfo().values(): + for name, (_, allocated_bytes) in categories.items(): + if name == "TemporaryMemoryBuffer": + temp_bytes += allocated_bytes + else: + index_bytes += allocated_bytes + scale = 1024.0 * 1024.0 + return index_bytes / scale, temp_bytes / scale + + +def recall(reference: np.ndarray, actual: np.ndarray) -> tuple[float, float]: + if reference.shape != actual.shape or reference.ndim != 2 or reference.shape[1] == 0: + raise ValueError("reference 与 actual 的形状必须相同且 K>0") + per_query = np.asarray( + [len(set(expected) & set(found)) / reference.shape[1] + for expected, found in zip(reference.tolist(), actual.tolist())], + dtype=np.float64, + ) + return float(per_query.mean()), float(per_query.min()) + + +def score_errors(reference: np.ndarray, actual: np.ndarray) -> tuple[float, float]: + """按名次比较 Top-K 分数,量化近似结果相对 exact 的质量损失。""" + if reference.shape != actual.shape or reference.size == 0: + raise ValueError("reference 与 actual 的分数形状必须相同且非空") + errors = np.abs( + np.asarray(reference, dtype=np.float64) + - np.asarray(actual, dtype=np.float64) + ) + return float(errors.mean()), float(errors.max()) + + +def as_float32(values: np.ndarray) -> np.ndarray: + return np.ascontiguousarray(values, dtype=np.float32) + + +def normalize_rows(values: np.ndarray) -> np.ndarray: + values = as_float32(values) + norms = np.linalg.norm(values, axis=1, keepdims=True) + if np.any(norms == 0): + raise ValueError("cosine 数据包含零向量") + return values / norms + + +def import_faiss(): + try: + import faiss # type: ignore + except ImportError as error: + raise RuntimeError( + "未安装 FAISS;请在隔离环境中安装 faiss-cpu 或 CUDA 对应的 " + "faiss-gpu 包" + ) from error + return faiss + + +def make_flat_index(faiss, dim: int, metric: str): + return faiss.IndexFlatL2(dim) if metric == "l2" else faiss.IndexFlatIP(dim) + + +def make_ivf_index(faiss, dim: int, metric: str, nlist: int, iterations: int, seed: int): + metric_id = faiss.METRIC_L2 if metric == "l2" else faiss.METRIC_INNER_PRODUCT + quantizer = make_flat_index(faiss, dim, metric) + index = faiss.IndexIVFFlat(quantizer, dim, nlist, metric_id) + index.cp.niter = iterations + index.cp.seed = seed + return index + + +def prepare_vectors(database: VectorFile, queries: VectorFile) -> tuple[np.ndarray, np.ndarray]: + if database.dim != queries.dim: + raise ValueError("数据库与 query 维度不一致") + database_values = as_float32(database.mmap()) + query_values = as_float32(queries.mmap()) + if database.metric == "cosine": + database_values = normalize_rows(database_values) + query_values = normalize_rows(query_values) + return database_values, query_values + + +def search_batches(index, queries: np.ndarray, top_k: int, batch_size: int): + distances = np.empty((len(queries), top_k), dtype=np.float32) + ids = np.empty((len(queries), top_k), dtype=np.int64) + latencies = [] + start_all = time.perf_counter() + for start in range(0, len(queries), batch_size): + end = min(start + batch_size, len(queries)) + start_batch = time.perf_counter() + batch_distances, batch_ids = index.search(queries[start:end], top_k) + latencies.append((time.perf_counter() - start_batch) * 1000.0) + distances[start:end] = batch_distances + ids[start:end] = batch_ids + total_ms = (time.perf_counter() - start_all) * 1000.0 + return distances, ids, total_ms, latencies + + +def write_results(path: Path, ids: np.ndarray, scores: np.ndarray) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w") as output: + for query_id, (query_ids, query_scores) in enumerate(zip(ids, scores)): + for vector_id, score in zip(query_ids, query_scores): + output.write(f"{query_id} {int(vector_id)} {float(score):.9g}\n") + + +def write_csv(path: Path, rows: list[BenchmarkRow]) -> None: + with path.open("w", newline="") as output: + writer = csv.DictWriter(output, fieldnames=list(asdict(rows[0]))) + writer.writeheader() + writer.writerows(asdict(row) for row in rows) + + +def read_result_arrays( + path: Path, num_queries: int, minimum_k: int +) -> tuple[np.ndarray, np.ndarray]: + id_rows: list[list[int]] = [[] for _ in range(num_queries)] + score_rows: list[list[float]] = [[] for _ in range(num_queries)] + with path.open() as source: + for line_number, line in enumerate(source, 1): + fields = line.split() + if len(fields) != 3: + raise ValueError(f"{path}:{line_number}: 结果行必须有三列") + query_id, vector_id, score = int(fields[0]), int(fields[1]), float(fields[2]) + if query_id < 0 or query_id >= num_queries: + raise ValueError(f"{path}:{line_number}: query_id 越界") + id_rows[query_id].append(vector_id) + score_rows[query_id].append(score) + if any(len(row) < minimum_k for row in id_rows): + raise ValueError(f"{path}: 每个 query 至少需要 {minimum_k} 个结果") + ids = np.asarray([row[:minimum_k] for row in id_rows], dtype=np.int64) + scores = np.asarray([row[:minimum_k] for row in score_rows], dtype=np.float32) + return ids, scores + + +def read_result_ids(path: Path, num_queries: int, minimum_k: int) -> np.ndarray: + """兼容已有调用者;新代码应使用 read_result_arrays 同时读取分数。""" + return read_result_arrays(path, num_queries, minimum_k)[0] + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--database", type=Path, required=True) + parser.add_argument("--queries", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--csv", type=Path, required=True) + parser.add_argument("--index-dir", type=Path, required=True) + parser.add_argument( + "--reference-results", type=Path, + help="可选的本项目 exact 结果,用来交叉验证 FAISS Flat", + ) + parser.add_argument("--backends", default="cpu,gpu", help="cpu,gpu 或二者") + parser.add_argument("--index-types", default="flat,ivf_flat") + parser.add_argument("--top-ks", default="10,50,100") + parser.add_argument("--nprobes", default="128,160,192,224") + parser.add_argument("--nlist", type=int, default=256) + parser.add_argument("--batch-size", type=int, default=64) + parser.add_argument("--train-samples", type=int, default=100000) + parser.add_argument("--iterations", type=int, default=15) + parser.add_argument("--seed", type=int, default=2026) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--cpu-threads", type=int, default=1) + parser.add_argument("--rebuild", action="store_true") + return parser.parse_args() + + +def validate_args(args: argparse.Namespace) -> tuple[list[str], list[str], list[int], list[int]]: + backends = [item.strip() for item in args.backends.split(",")] + index_types = [item.strip() for item in args.index_types.split(",")] + top_ks = parse_positive_csv(args.top_ks, "top-ks") + nprobes = parse_positive_csv(args.nprobes, "nprobes") + if not backends or any(item not in {"cpu", "gpu"} for item in backends): + raise ValueError("backends 只能包含 cpu,gpu") + if not index_types or any(item not in {"flat", "ivf_flat"} for item in index_types): + raise ValueError("index-types 只能包含 flat,ivf_flat") + for name in ( + "nlist", "batch_size", "train_samples", "iterations", "repeat", + "cpu_threads", + ): + if getattr(args, name) <= 0: + raise ValueError(f"{name} 必须大于 0") + if args.warmup < 0 or any(value > args.nlist for value in nprobes): + raise ValueError("warmup 必须非负,nprobe 必须位于 1..nlist") + return backends, index_types, top_ks, nprobes + + +def main() -> None: + args = parse_args() + backends, index_types, top_ks, nprobes = validate_args(args) + faiss = import_faiss() + faiss.omp_set_num_threads(args.cpu_threads) + database_info = read_database(args.database) + query_info = read_queries(args.queries) + database, queries = prepare_vectors(database_info, query_info) + if max(top_ks) > database_info.rows: + raise ValueError("top_k 不能超过数据库向量数") + + args.output_dir.mkdir(parents=True, exist_ok=True) + args.index_dir.mkdir(parents=True, exist_ok=True) + args.csv.parent.mkdir(parents=True, exist_ok=True) + metric = database_info.metric + assert metric is not None + metric_suffix = "l2" if metric == "l2" else "ip" + + cpu_indexes = {} + build_times = {} + load_times = {} + build_index_types = list(dict.fromkeys(["flat", *index_types])) + for index_type in build_index_types: + training_suffix = "" + if index_type == "ivf_flat": + training_suffix = ( + f"_train{min(args.train_samples, database_info.rows)}" + f"_iter{args.iterations}_seed{args.seed}" + ) + index_path = args.index_dir / ( + f"faiss_{index_type}_{metric_suffix}_{database_info.rows}x" + f"{database_info.dim}_nlist{args.nlist}{training_suffix}.index" + ) + if index_path.exists() and not args.rebuild: + start = time.perf_counter() + cpu_index = faiss.read_index(str(index_path)) + load_times[index_type] = (time.perf_counter() - start) * 1000.0 + build_times[index_type] = 0.0 + else: + start = time.perf_counter() + if index_type == "flat": + cpu_index = make_flat_index(faiss, database_info.dim, metric) + else: + cpu_index = make_ivf_index( + faiss, database_info.dim, metric, args.nlist, + args.iterations, args.seed, + ) + rng = np.random.default_rng(args.seed) + sample_count = min(args.train_samples, database_info.rows) + sample_ids = rng.choice(database_info.rows, sample_count, replace=False) + cpu_index.train(database[sample_ids]) + cpu_index.add(database) + build_times[index_type] = (time.perf_counter() - start) * 1000.0 + load_times[index_type] = 0.0 + faiss.write_index(cpu_index, str(index_path)) + if cpu_index.ntotal != database_info.rows: + raise RuntimeError(f"FAISS {index_type} 索引向量数不正确") + cpu_indexes[index_type] = cpu_index + + max_k = max(top_ks) + faiss_reference_scores, faiss_reference_ids = cpu_indexes["flat"].search( + queries, max_k + ) + if args.reference_results is not None: + reference_ids, reference_scores = read_result_arrays( + args.reference_results, query_info.rows, max_k + ) + else: + reference_ids, reference_scores = faiss_reference_ids, faiss_reference_scores + if args.reference_results is not None: + exact_recall, exact_minimum = recall(reference_ids, faiss_reference_ids) + exact_mean_error, exact_max_error = score_errors( + reference_scores, faiss_reference_scores + ) + print( + f"FAISS Flat vs project exact recall@{max_k}: " + f"{exact_recall:.9f}, min={exact_minimum:.9f}, " + f"mean_score_error={exact_mean_error:.9g}, " + f"max_score_error={exact_max_error:.9g}" + ) + if exact_recall < 1.0: + raise RuntimeError("FAISS Flat 与本项目 exact 的候选 ID 不一致") + rows: list[BenchmarkRow] = [] + for backend in backends: + if backend == "gpu" and ( + not hasattr(faiss, "get_num_gpus") or faiss.get_num_gpus() < 1 + ): + raise RuntimeError("请求了 GPU backend,但 FAISS 没有检测到 GPU") + for index_type in index_types: + gpu_transfer_ms = 0.0 + gpu_index_mib = 0.0 + gpu_temp_mib = 0.0 + if backend == "gpu": + resource = faiss.StandardGpuResources() + start = time.perf_counter() + index = faiss.index_cpu_to_gpu(resource, 0, cpu_indexes[index_type]) + gpu_transfer_ms = (time.perf_counter() - start) * 1000.0 + gpu_index_mib, gpu_temp_mib = gpu_memory_mib(resource) + else: + index = cpu_indexes[index_type] + + probe_values = [0] if index_type == "flat" else nprobes + for nprobe in probe_values: + if index_type == "ivf_flat": + index.nprobe = nprobe + for top_k in top_ks: + for _ in range(args.warmup): + # 与本项目 CLI 一致:预热覆盖完整 query set,避免 + # GPU 时钟爬升和 FAISS 延迟初始化进入正式统计。 + search_batches(index, queries, top_k, args.batch_size) + repeat_ms = [] + all_batch_ms = [] + last_scores = last_ids = None + for _ in range(args.repeat): + last_scores, last_ids, total_ms, batch_ms = search_batches( + index, queries, top_k, args.batch_size + ) + repeat_ms.append(total_ms) + all_batch_ms.extend(batch_ms) + assert last_scores is not None and last_ids is not None + average_ms = float(np.mean(repeat_ms)) + reference = reference_ids[:, :top_k] + recall_at_k, minimum_recall = recall(reference, last_ids) + mean_score_error, max_score_error = score_errors( + reference_scores[:, :top_k], last_scores + ) + row = BenchmarkRow( + implementation=f"faiss-{getattr(faiss, '__version__', 'unknown')}", + backend=backend, + index_type=index_type, + metric=metric, + num_vectors=database_info.rows, + num_queries=query_info.rows, + dim=database_info.dim, + dtype="fp32" if database_info.dtype_code == 1 else "fp16-to-fp32", + cpu_threads=args.cpu_threads, + top_k=top_k, + batch_size=args.batch_size, + nlist=0 if index_type == "flat" else args.nlist, + nprobe=nprobe, + train_samples=0 if index_type == "flat" else min( + args.train_samples, database_info.rows + ), + training_iterations=0 if index_type == "flat" else args.iterations, + training_seed=0 if index_type == "flat" else args.seed, + build_ms=build_times[index_type], + load_ms=load_times[index_type], + gpu_transfer_ms=gpu_transfer_ms, + gpu_index_mib=gpu_index_mib, + gpu_temp_mib=gpu_temp_mib, + average_query_ms=average_ms, + qps=query_info.rows / (average_ms / 1000.0), + run_p50_ms=percentile(repeat_ms, 0.50), + run_p99_ms=percentile(repeat_ms, 0.99), + run_samples=len(repeat_ms), + batch_p50_ms=percentile(all_batch_ms, 0.50), + batch_p99_ms=percentile(all_batch_ms, 0.99), + batch_latency_samples=len(all_batch_ms), + recall_at_k=recall_at_k, + min_query_recall=minimum_recall, + mean_absolute_score_error=mean_score_error, + max_absolute_score_error=max_score_error, + ) + rows.append(row) + # 长矩阵每完成一项立即落盘,远端中断时保留已完成结果。 + write_csv(args.csv, rows) + result_path = args.output_dir / ( + f"faiss_{backend}_{index_type}_k{top_k}_nprobe{nprobe}.txt" + ) + write_results(result_path, last_ids, last_scores) + print(json.dumps(asdict(row), ensure_ascii=False)) + if backend == "gpu": + del index + del resource + gc.collect() + + print(f"CSV: {args.csv}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_ivf_sweep.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_ivf_sweep.py new file mode 100644 index 00000000..520ea9ee --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_ivf_sweep.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""运行 IVF nprobe 扫描并把性能、显存和 recall 汇总为 CSV。""" + +import argparse +import csv +import re +import subprocess +from pathlib import Path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--index", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument("--params", required=True) + parser.add_argument("--exact", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--csv", required=True) + parser.add_argument("--nlist", type=int, required=True) + parser.add_argument("--training-samples", type=int, default=0) + parser.add_argument("--training-iterations", type=int, default=0) + parser.add_argument("--training-seed", type=int, default=0) + parser.add_argument("--nprobes", required=True, + help="逗号分隔,例如 64,128,192") + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + return parser.parse_args() + + +def read_results(path: Path) -> list[list[tuple[int, float]]]: + rows: dict[int, list[tuple[int, float]]] = {} + for line_number, line in enumerate(path.read_text().splitlines(), 1): + fields = line.split() + if len(fields) != 3: + raise ValueError(f"{path}:{line_number}: 结果行必须有三列") + query_id, vector_id, score = int(fields[0]), int(fields[1]), float(fields[2]) + rows.setdefault(query_id, []).append((vector_id, score)) + return [rows[query_id] for query_id in sorted(rows)] + + +def recall(exact: list[list[int]], approximate: list[list[int]]) -> tuple[float, float]: + if len(exact) != len(approximate) or not exact: + raise ValueError("exact 与 approximate 的 query 数不一致或为空") + recalls = [] + for expected, actual in zip(exact, approximate): + if len(expected) != len(actual) or not expected: + raise ValueError("exact 与 approximate 的 K 不一致或为空") + recalls.append(len(set(expected) & set(actual)) / len(expected)) + return sum(recalls) / len(recalls), min(recalls) + + +def quality_metrics( + exact: list[list[tuple[int, float]]], + approximate: list[list[tuple[int, float]]], +) -> tuple[float, float, float, float]: + if len(exact) != len(approximate) or not exact: + raise ValueError("exact 与 approximate 的 query 数不一致或为空") + exact_ids = [[item[0] for item in query] for query in exact] + approximate_ids = [[item[0] for item in query] for query in approximate] + recall_at_k, minimum_recall = recall(exact_ids, approximate_ids) + errors = [] + for expected, actual in zip(exact, approximate): + if len(expected) != len(actual) or not expected: + raise ValueError("exact 与 approximate 的 K 不一致或为空") + errors.extend( + abs(expected_item[1] - actual_item[1]) + for expected_item, actual_item in zip(expected, actual) + ) + return ( + recall_at_k, + minimum_recall, + sum(errors) / len(errors), + max(errors), + ) + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"无法从 ivf_search 输出解析字段: {pattern}") + return float(match.group(1)) + + +def extract_pair(text: str, pattern: str) -> tuple[float, float]: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"无法从 ivf_search 输出解析字段: {pattern}") + return float(match.group(1)), float(match.group(2)) + + +def read_params(path: Path) -> dict[str, str]: + params = {} + for line_number, raw_line in enumerate(path.read_text().splitlines(), 1): + line = raw_line.split("#", 1)[0].strip() + if not line: + continue + if "=" not in line: + raise ValueError(f"{path}:{line_number}: expected key = value") + key, value = (part.strip() for part in line.split("=", 1)) + params[key] = value + return params + + +def main() -> None: + args = parse_args() + nprobes = [int(value) for value in args.nprobes.split(",")] + if not nprobes or any(value <= 0 or value > args.nlist for value in nprobes): + raise ValueError("nprobes 必须位于 1..nlist") + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + csv_path = Path(args.csv) + csv_path.parent.mkdir(parents=True, exist_ok=True) + exact_results = read_results(Path(args.exact)) + params = read_params(Path(args.params)) + rows = [] + for nprobe in nprobes: + result_path = output_dir / f"nlist{args.nlist}_nprobe{nprobe}.txt" + command = [ + args.search_binary, + "--index", args.index, + "--queries", args.queries, + "--params", args.params, + "--nlist", str(args.nlist), + "--nprobe", str(nprobe), + "--backend", "gpu", + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + "--output", str(result_path), + ] + completed = subprocess.run(command, check=True, text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + print(completed.stdout, end="") + approximate_results = read_results(result_path) + recall_at_k, minimum_recall, mean_score_error, max_score_error = ( + quality_metrics(exact_results, approximate_results) + ) + top_k = int(extract(completed.stdout, r"nlist/nprobe/top_k: \d+/\d+/(\d+)")) + run_p50_ms, run_p99_ms = extract_pair( + completed.stdout, r"run P50/P99: ([0-9.eE+-]+)/([0-9.eE+-]+) ms" + ) + batch_p50_ms, batch_p99_ms = extract_pair( + completed.stdout, r"batch P50/P99: ([0-9.eE+-]+)/([0-9.eE+-]+) ms" + ) + row = { + "implementation": "WarpFusion", + "backend": "gpu", + "num_vectors": int(extract(completed.stdout, r"索引: (\d+) x \d+")), + "num_queries": len(approximate_results), + "dim": int(extract(completed.stdout, r"索引: \d+ x (\d+)")), + "metric": re.search( + r"dtype/metric: [^/]+/([^\n]+)", completed.stdout + ).group(1), + "batch_size": int(params["batch_size"]), + "distance_mode": params["distance_mode"], + "nlist": args.nlist, + "nprobe": nprobe, + "training_samples": args.training_samples, + "training_iterations": args.training_iterations, + "training_seed": args.training_seed, + "top_k": top_k, + "average_ms": extract(completed.stdout, r"平均查询: ([0-9.eE+-]+) ms"), + "qps": extract(completed.stdout, r"QPS: ([0-9.eE+-]+)"), + "run_p50_ms": run_p50_ms, + "run_p99_ms": run_p99_ms, + "batch_p50_ms": batch_p50_ms, + "batch_p99_ms": batch_p99_ms, + "recall_at_k": recall_at_k, + "min_query_recall": minimum_recall, + "mean_absolute_score_error": mean_score_error, + "max_absolute_score_error": max_score_error, + "run_samples": int(extract( + completed.stdout, r"run samples: (\d+)" + )), + "batch_latency_samples": int(extract( + completed.stdout, r"batch samples: (\d+)" + )), + "index_load_ms": extract(completed.stdout, r"索引加载: ([0-9.eE+-]+) ms"), + "gpu_initialization_ms": extract( + completed.stdout, r"GPU 初始化: ([0-9.eE+-]+) ms" + ), + "index_h2d_ms": extract(completed.stdout, r"索引 H2D: ([0-9.eE+-]+) ms"), + "gpu_buffer_mib": extract(completed.stdout, r"GPU 缓冲区: ([0-9.eE+-]+) MiB"), + "center_ms": extract(completed.stdout, r"平均 GPU 中心选择: ([0-9.eE+-]+) ms"), + "scan_ms": extract(completed.stdout, r"平均 GPU 桶扫描\+局部 Top-K: ([0-9.eE+-]+) ms"), + "merge_ms": extract(completed.stdout, r"平均 GPU 最终 Top-K 归并: ([0-9.eE+-]+) ms"), + } + rows.append(row) + # 长时间扫描每完成一个 nprobe 就落盘,远端中断时保留已完成结果。 + with csv_path.open("w", newline="") as csv_file: + writer = csv.DictWriter(csv_file, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + print(f"recall@{top_k}={recall_at_k:.6f}, " + f"min_query_recall={minimum_recall:.6f}, " + f"mean_absolute_score_error={mean_score_error:.9g}, " + f"max_absolute_score_error={max_score_error:.9g}") + + print(f"CSV: {csv_path}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/benchmark_memory_modes.py b/09_vector_retrieval/PurplePulse/scripts/benchmark_memory_modes.py new file mode 100644 index 00000000..a2c89b7c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/benchmark_memory_modes.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Compare fused Agent-memory scoring with a separate GPU rerank baseline.""" + +from __future__ import annotations + +import argparse +import csv +import re +import subprocess +from pathlib import Path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--search-binary", required=True) + parser.add_argument("--index", required=True) + parser.add_argument("--queries", required=True) + parser.add_argument("--params", required=True) + parser.add_argument("--memory-metadata", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--csv", required=True) + parser.add_argument("--nlist", type=int, required=True) + parser.add_argument("--nprobe", type=int, required=True) + parser.add_argument("--rerank-factor", type=int, default=10) + parser.add_argument("--semantic-weight", type=float, default=1.0) + parser.add_argument("--importance-weight", type=float, default=0.15) + parser.add_argument("--recency-weight", type=float, default=0.10) + parser.add_argument("--time-scale", type=float, default=604800.0) + parser.add_argument("--now", type=int, default=1_702_592_000) + parser.add_argument("--min-timestamp", type=int, default=0) + parser.add_argument("--session-id", default="any") + parser.add_argument("--source-type", default="any") + parser.add_argument("--warmup", type=int, default=2) + parser.add_argument("--repeat", type=int, default=5) + return parser.parse_args() + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"cannot parse ivf_search output: {pattern}") + return float(match.group(1)) + + +def read_ids(path: Path) -> list[list[int]]: + rows: dict[int, list[int]] = {} + for line_number, line in enumerate(path.read_text().splitlines(), 1): + fields = line.split() + if len(fields) != 3: + raise ValueError(f"{path}:{line_number}: expected three columns") + rows.setdefault(int(fields[0]), []).append(int(fields[1])) + return [rows[query_id] for query_id in sorted(rows)] + + +def recall(reference: list[list[int]], actual: list[list[int]]) -> tuple[float, float]: + if len(reference) != len(actual) or not reference: + raise ValueError("reference and actual query counts differ or are empty") + values = [] + for expected, found in zip(reference, actual): + if not expected: + raise ValueError("reference contains an empty query result") + values.append(len(set(expected) & set(found)) / len(expected)) + return sum(values) / len(values), min(values) + + +def main() -> None: + args = parse_args() + if args.nlist <= 0 or not 0 < args.nprobe <= args.nlist: + raise ValueError("invalid nlist/nprobe") + if args.rerank_factor <= 0 or args.semantic_weight <= 0: + raise ValueError("weights and rerank factor must be positive") + if args.importance_weight < 0 or args.recency_weight < 0 or args.time_scale <= 0: + raise ValueError("invalid memory scoring weights") + + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + csv_path = Path(args.csv) + csv_path.parent.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + reference_ids: list[list[int]] | None = None + for mode in ("fused", "rerank"): + result_path = output_dir / f"{mode}.txt" + command = [ + args.search_binary, + "--index", args.index, + "--queries", args.queries, + "--params", args.params, + "--memory-metadata", args.memory_metadata, + "--memory-mode", mode, + "--memory-semantic-weight", str(args.semantic_weight), + "--memory-importance-weight", str(args.importance_weight), + "--memory-recency-weight", str(args.recency_weight), + "--memory-time-scale", str(args.time_scale), + "--memory-now", str(args.now), + "--filter-min-timestamp", str(args.min_timestamp), + "--filter-session-id", args.session_id, + "--filter-source-type", args.source_type, + "--memory-rerank-factor", str(args.rerank_factor), + "--nlist", str(args.nlist), + "--nprobe", str(args.nprobe), + "--backend", "gpu", + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + "--output", str(result_path), + ] + completed = subprocess.run( + command, check=True, text=True, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT + ) + print(completed.stdout, end="") + ids = read_ids(result_path) + if reference_ids is None: + reference_ids = ids + recall_at_k, minimum_recall = 1.0, 1.0 + else: + recall_at_k, minimum_recall = recall(reference_ids, ids) + batch_match = re.search( + r"batch P50/P99: ([0-9.eE+-]+)/([0-9.eE+-]+) ms", + completed.stdout, + ) + if batch_match is None: + raise ValueError("cannot parse batch latency") + rows.append({ + "mode": mode, + "nlist": args.nlist, + "nprobe": args.nprobe, + "rerank_factor": 1 if mode == "fused" else args.rerank_factor, + "session_id": args.session_id, + "source_type": args.source_type, + "average_ms": extract(completed.stdout, r"平均查询: ([0-9.eE+-]+) ms"), + "qps": extract(completed.stdout, r"QPS: ([0-9.eE+-]+)"), + "batch_p50_ms": float(batch_match.group(1)), + "batch_p99_ms": float(batch_match.group(2)), + "scan_ms": extract(completed.stdout, r"平均 GPU 桶扫描\+局部 Top-K: ([0-9.eE+-]+) ms"), + "merge_ms": extract(completed.stdout, r"平均 GPU 最终 Top-K 归并: ([0-9.eE+-]+) ms"), + "rerank_ms": extract(completed.stdout, r"平均记忆独立重排: ([0-9.eE+-]+) ms"), + "gpu_buffer_mib": extract(completed.stdout, r"GPU 缓冲区: ([0-9.eE+-]+) MiB"), + "recall_vs_fused": recall_at_k, + "min_query_recall_vs_fused": minimum_recall, + }) + with csv_path.open("w", newline="") as csv_file: + writer = csv.DictWriter(csv_file, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + print(f"{mode}: recall_vs_fused={recall_at_k:.6f}") + print(f"CSV: {csv_path}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/build_final_report_pdf.py b/09_vector_retrieval/PurplePulse/scripts/build_final_report_pdf.py new file mode 100644 index 00000000..fb7339c2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/build_final_report_pdf.py @@ -0,0 +1,739 @@ +#!/usr/bin/env python3 +"""Render docs/FINAL_REPORT.md as a submission-ready A4 technical report.""" + +from __future__ import annotations + +import argparse +import os +import re +import xml.etree.ElementTree as ET +from html import escape +from pathlib import Path + +from reportlab.graphics.shapes import ( + Circle, + Drawing, + Line, + Path as GraphicsPath, + Rect, + String, +) +from reportlab.lib import colors +from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT +from reportlab.lib.pagesizes import A4 +from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet +from reportlab.lib.units import mm +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.ttfonts import TTFont +from reportlab.platypus import ( + BaseDocTemplate, + Flowable, + Frame, + PageTemplate, + Paragraph, + PageBreak, + Spacer, + Table, + TableStyle, +) + + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = ROOT / "docs" / "FINAL_REPORT.md" +OUTPUT = ROOT / "output" / "pdf" / "WarpFusion_Technical_Report.pdf" + +NAVY = colors.HexColor("#142B4A") +BLUE = colors.HexColor("#275D8C") +LIGHT_BLUE = colors.HexColor("#EAF1F7") +LIGHT_GRAY = colors.HexColor("#F4F5F7") +MID_GRAY = colors.HexColor("#B8C0C8") +TEXT = colors.HexColor("#18212B") + + +def choose_font(explicit: str | None, environment_name: str, + candidates: list[str], label: str, + fallback: str | None = None) -> str: + requested = explicit or os.environ.get(environment_name) + if requested: + path = Path(requested).expanduser() + if not path.is_file(): + raise FileNotFoundError(f"{label} font does not exist: {path}") + return str(path) + for candidate in candidates: + if Path(candidate).is_file(): + return candidate + if fallback is not None: + return fallback + raise FileNotFoundError( + f"cannot find a {label} font; pass the corresponding --*-font option" + ) + + +def register_fonts(body_font: str | None = None, + heading_font: str | None = None, + light_font: str | None = None, + mono_font: str | None = None) -> dict[str, str]: + body = choose_font( + body_font, + "PURPLEPULSE_REPORT_BODY_FONT", + [ + "/System/Library/Fonts/Supplemental/Songti.ttc", + "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", + ], + "CJK body", + ) + heading = choose_font( + heading_font, + "PURPLEPULSE_REPORT_HEADING_FONT", + [ + "/System/Library/Fonts/STHeiti Medium.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + ], + "CJK heading", + fallback=body, + ) + light = choose_font( + light_font, + "PURPLEPULSE_REPORT_LIGHT_FONT", + [ + "/System/Library/Fonts/STHeiti Light.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", + ], + "CJK light", + fallback=body, + ) + mono = choose_font( + mono_font, + "PURPLEPULSE_REPORT_MONO_FONT", + [ + "/System/Library/Fonts/SFNSMono.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", + "/usr/share/fonts/truetype/liberation2/LiberationMono-Regular.ttf", + ], + "monospace", + fallback=light, + ) + fonts = {"BodyCN": body, "HeadCN": heading, "LightCN": light, "Mono": mono} + # macOS CJK fonts are TrueType collections. Their first faces are not the + # simplified-Chinese regular faces: Songti index 0 is Black and the Heiti + # collections start with Traditional Chinese. Select the intended faces + # explicitly so simplified glyphs and body weight remain consistent. + collection_faces = { + ("BodyCN", "/System/Library/Fonts/Supplemental/Songti.ttc"): 6, + ("HeadCN", "/System/Library/Fonts/STHeiti Medium.ttc"): 1, + ("LightCN", "/System/Library/Fonts/STHeiti Light.ttc"): 1, + } + for name, path in fonts.items(): + subfont_index = collection_faces.get((name, str(Path(path))), 0) + pdfmetrics.registerFont(TTFont(name, path, subfontIndex=subfont_index)) + return fonts + + +def inline_markup(text: str) -> str: + placeholders: list[str] = [] + + # Keep punctuation portable across PDF renderers and submission systems. + text = text.replace("–", "-").replace("—", "-").replace("‑", "-") + + def save_code(match: re.Match[str]) -> str: + placeholders.append( + f'{escape(match.group(1))}' + ) + return f"@@CODE{len(placeholders) - 1}@@" + + text = re.sub(r"`([^`]+)`", save_code, text) + text = re.sub(r"\[([^\]]+)\]\([^\)]+\)", r"\1", text) + text = escape(text) + text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) + text = re.sub(r"\*([^*]+)\*", r"\1", text) + for index, value in enumerate(placeholders): + text = text.replace(f"@@CODE{index}@@", value) + return text + + +def equation_text(text: str) -> str: + replacements = { + r"\sum_j": "Σ_j", + r"\cdot": "·", + r"\qquad": " ", + r"\lVert": "||", + r"\rVert": "||", + r"\frac{q\cdot x}{\lVert q\rVert_2\lVert x\rVert_2}": + "(q · x) / (||q||₂ ||x||₂)", + } + for source, target in replacements.items(): + text = text.replace(source, target) + text = text.replace("_{L2}", "_L2").replace("_{IP}", "_IP") + text = text.replace("^2", "²") + text = text.replace("\\", "") + return text.strip() + + +class Rule(Flowable): + def __init__(self, width: float, color: colors.Color = BLUE) -> None: + super().__init__() + self.width = width + self.height = 1.2 + self.color = color + + def draw(self) -> None: + self.canv.setStrokeColor(self.color) + self.canv.setLineWidth(1.2) + self.canv.line(0, 0, self.width, 0) + + +class TechnicalReport(BaseDocTemplate): + def __init__(self, filename: str) -> None: + super().__init__( + filename, + pagesize=A4, + leftMargin=19 * mm, + rightMargin=19 * mm, + topMargin=19 * mm, + bottomMargin=18 * mm, + title="WarpFusion:面向大规模向量检索的 CUDA 并行设计与性能优化", + author="花生 (PurplePulse)", + subject="CUDA GPU 向量检索技术报告", + ) + frame = Frame( + self.leftMargin, + self.bottomMargin, + self.width, + self.height, + id="body", + leftPadding=0, + rightPadding=0, + topPadding=0, + bottomPadding=0, + ) + self.addPageTemplates(PageTemplate(id="main", frames=[frame], onPage=self.header_footer)) + + def header_footer(self, canvas, doc) -> None: # noqa: ANN001 + canvas.saveState() + if doc.page > 1: + canvas.setStrokeColor(MID_GRAY) + canvas.setLineWidth(0.35) + canvas.line(19 * mm, A4[1] - 13 * mm, A4[0] - 19 * mm, A4[1] - 13 * mm) + canvas.setFont("LightCN", 7.4) + canvas.setFillColor(colors.HexColor("#59636E")) + canvas.drawString(19 * mm, A4[1] - 10.5 * mm, "WarpFusion CUDA 向量检索技术报告") + canvas.drawRightString(A4[0] - 19 * mm, A4[1] - 10.5 * mm, "花生 · ID PurplePulse") + canvas.setFont("LightCN", 7.4) + canvas.setFillColor(colors.HexColor("#68727C")) + canvas.drawCentredString(A4[0] / 2, 9 * mm, str(doc.page)) + canvas.restoreState() + + def afterFlowable(self, flowable: Flowable) -> None: + if isinstance(flowable, Paragraph): + level = getattr(flowable, "heading_level", None) + if level in (1, 2): + key = f"section-{self.seq.nextf('section')}" + self.canv.bookmarkPage(key) + self.canv.addOutlineEntry(flowable.getPlainText(), key, level - 1, False) + + +def make_styles() -> dict[str, ParagraphStyle]: + sample = getSampleStyleSheet() + return { + "title": ParagraphStyle( + "ReportTitle", + parent=sample["Title"], + fontName="HeadCN", + fontSize=22, + leading=30, + textColor=NAVY, + alignment=TA_LEFT, + spaceAfter=8 * mm, + ), + "author": ParagraphStyle( + "Author", + fontName="LightCN", + fontSize=10.5, + leading=16, + textColor=colors.HexColor("#3D4955"), + spaceAfter=7 * mm, + ), + "h1": ParagraphStyle( + "Heading1CN", + fontName="HeadCN", + fontSize=14.2, + leading=20, + textColor=NAVY, + spaceBefore=7 * mm, + spaceAfter=3.2 * mm, + keepWithNext=True, + ), + "h2": ParagraphStyle( + "Heading2CN", + fontName="HeadCN", + fontSize=11.2, + leading=16, + textColor=BLUE, + spaceBefore=5 * mm, + spaceAfter=2.2 * mm, + keepWithNext=True, + ), + "references_heading": ParagraphStyle( + "ReferencesHeading", + fontName="HeadCN", + fontSize=12.2, + leading=17, + textColor=NAVY, + spaceBefore=3 * mm, + spaceAfter=1.8 * mm, + keepWithNext=True, + ), + "body": ParagraphStyle( + "BodyCN", + fontName="BodyCN", + fontSize=9.1, + leading=14.2, + textColor=TEXT, + alignment=TA_JUSTIFY, + firstLineIndent=2 * 9.1, + spaceAfter=2.1 * mm, + wordWrap="CJK", + ), + "abstract": ParagraphStyle( + "AbstractCN", + fontName="BodyCN", + fontSize=8.9, + leading=13.8, + textColor=TEXT, + alignment=TA_JUSTIFY, + firstLineIndent=2 * 8.9, + spaceAfter=2 * mm, + leftIndent=5 * mm, + rightIndent=5 * mm, + wordWrap="CJK", + ), + "list": ParagraphStyle( + "ListCN", + fontName="BodyCN", + fontSize=9.1, + leading=14.2, + textColor=TEXT, + alignment=TA_JUSTIFY, + leftIndent=7 * mm, + firstLineIndent=-4.5 * mm, + spaceAfter=1.5 * mm, + wordWrap="CJK", + ), + "references": ParagraphStyle( + "References", + fontName="BodyCN", + fontSize=8.0, + leading=10.8, + textColor=TEXT, + alignment=TA_LEFT, + leftIndent=5 * mm, + firstLineIndent=-3.5 * mm, + spaceAfter=0.8 * mm, + ), + "caption": ParagraphStyle( + "CaptionCN", + fontName="LightCN", + fontSize=7.8, + leading=11, + textColor=colors.HexColor("#4E5965"), + alignment=TA_CENTER, + spaceBefore=1.5 * mm, + spaceAfter=3 * mm, + wordWrap="CJK", + ), + "code": ParagraphStyle( + "CodeCN", + fontName="LightCN", + fontSize=7.7, + leading=11.2, + leftIndent=4 * mm, + rightIndent=4 * mm, + borderColor=MID_GRAY, + borderWidth=0.45, + borderPadding=4, + backColor=LIGHT_GRAY, + spaceBefore=1.5 * mm, + spaceAfter=3 * mm, + wordWrap="CJK", + ), + "equation": ParagraphStyle( + "Equation", + fontName="BodyCN", + fontSize=9.4, + leading=14, + textColor=TEXT, + alignment=TA_CENTER, + spaceBefore=1.5 * mm, + spaceAfter=2.5 * mm, + ), + "table": ParagraphStyle( + "TableCell", + fontName="BodyCN", + fontSize=7.1, + leading=9.7, + textColor=TEXT, + alignment=TA_LEFT, + wordWrap="CJK", + ), + "table_head": ParagraphStyle( + "TableHead", + fontName="HeadCN", + fontSize=7.1, + leading=9.7, + textColor=colors.white, + alignment=TA_CENTER, + wordWrap="CJK", + ), + } + + +def build_table(rows: list[list[str]], width: float, styles: dict[str, ParagraphStyle]) -> Table: + column_count = max(len(row) for row in rows) + normalized = [row + [""] * (column_count - len(row)) for row in rows] + data = [] + for row_index, row in enumerate(normalized): + style = styles["table_head"] if row_index == 0 else styles["table"] + data.append([Paragraph(inline_markup(cell.strip()), style) for cell in row]) + weights = [1.0] * column_count + if column_count >= 3: + weights[-1] = 1.35 + total = sum(weights) + column_widths = [width * value / total for value in weights] + table = Table(data, colWidths=column_widths, repeatRows=1, hAlign="CENTER") + table.setStyle( + TableStyle( + [ + ("BACKGROUND", (0, 0), (-1, 0), NAVY), + ("TEXTCOLOR", (0, 0), (-1, 0), colors.white), + ("GRID", (0, 0), (-1, -1), 0.35, MID_GRAY), + ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), + ("ALIGN", (0, 0), (-1, 0), "CENTER"), + ("LEFTPADDING", (0, 0), (-1, -1), 3.5), + ("RIGHTPADDING", (0, 0), (-1, -1), 3.5), + ("TOPPADDING", (0, 0), (-1, -1), 3.2), + ("BOTTOMPADDING", (0, 0), (-1, -1), 3.2), + ] + + [ + ("BACKGROUND", (0, row), (-1, row), LIGHT_BLUE) + for row in range(2, len(data), 2) + ] + ) + ) + return table + + +def simple_svg_drawing(path: Path) -> Drawing: + """Convert the chart SVG subset used by this report into ReportLab vectors.""" + root = ET.parse(path).getroot() + width = float(root.attrib["width"].removesuffix("px")) + height = float(root.attrib["height"].removesuffix("px")) + drawing = Drawing(width, height) + text_styles = { + "tick": (16, "LightCN", TEXT), + "label": (18, "HeadCN", TEXT), + "panel-title": (21, "HeadCN", TEXT), + "figure-title": (26, "HeadCN", TEXT), + "note": (15, "LightCN", colors.HexColor("#5F6368")), + } + line_styles = { + "grid": (colors.HexColor("#D9DDE3"), 1.0), + "axis": (colors.HexColor("#51565C"), 1.2), + } + + def number(value: str | None, default: float = 0.0) -> float: + return float(value) if value is not None else default + + for element in root: + tag = element.tag.rsplit("}", 1)[-1] + attrs = element.attrib + css_class = attrs.get("class", "") + if tag in {"title", "desc", "style"}: + continue + if tag == "rect": + rect_width = width if attrs.get("width") == "100%" else number(attrs.get("width")) + rect_height = height if attrs.get("height") == "100%" else number(attrs.get("height")) + x = number(attrs.get("x")) + y = height - number(attrs.get("y")) - rect_height + drawing.add( + Rect( + x, + y, + rect_width, + rect_height, + fillColor=colors.HexColor(attrs.get("fill", "#FFFFFF")), + strokeColor=None, + ) + ) + continue + if tag == "line": + stroke, stroke_width = line_styles.get( + css_class, + ( + colors.HexColor(attrs.get("stroke", "#000000")), + number(attrs.get("stroke-width"), 1.0), + ), + ) + drawing.add( + Line( + number(attrs.get("x1")), + height - number(attrs.get("y1")), + number(attrs.get("x2")), + height - number(attrs.get("y2")), + strokeColor=stroke, + strokeWidth=stroke_width, + ) + ) + continue + if tag == "circle": + drawing.add( + Circle( + number(attrs.get("cx")), + height - number(attrs.get("cy")), + number(attrs.get("r")), + fillColor=colors.HexColor(attrs.get("fill", "#000000")), + strokeColor=colors.HexColor(attrs.get("stroke", "#000000")), + strokeWidth=number(attrs.get("stroke-width"), 1.0), + ) + ) + continue + if tag == "path": + tokens = re.findall(r"[ML]|-?\d+(?:\.\d+)?", attrs.get("d", "")) + graphic_path = GraphicsPath() + cursor = 0 + command = "M" + while cursor < len(tokens): + if tokens[cursor] in {"M", "L"}: + command = tokens[cursor] + cursor += 1 + x = float(tokens[cursor]) + y = height - float(tokens[cursor + 1]) + cursor += 2 + if command == "M": + graphic_path.moveTo(x, y) + command = "L" + else: + graphic_path.lineTo(x, y) + graphic_path.fillColor = None + graphic_path.strokeColor = colors.HexColor(attrs.get("stroke", "#000000")) + graphic_path.strokeWidth = number(attrs.get("stroke-width"), 1.0) + drawing.add(graphic_path) + continue + if tag == "text": + font_size, font_name, fill = text_styles.get(css_class, (11, "LightCN", TEXT)) + angle = 90 if "rotate(-90" in attrs.get("transform", "") else 0 + value = "".join(element.itertext()).replace("–", "-").replace("—", "-") + drawing.add( + String( + number(attrs.get("x")), + height - number(attrs.get("y")), + value, + fontName=font_name, + fontSize=font_size, + fillColor=fill, + textAnchor=attrs.get("text-anchor", "start"), + angle=angle, + ) + ) + return drawing + + +def add_svg(story: list[Flowable], path: Path, max_width: float, max_height: float) -> bool: + if path.name.startswith("report-"): + drawing = simple_svg_drawing(path) + else: + try: + from svglib.svglib import svg2rlg + except ImportError: + drawing = simple_svg_drawing(path) + else: + drawing = svg2rlg(str(path)) + if drawing is None: + return False + scale = min(max_width / drawing.width, max_height / drawing.height, 1.0) + drawing.width *= scale + drawing.height *= scale + drawing.scale(scale, scale) + drawing.hAlign = "CENTER" + story.append(Spacer(1, 2 * mm)) + story.append(drawing) + return True + + +def parse_markdown(text: str, doc: TechnicalReport, styles: dict[str, ParagraphStyle]) -> list[Flowable]: + lines = text.splitlines() + story: list[Flowable] = [] + story.append(Spacer(1, 11 * mm)) + story.append(Paragraph(inline_markup(lines[0].removeprefix("# ")), styles["title"])) + story.append(Rule(doc.width)) + story.append(Spacer(1, 5 * mm)) + story.append(Paragraph("作者:花生  学员 ID:PurplePulse", styles["author"])) + + index = 2 + paragraph_lines: list[str] = [] + in_code = False + code_lines: list[str] = [] + in_equation = False + equation_lines: list[str] = [] + abstract_mode = False + references_mode = False + + def flush_paragraph() -> None: + if not paragraph_lines: + return + value = " ".join(part.strip() for part in paragraph_lines) + style = styles["abstract"] if abstract_mode else styles["body"] + story.append(Paragraph(inline_markup(value), style)) + paragraph_lines.clear() + + while index < len(lines): + line = lines[index] + stripped = line.strip() + + if stripped.startswith("```"): + flush_paragraph() + if in_code: + story.append( + Paragraph("
".join(escape(item) for item in code_lines), styles["code"]) + ) + code_lines.clear() + in_code = False + else: + in_code = True + index += 1 + continue + if in_code: + code_lines.append(line) + index += 1 + continue + + if stripped == "$$": + flush_paragraph() + if in_equation: + rendered = "
".join( + escape(equation_text(item)) for item in equation_lines if item.strip() + ) + story.append(Paragraph(rendered, styles["equation"])) + equation_lines.clear() + in_equation = False + else: + in_equation = True + index += 1 + continue + if in_equation: + equation_lines.append(line) + index += 1 + continue + + if stripped.startswith("!["): + flush_paragraph() + match = re.match(r"!\[([^\]]*)\]\(([^)]+)\)", stripped) + if match: + image_path = (SOURCE.parent / match.group(2)).resolve() + add_svg(story, image_path, doc.width * 0.88, 82 * mm) + index += 1 + continue + + if stripped.startswith("**图"): + flush_paragraph() + story.append(Paragraph(inline_markup(stripped), styles["caption"])) + index += 1 + continue + + if stripped.startswith("## "): + flush_paragraph() + title = stripped[3:].strip() + abstract_mode = title == "摘要" + references_mode = title == "参考文献" + heading_style = styles["references_heading"] if references_mode else styles["h1"] + paragraph = Paragraph(inline_markup(title), heading_style) + paragraph.heading_level = 1 + story.append(paragraph) + index += 1 + continue + + if stripped.startswith("### "): + flush_paragraph() + abstract_mode = False + paragraph = Paragraph(inline_markup(stripped[4:].strip()), styles["h2"]) + paragraph.heading_level = 2 + story.append(paragraph) + index += 1 + continue + + if stripped.startswith("|") and index + 1 < len(lines) and re.match( + r"^\s*\|?\s*:?-+", lines[index + 1] + ): + flush_paragraph() + rows: list[list[str]] = [] + rows.append([cell for cell in stripped.strip("|").split("|")]) + index += 2 + while index < len(lines) and lines[index].strip().startswith("|"): + rows.append([cell for cell in lines[index].strip().strip("|").split("|")]) + index += 1 + story.append(Spacer(1, 1.5 * mm)) + story.append(build_table(rows, doc.width, styles)) + story.append(Spacer(1, 2.8 * mm)) + continue + + list_match = re.match(r"^(\d+)\.\s+(.*)", stripped) + if list_match: + flush_paragraph() + item_parts = [list_match.group(2)] + item_number = list_match.group(1) + index += 1 + while index < len(lines) and lines[index].startswith(" "): + continuation = lines[index].strip() + if continuation: + item_parts.append(continuation) + index += 1 + story.append( + Paragraph( + f"{item_number}. {inline_markup(' '.join(item_parts))}", + styles["references"] if references_mode else styles["list"], + ) + ) + continue + + if not stripped: + flush_paragraph() + elif index == 2 and stripped.startswith("**作者"): + pass + else: + paragraph_lines.append(stripped) + index += 1 + + flush_paragraph() + return story + + +def main() -> None: + global SOURCE, OUTPUT + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, default=SOURCE) + parser.add_argument("--output", type=Path, default=OUTPUT) + parser.add_argument("--body-font") + parser.add_argument("--heading-font") + parser.add_argument("--light-font") + parser.add_argument("--mono-font") + args = parser.parse_args() + SOURCE = args.source.resolve() + OUTPUT = args.output.resolve() + from build_report_figures import generate_report_figures + + generate_report_figures() + register_fonts(args.body_font, args.heading_font, args.light_font, + args.mono_font) + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + doc = TechnicalReport(str(OUTPUT)) + styles = make_styles() + story = parse_markdown(SOURCE.read_text(encoding="utf-8"), doc, styles) + doc.build(story) + print(OUTPUT) + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/build_report_figures.py b/09_vector_retrieval/PurplePulse/scripts/build_report_figures.py new file mode 100644 index 00000000..3042ef65 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/build_report_figures.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""Generate the Chinese figures used by the final technical report.""" + +from __future__ import annotations + +import csv +import html +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / "results" / "figures" +WIDTH = 1120 +HEIGHT = 520 + +NAVY = "#142B4A" +BLUE = "#2878B5" +ORANGE = "#D95F02" +GREEN = "#2A9D8F" +GOLD = "#E9C46A" +PALE = "#EAF1F7" +GRID = "#D9DDE3" +TEXT = "#18212B" +MUTED = "#65717D" + + +def esc(value: object) -> str: + return html.escape(str(value), quote=True) + + +def attrs(values: dict[str, object]) -> str: + return " ".join( + f'{key.rstrip("_").replace("_", "-")}="{esc(value)}"' + for key, value in values.items() + ) + + +def text(x: float, y: float, value: object, css: str = "label", **extra: object) -> str: + return f'{esc(value)}' + + +def line(x1: float, y1: float, x2: float, y2: float, css: str = "grid", **extra: object) -> str: + return ( + f'' + ) + + +def rect(x: float, y: float, width: float, height: float, fill: str, **extra: object) -> str: + return ( + f'' + ) + + +def circle(x: float, y: float, radius: float, fill: str) -> str: + return ( + f'' + ) + + +def path(points: list[tuple[float, float]], color: str) -> str: + commands = " ".join( + f'{"M" if index == 0 else "L"} {x:.2f} {y:.2f}' + for index, (x, y) in enumerate(points) + ) + return f'' + + +def svg(title: str, body: list[str], width: int = WIDTH, height: int = HEIGHT) -> str: + return "\n".join( + [ + f'', + f'{esc(title)}', + '图中数据由仓库内原始 CSV 自动生成。', + '', + '', + *body, + '', + '', + ] + ) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as source: + rows = list(csv.DictReader(source)) + if not rows: + raise ValueError(f"empty CSV: {path}") + return rows + + +def integer_label(value: float | int) -> str: + """Format chart counts consistently with report tables.""" + return f"{round(float(value)):,}" + + +def write(name: str, contents: str) -> Path: + OUT.mkdir(parents=True, exist_ok=True) + target = OUT / name + target.write_text(contents, encoding="utf-8") + return target + + +def architecture_figure() -> str: + body = [text(40, 42, "WarpFusion 向量检索系统的组成与数据流", "figure-title")] + panels = [ + (36, 210, "输入", ["向量库与查询", "检索参数", "公开数据校验和"]), + (278, 248, "CPU 端准备", ["格式与参数检查", "精确结果参考", "构建并保存 IVF 索引"]), + (558, 300, "GPU 常驻检索", ["Exact:边算距离边选 Top-K", "IVF:选桶、扫描、合并", "每批只传查询与结果"]), + (890, 194, "输出证据", ["ID 与分数", "召回率与延迟", "CSV、图表、报告"]), + ] + for x, width, heading, items in panels: + body.append(rect(x, 78, width, 354, PALE if heading == "GPU 常驻检索" else "#F4F5F7")) + body.append(text(x + 20, 112, heading, "panel-title")) + for index, item in enumerate(items): + y = 142 + index * 86 + body.append(rect(x + 20, y, width - 40, 62, "#FFFFFF")) + body.append(text(x + width / 2, y + 37, item, "label", text_anchor="middle")) + for x1, x2 in ((246, 278), (526, 558), (858, 890)): + body.append(line(x1, 255, x2, 255, "axis", stroke=BLUE, stroke_width=2.4)) + body.append(text((x1 + x2) / 2, 245, "→", "label", text_anchor="middle")) + body.append(line(55, 463, 1065, 463, "axis", stroke=GRID, stroke_width=1.2)) + body.append(text(WIDTH / 2, 494, "每一次优化都要同时通过正确性检查和同输入 A/B 对照", "note", text_anchor="middle")) + return svg("WarpFusion 系统流程", body) + + +def exact_fused_figure() -> str: + rows = read_csv(ROOT / "results/exact_fused/million_compare.csv") + values = {(int(row["top_k"]), row["mode"]): float(row["qps"]) for row in rows} + body = [text(WIDTH / 2, 34, "Exact 融合路径与距离矩阵基线的吞吐对比", "figure-title", text_anchor="middle")] + left, right, top, bottom = 95, 1070, 78, 420 + maximum = 6000.0 + for tick in range(0, 6001, 1000): + y = bottom - tick / maximum * (bottom - top) + body.append(line(left, y, right, y)) + body.append(text(left - 12, y + 4, integer_label(tick), "tick", text_anchor="end")) + body.append(line(left, top, left, bottom, "axis", stroke=MUTED, stroke_width=1.2)) + centers = [260, 560, 860] + bar_width = 82 + for center, top_k in zip(centers, (10, 50, 100)): + matrix = values[(top_k, "matrix")] + fused = values[(top_k, "fused")] + for offset, value, color, label in ((-52, matrix, MUTED, "距离矩阵"), (52, fused, BLUE, "融合路径")): + height = value / maximum * (bottom - top) + body.append(rect(center + offset - bar_width / 2, bottom - height, bar_width, height, color)) + body.append(text(center + offset, bottom - height - 10, integer_label(value), "note", text_anchor="middle")) + body.append(text(center, 452, f"K={top_k}", "label", text_anchor="middle")) + body.append(text(center, 482, f"加速比 {fused / matrix:.2f}×", "note", text_anchor="middle")) + body.extend([ + rect(770, 48, 18, 12, MUTED), text(797, 60, "先写距离矩阵", "note"), + rect(925, 48, 18, 12, BLUE), text(952, 60, "边计算边选 Top-K", "note"), + ]) + return svg("Exact 融合路径吞吐", body) + + +def exact_breakdown_figure() -> str: + datasets = [ + ("百万条 128 维合成数据", ROOT / "results/stage7_exact_profile/synthetic1m/breakdown.csv"), + ("67.7 万条 384 维文本向量", ROOT / "results/stage7_exact_profile/yahoo-minilm-384/breakdown.csv"), + ] + body = [text(WIDTH / 2, 34, "Exact 融合路径的 GPU 执行时间分解", "figure-title", text_anchor="middle")] + colors = [BLUE, GOLD, ORANGE] + labels = ["距离与向量读取", "局部 Top-K", "最终合并"] + for index, (label, _) in enumerate(zip(labels, colors)): + x = 370 + index * 180 + body.append(rect(x, 49, 16, 11, colors[index])) + body.append(text(x + 24, 60, label, "note")) + for panel_index, (dataset_name, source) in enumerate(datasets): + rows = read_csv(source) + x0 = 60 + panel_index * 550 + body.append(text(x0 + 250, 94, dataset_name, "panel-title", text_anchor="middle")) + for bar_index, row in enumerate(rows): + x = x0 + 90 + bar_index * 145 + y = 400 + shares = [ + float(row["distance_share"]), + float(row["local_topk_share"]), + float(row["final_merge_share"]), + ] + for share, color in zip(shares, colors): + height = share * 270 + body.append(rect(x, y - height, 72, height, color)) + y -= height + body.append(text(x + 36, 427, f"K={row['top_k']}", "label", text_anchor="middle")) + body.append(text(x + 36, 118, f"{shares[0] * 100:.1f}%", "note", text_anchor="middle")) + body.append(line(x0 + 50, 400, x0 + 500, 400, "axis", stroke=MUTED, stroke_width=1.2)) + body.append(text(WIDTH / 2, 482, "柱顶数字表示“距离计算与向量读取”占 GPU 核函数流水的比例", "note", text_anchor="middle")) + return svg("Exact 耗时分解", body) + + +def k50_scheduling_figure() -> str: + rows = read_csv(ROOT / "results/formal_4090d_20260908/k50_bucket_major_sweep.csv") + body = [text(WIDTH / 2, 34, "K=50 条件下按桶任务调度的性能影响", "figure-title", text_anchor="middle")] + left, right, top, bottom = 95, 1070, 80, 410 + x_values = [float(row["nprobe"]) for row in rows] + all_qps = [float(row[key]) for row in rows for key in ("probe_major_qps", "bucket_major_qps")] + y_min, y_max = 0.0, max(all_qps) * 1.08 + for tick in range(0, 25001, 5000): + y = bottom - (tick - y_min) / (y_max - y_min) * (bottom - top) + body.append(line(left, y, right, y)) + body.append(text(left - 10, y + 4, integer_label(tick), "tick", text_anchor="end")) + def px(value: float) -> float: + return left + (value - min(x_values)) / (max(x_values) - min(x_values)) * (right - left) + def py(value: float) -> float: + return bottom - (value - y_min) / (y_max - y_min) * (bottom - top) + for value in x_values: + x = px(value) + body.append(line(x, top, x, bottom)) + body.append(text(x, 434, int(value), "tick", text_anchor="middle")) + for key, color, label in (("probe_major_qps", MUTED, "按查询顺序"), ("bucket_major_qps", BLUE, "按桶重排")): + points = [(px(float(row["nprobe"])), py(float(row[key]))) for row in rows] + body.append(path(points, color)) + for x, y in points: + body.append(circle(x, y, 5, color)) + body.append(line(770 if key == "probe_major_qps" else 920, 55, 795 if key == "probe_major_qps" else 945, 55, "axis", stroke=color, stroke_width=3)) + body.append(text(802 if key == "probe_major_qps" else 952, 60, label, "note")) + last = rows[-1] + body.append(text(px(float(last["nprobe"])) - 5, py(float(last["bucket_major_qps"])) - 14, f"+{float(last['speedup_percent']):.1f}%", "label", text_anchor="end")) + body.append(text((left + right) / 2, 474, "搜索桶数 nprobe", "label", text_anchor="middle")) + return svg("K=50 任务调度", body) + + +def k100_partitioned_figure() -> str: + full = read_csv(ROOT / "results/real/sift1m/ivf_k100_full_heap.csv") + partitioned = read_csv(ROOT / "results/real/sift1m/ivf_k100_partitioned.csv") + body = [text(WIDTH / 2, 34, "K=100 条件下分区候选结构的性能影响", "figure-title", text_anchor="middle")] + left, right, top, bottom = 95, 1070, 82, 410 + x_values = [float(row["nprobe"]) for row in full] + maximum = max(float(row["qps"]) for row in partitioned) * 1.08 + for tick in range(0, 50001, 10000): + y = bottom - tick / maximum * (bottom - top) + body.append(line(left, y, right, y)) + body.append(text(left - 10, y + 4, integer_label(tick), "tick", text_anchor="end")) + def px(value: float) -> float: + return left + (value - min(x_values)) / (max(x_values) - min(x_values)) * (right - left) + def py(value: float) -> float: + return bottom - value / maximum * (bottom - top) + for value in x_values: + x = px(value) + body.append(line(x, top, x, bottom)) + body.append(text(x, 434, int(value), "tick", text_anchor="middle")) + for rows, color, label in ((full, MUTED, "完整大候选表"), (partitioned, GREEN, "4 个小候选表")): + points = [(px(float(row["nprobe"])), py(float(row["qps"]))) for row in rows] + body.append(path(points, color)) + for x, y in points: + body.append(circle(x, y, 5, color)) + base_x = 780 if rows is full else 940 + body.append(line(base_x, 56, base_x + 25, 56, "axis", stroke=color, stroke_width=3)) + body.append(text(base_x + 32, 61, label, "note")) + row160_full = next(row for row in full if int(row["nprobe"]) == 160) + row160_part = next(row for row in partitioned if int(row["nprobe"]) == 160) + ratio = float(row160_part["qps"]) / float(row160_full["qps"]) + body.append(text(px(160), py(float(row160_part["qps"])) - 16, f"Recall@100 相同;加速比 {ratio:.2f}×", "label", text_anchor="middle")) + body.append(text((left + right) / 2, 474, "搜索桶数 nprobe", "label", text_anchor="middle")) + return svg("K=100 分区候选", body) + + +def real_comparison_figure() -> str: + datasets = [("SIFT1M(图像特征)", "sift1m"), ("Yahoo MiniLM(文本向量)", "yahoo-minilm-384")] + body = [text(WIDTH / 2, 34, "公开数据集上的端到端吞吐对比(nprobe=160)", "figure-title", text_anchor="middle")] + for panel_index, (title, directory) in enumerate(datasets): + root = ROOT / "results/real" / directory + faiss = read_csv(root / "faiss_gpu.csv") + x0 = 55 + panel_index * 550 + body.append(text(x0 + 250, 80, title, "panel-title", text_anchor="middle")) + warp_values = [] + faiss_values = [] + recalls = [] + for top_k in (10, 50, 100): + warp = next(row for row in read_csv(root / f"ivf_k{top_k}.csv") if int(row["nprobe"]) == 160) + baseline = next( + row for row in faiss + if row["index_type"] == "ivf_flat" and int(row["top_k"]) == top_k and int(row["nprobe"]) == 160 + ) + warp_values.append(float(warp["qps"])) + faiss_values.append(float(baseline["qps"])) + recalls.append((float(warp["recall_at_k"]), float(baseline["recall_at_k"]))) + maximum = max(warp_values + faiss_values) * 1.15 + panel_bottom, panel_top = 405, 112 + for group, top_k in enumerate((10, 50, 100)): + center = x0 + 95 + group * 155 + for offset, value, color in ((-27, warp_values[group], BLUE), (27, faiss_values[group], ORANGE)): + height = value / maximum * (panel_bottom - panel_top) + body.append(rect(center + offset - 22, panel_bottom - height, 44, height, color)) + ratio = warp_values[group] / faiss_values[group] + body.append(text(center, min(panel_bottom - warp_values[group] / maximum * (panel_bottom - panel_top), panel_bottom - faiss_values[group] / maximum * (panel_bottom - panel_top)) - 10, f"{ratio:.2f}×", "note", text_anchor="middle")) + body.append(text(center, 432, f"K={top_k}", "label", text_anchor="middle")) + body.append(text(center, 458, f"召回 {recalls[group][0]:.4f}/{recalls[group][1]:.4f}", "note", text_anchor="middle")) + body.append(line(x0 + 35, panel_bottom, x0 + 505, panel_bottom, "axis", stroke=MUTED, stroke_width=1.2)) + body.extend([ + rect(780, 49, 16, 11, BLUE), text(804, 60, "WarpFusion", "note"), + rect(920, 49, 16, 11, ORANGE), text(944, 60, "FAISS GPU", "note"), + text(WIDTH / 2, 496, "召回数字依次为 WarpFusion / FAISS;两者各自训练聚类中心", "note", text_anchor="middle"), + ]) + return svg("公开数据对比", body) + + +def recall_qps_figure() -> str: + datasets = [ + ("SIFT1M(图像特征)", "sift1m"), + ("Yahoo MiniLM(文本向量)", "yahoo-minilm-384"), + ] + body = [ + text( + WIDTH / 2, + 34, + "公开数据集上的召回率与吞吐权衡(K=10)", + "figure-title", + text_anchor="middle", + ) + ] + panel_top, panel_bottom = 98, 402 + panel_width = 455 + for panel_index, (title, directory) in enumerate(datasets): + root = ROOT / "results" / "real" / directory + warp = read_csv(root / "ivf_k10.csv") + faiss = [ + row + for row in read_csv(root / "faiss_gpu.csv") + if row["index_type"] == "ivf_flat" and int(row["top_k"]) == 10 + ] + series = ((warp, BLUE, "WarpFusion"), (faiss, ORANGE, "FAISS GPU")) + recalls = [float(row["recall_at_k"]) for rows, _, _ in series for row in rows] + qps_values = [float(row["qps"]) for rows, _, _ in series for row in rows] + x_min = max(0.0, min(recalls) - 0.003) + x_max = min(1.0, max(recalls) + 0.001) + y_max = max(qps_values) * 1.08 + left = 78 + panel_index * 550 + right = left + panel_width + + body.append(text((left + right) / 2, 76, title, "panel-title", text_anchor="middle")) + for tick_index in range(5): + fraction = tick_index / 4 + x = left + fraction * panel_width + recall = x_min + fraction * (x_max - x_min) + body.append(line(x, panel_top, x, panel_bottom)) + body.append(text(x, 425, f"{recall * 100:.1f}%", "tick", text_anchor="middle")) + qps_tick = y_max * fraction + y = panel_bottom - fraction * (panel_bottom - panel_top) + body.append(line(left, y, right, y)) + body.append(text(left - 9, y + 4, integer_label(qps_tick), "tick", text_anchor="end")) + + def px(value: float) -> float: + return left + (value - x_min) / (x_max - x_min) * panel_width + + def py(value: float) -> float: + return panel_bottom - value / y_max * (panel_bottom - panel_top) + + for rows, color, _ in series: + points = [(px(float(row["recall_at_k"])), py(float(row["qps"]))) for row in rows] + body.append(path(points, color)) + for x, y in points: + body.append(circle(x, y, 4.5, color)) + body.append(text(left + 8, panel_top + 18, "nprobe=32", "note")) + body.append(text(right - 8, panel_bottom - 10, "nprobe=224", "note", text_anchor="end")) + body.append(line(left, panel_top, left, panel_bottom, "axis", stroke=MUTED, stroke_width=1.2)) + body.append(line(left, panel_bottom, right, panel_bottom, "axis", stroke=MUTED, stroke_width=1.2)) + + body.extend( + [ + line(770, 52, 795, 52, "axis", stroke=BLUE, stroke_width=3), + text(802, 57, "WarpFusion", "note"), + line(920, 52, 945, 52, "axis", stroke=ORANGE, stroke_width=3), + text(952, 57, "FAISS GPU", "note"), + text(WIDTH / 2, 458, "横轴为 Recall@10,纵轴为 QPS;每条曲线包含 nprobe=32、64、128、160、192、224", "note", text_anchor="middle"), + text(WIDTH / 2, 486, "越靠近右上方表示在相同召回率附近具有更高吞吐", "note", text_anchor="middle"), + ] + ) + return svg("召回率与吞吐权衡", body) + + +def generate_report_figures() -> list[Path]: + figures = { + "report-architecture.svg": architecture_figure(), + "report-exact-fused.svg": exact_fused_figure(), + "report-exact-breakdown.svg": exact_breakdown_figure(), + "report-k50-scheduling.svg": k50_scheduling_figure(), + "report-k100-partitioned.svg": k100_partitioned_figure(), + "report-recall-qps.svg": recall_qps_figure(), + "report-real-comparison.svg": real_comparison_figure(), + } + return [write(name, contents) for name, contents in figures.items()] + + +if __name__ == "__main__": + for generated in generate_report_figures(): + print(generated) diff --git a/09_vector_retrieval/PurplePulse/scripts/evaluate_ivecs_groundtruth.py b/09_vector_retrieval/PurplePulse/scripts/evaluate_ivecs_groundtruth.py new file mode 100644 index 00000000..d69b0da7 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/evaluate_ivecs_groundtruth.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Evaluate WarpFusion text results against TexMex ivecs ground truth.""" + +from __future__ import annotations + +import argparse +import json +import struct +from pathlib import Path + +import numpy as np + +from import_sift1m import inspect_vecs, record_dtype + + +def read_result_rows(path: Path) -> tuple[list[list[int]], list[list[float]]]: + rows: dict[int, list[int]] = {} + scores: dict[int, list[float]] = {} + for line_number, line in enumerate(path.read_text().splitlines(), 1): + parts = line.split() + if len(parts) != 3: + raise ValueError(f"{path}:{line_number}: expected three columns") + query_id = int(parts[0]) + vector_id = int(parts[1]) + score = float(parts[2]) + if query_id < 0 or vector_id < 0: + raise ValueError(f"{path}:{line_number}: IDs must be non-negative") + rows.setdefault(query_id, []).append(vector_id) + scores.setdefault(query_id, []).append(score) + if not rows or sorted(rows) != list(range(len(rows))): + raise ValueError("result query IDs must be contiguous and start at zero") + top_k = len(rows[0]) + if top_k == 0 or any(len(values) != top_k for values in rows.values()): + raise ValueError("all result queries must have the same positive K") + return ( + [rows[index] for index in range(len(rows))], + [scores[index] for index in range(len(rows))], + ) + + +def read_result_ids(path: Path) -> list[list[int]]: + return read_result_rows(path)[0] + + +def read_vectors(path: Path, database: bool): + with path.open("rb") as source: + magic = source.read(8) + expected_magic = b"PPVEC001" if database else b"PPQRY001" + if magic != expected_magic: + raise ValueError(f"{path}: invalid vector file magic") + if database: + rows, dim, dtype_code, metric_code = struct.unpack(" None: + database, metric = read_vectors(database_path, database=True) + queries, _ = read_vectors(query_path, database=False) + if metric is None or len(queries) < len(actual_ids) or database.shape[1] != queries.shape[1]: + raise ValueError("database/query shape or metric mismatch") + equivalent_queries = 0 + rank_errors = [] + reported_errors = [] + descending = metric in {2, 3} + for query_id in range(len(actual_ids)): + expected_scores = vector_scores( + database, queries[query_id], reference[query_id], metric + ) + recomputed_scores = vector_scores( + database, queries[query_id], actual_ids[query_id], metric + ) + expected_scores = np.sort(expected_scores) + recomputed_scores = np.sort(recomputed_scores) + if descending: + expected_scores = expected_scores[::-1] + recomputed_scores = recomputed_scores[::-1] + errors = np.abs( + expected_scores.astype(np.float64) - recomputed_scores.astype(np.float64) + ) + rank_errors.extend(errors.tolist()) + if np.allclose(expected_scores, recomputed_scores, rtol=rtol, atol=atol): + equivalent_queries += 1 + reported_errors.extend( + np.abs( + actual_reported_scores[query_id].astype(np.float64) + - vector_scores( + database, queries[query_id], actual_ids[query_id], metric + ).astype(np.float64) + ).tolist() + ) + result.update( + { + "metric": {1: "l2", 2: "inner_product", 3: "cosine"}[metric], + "score_equivalent_query_fraction": equivalent_queries / len(actual_ids), + "mean_rank_score_error": float(np.mean(rank_errors)), + "max_rank_score_error": float(np.max(rank_errors)), + "mean_reported_score_error": float(np.mean(reported_errors)), + "max_reported_score_error": float(np.max(reported_errors)), + "score_rtol": rtol, + "score_atol": atol, + } + ) + del database + del queries + + +def evaluate( + groundtruth_path: Path, + result_path: Path, + database_path: Path | None = None, + query_path: Path | None = None, + score_rtol: float = 1e-5, + score_atol: float = 1e-4, +) -> dict[str, float | int | str]: + actual, actual_scores = read_result_rows(result_path) + info = inspect_vecs(groundtruth_path, "ivecs") + if len(actual) > info.rows: + raise ValueError("results contain more queries than ground truth") + top_k = len(actual[0]) + if top_k > info.dim: + raise ValueError(f"result K={top_k} exceeds ground truth K={info.dim}") + records = np.memmap( + groundtruth_path, + dtype=record_dtype(info.dim, "ivecs"), + mode="r", + shape=(info.rows,), + ) + reference = np.asarray(records["values"][: len(actual), :top_k]) + actual_array = np.asarray(actual, dtype=np.int64) + per_query = np.asarray( + [ + len(set(expected.tolist()) & set(found.tolist())) / top_k + for expected, found in zip(reference, actual_array) + ], + dtype=np.float64, + ) + result: dict[str, float | int | str] = { + "queries": len(actual), + "top_k": top_k, + "recall_at_k": float(per_query.mean()), + "min_query_recall": float(per_query.min()), + "exact_query_fraction": float(np.mean(per_query == 1.0)), + } + if (database_path is None) != (query_path is None): + raise ValueError("database and queries must be provided together") + if database_path is not None and query_path is not None: + add_score_equivalence( + result, + reference, + actual_array, + np.asarray(actual_scores, dtype=np.float32), + database_path, + query_path, + score_rtol, + score_atol, + ) + del records + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--groundtruth", type=Path, required=True) + parser.add_argument("--results", type=Path, required=True) + parser.add_argument("--database", type=Path) + parser.add_argument("--queries", type=Path) + parser.add_argument("--score-rtol", type=float, default=1e-5) + parser.add_argument("--score-atol", type=float, default=1e-4) + parser.add_argument("--json", action="store_true") + args = parser.parse_args() + result = evaluate( + args.groundtruth, + args.results, + args.database, + args.queries, + args.score_rtol, + args.score_atol, + ) + if args.json: + print(json.dumps(result, sort_keys=True)) + else: + print( + f"recall@{result['top_k']}={result['recall_at_k']:.6f}, " + f"min_query_recall={result['min_query_recall']:.6f}, " + f"exact_query_fraction={result['exact_query_fraction']:.6f}, " + f"queries={result['queries']}" + ) + if "score_equivalent_query_fraction" in result: + print( + "score_equivalent_query_fraction=" + f"{result['score_equivalent_query_fraction']:.6f}, " + f"max_rank_score_error={result['max_rank_score_error']:.9g}, " + f"max_reported_score_error={result['max_reported_score_error']:.9g}" + ) + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/evaluate_recall.py b/09_vector_retrieval/PurplePulse/scripts/evaluate_recall.py new file mode 100644 index 00000000..755c1f72 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/evaluate_recall.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""计算近似 Top-K 相对 exact ground truth 的 recall@K 和分数误差。""" + +import argparse +from collections import defaultdict +from pathlib import Path + + +def read_results(path): + results = defaultdict(list) + for line_number, line in enumerate(Path(path).read_text().splitlines(), 1): + parts = line.split() + if len(parts) != 3: + raise ValueError(f"{path}:{line_number} 不是三列") + results[int(parts[0])].append((int(parts[1]), float(parts[2]))) + return results + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--exact", required=True) + parser.add_argument("--approximate", required=True) + args = parser.parse_args() + + exact = read_results(args.exact) + approximate = read_results(args.approximate) + if exact.keys() != approximate.keys(): + raise SystemExit("失败:query ID 集合不同") + + matches = 0 + total = 0 + per_query = [] + for query_id in exact: + if len(exact[query_id]) != len(approximate[query_id]): + raise SystemExit(f"失败:query {query_id} 的 K 不同") + exact_ids = {vector_id for vector_id, _ in exact[query_id]} + approximate_ids = {vector_id for vector_id, _ in approximate[query_id]} + query_matches = len(exact_ids & approximate_ids) + matches += query_matches + total += len(exact[query_id]) + per_query.append(query_matches / len(exact[query_id])) + + score_errors = [ + abs(exact_neighbor[1] - approximate_neighbor[1]) + for query_id in exact + for exact_neighbor, approximate_neighbor in zip( + exact[query_id], approximate[query_id] + ) + ] + + print( + f"recall@K={matches / total:.6f}, " + f"min_query_recall={min(per_query):.6f}, " + f"mean_absolute_score_error={sum(score_errors) / len(score_errors):.9g}, " + f"max_absolute_score_error={max(score_errors):.9g}, " + f"queries={len(per_query)}, K={len(next(iter(exact.values())))}" + ) + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/generate_data.py b/09_vector_retrieval/PurplePulse/scripts/generate_data.py new file mode 100644 index 00000000..8e4b4234 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/generate_data.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""生成项目自定义的 FP32/FP16 向量库和查询文件。""" + +import argparse +import random +import struct +from pathlib import Path + +try: + import numpy as np +except ImportError: + np = None + + +METRICS = {"l2": 1, "inner_product": 2, "cosine": 3} +FLOAT32 = 1 +FLOAT16 = 2 +DTYPES = {"fp32": FLOAT32, "fp16": FLOAT16} + + +def write_floats(file, values, dtype, chunk_size=65536): + """分块写入,避免百万级数据时一次创建巨大的 bytes 对象。""" + for start in range(0, len(values), chunk_size): + chunk = values[start : start + chunk_size] + format_code = "f" if dtype == "fp32" else "e" + file.write(struct.pack(f"<{len(chunk)}{format_code}", *chunk)) + + +def make_values(random_generator, count): + return [random_generator.uniform(-1.0, 1.0) for _ in range(count)] + + +def write_random_values(file, random_generator, total_count, dtype): + while total_count: + count = min(total_count, 1_048_576) + if np is None: + write_floats(file, make_values(random_generator, count), dtype) + else: + numpy_dtype = " argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--num-vectors", type=int, required=True) + parser.add_argument("--sessions", type=int, default=16) + parser.add_argument("--source-types", type=int, default=4) + parser.add_argument("--start-timestamp", type=int, default=1_700_000_000) + parser.add_argument("--timestamp-span", type=int, default=2_592_000) + parser.add_argument("--seed", type=int, default=2026) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if ( + args.num_vectors <= 0 + or args.sessions <= 0 + or args.source_types <= 0 + or args.start_timestamp < 0 + or args.timestamp_span < 0 + ): + raise SystemExit("counts must be positive and timestamps non-negative") + if args.sessions >= 2**32 or args.source_types >= 2**32: + raise SystemExit("sessions and source-types must fit uint32") + + rng = random.Random(args.seed) + timestamps = [ + args.start_timestamp + rng.randrange(args.timestamp_span + 1) + for _ in range(args.num_vectors) + ] + importance = [rng.random() for _ in range(args.num_vectors)] + sessions = [rng.randrange(args.sessions) for _ in range(args.num_vectors)] + source_types = [ + rng.randrange(args.source_types) for _ in range(args.num_vectors) + ] + + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.open("wb") as output: + output.write(MAGIC) + output.write(struct.pack(" str: + digest = hashlib.sha256() + with path.open("rb") as source: + while chunk := source.read(chunk_bytes): + digest.update(chunk) + return digest.hexdigest() + + +def normalized_distance(value: object) -> str: + if isinstance(value, bytes): + value = value.decode("utf-8") + distance = str(value).strip().lower() + if distance not in METRIC_CODES: + raise ValueError(f"unsupported ANN-Benchmarks distance: {distance}") + return distance + + +def write_vector_file( + dataset, + destination: Path, + rows: int, + metric_code: int | None, + chunk_rows: int = 16384, +) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + dim = int(dataset.shape[1]) + with destination.open("wb") as output: + if metric_code is None: + output.write(QUERY_MAGIC) + output.write(struct.pack(" None: + destination.parent.mkdir(parents=True, exist_ok=True) + top_k = int(dataset.shape[1]) + with destination.open("wb") as output: + for start in range(0, rows, chunk_rows): + ids = np.ascontiguousarray( + dataset[start : min(start + chunk_rows, rows)], dtype="= database_rows): + raise ValueError("ground truth contains an out-of-range vector ID") + if np.any(np.diff(np.sort(ids, axis=1), axis=1) == 0): + raise ValueError("ground truth contains duplicate IDs in one query") + records = np.empty((len(ids), top_k + 1), dtype=" None: + for start in range(0, int(dataset.shape[0]), chunk_rows): + values = np.asarray(dataset[start : start + chunk_rows], dtype=np.float32) + norms = np.linalg.norm(values, axis=1) + if not np.all(np.isfinite(norms)) or not np.allclose( + norms, 1.0, rtol=5e-4, atol=5e-4 + ): + maximum_error = float(np.max(np.abs(norms - 1.0))) + raise ValueError( + f"{name} declares normalized vectors but unit-norm validation failed; " + f"maximum absolute norm error={maximum_error}" + ) + + +def convert( + input_path: Path, + database_output: Path, + query_output: Path, + groundtruth_output: Path, + manifest_output: Path, + query_limit: int | None = None, + expected_sha256: str | None = None, + source_url: str | None = None, + dataset_name: str | None = None, + expected_dim: int | None = None, +) -> dict[str, object]: + try: + import h5py + except ImportError as error: + raise RuntimeError("h5py is required to import ANN-Benchmarks HDF5 files") from error + + input_sha256 = sha256_file(input_path) + if expected_sha256 is not None and input_sha256.lower() != expected_sha256.lower(): + raise ValueError( + f"input SHA-256 mismatch: expected {expected_sha256}, got {input_sha256}" + ) + + with h5py.File(input_path, "r") as source: + required = {"train", "test", "neighbors"} + missing = sorted(required - set(source.keys())) + if missing: + raise ValueError(f"HDF5 is missing datasets: {missing}") + train = source["train"] + test = source["test"] + neighbors = source["neighbors"] + if train.ndim != 2 or test.ndim != 2 or neighbors.ndim != 2: + raise ValueError("train, test, and neighbors must be two-dimensional") + if train.shape[1] != test.shape[1]: + raise ValueError("train and test dimensions differ") + if expected_dim is not None and int(train.shape[1]) != expected_dim: + raise ValueError( + f"dataset dimension mismatch: expected {expected_dim}, " + f"got {int(train.shape[1])}" + ) + if test.shape[0] != neighbors.shape[0]: + raise ValueError("test and neighbors row counts differ") + if query_limit is not None and query_limit <= 0: + raise ValueError("query_limit must be positive") + query_rows = int(test.shape[0]) if query_limit is None else min( + query_limit, int(test.shape[0]) + ) + distance = normalized_distance(source.attrs.get("distance", "euclidean")) + if distance == "normalized": + validate_unit_norms(train, "train") + validate_unit_norms(test, "test") + metric_code = METRIC_CODES[distance] + write_vector_file(train, database_output, int(train.shape[0]), metric_code) + write_vector_file(test, query_output, query_rows, None) + write_groundtruth_ivecs( + neighbors, groundtruth_output, query_rows, int(train.shape[0]) + ) + shape = { + "database_rows": int(train.shape[0]), + "query_rows": query_rows, + "dim": int(train.shape[1]), + "groundtruth_k": int(neighbors.shape[1]), + } + + outputs = {} + for name, path in { + "database": database_output, + "queries": query_output, + "groundtruth": groundtruth_output, + }.items(): + outputs[name] = { + "path": str(path), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + manifest: dict[str, object] = { + "dataset": dataset_name or input_path.stem, + "source_url": source_url, + "source_path": str(input_path), + "source_bytes": input_path.stat().st_size, + "source_sha256": input_sha256, + "distance": distance, + "warpfusion_metric": "cosine" if metric_code == 3 else "l2", + **shape, + "outputs": outputs, + } + manifest_output.parent.mkdir(parents=True, exist_ok=True) + manifest_output.write_text( + json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--database-output", type=Path, required=True) + parser.add_argument("--query-output", type=Path, required=True) + parser.add_argument("--groundtruth-output", type=Path, required=True) + parser.add_argument("--manifest-output", type=Path, required=True) + parser.add_argument("--query-limit", type=int) + parser.add_argument("--expected-sha256") + parser.add_argument("--source-url") + parser.add_argument( + "--dataset-name", + help="Name recorded in the provenance manifest (defaults to the input stem)", + ) + parser.add_argument("--expected-dim", type=int) + args = parser.parse_args() + manifest = convert( + args.input, + args.database_output, + args.query_output, + args.groundtruth_output, + args.manifest_output, + args.query_limit, + args.expected_sha256, + args.source_url, + args.dataset_name, + args.expected_dim, + ) + print( + f"{manifest['dataset']}: {manifest['database_rows']} x {manifest['dim']}, " + f"queries={manifest['query_rows']}, groundtruth_k={manifest['groundtruth_k']}, " + f"distance={manifest['distance']}" + ) + print(f"manifest: {args.manifest_output}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/import_mnist.py b/09_vector_retrieval/PurplePulse/scripts/import_mnist.py new file mode 100644 index 00000000..d798dd86 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/import_mnist.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Convert the public Keras MNIST archive to the project vector format.""" + +from __future__ import annotations + +import argparse +import struct +from pathlib import Path + +import numpy as np + + +def images_to_vectors(images: np.ndarray) -> np.ndarray: + if images.ndim < 2: + raise ValueError("MNIST image array must have at least two dimensions") + rows = images.shape[0] + return np.ascontiguousarray(images.reshape(rows, -1), dtype=" None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("wb") as destination: + destination.write(b"PPVEC001") + destination.write( + struct.pack(" None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("wb") as destination: + destination.write(b"PPQRY001") + destination.write(struct.pack(" tuple[tuple[int, int], tuple[int, int]]: + with np.load(input_path) as archive: + if "x_train" not in archive or "x_test" not in archive: + raise ValueError("MNIST archive must contain x_train and x_test") + database = images_to_vectors(archive["x_train"]) + queries = images_to_vectors(archive["x_test"]) + if database.shape[1] != queries.shape[1]: + raise ValueError("MNIST train and test dimensions differ") + if database_size is not None: + database = database[:database_size] + if query_count is not None: + queries = queries[:query_count] + if len(database) == 0 or len(queries) == 0: + raise ValueError("database and query counts must be positive") + write_database(database_path, database) + write_queries(query_path, queries) + return database.shape, queries.shape + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--database", type=Path, required=True) + parser.add_argument("--queries", type=Path, required=True) + parser.add_argument("--database-size", type=int) + parser.add_argument("--query-count", type=int) + args = parser.parse_args() + database_shape, query_shape = convert( + args.input, + args.database, + args.queries, + args.database_size, + args.query_count, + ) + print(f"database: {database_shape[0]} x {database_shape[1]}") + print(f"queries: {query_shape[0]} x {query_shape[1]}") + print("dtype/metric: fp32/l2") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/import_sift1m.py b/09_vector_retrieval/PurplePulse/scripts/import_sift1m.py new file mode 100644 index 00000000..66359cf0 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/import_sift1m.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Convert TexMex SIFT1M fvecs/ivecs files to WarpFusion input files.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import shutil +import struct +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + + +OFFICIAL_SOURCE = "ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz" +DATABASE_MAGIC = b"PPVEC001" +QUERY_MAGIC = b"PPQRY001" +FLOAT32 = 1 +L2 = 1 + + +@dataclass(frozen=True) +class VecsInfo: + path: str + kind: str + rows: int + dim: int + bytes: int + sha256: str + + +def sha256_file(path: Path, chunk_bytes: int = 8 * 1024 * 1024) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + while chunk := source.read(chunk_bytes): + digest.update(chunk) + return digest.hexdigest() + + +def record_dtype(dim: int, kind: str) -> np.dtype: + value_dtype = " VecsInfo: + if kind not in {"fvecs", "ivecs"}: + raise ValueError("kind must be fvecs or ivecs") + if not path.is_file() or path.stat().st_size < 4: + raise ValueError(f"{path}: missing or too small") + dim = int(np.fromfile(path, dtype=" 1_000_000: + raise ValueError(f"{path}: invalid row dimension {dim}") + record_bytes = (dim + 1) * 4 + size = path.stat().st_size + if size % record_bytes != 0: + raise ValueError( + f"{path}: size {size} is not divisible by record size {record_bytes}" + ) + rows = size // record_bytes + if rows == 0: + raise ValueError(f"{path}: no rows") + records = np.memmap(path, dtype=record_dtype(dim, kind), mode="r", shape=(rows,)) + for start in range(0, rows, chunk_rows): + if not np.all(records["dim"][start : start + chunk_rows] == dim): + raise ValueError(f"{path}: inconsistent row dimensions") + del records + return VecsInfo( + path=str(path), + kind=kind, + rows=rows, + dim=dim, + bytes=size, + sha256=sha256_file(path), + ) + + +def write_warpfusion_vectors( + source: Path, + destination: Path, + info: VecsInfo, + rows: int, + database: bool, + chunk_rows: int = 16384, +) -> None: + if info.kind != "fvecs": + raise ValueError("WarpFusion vectors must be imported from fvecs") + if rows <= 0 or rows > info.rows: + raise ValueError(f"requested rows must be in [1, {info.rows}]") + records = np.memmap( + source, + dtype=record_dtype(info.dim, "fvecs"), + mode="r", + shape=(info.rows,), + ) + destination.parent.mkdir(parents=True, exist_ok=True) + with destination.open("wb") as output: + if database: + output.write(DATABASE_MAGIC) + output.write(struct.pack(" None: + if info.kind != "ivecs": + raise ValueError("ground truth must use ivecs") + if info.rows < query_rows: + raise ValueError( + f"ground truth has {info.rows} rows but {query_rows} queries were requested" + ) + records = np.memmap( + path, + dtype=record_dtype(info.dim, "ivecs"), + mode="r", + shape=(info.rows,), + ) + values = np.asarray(records["values"][:query_rows]) + if np.any(values < 0) or np.any(values >= database_rows): + raise ValueError("ground truth contains an out-of-range vector ID") + if np.any(np.diff(np.sort(values, axis=1), axis=1) == 0): + raise ValueError("ground truth contains duplicate IDs in one query") + del records + + +def convert( + base_path: Path, + query_path: Path, + groundtruth_path: Path, + database_output: Path, + query_output: Path, + manifest_output: Path, + query_limit: int | None = None, + source_url: str = OFFICIAL_SOURCE, + groundtruth_output: Path | None = None, +) -> dict[str, object]: + base = inspect_vecs(base_path, "fvecs") + queries = inspect_vecs(query_path, "fvecs") + groundtruth = inspect_vecs(groundtruth_path, "ivecs") + if base.dim != queries.dim: + raise ValueError(f"base dim {base.dim} differs from query dim {queries.dim}") + if query_limit is not None and query_limit <= 0: + raise ValueError("query_limit must be positive") + query_rows = queries.rows if query_limit is None else min(query_limit, queries.rows) + validate_groundtruth(groundtruth_path, groundtruth, query_rows, base.rows) + write_warpfusion_vectors(base_path, database_output, base, base.rows, True) + write_warpfusion_vectors(query_path, query_output, queries, query_rows, False) + if groundtruth_output is not None: + groundtruth_output.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(groundtruth_path, groundtruth_output) + + output_paths = { + "database": database_output, + "queries": query_output, + } + if groundtruth_output is not None: + output_paths["groundtruth"] = groundtruth_output + + manifest: dict[str, object] = { + "dataset": "SIFT1M", + "source_url": source_url, + "metric": "l2", + "database_rows": base.rows, + "query_rows": query_rows, + "dim": base.dim, + "groundtruth_k": groundtruth.dim, + "inputs": { + "base": asdict(base), + "queries": asdict(queries), + "groundtruth": asdict(groundtruth), + }, + "outputs": { + name: { + "path": str(path), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + for name, path in output_paths.items() + }, + } + manifest_output.parent.mkdir(parents=True, exist_ok=True) + manifest_output.write_text( + json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base", type=Path, required=True) + parser.add_argument("--queries", type=Path, required=True) + parser.add_argument("--groundtruth", type=Path, required=True) + parser.add_argument("--database-output", type=Path, required=True) + parser.add_argument("--query-output", type=Path, required=True) + parser.add_argument("--manifest-output", type=Path, required=True) + parser.add_argument("--groundtruth-output", type=Path) + parser.add_argument("--query-limit", type=int) + parser.add_argument("--source-url", default=OFFICIAL_SOURCE) + args = parser.parse_args() + manifest = convert( + args.base, + args.queries, + args.groundtruth, + args.database_output, + args.query_output, + args.manifest_output, + args.query_limit, + args.source_url, + args.groundtruth_output, + ) + print( + f"SIFT1M: {manifest['database_rows']} x {manifest['dim']}, " + f"queries={manifest['query_rows']}, groundtruth_k={manifest['groundtruth_k']}" + ) + print(f"manifest: {args.manifest_output}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/plot_results.py b/09_vector_retrieval/PurplePulse/scripts/plot_results.py new file mode 100644 index 00000000..dd7513b3 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/plot_results.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Generate dependency-free SVG figures from project benchmark CSV files.""" + +from __future__ import annotations + +import argparse +import csv +import html +from pathlib import Path + + +WIDTH = 1180 +HEIGHT = 430 +COLORS = {"WarpFusion": "#0072B2", "FAISS GPU": "#D55E00"} +K_COLORS = {10: "#0072B2", 50: "#009E73", 100: "#D55E00"} + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="") as source: + rows = list(csv.DictReader(source)) + if not rows: + raise ValueError(f"empty CSV: {path}") + return rows + + +def esc(value: object) -> str: + return html.escape(str(value), quote=True) + + +def line(x1: float, y1: float, x2: float, y2: float, **attrs: object) -> str: + attributes = " ".join(f'{key.rstrip("_").replace("_", "-")}="{esc(value)}"' for key, value in attrs.items()) + return f'' + + +def text(x: float, y: float, value: object, **attrs: object) -> str: + attributes = " ".join(f'{key.rstrip("_").replace("_", "-")}="{esc(attr)}"' for key, attr in attrs.items()) + return f'{esc(value)}' + + +def padded_domain(values: list[float], fraction: float = 0.06) -> tuple[float, float]: + low, high = min(values), max(values) + span = high - low + padding = span * fraction if span else max(abs(high) * fraction, 1.0) + return low - padding, high + padding + + +def scale(value: float, domain: tuple[float, float], start: float, end: float) -> float: + low, high = domain + return start + (value - low) / (high - low) * (end - start) + + +def ticks(domain: tuple[float, float], count: int = 5) -> list[float]: + low, high = domain + return [low + index * (high - low) / (count - 1) for index in range(count)] + + +def base_svg(title: str, body: list[str], width: int = WIDTH, height: int = HEIGHT) -> str: + return "\n".join([ + f'', + f'{esc(title)}', + 'Benchmark curves generated from the checked-in raw CSV data.', + '', + '', + *body, + '', + '', + ]) + + +def load_quality_series(results_dir: Path) -> dict[int, dict[str, list[dict[str, float]]]]: + formal_files = {top_k: f"ivf_k{top_k}.csv" for top_k in (10, 50, 100)} + purple_files = ( + formal_files + if all((results_dir / filename).exists() for filename in formal_files.values()) + else {top_k: f"optimized_v1_k{top_k}.csv" for top_k in (10, 50, 100)} + ) + series: dict[int, dict[str, list[dict[str, float]]]] = {} + for top_k, filename in purple_files.items(): + rows = read_csv(results_dir / filename) + series[top_k] = { + "WarpFusion": [ + { + "recall": float(row["recall_at_k"]), + "latency": float(row["average_ms"]), + "qps": float(row["qps"]), + "nprobe": float(row["nprobe"]), + } + for row in rows + ] + } + faiss_filename = ( + "faiss_gpu.csv" + if (results_dir / "faiss_gpu.csv").exists() + else "faiss_gpu_formal_v3.csv" + ) + faiss_rows = read_csv(results_dir / faiss_filename) + for top_k in purple_files: + series[top_k]["FAISS GPU"] = [ + { + "recall": float(row["recall_at_k"]), + "latency": float(row["average_query_ms"]), + "qps": float(row["qps"]), + "nprobe": float(row["nprobe"]), + } + for row in faiss_rows + if row["backend"] == "gpu" + and row["index_type"] == "ivf_flat" + and int(row["top_k"]) == top_k + ] + if not series[top_k]["FAISS GPU"]: + raise ValueError(f"missing FAISS GPU IVF rows for K={top_k}") + return series + + +def quality_figure(series: dict[int, dict[str, list[dict[str, float]]]], metric: str, + title: str, y_label: str) -> str: + body = [text(WIDTH / 2, 27, title, text_anchor="middle", class_="figure-title")] + body.extend([ + line(430, 47, 455, 47, stroke=COLORS["WarpFusion"], stroke_width=3), + text(462, 51, "WarpFusion", class_="label"), + line(590, 47, 615, 47, stroke=COLORS["FAISS GPU"], stroke_width=3), + text(622, 51, "FAISS GPU", class_="label"), + ]) + panel_width = 350 + panel_gap = 30 + plot_top, plot_bottom = 86, 355 + for panel_index, top_k in enumerate((10, 50, 100)): + panel_left = 55 + panel_index * (panel_width + panel_gap) + plot_left, plot_right = panel_left + 48, panel_left + panel_width - 10 + all_points = [point for values in series[top_k].values() for point in values] + x_domain = padded_domain([point["recall"] for point in all_points], 0.04) + y_domain = padded_domain([point[metric] for point in all_points], 0.08) + body.append(text((plot_left + plot_right) / 2, 73, f"K = {top_k}", text_anchor="middle", class_="panel-title")) + for value in ticks(y_domain): + y = scale(value, y_domain, plot_bottom, plot_top) + body.append(line(plot_left, y, plot_right, y, class_="grid")) + body.append(text(plot_left - 7, y + 4, f"{value:.0f}", text_anchor="end", class_="tick")) + for value in ticks(x_domain): + x = scale(value, x_domain, plot_left, plot_right) + body.append(line(x, plot_top, x, plot_bottom, class_="grid")) + body.append(text(x, plot_bottom + 17, f"{value:.2f}", text_anchor="middle", class_="tick")) + body.extend([ + line(plot_left, plot_top, plot_left, plot_bottom, class_="axis"), + line(plot_left, plot_bottom, plot_right, plot_bottom, class_="axis"), + text((plot_left + plot_right) / 2, 397, "Recall@K", text_anchor="middle", class_="label"), + ]) + if panel_index == 0: + body.append(text(15, (plot_top + plot_bottom) / 2, y_label, text_anchor="middle", class_="label", transform=f"rotate(-90 15 {(plot_top + plot_bottom) / 2})")) + for name in ("WarpFusion", "FAISS GPU"): + points = sorted(series[top_k][name], key=lambda item: item["recall"]) + coordinates = [ + (scale(point["recall"], x_domain, plot_left, plot_right), + scale(point[metric], y_domain, plot_bottom, plot_top), point) + for point in points + ] + path = " ".join(("M" if index == 0 else "L") + f" {x:.2f} {y:.2f}" for index, (x, y, _) in enumerate(coordinates)) + body.append(f'') + for x, y, point in coordinates: + body.append(f'') + body.append(text(x + 5, y - 6, int(point["nprobe"]), class_="note")) + body.append(text(WIDTH - 10, HEIGHT - 8, "Matched batch=64 · point labels: nprobe", text_anchor="end", class_="note")) + return base_svg(title, body) + + +def batch_figure(results_dir: Path) -> str: + rows = read_csv(results_dir / "optimized_v1_batch_sweep.csv") + body = [text(WIDTH / 2, 28, "Batch size vs throughput", text_anchor="middle", class_="figure-title")] + plot_left, plot_right, plot_top, plot_bottom = 85, 1135, 78, 350 + x_values = sorted({int(row["batch_size"]) for row in rows}) + qps_values = [float(row["qps"]) for row in rows] + x_domain = padded_domain([float(value) for value in x_values], 0.03) + y_domain = padded_domain(qps_values, 0.08) + for value in ticks(y_domain): + y = scale(value, y_domain, plot_bottom, plot_top) + body.append(line(plot_left, y, plot_right, y, class_="grid")) + body.append(text(plot_left - 9, y + 4, f"{value:.0f}", text_anchor="end", class_="tick")) + for value in x_values: + x = scale(value, x_domain, plot_left, plot_right) + body.append(line(x, plot_top, x, plot_bottom, class_="grid")) + body.append(text(x, plot_bottom + 18, value, text_anchor="middle", class_="tick")) + body.extend([ + line(plot_left, plot_top, plot_left, plot_bottom, class_="axis"), + line(plot_left, plot_bottom, plot_right, plot_bottom, class_="axis"), + text((plot_left + plot_right) / 2, 397, "Batch size (queries)", text_anchor="middle", class_="label"), + text(20, (plot_top + plot_bottom) / 2, "Throughput (QPS)", text_anchor="middle", class_="label", transform=f"rotate(-90 20 {(plot_top + plot_bottom) / 2})"), + ]) + legend_x = 430 + for index, top_k in enumerate((10, 50, 100)): + color = K_COLORS[top_k] + body.append(line(legend_x + index * 135, 50, legend_x + 25 + index * 135, 50, stroke=color, stroke_width=3)) + body.append(text(legend_x + 32 + index * 135, 54, f"K={top_k}", class_="label")) + points = sorted( + ((int(row["batch_size"]), float(row["qps"])) for row in rows if int(row["top_k"]) == top_k), + key=lambda item: item[0], + ) + coordinates = [(scale(x, x_domain, plot_left, plot_right), scale(y, y_domain, plot_bottom, plot_top)) for x, y in points] + path = " ".join(("M" if item == 0 else "L") + f" {x:.2f} {y:.2f}" for item, (x, y) in enumerate(coordinates)) + body.append(f'') + for x, y in coordinates: + body.append(f'') + return base_svg("Batch size vs throughput", body) + + +def generate_figures( + results_dir: Path, + output_dir: Path, + batch_results_dir: Path | None = None, +) -> list[Path]: + output_dir.mkdir(parents=True, exist_ok=True) + quality = load_quality_series(results_dir) + figures = { + "recall-latency.svg": quality_figure( + quality, "latency", "Recall–latency frontier", "1000-query latency (ms)" + ), + "recall-qps.svg": quality_figure( + quality, "qps", "Recall–throughput frontier", "Throughput (QPS)" + ), + } + batch_root = batch_results_dir if batch_results_dir is not None else results_dir + if (batch_root / "optimized_v1_batch_sweep.csv").exists(): + figures["batch-qps.svg"] = batch_figure(batch_root) + paths = [] + for filename, contents in figures.items(): + path = output_dir / filename + path.write_text(contents) + paths.append(path) + return paths + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--results-dir", type=Path, default=Path("results/million")) + parser.add_argument("--output-dir", type=Path, default=Path("results/figures")) + parser.add_argument("--batch-results-dir", type=Path) + args = parser.parse_args() + for path in generate_figures( + args.results_dir, args.output_dir, args.batch_results_dir + ): + print(path) + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/prepare_real_datasets.py b/09_vector_retrieval/PurplePulse/scripts/prepare_real_datasets.py new file mode 100644 index 00000000..b6aed852 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/prepare_real_datasets.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Download, verify, and convert the two Stage-6 public datasets.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import tarfile +import urllib.request +from pathlib import Path + +from import_ann_benchmarks import convert as convert_hdf5 +from import_sift1m import convert as convert_sift + + +SIFT_URL = "ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz" +SIFT_MD5 = "b23d1b3b2ee8469d819b61ca900ef0ed" +VIBE_NAME = "yahoo-minilm-384-normalized" +VIBE_URL = ( + "https://huggingface.co/datasets/vector-index-bench/vibe/resolve/main/" + f"{VIBE_NAME}.hdf5" +) +VIBE_MIRROR_URL = ( + "https://hf-mirror.com/datasets/vector-index-bench/vibe/resolve/main/" + f"{VIBE_NAME}.hdf5" +) +VIBE_SHA256 = "8b0519850249d7ea4aea258eb43ae837dca1bb2f7a85ee0a5145afdb699c4136" + + +def file_hash(path: Path, algorithm: str) -> str: + digest = hashlib.new(algorithm) + with path.open("rb") as source: + while chunk := source.read(8 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def verify(path: Path, algorithm: str, expected: str) -> None: + actual = file_hash(path, algorithm) + if actual.lower() != expected.lower(): + raise ValueError( + f"{path}: {algorithm} mismatch: expected {expected}, got {actual}" + ) + + +def download(url: str, destination: Path, algorithm: str, expected: str) -> Path: + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + verify(destination, algorithm, expected) + print(f"verified cached download: {destination}") + return destination + + partial = destination.with_suffix(destination.suffix + ".part") + request = urllib.request.Request(url, headers={"User-Agent": "WarpFusion/0.1"}) + downloaded = 0 + with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as out: + total = int(response.headers.get("Content-Length", "0")) + while chunk := response.read(8 * 1024 * 1024): + out.write(chunk) + downloaded += len(chunk) + if total: + print( + f"\r{destination.name}: {downloaded / (1024**2):.1f}/" + f"{total / (1024**2):.1f} MiB", + end="", + flush=True, + ) + print() + verify(partial, algorithm, expected) + partial.replace(destination) + return destination + + +def safe_extract(archive: Path, destination: Path) -> None: + destination.mkdir(parents=True, exist_ok=True) + root = destination.resolve() + with tarfile.open(archive, "r:gz") as source: + for member in source.getmembers(): + target = (destination / member.name).resolve() + if root != target and root not in target.parents: + raise ValueError(f"unsafe archive member: {member.name}") + source.extractall(destination) + + +def prepare_sift(raw_dir: Path, output_dir: Path, skip_download: bool) -> dict: + archive = raw_dir / "sift1m" / "sift.tar.gz" + if not skip_download: + download(SIFT_URL, archive, "md5", SIFT_MD5) + elif not archive.is_file(): + raise FileNotFoundError(archive) + else: + verify(archive, "md5", SIFT_MD5) + + extracted = raw_dir / "sift1m" / "extracted" + required = { + "base": extracted / "sift" / "sift_base.fvecs", + "queries": extracted / "sift" / "sift_query.fvecs", + "groundtruth": extracted / "sift" / "sift_groundtruth.ivecs", + } + if not all(path.is_file() for path in required.values()): + safe_extract(archive, extracted) + + destination = output_dir / "sift1m" + manifest = convert_sift( + required["base"], + required["queries"], + required["groundtruth"], + destination / "database.bin", + destination / "queries.bin", + destination / "manifest.json", + source_url=SIFT_URL, + groundtruth_output=destination / "groundtruth.ivecs", + ) + manifest["archive"] = { + "path": str(archive), + "bytes": archive.stat().st_size, + "md5": file_hash(archive, "md5"), + "sha256": file_hash(archive, "sha256"), + } + (destination / "manifest.json").write_text( + json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + return manifest + + +def prepare_vibe(raw_dir: Path, output_dir: Path, skip_download: bool) -> dict: + source = raw_dir / "vibe" / f"{VIBE_NAME}.hdf5" + if not skip_download: + try: + download(VIBE_URL, source, "sha256", VIBE_SHA256) + except Exception as primary_error: + print( + f"primary Hugging Face download failed ({primary_error}); " + "trying the checksum-equivalent mirror", + file=sys.stderr, + ) + download(VIBE_MIRROR_URL, source, "sha256", VIBE_SHA256) + elif not source.is_file(): + raise FileNotFoundError(source) + else: + verify(source, "sha256", VIBE_SHA256) + + destination = output_dir / VIBE_NAME + return convert_hdf5( + source, + destination / "database.bin", + destination / "queries.bin", + destination / "groundtruth.ivecs", + destination / "manifest.json", + expected_sha256=VIBE_SHA256, + source_url=VIBE_URL, + dataset_name=VIBE_NAME, + expected_dim=384, + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--dataset", + choices=("all", "sift1m", VIBE_NAME), + default="all", + ) + parser.add_argument("--raw-dir", type=Path, default=Path("data/real/raw")) + parser.add_argument("--output-dir", type=Path, default=Path("data/real")) + parser.add_argument( + "--skip-download", + action="store_true", + help="Require already-downloaded archives, but still verify their checksums", + ) + args = parser.parse_args() + + selected = ( + ("sift1m", VIBE_NAME) if args.dataset == "all" else (args.dataset,) + ) + for name in selected: + try: + manifest = ( + prepare_sift(args.raw_dir, args.output_dir, args.skip_download) + if name == "sift1m" + else prepare_vibe(args.raw_dir, args.output_dir, args.skip_download) + ) + except Exception as error: + print(f"failed to prepare {name}: {error}", file=sys.stderr) + raise + print( + f"prepared {manifest['dataset']}: {manifest['database_rows']} x " + f"{manifest['dim']}, queries={manifest['query_rows']}" + ) + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/reproduce.py b/09_vector_retrieval/PurplePulse/scripts/reproduce.py new file mode 100644 index 00000000..63c64bd8 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/reproduce.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Run the complete WarpFusion build, benchmark, report, and validation flow.""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +DATASETS = ("sift1m", "yahoo-minilm-384") +PREPARE_NAMES = { + "sift1m": "sift1m", + "yahoo-minilm-384": "yahoo-minilm-384-normalized", +} + + +def rooted(root: Path, value: Path) -> Path: + return value.resolve() if value.is_absolute() else (root / value).resolve() + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Build, test, prepare public data, run WarpFusion/FAISS, plot, " + "build the report, and validate release artifacts." + ) + ) + parser.add_argument("--project-root", type=Path, default=ROOT) + parser.add_argument("--dataset", action="append", choices=DATASETS) + parser.add_argument("--raw-dir", type=Path, default=Path("data/real/raw")) + parser.add_argument("--data-root", type=Path, default=Path("data/real")) + parser.add_argument("--results-root", type=Path, default=Path("results/real")) + parser.add_argument("--build-dir", type=Path, default=Path("build-reproduce")) + parser.add_argument( + "--report-output", + type=Path, + default=Path("output/pdf/WarpFusion_Technical_Report.pdf"), + ) + parser.add_argument("--cuda-architectures", default="native") + parser.add_argument("--nlist", type=int, default=1024) + parser.add_argument("--nprobes", default="32,64,128,160,192,224") + parser.add_argument("--training-samples", type=int, default=100000) + parser.add_argument("--iterations", type=int, default=15) + parser.add_argument("--threads", type=int, default=16) + parser.add_argument("--batch-size", type=int, default=64) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--skip-download", action="store_true") + parser.add_argument("--skip-index-build", action="store_true") + parser.add_argument("--skip-faiss", action="store_true") + parser.add_argument("--resume", action="store_true") + parser.add_argument("--dry-run", action="store_true") + return parser.parse_args(argv) + + +def make_step(name: str, command: list[str], log: Path) -> dict[str, object]: + return {"name": name, "command": command, "log": log} + + +def build_plan(args: argparse.Namespace) -> tuple[Path, list[dict[str, object]]]: + root = args.project_root.resolve() + build = rooted(root, args.build_dir) + raw = rooted(root, args.raw_dir) + data = rooted(root, args.data_root) + results = rooted(root, args.results_root) + report = rooted(root, args.report_output) + state_root = results / "reproducibility" + logs = state_root / "logs" + python = sys.executable + datasets = tuple(dict.fromkeys(args.dataset or DATASETS)) + + steps = [ + make_step( + "configure", + [ + "cmake", "-S", str(root), "-B", str(build), "-G", "Ninja", + "-DCMAKE_BUILD_TYPE=Release", + f"-DCMAKE_CUDA_ARCHITECTURES={args.cuda_architectures}", + ], + logs / "configure.log", + ), + make_step( + "build", ["cmake", "--build", str(build)], logs / "build.log" + ), + make_step( + "test", + ["ctest", "--test-dir", str(build), "--output-on-failure"], + logs / "ctest.log", + ), + ] + + prepare = [ + python, + str(root / "scripts" / "prepare_real_datasets.py"), + "--dataset", + "all" if set(datasets) == set(DATASETS) else PREPARE_NAMES[datasets[0]], + "--raw-dir", str(raw), + "--output-dir", str(data), + ] + if args.skip_download: + prepare.append("--skip-download") + if set(datasets) == set(DATASETS) or len(datasets) == 1: + steps.append(make_step("prepare", prepare, logs / "prepare.log")) + else: + raise ValueError("unsupported dataset selection") + + for dataset in datasets: + command = [ + python, + str(root / "scripts" / "run_real_benchmarks.py"), + "--dataset", dataset, + "--project-root", str(root), + "--data-root", str(data), + "--results-root", str(results), + "--build-dir", str(build), + "--nlist", str(args.nlist), + "--nprobes", args.nprobes, + "--training-samples", str(args.training_samples), + "--iterations", str(args.iterations), + "--threads", str(args.threads), + "--batch-size", str(args.batch_size), + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + ] + if args.skip_index_build: + command.append("--skip-index-build") + if args.skip_faiss: + command.append("--skip-faiss") + steps.append(make_step(f"benchmark:{dataset}", command, + logs / f"benchmark-{dataset}.log")) + steps.append( + make_step( + f"plot:{dataset}", + [ + python, + str(root / "scripts" / "plot_results.py"), + "--results-dir", str(results / dataset), + "--output-dir", str(results / dataset / "figures"), + ], + logs / f"plot-{dataset}.log", + ) + ) + + steps.extend( + [ + make_step( + "report", + [ + python, + str(root / "scripts" / "build_final_report_pdf.py"), + "--source", str(root / "docs" / "FINAL_REPORT.md"), + "--output", str(report), + ], + logs / "report.log", + ), + make_step( + "validate", + [ + python, + str(root / "scripts" / "validate_release.py"), + "--project-root", str(root), + "--report", str(report), + ], + logs / "validate.log", + ), + ] + ) + return state_root, steps + + +def load_checkpoint(path: Path) -> dict[str, object]: + if not path.is_file(): + return {"completed": [], "steps": {}} + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value.get("completed"), list): + raise ValueError(f"invalid checkpoint: {path}") + return value + + +def write_checkpoint(path: Path, state: dict[str, object]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text( + json.dumps(state, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + temporary.replace(path) + + +def run_step(root: Path, step: dict[str, object]) -> int: + log = Path(step["log"]) + command = [str(item) for item in step["command"]] + log.parent.mkdir(parents=True, exist_ok=True) + print(f"[{step['name']}] {' '.join(command)}", flush=True) + with log.open("w", encoding="utf-8") as output: + completed = subprocess.run( + command, + cwd=root, + env=os.environ.copy(), + stdout=output, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + return completed.returncode + + +def main(argv: list[str] | None = None) -> None: + args = parse_args(argv) + state_root, steps = build_plan(args) + root = args.project_root.resolve() + checkpoint_path = state_root / "checkpoint.json" + if args.dry_run: + print(json.dumps({"project_root": str(root), "steps": steps}, + ensure_ascii=False, indent=2, default=str)) + return + + state = load_checkpoint(checkpoint_path) if args.resume else { + "completed": [], "steps": {} + } + completed_names = set(state["completed"]) + state["started_utc"] = state.get( + "started_utc", datetime.now(timezone.utc).isoformat() + ) + state["project_root"] = str(root) + for step in steps: + name = str(step["name"]) + if args.resume and name in completed_names: + print(f"[{name}] checkpoint complete; skipping", flush=True) + continue + returncode = run_step(root, step) + state.setdefault("steps", {})[name] = { + "returncode": returncode, + "log": str(step["log"]), + "finished_utc": datetime.now(timezone.utc).isoformat(), + } + if returncode != 0: + state["failed_step"] = name + write_checkpoint(checkpoint_path, state) + raise SystemExit(f"step failed: {name}; see {step['log']}") + completed_names.add(name) + state["completed"] = [ + str(item["name"]) for item in steps + if str(item["name"]) in completed_names + ] + state.pop("failed_step", None) + write_checkpoint(checkpoint_path, state) + state["finished_utc"] = datetime.now(timezone.utc).isoformat() + write_checkpoint(checkpoint_path, state) + print(f"reproduction complete: {checkpoint_path}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/run_real_benchmarks.py b/09_vector_retrieval/PurplePulse/scripts/run_real_benchmarks.py new file mode 100644 index 00000000..227e1666 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/run_real_benchmarks.py @@ -0,0 +1,378 @@ +#!/usr/bin/env python3 +"""Run the Stage-6 benchmark matrix for one prepared public dataset.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + + +DATA_DIR_NAMES = { + "sift1m": "sift1m", + "yahoo-minilm-384": "yahoo-minilm-384-normalized", +} +TOP_KS = (10, 50, 100) +PROVENANCE_FILES = ( + "src/gpu_ivf_flat.cu", + "src/gpu_search.cu", + "src/ivf_flat.cpp", + "scripts/run_real_benchmarks.py", + "scripts/benchmark_exact.py", + "scripts/benchmark_ivf_sweep.py", + "scripts/benchmark_faiss.py", +) + + +def run(command: list[str], log_path: Path | None = None) -> str: + print("+", " ".join(command), flush=True) + completed = subprocess.run( + command, + check=True, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + print(completed.stdout, end="") + if log_path is not None: + log_path.parent.mkdir(parents=True, exist_ok=True) + log_path.write_text(completed.stdout, encoding="utf-8") + return completed.stdout + + +def capture(command: list[str]) -> str: + try: + return subprocess.run( + command, + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ).stdout.strip() + except OSError as error: + return f"unavailable: {error}" + + +def extract(text: str, pattern: str) -> float: + match = re.search(pattern, text) + if match is None: + raise ValueError(f"cannot parse command output: {pattern}") + return float(match.group(1)) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + while chunk := source.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def parse_build_stats(text: str, dataset: str, nlist: int) -> dict[str, object]: + training = re.search(r"迭代/训练样本: (\d+)/(\d+)", text) + buckets = re.search( + r"桶大小 min/avg/max: ([0-9.eE+-]+)/([0-9.eE+-]+)/([0-9.eE+-]+)", + text, + ) + if training is None or buckets is None: + raise ValueError("cannot parse IVF build metadata") + return { + "dataset": dataset, + "nlist": nlist, + "training_iterations": int(training.group(1)), + "training_samples": int(training.group(2)), + "threads": int(extract(text, r"建库线程: (\d+)")), + "build_ms": extract(text, r"构建时间: ([0-9.eE+-]+) ms"), + "save_ms": extract(text, r"保存时间: ([0-9.eE+-]+) ms"), + "minimum_bucket": int(float(buckets.group(1))), + "average_bucket": float(buckets.group(2)), + "maximum_bucket": int(float(buckets.group(3))), + "empty_buckets": int(extract(text, r"空桶: (\d+)")), + "index_bytes": int(extract(text, r"索引大小: (\d+) bytes")), + } + + +def write_one_row_csv(path: Path, row: dict[str, object]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="") as output: + writer = csv.DictWriter(output, fieldnames=list(row)) + writer.writeheader() + writer.writerow(row) + + +def read_csv_by_nprobe(path: Path) -> dict[int, dict[str, str]]: + with path.open(newline="") as source: + rows = list(csv.DictReader(source)) + return {int(row["nprobe"]): row for row in rows} + + +def choose_partitioned_result( + partitioned_csv: Path, + full_heap_csv: Path, + effective_csv: Path, + maximum_recall_loss: float, +) -> dict[str, object]: + partitioned = read_csv_by_nprobe(partitioned_csv) + full_heap = read_csv_by_nprobe(full_heap_csv) + if partitioned.keys() != full_heap.keys(): + raise ValueError("partitioned and full-heap scans use different nprobe values") + comparisons = [] + fallback = False + for nprobe in sorted(partitioned): + partitioned_recall = float(partitioned[nprobe]["recall_at_k"]) + full_heap_recall = float(full_heap[nprobe]["recall_at_k"]) + recall_loss = full_heap_recall - partitioned_recall + fallback = fallback or recall_loss > maximum_recall_loss + comparisons.append( + { + "nprobe": nprobe, + "partitioned_recall": partitioned_recall, + "full_heap_recall": full_heap_recall, + "partitioned_qps": float(partitioned[nprobe]["qps"]), + "full_heap_qps": float(full_heap[nprobe]["qps"]), + "recall_loss": recall_loss, + } + ) + selected = full_heap_csv if fallback else partitioned_csv + shutil.copyfile(selected, effective_csv) + return { + "selected_mode": "full_heap" if fallback else "partitioned", + "maximum_allowed_recall_loss": maximum_recall_loss, + "comparisons": comparisons, + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=tuple(DATA_DIR_NAMES), required=True) + parser.add_argument("--project-root", type=Path, default=Path.cwd()) + parser.add_argument("--data-root", type=Path, default=Path("data/real")) + parser.add_argument("--results-root", type=Path, default=Path("results/real")) + parser.add_argument("--build-dir", type=Path, default=Path("build")) + parser.add_argument("--nlist", type=int, default=1024) + parser.add_argument("--nprobes", default="32,64,128,160,192,224") + parser.add_argument("--training-samples", type=int, default=100000) + parser.add_argument("--iterations", type=int, default=15) + parser.add_argument("--threads", type=int, default=16) + parser.add_argument("--batch-size", type=int, default=64) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--skip-index-build", action="store_true") + parser.add_argument("--skip-faiss", action="store_true") + parser.add_argument( + "--maximum-partition-recall-loss", + type=float, + default=1e-4, + help="Fall back to the complete heap if any nprobe exceeds this loss", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if args.maximum_partition_recall_loss < 0: + raise ValueError("maximum-partition-recall-loss must be non-negative") + os.environ.setdefault("_FAISS_WHEEL_DISABLE_CUDA_PRELOAD", "1") + cuda_library = "/usr/local/cuda/lib64" + library_path = os.environ.get("LD_LIBRARY_PATH", "") + if Path(cuda_library).is_dir() and cuda_library not in library_path.split(":"): + os.environ["LD_LIBRARY_PATH"] = ":".join( + item for item in (cuda_library, library_path) if item + ) + root = args.project_root.resolve() + data = (root / args.data_root / DATA_DIR_NAMES[args.dataset]).resolve() + results = (root / args.results_root / args.dataset).resolve() + build = (root / args.build_dir).resolve() + scripts = root / "scripts" + configs = root / "configs" + results.mkdir(parents=True, exist_ok=True) + + for required in ( + data / "database.bin", + data / "queries.bin", + data / "groundtruth.ivecs", + build / "vector_search", + build / "ivf_build", + build / "ivf_search", + ): + if not required.is_file(): + raise FileNotFoundError(required) + + index = data / f"nlist{args.nlist}.ivf" + if not args.skip_index_build: + build_text = run( + [ + str(build / "ivf_build"), + "--database", str(data / "database.bin"), + "--output", str(index), + "--nlist", str(args.nlist), + "--iterations", str(args.iterations), + "--training-samples", str(args.training_samples), + "--threads", str(args.threads), + ], + results / "logs" / "ivf_build.log", + ) + write_one_row_csv( + results / "build.csv", + parse_build_stats(build_text, args.dataset, args.nlist), + ) + elif not index.is_file(): + raise FileNotFoundError(index) + + exact_configs = ",".join( + f"{top_k}:{configs / f'real_exact_k{top_k}.conf'}" + for top_k in TOP_KS + ) + run( + [ + sys.executable, + str(scripts / "benchmark_exact.py"), + "--search-binary", str(build / "vector_search"), + "--database", str(data / "database.bin"), + "--queries", str(data / "queries.bin"), + "--configs", exact_configs, + "--output-dir", str(results / "exact_outputs"), + "--csv", str(results / "exact_gpu.csv"), + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + ], + results / "logs" / "exact.log", + ) + + validations = [] + for top_k in TOP_KS: + output = run( + [ + sys.executable, + str(scripts / "evaluate_ivecs_groundtruth.py"), + "--groundtruth", str(data / "groundtruth.ivecs"), + "--results", str(results / "exact_outputs" / f"exact_k{top_k}.txt"), + "--database", str(data / "database.bin"), + "--queries", str(data / "queries.bin"), + "--json", + ] + ) + validations.append(json.loads(output)) + (results / "groundtruth_validation.json").write_text( + json.dumps(validations, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + + def run_ivf(top_k: int, config: Path, suffix: str) -> Path: + csv_path = results / f"ivf_k{top_k}{suffix}.csv" + run( + [ + sys.executable, + str(scripts / "benchmark_ivf_sweep.py"), + "--search-binary", str(build / "ivf_search"), + "--index", str(index), + "--queries", str(data / "queries.bin"), + "--params", str(config), + "--exact", str(results / "exact_outputs" / f"exact_k{top_k}.txt"), + "--output-dir", str(results / f"ivf_k{top_k}{suffix}_outputs"), + "--csv", str(csv_path), + "--nlist", str(args.nlist), + "--training-samples", str(args.training_samples), + "--training-iterations", str(args.iterations), + "--training-seed", "2026", + "--nprobes", args.nprobes, + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + ], + results / "logs" / f"ivf_k{top_k}{suffix}.log", + ) + return csv_path + + partition_validations = {} + for top_k in TOP_KS: + optimized_config = configs / f"real_ivf_nlist1024_k{top_k}.conf" + if top_k == 10: + run_ivf(top_k, optimized_config, "") + continue + partitioned_csv = run_ivf(top_k, optimized_config, "_partitioned") + full_heap_csv = run_ivf( + top_k, + configs / f"real_ivf_nlist1024_k{top_k}_safe.conf", + "_full_heap", + ) + partition_validations[str(top_k)] = choose_partitioned_result( + partitioned_csv, + full_heap_csv, + results / f"ivf_k{top_k}.csv", + args.maximum_partition_recall_loss, + ) + (results / "partitioned_topk_validation.json").write_text( + json.dumps(partition_validations, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + + if not args.skip_faiss: + run( + [ + sys.executable, + str(scripts / "benchmark_faiss.py"), + "--database", str(data / "database.bin"), + "--queries", str(data / "queries.bin"), + "--output-dir", str(results / "faiss_outputs"), + "--csv", str(results / "faiss_gpu.csv"), + "--index-dir", str(data / "faiss_indexes"), + "--reference-results", str(results / "exact_outputs" / "exact_k100.txt"), + "--backends", "gpu", + "--index-types", "flat,ivf_flat", + "--top-ks", "10,50,100", + "--nprobes", args.nprobes, + "--nlist", str(args.nlist), + "--batch-size", str(args.batch_size), + "--train-samples", str(args.training_samples), + "--iterations", str(args.iterations), + "--seed", "2026", + "--warmup", str(args.warmup), + "--repeat", str(args.repeat), + ], + results / "logs" / "faiss_gpu.log", + ) + run( + [ + sys.executable, + str(scripts / "plot_results.py"), + "--results-dir", str(results), + "--output-dir", str(results / "figures"), + ] + ) + + environment = { + "dataset": args.dataset, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "git_commit": capture(["git", "-C", str(root), "rev-parse", "HEAD"]), + "source_sha256": { + name: sha256_file(root / name) for name in PROVENANCE_FILES + }, + "gpu": capture([ + "nvidia-smi", + "--query-gpu=name,driver_version,memory.total", + "--format=csv,noheader", + ]), + "nvcc": capture(["nvcc", "--version"]), + "python": sys.version, + "parameters": { + key: str(value) if isinstance(value, Path) else value + for key, value in vars(args).items() + }, + } + (results / "environment.json").write_text( + json.dumps(environment, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + print(f"Stage-6 results: {results}") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/slice_queries.py b/09_vector_retrieval/PurplePulse/scripts/slice_queries.py new file mode 100644 index 00000000..27373dd6 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/slice_queries.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""从查询文件中复制前 N 条 query,用于较慢的 CPU 正确性验证。""" + +import argparse +import struct +from pathlib import Path + + +DTYPE_SIZES = {1: 4, 2: 2} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--input", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--count", type=int, required=True) + args = parser.parse_args() + + if args.count <= 0: + parser.error("count 必须大于 0") + + with Path(args.input).open("rb") as source: + magic = source.read(8) + if magic != b"PPQRY001": + raise SystemExit("输入不是本项目的 query 文件") + num_queries, dim, dtype = struct.unpack(" num_queries: + raise SystemExit("count 不能大于原文件的 query 数量") + value_bytes = args.count * dim * DTYPE_SIZES[dtype] + values = source.read(value_bytes) + if len(values) != value_bytes: + raise SystemExit("输入文件数据不完整") + + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + with output_path.open("wb") as output: + output.write(b"PPQRY001") + output.write(struct.pack(" int: + if not path.is_file(): + raise FileNotFoundError(path) + with path.open(newline="", encoding="utf-8") as source: + reader = csv.DictReader(source) + fields = set(reader.fieldnames or ()) + if required_columns and not required_columns <= fields: + missing = sorted(required_columns - fields) + raise ValueError(f"{path}: missing columns {missing}") + rows = list(reader) + if not rows: + raise ValueError(f"{path}: no data rows") + return len(rows) + + +def validate_pdf(path: Path) -> int: + if not path.is_file() or path.stat().st_size < 1024: + raise ValueError(f"missing or undersized PDF: {path}") + with path.open("rb") as source: + if source.read(5) != b"%PDF-": + raise ValueError(f"invalid PDF header: {path}") + return path.stat().st_size + + +def validate(root: Path, report: Path) -> dict[str, object]: + required_docs = { + "README.md": "一条命令复现", + "docs/FINAL_REPORT.md": "7.4", + "docs/REPRODUCIBILITY.md": "第九阶段工程化入口", + "docs/STABILITY_MATRIX.md": "Exact 选择规则", + "docs/API.md": "C++ API", + } + for relative, marker in required_docs.items(): + path = root / relative + if not path.is_file() or marker not in path.read_text(encoding="utf-8"): + raise ValueError(f"{relative}: missing required marker {marker!r}") + + csv_rows: dict[str, int] = {} + for dataset in ("sift1m", "yahoo-minilm-384"): + base = root / "results" / "real" / dataset + for filename, columns in ( + ("exact_gpu.csv", {"top_k", "qps"}), + ("faiss_gpu.csv", {"top_k", "qps"}), + ("ivf_k10.csv", {"nprobe", "recall_at_k", "qps"}), + ("ivf_k50.csv", {"nprobe", "recall_at_k", "qps"}), + ("ivf_k100.csv", {"nprobe", "recall_at_k", "qps"}), + ): + path = base / filename + csv_rows[str(path.relative_to(root))] = validate_csv(path, columns) + + for filename, columns in ( + ("exact_gpu.csv", {"top_k", "qps", "run_samples"}), + ("faiss_cpu_flat.csv", {"top_k", "qps", "run_samples"}), + ): + path = root / "results" / "formal_100k15" / filename + csv_rows[str(path.relative_to(root))] = validate_csv(path, columns) + + nsys_summary = root / "evidence" / "2026-09-04" / "nsys_exact_k10.txt" + nsys_text = nsys_summary.read_text(encoding="utf-8") + for marker in ("99.9", "exactFusedWarpTopKKernel", "cuda_gpu_kern_sum"): + if marker not in nsys_text: + raise ValueError(f"{nsys_summary.relative_to(root)}: missing marker {marker!r}") + + coverage = root / "results" / "stage8_stability" / "coverage.csv" + csv_rows[str(coverage.relative_to(root))] = validate_csv( + coverage, {"suite", "cases", "status"} + ) + with coverage.open(newline="", encoding="utf-8") as source: + failed = [row["suite"] for row in csv.DictReader(source) + if row["status"] != "passed"] + if failed: + raise ValueError(f"stage8 coverage failures: {failed}") + + for path in ( + root / "results" / "figures" / "report-architecture.svg", + root / "results" / "figures" / "report-exact-fused.svg", + root / "results" / "figures" / "report-exact-breakdown.svg", + root / "results" / "figures" / "report-k50-scheduling.svg", + root / "results" / "figures" / "report-k100-partitioned.svg", + root / "results" / "figures" / "report-recall-qps.svg", + root / "results" / "figures" / "report-real-comparison.svg", + ): + if not path.is_file() or " None: + parser = argparse.ArgumentParser() + parser.add_argument("--project-root", type=Path, default=ROOT) + parser.add_argument( + "--report", type=Path, + default=Path("output/pdf/WarpFusion_Technical_Report.pdf"), + ) + parser.add_argument("--json-output", type=Path) + args = parser.parse_args() + root = args.project_root.resolve() + report = args.report.resolve() if args.report.is_absolute() else (root / args.report) + result = validate(root, report) + text = json.dumps(result, ensure_ascii=False, indent=2) + "\n" + if args.json_output: + output = (args.json_output if args.json_output.is_absolute() + else root / args.json_output) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(text, encoding="utf-8") + print(text, end="") + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/scripts/verify_results.py b/09_vector_retrieval/PurplePulse/scripts/verify_results.py new file mode 100644 index 00000000..9dc44349 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/scripts/verify_results.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""比较 CPU 与 GPU 的文本结果,检查 Top-K ID 和分数误差。""" + +import argparse +from collections import defaultdict +from pathlib import Path + + +def read_results(path): + rows = [] + for line_number, line in enumerate(Path(path).read_text().splitlines(), 1): + parts = line.split() + if len(parts) != 3: + raise ValueError(f"{path}:{line_number} 不是三列") + rows.append((int(parts[0]), int(parts[1]), float(parts[2]))) + return rows + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--expected", required=True) + parser.add_argument("--actual", required=True) + parser.add_argument( + "--tolerance", + type=float, + default=5e-5, + help="CPU 串行累加与 GPU warp 归约的允许绝对误差", + ) + args = parser.parse_args() + + expected = read_results(args.expected) + actual = read_results(args.actual) + if len(expected) != len(actual): + raise SystemExit( + f"失败:行数不同,expected={len(expected)}, actual={len(actual)}" + ) + + expected_by_query = defaultdict(list) + actual_by_query = defaultdict(list) + for row in expected: + expected_by_query[row[0]].append(row) + for row in actual: + actual_by_query[row[0]].append(row) + + if expected_by_query.keys() != actual_by_query.keys(): + raise SystemExit("失败:query ID 集合不同") + + max_error = 0.0 + error_sum = 0.0 + error_count = 0 + near_tie_reorders = 0 + for query_id in expected_by_query: + expected_rows = expected_by_query[query_id] + actual_rows = actual_by_query[query_id] + expected_scores = {row[1]: row[2] for row in expected_rows} + actual_scores = {row[1]: row[2] for row in actual_rows} + if expected_scores.keys() != actual_scores.keys(): + missing = expected_scores.keys() - actual_scores.keys() + unexpected = actual_scores.keys() - expected_scores.keys() + raise SystemExit( + f"失败:query {query_id} 的 Top-K 集合不同," + f"missing={sorted(missing)}, unexpected={sorted(unexpected)}" + ) + for vector_id in expected_scores: + error = abs(expected_scores[vector_id] - actual_scores[vector_id]) + max_error = max(max_error, error) + error_sum += error + error_count += 1 + for rank, (left, right) in enumerate(zip(expected_rows, actual_rows)): + if left[1] != right[1]: + score_gap = abs(left[2] - right[2]) + if score_gap > args.tolerance: + raise SystemExit( + f"失败:query {query_id} rank {rank} 顺序不同且非近似并列," + f"expected={left}, actual={right}" + ) + near_tie_reorders += 1 + + if max_error > args.tolerance: + raise SystemExit( + f"失败:最大分数误差 {max_error} 超过容差 {args.tolerance}" + ) + print( + "通过:Top-K 候选集合相同," + f"平均绝对分数误差={error_sum / error_count if error_count else 0.0}," + f"最大分数误差={max_error},近似并列换位数={near_tie_reorders}" + ) + + +if __name__ == "__main__": + main() diff --git a/09_vector_retrieval/PurplePulse/src/build_ivf.cpp b/09_vector_retrieval/PurplePulse/src/build_ivf.cpp new file mode 100644 index 00000000..4e01abf5 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/build_ivf.cpp @@ -0,0 +1,137 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "ivf_flat.h" + +namespace { + +void printUsage(const char* program) { + std::cerr << "用法:\n " << program + << " --database <文件> --output <索引文件> --nlist <数量>" + " [--iterations 15] [--training-samples 100000]" + " [--threads N]\n"; +} + +std::unordered_map parseArguments(int argc, + char** argv) { + std::unordered_map arguments; + for (int index = 1; index < argc; index += 2) { + if (index + 1 >= argc || std::string(argv[index]).rfind("--", 0) != 0) { + throw std::runtime_error("命令行参数必须是 --名称 值 的形式"); + } + arguments[argv[index]] = argv[index + 1]; + } + for (const char* required : {"--database", "--output", "--nlist"}) { + if (arguments.count(required) == 0) { + throw std::runtime_error(std::string("缺少参数: ") + required); + } + } + return arguments; +} + +std::uint64_t readPositive( + const std::unordered_map& arguments, + const std::string& name, std::uint64_t default_value) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + std::size_t parsed_chars = 0; + const unsigned long long parsed = std::stoull(found->second, &parsed_chars); + if (parsed_chars != found->second.size() || parsed == 0) { + throw std::runtime_error(name + " 必须是正整数"); + } + return parsed; +} + +} // namespace + +int main(int argc, char** argv) { + try { + if (argc == 2 && std::string(argv[1]) == "--help") { + printUsage(argv[0]); + return EXIT_SUCCESS; + } + if (argc == 1) { + printUsage(argv[0]); + return EXIT_FAILURE; + } + const auto arguments = parseArguments(argc, argv); + const std::uint64_t parsed_nlist = readPositive(arguments, "--nlist", 0); + const std::uint64_t parsed_iterations = + readPositive(arguments, "--iterations", 15); + if (parsed_nlist > UINT32_MAX || parsed_iterations > UINT32_MAX) { + throw std::runtime_error("nlist 或 iterations 超过 uint32 范围"); + } + const std::uint64_t training_samples = + readPositive(arguments, "--training-samples", 100000); + const std::uint32_t default_threads = std::max( + 1U, std::min(16U, std::thread::hardware_concurrency())); + const std::uint64_t parsed_threads = + readPositive(arguments, "--threads", default_threads); + if (parsed_threads > 1024) { + throw std::runtime_error("threads 必须位于 [1, 1024]"); + } + const VectorDatabase database = + readVectorDatabase(arguments.at("--database")); + + const auto build_start = std::chrono::steady_clock::now(); + const IvfFlatIndex index = buildIvfFlatIndex( + database, static_cast(parsed_nlist), + static_cast(parsed_iterations), training_samples, + static_cast(parsed_threads)); + const auto build_end = std::chrono::steady_clock::now(); + + const std::filesystem::path output_path(arguments.at("--output")); + if (output_path.has_parent_path()) { + std::filesystem::create_directories(output_path.parent_path()); + } + const auto save_start = std::chrono::steady_clock::now(); + writeIvfFlatIndex(output_path.string(), index); + const auto save_end = std::chrono::steady_clock::now(); + + std::uint64_t minimum_bucket = index.num_vectors; + std::uint64_t maximum_bucket = 0; + std::uint32_t empty_buckets = 0; + for (std::uint32_t center_id = 0; center_id < index.nlist; ++center_id) { + const std::uint64_t size = + index.offsets[center_id + 1] - index.offsets[center_id]; + minimum_bucket = std::min(minimum_bucket, size); + maximum_bucket = std::max(maximum_bucket, size); + empty_buckets += size == 0; + } + const double build_ms = + std::chrono::duration(build_end - build_start) + .count(); + const double save_ms = + std::chrono::duration(save_end - save_start) + .count(); + std::cout << "IVF-Flat 索引构建完成" << "\n向量库: " << index.num_vectors + << " x " << index.dim + << "\ndtype/metric: " << dataTypeName(index.dtype) << '/' + << metricName(index.metric) << "\nnlist: " << index.nlist + << "\n迭代/训练样本: " << parsed_iterations << '/' + << std::min(training_samples, index.num_vectors) + << "\n建库线程: " << parsed_threads + << "\n构建时间: " << build_ms << " ms" + << "\n保存时间: " << save_ms << " ms" + << "\n桶大小 min/avg/max: " << minimum_bucket << '/' + << static_cast(index.num_vectors) / index.nlist << '/' + << maximum_bucket << "\n空桶: " << empty_buckets + << "\n索引大小: " << std::filesystem::file_size(output_path) + << " bytes\n输出: " << output_path << '\n'; + return EXIT_SUCCESS; + } catch (const std::exception& error) { + std::cerr << "错误: " << error.what() << '\n'; + printUsage(argv[0]); + return EXIT_FAILURE; + } +} diff --git a/09_vector_retrieval/PurplePulse/src/cpu_search.cpp b/09_vector_retrieval/PurplePulse/src/cpu_search.cpp new file mode 100644 index 00000000..5670d17d --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/cpu_search.cpp @@ -0,0 +1,163 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "search.h" + +namespace { + +float halfToFloat(std::uint16_t bits) { + const bool negative = (bits & 0x8000U) != 0; + const std::uint32_t exponent = (bits >> 10U) & 0x1fU; + const std::uint32_t mantissa = bits & 0x03ffU; + float value = 0.0F; + if (exponent == 0) { + value = std::ldexp(static_cast(mantissa), -24); + } else if (exponent == 31) { + value = mantissa == 0 ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + } else { + value = std::ldexp(static_cast(1024U + mantissa), + static_cast(exponent) - 25); + } + return negative ? -value : value; +} + +float databaseValue(const VectorDatabase& database, std::uint64_t index) { + return database.dtype == DataType::kFloat32 + ? database.values[index] + : halfToFloat(database.half_values[index]); +} + +float queryValue(const QuerySet& queries, std::uint64_t index) { + return queries.dtype == DataType::kFloat32 + ? queries.values[index] + : halfToFloat(queries.half_values[index]); +} + +float computeScore(const VectorDatabase& database, const QuerySet& queries, + std::uint64_t query_id, std::uint64_t vector_id) { + float dot = 0.0F; + float query_norm = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + + for (std::uint32_t d = 0; d < database.dim; ++d) { + const float q = queryValue(queries, query_id * queries.dim + d); + const float x = databaseValue(database, vector_id * database.dim + d); + if (database.metric == Metric::kL2) { + const float difference = q - x; + squared_l2 = std::fma(difference, difference, squared_l2); + } else { + dot = std::fma(q, x, dot); + if (database.metric == Metric::kCosine) { + query_norm = std::fma(q, q, query_norm); + vector_norm = std::fma(x, x, vector_norm); + } + } + } + + if (database.metric == Metric::kL2) { + return squared_l2; + } + if (database.metric == Metric::kInnerProduct) { + return dot; + } + if (query_norm == 0.0F || vector_norm == 0.0F) { + return 0.0F; + } + return dot / std::sqrt(query_norm * vector_norm); +} + +bool isBetter(const Neighbor& left, const Neighbor& right, Metric metric) { + if (left.score == right.score) { + return left.id < right.id; + } + if (metric == Metric::kL2) { + return left.score < right.score; + } + return left.score > right.score; +} + +std::vector selectTopK(std::vector candidates, + std::uint32_t top_k, Metric metric) { + const auto comparator = [metric](const Neighbor& left, + const Neighbor& right) { + return isBetter(left, right, metric); + }; + + // nth_element 先把最好的 K 个移到前面,再只排序这 K 个。 + // 它比对全部候选排序更省时间,同时代码仍然很容易理解。 + if (top_k < candidates.size()) { + std::nth_element(candidates.begin(), candidates.begin() + top_k, + candidates.end(), comparator); + candidates.resize(top_k); + } + std::sort(candidates.begin(), candidates.end(), comparator); + return candidates; +} + +} // namespace + +SearchResults cpuExactSearch(const VectorDatabase& database, + const QuerySet& queries, + const SearchParams& params) { + validateInputs(database, queries, params); + SearchResults results(queries.num_queries); + + for (std::uint64_t query_id = 0; query_id < queries.num_queries; ++query_id) { + std::vector candidates(database.num_vectors); + + for (std::uint64_t vector_id = 0; vector_id < database.num_vectors; + ++vector_id) { + candidates[vector_id] = { + vector_id, + computeScore(database, queries, query_id, vector_id), + }; + } + results[query_id] = + selectTopK(std::move(candidates), params.top_k, database.metric); + } + return results; +} + +bool resultsMatch(const SearchResults& expected, const SearchResults& actual, + float absolute_tolerance, std::string* error_message) { + if (expected.size() != actual.size()) { + if (error_message != nullptr) { + *error_message = "query 数量不同"; + } + return false; + } + + for (std::size_t query_id = 0; query_id < expected.size(); ++query_id) { + if (expected[query_id].size() != actual[query_id].size()) { + if (error_message != nullptr) { + *error_message = "query " + std::to_string(query_id) + " 的 K 不同"; + } + return false; + } + for (std::size_t rank = 0; rank < expected[query_id].size(); ++rank) { + const Neighbor& left = expected[query_id][rank]; + const Neighbor& right = actual[query_id][rank]; + if (left.id != right.id || + std::fabs(left.score - right.score) > absolute_tolerance) { + if (error_message != nullptr) { + std::ostringstream message; + message << "query=" << query_id << ", rank=" << rank + << " 不一致,CPU(id=" << left.id << ", score=" << left.score + << "),GPU(id=" << right.id << ", score=" << right.score + << ')'; + *error_message = message.str(); + } + return false; + } + } + } + return true; +} diff --git a/09_vector_retrieval/PurplePulse/src/file_io.cpp b/09_vector_retrieval/PurplePulse/src/file_io.cpp new file mode 100644 index 00000000..a99d7174 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/file_io.cpp @@ -0,0 +1,533 @@ +#include "file_io.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::array kDatabaseMagic = {'P', 'P', 'V', 'E', + 'C', '0', '0', '1'}; +constexpr std::array kQueryMagic = {'P', 'P', 'Q', 'R', + 'Y', '0', '0', '1'}; +constexpr std::array kMemoryMetadataMagic = {'P', 'P', 'M', 'E', + 'T', 'A', '0', '1'}; + +template +void writeValue(std::ofstream& output, const T& value) { + output.write(reinterpret_cast(&value), sizeof(T)); +} + +template +T readValue(std::ifstream& input, const char* field_name) { + T value{}; + input.read(reinterpret_cast(&value), sizeof(T)); + if (!input) { + throw std::runtime_error(std::string("读取字段失败: ") + field_name); + } + return value; +} + +std::string trim(std::string text) { + const auto not_space = [](unsigned char c) { return !std::isspace(c); }; + text.erase(text.begin(), std::find_if(text.begin(), text.end(), not_space)); + text.erase(std::find_if(text.rbegin(), text.rend(), not_space).base(), + text.end()); + if (text.size() >= 2 && text.front() == '"' && text.back() == '"') { + text = text.substr(1, text.size() - 2); + } + return text; +} + +std::uint32_t parsePositiveInt(const std::string& value, + const std::string& key) { + std::size_t parsed_chars = 0; + const unsigned long parsed = std::stoul(value, &parsed_chars); + if (parsed_chars != value.size() || parsed == 0 || parsed > UINT32_MAX) { + throw std::runtime_error("参数 " + key + " 必须是正整数"); + } + return static_cast(parsed); +} + +float parsePositiveFloat(const std::string& value, const std::string& key) { + std::size_t parsed_chars = 0; + const float parsed = std::stof(value, &parsed_chars); + if (parsed_chars != value.size() || !std::isfinite(parsed) || + parsed <= 0.0F) { + throw std::runtime_error("参数 " + key + " 必须是有限正数"); + } + return parsed; +} + +float parseNonnegativeFloat(const std::string& value, const std::string& key) { + std::size_t parsed_chars = 0; + const float parsed = std::stof(value, &parsed_chars); + if (parsed_chars != value.size() || !std::isfinite(parsed) || parsed < 0.0F) { + throw std::runtime_error("参数 " + key + " 必须是有限非负数"); + } + return parsed; +} + +std::uint64_t parseUint64(const std::string& value, const std::string& key) { + if (value.empty() || value.front() == '-') { + throw std::runtime_error("参数 " + key + " 必须是非负整数"); + } + std::size_t parsed_chars = 0; + const unsigned long long parsed = std::stoull(value, &parsed_chars); + if (parsed_chars != value.size()) { + throw std::runtime_error("参数 " + key + " 必须是非负整数"); + } + return static_cast(parsed); +} + +std::uint32_t parseOptionalUint32(const std::string& value, + const std::string& key) { + if (value == "any") { + return UINT32_MAX; + } + const std::uint64_t parsed = parseUint64(value, key); + if (parsed >= UINT32_MAX) { + throw std::runtime_error("参数 " + key + " 必须小于 UINT32_MAX"); + } + return static_cast(parsed); +} + +std::uint64_t elementSize(DataType dtype) { + if (dtype == DataType::kFloat32) { + return sizeof(float); + } + if (dtype == DataType::kFloat16) { + return sizeof(std::uint16_t); + } + throw std::runtime_error("不支持的 dtype 编号: " + + std::to_string(static_cast(dtype))); +} + +std::uint64_t checkedValueCount(std::uint64_t rows, std::uint32_t dim, + const std::string& path) { + if (dim != 0 && rows > UINT64_MAX / dim) { + throw std::runtime_error("向量数量与维度乘积溢出: " + path); + } + return rows * dim; +} + +void checkFileSize(const std::string& path, std::uint64_t header_bytes, + std::uint64_t value_count, DataType dtype) { + const std::uint64_t element_bytes = elementSize(dtype); + if (value_count > (UINT64_MAX - header_bytes) / element_bytes) { + throw std::runtime_error("文件大小计算溢出: " + path); + } + const std::uint64_t expected = header_bytes + value_count * element_bytes; + const std::uint64_t actual = std::filesystem::file_size(path); + if (actual != expected) { + throw std::runtime_error("文件大小不正确: " + path + ",期望 " + + std::to_string(expected) + " 字节,实际 " + + std::to_string(actual) + " 字节"); + } +} + +} // namespace + +const char* metricName(Metric metric) { + switch (metric) { + case Metric::kL2: + return "l2"; + case Metric::kInnerProduct: + return "inner_product"; + case Metric::kCosine: + return "cosine"; + } + throw std::runtime_error("未知的距离类型"); +} + +const char* dataTypeName(DataType dtype) { + switch (dtype) { + case DataType::kFloat32: + return "fp32"; + case DataType::kFloat16: + return "fp16"; + } + throw std::runtime_error("未知的数据类型"); +} + +Metric parseMetric(const std::string& text) { + if (text == "l2") { + return Metric::kL2; + } + if (text == "inner_product") { + return Metric::kInnerProduct; + } + if (text == "cosine") { + return Metric::kCosine; + } + throw std::runtime_error("不支持的 metric: " + text); +} + +VectorDatabase readVectorDatabase(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) { + throw std::runtime_error("无法打开向量库: " + path); + } + + std::array magic{}; + input.read(magic.data(), magic.size()); + if (magic != kDatabaseMagic) { + throw std::runtime_error("向量库 magic/version 不正确: " + path); + } + + VectorDatabase database; + database.num_vectors = readValue(input, "num_vectors"); + database.dim = readValue(input, "dim"); + database.dtype = + static_cast(readValue(input, "dtype")); + database.metric = + static_cast(readValue(input, "metric")); + + (void)dataTypeName(database.dtype); + (void)metricName(database.metric); + if (database.num_vectors == 0 || database.dim == 0) { + throw std::runtime_error("向量库的数量和维度必须大于 0"); + } + + const std::uint64_t count = + checkedValueCount(database.num_vectors, database.dim, path); + checkFileSize(path, 8 + 8 + 4 + 4 + 4, count, database.dtype); + if (database.dtype == DataType::kFloat32) { + database.values.resize(count); + input.read(reinterpret_cast(database.values.data()), + static_cast(count * sizeof(float))); + } else { + database.half_values.resize(count); + input.read(reinterpret_cast(database.half_values.data()), + static_cast(count * sizeof(std::uint16_t))); + } + if (!input) { + throw std::runtime_error("读取向量库数据失败: " + path); + } + return database; +} + +QuerySet readQuerySet(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) { + throw std::runtime_error("无法打开查询文件: " + path); + } + + std::array magic{}; + input.read(magic.data(), magic.size()); + if (magic != kQueryMagic) { + throw std::runtime_error("查询文件 magic/version 不正确: " + path); + } + + QuerySet queries; + queries.num_queries = readValue(input, "num_queries"); + queries.dim = readValue(input, "dim"); + queries.dtype = + static_cast(readValue(input, "dtype")); + (void)dataTypeName(queries.dtype); + if (queries.num_queries == 0 || queries.dim == 0) { + throw std::runtime_error("查询数量和维度必须大于 0"); + } + + const std::uint64_t count = + checkedValueCount(queries.num_queries, queries.dim, path); + checkFileSize(path, 8 + 8 + 4 + 4, count, queries.dtype); + if (queries.dtype == DataType::kFloat32) { + queries.values.resize(count); + input.read(reinterpret_cast(queries.values.data()), + static_cast(count * sizeof(float))); + } else { + queries.half_values.resize(count); + input.read(reinterpret_cast(queries.half_values.data()), + static_cast(count * sizeof(std::uint16_t))); + } + if (!input) { + throw std::runtime_error("读取查询数据失败: " + path); + } + return queries; +} + +void validateMemoryMetadata(const MemoryMetadata& metadata, + std::uint64_t expected_vectors) { + if (metadata.num_vectors == 0 || + (expected_vectors != 0 && metadata.num_vectors != expected_vectors) || + metadata.timestamps.size() != metadata.num_vectors || + metadata.importance.size() != metadata.num_vectors || + metadata.session_ids.size() != metadata.num_vectors || + metadata.source_types.size() != metadata.num_vectors) { + throw std::runtime_error("记忆元数据列长度或向量数量不一致"); + } + for (const float value : metadata.importance) { + if (!std::isfinite(value) || value < 0.0F || value > 1.0F) { + throw std::runtime_error("记忆 importance 必须位于 [0, 1]"); + } + } +} + +void writeMemoryMetadata(const std::string& path, + const MemoryMetadata& metadata) { + validateMemoryMetadata(metadata); + std::ofstream output(path, std::ios::binary); + if (!output) { + throw std::runtime_error("无法写入记忆元数据: " + path); + } + output.write(kMemoryMetadataMagic.data(), kMemoryMetadataMagic.size()); + writeValue(output, metadata.num_vectors); + output.write(reinterpret_cast(metadata.timestamps.data()), + static_cast(metadata.num_vectors * + sizeof(std::uint64_t))); + output.write( + reinterpret_cast(metadata.importance.data()), + static_cast(metadata.num_vectors * sizeof(float))); + output.write(reinterpret_cast(metadata.session_ids.data()), + static_cast(metadata.num_vectors * + sizeof(std::uint32_t))); + output.write(reinterpret_cast(metadata.source_types.data()), + static_cast(metadata.num_vectors * + sizeof(std::uint32_t))); + if (!output) { + throw std::runtime_error("写入记忆元数据失败: " + path); + } +} + +MemoryMetadata readMemoryMetadata(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) { + throw std::runtime_error("无法打开记忆元数据: " + path); + } + std::array magic{}; + input.read(magic.data(), magic.size()); + if (magic != kMemoryMetadataMagic) { + throw std::runtime_error("记忆元数据 magic/version 不正确: " + path); + } + MemoryMetadata metadata; + metadata.num_vectors = readValue(input, "num_vectors"); + constexpr std::uint64_t kBytesPerVector = + sizeof(std::uint64_t) + sizeof(float) + 2 * sizeof(std::uint32_t); + if (metadata.num_vectors == 0 || + metadata.num_vectors > (UINT64_MAX - 16) / kBytesPerVector || + std::filesystem::file_size(path) != + 16 + metadata.num_vectors * kBytesPerVector) { + throw std::runtime_error("记忆元数据文件大小不正确: " + path); + } + metadata.timestamps.resize(metadata.num_vectors); + metadata.importance.resize(metadata.num_vectors); + metadata.session_ids.resize(metadata.num_vectors); + metadata.source_types.resize(metadata.num_vectors); + input.read(reinterpret_cast(metadata.timestamps.data()), + static_cast(metadata.num_vectors * + sizeof(std::uint64_t))); + input.read( + reinterpret_cast(metadata.importance.data()), + static_cast(metadata.num_vectors * sizeof(float))); + input.read(reinterpret_cast(metadata.session_ids.data()), + static_cast(metadata.num_vectors * + sizeof(std::uint32_t))); + input.read(reinterpret_cast(metadata.source_types.data()), + static_cast(metadata.num_vectors * + sizeof(std::uint32_t))); + if (!input) { + throw std::runtime_error("读取记忆元数据失败: " + path); + } + validateMemoryMetadata(metadata); + return metadata; +} + +SearchParams readSearchParams(const std::string& path) { + std::ifstream input(path); + if (!input) { + throw std::runtime_error("无法打开参数文件: " + path); + } + + SearchParams params; + std::string line; + while (std::getline(input, line)) { + const std::size_t comment = line.find('#'); + if (comment != std::string::npos) { + line.erase(comment); + } + line = trim(line); + if (line.empty()) { + continue; + } + + const std::size_t equal = line.find('='); + if (equal == std::string::npos) { + throw std::runtime_error("参数行缺少 '=': " + line); + } + const std::string key = trim(line.substr(0, equal)); + const std::string value = trim(line.substr(equal + 1)); + + if (key == "top_k") { + params.top_k = parsePositiveInt(value, key); + } else if (key == "search_mode") { + params.search_mode = value; + } else if (key == "batch_size") { + params.batch_size = parsePositiveInt(value, key); + } else if (key == "distance_mode") { + params.distance_mode = value; + } else if (key == "topk_mode") { + params.topk_mode = value; + } else if (key == "exact_query_tile") { + params.exact_query_tile = parsePositiveInt(value, key); + } else if (key == "exact_fused_layout") { + params.exact_fused_layout = value; + } else if (key == "exact_fused_blocks") { + params.exact_fused_blocks = parsePositiveInt(value, key); + } else if (key == "nlist") { + params.nlist = parsePositiveInt(value, key); + } else if (key == "nprobe") { + params.nprobe = parsePositiveInt(value, key); + } else if (key == "nprobe_policy") { + params.nprobe_policy = value; + } else if (key == "adaptive_execution") { + params.adaptive_execution = value; + } else if (key == "adaptive_nprobe_min") { + params.adaptive_nprobe_min = parsePositiveInt(value, key); + } else if (key == "adaptive_nprobe_step") { + params.adaptive_nprobe_step = parsePositiveInt(value, key); + } else if (key == "adaptive_target_mass") { + params.adaptive_target_mass = parsePositiveFloat(value, key); + } else if (key == "adaptive_temperature") { + params.adaptive_temperature = parsePositiveFloat(value, key); + } else if (key == "memory_mode") { + params.memory_mode = value; + } else if (key == "memory_semantic_weight") { + params.memory_semantic_weight = parsePositiveFloat(value, key); + } else if (key == "memory_importance_weight") { + params.memory_importance_weight = parseNonnegativeFloat(value, key); + } else if (key == "memory_recency_weight") { + params.memory_recency_weight = parseNonnegativeFloat(value, key); + } else if (key == "memory_time_scale") { + params.memory_time_scale = parsePositiveFloat(value, key); + } else if (key == "memory_now") { + params.memory_now = parseUint64(value, key); + } else if (key == "filter_min_timestamp") { + params.filter_min_timestamp = parseUint64(value, key); + } else if (key == "filter_session_id") { + params.filter_session_id = parseOptionalUint32(value, key); + } else if (key == "filter_source_type") { + params.filter_source_type = parseOptionalUint32(value, key); + } else if (key == "memory_rerank_factor") { + params.memory_rerank_factor = parsePositiveInt(value, key); + } else if (key == "pq_m") { + params.pq_m = parsePositiveInt(value, key); + } else { + throw std::runtime_error("未知参数: " + key); + } + } + return params; +} + +void writeSearchResults(const std::string& path, const SearchResults& results) { + std::ofstream output(path); + if (!output) { + throw std::runtime_error("无法写入结果文件: " + path); + } + output.precision(9); + for (std::size_t query_id = 0; query_id < results.size(); ++query_id) { + for (const Neighbor& neighbor : results[query_id]) { + output << query_id << ' ' << neighbor.id << ' ' << neighbor.score << '\n'; + } + } +} + +void validateInputs(const VectorDatabase& database, const QuerySet& queries, + const SearchParams& params) { + if (database.num_vectors == 0 || database.dim == 0) { + throw std::runtime_error("向量库的数量和维度必须大于 0"); + } + if (queries.num_queries == 0 || queries.dim == 0) { + throw std::runtime_error("查询数量和维度必须大于 0"); + } + if (database.dim != queries.dim) { + throw std::runtime_error("向量库维度与查询维度不一致"); + } + if (database.dtype != queries.dtype) { + throw std::runtime_error("向量库与查询的数据类型不一致"); + } + const std::uint64_t database_count = + checkedValueCount(database.num_vectors, database.dim, "向量库"); + const std::uint64_t query_count = + checkedValueCount(queries.num_queries, queries.dim, "查询集"); + if (database.dtype == DataType::kFloat32) { + if (database.values.size() != database_count || + queries.values.size() != query_count) { + throw std::runtime_error("FP32 数据长度与头部元数据不一致"); + } + } else if (database.dtype == DataType::kFloat16) { + if (database.half_values.size() != database_count || + queries.half_values.size() != query_count) { + throw std::runtime_error("FP16 数据长度与头部元数据不一致"); + } + } else { + (void)elementSize(database.dtype); + } + if (params.top_k == 0) { + throw std::runtime_error("top_k 必须大于 0"); + } + if (params.top_k > database.num_vectors) { + throw std::runtime_error("top_k 不能大于向量库大小"); + } + if (params.top_k > 100) { + throw std::runtime_error("当前按照项目要求支持 top_k <= 100"); + } + if (params.batch_size == 0) { + throw std::runtime_error("batch_size 必须大于 0"); + } + if (params.search_mode != "exact") { + throw std::runtime_error("当前只实现了 search_mode=exact,尚未实现: " + + params.search_mode); + } + if (params.topk_mode != "simple" && params.topk_mode != "block" && + params.topk_mode != "two_stage" && params.topk_mode != "fused") { + throw std::runtime_error( + "topk_mode 必须是 simple、block、two_stage 或 fused"); + } + if (params.topk_mode == "two_stage" && params.top_k > 10) { + throw std::runtime_error("当前 two_stage Top-K 支持 top_k <= 10"); + } + if (params.distance_mode != "simple" && params.distance_mode != "warp") { + throw std::runtime_error("distance_mode 必须是 simple 或 warp"); + } + if (params.topk_mode == "fused" && params.distance_mode != "warp") { + throw std::runtime_error("fused Top-K 要求 distance_mode=warp"); + } + if (params.exact_query_tile != 1 && params.exact_query_tile != 2 && + params.exact_query_tile != 4 && params.exact_query_tile != 8) { + throw std::runtime_error("exact_query_tile 必须是 1、2、4 或 8"); + } + if (params.exact_query_tile != 1 && params.topk_mode != "fused") { + throw std::runtime_error("exact_query_tile > 1 只支持 fused Top-K"); + } + if (params.exact_fused_blocks != 0 && params.topk_mode != "fused") { + throw std::runtime_error("exact_fused_blocks 只支持 fused Top-K"); + } + if (params.exact_query_tile == 8 && params.top_k > 10) { + throw std::runtime_error("exact_query_tile=8 当前只支持 top_k <= 10"); + } + if (params.exact_fused_layout != "warp_query" && + params.exact_fused_layout != "block_tile") { + throw std::runtime_error( + "exact_fused_layout 必须是 warp_query 或 block_tile"); + } + if (params.exact_fused_layout == "block_tile" && + (params.topk_mode != "fused" || params.exact_query_tile != 8 || + params.top_k > 10)) { + throw std::runtime_error( + "block_tile 当前要求 fused、exact_query_tile=8、top_k<=10"); + } + if (params.exact_fused_layout == "block_tile") { + const std::uint32_t maximum_dim = + database.dtype == DataType::kFloat32 ? 384 : 768; + if (database.dim > maximum_dim) { + throw std::runtime_error("block_tile 当前共享内存预算不支持该维度"); + } + } +} diff --git a/09_vector_retrieval/PurplePulse/src/gpu_ivf_flat.cu b/09_vector_retrieval/PurplePulse/src/gpu_ivf_flat.cu new file mode 100644 index 00000000..677b71cf --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/gpu_ivf_flat.cu @@ -0,0 +1,2098 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "ivf_flat.h" + +namespace { + +void checkCuda(cudaError_t status, const char* operation) { + if (status != cudaSuccess) { + throw std::runtime_error(std::string(operation) + ": " + + cudaGetErrorString(status)); + } +} + +class DeviceBuffer { + public: + explicit DeviceBuffer(std::size_t bytes) { + checkCuda(cudaMalloc(&data_, bytes), "cudaMalloc IVF"); + } + ~DeviceBuffer() { + if (data_ != nullptr) { + cudaFree(data_); + } + } + DeviceBuffer(const DeviceBuffer&) = delete; + DeviceBuffer& operator=(const DeviceBuffer&) = delete; + void* data() { return data_; } + + private: + void* data_ = nullptr; +}; + +class CudaEvent { + public: + CudaEvent() { checkCuda(cudaEventCreate(&event_), "cudaEventCreate IVF"); } + ~CudaEvent() { cudaEventDestroy(event_); } + CudaEvent(const CudaEvent&) = delete; + CudaEvent& operator=(const CudaEvent&) = delete; + void record() { checkCuda(cudaEventRecord(event_), "cudaEventRecord IVF"); } + void synchronize() { + checkCuda(cudaEventSynchronize(event_), "cudaEventSynchronize IVF"); + } + cudaEvent_t get() const { return event_; } + + private: + cudaEvent_t event_{}; +}; + +double elapsedMilliseconds(const CudaEvent& start, const CudaEvent& end) { + float milliseconds = 0.0F; + checkCuda(cudaEventElapsedTime(&milliseconds, start.get(), end.get()), + "cudaEventElapsedTime IVF"); + return milliseconds; +} + +__device__ __forceinline__ float loadInput(const float* values, + std::uint64_t index) { + return values[index]; +} + +__device__ __forceinline__ float loadInput(const __half* values, + std::uint64_t index) { + return __half2float(values[index]); +} + +__device__ __forceinline__ float warpReduceSum(float value) { + for (int offset = warpSize / 2; offset > 0; offset >>= 1) { + value += __shfl_down_sync(0xFFFFFFFFU, value, offset); + } + return value; +} + +__device__ bool isBetter(float candidate_score, std::uint64_t candidate_id, + float current_score, std::uint64_t current_id, + Metric metric) { + if (candidate_score == current_score) { + return candidate_id < current_id; + } + return metric == Metric::kL2 ? candidate_score < current_score + : candidate_score > current_score; +} + +struct DeviceMemoryView { + const std::uint64_t* timestamps = nullptr; + const float* importance = nullptr; + const std::uint32_t* session_ids = nullptr; + const std::uint32_t* source_types = nullptr; +}; + +struct DeviceMemoryOptions { + float semantic_weight = 1.0F; + float importance_weight = 0.0F; + float recency_weight = 0.0F; + float time_scale = 1.0F; + std::uint64_t now = 0; + std::uint64_t min_timestamp = 0; + std::uint32_t session_id = UINT32_MAX; + std::uint32_t source_type = UINT32_MAX; +}; + +__device__ __forceinline__ bool memoryCandidateMatches( + DeviceMemoryView metadata, std::uint64_t vector_id, + DeviceMemoryOptions options) { + return metadata.timestamps[vector_id] >= options.min_timestamp && + (options.session_id == UINT32_MAX || + metadata.session_ids[vector_id] == options.session_id) && + (options.source_type == UINT32_MAX || + metadata.source_types[vector_id] == options.source_type); +} + +template +__device__ __forceinline__ float applyMemoryScore(float semantic_score, + std::uint64_t vector_id, + DeviceMemoryView metadata, + DeviceMemoryOptions options) { + float recency = 0.0F; + if (options.recency_weight != 0.0F && options.now != 0) { + const std::uint64_t timestamp = metadata.timestamps[vector_id]; + const double age = timestamp >= options.now + ? 0.0 + : static_cast(options.now - timestamp); + recency = expf(-static_cast(age / options.time_scale)); + } + const float boost = + options.importance_weight * metadata.importance[vector_id] + + options.recency_weight * recency; + const float weighted_semantic = options.semantic_weight * semantic_score; + return MetricValue == Metric::kL2 ? weighted_semantic - boost + : weighted_semantic + boost; +} + +template +__global__ void ivfCenterScoresKernel(const float* centers, + const InputType* queries, + float* center_scores, std::uint32_t nlist, + std::uint32_t dim, + std::uint32_t batch_count, + Metric metric) { + const std::uint32_t center_id = blockIdx.x * blockDim.x + threadIdx.x; + const std::uint32_t query_id = blockIdx.y; + if (center_id >= nlist || query_id >= batch_count) { + return; + } + const std::uint64_t center_offset = + static_cast(center_id) * dim; + const std::uint64_t query_offset = static_cast(query_id) * dim; + float dot = 0.0F; + float center_norm = 0.0F; + float query_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + const float center = centers[center_offset + d]; + if (metric == Metric::kL2) { + const float difference = query - center; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, center, dot); + if (metric == Metric::kCosine) { + query_norm = fmaf(query, query, query_norm); + center_norm = fmaf(center, center, center_norm); + } + } + } + float score = dot; + if (metric == Metric::kL2) { + score = squared_l2; + } else if (metric == Metric::kCosine) { + score = query_norm == 0.0F || center_norm == 0.0F + ? 0.0F + : dot / sqrtf(query_norm * center_norm); + } + center_scores[static_cast(query_id) * nlist + center_id] = + score; +} + +// 并行选择 nprobe:每轮让 256 个线程共同从剩余中心中归约出最佳中心, +// 选中后把该分数改为哨兵,再进行下一轮。 +__global__ void ivfSelectProbesBlockKernel(float* center_scores, + std::uint32_t* selected_centers, + float* selected_scores, + std::uint32_t nlist, + std::uint32_t nprobe, + Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float shared_scores[kThreads]; + __shared__ std::uint32_t shared_ids[kThreads]; + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t query_id = blockIdx.x; + const float worst_score = + metric == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + float* query_scores = + center_scores + static_cast(query_id) * nlist; + + for (std::uint32_t probe = 0; probe < nprobe; ++probe) { + float local_best_score = worst_score; + std::uint32_t local_best_id = UINT32_MAX; + for (std::uint32_t center_id = thread_id; center_id < nlist; + center_id += blockDim.x) { + const float score = query_scores[center_id]; + if (isBetter(score, center_id, local_best_score, local_best_id, metric)) { + local_best_score = score; + local_best_id = center_id; + } + } + shared_scores[thread_id] = local_best_score; + shared_ids[thread_id] = local_best_id; + __syncthreads(); + for (std::uint32_t stride = kThreads / 2; stride > 0; stride >>= 1) { + if (thread_id < stride && + isBetter(shared_scores[thread_id + stride], + shared_ids[thread_id + stride], shared_scores[thread_id], + shared_ids[thread_id], metric)) { + shared_scores[thread_id] = shared_scores[thread_id + stride]; + shared_ids[thread_id] = shared_ids[thread_id + stride]; + } + __syncthreads(); + } + if (thread_id == 0) { + const std::uint32_t selected_id = shared_ids[0]; + selected_centers[static_cast(query_id) * nprobe + probe] = + selected_id; + if (selected_scores != nullptr) { + selected_scores[static_cast(query_id) * nprobe + probe] = + shared_scores[0]; + } + query_scores[selected_id] = worst_score; + } + __syncthreads(); + } +} + +// 将已按优劣排序的中心分数转换为概率质量。分数差先除以当前 query 的 +// top-1 到第 max_nprobe 个中心的跨度,使 temperature 对查询模长和 metric +// 尺度不敏感。集中分布会较早达到 target_mass,使用较少 probe;平坦分布 +// 会自动接近 nprobe 上限。 +__global__ void chooseAdaptiveNprobeKernel( + const float* selected_scores, std::uint32_t* query_nprobes, + std::uint32_t batch_count, std::uint32_t max_nprobe, + std::uint32_t min_nprobe, std::uint32_t step, float target_mass, + float temperature, Metric metric) { + const std::uint32_t query_id = blockIdx.x * blockDim.x + threadIdx.x; + if (query_id >= batch_count) { + return; + } + const float* scores = + selected_scores + static_cast(query_id) * max_nprobe; + const float direction = metric == Metric::kL2 ? -1.0F : 1.0F; + const float best_utility = direction * scores[0]; + const float worst_utility = direction * scores[max_nprobe - 1]; + const float utility_span = fmaxf(best_utility - worst_utility, 1.0e-6F); + const float inverse_scale = 1.0F / (temperature * utility_span); + float total_mass = 0.0F; + for (std::uint32_t probe = 0; probe < max_nprobe; ++probe) { + total_mass += + expf((direction * scores[probe] - best_utility) * inverse_scale); + } + + std::uint32_t selected_nprobe = max_nprobe; + if (target_mass < 1.0F) { + float prefix_mass = 0.0F; + for (std::uint32_t probe = 0; probe < max_nprobe; ++probe) { + prefix_mass += + expf((direction * scores[probe] - best_utility) * inverse_scale); + const std::uint32_t count = probe + 1; + const bool selectable = + count >= min_nprobe && + (((count - min_nprobe) % step) == 0 || count == max_nprobe); + if (selectable && prefix_mass >= target_mass * total_mass) { + selected_nprobe = count; + break; + } + } + } + query_nprobes[query_id] = selected_nprobe; +} + +// 正确性 baseline:每个 query 使用一个 CUDA 线程,直接遍历选中桶的候选, +// 距离计算和有序 Top-K 在同一个 kernel 中完成。索引常驻显存,避免复制向量。 +// 下一版会让一个 block/多个 warp 共同扫描一个 query 的候选。 +template +__global__ void fusedIvfScanTopKKernel( + const InputType* vectors, const std::uint64_t* original_ids, + const InputType* queries, const std::uint64_t* candidate_positions, + const std::uint64_t* candidate_counts, float* top_scores, + std::uint64_t* top_ids, std::uint64_t candidate_stride, std::uint32_t dim, + std::uint32_t top_k, Metric metric) { + if (threadIdx.x != 0) { + return; + } + constexpr std::uint32_t kMaximumK = 100; + constexpr float kFloatMaximum = 3.402823466e+38F; + const float worst_score = + metric == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + float best_scores[kMaximumK]; + std::uint64_t best_ids[kMaximumK]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + best_scores[rank] = worst_score; + best_ids[rank] = UINT64_MAX; + } + + const std::uint32_t query_id = blockIdx.x; + const std::uint64_t query_offset = static_cast(query_id) * dim; + float query_norm = 0.0F; + if (metric == Metric::kCosine) { + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + query_norm = fmaf(query, query, query_norm); + } + } + + const std::uint64_t positions_offset = + static_cast(query_id) * candidate_stride; + for (std::uint64_t candidate = 0; candidate < candidate_counts[query_id]; + ++candidate) { + const std::uint64_t position = + candidate_positions[positions_offset + candidate]; + const std::uint64_t vector_offset = position * dim; + float dot = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + const float vector = loadInput(vectors, vector_offset + d); + if (metric == Metric::kL2) { + const float difference = query - vector; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, vector, dot); + if (metric == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } + } + } + float score = dot; + if (metric == Metric::kL2) { + score = squared_l2; + } else if (metric == Metric::kCosine) { + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot / sqrtf(query_norm * vector_norm); + } + const std::uint64_t vector_id = original_ids[position]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + if (isBetter(score, vector_id, best_scores[rank], best_ids[rank], + metric)) { + for (std::uint32_t shift = top_k - 1; shift > rank; --shift) { + best_scores[shift] = best_scores[shift - 1]; + best_ids[shift] = best_ids[shift - 1]; + } + best_scores[rank] = score; + best_ids[rank] = vector_id; + break; + } + } + } + + const std::uint64_t output_offset = + static_cast(query_id) * top_k; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + top_scores[output_offset + rank] = best_scores[rank]; + top_ids[output_offset + rank] = best_ids[rank]; + } +} + +// 并行版:一个 block 处理一个 query。每个线程扫描一部分候选并维护无序 +// 局部 Top-K,随后 block 用共享内存归约出最终 K 个结果。 +template +__global__ void fusedIvfBlockScanTopKKernel( + const InputType* vectors, const std::uint64_t* original_ids, + const InputType* queries, const std::uint64_t* candidate_positions, + const std::uint64_t* candidate_counts, float* top_scores, + std::uint64_t* top_ids, std::uint64_t candidate_stride, std::uint32_t dim, + std::uint32_t top_k, Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr std::uint32_t kMaximumK = 10; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float shared_scores[kThreads]; + __shared__ std::uint64_t shared_ids[kThreads]; + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t query_id = blockIdx.x; + const float worst_score = + metric == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + float local_scores[kMaximumK]; + std::uint64_t local_ids[kMaximumK]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + local_scores[rank] = worst_score; + local_ids[rank] = UINT64_MAX; + } + std::uint32_t local_worst_rank = 0; + + const std::uint64_t query_offset = static_cast(query_id) * dim; + float query_norm = 0.0F; + if (metric == Metric::kCosine) { + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + query_norm = fmaf(query, query, query_norm); + } + } + const std::uint64_t positions_offset = + static_cast(query_id) * candidate_stride; + for (std::uint64_t candidate = thread_id; + candidate < candidate_counts[query_id]; candidate += blockDim.x) { + const std::uint64_t position = + candidate_positions[positions_offset + candidate]; + const std::uint64_t vector_offset = position * dim; + float dot = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + const float vector = loadInput(vectors, vector_offset + d); + if (metric == Metric::kL2) { + const float difference = query - vector; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, vector, dot); + if (metric == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } + } + } + float score = dot; + if (metric == Metric::kL2) { + score = squared_l2; + } else if (metric == Metric::kCosine) { + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot / sqrtf(query_norm * vector_norm); + } + const std::uint64_t vector_id = original_ids[position]; + if (isBetter(score, vector_id, local_scores[local_worst_rank], + local_ids[local_worst_rank], metric)) { + local_scores[local_worst_rank] = score; + local_ids[local_worst_rank] = vector_id; + local_worst_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(local_scores[local_worst_rank], + local_ids[local_worst_rank], local_scores[rank], + local_ids[rank], metric)) { + local_worst_rank = rank; + } + } + } + } + + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + std::uint32_t local_best_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(local_scores[rank], local_ids[rank], + local_scores[local_best_rank], local_ids[local_best_rank], + metric)) { + local_best_rank = rank; + } + } + shared_scores[thread_id] = local_scores[local_best_rank]; + shared_ids[thread_id] = local_ids[local_best_rank]; + __syncthreads(); + for (std::uint32_t stride = kThreads / 2; stride > 0; stride >>= 1) { + if (thread_id < stride && + isBetter(shared_scores[thread_id + stride], + shared_ids[thread_id + stride], shared_scores[thread_id], + shared_ids[thread_id], metric)) { + shared_scores[thread_id] = shared_scores[thread_id + stride]; + shared_ids[thread_id] = shared_ids[thread_id + stride]; + } + __syncthreads(); + } + if (thread_id == 0) { + const std::uint64_t output_offset = + static_cast(query_id) * top_k + output_rank; + top_scores[output_offset] = shared_scores[0]; + top_ids[output_offset] = shared_ids[0]; + } + const std::uint64_t selected_id = shared_ids[0]; + if (local_ids[local_best_rank] == selected_id) { + local_scores[local_best_rank] = worst_score; + local_ids[local_best_rank] = UINT64_MAX; + } + __syncthreads(); + } +} + +template +__global__ void ivfScanBucketsScalarKernel( + const InputType* vectors, const std::uint64_t* original_ids, + const std::uint64_t* bucket_offsets, const std::uint32_t* selected_centers, + const InputType* queries, float* probe_scores, std::uint64_t* probe_ids, + const std::uint32_t* active_query_ids, const std::uint32_t* query_nprobes, + std::uint32_t nprobe, std::uint32_t dim, std::uint32_t top_k, Metric metric, + bool apply_memory, DeviceMemoryView metadata, + DeviceMemoryOptions memory_options) { + constexpr std::uint32_t kThreads = 256; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float shared_scores[kThreads]; + __shared__ std::uint64_t shared_ids[kThreads]; + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t probe = blockIdx.x; + const std::uint32_t query_id = + active_query_ids == nullptr ? blockIdx.y : active_query_ids[blockIdx.y]; + if (query_nprobes != nullptr && probe >= query_nprobes[query_id]) { + return; + } + const std::uint32_t center_id = + selected_centers[static_cast(query_id) * nprobe + probe]; + const std::uint64_t bucket_start = bucket_offsets[center_id]; + const std::uint64_t bucket_end = bucket_offsets[center_id + 1]; + const float worst_score = + metric == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + float local_scores[MaximumK]; + std::uint64_t local_ids[MaximumK]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + local_scores[rank] = worst_score; + local_ids[rank] = UINT64_MAX; + } + std::uint32_t local_worst_rank = 0; + + const std::uint64_t query_offset = static_cast(query_id) * dim; + float query_norm = 0.0F; + if (metric == Metric::kCosine) { + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + query_norm = fmaf(query, query, query_norm); + } + } + for (std::uint64_t position = bucket_start + thread_id; position < bucket_end; + position += blockDim.x) { + const std::uint64_t vector_id = original_ids[position]; + if (apply_memory && + !memoryCandidateMatches(metadata, vector_id, memory_options)) { + continue; + } + const std::uint64_t vector_offset = position * dim; + float dot = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + const float query = loadInput(queries, query_offset + d); + const float vector = loadInput(vectors, vector_offset + d); + if (metric == Metric::kL2) { + const float difference = query - vector; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, vector, dot); + if (metric == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } + } + } + float score = dot; + if (metric == Metric::kL2) { + score = squared_l2; + } else if (metric == Metric::kCosine) { + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot / sqrtf(query_norm * vector_norm); + } + if (apply_memory) { + const float boost = + memory_options.importance_weight * metadata.importance[vector_id] + + (memory_options.recency_weight == 0.0F || memory_options.now == 0 + ? 0.0F + : memory_options.recency_weight * + expf(-static_cast( + (metadata.timestamps[vector_id] >= memory_options.now + ? 0.0 + : static_cast( + memory_options.now - + metadata.timestamps[vector_id])) / + memory_options.time_scale))); + score = memory_options.semantic_weight * score + + (metric == Metric::kL2 ? -boost : boost); + } + if (isBetter(score, vector_id, local_scores[local_worst_rank], + local_ids[local_worst_rank], metric)) { + local_scores[local_worst_rank] = score; + local_ids[local_worst_rank] = vector_id; + local_worst_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(local_scores[local_worst_rank], + local_ids[local_worst_rank], local_scores[rank], + local_ids[rank], metric)) { + local_worst_rank = rank; + } + } + } + } + + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + std::uint32_t local_best_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(local_scores[rank], local_ids[rank], + local_scores[local_best_rank], local_ids[local_best_rank], + metric)) { + local_best_rank = rank; + } + } + shared_scores[thread_id] = local_scores[local_best_rank]; + shared_ids[thread_id] = local_ids[local_best_rank]; + __syncthreads(); + for (std::uint32_t stride = kThreads / 2; stride > 0; stride >>= 1) { + if (thread_id < stride && + isBetter(shared_scores[thread_id + stride], + shared_ids[thread_id + stride], shared_scores[thread_id], + shared_ids[thread_id], metric)) { + shared_scores[thread_id] = shared_scores[thread_id + stride]; + shared_ids[thread_id] = shared_ids[thread_id + stride]; + } + __syncthreads(); + } + if (thread_id == 0) { + const std::uint64_t output_offset = + (static_cast(query_id) * nprobe + probe) * top_k + + output_rank; + probe_scores[output_offset] = shared_scores[0]; + probe_ids[output_offset] = shared_ids[0]; + } + const std::uint64_t selected_id = shared_ids[0]; + if (local_ids[local_best_rank] == selected_id) { + local_scores[local_best_rank] = worst_score; + local_ids[local_best_rank] = UINT64_MAX; + } + __syncthreads(); + } +} + +__global__ void countSelectedCenterTasksKernel( + const std::uint32_t* selected_centers, std::uint32_t* center_counts, + std::uint32_t task_count) { + const std::uint32_t task = blockIdx.x * blockDim.x + threadIdx.x; + if (task < task_count) { + atomicAdd(¢er_counts[selected_centers[task]], 1U); + } +} + +__global__ void prepareCenterTaskCursorsKernel( + const std::uint32_t* center_counts, std::uint32_t* center_cursors, + std::uint32_t nlist) { + if (blockIdx.x != 0 || threadIdx.x != 0) { + return; + } + std::uint32_t offset = 0; + for (std::uint32_t center = 0; center < nlist; ++center) { + center_cursors[center] = offset; + offset += center_counts[center]; + } +} + +__global__ void scatterSelectedCenterTasksKernel( + const std::uint32_t* selected_centers, std::uint32_t* center_cursors, + std::uint64_t* bucket_tasks, std::uint32_t nprobe, + std::uint32_t task_count) { + const std::uint32_t task = blockIdx.x * blockDim.x + threadIdx.x; + if (task >= task_count) { + return; + } + const std::uint32_t center = selected_centers[task]; + const std::uint32_t destination = atomicAdd(¢er_cursors[center], 1U); + const std::uint32_t query_id = task / nprobe; + const std::uint32_t probe = task - query_id * nprobe; + bucket_tasks[destination] = + (static_cast(query_id) << 32U) | probe; +} + +// 一个 block 包含若干 warp,每个 warp 协作计算一个候选向量。相邻 lane +// 读取相邻维度,适合行主序向量;lane 0 为该 warp 维护局部 Top-K,最后在 +// WarpsPerBlock 可取 1/2/4/8。大 K 使用更少的独立 heap,并让更多 probe block +// 并发以维持活跃 warp;旧 8-warp 路径和 scalar 路径都保留用于 A/B。 +template +__global__ void ivfScanBucketsWarpKernel( + const InputType* vectors, const std::uint64_t* original_ids, + const std::uint64_t* bucket_offsets, const std::uint32_t* selected_centers, + const std::uint64_t* bucket_tasks, const InputType* queries, + float* probe_scores, std::uint64_t* probe_ids, + const std::uint32_t* active_query_ids, const std::uint32_t* query_nprobes, + std::uint32_t nprobe, std::uint32_t dim, std::uint32_t top_k, + std::uint32_t heap_k, + bool cache_query, bool apply_memory, DeviceMemoryView metadata, + DeviceMemoryOptions memory_options) { + constexpr std::uint32_t kWarpSize = 32; + constexpr std::uint32_t kWarps = WarpsPerBlock; + static_assert(WarpsPerBlock == 1 || WarpsPerBlock == 2 || + WarpsPerBlock == 4 || WarpsPerBlock == 8, + "IVF warp block 只支持 1/2/4/8 个 warp"); + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float warp_scores[kWarps][MaximumK]; + __shared__ std::uint64_t warp_ids[kWarps][MaximumK]; + __shared__ float best_scores[kWarps]; + __shared__ std::uint64_t best_ids[kWarps]; + __shared__ std::uint32_t warp_ranks[kWarps]; + extern __shared__ __align__(16) unsigned char dynamic_shared[]; + auto* shared_query = reinterpret_cast(dynamic_shared); + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t lane_id = thread_id % kWarpSize; + const std::uint32_t warp_id = thread_id / kWarpSize; + std::uint32_t query_slot = blockIdx.y; + std::uint32_t probe = blockIdx.x; + if constexpr (BucketMajor) { + const std::uint64_t task = bucket_tasks[blockIdx.x]; + query_slot = static_cast(task >> 32U); + probe = static_cast(task); + } + const std::uint32_t query_id = active_query_ids == nullptr + ? query_slot + : active_query_ids[query_slot]; + if (query_nprobes != nullptr && probe >= query_nprobes[query_id]) { + return; + } + const std::uint32_t center_id = + selected_centers[static_cast(query_id) * nprobe + probe]; + const std::uint64_t bucket_start = bucket_offsets[center_id]; + const std::uint64_t bucket_end = bucket_offsets[center_id + 1]; + const float worst_score = + MetricValue == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + float heap_root_score = worst_score; + std::uint64_t heap_root_id = UINT64_MAX; + + if (lane_id == 0) { + for (std::uint32_t rank = 0; rank < heap_k; ++rank) { + warp_scores[warp_id][rank] = worst_score; + warp_ids[warp_id][rank] = UINT64_MAX; + } + } + const std::uint64_t query_offset = static_cast(query_id) * dim; + const InputType* query_values = queries + query_offset; + if (cache_query) { + for (std::uint32_t d = thread_id; d < dim; d += blockDim.x) { + shared_query[d] = query_values[d]; + } + } + // 同时等待 heap 初始化和可选 query 缓存完成,不增加额外 block barrier。 + __syncthreads(); + if (cache_query) { + query_values = shared_query; + } + + float query_norm = 0.0F; + if constexpr (MetricValue == Metric::kCosine) { + for (std::uint32_t d = lane_id; d < dim; d += kWarpSize) { + const float query = loadInput(query_values, d); + query_norm = fmaf(query, query, query_norm); + } + query_norm = warpReduceSum(query_norm); + } + + for (std::uint64_t position = bucket_start + warp_id; position < bucket_end; + position += kWarps) { + const std::uint64_t vector_id = original_ids[position]; + const bool accepted = + !apply_memory || + (lane_id == 0 && + memoryCandidateMatches(metadata, vector_id, memory_options)); + if (!__shfl_sync(0xFFFFFFFFU, accepted, 0)) { + continue; + } + const std::uint64_t vector_offset = position * dim; + float dot = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = lane_id; d < dim; d += kWarpSize) { + const float query = loadInput(query_values, d); + const float vector = loadInput(vectors, vector_offset + d); + if constexpr (MetricValue == Metric::kL2) { + const float difference = query - vector; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, vector, dot); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } + } + } + // 每种 metric 只归约实际使用的累加器。旧代码在 inner-product 下还会 + // 对恒为 0 的 squared_l2 做一次完整 shuffle 归约,L2 下也会归约恒为 + // 0 的 dot;这在每个候选上浪费 5 次 warp shuffle。 + if constexpr (MetricValue == Metric::kL2) { + squared_l2 = warpReduceSum(squared_l2); + } else { + dot = warpReduceSum(dot); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm = warpReduceSum(vector_norm); + } + } + if (lane_id == 0) { + float score = dot; + if constexpr (MetricValue == Metric::kL2) { + score = squared_l2; + } else if constexpr (MetricValue == Metric::kCosine) { + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot / sqrtf(query_norm * vector_norm); + } + if (apply_memory) { + score = applyMemoryScore(score, vector_id, metadata, + memory_options); + } + if (isBetter(score, vector_id, heap_root_score, heap_root_id, + MetricValue)) { + // 以空穴下沉代替逐层交换:候选保存在寄存器中,每层只把更差的 + // child 上移一次,最后写入候选。根节点也缓存在寄存器中,避免每个 + // 被扫描向量都读取 shared memory。 + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= heap_k) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < heap_k && + isBetter(warp_scores[warp_id][left], warp_ids[warp_id][left], + warp_scores[warp_id][right], warp_ids[warp_id][right], + MetricValue)) { + worse_child = right; + } + if (!isBetter(score, vector_id, warp_scores[warp_id][worse_child], + warp_ids[warp_id][worse_child], MetricValue)) { + break; + } + warp_scores[warp_id][parent] = warp_scores[warp_id][worse_child]; + warp_ids[warp_id][parent] = warp_ids[warp_id][worse_child]; + parent = worse_child; + } + warp_scores[warp_id][parent] = score; + warp_ids[warp_id][parent] = vector_id; + heap_root_score = warp_scores[warp_id][0]; + heap_root_id = warp_ids[warp_id][0]; + } + } + } + __syncthreads(); + + // 根节点始终是当前最差候选。原地 heap sort 后,每个 warp 的数组按 + // best -> worst 排列,随后只需合并少量 warp 有序列表。 + if (lane_id == 0) { + for (std::uint32_t heap_size = heap_k; heap_size > 1; --heap_size) { + const std::uint32_t last = heap_size - 1; + const float sorted_score = warp_scores[warp_id][0]; + const std::uint64_t sorted_id = warp_ids[warp_id][0]; + const float candidate_score = warp_scores[warp_id][last]; + const std::uint64_t candidate_id = warp_ids[warp_id][last]; + warp_scores[warp_id][last] = sorted_score; + warp_ids[warp_id][last] = sorted_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= last) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < last && + isBetter(warp_scores[warp_id][left], warp_ids[warp_id][left], + warp_scores[warp_id][right], warp_ids[warp_id][right], + MetricValue)) { + worse_child = right; + } + if (!isBetter(candidate_score, candidate_id, + warp_scores[warp_id][worse_child], + warp_ids[warp_id][worse_child], MetricValue)) { + break; + } + warp_scores[warp_id][parent] = warp_scores[warp_id][worse_child]; + warp_ids[warp_id][parent] = warp_ids[warp_id][worse_child]; + parent = worse_child; + } + warp_scores[warp_id][parent] = candidate_score; + warp_ids[warp_id][parent] = candidate_id; + } + warp_ranks[warp_id] = 0; + } + __syncthreads(); + + if constexpr (kWarps == 1) { + if (lane_id == 0) { + const std::uint64_t output_offset = + (static_cast(query_id) * nprobe + probe) * top_k; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + probe_scores[output_offset + rank] = warp_scores[0][rank]; + probe_ids[output_offset + rank] = warp_ids[0][rank]; + } + } + } else { + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + if (lane_id == 0) { + const std::uint32_t rank = warp_ranks[warp_id]; + best_scores[warp_id] = + rank < heap_k ? warp_scores[warp_id][rank] : worst_score; + best_ids[warp_id] = + rank < heap_k ? warp_ids[warp_id][rank] : UINT64_MAX; + } + __syncthreads(); + if (thread_id == 0) { + std::uint32_t best_warp = 0; + for (std::uint32_t candidate_warp = 1; candidate_warp < kWarps; + ++candidate_warp) { + if (isBetter(best_scores[candidate_warp], best_ids[candidate_warp], + best_scores[best_warp], best_ids[best_warp], + MetricValue)) { + best_warp = candidate_warp; + } + } + const std::uint64_t output_offset = + (static_cast(query_id) * nprobe + probe) * top_k + + output_rank; + probe_scores[output_offset] = best_scores[best_warp]; + probe_ids[output_offset] = best_ids[best_warp]; + ++warp_ranks[best_warp]; + } + __syncthreads(); + } + } +} + +template +void launchIvfBucketScanWarp( + dim3 grid, const InputType* vectors, const std::uint64_t* original_ids, + const std::uint64_t* bucket_offsets, const std::uint32_t* selected_centers, + const std::uint64_t* bucket_tasks, const InputType* queries, + float* probe_scores, std::uint64_t* probe_ids, + const std::uint32_t* active_query_ids, const std::uint32_t* query_nprobes, + std::uint32_t nprobe, std::uint32_t dim, std::uint32_t top_k, + std::uint32_t heap_k, Metric metric, bool apply_memory, + DeviceMemoryView metadata, + DeviceMemoryOptions memory_options) { + constexpr std::uint32_t kThreads = WarpsPerBlock * 32; + constexpr std::size_t kMaximumCachedQueryBytes = 8192; + const std::size_t query_bytes = + static_cast(dim) * sizeof(InputType); + const bool cache_query = query_bytes <= kMaximumCachedQueryBytes; + const std::size_t shared_bytes = cache_query ? query_bytes : 0; + if (metric == Metric::kL2) { + ivfScanBucketsWarpKernel + <<>>( + vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, heap_k, cache_query, apply_memory, + metadata, memory_options); + } else if (metric == Metric::kInnerProduct) { + ivfScanBucketsWarpKernel + <<>>( + vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, heap_k, cache_query, apply_memory, + metadata, memory_options); + } else { + ivfScanBucketsWarpKernel + <<>>( + vectors, original_ids, bucket_offsets, selected_centers, bucket_tasks, + queries, probe_scores, probe_ids, active_query_ids, query_nprobes, + nprobe, dim, top_k, heap_k, cache_query, apply_memory, metadata, + memory_options); + } +} + +template +void launchIvfBucketScan( + dim3 grid, const InputType* vectors, const std::uint64_t* original_ids, + const std::uint64_t* bucket_offsets, const std::uint32_t* selected_centers, + const std::uint64_t* bucket_tasks, const InputType* queries, + float* probe_scores, std::uint64_t* probe_ids, + const std::uint32_t* active_query_ids, const std::uint32_t* query_nprobes, + std::uint32_t nprobe, std::uint32_t dim, std::uint32_t top_k, Metric metric, + std::uint32_t warps_per_block, bool bucket_major, + std::uint32_t partitioned_topk_warps, + std::uint32_t partitioned_topk_heap_k, + bool apply_memory, DeviceMemoryView metadata, + DeviceMemoryOptions memory_options) { + constexpr std::uint32_t kThreads = 256; + if (partitioned_topk_warps == 2) { + constexpr std::uint32_t kPartitionHeapK = 32; + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } + return; + } + if (partitioned_topk_warps == 4) { + if (partitioned_topk_heap_k == 16) { + constexpr std::uint32_t kPartitionHeapK = 16; + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } + } else if (top_k <= 50) { + constexpr std::uint32_t kPartitionHeapK = 20; + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } + } else { + constexpr std::uint32_t kPartitionHeapK = 40; + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } + } + return; + } + if (partitioned_topk_warps == 8) { + constexpr std::uint32_t kPartitionHeapK = 8; + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, kPartitionHeapK, metric, + apply_memory, metadata, memory_options); + } + return; + } + if (warps_per_block == 1) { + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } + } else if (warps_per_block == 2) { + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } + } else if (warps_per_block == 4) { + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } + } else if (warps_per_block == 8) { + if (bucket_major) { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } else { + launchIvfBucketScanWarp( + grid, vectors, original_ids, bucket_offsets, selected_centers, + bucket_tasks, queries, probe_scores, probe_ids, active_query_ids, + query_nprobes, nprobe, dim, top_k, top_k, metric, apply_memory, metadata, + memory_options); + } + } else { + ivfScanBucketsScalarKernel<<>>( + vectors, original_ids, bucket_offsets, selected_centers, queries, + probe_scores, probe_ids, active_query_ids, query_nprobes, nprobe, dim, + top_k, metric, apply_memory, metadata, memory_options); + } +} + +// 每个 probe 已按优劣输出有序 Top-K。最终阶段只需维护每个 probe 的当前 +// 游标,每轮在所有列表头之间归约出一个全局结果,避免为 K=50/100 给每个 +// CUDA 线程分配大型局部数组。 +__global__ void ivfMergeProbeTopKKernel(const float* probe_scores, + const std::uint64_t* probe_ids, + float* top_scores, + std::uint64_t* top_ids, + const std::uint32_t* query_nprobes, + std::uint32_t nprobe, + std::uint32_t top_k, Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float shared_scores[kThreads]; + __shared__ std::uint64_t shared_ids[kThreads]; + __shared__ std::uint32_t shared_probes[kThreads]; + extern __shared__ std::uint32_t probe_ranks[]; + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t query_id = blockIdx.x; + const std::uint32_t active_nprobe = + query_nprobes == nullptr ? nprobe : query_nprobes[query_id]; + const float worst_score = + metric == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + for (std::uint32_t probe = thread_id; probe < active_nprobe; + probe += blockDim.x) { + probe_ranks[probe] = 0; + } + __syncthreads(); + + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + float local_best_score = worst_score; + std::uint64_t local_best_id = UINT64_MAX; + std::uint32_t local_best_probe = UINT32_MAX; + for (std::uint32_t probe = thread_id; probe < active_nprobe; + probe += blockDim.x) { + const std::uint32_t rank = probe_ranks[probe]; + if (rank < top_k) { + const std::uint64_t input_offset = + (static_cast(query_id) * nprobe + probe) * top_k + + rank; + const float score = probe_scores[input_offset]; + const std::uint64_t id = probe_ids[input_offset]; + if (isBetter(score, id, local_best_score, local_best_id, metric)) { + local_best_score = score; + local_best_id = id; + local_best_probe = probe; + } + } + } + shared_scores[thread_id] = local_best_score; + shared_ids[thread_id] = local_best_id; + shared_probes[thread_id] = local_best_probe; + __syncthreads(); + for (std::uint32_t stride = kThreads / 2; stride > 0; stride >>= 1) { + if (thread_id < stride && + isBetter(shared_scores[thread_id + stride], + shared_ids[thread_id + stride], shared_scores[thread_id], + shared_ids[thread_id], metric)) { + shared_scores[thread_id] = shared_scores[thread_id + stride]; + shared_ids[thread_id] = shared_ids[thread_id + stride]; + shared_probes[thread_id] = shared_probes[thread_id + stride]; + } + __syncthreads(); + } + if (thread_id == 0) { + const std::uint64_t output_offset = + static_cast(query_id) * top_k + output_rank; + top_scores[output_offset] = shared_scores[0]; + top_ids[output_offset] = shared_ids[0]; + if (shared_probes[0] != UINT32_MAX && shared_ids[0] != UINT64_MAX) { + ++probe_ranks[shared_probes[0]]; + } + } + __syncthreads(); + } +} + +// Deliberately separate baseline: first retrieve semantic Top-(K * factor), +// then launch a second kernel to filter and rerank that bounded candidate set. +// This is kept beside the fused path so their latency and result quality can be +// compared without involving a CPU reranker. +__global__ void rerankMemoryTopKKernel( + const float* semantic_scores, const std::uint64_t* semantic_ids, + float* output_scores, std::uint64_t* output_ids, std::uint32_t semantic_k, + std::uint32_t top_k, Metric metric, DeviceMemoryView metadata, + DeviceMemoryOptions options) { + if (threadIdx.x != 0) { + return; + } + constexpr std::uint32_t kMaximumK = 100; + constexpr float kFloatMaximum = 3.402823466e+38F; + const std::uint32_t query_id = blockIdx.x; + const float worst_score = + metric == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + float best_scores[kMaximumK]; + std::uint64_t best_ids[kMaximumK]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + best_scores[rank] = worst_score; + best_ids[rank] = UINT64_MAX; + } + std::uint32_t worst_rank = 0; + const std::uint64_t input_offset = + static_cast(query_id) * semantic_k; + for (std::uint32_t candidate = 0; candidate < semantic_k; ++candidate) { + const std::uint64_t vector_id = semantic_ids[input_offset + candidate]; + if (vector_id == UINT64_MAX || + !memoryCandidateMatches(metadata, vector_id, options)) { + continue; + } + const float semantic_score = semantic_scores[input_offset + candidate]; + float recency = 0.0F; + if (options.recency_weight != 0.0F && options.now != 0) { + const std::uint64_t timestamp = metadata.timestamps[vector_id]; + const double age = timestamp >= options.now + ? 0.0 + : static_cast(options.now - timestamp); + recency = expf(-static_cast(age / options.time_scale)); + } + const float boost = + options.importance_weight * metadata.importance[vector_id] + + options.recency_weight * recency; + const float score = options.semantic_weight * semantic_score + + (metric == Metric::kL2 ? -boost : boost); + if (isBetter(score, vector_id, best_scores[worst_rank], + best_ids[worst_rank], metric)) { + best_scores[worst_rank] = score; + best_ids[worst_rank] = vector_id; + worst_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(best_scores[worst_rank], best_ids[worst_rank], + best_scores[rank], best_ids[rank], metric)) { + worst_rank = rank; + } + } + } + } + const std::uint64_t output_offset = + static_cast(query_id) * top_k; + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + std::uint32_t best_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(best_scores[rank], best_ids[rank], best_scores[best_rank], + best_ids[best_rank], metric)) { + best_rank = rank; + } + } + output_scores[output_offset + output_rank] = best_scores[best_rank]; + output_ids[output_offset + output_rank] = best_ids[best_rank]; + best_scores[best_rank] = worst_score; + best_ids[best_rank] = UINT64_MAX; + } +} + +void validateSearchConfiguration(const IvfFlatIndex& index, + const QuerySet& queries, + const SearchParams& params, + const MemoryMetadata* metadata) { + validateIvfFlatIndex(index); + if (queries.num_queries == 0 || queries.dim != index.dim || + queries.dtype != index.dtype) { + throw std::runtime_error("查询集与 GPU IVF 索引的维度或 dtype 不匹配"); + } + const std::uint64_t expected_values = queries.num_queries * queries.dim; + if ((index.dtype == DataType::kFloat32 && + queries.values.size() != expected_values) || + (index.dtype == DataType::kFloat16 && + queries.half_values.size() != expected_values)) { + throw std::runtime_error("GPU IVF 查询数据长度与元数据不一致"); + } + constexpr std::uint32_t kMaximumTopK = 100; + constexpr std::uint32_t kMaximumNprobe = 8192; + if (params.top_k == 0 || params.top_k > kMaximumTopK || + params.top_k > index.num_vectors || params.nprobe == 0 || + params.nprobe > index.nlist || params.nprobe > kMaximumNprobe || + params.batch_size == 0) { + throw std::runtime_error("GPU IVF 的 top_k、nprobe 或 batch_size 不合法"); + } + if (params.distance_mode != "simple" && params.distance_mode != "warp" && + params.distance_mode != "warp_compact" && + params.distance_mode != "bucket_major" && + params.distance_mode != "bucket_major_partitioned" && + params.distance_mode != "bucket_major_partitioned2" && + params.distance_mode != "bucket_major_partitioned4x16" && + params.distance_mode != "bucket_major_partitioned8x8" && + params.distance_mode != "warp1" && params.distance_mode != "warp2" && + params.distance_mode != "warp4" && params.distance_mode != "warp8") { + throw std::runtime_error( + "GPU IVF 的 distance_mode 必须是 simple、warp、warp_compact、" + "bucket_major、bucket_major_partitioned、" + "bucket_major_partitioned2、bucket_major_partitioned4x16、" + "bucket_major_partitioned8x8、warp1、warp2、warp4 或 warp8"); + } + const bool bucket_major = params.distance_mode == "bucket_major" || + params.distance_mode == + "bucket_major_partitioned" || + params.distance_mode == + "bucket_major_partitioned2" || + params.distance_mode == + "bucket_major_partitioned4x16" || + params.distance_mode == + "bucket_major_partitioned8x8"; + if (bucket_major && + (params.nprobe_policy != "fixed" || + static_cast(params.batch_size) * params.nprobe > + UINT32_MAX)) { + throw std::runtime_error( + "GPU IVF 的 bucket_major 当前只支持 fixed nprobe 和 32 位任务数"); + } + const bool partitioned = + params.distance_mode == "bucket_major_partitioned" || + params.distance_mode == "bucket_major_partitioned2" || + params.distance_mode == "bucket_major_partitioned4x16" || + params.distance_mode == "bucket_major_partitioned8x8"; + if (partitioned && params.top_k != 50 && params.top_k != 100) { + throw std::runtime_error( + "bucket_major_partitioned 仅支持 top_k=50 或 top_k=100"); + } + if (params.distance_mode == "bucket_major_partitioned2" && + params.top_k != 50) { + throw std::runtime_error( + "bucket_major_partitioned2 仅用于 top_k=50 的 2x32 实验"); + } + if ((params.distance_mode == "bucket_major_partitioned4x16" || + params.distance_mode == "bucket_major_partitioned8x8") && + params.top_k != 50) { + throw std::runtime_error( + "4x16 与 8x8 分区模式仅用于 top_k=50 实验"); + } + if (partitioned && params.memory_mode != "disabled") { + throw std::runtime_error( + "bucket_major_partitioned 要求 memory_mode=disabled"); + } + if (params.nprobe_policy != "fixed" && params.nprobe_policy != "score_mass") { + throw std::runtime_error( + "GPU IVF 的 nprobe_policy 必须是 fixed 或 score_mass"); + } + if (params.nprobe_policy == "score_mass" && + (params.adaptive_nprobe_min == 0 || + params.adaptive_nprobe_min > params.nprobe || + params.adaptive_nprobe_step == 0 || + !std::isfinite(params.adaptive_target_mass) || + params.adaptive_target_mass <= 0.0F || + params.adaptive_target_mass > 1.0F || + !std::isfinite(params.adaptive_temperature) || + params.adaptive_temperature <= 0.0F)) { + throw std::runtime_error("GPU IVF 的自适应 nprobe 参数不合法"); + } + if (params.adaptive_execution != "masked" && + params.adaptive_execution != "grouped") { + throw std::runtime_error( + "GPU IVF 的 adaptive_execution 必须是 masked 或 grouped"); + } + if (params.memory_mode != "disabled" && params.memory_mode != "fused" && + params.memory_mode != "rerank") { + throw std::runtime_error( + "GPU IVF 的 memory_mode 必须是 disabled、fused 或 rerank"); + } + if (params.memory_mode != "disabled") { + if (metadata == nullptr) { + throw std::runtime_error("GPU 记忆检索必须提供元数据"); + } + validateMemoryMetadata(*metadata, index.num_vectors); + if (!std::isfinite(params.memory_semantic_weight) || + params.memory_semantic_weight <= 0.0F || + !std::isfinite(params.memory_importance_weight) || + params.memory_importance_weight < 0.0F || + !std::isfinite(params.memory_recency_weight) || + params.memory_recency_weight < 0.0F || + !std::isfinite(params.memory_time_scale) || + params.memory_time_scale <= 0.0F || params.memory_rerank_factor == 0) { + throw std::runtime_error("GPU 记忆评分参数不合法"); + } + } +} + +} // namespace + +struct GpuIvfFlatSearchEngine::Impl { + Impl(const IvfFlatIndex& index, const QuerySet& initial_queries, + const SearchParams& search_params, const MemoryMetadata* metadata) + : num_vectors(index.num_vectors), + dim(index.dim), + nlist(index.nlist), + dtype(index.dtype), + metric(index.metric), + params(search_params), + adaptive_nprobe(search_params.nprobe_policy == "score_mass"), + group_adaptive_queries(search_params.nprobe_policy == "score_mass" && + search_params.adaptive_execution == "grouped"), + bucket_major(search_params.distance_mode == "bucket_major" || + search_params.distance_mode == + "bucket_major_partitioned" || + search_params.distance_mode == + "bucket_major_partitioned2" || + search_params.distance_mode == + "bucket_major_partitioned4x16" || + search_params.distance_mode == + "bucket_major_partitioned8x8"), + partitioned_topk_warps( + search_params.distance_mode == "bucket_major_partitioned2" + ? 2U + : search_params.distance_mode == + "bucket_major_partitioned8x8" + ? 8U + : search_params.distance_mode == "bucket_major_partitioned" + || search_params.distance_mode == + "bucket_major_partitioned4x16" + ? 4U + : 0U), + partitioned_topk_heap_k( + search_params.distance_mode == "bucket_major_partitioned2" + ? 32U + : search_params.distance_mode == + "bucket_major_partitioned4x16" + ? 16U + : search_params.distance_mode == + "bucket_major_partitioned8x8" + ? 8U + : search_params.top_k <= 50 ? 20U : 40U), + memory_enabled(search_params.memory_mode != "disabled"), + fused_memory(search_params.memory_mode == "fused"), + separate_rerank(search_params.memory_mode == "rerank"), + use_fp16(index.dtype == DataType::kFloat16), + input_element_bytes(use_fp16 ? sizeof(std::uint16_t) : sizeof(float)), + batch_capacity(search_params.batch_size), + host_index(&index), + host_metadata(metadata) { + validateSearchConfiguration(index, initial_queries, params, metadata); + scan_top_k = params.top_k; + if (separate_rerank) { + const std::uint64_t requested = static_cast(params.top_k) * + params.memory_rerank_factor; + scan_top_k = static_cast( + std::min({requested, 100, num_vectors})); + } + std::vector bucket_sizes(index.nlist); + for (std::uint32_t center_id = 0; center_id < index.nlist; ++center_id) { + bucket_sizes[center_id] = + index.offsets[center_id + 1] - index.offsets[center_id]; + } + std::sort(bucket_sizes.begin(), bucket_sizes.end()); + const std::uint32_t minimum_probe_count = + adaptive_nprobe ? params.adaptive_nprobe_min : params.nprobe; + const std::uint64_t minimum_candidate_count = std::accumulate( + bucket_sizes.begin(), bucket_sizes.begin() + minimum_probe_count, + std::uint64_t{0}); + if (minimum_candidate_count < scan_top_k) { + throw std::runtime_error( + "GPU IVF 的部分 nprobe 桶组合候选数可能少于 top_k"); + } + const std::size_t vector_bytes = + static_cast(num_vectors) * dim * input_element_bytes; + const std::size_t query_bytes = + static_cast(batch_capacity) * dim * input_element_bytes; + const std::size_t center_score_slots = + static_cast(batch_capacity) * nlist; + const std::size_t selected_center_slots = + static_cast(batch_capacity) * params.nprobe; + const std::size_t probe_result_slots = selected_center_slots * scan_top_k; + const std::size_t result_slots = + static_cast(batch_capacity) * scan_top_k; + device_bytes = + vector_bytes + + static_cast(num_vectors) * sizeof(std::uint64_t) + + (memory_enabled ? static_cast(num_vectors) * + (sizeof(std::uint64_t) + sizeof(float) + + 2 * sizeof(std::uint32_t)) + : 0) + + static_cast(nlist) * dim * sizeof(float) + + (static_cast(nlist) + 1) * sizeof(std::uint64_t) + + query_bytes + center_score_slots * sizeof(float) + + selected_center_slots * sizeof(std::uint32_t) + + (adaptive_nprobe ? selected_center_slots * sizeof(float) + + static_cast(batch_capacity) * + sizeof(std::uint32_t) + + (group_adaptive_queries + ? static_cast(batch_capacity) * + sizeof(std::uint32_t) + : 0) + : 0) + + (bucket_major + ? 2 * static_cast(nlist) * sizeof(std::uint32_t) + + selected_center_slots * sizeof(std::uint64_t) + : 0) + + probe_result_slots * (sizeof(float) + sizeof(std::uint64_t)) + + result_slots * (sizeof(float) + sizeof(std::uint64_t)); + device_vectors = std::make_unique(vector_bytes); + device_ids = std::make_unique( + static_cast(num_vectors) * sizeof(std::uint64_t)); + device_centers = std::make_unique( + static_cast(nlist) * dim * sizeof(float)); + device_offsets = std::make_unique( + (static_cast(nlist) + 1) * sizeof(std::uint64_t)); + if (memory_enabled) { + device_timestamps = std::make_unique( + static_cast(num_vectors) * sizeof(std::uint64_t)); + device_importance = std::make_unique( + static_cast(num_vectors) * sizeof(float)); + device_session_ids = std::make_unique( + static_cast(num_vectors) * sizeof(std::uint32_t)); + device_source_types = std::make_unique( + static_cast(num_vectors) * sizeof(std::uint32_t)); + } + device_queries = std::make_unique(query_bytes); + device_center_scores = + std::make_unique(center_score_slots * sizeof(float)); + device_selected_centers = std::make_unique( + selected_center_slots * sizeof(std::uint32_t)); + if (adaptive_nprobe) { + device_selected_scores = + std::make_unique(selected_center_slots * sizeof(float)); + device_query_nprobes = std::make_unique( + static_cast(batch_capacity) * sizeof(std::uint32_t)); + if (group_adaptive_queries) { + device_active_query_ids = std::make_unique( + static_cast(batch_capacity) * sizeof(std::uint32_t)); + } + } + if (bucket_major) { + device_bucket_task_counts = std::make_unique( + static_cast(nlist) * sizeof(std::uint32_t)); + device_bucket_task_cursors = std::make_unique( + static_cast(nlist) * sizeof(std::uint32_t)); + device_bucket_tasks = std::make_unique( + selected_center_slots * sizeof(std::uint64_t)); + } + device_probe_scores = + std::make_unique(probe_result_slots * sizeof(float)); + device_probe_ids = std::make_unique(probe_result_slots * + sizeof(std::uint64_t)); + device_top_scores = + std::make_unique(result_slots * sizeof(float)); + device_top_ids = + std::make_unique(result_slots * sizeof(std::uint64_t)); + + CudaEvent copy_start; + CudaEvent copy_end; + copy_start.record(); + const void* vectors = + use_fp16 ? static_cast(index.half_values.data()) + : static_cast(index.values.data()); + checkCuda(cudaMemcpy(device_vectors->data(), vectors, vector_bytes, + cudaMemcpyHostToDevice), + "复制 IVF 向量到 GPU"); + checkCuda(cudaMemcpy( + device_ids->data(), index.ids.data(), + static_cast(num_vectors) * sizeof(std::uint64_t), + cudaMemcpyHostToDevice), + "复制 IVF ID 到 GPU"); + checkCuda(cudaMemcpy(device_centers->data(), index.centers.data(), + static_cast(nlist) * dim * sizeof(float), + cudaMemcpyHostToDevice), + "复制 IVF centers 到 GPU"); + checkCuda(cudaMemcpy( + device_offsets->data(), index.offsets.data(), + (static_cast(nlist) + 1) * sizeof(std::uint64_t), + cudaMemcpyHostToDevice), + "复制 IVF offsets 到 GPU"); + if (memory_enabled) { + checkCuda( + cudaMemcpy( + device_timestamps->data(), metadata->timestamps.data(), + static_cast(num_vectors) * sizeof(std::uint64_t), + cudaMemcpyHostToDevice), + "复制记忆 timestamps 到 GPU"); + checkCuda( + cudaMemcpy(device_importance->data(), metadata->importance.data(), + static_cast(num_vectors) * sizeof(float), + cudaMemcpyHostToDevice), + "复制记忆 importance 到 GPU"); + checkCuda( + cudaMemcpy( + device_session_ids->data(), metadata->session_ids.data(), + static_cast(num_vectors) * sizeof(std::uint32_t), + cudaMemcpyHostToDevice), + "复制记忆 session IDs 到 GPU"); + checkCuda( + cudaMemcpy( + device_source_types->data(), metadata->source_types.data(), + static_cast(num_vectors) * sizeof(std::uint32_t), + cudaMemcpyHostToDevice), + "复制记忆 source types 到 GPU"); + } + copy_end.record(); + copy_end.synchronize(); + index_h2d_ms = elapsedMilliseconds(copy_start, copy_end); + } + + std::uint64_t num_vectors; + std::uint32_t dim; + std::uint32_t nlist; + DataType dtype; + Metric metric; + SearchParams params; + bool adaptive_nprobe; + bool group_adaptive_queries; + bool bucket_major; + std::uint32_t partitioned_topk_warps; + std::uint32_t partitioned_topk_heap_k; + bool memory_enabled; + bool fused_memory; + bool separate_rerank; + bool use_fp16; + std::size_t input_element_bytes; + std::uint32_t batch_capacity; + std::uint32_t scan_top_k = 0; + const IvfFlatIndex* host_index; + const MemoryMetadata* host_metadata; + double index_h2d_ms = 0.0; + std::size_t device_bytes = 0; + std::unique_ptr device_vectors; + std::unique_ptr device_ids; + std::unique_ptr device_centers; + std::unique_ptr device_offsets; + std::unique_ptr device_timestamps; + std::unique_ptr device_importance; + std::unique_ptr device_session_ids; + std::unique_ptr device_source_types; + std::unique_ptr device_queries; + std::unique_ptr device_center_scores; + std::unique_ptr device_selected_centers; + std::unique_ptr device_selected_scores; + std::unique_ptr device_query_nprobes; + std::unique_ptr device_active_query_ids; + std::unique_ptr device_bucket_task_counts; + std::unique_ptr device_bucket_task_cursors; + std::unique_ptr device_bucket_tasks; + std::unique_ptr device_probe_scores; + std::unique_ptr device_probe_ids; + std::unique_ptr device_top_scores; + std::unique_ptr device_top_ids; +}; + +GpuIvfFlatSearchEngine::GpuIvfFlatSearchEngine(const IvfFlatIndex& index, + const QuerySet& initial_queries, + const SearchParams& params, + const MemoryMetadata* metadata) + : impl_(std::make_unique(index, initial_queries, params, metadata)) {} + +GpuIvfFlatSearchEngine::~GpuIvfFlatSearchEngine() = default; +GpuIvfFlatSearchEngine::GpuIvfFlatSearchEngine( + GpuIvfFlatSearchEngine&&) noexcept = default; +GpuIvfFlatSearchEngine& GpuIvfFlatSearchEngine::operator=( + GpuIvfFlatSearchEngine&&) noexcept = default; + +double GpuIvfFlatSearchEngine::indexH2DMilliseconds() const { + return impl_->index_h2d_ms; +} + +std::size_t GpuIvfFlatSearchEngine::deviceBytes() const { + return impl_->device_bytes; +} + +SearchResults GpuIvfFlatSearchEngine::search(const QuerySet& queries, + SearchStats* stats) { + validateSearchConfiguration(*impl_->host_index, queries, impl_->params, + impl_->host_metadata); + SearchStats measured; + SearchResults results(queries.num_queries); + std::vector host_top_scores( + static_cast(impl_->batch_capacity) * impl_->params.top_k); + std::vector host_top_ids( + static_cast(impl_->batch_capacity) * impl_->params.top_k); + std::vector host_query_nprobes(impl_->batch_capacity, + impl_->params.nprobe); + + CudaEvent copy_start; + CudaEvent copy_end; + CudaEvent center_end; + CudaEvent scan_end; + CudaEvent merge_end; + CudaEvent rerank_end; + CudaEvent result_end; + for (std::uint64_t batch_start = 0; batch_start < queries.num_queries; + batch_start += impl_->batch_capacity) { + const std::uint32_t batch_count = + static_cast(std::min( + impl_->batch_capacity, queries.num_queries - batch_start)); + const std::size_t query_value_offset = + static_cast(batch_start) * impl_->dim; + const void* query_data = + impl_->use_fp16 ? static_cast(queries.half_values.data() + + query_value_offset) + : static_cast(queries.values.data() + + query_value_offset); + copy_start.record(); + checkCuda(cudaMemcpy(impl_->device_queries->data(), query_data, + static_cast(batch_count) * impl_->dim * + impl_->input_element_bytes, + cudaMemcpyHostToDevice), + "复制 IVF queries 到 GPU"); + copy_end.record(); + + constexpr std::uint32_t kThreads = 256; + const dim3 center_grid((impl_->nlist + kThreads - 1) / kThreads, + batch_count); + if (impl_->use_fp16) { + ivfCenterScoresKernel<<>>( + static_cast(impl_->device_centers->data()), + static_cast(impl_->device_queries->data()), + static_cast(impl_->device_center_scores->data()), + impl_->nlist, impl_->dim, batch_count, impl_->metric); + } else { + ivfCenterScoresKernel<<>>( + static_cast(impl_->device_centers->data()), + static_cast(impl_->device_queries->data()), + static_cast(impl_->device_center_scores->data()), + impl_->nlist, impl_->dim, batch_count, impl_->metric); + } + checkCuda(cudaGetLastError(), "启动 ivfCenterScoresKernel"); + ivfSelectProbesBlockKernel<<>>( + static_cast(impl_->device_center_scores->data()), + static_cast(impl_->device_selected_centers->data()), + impl_->adaptive_nprobe + ? static_cast(impl_->device_selected_scores->data()) + : nullptr, + impl_->nlist, impl_->params.nprobe, impl_->metric); + checkCuda(cudaGetLastError(), "启动 ivfSelectProbesBlockKernel"); + if (impl_->adaptive_nprobe) { + constexpr std::uint32_t kPolicyThreads = 128; + const std::uint32_t policy_blocks = + (batch_count + kPolicyThreads - 1) / kPolicyThreads; + chooseAdaptiveNprobeKernel<<>>( + static_cast(impl_->device_selected_scores->data()), + static_cast(impl_->device_query_nprobes->data()), + batch_count, impl_->params.nprobe, impl_->params.adaptive_nprobe_min, + impl_->params.adaptive_nprobe_step, + impl_->params.adaptive_target_mass, + impl_->params.adaptive_temperature, impl_->metric); + checkCuda(cudaGetLastError(), "启动 chooseAdaptiveNprobeKernel"); + } + center_end.record(); + + struct QueryTier { + std::uint32_t nprobe; + std::uint32_t offset; + std::uint32_t count; + }; + std::vector query_tiers; + std::vector active_query_ids; + if (impl_->group_adaptive_queries) { + // 自适应策略会产生多个 nprobe tier。先取回很小的计数数组,在 CPU + // 上稳定分组,再一次性上传 query ID;桶扫描因此不再启动空 block, + // 同一个 kernel launch 内也不会混入工作量悬殊的 query。 + center_end.synchronize(); + const auto policy_start = std::chrono::steady_clock::now(); + checkCuda( + cudaMemcpy( + host_query_nprobes.data(), impl_->device_query_nprobes->data(), + static_cast(batch_count) * sizeof(std::uint32_t), + cudaMemcpyDeviceToHost), + "复制自适应 nprobe 到 CPU"); + std::vector unique_nprobes( + host_query_nprobes.begin(), host_query_nprobes.begin() + batch_count); + std::sort(unique_nprobes.begin(), unique_nprobes.end()); + unique_nprobes.erase( + std::unique(unique_nprobes.begin(), unique_nprobes.end()), + unique_nprobes.end()); + active_query_ids.reserve(batch_count); + for (const std::uint32_t tier_nprobe : unique_nprobes) { + const std::uint32_t offset = + static_cast(active_query_ids.size()); + for (std::uint32_t query_id = 0; query_id < batch_count; ++query_id) { + if (host_query_nprobes[query_id] == tier_nprobe) { + active_query_ids.push_back(query_id); + } + } + query_tiers.push_back( + {tier_nprobe, offset, + static_cast(active_query_ids.size()) - offset}); + } + checkCuda( + cudaMemcpy( + impl_->device_active_query_ids->data(), active_query_ids.data(), + static_cast(batch_count) * sizeof(std::uint32_t), + cudaMemcpyHostToDevice), + "复制自适应 query 分层到 GPU"); + const auto policy_end = std::chrono::steady_clock::now(); + measured.adaptive_policy_ms += + std::chrono::duration(policy_end - policy_start) + .count(); + } + + const auto* device_ids = + static_cast(impl_->device_ids->data()); + const auto* device_offsets = + static_cast(impl_->device_offsets->data()); + const auto* selected_centers = static_cast( + impl_->device_selected_centers->data()); + auto* probe_scores = + static_cast(impl_->device_probe_scores->data()); + auto* probe_ids = + static_cast(impl_->device_probe_ids->data()); + DeviceMemoryView memory_view; + DeviceMemoryOptions memory_options; + if (impl_->memory_enabled) { + memory_view = { + static_cast(impl_->device_timestamps->data()), + static_cast(impl_->device_importance->data()), + static_cast(impl_->device_session_ids->data()), + static_cast( + impl_->device_source_types->data())}; + memory_options = {impl_->params.memory_semantic_weight, + impl_->params.memory_importance_weight, + impl_->params.memory_recency_weight, + impl_->params.memory_time_scale, + impl_->params.memory_now, + impl_->params.filter_min_timestamp, + impl_->params.filter_session_id, + impl_->params.filter_source_type}; + } + const auto* query_nprobes = impl_->adaptive_nprobe + ? static_cast( + impl_->device_query_nprobes->data()) + : nullptr; + std::uint32_t warps_per_block = 0; + const bool bucket_major = impl_->bucket_major; + const std::uint32_t partitioned_topk_warps = + impl_->partitioned_topk_warps; + const std::uint64_t* bucket_tasks = nullptr; + if (bucket_major) { + const std::uint32_t task_count = batch_count * impl_->params.nprobe; + auto* center_counts = static_cast( + impl_->device_bucket_task_counts->data()); + auto* center_cursors = static_cast( + impl_->device_bucket_task_cursors->data()); + auto* mutable_bucket_tasks = static_cast( + impl_->device_bucket_tasks->data()); + checkCuda(cudaMemsetAsync(center_counts, 0, + static_cast(impl_->nlist) * + sizeof(std::uint32_t)), + "清零 bucket-major 任务计数"); + const std::uint32_t task_blocks = + (task_count + kThreads - 1) / kThreads; + countSelectedCenterTasksKernel<<>>( + selected_centers, center_counts, task_count); + prepareCenterTaskCursorsKernel<<<1, 1>>>( + center_counts, center_cursors, impl_->nlist); + scatterSelectedCenterTasksKernel<<>>( + selected_centers, center_cursors, mutable_bucket_tasks, + impl_->params.nprobe, task_count); + bucket_tasks = mutable_bucket_tasks; + } + if (impl_->params.distance_mode == "warp" || + impl_->params.distance_mode == "warp8") { + warps_per_block = 8; + } else if (impl_->params.distance_mode == "warp1") { + warps_per_block = 1; + } else if (impl_->params.distance_mode == "warp4") { + warps_per_block = 4; + } else if (impl_->params.distance_mode == "warp2") { + warps_per_block = 2; + } else if (impl_->params.distance_mode == "warp_compact" || + bucket_major) { + // K10 保持高距离计算并行度;K50/K100 逐步减少每个 probe 重复维护的 + // heap 数。K100 的单 warp 版本在 Ada 上减少了候选插入与排序开销。 + warps_per_block = impl_->scan_top_k <= 10 ? 8 + : impl_->scan_top_k <= 50 ? 2 + : 1; + } + const auto launch_scan = [&](dim3 scan_grid, + const std::uint32_t* active_ids) { + if (impl_->use_fp16) { + const auto* vectors = + static_cast(impl_->device_vectors->data()); + const auto* device_queries = + static_cast(impl_->device_queries->data()); + if (impl_->scan_top_k <= 10) { + launchIvfBucketScan<__half, 10>( + scan_grid, vectors, device_ids, device_offsets, selected_centers, + bucket_tasks, device_queries, probe_scores, probe_ids, active_ids, + query_nprobes, impl_->params.nprobe, impl_->dim, + impl_->scan_top_k, impl_->metric, warps_per_block, + bucket_major, partitioned_topk_warps, + impl_->partitioned_topk_heap_k, impl_->fused_memory, memory_view, + memory_options); + } else if (impl_->scan_top_k <= 50) { + launchIvfBucketScan<__half, 50>( + scan_grid, vectors, device_ids, device_offsets, selected_centers, + bucket_tasks, device_queries, probe_scores, probe_ids, active_ids, + query_nprobes, impl_->params.nprobe, impl_->dim, + impl_->scan_top_k, impl_->metric, warps_per_block, + bucket_major, partitioned_topk_warps, + impl_->partitioned_topk_heap_k, impl_->fused_memory, memory_view, + memory_options); + } else { + launchIvfBucketScan<__half, 100>( + scan_grid, vectors, device_ids, device_offsets, selected_centers, + bucket_tasks, device_queries, probe_scores, probe_ids, active_ids, + query_nprobes, impl_->params.nprobe, impl_->dim, + impl_->scan_top_k, impl_->metric, warps_per_block, + bucket_major, partitioned_topk_warps, + impl_->partitioned_topk_heap_k, impl_->fused_memory, memory_view, + memory_options); + } + } else { + const auto* vectors = + static_cast(impl_->device_vectors->data()); + const auto* device_queries = + static_cast(impl_->device_queries->data()); + if (impl_->scan_top_k <= 10) { + launchIvfBucketScan( + scan_grid, vectors, device_ids, device_offsets, selected_centers, + bucket_tasks, device_queries, probe_scores, probe_ids, active_ids, + query_nprobes, impl_->params.nprobe, impl_->dim, + impl_->scan_top_k, impl_->metric, warps_per_block, + bucket_major, partitioned_topk_warps, + impl_->partitioned_topk_heap_k, impl_->fused_memory, memory_view, + memory_options); + } else if (impl_->scan_top_k <= 50) { + launchIvfBucketScan( + scan_grid, vectors, device_ids, device_offsets, selected_centers, + bucket_tasks, device_queries, probe_scores, probe_ids, active_ids, + query_nprobes, impl_->params.nprobe, impl_->dim, + impl_->scan_top_k, impl_->metric, warps_per_block, + bucket_major, partitioned_topk_warps, + impl_->partitioned_topk_heap_k, impl_->fused_memory, memory_view, + memory_options); + } else { + launchIvfBucketScan( + scan_grid, vectors, device_ids, device_offsets, selected_centers, + bucket_tasks, device_queries, probe_scores, probe_ids, active_ids, + query_nprobes, impl_->params.nprobe, impl_->dim, + impl_->scan_top_k, impl_->metric, warps_per_block, + bucket_major, partitioned_topk_warps, + impl_->partitioned_topk_heap_k, impl_->fused_memory, memory_view, + memory_options); + } + } + }; + if (impl_->group_adaptive_queries) { + const auto* grouped_query_ids = static_cast( + impl_->device_active_query_ids->data()); + for (const QueryTier& tier : query_tiers) { + launch_scan(bucket_major + ? dim3(tier.count, impl_->host_index->nlist) + : dim3(tier.nprobe, tier.count), + grouped_query_ids + tier.offset); + } + } else { + launch_scan(bucket_major + ? dim3(batch_count * impl_->params.nprobe) + : dim3(impl_->params.nprobe, batch_count), + nullptr); + } + checkCuda(cudaGetLastError(), "启动 IVF bucket scan kernel"); + scan_end.record(); + + const std::size_t merge_shared_bytes = + static_cast(impl_->params.nprobe) * sizeof(std::uint32_t); + ivfMergeProbeTopKKernel<<>>( + static_cast(impl_->device_probe_scores->data()), + static_cast(impl_->device_probe_ids->data()), + static_cast(impl_->device_top_scores->data()), + static_cast(impl_->device_top_ids->data()), + query_nprobes, impl_->params.nprobe, impl_->scan_top_k, impl_->metric); + checkCuda(cudaGetLastError(), "启动 ivfMergeProbeTopKKernel"); + merge_end.record(); + + const float* result_scores = + static_cast(impl_->device_top_scores->data()); + const std::uint64_t* result_ids = + static_cast(impl_->device_top_ids->data()); + if (impl_->separate_rerank) { + rerankMemoryTopKKernel<<>>( + result_scores, result_ids, + static_cast(impl_->device_probe_scores->data()), + static_cast(impl_->device_probe_ids->data()), + impl_->scan_top_k, impl_->params.top_k, impl_->metric, memory_view, + memory_options); + checkCuda(cudaGetLastError(), "启动 rerankMemoryTopKKernel"); + result_scores = + static_cast(impl_->device_probe_scores->data()); + result_ids = + static_cast(impl_->device_probe_ids->data()); + } + rerank_end.record(); + + const std::size_t result_count = + static_cast(batch_count) * impl_->params.top_k; + checkCuda(cudaMemcpy(host_top_scores.data(), result_scores, + result_count * sizeof(float), cudaMemcpyDeviceToHost), + "复制 IVF Top-K 分数到 CPU"); + checkCuda(cudaMemcpy(host_top_ids.data(), result_ids, + result_count * sizeof(std::uint64_t), + cudaMemcpyDeviceToHost), + "复制 IVF Top-K ID 到 CPU"); + if (stats != nullptr && impl_->adaptive_nprobe && + !impl_->group_adaptive_queries) { + checkCuda( + cudaMemcpy( + host_query_nprobes.data(), impl_->device_query_nprobes->data(), + static_cast(batch_count) * sizeof(std::uint32_t), + cudaMemcpyDeviceToHost), + "复制自适应 nprobe 到 CPU"); + } + result_end.record(); + result_end.synchronize(); + + measured.query_h2d_ms += elapsedMilliseconds(copy_start, copy_end); + measured.center_selection_ms += elapsedMilliseconds(copy_end, center_end); + measured.distance_kernel_ms += elapsedMilliseconds(center_end, scan_end); + measured.topk_kernel_ms += elapsedMilliseconds(scan_end, merge_end); + if (impl_->separate_rerank) { + measured.memory_rerank_ms += elapsedMilliseconds(merge_end, rerank_end); + } + measured.result_d2h_ms += elapsedMilliseconds(rerank_end, result_end); + measured.batch_latency_ms.push_back( + elapsedMilliseconds(copy_start, result_end)); + if (stats != nullptr) { + for (std::uint32_t query_in_batch = 0; query_in_batch < batch_count; + ++query_in_batch) { + const std::uint32_t selected = impl_->adaptive_nprobe + ? host_query_nprobes[query_in_batch] + : impl_->params.nprobe; + if (measured.selected_probe_queries == 0) { + measured.selected_probe_min = selected; + } else { + measured.selected_probe_min = + std::min(measured.selected_probe_min, selected); + } + measured.selected_probe_max = + std::max(measured.selected_probe_max, selected); + measured.selected_probe_sum += selected; + ++measured.selected_probe_queries; + measured.selected_probe_counts.push_back(selected); + } + } + for (std::uint32_t query_in_batch = 0; query_in_batch < batch_count; + ++query_in_batch) { + std::vector& query_results = + results[batch_start + query_in_batch]; + query_results.reserve(impl_->params.top_k); + const std::size_t offset = + static_cast(query_in_batch) * impl_->params.top_k; + for (std::uint32_t rank = 0; rank < impl_->params.top_k; ++rank) { + if (host_top_ids[offset + rank] == UINT64_MAX) { + break; + } + query_results.push_back( + {host_top_ids[offset + rank], host_top_scores[offset + rank]}); + } + } + } + if (stats != nullptr) { + *stats = measured; + } + return results; +} + +SearchResults gpuIvfFlatSearch(const IvfFlatIndex& index, + const QuerySet& queries, + const SearchParams& params, SearchStats* stats, + const MemoryMetadata* metadata) { + GpuIvfFlatSearchEngine engine(index, queries, params, metadata); + SearchResults results = engine.search(queries, stats); + if (stats != nullptr) { + stats->database_h2d_ms = engine.indexH2DMilliseconds(); + } + return results; +} diff --git a/09_vector_retrieval/PurplePulse/src/gpu_search.cu b/09_vector_retrieval/PurplePulse/src/gpu_search.cu new file mode 100644 index 00000000..8a1390e2 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/gpu_search.cu @@ -0,0 +1,1902 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "search.h" + +// 这是第一版 baseline:一个 CUDA 线程计算一对 query/vector 的完整距离。 +// 优点是代码直观,缺点是暂时没有在线程间共同处理一个向量。 +__device__ __forceinline__ float loadInput(const float* values, + std::uint64_t index) { + return values[index]; +} + +__device__ __forceinline__ float loadInput(const __half* values, + std::uint64_t index) { + return __half2float(values[index]); +} + +template +__global__ void exactDistanceKernel(const InputType* database, + const InputType* queries, float* scores, + std::uint64_t num_vectors, + std::uint32_t dim, + std::uint32_t batch_count, Metric metric) { + const std::uint64_t vector_id = + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const std::uint32_t query_in_batch = blockIdx.y; + if (vector_id >= num_vectors || query_in_batch >= batch_count) { + return; + } + + const std::uint64_t vector_offset = vector_id * dim; + const std::uint64_t query_offset = + static_cast(query_in_batch) * dim; + + float dot = 0.0F; + float query_norm = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + const float q = loadInput(queries, query_offset + d); + const float x = loadInput(database, vector_offset + d); + if (metric == Metric::kL2) { + const float difference = q - x; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(q, x, dot); + if (metric == Metric::kCosine) { + query_norm = fmaf(q, q, query_norm); + vector_norm = fmaf(x, x, vector_norm); + } + } + } + + float score = dot; + if (metric == Metric::kL2) { + score = squared_l2; + } else if (metric == Metric::kCosine) { + score = (query_norm == 0.0F || vector_norm == 0.0F) + ? 0.0F + : dot * rsqrtf(query_norm * vector_norm); + } + scores[static_cast(query_in_batch) * num_vectors + vector_id] = + score; +} + +// 优化版距离计算:一个 warp(32 个线程)共同处理一个向量。 +// lane 0 计算维度 0、32、64...,lane 1 计算 1、33、65...,因此访问是连续的。 +template +__global__ void exactDistanceWarpKernel(const InputType* database, + const InputType* queries, float* scores, + std::uint64_t num_vectors, + std::uint32_t dim, + std::uint32_t batch_count, + Metric metric) { + constexpr std::uint32_t kWarpSize = 32; + const std::uint32_t lane = threadIdx.x % kWarpSize; + const std::uint32_t warp_in_block = threadIdx.x / kWarpSize; + const std::uint32_t warps_per_block = blockDim.x / kWarpSize; + const std::uint64_t first_vector_id = + static_cast(blockIdx.x) * warps_per_block + warp_in_block; + const std::uint32_t query_in_batch = blockIdx.y; + if (query_in_batch >= batch_count) { + return; + } + const std::uint64_t query_offset = + static_cast(query_in_batch) * dim; + + // grid-stride 循环让同一个 warp 连续处理多个向量,避免启动过多 block。 + const std::uint64_t vector_stride = + static_cast(gridDim.x) * warps_per_block; + for (std::uint64_t vector_id = first_vector_id; vector_id < num_vectors; + vector_id += vector_stride) { + const std::uint64_t vector_offset = vector_id * dim; + float dot = 0.0F; + float query_norm = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float q = loadInput(queries, query_offset + d); + const float x = loadInput(database, vector_offset + d); + if (metric == Metric::kL2) { + const float difference = q - x; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(q, x, dot); + if (metric == Metric::kCosine) { + query_norm = fmaf(q, q, query_norm); + vector_norm = fmaf(x, x, vector_norm); + } + } + } + + // 每次让后半部分 lane 的结果加到前半部分,最终总和位于 lane 0。 + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + squared_l2 += __shfl_down_sync(0xffffffff, squared_l2, offset); + dot += __shfl_down_sync(0xffffffff, dot, offset); + query_norm += __shfl_down_sync(0xffffffff, query_norm, offset); + vector_norm += __shfl_down_sync(0xffffffff, vector_norm, offset); + } + + if (lane == 0) { + float score = dot; + if (metric == Metric::kL2) { + score = squared_l2; + } else if (metric == Metric::kCosine) { + score = (query_norm == 0.0F || vector_norm == 0.0F) + ? 0.0F + : dot * rsqrtf(query_norm * vector_norm); + } + scores[static_cast(query_in_batch) * num_vectors + + vector_id] = score; + } + } +} + +__device__ bool isBetter(float candidate_score, std::uint64_t candidate_id, + float current_score, std::uint64_t current_id, + Metric metric) { + if (candidate_score == current_score) { + return candidate_id < current_id; + } + if (metric == Metric::kL2) { + return candidate_score < current_score; + } + return candidate_score > current_score; +} + +// 教学版 GPU Top-K:每个 query 使用一个线程,按顺序维护有序的前 K 个结果。 +// 它的并行度不高,但逻辑清楚,并且避免把完整距离矩阵复制回 CPU。 +// 下一版会用一个 block 共同处理一个 query,作为明确的性能优化步骤。 +__global__ void simpleTopKKernel(const float* scores, float* top_scores, + std::uint64_t* top_ids, + std::uint64_t num_vectors, std::uint32_t top_k, + Metric metric) { + const std::uint32_t query_in_batch = blockIdx.x; + if (threadIdx.x != 0) { + return; + } + + constexpr std::uint32_t kMaximumK = 100; + float best_scores[kMaximumK]; + std::uint64_t best_ids[kMaximumK]; + // 使用 float 最大值作为哨兵,避免依赖额外的 CUDA 数学常量头文件。 + constexpr float kFloatMaximum = 3.402823466e+38F; + const float worst_score = + (metric == Metric::kL2) ? kFloatMaximum : -kFloatMaximum; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + best_scores[rank] = worst_score; + best_ids[rank] = UINT64_MAX; + } + + const float* query_scores = + scores + static_cast(query_in_batch) * num_vectors; + for (std::uint64_t vector_id = 0; vector_id < num_vectors; ++vector_id) { + const float score = query_scores[vector_id]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + if (isBetter(score, vector_id, best_scores[rank], best_ids[rank], + metric)) { + for (std::uint32_t shift = top_k - 1; shift > rank; --shift) { + best_scores[shift] = best_scores[shift - 1]; + best_ids[shift] = best_ids[shift - 1]; + } + best_scores[rank] = score; + best_ids[rank] = vector_id; + break; + } + } + } + + const std::uint64_t output_offset = + static_cast(query_in_batch) * top_k; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + top_scores[output_offset + rank] = best_scores[rank]; + top_ids[output_offset + rank] = best_ids[rank]; + } +} + +// 并行版 GPU Top-K:一个 block 共同处理一个 query。 +// 每一轮中,各线程先在自己负责的候选中找最好结果,再用共享内存归约出全局最好结果。 +// 找到一个结果后将其标记为“最差”,重复 K 轮。这不是最终最优算法,但比单线程版本 +// 更容易理解,也能直接展示线程协作带来的收益。 +__global__ void blockTopKKernel(float* scores, + const std::uint64_t* candidate_ids, + float* top_scores, std::uint64_t* top_ids, + std::uint64_t num_vectors, std::uint32_t top_k, + Metric metric) { + constexpr std::uint32_t kThreads = 256; + __shared__ float shared_scores[kThreads]; + __shared__ std::uint64_t shared_ids[kThreads]; + __shared__ std::uint64_t shared_positions[kThreads]; + + const std::uint32_t query_in_batch = blockIdx.x; + const std::uint32_t thread_id = threadIdx.x; + float* query_scores = + scores + static_cast(query_in_batch) * num_vectors; + constexpr float kFloatMaximum = 3.402823466e+38F; + const float worst_score = + (metric == Metric::kL2) ? kFloatMaximum : -kFloatMaximum; + + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + float local_best_score = worst_score; + std::uint64_t local_best_id = UINT64_MAX; + std::uint64_t local_best_position = UINT64_MAX; + + for (std::uint64_t position = thread_id; position < num_vectors; + position += blockDim.x) { + const float score = query_scores[position]; + const std::uint64_t vector_id = + candidate_ids == nullptr + ? position + : candidate_ids[static_cast(query_in_batch) * + num_vectors + + position]; + if (isBetter(score, vector_id, local_best_score, local_best_id, metric)) { + local_best_score = score; + local_best_id = vector_id; + local_best_position = position; + } + } + + shared_scores[thread_id] = local_best_score; + shared_ids[thread_id] = local_best_id; + shared_positions[thread_id] = local_best_position; + __syncthreads(); + + for (std::uint32_t stride = kThreads / 2; stride > 0; stride >>= 1) { + if (thread_id < stride && + isBetter(shared_scores[thread_id + stride], + shared_ids[thread_id + stride], shared_scores[thread_id], + shared_ids[thread_id], metric)) { + shared_scores[thread_id] = shared_scores[thread_id + stride]; + shared_ids[thread_id] = shared_ids[thread_id + stride]; + shared_positions[thread_id] = shared_positions[thread_id + stride]; + } + __syncthreads(); + } + + if (thread_id == 0) { + const std::uint64_t output_offset = + static_cast(query_in_batch) * top_k + rank; + top_scores[output_offset] = shared_scores[0]; + top_ids[output_offset] = shared_ids[0]; + query_scores[shared_positions[0]] = worst_score; + } + __syncthreads(); + } +} + +// 两阶段 Top-K 的第一阶段:每个线程只扫描自己负责的候选,并保留本线程的 Top-K。 +// 局部数组不需要有序:绝大多数候选只与当前最差项比较一次;只有候选真正 +// 进入 Top-K 时,才扫描 K 个槽位重新找最差项。256 个线程产生 256*K 个候选后, +// 再交给 blockTopKKernel 做最终有序归并。 +__global__ void localTopKCandidatesKernel(const float* scores, + float* local_scores, + std::uint64_t* local_ids, + std::uint64_t num_vectors, + std::uint32_t top_k, Metric metric) { + constexpr std::uint32_t kMaximumLocalK = 10; + const std::uint32_t query_in_batch = blockIdx.x; + const std::uint32_t thread_id = threadIdx.x; + constexpr float kFloatMaximum = 3.402823466e+38F; + const float worst_score = + (metric == Metric::kL2) ? kFloatMaximum : -kFloatMaximum; + + float best_scores[kMaximumLocalK]; + std::uint64_t best_ids[kMaximumLocalK]; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + best_scores[rank] = worst_score; + best_ids[rank] = UINT64_MAX; + } + std::uint32_t worst_rank = 0; + + const float* query_scores = + scores + static_cast(query_in_batch) * num_vectors; + for (std::uint64_t vector_id = thread_id; vector_id < num_vectors; + vector_id += blockDim.x) { + const float score = query_scores[vector_id]; + if (isBetter(score, vector_id, best_scores[worst_rank], + best_ids[worst_rank], metric)) { + best_scores[worst_rank] = score; + best_ids[worst_rank] = vector_id; + worst_rank = 0; + for (std::uint32_t rank = 1; rank < top_k; ++rank) { + if (isBetter(best_scores[worst_rank], best_ids[worst_rank], + best_scores[rank], best_ids[rank], metric)) { + worst_rank = rank; + } + } + } + } + + const std::uint64_t output_offset = + (static_cast(query_in_batch) * blockDim.x + thread_id) * + top_k; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + local_scores[output_offset + rank] = best_scores[rank]; + local_ids[output_offset + rank] = best_ids[rank]; + } +} + +// K=1/10 是项目的主要评测档。将 K 变成编译期常量后,编译器可以展开 +// 局部槽位扫描,并尽量避免通用 kernel 因动态数组索引产生的 thread stack。 +template +__global__ void localTopKCandidatesFixedKernel(const float* scores, + float* local_scores, + std::uint64_t* local_ids, + std::uint64_t num_vectors, + Metric metric) { + static_assert(TopK >= 1 && TopK <= 10, "fixed Top-K 必须位于 [1, 10]"); + const std::uint32_t query_in_batch = blockIdx.x; + const std::uint32_t thread_id = threadIdx.x; + constexpr float kFloatMaximum = 3.402823466e+38F; + const float worst_score = + (metric == Metric::kL2) ? kFloatMaximum : -kFloatMaximum; + + float best_scores[TopK]; + std::uint64_t best_ids[TopK]; +#pragma unroll + for (std::uint32_t rank = 0; rank < TopK; ++rank) { + best_scores[rank] = worst_score; + best_ids[rank] = UINT64_MAX; + } + std::uint32_t worst_rank = 0; + + const float* query_scores = + scores + static_cast(query_in_batch) * num_vectors; + for (std::uint64_t vector_id = thread_id; vector_id < num_vectors; + vector_id += blockDim.x) { + const float score = query_scores[vector_id]; + if (isBetter(score, vector_id, best_scores[worst_rank], + best_ids[worst_rank], metric)) { + best_scores[worst_rank] = score; + best_ids[worst_rank] = vector_id; + worst_rank = 0; +#pragma unroll + for (std::uint32_t rank = 1; rank < TopK; ++rank) { + if (isBetter(best_scores[worst_rank], best_ids[worst_rank], + best_scores[rank], best_ids[rank], metric)) { + worst_rank = rank; + } + } + } + } + + const std::uint64_t output_offset = + (static_cast(query_in_batch) * blockDim.x + thread_id) * + TopK; +#pragma unroll + for (std::uint32_t rank = 0; rank < TopK; ++rank) { + local_scores[output_offset + rank] = best_scores[rank]; + local_ids[output_offset + rank] = best_ids[rank]; + } +} + +// Fused exact scan: each block owns one query/chunk pair and contains eight +// cooperative warps. A warp computes one vector score and maintains a shared +// Top-K heap. The block emits only K candidates, so the full batch*N score +// matrix is never materialized. A small final merge combines all chunks. +// +// The distance-only kernel immediately below is a diagnostic differential +// probe. It intentionally mirrors the fused traversal and arithmetic but +// replaces heap maintenance with one checksum per warp. Comparing its event +// time with the full fused kernel estimates local-selection cost without +// changing the production search path or materializing the score matrix. +template +__global__ void exactFusedDistanceOnlyKernel( + const InputType* database, const InputType* queries, float* warp_checksums, + std::uint64_t num_vectors, std::uint32_t dim, bool cache_query) { + constexpr std::uint32_t kWarpSize = 32; + constexpr std::uint32_t kWarps = 8; + extern __shared__ __align__(16) unsigned char dynamic_shared[]; + auto* shared_query = reinterpret_cast(dynamic_shared); + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t lane = thread_id % kWarpSize; + const std::uint32_t warp = thread_id / kWarpSize; + const std::uint32_t query_id = blockIdx.y; + const InputType* query_values = + queries + static_cast(query_id) * dim; + if (cache_query) { + for (std::uint32_t d = thread_id; d < dim; d += blockDim.x) { + shared_query[d] = query_values[d]; + } + } + __syncthreads(); + if (cache_query) { + query_values = shared_query; + } + + float query_norm = 0.0F; + if constexpr (MetricValue == Metric::kCosine) { + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float query = loadInput(query_values, d); + query_norm = fmaf(query, query, query_norm); + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + query_norm += __shfl_down_sync(0xffffffffU, query_norm, offset); + } + } + + float checksum = 0.0F; + const std::uint64_t first_vector = + static_cast(blockIdx.x) * kWarps + warp; + const std::uint64_t vector_stride = + static_cast(gridDim.x) * kWarps; + for (std::uint64_t vector_id = first_vector; vector_id < num_vectors; + vector_id += vector_stride) { + const std::uint64_t vector_offset = vector_id * dim; + float dot = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float query = loadInput(query_values, d); + const float vector = loadInput(database, vector_offset + d); + if constexpr (MetricValue == Metric::kL2) { + const float difference = query - vector; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, vector, dot); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } + } + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + if constexpr (MetricValue == Metric::kL2) { + squared_l2 += __shfl_down_sync(0xffffffffU, squared_l2, offset); + } else { + dot += __shfl_down_sync(0xffffffffU, dot, offset); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm += __shfl_down_sync(0xffffffffU, vector_norm, offset); + } + } + } + if (lane == 0) { + float score = dot; + if constexpr (MetricValue == Metric::kL2) { + score = squared_l2; + } else if constexpr (MetricValue == Metric::kCosine) { + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot * rsqrtf(query_norm * vector_norm); + } + checksum += score; + } + } + if (lane == 0) { + const std::uint64_t output = + (static_cast(query_id) * gridDim.x + blockIdx.x) * + kWarps + + warp; + warp_checksums[output] = checksum; + } +} + +template +__global__ void exactFusedWarpTopKKernel( + const InputType* database, const InputType* queries, float* local_scores, + std::uint64_t* local_ids, std::uint64_t num_vectors, std::uint32_t dim, + std::uint32_t top_k, bool cache_query) { + constexpr std::uint32_t kWarpSize = 32; + constexpr std::uint32_t kWarps = 8; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float warp_scores[kWarps][MaximumK]; + __shared__ std::uint64_t warp_ids[kWarps][MaximumK]; + __shared__ float merge_scores[kWarps]; + __shared__ std::uint64_t merge_ids[kWarps]; + __shared__ std::uint32_t warp_ranks[kWarps]; + extern __shared__ __align__(16) unsigned char dynamic_shared[]; + auto* shared_query = reinterpret_cast(dynamic_shared); + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t lane = thread_id % kWarpSize; + const std::uint32_t warp = thread_id / kWarpSize; + const std::uint32_t query_id = blockIdx.y; + const float worst_score = + MetricValue == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + if (lane == 0) { + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + warp_scores[warp][rank] = worst_score; + warp_ids[warp][rank] = UINT64_MAX; + } + } + + const InputType* query_values = + queries + static_cast(query_id) * dim; + if (cache_query) { + for (std::uint32_t d = thread_id; d < dim; d += blockDim.x) { + shared_query[d] = query_values[d]; + } + } + __syncthreads(); + if (cache_query) { + query_values = shared_query; + } + + float query_norm = 0.0F; + if constexpr (MetricValue == Metric::kCosine) { + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float query = loadInput(query_values, d); + query_norm = fmaf(query, query, query_norm); + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + query_norm += __shfl_down_sync(0xffffffffU, query_norm, offset); + } + } + + const std::uint64_t first_vector = + static_cast(blockIdx.x) * kWarps + warp; + const std::uint64_t vector_stride = + static_cast(gridDim.x) * kWarps; + for (std::uint64_t vector_id = first_vector; vector_id < num_vectors; + vector_id += vector_stride) { + const std::uint64_t vector_offset = vector_id * dim; + float dot = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float query = loadInput(query_values, d); + const float vector = loadInput(database, vector_offset + d); + if constexpr (MetricValue == Metric::kL2) { + const float difference = query - vector; + squared_l2 = fmaf(difference, difference, squared_l2); + } else { + dot = fmaf(query, vector, dot); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } + } + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + if constexpr (MetricValue == Metric::kL2) { + squared_l2 += __shfl_down_sync(0xffffffffU, squared_l2, offset); + } else { + dot += __shfl_down_sync(0xffffffffU, dot, offset); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm += __shfl_down_sync(0xffffffffU, vector_norm, offset); + } + } + } + if (lane == 0) { + float score = dot; + if constexpr (MetricValue == Metric::kL2) { + score = squared_l2; + } else if constexpr (MetricValue == Metric::kCosine) { + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot * rsqrtf(query_norm * vector_norm); + } + if (isBetter(score, vector_id, warp_scores[warp][0], warp_ids[warp][0], + MetricValue)) { + warp_scores[warp][0] = score; + warp_ids[warp][0] = vector_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= top_k) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < top_k && + isBetter(warp_scores[warp][left], warp_ids[warp][left], + warp_scores[warp][right], warp_ids[warp][right], + MetricValue)) { + worse_child = right; + } + if (!isBetter(warp_scores[warp][parent], warp_ids[warp][parent], + warp_scores[warp][worse_child], + warp_ids[warp][worse_child], MetricValue)) { + break; + } + const float swap_score = warp_scores[warp][parent]; + const std::uint64_t swap_id = warp_ids[warp][parent]; + warp_scores[warp][parent] = warp_scores[warp][worse_child]; + warp_ids[warp][parent] = warp_ids[warp][worse_child]; + warp_scores[warp][worse_child] = swap_score; + warp_ids[warp][worse_child] = swap_id; + parent = worse_child; + } + } + } + } + __syncthreads(); + + // Heap sort each warp into best-to-worst order. + if (lane == 0) { + for (std::uint32_t heap_size = top_k; heap_size > 1; --heap_size) { + const std::uint32_t last = heap_size - 1; + const float swap_score = warp_scores[warp][0]; + const std::uint64_t swap_id = warp_ids[warp][0]; + warp_scores[warp][0] = warp_scores[warp][last]; + warp_ids[warp][0] = warp_ids[warp][last]; + warp_scores[warp][last] = swap_score; + warp_ids[warp][last] = swap_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= last) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < last && + isBetter(warp_scores[warp][left], warp_ids[warp][left], + warp_scores[warp][right], warp_ids[warp][right], + MetricValue)) { + worse_child = right; + } + if (!isBetter(warp_scores[warp][parent], warp_ids[warp][parent], + warp_scores[warp][worse_child], + warp_ids[warp][worse_child], MetricValue)) { + break; + } + const float parent_score = warp_scores[warp][parent]; + const std::uint64_t parent_id = warp_ids[warp][parent]; + warp_scores[warp][parent] = warp_scores[warp][worse_child]; + warp_ids[warp][parent] = warp_ids[warp][worse_child]; + warp_scores[warp][worse_child] = parent_score; + warp_ids[warp][worse_child] = parent_id; + parent = worse_child; + } + } + warp_ranks[warp] = 0; + } + __syncthreads(); + + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + if (lane == 0) { + const std::uint32_t rank = warp_ranks[warp]; + merge_scores[warp] = warp_scores[warp][rank]; + merge_ids[warp] = warp_ids[warp][rank]; + } + __syncthreads(); + if (thread_id == 0) { + std::uint32_t best_warp = 0; + for (std::uint32_t candidate_warp = 1; candidate_warp < kWarps; + ++candidate_warp) { + if (isBetter(merge_scores[candidate_warp], merge_ids[candidate_warp], + merge_scores[best_warp], merge_ids[best_warp], + MetricValue)) { + best_warp = candidate_warp; + } + } + const std::uint64_t output_offset = + (static_cast(query_id) * gridDim.x + blockIdx.x) * + top_k + + output_rank; + local_scores[output_offset] = merge_scores[best_warp]; + local_ids[output_offset] = merge_ids[best_warp]; + ++warp_ranks[best_warp]; + } + __syncthreads(); + } +} + +// Experimental cross-query tile. A block owns QueryTile queries for the same +// vector chunk, so every database element loaded by a lane is reused for all +// queries in the tile. QueryTile=1 continues to use the established kernel +// above; keeping the paths separate makes the A/B reversible. +template +__global__ void exactFusedQueryTiledTopKKernel( + const InputType* database, const InputType* queries, float* local_scores, + std::uint64_t* local_ids, std::uint64_t num_vectors, std::uint32_t dim, + std::uint32_t batch_count, std::uint32_t top_k, bool cache_queries) { + static_assert(QueryTile == 2 || QueryTile == 4 || QueryTile == 8, + "query tile must be 2, 4, or 8"); + constexpr std::uint32_t kWarpSize = 32; + constexpr std::uint32_t kWarps = 8; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float warp_scores[QueryTile][kWarps][MaximumK]; + __shared__ std::uint64_t warp_ids[QueryTile][kWarps][MaximumK]; + __shared__ float merge_scores[QueryTile][kWarps]; + __shared__ std::uint64_t merge_ids[QueryTile][kWarps]; + __shared__ std::uint32_t warp_ranks[QueryTile][kWarps]; + extern __shared__ __align__(16) unsigned char dynamic_shared[]; + auto* shared_queries = reinterpret_cast(dynamic_shared); + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t lane = thread_id % kWarpSize; + const std::uint32_t warp = thread_id / kWarpSize; + const std::uint32_t query_base = blockIdx.y * QueryTile; + const std::uint32_t remaining_queries = + query_base < batch_count ? batch_count - query_base : 0; + const std::uint32_t query_count = + remaining_queries < QueryTile ? remaining_queries : QueryTile; + const float worst_score = + MetricValue == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + + if (lane == 0) { + for (std::uint32_t query = 0; query < query_count; ++query) { + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + warp_scores[query][warp][rank] = worst_score; + warp_ids[query][warp][rank] = UINT64_MAX; + } + } + } + + const InputType* query_values[QueryTile]; +#pragma unroll + for (std::uint32_t query = 0; query < QueryTile; ++query) { + query_values[query] = + query < query_count + ? queries + static_cast(query_base + query) * dim + : queries; + } + if (cache_queries) { + const std::uint32_t tile_values = query_count * dim; + for (std::uint32_t index = thread_id; index < tile_values; + index += blockDim.x) { + const std::uint32_t query = index / dim; + const std::uint32_t d = index - query * dim; + shared_queries[index] = query_values[query][d]; + } + } + __syncthreads(); + if (cache_queries) { +#pragma unroll + for (std::uint32_t query = 0; query < QueryTile; ++query) { + query_values[query] = shared_queries + query * dim; + } + } + + float query_norm[QueryTile] = {}; + if constexpr (MetricValue == Metric::kCosine) { +#pragma unroll + for (std::uint32_t query = 0; query < QueryTile; ++query) { + if (query < query_count) { + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float value = loadInput(query_values[query], d); + query_norm[query] = fmaf(value, value, query_norm[query]); + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + query_norm[query] += + __shfl_down_sync(0xffffffffU, query_norm[query], offset); + } + } + } + } + + const std::uint64_t first_vector = + static_cast(blockIdx.x) * kWarps + warp; + const std::uint64_t vector_stride = + static_cast(gridDim.x) * kWarps; + for (std::uint64_t vector_id = first_vector; vector_id < num_vectors; + vector_id += vector_stride) { + const std::uint64_t vector_offset = vector_id * dim; + float dot[QueryTile] = {}; + float squared_l2[QueryTile] = {}; + float vector_norm = 0.0F; + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float vector = loadInput(database, vector_offset + d); + if constexpr (MetricValue == Metric::kCosine) { + vector_norm = fmaf(vector, vector, vector_norm); + } +#pragma unroll + for (std::uint32_t query = 0; query < QueryTile; ++query) { + if (query < query_count) { + const float query_value = loadInput(query_values[query], d); + if constexpr (MetricValue == Metric::kL2) { + const float difference = query_value - vector; + squared_l2[query] = + fmaf(difference, difference, squared_l2[query]); + } else { + dot[query] = fmaf(query_value, vector, dot[query]); + } + } + } + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + if constexpr (MetricValue == Metric::kCosine) { + vector_norm += __shfl_down_sync(0xffffffffU, vector_norm, offset); + } +#pragma unroll + for (std::uint32_t query = 0; query < QueryTile; ++query) { + if (query < query_count) { + if constexpr (MetricValue == Metric::kL2) { + squared_l2[query] += __shfl_down_sync( + 0xffffffffU, squared_l2[query], offset); + } else { + dot[query] += + __shfl_down_sync(0xffffffffU, dot[query], offset); + } + } + } + } + if (lane == 0) { +#pragma unroll + for (std::uint32_t query = 0; query < QueryTile; ++query) { + if (query >= query_count) { + continue; + } + float score = dot[query]; + if constexpr (MetricValue == Metric::kL2) { + score = squared_l2[query]; + } else if constexpr (MetricValue == Metric::kCosine) { + score = query_norm[query] == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot[query] * + rsqrtf(query_norm[query] * vector_norm); + } + if (isBetter(score, vector_id, warp_scores[query][warp][0], + warp_ids[query][warp][0], MetricValue)) { + warp_scores[query][warp][0] = score; + warp_ids[query][warp][0] = vector_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= top_k) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < top_k && + isBetter(warp_scores[query][warp][left], + warp_ids[query][warp][left], + warp_scores[query][warp][right], + warp_ids[query][warp][right], MetricValue)) { + worse_child = right; + } + if (!isBetter(warp_scores[query][warp][parent], + warp_ids[query][warp][parent], + warp_scores[query][warp][worse_child], + warp_ids[query][warp][worse_child], MetricValue)) { + break; + } + const float swap_score = warp_scores[query][warp][parent]; + const std::uint64_t swap_id = warp_ids[query][warp][parent]; + warp_scores[query][warp][parent] = + warp_scores[query][warp][worse_child]; + warp_ids[query][warp][parent] = + warp_ids[query][warp][worse_child]; + warp_scores[query][warp][worse_child] = swap_score; + warp_ids[query][warp][worse_child] = swap_id; + parent = worse_child; + } + } + } + } + } + __syncthreads(); + + if (lane == 0) { + for (std::uint32_t query = 0; query < query_count; ++query) { + for (std::uint32_t heap_size = top_k; heap_size > 1; --heap_size) { + const std::uint32_t last = heap_size - 1; + const float swap_score = warp_scores[query][warp][0]; + const std::uint64_t swap_id = warp_ids[query][warp][0]; + warp_scores[query][warp][0] = warp_scores[query][warp][last]; + warp_ids[query][warp][0] = warp_ids[query][warp][last]; + warp_scores[query][warp][last] = swap_score; + warp_ids[query][warp][last] = swap_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= last) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < last && + isBetter(warp_scores[query][warp][left], + warp_ids[query][warp][left], + warp_scores[query][warp][right], + warp_ids[query][warp][right], MetricValue)) { + worse_child = right; + } + if (!isBetter(warp_scores[query][warp][parent], + warp_ids[query][warp][parent], + warp_scores[query][warp][worse_child], + warp_ids[query][warp][worse_child], MetricValue)) { + break; + } + const float parent_score = warp_scores[query][warp][parent]; + const std::uint64_t parent_id = warp_ids[query][warp][parent]; + warp_scores[query][warp][parent] = + warp_scores[query][warp][worse_child]; + warp_ids[query][warp][parent] = warp_ids[query][warp][worse_child]; + warp_scores[query][warp][worse_child] = parent_score; + warp_ids[query][warp][worse_child] = parent_id; + parent = worse_child; + } + } + warp_ranks[query][warp] = 0; + } + } + __syncthreads(); + + for (std::uint32_t query = 0; query < query_count; ++query) { + const std::uint32_t query_id = query_base + query; + for (std::uint32_t output_rank = 0; output_rank < top_k; ++output_rank) { + if (lane == 0) { + const std::uint32_t rank = warp_ranks[query][warp]; + merge_scores[query][warp] = warp_scores[query][warp][rank]; + merge_ids[query][warp] = warp_ids[query][warp][rank]; + } + __syncthreads(); + if (thread_id == 0) { + std::uint32_t best_warp = 0; + for (std::uint32_t candidate_warp = 1; candidate_warp < kWarps; + ++candidate_warp) { + if (isBetter(merge_scores[query][candidate_warp], + merge_ids[query][candidate_warp], + merge_scores[query][best_warp], + merge_ids[query][best_warp], MetricValue)) { + best_warp = candidate_warp; + } + } + const std::uint64_t output_offset = + (static_cast(query_id) * gridDim.x + blockIdx.x) * + top_k + + output_rank; + local_scores[output_offset] = merge_scores[query][best_warp]; + local_ids[output_offset] = merge_ids[query][best_warp]; + ++warp_ranks[query][best_warp]; + } + __syncthreads(); + } + } +} + +// Block-tiled variant: one warp owns one query while all eight query warps +// reuse a shared tile of eight database vectors. This preserves query-level +// parallelism, unlike the warp-query tile above where one warp serially +// accumulates several queries. +template +__global__ void exactFusedBlockTiledTopKKernel( + const InputType* database, const InputType* queries, float* local_scores, + std::uint64_t* local_ids, std::uint64_t num_vectors, std::uint32_t dim, + std::uint32_t batch_count, std::uint32_t top_k) { + constexpr std::uint32_t kWarpSize = 32; + constexpr std::uint32_t kWarps = 8; + constexpr std::uint32_t kQueryTile = 8; + constexpr std::uint32_t kVectorTile = 8; + constexpr float kFloatMaximum = 3.402823466e+38F; + __shared__ float warp_scores[kWarps][MaximumK]; + __shared__ std::uint64_t warp_ids[kWarps][MaximumK]; + __shared__ float shared_vector_norms[kVectorTile]; + extern __shared__ __align__(16) unsigned char dynamic_shared[]; + auto* shared_queries = reinterpret_cast(dynamic_shared); + InputType* shared_database = shared_queries + kQueryTile * dim; + + const std::uint32_t thread_id = threadIdx.x; + const std::uint32_t lane = thread_id % kWarpSize; + const std::uint32_t warp = thread_id / kWarpSize; + const std::uint32_t query_base = blockIdx.y * kQueryTile; + const std::uint32_t remaining_queries = + query_base < batch_count ? batch_count - query_base : 0; + const std::uint32_t query_count = + remaining_queries < kQueryTile ? remaining_queries : kQueryTile; + const bool valid_query = warp < query_count; + const float worst_score = + MetricValue == Metric::kL2 ? kFloatMaximum : -kFloatMaximum; + + if (valid_query && lane == 0) { + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + warp_scores[warp][rank] = worst_score; + warp_ids[warp][rank] = UINT64_MAX; + } + } + + const std::uint32_t query_values = query_count * dim; + for (std::uint32_t index = thread_id; index < query_values; + index += blockDim.x) { + const std::uint32_t query = index / dim; + const std::uint32_t d = index - query * dim; + shared_queries[index] = + queries[static_cast(query_base + query) * dim + d]; + } + __syncthreads(); + + float query_norm = 0.0F; + if constexpr (MetricValue == Metric::kCosine) { + if (valid_query) { + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float query = + loadInput(shared_queries + static_cast(warp) * dim, + d); + query_norm = fmaf(query, query, query_norm); + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + query_norm += __shfl_down_sync(0xffffffffU, query_norm, offset); + } + } + } + + const std::uint64_t first_tile = + static_cast(blockIdx.x) * kVectorTile; + const std::uint64_t tile_stride = + static_cast(gridDim.x) * kVectorTile; + for (std::uint64_t tile_base = first_tile; tile_base < num_vectors; + tile_base += tile_stride) { + const std::uint32_t tile_count = static_cast( + num_vectors - tile_base < kVectorTile ? num_vectors - tile_base + : kVectorTile); + const std::uint32_t database_values = tile_count * dim; + for (std::uint32_t index = thread_id; index < database_values; + index += blockDim.x) { + const std::uint32_t vector = index / dim; + const std::uint32_t d = index - vector * dim; + shared_database[index] = + database[(tile_base + vector) * static_cast(dim) + d]; + } + __syncthreads(); + + if constexpr (MetricValue == Metric::kCosine) { + if (warp < tile_count) { + float vector_norm = 0.0F; + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float vector = loadInput( + shared_database + static_cast(warp) * dim, d); + vector_norm = fmaf(vector, vector, vector_norm); + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { + vector_norm += + __shfl_down_sync(0xffffffffU, vector_norm, offset); + } + if (lane == 0) { + shared_vector_norms[warp] = vector_norm; + } + } + __syncthreads(); + } + + float dot[kVectorTile] = {}; + float squared_l2[kVectorTile] = {}; + if (valid_query) { + const InputType* query_values_ptr = + shared_queries + static_cast(warp) * dim; + for (std::uint32_t d = lane; d < dim; d += kWarpSize) { + const float query = loadInput(query_values_ptr, d); +#pragma unroll + for (std::uint32_t vector = 0; vector < kVectorTile; ++vector) { + if (vector < tile_count) { + const float value = loadInput( + shared_database + static_cast(vector) * dim, d); + if constexpr (MetricValue == Metric::kL2) { + const float difference = query - value; + squared_l2[vector] = + fmaf(difference, difference, squared_l2[vector]); + } else { + dot[vector] = fmaf(query, value, dot[vector]); + } + } + } + } + for (std::uint32_t offset = kWarpSize / 2; offset > 0; offset >>= 1) { +#pragma unroll + for (std::uint32_t vector = 0; vector < kVectorTile; ++vector) { + if (vector < tile_count) { + if constexpr (MetricValue == Metric::kL2) { + squared_l2[vector] += __shfl_down_sync( + 0xffffffffU, squared_l2[vector], offset); + } else { + dot[vector] += + __shfl_down_sync(0xffffffffU, dot[vector], offset); + } + } + } + } + if (lane == 0) { + for (std::uint32_t vector = 0; vector < tile_count; ++vector) { + const std::uint64_t vector_id = tile_base + vector; + float score = dot[vector]; + if constexpr (MetricValue == Metric::kL2) { + score = squared_l2[vector]; + } else if constexpr (MetricValue == Metric::kCosine) { + const float vector_norm = shared_vector_norms[vector]; + score = query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot[vector] * rsqrtf(query_norm * vector_norm); + } + if (isBetter(score, vector_id, warp_scores[warp][0], + warp_ids[warp][0], MetricValue)) { + warp_scores[warp][0] = score; + warp_ids[warp][0] = vector_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= top_k) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < top_k && + isBetter(warp_scores[warp][left], warp_ids[warp][left], + warp_scores[warp][right], warp_ids[warp][right], + MetricValue)) { + worse_child = right; + } + if (!isBetter(warp_scores[warp][parent], warp_ids[warp][parent], + warp_scores[warp][worse_child], + warp_ids[warp][worse_child], MetricValue)) { + break; + } + const float swap_score = warp_scores[warp][parent]; + const std::uint64_t swap_id = warp_ids[warp][parent]; + warp_scores[warp][parent] = warp_scores[warp][worse_child]; + warp_ids[warp][parent] = warp_ids[warp][worse_child]; + warp_scores[warp][worse_child] = swap_score; + warp_ids[warp][worse_child] = swap_id; + parent = worse_child; + } + } + } + } + } + __syncthreads(); + } + + if (valid_query && lane == 0) { + for (std::uint32_t heap_size = top_k; heap_size > 1; --heap_size) { + const std::uint32_t last = heap_size - 1; + const float swap_score = warp_scores[warp][0]; + const std::uint64_t swap_id = warp_ids[warp][0]; + warp_scores[warp][0] = warp_scores[warp][last]; + warp_ids[warp][0] = warp_ids[warp][last]; + warp_scores[warp][last] = swap_score; + warp_ids[warp][last] = swap_id; + std::uint32_t parent = 0; + while (true) { + const std::uint32_t left = parent * 2 + 1; + if (left >= last) { + break; + } + const std::uint32_t right = left + 1; + std::uint32_t worse_child = left; + if (right < last && + isBetter(warp_scores[warp][left], warp_ids[warp][left], + warp_scores[warp][right], warp_ids[warp][right], + MetricValue)) { + worse_child = right; + } + if (!isBetter(warp_scores[warp][parent], warp_ids[warp][parent], + warp_scores[warp][worse_child], + warp_ids[warp][worse_child], MetricValue)) { + break; + } + const float parent_score = warp_scores[warp][parent]; + const std::uint64_t parent_id = warp_ids[warp][parent]; + warp_scores[warp][parent] = warp_scores[warp][worse_child]; + warp_ids[warp][parent] = warp_ids[warp][worse_child]; + warp_scores[warp][worse_child] = parent_score; + warp_ids[warp][worse_child] = parent_id; + parent = worse_child; + } + } + const std::uint32_t query_id = query_base + warp; + const std::uint64_t output_offset = + (static_cast(query_id) * gridDim.x + blockIdx.x) * + top_k; + for (std::uint32_t rank = 0; rank < top_k; ++rank) { + local_scores[output_offset + rank] = warp_scores[warp][rank]; + local_ids[output_offset + rank] = warp_ids[warp][rank]; + } + } +} + +namespace { + +void checkCuda(cudaError_t status, const char* operation) { + if (status != cudaSuccess) { + throw std::runtime_error(std::string(operation) + ": " + + cudaGetErrorString(status)); + } +} + +class DeviceBuffer { + public: + explicit DeviceBuffer(std::size_t bytes) { + checkCuda(cudaMalloc(&data_, bytes), "cudaMalloc"); + } + + ~DeviceBuffer() { + if (data_ != nullptr) { + cudaFree(data_); + } + } + + DeviceBuffer(const DeviceBuffer&) = delete; + DeviceBuffer& operator=(const DeviceBuffer&) = delete; + + void* data() { return data_; } + + private: + void* data_ = nullptr; +}; + +class CudaEvent { + public: + CudaEvent() { checkCuda(cudaEventCreate(&event_), "cudaEventCreate"); } + ~CudaEvent() { cudaEventDestroy(event_); } + + CudaEvent(const CudaEvent&) = delete; + CudaEvent& operator=(const CudaEvent&) = delete; + + void record() { checkCuda(cudaEventRecord(event_), "cudaEventRecord"); } + void synchronize() { + checkCuda(cudaEventSynchronize(event_), "cudaEventSynchronize"); + } + cudaEvent_t get() const { return event_; } + + private: + cudaEvent_t event_{}; +}; + +double elapsedMilliseconds(const CudaEvent& start, const CudaEvent& end) { + float milliseconds = 0.0F; + checkCuda(cudaEventElapsedTime(&milliseconds, start.get(), end.get()), + "cudaEventElapsedTime"); + return milliseconds; +} + +template +void launchExactFusedWarpTopK(dim3 grid, const InputType* database, + const InputType* queries, float* local_scores, + std::uint64_t* local_ids, + std::uint64_t num_vectors, std::uint32_t dim, + std::uint32_t top_k, Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr std::size_t kMaximumCachedQueryBytes = 8192; + const std::size_t query_bytes = + static_cast(dim) * sizeof(InputType); + const bool cache_query = query_bytes <= kMaximumCachedQueryBytes; + const std::size_t shared_bytes = cache_query ? query_bytes : 0; + if (metric == Metric::kL2) { + exactFusedWarpTopKKernel + <<>>(database, queries, local_scores, + local_ids, num_vectors, dim, top_k, + cache_query); + } else if (metric == Metric::kInnerProduct) { + exactFusedWarpTopKKernel + <<>>(database, queries, local_scores, + local_ids, num_vectors, dim, top_k, + cache_query); + } else { + exactFusedWarpTopKKernel + <<>>(database, queries, local_scores, + local_ids, num_vectors, dim, top_k, + cache_query); + } +} + +template +void launchExactFusedQueryTiledTopK( + dim3 grid, const InputType* database, const InputType* queries, + float* local_scores, std::uint64_t* local_ids, std::uint64_t num_vectors, + std::uint32_t dim, std::uint32_t batch_count, std::uint32_t top_k, + Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr std::size_t kMaximumCachedTileBytes = 8192; + const std::size_t tile_bytes = static_cast(QueryTile) * dim * + sizeof(InputType); + const bool cache_queries = tile_bytes <= kMaximumCachedTileBytes; + const std::size_t shared_bytes = cache_queries ? tile_bytes : 0; + if (metric == Metric::kL2) { + exactFusedQueryTiledTopKKernel + <<>>( + database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, cache_queries); + } else if (metric == Metric::kInnerProduct) { + exactFusedQueryTiledTopKKernel + <<>>( + database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, cache_queries); + } else { + exactFusedQueryTiledTopKKernel + <<>>( + database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, cache_queries); + } +} + +template +void launchExactFusedBlockTiledTopK( + dim3 grid, const InputType* database, const InputType* queries, + float* local_scores, std::uint64_t* local_ids, std::uint64_t num_vectors, + std::uint32_t dim, std::uint32_t batch_count, std::uint32_t top_k, + Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr std::uint32_t kQueryTile = 8; + constexpr std::uint32_t kVectorTile = 8; + const std::size_t shared_bytes = + static_cast(kQueryTile + kVectorTile) * dim * + sizeof(InputType); + if (metric == Metric::kL2) { + exactFusedBlockTiledTopKKernel + <<>>( + database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k); + } else if (metric == Metric::kInnerProduct) { + exactFusedBlockTiledTopKKernel + <<>>( + database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k); + } else { + exactFusedBlockTiledTopKKernel + <<>>( + database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k); + } +} + +template +void launchExactFusedWarpTopKWithQueryTile( + dim3 grid, const InputType* database, const InputType* queries, + float* local_scores, std::uint64_t* local_ids, std::uint64_t num_vectors, + std::uint32_t dim, std::uint32_t batch_count, std::uint32_t top_k, + std::uint32_t query_tile, bool block_tiled, Metric metric) { + if (block_tiled) { + if constexpr (MaximumK <= 10) { + launchExactFusedBlockTiledTopK( + grid, database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, metric); + } else { + throw std::runtime_error( + "block_tile cannot be instantiated for MaximumK > 10"); + } + return; + } + if (query_tile == 1) { + launchExactFusedWarpTopK( + grid, database, queries, local_scores, local_ids, num_vectors, dim, + top_k, metric); + } else if (query_tile == 2) { + launchExactFusedQueryTiledTopK( + grid, database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, metric); + } else if (query_tile == 4) { + launchExactFusedQueryTiledTopK( + grid, database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, metric); + } else { + if constexpr (MaximumK <= 10) { + launchExactFusedQueryTiledTopK( + grid, database, queries, local_scores, local_ids, num_vectors, dim, + batch_count, top_k, metric); + } else { + throw std::runtime_error( + "exact_query_tile=8 cannot be instantiated for MaximumK > 10"); + } + } +} + +template +void launchExactFusedDistanceOnly(dim3 grid, const InputType* database, + const InputType* queries, + float* warp_checksums, + std::uint64_t num_vectors, + std::uint32_t dim, Metric metric) { + constexpr std::uint32_t kThreads = 256; + constexpr std::size_t kMaximumCachedQueryBytes = 8192; + const std::size_t query_bytes = + static_cast(dim) * sizeof(InputType); + const bool cache_query = query_bytes <= kMaximumCachedQueryBytes; + const std::size_t shared_bytes = cache_query ? query_bytes : 0; + if (metric == Metric::kL2) { + exactFusedDistanceOnlyKernel + <<>>(database, queries, warp_checksums, + num_vectors, dim, cache_query); + } else if (metric == Metric::kInnerProduct) { + exactFusedDistanceOnlyKernel + <<>>(database, queries, warp_checksums, + num_vectors, dim, cache_query); + } else { + exactFusedDistanceOnlyKernel + <<>>(database, queries, warp_checksums, + num_vectors, dim, cache_query); + } +} + +} // namespace + +struct GpuExactSearchEngine::Impl { + explicit Impl(const VectorDatabase& database, const QuerySet& queries, + const SearchParams& search_params) + : num_vectors(database.num_vectors), + dim(database.dim), + dtype(database.dtype), + metric(database.metric), + params(search_params), + fused_topk(search_params.topk_mode == "fused"), + use_fp16(database.dtype == DataType::kFloat16), + input_element_bytes(use_fp16 ? sizeof(std::uint16_t) : sizeof(float)), + batch_capacity(search_params.batch_size) { + validateInputs(database, queries, params); + constexpr std::uint32_t kThreads = 256; + const std::size_t database_value_count = + static_cast(num_vectors) * dim; + const std::size_t database_bytes = + database_value_count * input_element_bytes; + const std::size_t query_bytes = + static_cast(batch_capacity) * dim * input_element_bytes; + const std::size_t score_bytes = + fused_topk ? 0 + : static_cast(batch_capacity) * num_vectors * + sizeof(float); + const std::size_t result_count = + static_cast(batch_capacity) * params.top_k; + const std::uint32_t required_fused_blocks = + static_cast((num_vectors + 8 - 1) / 8); + // Keep enough query/chunk blocks in flight to occupy the GPU, without + // producing 256*K candidates per query for large batches. + // Query tiling reduces grid.y. Scale grid.x by the same factor so the + // experiment keeps roughly the established 1024 resident/work blocks and + // does not confuse data reuse with a simple loss of parallelism. + const std::uint32_t target_blocks = 1024U * params.exact_query_tile; + const std::uint32_t occupancy_blocks_per_query = std::max( + 1, (target_blocks + batch_capacity - 1) / batch_capacity); + const std::uint32_t selected_fused_blocks = + params.exact_fused_blocks == 0 ? occupancy_blocks_per_query + : params.exact_fused_blocks; + fused_blocks_x = + std::min(required_fused_blocks, selected_fused_blocks); + const std::uint32_t local_blocks = fused_topk ? fused_blocks_x : kThreads; + const std::size_t local_candidate_count = + uses_local_candidates ? result_count * local_blocks : 0; + device_bytes = + database_bytes + query_bytes + score_bytes + + result_count * (sizeof(float) + sizeof(std::uint64_t)) + + local_candidate_count * (sizeof(float) + sizeof(std::uint64_t)); + + device_database = std::make_unique(database_bytes); + device_queries = std::make_unique(query_bytes); + if (!fused_topk) { + device_scores = std::make_unique(score_bytes); + } + device_top_scores = + std::make_unique(result_count * sizeof(float)); + device_top_ids = + std::make_unique(result_count * sizeof(std::uint64_t)); + if (uses_local_candidates) { + device_local_scores = + std::make_unique(local_candidate_count * sizeof(float)); + device_local_ids = std::make_unique(local_candidate_count * + sizeof(std::uint64_t)); + } + + CudaEvent database_copy_start; + CudaEvent database_copy_end; + database_copy_start.record(); + const void* database_data = + use_fp16 ? static_cast(database.half_values.data()) + : static_cast(database.values.data()); + checkCuda(cudaMemcpy(device_database->data(), database_data, database_bytes, + cudaMemcpyHostToDevice), + "复制向量库到 GPU"); + database_copy_end.record(); + database_copy_end.synchronize(); + database_h2d_ms = + elapsedMilliseconds(database_copy_start, database_copy_end); + } + + std::uint64_t num_vectors; + std::uint32_t dim; + DataType dtype; + Metric metric; + SearchParams params; + bool fused_topk; + bool uses_local_candidates = + params.topk_mode == "two_stage" || params.topk_mode == "fused"; + bool use_fp16; + std::size_t input_element_bytes; + std::uint32_t batch_capacity; + std::uint32_t fused_blocks_x = 0; + double database_h2d_ms = 0.0; + std::size_t device_bytes = 0; + std::unique_ptr device_database; + std::unique_ptr device_queries; + std::unique_ptr device_scores; + std::unique_ptr device_top_scores; + std::unique_ptr device_top_ids; + std::unique_ptr device_local_scores; + std::unique_ptr device_local_ids; +}; + +GpuExactSearchEngine::GpuExactSearchEngine(const VectorDatabase& database, + const QuerySet& initial_queries, + const SearchParams& params) + : impl_(std::make_unique(database, initial_queries, params)) {} + +GpuExactSearchEngine::~GpuExactSearchEngine() = default; +GpuExactSearchEngine::GpuExactSearchEngine(GpuExactSearchEngine&&) noexcept = + default; +GpuExactSearchEngine& GpuExactSearchEngine::operator=( + GpuExactSearchEngine&&) noexcept = default; + +double GpuExactSearchEngine::databaseH2DMilliseconds() const { + return impl_->database_h2d_ms; +} + +std::size_t GpuExactSearchEngine::deviceBytes() const { + return impl_->device_bytes; +} + +double GpuExactSearchEngine::profileDistanceOnlyMilliseconds( + const QuerySet& queries, std::uint32_t warmup, std::uint32_t repeat) { + if (!impl_->fused_topk) { + throw std::runtime_error("distance-only 差分剖析只支持 fused Exact 路径"); + } + if (repeat == 0) { + throw std::runtime_error("distance-only 剖析 repeat 必须大于 0"); + } + if (impl_->params.exact_query_tile != 1) { + throw std::runtime_error( + "distance-only 差分剖析当前只支持 exact_query_tile=1"); + } + if (impl_->params.exact_fused_layout != "warp_query") { + throw std::runtime_error( + "distance-only 差分剖析当前只支持 warp_query layout"); + } + if (queries.num_queries == 0 || queries.dim != impl_->dim || + queries.dtype != impl_->dtype) { + throw std::runtime_error("剖析查询集与 GPU 常驻引擎不匹配"); + } + const std::uint64_t expected_query_values = queries.num_queries * queries.dim; + if ((impl_->use_fp16 && + queries.half_values.size() != expected_query_values) || + (!impl_->use_fp16 && queries.values.size() != expected_query_values)) { + throw std::runtime_error("剖析查询数据长度与元数据不一致"); + } + + constexpr std::uint32_t kWarps = 8; + const std::size_t checksum_count = + static_cast(impl_->batch_capacity) * impl_->fused_blocks_x * + kWarps; + DeviceBuffer device_checksums(checksum_count * sizeof(float)); + CudaEvent kernel_start; + CudaEvent kernel_end; + + const auto run_once = [&](bool measure) { + double milliseconds = 0.0; + for (std::uint64_t batch_start = 0; batch_start < queries.num_queries; + batch_start += impl_->batch_capacity) { + const std::uint32_t batch_count = + static_cast(std::min( + impl_->batch_capacity, queries.num_queries - batch_start)); + const std::size_t query_value_offset = + static_cast(batch_start) * queries.dim; + const std::size_t current_query_bytes = + static_cast(batch_count) * queries.dim * + impl_->input_element_bytes; + const void* query_data = + impl_->use_fp16 + ? static_cast(queries.half_values.data() + + query_value_offset) + : static_cast(queries.values.data() + + query_value_offset); + checkCuda(cudaMemcpy(impl_->device_queries->data(), query_data, + current_query_bytes, cudaMemcpyHostToDevice), + "复制剖析查询到 GPU"); + + const dim3 grid(impl_->fused_blocks_x, batch_count); + kernel_start.record(); + if (impl_->use_fp16) { + launchExactFusedDistanceOnly( + grid, static_cast(impl_->device_database->data()), + static_cast(impl_->device_queries->data()), + static_cast(device_checksums.data()), impl_->num_vectors, + impl_->dim, impl_->metric); + } else { + launchExactFusedDistanceOnly( + grid, static_cast(impl_->device_database->data()), + static_cast(impl_->device_queries->data()), + static_cast(device_checksums.data()), impl_->num_vectors, + impl_->dim, impl_->metric); + } + checkCuda(cudaGetLastError(), "启动 exactFusedDistanceOnlyKernel"); + kernel_end.record(); + kernel_end.synchronize(); + if (measure) { + milliseconds += elapsedMilliseconds(kernel_start, kernel_end); + } + } + return milliseconds; + }; + + for (std::uint32_t run = 0; run < warmup; ++run) { + (void)run_once(false); + } + double total_ms = 0.0; + for (std::uint32_t run = 0; run < repeat; ++run) { + total_ms += run_once(true); + } + return total_ms / repeat; +} + +SearchResults GpuExactSearchEngine::search(const QuerySet& queries, + SearchStats* stats) { + if (queries.num_queries == 0 || queries.dim != impl_->dim || + queries.dtype != impl_->dtype) { + throw std::runtime_error("查询集与 GPU 常驻引擎的维度或 dtype 不匹配"); + } + const std::uint64_t expected_query_values = queries.num_queries * queries.dim; + if ((impl_->use_fp16 && + queries.half_values.size() != expected_query_values) || + (!impl_->use_fp16 && queries.values.size() != expected_query_values)) { + throw std::runtime_error("查询数据长度与元数据不一致"); + } + + SearchStats measured_stats; + const SearchParams& params = impl_->params; + const bool use_fp16 = impl_->use_fp16; + const std::size_t input_element_bytes = impl_->input_element_bytes; + const std::uint32_t batch_capacity = impl_->batch_capacity; + const std::uint64_t num_vectors = impl_->num_vectors; + const std::uint32_t dim = impl_->dim; + const Metric metric = impl_->metric; + DeviceBuffer& device_database = *impl_->device_database; + DeviceBuffer& device_queries = *impl_->device_queries; + DeviceBuffer* device_scores = impl_->device_scores.get(); + DeviceBuffer& device_top_scores = *impl_->device_top_scores; + DeviceBuffer& device_top_ids = *impl_->device_top_ids; + DeviceBuffer* device_local_scores = impl_->device_local_scores.get(); + DeviceBuffer* device_local_ids = impl_->device_local_ids.get(); + constexpr std::uint32_t kThreads = 256; + + SearchResults results(queries.num_queries); + std::vector host_top_scores(static_cast(batch_capacity) * + params.top_k); + std::vector host_top_ids( + static_cast(batch_capacity) * params.top_k); + const std::uint32_t simple_blocks_x = + static_cast((num_vectors + kThreads - 1) / kThreads); + constexpr std::uint32_t kWarpsPerBlock = kThreads / 32; + const std::uint32_t required_warp_blocks = static_cast( + (num_vectors + kWarpsPerBlock - 1) / kWarpsPerBlock); + const std::uint32_t warp_blocks_x = + std::min(required_warp_blocks, 4096); + const std::uint32_t fused_blocks_x = impl_->fused_blocks_x; + const std::uint32_t exact_query_tile = params.exact_query_tile; + const bool block_tiled = params.exact_fused_layout == "block_tile"; + + CudaEvent query_copy_start; + CudaEvent query_copy_end; + CudaEvent distance_end; + CudaEvent topk_end; + CudaEvent result_copy_end; + + for (std::uint64_t batch_start = 0; batch_start < queries.num_queries; + batch_start += batch_capacity) { + const std::uint32_t batch_count = + static_cast(std::min( + batch_capacity, queries.num_queries - batch_start)); + const std::size_t current_query_bytes = + static_cast(batch_count) * queries.dim * + input_element_bytes; + const std::size_t query_value_offset = + static_cast(batch_start) * queries.dim; + const void* query_data = + use_fp16 ? static_cast(queries.half_values.data() + + query_value_offset) + : static_cast(queries.values.data() + + query_value_offset); + query_copy_start.record(); + checkCuda(cudaMemcpy(device_queries.data(), query_data, current_query_bytes, + cudaMemcpyHostToDevice), + "复制查询到 GPU"); + query_copy_end.record(); + + if (params.topk_mode == "fused") { + const dim3 grid(fused_blocks_x, + (batch_count + exact_query_tile - 1) / + exact_query_tile); + if (use_fp16) { + const auto* database_values = + static_cast(device_database.data()); + const auto* query_values = + static_cast(device_queries.data()); + if (params.top_k <= 10) { + launchExactFusedWarpTopKWithQueryTile<__half, 10>( + grid, database_values, query_values, + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, dim, batch_count, params.top_k, exact_query_tile, + block_tiled, metric); + } else if (params.top_k <= 50) { + launchExactFusedWarpTopKWithQueryTile<__half, 50>( + grid, database_values, query_values, + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, dim, batch_count, params.top_k, exact_query_tile, + block_tiled, metric); + } else { + launchExactFusedWarpTopKWithQueryTile<__half, 100>( + grid, database_values, query_values, + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, dim, batch_count, params.top_k, exact_query_tile, + block_tiled, metric); + } + } else { + const auto* database_values = + static_cast(device_database.data()); + const auto* query_values = + static_cast(device_queries.data()); + if (params.top_k <= 10) { + launchExactFusedWarpTopKWithQueryTile( + grid, database_values, query_values, + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, dim, batch_count, params.top_k, exact_query_tile, + block_tiled, metric); + } else if (params.top_k <= 50) { + launchExactFusedWarpTopKWithQueryTile( + grid, database_values, query_values, + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, dim, batch_count, params.top_k, exact_query_tile, + block_tiled, metric); + } else { + launchExactFusedWarpTopKWithQueryTile( + grid, database_values, query_values, + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, dim, batch_count, params.top_k, exact_query_tile, + block_tiled, metric); + } + } + checkCuda(cudaGetLastError(), "启动 exactFusedWarpTopKKernel"); + distance_end.record(); + const std::uint64_t candidates_per_query = + static_cast(fused_blocks_x) * params.top_k; + blockTopKKernel<<>>( + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + static_cast(device_top_scores.data()), + static_cast(device_top_ids.data()), + candidates_per_query, params.top_k, metric); + checkCuda(cudaGetLastError(), "启动 fused exact 最终归并"); + } else { + if (params.distance_mode == "simple") { + const dim3 grid(simple_blocks_x, batch_count); + if (use_fp16) { + exactDistanceKernel<<>>( + static_cast(device_database.data()), + static_cast(device_queries.data()), + static_cast(device_scores->data()), num_vectors, dim, + batch_count, metric); + } else { + exactDistanceKernel<<>>( + static_cast(device_database.data()), + static_cast(device_queries.data()), + static_cast(device_scores->data()), num_vectors, dim, + batch_count, metric); + } + checkCuda(cudaGetLastError(), "启动 exactDistanceKernel"); + } else { + const dim3 grid(warp_blocks_x, batch_count); + if (use_fp16) { + exactDistanceWarpKernel<<>>( + static_cast(device_database.data()), + static_cast(device_queries.data()), + static_cast(device_scores->data()), num_vectors, dim, + batch_count, metric); + } else { + exactDistanceWarpKernel<<>>( + static_cast(device_database.data()), + static_cast(device_queries.data()), + static_cast(device_scores->data()), num_vectors, dim, + batch_count, metric); + } + checkCuda(cudaGetLastError(), "启动 exactDistanceWarpKernel"); + } + distance_end.record(); + + if (params.topk_mode == "simple") { + simpleTopKKernel<<>>( + static_cast(device_scores->data()), + static_cast(device_top_scores.data()), + static_cast(device_top_ids.data()), num_vectors, + params.top_k, metric); + checkCuda(cudaGetLastError(), "启动 simpleTopKKernel"); + } else if (params.topk_mode == "block") { + blockTopKKernel<<>>( + static_cast(device_scores->data()), nullptr, + static_cast(device_top_scores.data()), + static_cast(device_top_ids.data()), num_vectors, + params.top_k, metric); + checkCuda(cudaGetLastError(), "启动 blockTopKKernel"); + } else { + if (params.top_k == 1) { + localTopKCandidatesFixedKernel<1><<>>( + static_cast(device_scores->data()), + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, metric); + } else if (params.top_k == 10) { + localTopKCandidatesFixedKernel<10><<>>( + static_cast(device_scores->data()), + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, metric); + } else { + localTopKCandidatesKernel<<>>( + static_cast(device_scores->data()), + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + num_vectors, params.top_k, metric); + } + checkCuda(cudaGetLastError(), "启动 localTopKCandidatesKernel"); + + const std::uint64_t candidates_per_query = + static_cast(kThreads) * params.top_k; + blockTopKKernel<<>>( + static_cast(device_local_scores->data()), + static_cast(device_local_ids->data()), + static_cast(device_top_scores.data()), + static_cast(device_top_ids.data()), + candidates_per_query, params.top_k, metric); + checkCuda(cudaGetLastError(), "启动两阶段归并 blockTopKKernel"); + } + } + topk_end.record(); + + const std::size_t result_count = + static_cast(batch_count) * params.top_k; + checkCuda(cudaMemcpy(host_top_scores.data(), device_top_scores.data(), + result_count * sizeof(float), cudaMemcpyDeviceToHost), + "复制 Top-K 分数到 CPU"); + checkCuda(cudaMemcpy(host_top_ids.data(), device_top_ids.data(), + result_count * sizeof(std::uint64_t), + cudaMemcpyDeviceToHost), + "复制 Top-K ID 到 CPU"); + result_copy_end.record(); + result_copy_end.synchronize(); + + measured_stats.query_h2d_ms += + elapsedMilliseconds(query_copy_start, query_copy_end); + measured_stats.distance_kernel_ms += + elapsedMilliseconds(query_copy_end, distance_end); + measured_stats.topk_kernel_ms += + elapsedMilliseconds(distance_end, topk_end); + measured_stats.result_d2h_ms += + elapsedMilliseconds(topk_end, result_copy_end); + measured_stats.batch_latency_ms.push_back( + elapsedMilliseconds(query_copy_start, result_copy_end)); + + for (std::uint32_t query_in_batch = 0; query_in_batch < batch_count; + ++query_in_batch) { + std::vector& query_results = + results[batch_start + query_in_batch]; + query_results.resize(params.top_k); + const std::size_t offset = + static_cast(query_in_batch) * params.top_k; + for (std::uint32_t rank = 0; rank < params.top_k; ++rank) { + query_results[rank] = {host_top_ids[offset + rank], + host_top_scores[offset + rank]}; + } + } + } + if (stats != nullptr) { + *stats = measured_stats; + } + return results; +} + +SearchResults gpuExactSearch(const VectorDatabase& database, + const QuerySet& queries, + const SearchParams& params, SearchStats* stats) { + GpuExactSearchEngine engine(database, queries, params); + SearchResults results = engine.search(queries, stats); + if (stats != nullptr) { + stats->database_h2d_ms = engine.databaseH2DMilliseconds(); + } + return results; +} diff --git a/09_vector_retrieval/PurplePulse/src/ivf_flat.cpp b/09_vector_retrieval/PurplePulse/src/ivf_flat.cpp new file mode 100644 index 00000000..e1868607 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/ivf_flat.cpp @@ -0,0 +1,722 @@ +#include "ivf_flat.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" + +namespace { + +constexpr std::array kIvfMagic = {'P', 'P', 'I', 'V', + 'F', '0', '0', '1'}; +constexpr std::uint64_t kHeaderBytes = 8 + 8 + 4 + 4 + 4 + 4; + +template +void writeValue(std::ofstream& output, const T& value) { + output.write(reinterpret_cast(&value), sizeof(T)); +} + +template +T readValue(std::ifstream& input, const char* field_name) { + T value{}; + input.read(reinterpret_cast(&value), sizeof(T)); + if (!input) { + throw std::runtime_error(std::string("读取 IVF 字段失败: ") + field_name); + } + return value; +} + +float halfToFloat(std::uint16_t bits) { + const bool negative = (bits & 0x8000U) != 0; + const std::uint32_t exponent = (bits >> 10U) & 0x1fU; + const std::uint32_t mantissa = bits & 0x03ffU; + float value = 0.0F; + if (exponent == 0) { + value = std::ldexp(static_cast(mantissa), -24); + } else if (exponent == 31) { + value = mantissa == 0 ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + } else { + value = std::ldexp(static_cast(1024U + mantissa), + static_cast(exponent) - 25); + } + return negative ? -value : value; +} + +float databaseValue(const VectorDatabase& database, std::uint64_t index) { + return database.dtype == DataType::kFloat32 + ? database.values[index] + : halfToFloat(database.half_values[index]); +} + +float indexValue(const IvfFlatIndex& index, std::uint64_t index_position) { + return index.dtype == DataType::kFloat32 + ? index.values[index_position] + : halfToFloat(index.half_values[index_position]); +} + +float queryValue(const QuerySet& queries, std::uint64_t index) { + return queries.dtype == DataType::kFloat32 + ? queries.values[index] + : halfToFloat(queries.half_values[index]); +} + +bool isBetter(float left_score, std::uint64_t left_id, float right_score, + std::uint64_t right_id, Metric metric) { + if (left_score == right_score) { + return left_id < right_id; + } + return metric == Metric::kL2 ? left_score < right_score + : left_score > right_score; +} + +float centerScore(const float* vector, const float* center, std::uint32_t dim, + Metric metric) { + float dot = 0.0F; + float vector_norm = 0.0F; + float center_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + if (metric == Metric::kL2) { + const float difference = vector[d] - center[d]; + squared_l2 = std::fma(difference, difference, squared_l2); + } else { + dot = std::fma(vector[d], center[d], dot); + if (metric == Metric::kCosine) { + vector_norm = std::fma(vector[d], vector[d], vector_norm); + center_norm = std::fma(center[d], center[d], center_norm); + } + } + } + if (metric == Metric::kL2) { + return squared_l2; + } + if (metric == Metric::kInnerProduct) { + return dot; + } + return vector_norm == 0.0F || center_norm == 0.0F + ? 0.0F + : dot / std::sqrt(vector_norm * center_norm); +} + +std::uint32_t nearestCenter(const float* vector, + const std::vector& centers, + std::uint32_t nlist, std::uint32_t dim, + Metric metric) { + std::uint32_t best = 0; + float best_score = centerScore(vector, centers.data(), dim, metric); + for (std::uint32_t center_id = 1; center_id < nlist; ++center_id) { + const float score = centerScore( + vector, centers.data() + static_cast(center_id) * dim, + dim, metric); + if (isBetter(score, center_id, best_score, best, metric)) { + best = center_id; + best_score = score; + } + } + return best; +} + +void normalize(float* vector, std::uint32_t dim) { + float squared_norm = 0.0F; + for (std::uint32_t d = 0; d < dim; ++d) { + squared_norm = std::fma(vector[d], vector[d], squared_norm); + } + if (squared_norm == 0.0F) { + return; + } + const float inverse_norm = 1.0F / std::sqrt(squared_norm); + for (std::uint32_t d = 0; d < dim; ++d) { + vector[d] *= inverse_norm; + } +} + +std::uint64_t checkedMultiply(std::uint64_t left, std::uint64_t right, + const char* description) { + if (right != 0 && left > UINT64_MAX / right) { + throw std::runtime_error(std::string(description) + " 大小溢出"); + } + return left * right; +} + +template +void parallelFor(std::uint64_t count, std::uint32_t requested_threads, + Function function) { + const std::uint32_t threads = static_cast( + std::min(count, requested_threads)); + if (threads <= 1) { + function(0, 0, count); + return; + } + std::vector workers; + workers.reserve(threads - 1); + for (std::uint32_t worker = 1; worker < threads; ++worker) { + const std::uint64_t begin = count * worker / threads; + const std::uint64_t end = count * (worker + 1) / threads; + workers.emplace_back(function, worker, begin, end); + } + function(0, 0, count / threads); + for (std::thread& worker : workers) { + worker.join(); + } +} + +float candidateScore(const IvfFlatIndex& index, const QuerySet& queries, + std::uint64_t query_id, std::uint64_t position) { + float dot = 0.0F; + float query_norm = 0.0F; + float vector_norm = 0.0F; + float squared_l2 = 0.0F; + for (std::uint32_t d = 0; d < index.dim; ++d) { + const float query = queryValue(queries, query_id * index.dim + d); + const float vector = indexValue(index, position * index.dim + d); + if (index.metric == Metric::kL2) { + const float difference = query - vector; + squared_l2 = std::fma(difference, difference, squared_l2); + } else { + dot = std::fma(query, vector, dot); + if (index.metric == Metric::kCosine) { + query_norm = std::fma(query, query, query_norm); + vector_norm = std::fma(vector, vector, vector_norm); + } + } + } + if (index.metric == Metric::kL2) { + return squared_l2; + } + if (index.metric == Metric::kInnerProduct) { + return dot; + } + return query_norm == 0.0F || vector_norm == 0.0F + ? 0.0F + : dot / std::sqrt(query_norm * vector_norm); +} + +bool memoryCandidateMatches(const MemoryMetadata& metadata, + std::uint64_t vector_id, + const SearchParams& params) { + return metadata.timestamps[vector_id] >= params.filter_min_timestamp && + (params.filter_session_id == UINT32_MAX || + metadata.session_ids[vector_id] == params.filter_session_id) && + (params.filter_source_type == UINT32_MAX || + metadata.source_types[vector_id] == params.filter_source_type); +} + +float applyMemoryScore(float semantic_score, std::uint64_t vector_id, + Metric metric, const MemoryMetadata& metadata, + const SearchParams& params) { + float recency = 0.0F; + if (params.memory_recency_weight != 0.0F && params.memory_now != 0) { + const std::uint64_t timestamp = metadata.timestamps[vector_id]; + const double age = timestamp >= params.memory_now + ? 0.0 + : static_cast(params.memory_now - timestamp); + recency = static_cast( + std::exp(-age / static_cast(params.memory_time_scale))); + } + const float boost = + params.memory_importance_weight * metadata.importance[vector_id] + + params.memory_recency_weight * recency; + const float weighted_semantic = + params.memory_semantic_weight * semantic_score; + return metric == Metric::kL2 ? weighted_semantic - boost + : weighted_semantic + boost; +} + +void validateMemorySearch(const IvfFlatIndex& index, const SearchParams& params, + const MemoryMetadata* metadata) { + if (params.memory_mode != "disabled" && params.memory_mode != "fused" && + params.memory_mode != "rerank") { + throw std::runtime_error("memory_mode 必须是 disabled、fused 或 rerank"); + } + if (params.memory_mode == "disabled") { + return; + } + if (metadata == nullptr) { + throw std::runtime_error("启用记忆检索时必须提供元数据"); + } + validateMemoryMetadata(*metadata, index.num_vectors); + if (!std::isfinite(params.memory_semantic_weight) || + params.memory_semantic_weight <= 0.0F || + !std::isfinite(params.memory_importance_weight) || + params.memory_importance_weight < 0.0F || + !std::isfinite(params.memory_recency_weight) || + params.memory_recency_weight < 0.0F || + !std::isfinite(params.memory_time_scale) || + params.memory_time_scale <= 0.0F || params.memory_rerank_factor == 0) { + throw std::runtime_error("记忆评分参数不合法"); + } +} + +} // namespace + +IvfFlatIndex buildIvfFlatIndex(const VectorDatabase& database, + std::uint32_t nlist, std::uint32_t iterations, + std::uint64_t max_training_vectors, + std::uint32_t num_threads) { + if (database.num_vectors == 0 || database.dim == 0) { + throw std::runtime_error("IVF 建库输入不能为空"); + } + if (nlist == 0 || nlist > database.num_vectors) { + throw std::runtime_error("nlist 必须位于 [1, num_vectors]"); + } + if (iterations == 0 || max_training_vectors == 0 || num_threads == 0) { + throw std::runtime_error("IVF 训练迭代数、采样数和线程数必须大于 0"); + } + const std::uint64_t value_count = + checkedMultiply(database.num_vectors, database.dim, "向量库"); + if ((database.dtype == DataType::kFloat32 && + database.values.size() != value_count) || + (database.dtype == DataType::kFloat16 && + database.half_values.size() != value_count)) { + throw std::runtime_error("IVF 建库数据长度与元数据不一致"); + } + + const std::uint64_t sample_count = std::min( + database.num_vectors, + std::max(nlist, max_training_vectors)); + std::vector samples(sample_count * database.dim); + for (std::uint64_t sample_id = 0; sample_id < sample_count; ++sample_id) { + const std::uint64_t vector_id = + sample_id * database.num_vectors / sample_count; + for (std::uint32_t d = 0; d < database.dim; ++d) { + samples[sample_id * database.dim + d] = + databaseValue(database, vector_id * database.dim + d); + } + } + + std::vector centers(static_cast(nlist) * database.dim); + for (std::uint32_t center_id = 0; center_id < nlist; ++center_id) { + const std::uint64_t sample_id = + static_cast(center_id) * sample_count / nlist; + std::copy_n( + samples.data() + sample_id * database.dim, database.dim, + centers.data() + static_cast(center_id) * database.dim); + if (database.metric != Metric::kL2) { + normalize( + centers.data() + static_cast(center_id) * database.dim, + database.dim); + } + } + + std::vector sums(centers.size()); + std::vector counts(nlist); + const std::uint32_t training_threads = static_cast( + std::min(num_threads, sample_count)); + std::vector partial_sums( + static_cast(training_threads) * centers.size()); + std::vector partial_counts( + static_cast(training_threads) * nlist); + for (std::uint32_t iteration = 0; iteration < iterations; ++iteration) { + std::fill(sums.begin(), sums.end(), 0.0F); + std::fill(counts.begin(), counts.end(), 0); + std::fill(partial_sums.begin(), partial_sums.end(), 0.0F); + std::fill(partial_counts.begin(), partial_counts.end(), 0); + parallelFor(sample_count, training_threads, + [&](std::uint32_t worker, std::uint64_t begin, + std::uint64_t end) { + float* worker_sums = + partial_sums.data() + + static_cast(worker) * centers.size(); + std::uint64_t* worker_counts = + partial_counts.data() + static_cast(worker) * nlist; + for (std::uint64_t sample_id = begin; sample_id < end; ++sample_id) { + const std::uint32_t center_id = + nearestCenter(samples.data() + sample_id * database.dim, centers, + nlist, database.dim, database.metric); + ++worker_counts[center_id]; + for (std::uint32_t d = 0; d < database.dim; ++d) { + worker_sums[static_cast(center_id) * database.dim + + d] += samples[sample_id * database.dim + d]; + } + } + }); + for (std::uint32_t worker = 0; worker < training_threads; ++worker) { + const float* worker_sums = + partial_sums.data() + + static_cast(worker) * centers.size(); + const std::uint64_t* worker_counts = + partial_counts.data() + static_cast(worker) * nlist; + for (std::uint32_t center_id = 0; center_id < nlist; ++center_id) { + counts[center_id] += worker_counts[center_id]; + } + for (std::size_t value = 0; value < centers.size(); ++value) { + sums[value] += worker_sums[value]; + } + } + for (std::uint32_t center_id = 0; center_id < nlist; ++center_id) { + float* center = + centers.data() + static_cast(center_id) * database.dim; + if (counts[center_id] == 0) { + const std::uint64_t replacement = + (static_cast(center_id) + iteration) % sample_count; + std::copy_n(samples.data() + replacement * database.dim, database.dim, + center); + } else { + const float inverse_count = + 1.0F / static_cast(counts[center_id]); + for (std::uint32_t d = 0; d < database.dim; ++d) { + center[d] = + sums[static_cast(center_id) * database.dim + d] * + inverse_count; + } + } + // 对 Cosine 和 Inner Product 使用 spherical k-means。若不归一化, + // 高范数中心会在点积比较中吸收过多向量,nlist 较大时桶会严重倾斜。 + if (database.metric != Metric::kL2) { + normalize(center, database.dim); + } + } + } + + std::vector database_assignments(database.num_vectors); + counts.assign(nlist, 0); + parallelFor(database.num_vectors, num_threads, + [&](std::uint32_t, std::uint64_t begin, std::uint64_t end) { + std::vector vector(database.dim); + for (std::uint64_t vector_id = begin; vector_id < end; ++vector_id) { + for (std::uint32_t d = 0; d < database.dim; ++d) { + vector[d] = databaseValue(database, vector_id * database.dim + d); + } + database_assignments[vector_id] = nearestCenter( + vector.data(), centers, nlist, database.dim, database.metric); + } + }); + for (const std::uint32_t center_id : database_assignments) { + ++counts[center_id]; + } + + IvfFlatIndex index; + index.num_vectors = database.num_vectors; + index.dim = database.dim; + index.nlist = nlist; + index.dtype = database.dtype; + index.metric = database.metric; + index.centers = std::move(centers); + index.offsets.resize(static_cast(nlist) + 1, 0); + for (std::uint32_t center_id = 0; center_id < nlist; ++center_id) { + index.offsets[center_id + 1] = index.offsets[center_id] + counts[center_id]; + } + std::vector positions = index.offsets; + index.ids.resize(database.num_vectors); + if (database.dtype == DataType::kFloat32) { + index.values.resize(value_count); + } else { + index.half_values.resize(value_count); + } + for (std::uint64_t vector_id = 0; vector_id < database.num_vectors; + ++vector_id) { + const std::uint64_t position = positions[database_assignments[vector_id]]++; + index.ids[position] = vector_id; + const std::uint64_t source = vector_id * database.dim; + const std::uint64_t destination = position * database.dim; + if (database.dtype == DataType::kFloat32) { + std::copy_n(database.values.data() + source, database.dim, + index.values.data() + destination); + } else { + std::copy_n(database.half_values.data() + source, database.dim, + index.half_values.data() + destination); + } + } + validateIvfFlatIndex(index); + return index; +} + +void validateIvfFlatIndex(const IvfFlatIndex& index) { + if (index.num_vectors == 0 || index.dim == 0 || index.nlist == 0 || + index.nlist > index.num_vectors) { + throw std::runtime_error("IVF 索引元数据不合法"); + } + const std::uint64_t center_count = + checkedMultiply(index.nlist, index.dim, "IVF centers"); + const std::uint64_t value_count = + checkedMultiply(index.num_vectors, index.dim, "IVF vectors"); + if (index.centers.size() != center_count || + index.offsets.size() != static_cast(index.nlist) + 1 || + index.ids.size() != index.num_vectors || index.offsets.front() != 0 || + index.offsets.back() != index.num_vectors) { + throw std::runtime_error("IVF 索引数组长度与元数据不一致"); + } + if ((index.dtype == DataType::kFloat32 && + (index.values.size() != value_count || !index.half_values.empty())) || + (index.dtype == DataType::kFloat16 && + (index.half_values.size() != value_count || !index.values.empty()))) { + throw std::runtime_error("IVF 索引向量 dtype 或长度不正确"); + } + if (index.dtype != DataType::kFloat32 && index.dtype != DataType::kFloat16) { + throw std::runtime_error("IVF 索引 dtype 不支持"); + } + if (index.metric != Metric::kL2 && index.metric != Metric::kInnerProduct && + index.metric != Metric::kCosine) { + throw std::runtime_error("IVF 索引 metric 不支持"); + } + for (std::uint32_t center_id = 0; center_id < index.nlist; ++center_id) { + if (index.offsets[center_id] > index.offsets[center_id + 1]) { + throw std::runtime_error("IVF 桶 offsets 必须单调递增"); + } + } + std::vector seen(index.num_vectors, false); + for (const std::uint64_t id : index.ids) { + if (id >= index.num_vectors || seen[id]) { + throw std::runtime_error("IVF 原始向量 ID 越界或重复"); + } + seen[id] = true; + } +} + +void writeIvfFlatIndex(const std::string& path, const IvfFlatIndex& index) { + validateIvfFlatIndex(index); + std::ofstream output(path, std::ios::binary); + if (!output) { + throw std::runtime_error("无法写入 IVF 索引: " + path); + } + output.write(kIvfMagic.data(), kIvfMagic.size()); + writeValue(output, index.num_vectors); + writeValue(output, index.dim); + writeValue(output, static_cast(index.dtype)); + writeValue(output, static_cast(index.metric)); + writeValue(output, index.nlist); + output.write( + reinterpret_cast(index.centers.data()), + static_cast(index.centers.size() * sizeof(float))); + output.write(reinterpret_cast(index.offsets.data()), + static_cast(index.offsets.size() * + sizeof(std::uint64_t))); + output.write( + reinterpret_cast(index.ids.data()), + static_cast(index.ids.size() * sizeof(std::uint64_t))); + const void* values = index.dtype == DataType::kFloat32 + ? static_cast(index.values.data()) + : static_cast(index.half_values.data()); + const std::uint64_t element_bytes = + index.dtype == DataType::kFloat32 ? sizeof(float) : sizeof(std::uint16_t); + output.write(reinterpret_cast(values), + static_cast(index.num_vectors * index.dim * + element_bytes)); + if (!output) { + throw std::runtime_error("写入 IVF 索引失败: " + path); + } +} + +IvfFlatIndex readIvfFlatIndex(const std::string& path) { + std::ifstream input(path, std::ios::binary); + if (!input) { + throw std::runtime_error("无法打开 IVF 索引: " + path); + } + std::array magic{}; + input.read(magic.data(), magic.size()); + if (magic != kIvfMagic) { + throw std::runtime_error("IVF 索引 magic/version 不正确: " + path); + } + IvfFlatIndex index; + index.num_vectors = readValue(input, "num_vectors"); + index.dim = readValue(input, "dim"); + index.dtype = static_cast(readValue(input, "dtype")); + index.metric = static_cast(readValue(input, "metric")); + index.nlist = readValue(input, "nlist"); + if (index.num_vectors == 0 || index.dim == 0 || index.nlist == 0 || + index.nlist > index.num_vectors) { + throw std::runtime_error("IVF 索引元数据不合法: " + path); + } + const std::uint64_t center_count = + checkedMultiply(index.nlist, index.dim, "IVF centers"); + const std::uint64_t value_count = + checkedMultiply(index.num_vectors, index.dim, "IVF vectors"); + const std::uint64_t element_bytes = + index.dtype == DataType::kFloat32 ? sizeof(float) + : index.dtype == DataType::kFloat16 ? sizeof(std::uint16_t) + : 0; + if (element_bytes == 0) { + throw std::runtime_error("IVF 索引 dtype 不支持: " + path); + } + const std::uint64_t expected_size = + kHeaderBytes + center_count * sizeof(float) + + (static_cast(index.nlist) + 1) * sizeof(std::uint64_t) + + index.num_vectors * sizeof(std::uint64_t) + value_count * element_bytes; + if (std::filesystem::file_size(path) != expected_size) { + throw std::runtime_error("IVF 索引文件大小不正确: " + path); + } + index.centers.resize(center_count); + index.offsets.resize(static_cast(index.nlist) + 1); + index.ids.resize(index.num_vectors); + input.read(reinterpret_cast(index.centers.data()), + static_cast(center_count * sizeof(float))); + input.read(reinterpret_cast(index.offsets.data()), + static_cast(index.offsets.size() * + sizeof(std::uint64_t))); + input.read( + reinterpret_cast(index.ids.data()), + static_cast(index.ids.size() * sizeof(std::uint64_t))); + if (index.dtype == DataType::kFloat32) { + index.values.resize(value_count); + input.read(reinterpret_cast(index.values.data()), + static_cast(value_count * sizeof(float))); + } else { + index.half_values.resize(value_count); + input.read( + reinterpret_cast(index.half_values.data()), + static_cast(value_count * sizeof(std::uint16_t))); + } + if (!input) { + throw std::runtime_error("读取 IVF 索引数据失败: " + path); + } + validateIvfFlatIndex(index); + return index; +} + +SearchResults cpuIvfFlatSearch(const IvfFlatIndex& index, + const QuerySet& queries, + const SearchParams& params, + const MemoryMetadata* metadata) { + if (params.nprobe_policy != "fixed") { + throw std::runtime_error("自适应 nprobe 当前只支持 GPU backend"); + } + const std::vector> candidate_positions = + selectIvfCandidatePositions(index, queries, params.nprobe); + if (params.top_k == 0 || params.top_k > index.num_vectors) { + throw std::runtime_error("IVF 的 top_k 不合法"); + } + validateMemorySearch(index, params, metadata); + + SearchResults results(queries.num_queries); + for (std::uint64_t query_id = 0; query_id < queries.num_queries; ++query_id) { + std::vector candidates; + candidates.reserve(candidate_positions[query_id].size()); + for (const std::uint64_t position : candidate_positions[query_id]) { + const std::uint64_t vector_id = index.ids[position]; + if (params.memory_mode == "fused" && + !memoryCandidateMatches(*metadata, vector_id, params)) { + continue; + } + float score = candidateScore(index, queries, query_id, position); + if (params.memory_mode == "fused") { + score = + applyMemoryScore(score, vector_id, index.metric, *metadata, params); + } + candidates.push_back({vector_id, score}); + } + if (params.memory_mode == "disabled" && candidates.size() < params.top_k) { + throw std::runtime_error("IVF 探测桶的候选数少于 top_k,请增大 nprobe"); + } + const auto better = [&](const Neighbor& left, const Neighbor& right) { + return isBetter(left.score, left.id, right.score, right.id, index.metric); + }; + std::size_t selected_k = + std::min(params.top_k, candidates.size()); + if (params.memory_mode == "rerank") { + const std::uint64_t requested = static_cast(params.top_k) * + params.memory_rerank_factor; + const std::size_t rerank_k = static_cast( + std::min({requested, 100, candidates.size()})); + if (rerank_k < candidates.size()) { + std::nth_element(candidates.begin(), candidates.begin() + rerank_k, + candidates.end(), better); + candidates.resize(rerank_k); + } + candidates.erase(std::remove_if(candidates.begin(), candidates.end(), + [&](const Neighbor& candidate) { + return !memoryCandidateMatches( + *metadata, candidate.id, params); + }), + candidates.end()); + for (Neighbor& candidate : candidates) { + candidate.score = applyMemoryScore(candidate.score, candidate.id, + index.metric, *metadata, params); + } + selected_k = std::min(params.top_k, candidates.size()); + } + if (selected_k < candidates.size()) { + std::nth_element(candidates.begin(), candidates.begin() + selected_k, + candidates.end(), better); + candidates.resize(selected_k); + } + std::sort(candidates.begin(), candidates.end(), better); + results[query_id] = std::move(candidates); + } + return results; +} + +std::vector> selectIvfCandidatePositions( + const IvfFlatIndex& index, const QuerySet& queries, std::uint32_t nprobe) { + validateIvfFlatIndex(index); + if (queries.num_queries == 0 || queries.dim != index.dim || + queries.dtype != index.dtype) { + throw std::runtime_error("查询集与 IVF 索引的维度或 dtype 不匹配"); + } + const std::uint64_t query_value_count = + checkedMultiply(queries.num_queries, queries.dim, "IVF queries"); + if ((queries.dtype == DataType::kFloat32 && + queries.values.size() != query_value_count) || + (queries.dtype == DataType::kFloat16 && + queries.half_values.size() != query_value_count)) { + throw std::runtime_error("IVF 查询数据长度与元数据不一致"); + } + if (nprobe == 0 || nprobe > index.nlist) { + throw std::runtime_error("IVF 的 nprobe 不合法"); + } + + std::vector> selected(queries.num_queries); + std::vector query(index.dim); + for (std::uint64_t query_id = 0; query_id < queries.num_queries; ++query_id) { + for (std::uint32_t d = 0; d < index.dim; ++d) { + query[d] = queryValue(queries, query_id * index.dim + d); + } + std::vector center_ranking(index.nlist); + for (std::uint32_t center_id = 0; center_id < index.nlist; ++center_id) { + center_ranking[center_id] = { + center_id, + centerScore(query.data(), + index.centers.data() + + static_cast(center_id) * index.dim, + index.dim, index.metric)}; + } + const auto better = [&](const Neighbor& left, const Neighbor& right) { + return isBetter(left.score, left.id, right.score, right.id, index.metric); + }; + std::partial_sort(center_ranking.begin(), center_ranking.begin() + nprobe, + center_ranking.end(), better); + + std::vector& positions = selected[query_id]; + for (std::uint32_t probe = 0; probe < nprobe; ++probe) { + const std::uint64_t center_id = center_ranking[probe].id; + for (std::uint64_t position = index.offsets[center_id]; + position < index.offsets[center_id + 1]; ++position) { + positions.push_back(position); + } + } + } + return selected; +} + +double recallAtK(const SearchResults& exact, const SearchResults& approximate) { + if (exact.size() != approximate.size()) { + throw std::runtime_error("recall@K 的 query 数量不同"); + } + std::uint64_t matches = 0; + std::uint64_t total = 0; + for (std::size_t query_id = 0; query_id < exact.size(); ++query_id) { + if (exact[query_id].size() != approximate[query_id].size()) { + throw std::runtime_error("recall@K 的 K 不同"); + } + std::unordered_set exact_ids; + for (const Neighbor& neighbor : exact[query_id]) { + exact_ids.insert(neighbor.id); + } + for (const Neighbor& neighbor : approximate[query_id]) { + matches += exact_ids.count(neighbor.id); + } + total += exact[query_id].size(); + } + return total == 0 ? 1.0 : static_cast(matches) / total; +} diff --git a/09_vector_retrieval/PurplePulse/src/main.cpp b/09_vector_retrieval/PurplePulse/src/main.cpp new file mode 100644 index 00000000..6d1ebe8c --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/main.cpp @@ -0,0 +1,234 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "search.h" + +namespace { + +void printUsage(const char* program) { + std::cerr << "用法:\n " << program + << " --database <文件> --queries <文件> --params <文件>" + " --backend --output <文件>" + " [--warmup 1] [--repeat 5]" + " [--profile-breakdown 0|1] [--profile-repeat 5]\n"; +} + +std::unordered_map parseArguments(int argc, + char** argv) { + std::unordered_map arguments; + for (int index = 1; index < argc; index += 2) { + if (index + 1 >= argc || std::string(argv[index]).rfind("--", 0) != 0) { + throw std::runtime_error("命令行参数必须是 --名称 值 的形式"); + } + arguments[argv[index]] = argv[index + 1]; + } + for (const char* required : + {"--database", "--queries", "--params", "--backend", "--output"}) { + if (arguments.count(required) == 0) { + throw std::runtime_error(std::string("缺少参数: ") + required); + } + } + return arguments; +} + +double percentile(std::vector values, double fraction) { + if (values.empty()) { + return 0.0; + } + std::sort(values.begin(), values.end()); + const std::size_t index = + static_cast( + std::ceil(fraction * static_cast(values.size()))) - + 1; + return values[index]; +} + +std::uint32_t readCount( + const std::unordered_map& arguments, + const std::string& name, std::uint32_t default_value, bool allow_zero) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + std::size_t parsed_chars = 0; + const unsigned long parsed = std::stoul(found->second, &parsed_chars); + if (parsed_chars != found->second.size() || (!allow_zero && parsed == 0) || + parsed > UINT32_MAX) { + throw std::runtime_error(name + " 的值不合法"); + } + return static_cast(parsed); +} + +void addStats(SearchStats* total, const SearchStats& current) { + total->host_selection_ms += current.host_selection_ms; + total->center_selection_ms += current.center_selection_ms; + total->database_h2d_ms += current.database_h2d_ms; + total->query_h2d_ms += current.query_h2d_ms; + total->distance_kernel_ms += current.distance_kernel_ms; + total->topk_kernel_ms += current.topk_kernel_ms; + total->result_d2h_ms += current.result_d2h_ms; + total->batch_latency_ms.insert(total->batch_latency_ms.end(), + current.batch_latency_ms.begin(), + current.batch_latency_ms.end()); +} + +} // namespace + +int main(int argc, char** argv) { + try { + if (argc == 2 && std::string(argv[1]) == "--help") { + printUsage(argv[0]); + return EXIT_SUCCESS; + } + if (argc == 1) { + printUsage(argv[0]); + return 1; + } + const auto arguments = parseArguments(argc, argv); + const VectorDatabase database = + readVectorDatabase(arguments.at("--database")); + const QuerySet queries = readQuerySet(arguments.at("--queries")); + const SearchParams params = readSearchParams(arguments.at("--params")); + validateInputs(database, queries, params); + const std::uint32_t warmup = readCount(arguments, "--warmup", 0, true); + const std::uint32_t repeat = readCount(arguments, "--repeat", 1, false); + const bool profile_breakdown = + readCount(arguments, "--profile-breakdown", 0, true) != 0; + const std::uint32_t profile_repeat = + readCount(arguments, "--profile-repeat", repeat, false); + + std::cout << "向量库: " << database.num_vectors << " x " << database.dim + << "\n查询数: " << queries.num_queries + << "\ndtype: " << dataTypeName(database.dtype) + << "\nmetric: " << metricName(database.metric) + << "\ntop_k: " << params.top_k + << "\nbatch_size: " << params.batch_size + << "\ndistance_mode: " << params.distance_mode + << "\ntopk_mode: " << params.topk_mode + << "\nexact_query_tile: " << params.exact_query_tile + << "\nexact_fused_layout: " << params.exact_fused_layout + << "\nexact_fused_blocks: " << params.exact_fused_blocks + << "\nwarmup/repeat: " << warmup << '/' << repeat << '\n'; + + SearchResults results; + SearchStats stats; + const std::string backend = arguments.at("--backend"); + if (backend != "cpu" && backend != "gpu") { + throw std::runtime_error("backend 必须是 cpu 或 gpu"); + } + if (profile_breakdown && + (backend != "gpu" || params.topk_mode != "fused")) { + throw std::runtime_error( + "--profile-breakdown 只支持 backend=gpu、topk_mode=fused"); + } + + std::unique_ptr gpu_engine; + double gpu_initialization_ms = 0.0; + if (backend == "gpu") { + const auto initialization_start = std::chrono::steady_clock::now(); + gpu_engine = + std::make_unique(database, queries, params); + const auto initialization_end = std::chrono::steady_clock::now(); + gpu_initialization_ms = std::chrono::duration( + initialization_end - initialization_start) + .count(); + } + + const auto run_search = [&](SearchStats* run_stats) { + if (backend == "cpu") { + return cpuExactSearch(database, queries, params); + } + return gpu_engine->search(queries, run_stats); + }; + + for (std::uint32_t run = 0; run < warmup; ++run) { + SearchStats ignored_stats; + results = run_search(&ignored_stats); + } + + std::vector run_times_ms; + for (std::uint32_t run = 0; run < repeat; ++run) { + SearchStats run_stats; + const auto start = std::chrono::steady_clock::now(); + results = run_search(&run_stats); + const auto end = std::chrono::steady_clock::now(); + run_times_ms.push_back( + std::chrono::duration(end - start).count()); + addStats(&stats, run_stats); + } + + const std::filesystem::path output_path(arguments.at("--output")); + if (output_path.has_parent_path()) { + std::filesystem::create_directories(output_path.parent_path()); + } + writeSearchResults(output_path.string(), results); + + double total_ms = 0.0; + for (double time_ms : run_times_ms) { + total_ms += time_ms; + } + const double average_ms = total_ms / repeat; + const double qps = + static_cast(queries.num_queries) * repeat / (total_ms / 1000.0); + std::cout << "backend: " << backend; + if (backend == "gpu") { + std::cout << "\nGPU 一次性初始化总时间: " << gpu_initialization_ms + << " ms\n数据库一次性 H2D: " + << gpu_engine->databaseH2DMilliseconds() << " ms\nGPU 缓冲区: " + << gpu_engine->deviceBytes() / (1024.0 * 1024.0) << " MiB" + << "\n估算冷启动端到端: " << gpu_initialization_ms + average_ms + << " ms\n平均常驻查询时间: " << average_ms; + } else { + std::cout << "\n平均单次总时间: " << average_ms; + } + std::cout << " ms\nrun P50: " << percentile(run_times_ms, 0.50) + << " ms\nrun P99: " << percentile(run_times_ms, 0.99) << " ms\n" + << "run samples: " << run_times_ms.size() << '\n' + << (backend == "gpu" ? "常驻 QPS: " : "QPS: ") << qps + << "\n结果: " << output_path << '\n'; + if (backend == "gpu") { + double distance_only_ms = 0.0; + if (profile_breakdown) { + distance_only_ms = gpu_engine->profileDistanceOnlyMilliseconds( + queries, 1, profile_repeat); + } + std::cout + << "平均查询 H2D: " << stats.query_h2d_ms / repeat << " ms\n" + << (params.topk_mode == "fused" ? "平均融合距离+局部 Top-K kernel: " + : "平均距离 kernel: ") + << stats.distance_kernel_ms / repeat + << " ms\n平均最终 Top-K kernel: " << stats.topk_kernel_ms / repeat + << " ms\n平均结果 D2H: " << stats.result_d2h_ms / repeat + << " ms\nbatch P50: " << percentile(stats.batch_latency_ms, 0.50) + << " ms\nbatch P99: " << percentile(stats.batch_latency_ms, 0.99) + << " ms\nbatch samples: " << stats.batch_latency_ms.size() << '\n'; + if (profile_breakdown) { + const double fused_ms = stats.distance_kernel_ms / repeat; + const double final_merge_ms = stats.topk_kernel_ms / repeat; + const double local_topk_estimated_ms = + std::max(0.0, fused_ms - distance_only_ms); + std::cout + << "剖析方法: distance-only differential\n" + << "剖析重复次数: " << profile_repeat << '\n' + << "剖析距离-only kernel: " << distance_only_ms << " ms\n" + << "剖析局部 Top-K 估算: " << local_topk_estimated_ms << " ms\n" + << "剖析融合 kernel: " << fused_ms << " ms\n" + << "剖析最终归并 kernel: " << final_merge_ms << " ms\n"; + } + } + return 0; + } catch (const std::exception& error) { + std::cerr << "错误: " << error.what() << '\n'; + printUsage(argv[0]); + return 1; + } +} diff --git a/09_vector_retrieval/PurplePulse/src/search_ivf.cpp b/09_vector_retrieval/PurplePulse/src/search_ivf.cpp new file mode 100644 index 00000000..71404d2a --- /dev/null +++ b/09_vector_retrieval/PurplePulse/src/search_ivf.cpp @@ -0,0 +1,391 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "ivf_flat.h" + +namespace { + +void printUsage(const char* program) { + std::cerr << "用法:\n " << program + << " --index <文件> --queries <文件> --params <文件>" + " --output <文件> [--nlist N] [--nprobe N]" + " [--nprobe-policy fixed|score_mass]" + " [--adaptive-nprobe-min N] [--adaptive-nprobe-step N]" + " [--adaptive-target-mass F] [--adaptive-temperature F]" + " [--memory-metadata <文件>]" + " [--memory-mode disabled|fused|rerank]" + " [--filter-session-id N|any] [--filter-source-type N|any]" + " [--backend cpu|gpu] [--warmup 1] [--repeat 5]\n"; +} + +std::unordered_map parseArguments(int argc, + char** argv) { + std::unordered_map arguments; + for (int index = 1; index < argc; index += 2) { + if (index + 1 >= argc || std::string(argv[index]).rfind("--", 0) != 0) { + throw std::runtime_error("命令行参数必须是 --名称 值 的形式"); + } + arguments[argv[index]] = argv[index + 1]; + } + for (const char* required : + {"--index", "--queries", "--params", "--output"}) { + if (arguments.count(required) == 0) { + throw std::runtime_error(std::string("缺少参数: ") + required); + } + } + return arguments; +} + +std::uint32_t readCount( + const std::unordered_map& arguments, + const std::string& name, std::uint32_t default_value, bool allow_zero) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + std::size_t parsed_chars = 0; + const unsigned long parsed = std::stoul(found->second, &parsed_chars); + if (parsed_chars != found->second.size() || (!allow_zero && parsed == 0) || + parsed > UINT32_MAX) { + throw std::runtime_error(name + " 的值不合法"); + } + return static_cast(parsed); +} + +float readPositiveFloat( + const std::unordered_map& arguments, + const std::string& name, float default_value) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + std::size_t parsed_chars = 0; + const float parsed = std::stof(found->second, &parsed_chars); + if (parsed_chars != found->second.size() || !std::isfinite(parsed) || + parsed <= 0.0F) { + throw std::runtime_error(name + " 的值必须是有限正数"); + } + return parsed; +} + +float readNonnegativeFloat( + const std::unordered_map& arguments, + const std::string& name, float default_value) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + std::size_t parsed_chars = 0; + const float parsed = std::stof(found->second, &parsed_chars); + if (parsed_chars != found->second.size() || !std::isfinite(parsed) || + parsed < 0.0F) { + throw std::runtime_error(name + " 的值必须是有限非负数"); + } + return parsed; +} + +std::uint64_t readUint64( + const std::unordered_map& arguments, + const std::string& name, std::uint64_t default_value) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + if (found->second.empty() || found->second.front() == '-') { + throw std::runtime_error(name + " 的值必须是非负整数"); + } + std::size_t parsed_chars = 0; + const unsigned long long parsed = std::stoull(found->second, &parsed_chars); + if (parsed_chars != found->second.size()) { + throw std::runtime_error(name + " 的值必须是非负整数"); + } + return static_cast(parsed); +} + +std::uint32_t readOptionalId( + const std::unordered_map& arguments, + const std::string& name, std::uint32_t default_value) { + const auto found = arguments.find(name); + if (found == arguments.end()) { + return default_value; + } + if (found->second == "any") { + return UINT32_MAX; + } + const std::uint64_t parsed = readUint64(arguments, name, default_value); + if (parsed >= UINT32_MAX) { + throw std::runtime_error(name + " 的值必须小于 UINT32_MAX"); + } + return static_cast(parsed); +} + +double percentile(std::vector values, double fraction) { + if (values.empty()) { + return 0.0; + } + std::sort(values.begin(), values.end()); + const std::size_t index = + static_cast( + std::ceil(fraction * static_cast(values.size()))) - + 1; + return values[index]; +} + +void addStats(SearchStats* total, const SearchStats& current) { + total->host_selection_ms += current.host_selection_ms; + total->center_selection_ms += current.center_selection_ms; + total->adaptive_policy_ms += current.adaptive_policy_ms; + total->database_h2d_ms += current.database_h2d_ms; + total->query_h2d_ms += current.query_h2d_ms; + total->distance_kernel_ms += current.distance_kernel_ms; + total->topk_kernel_ms += current.topk_kernel_ms; + total->memory_rerank_ms += current.memory_rerank_ms; + total->result_d2h_ms += current.result_d2h_ms; + total->batch_latency_ms.insert(total->batch_latency_ms.end(), + current.batch_latency_ms.begin(), + current.batch_latency_ms.end()); + if (current.selected_probe_queries != 0) { + if (total->selected_probe_queries == 0) { + total->selected_probe_min = current.selected_probe_min; + } else { + total->selected_probe_min = + std::min(total->selected_probe_min, current.selected_probe_min); + } + total->selected_probe_max = + std::max(total->selected_probe_max, current.selected_probe_max); + total->selected_probe_sum += current.selected_probe_sum; + total->selected_probe_queries += current.selected_probe_queries; + if (total->selected_probe_counts.empty()) { + total->selected_probe_counts = current.selected_probe_counts; + } + } +} + +} // namespace + +int main(int argc, char** argv) { + try { + if (argc == 2 && std::string(argv[1]) == "--help") { + printUsage(argv[0]); + return EXIT_SUCCESS; + } + if (argc == 1) { + printUsage(argv[0]); + return EXIT_FAILURE; + } + const auto arguments = parseArguments(argc, argv); + const auto load_start = std::chrono::steady_clock::now(); + const IvfFlatIndex index = readIvfFlatIndex(arguments.at("--index")); + const auto load_end = std::chrono::steady_clock::now(); + const QuerySet queries = readQuerySet(arguments.at("--queries")); + SearchParams params = readSearchParams(arguments.at("--params")); + if (params.search_mode != "ivf_flat") { + throw std::runtime_error("IVF 查询要求 search_mode=ivf_flat"); + } + if (arguments.count("--nlist") != 0) { + params.nlist = readCount(arguments, "--nlist", params.nlist, false); + } + if (arguments.count("--nprobe") != 0) { + params.nprobe = readCount(arguments, "--nprobe", params.nprobe, false); + } + if (arguments.count("--nprobe-policy") != 0) { + params.nprobe_policy = arguments.at("--nprobe-policy"); + } + if (arguments.count("--adaptive-execution") != 0) { + params.adaptive_execution = arguments.at("--adaptive-execution"); + } + params.adaptive_nprobe_min = readCount(arguments, "--adaptive-nprobe-min", + params.adaptive_nprobe_min, false); + params.adaptive_nprobe_step = readCount(arguments, "--adaptive-nprobe-step", + params.adaptive_nprobe_step, false); + params.adaptive_target_mass = readPositiveFloat( + arguments, "--adaptive-target-mass", params.adaptive_target_mass); + params.adaptive_temperature = readPositiveFloat( + arguments, "--adaptive-temperature", params.adaptive_temperature); + if (arguments.count("--memory-mode") != 0) { + params.memory_mode = arguments.at("--memory-mode"); + } + params.memory_semantic_weight = readPositiveFloat( + arguments, "--memory-semantic-weight", params.memory_semantic_weight); + params.memory_importance_weight = + readNonnegativeFloat(arguments, "--memory-importance-weight", + params.memory_importance_weight); + params.memory_recency_weight = readNonnegativeFloat( + arguments, "--memory-recency-weight", params.memory_recency_weight); + params.memory_time_scale = readPositiveFloat( + arguments, "--memory-time-scale", params.memory_time_scale); + params.memory_now = + readUint64(arguments, "--memory-now", params.memory_now); + params.filter_min_timestamp = readUint64( + arguments, "--filter-min-timestamp", params.filter_min_timestamp); + params.filter_session_id = readOptionalId(arguments, "--filter-session-id", + params.filter_session_id); + params.filter_source_type = readOptionalId( + arguments, "--filter-source-type", params.filter_source_type); + params.memory_rerank_factor = readCount(arguments, "--memory-rerank-factor", + params.memory_rerank_factor, false); + if (params.nlist != index.nlist) { + throw std::runtime_error("参数 nlist 与索引 nlist 不一致"); + } + const std::uint32_t warmup = readCount(arguments, "--warmup", 0, true); + const std::uint32_t repeat = readCount(arguments, "--repeat", 1, false); + const std::string backend = + arguments.count("--backend") == 0 ? "cpu" : arguments.at("--backend"); + if (backend != "cpu" && backend != "gpu") { + throw std::runtime_error("backend 必须是 cpu 或 gpu"); + } + if (backend == "cpu" && params.nprobe_policy != "fixed") { + throw std::runtime_error("自适应 nprobe 当前只支持 GPU backend"); + } + MemoryMetadata memory_metadata; + const MemoryMetadata* metadata = nullptr; + const auto metadata_argument = arguments.find("--memory-metadata"); + if (metadata_argument != arguments.end()) { + memory_metadata = readMemoryMetadata(metadata_argument->second); + validateMemoryMetadata(memory_metadata, index.num_vectors); + metadata = &memory_metadata; + } + if (params.memory_mode != "disabled" && metadata == nullptr) { + throw std::runtime_error("memory_mode 启用时必须传入 --memory-metadata"); + } + + std::unique_ptr gpu_engine; + double gpu_initialization_ms = 0.0; + if (backend == "gpu") { + const auto initialization_start = std::chrono::steady_clock::now(); + gpu_engine = std::make_unique(index, queries, + params, metadata); + const auto initialization_end = std::chrono::steady_clock::now(); + gpu_initialization_ms = std::chrono::duration( + initialization_end - initialization_start) + .count(); + } + + SearchResults results; + const auto run_search = [&](SearchStats* stats) { + return backend == "gpu" + ? gpu_engine->search(queries, stats) + : cpuIvfFlatSearch(index, queries, params, metadata); + }; + for (std::uint32_t run = 0; run < warmup; ++run) { + SearchStats ignored; + results = run_search(&ignored); + } + std::vector run_times; + SearchStats stats; + for (std::uint32_t run = 0; run < repeat; ++run) { + SearchStats run_stats; + const auto start = std::chrono::steady_clock::now(); + results = run_search(&run_stats); + const auto end = std::chrono::steady_clock::now(); + run_times.push_back( + std::chrono::duration(end - start).count()); + addStats(&stats, run_stats); + } + const std::filesystem::path output_path(arguments.at("--output")); + if (output_path.has_parent_path()) { + std::filesystem::create_directories(output_path.parent_path()); + } + writeSearchResults(output_path.string(), results); + double total_ms = 0.0; + for (const double time : run_times) { + total_ms += time; + } + const double average_ms = total_ms / repeat; + const double load_ms = + std::chrono::duration(load_end - load_start) + .count(); + std::cout << "IVF-Flat " << backend << " 查询完成" + << "\n索引: " << index.num_vectors << " x " << index.dim + << "\ndtype/metric: " << dataTypeName(index.dtype) << '/' + << metricName(index.metric) + << "\nnlist/nprobe/top_k: " << index.nlist << '/' << params.nprobe + << '/' << params.top_k + << "\nnprobe policy: " << params.nprobe_policy + << "\nmemory mode: " << params.memory_mode + << "\n索引加载: " << load_ms << " ms" + << (backend == "gpu" ? "\nGPU 初始化: " : "") + << (backend == "gpu" ? std::to_string(gpu_initialization_ms) + : std::string()) + << (backend == "gpu" ? " ms\n索引 H2D: " : "") + << (backend == "gpu" + ? std::to_string(gpu_engine->indexH2DMilliseconds()) + : std::string()) + << (backend == "gpu" ? " ms" : "") + << (backend == "gpu" ? "\nGPU 缓冲区: " : "") + << (backend == "gpu" ? std::to_string(gpu_engine->deviceBytes() / + (1024.0 * 1024.0)) + : std::string()) + << (backend == "gpu" ? " MiB" : "") + << "\n平均查询: " << average_ms << " ms" + << "\nrun P50/P99: " << percentile(run_times, 0.50) << '/' + << percentile(run_times, 0.99) << " ms" + << "\nrun samples: " << run_times.size() + << "\nQPS: " << queries.num_queries * repeat / (total_ms / 1000.0) + << "\n输出: " << output_path << '\n'; + if (params.nprobe_policy == "score_mass") { + std::cout << "自适应 min/step/target/temperature: " + << params.adaptive_nprobe_min << '/' + << params.adaptive_nprobe_step << '/' + << params.adaptive_target_mass << '/' + << params.adaptive_temperature << '\n'; + std::cout << "自适应执行方式: " << params.adaptive_execution << '\n'; + } + if (backend == "gpu") { + std::cout + << "平均 CPU 中心/桶选择: " << stats.host_selection_ms / repeat + << " ms\n平均 query H2D: " << stats.query_h2d_ms / repeat + << " ms\n平均 GPU 中心选择: " << stats.center_selection_ms / repeat + << " ms\n平均自适应分层开销: " << stats.adaptive_policy_ms / repeat + << " ms\n平均 GPU 桶扫描+局部 Top-K: " + << stats.distance_kernel_ms / repeat + << " ms\n平均 GPU 最终 Top-K 归并: " << stats.topk_kernel_ms / repeat + << " ms\n平均记忆独立重排: " << stats.memory_rerank_ms / repeat + << " ms\n平均结果 D2H: " << stats.result_d2h_ms / repeat + << " ms\nbatch P50/P99: " << percentile(stats.batch_latency_ms, 0.50) + << '/' << percentile(stats.batch_latency_ms, 0.99) + << " ms\nbatch samples: " << stats.batch_latency_ms.size() << '\n'; + if (stats.selected_probe_queries != 0) { + std::cout << "实际 nprobe min/avg/max: " << stats.selected_probe_min + << '/' + << static_cast(stats.selected_probe_sum) / + stats.selected_probe_queries + << '/' << stats.selected_probe_max << '\n'; + } + const auto probe_counts_argument = + arguments.find("--probe-counts-output"); + if (probe_counts_argument != arguments.end()) { + const std::filesystem::path counts_path(probe_counts_argument->second); + if (counts_path.has_parent_path()) { + std::filesystem::create_directories(counts_path.parent_path()); + } + std::ofstream counts_output(counts_path); + if (!counts_output) { + throw std::runtime_error("无法写入实际 nprobe 文件: " + + counts_path.string()); + } + for (std::size_t query_id = 0; + query_id < stats.selected_probe_counts.size(); ++query_id) { + counts_output << query_id << ' ' + << stats.selected_probe_counts[query_id] << '\n'; + } + } + } + return EXIT_SUCCESS; + } catch (const std::exception& error) { + std::cerr << "错误: " << error.what() << '\n'; + printUsage(argv[0]); + return EXIT_FAILURE; + } +} diff --git a/09_vector_retrieval/PurplePulse/tests/file_io_tests.cpp b/09_vector_retrieval/PurplePulse/tests/file_io_tests.cpp new file mode 100644 index 00000000..b8ab98b9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/file_io_tests.cpp @@ -0,0 +1,195 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "file_io.h" + +namespace { + +template +void writeValue(std::ofstream& output, const T& value) { + output.write(reinterpret_cast(&value), sizeof(T)); +} + +void require(bool condition, const std::string& message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +template +void requireThrows(Operation operation, const std::string& message) { + try { + operation(); + } catch (const std::runtime_error&) { + return; + } + throw std::runtime_error(message); +} + +void writeDatabase(const std::filesystem::path& path) { + std::ofstream output(path, std::ios::binary); + const std::array magic = {'P', 'P', 'V', 'E', 'C', '0', '0', '1'}; + const std::uint64_t rows = 2; + const std::uint32_t dim = 2; + const std::uint32_t dtype = static_cast(DataType::kFloat16); + const std::uint32_t metric = static_cast(Metric::kL2); + const std::array values = {0x3c00, 0x0000, 0x4000, 0xbc00}; + output.write(magic.data(), magic.size()); + writeValue(output, rows); + writeValue(output, dim); + writeValue(output, dtype); + writeValue(output, metric); + output.write(reinterpret_cast(values.data()), + values.size() * sizeof(values[0])); +} + +void writeQueries(const std::filesystem::path& path) { + std::ofstream output(path, std::ios::binary); + const std::array magic = {'P', 'P', 'Q', 'R', 'Y', '0', '0', '1'}; + const std::uint64_t rows = 1; + const std::uint32_t dim = 2; + const std::uint32_t dtype = static_cast(DataType::kFloat16); + const std::array values = {0x3c00, 0x0000}; + output.write(magic.data(), magic.size()); + writeValue(output, rows); + writeValue(output, dim); + writeValue(output, dtype); + output.write(reinterpret_cast(values.data()), + values.size() * sizeof(values[0])); +} + +} // namespace + +int main() { + const auto unique = + std::chrono::steady_clock::now().time_since_epoch().count(); + const std::filesystem::path directory = + std::filesystem::temp_directory_path() / + ("purplepulse-file-io-test-" + std::to_string(unique)); + try { + std::filesystem::create_directories(directory); + const std::filesystem::path database_path = directory / "database.bin"; + const std::filesystem::path query_path = directory / "queries.bin"; + writeDatabase(database_path); + writeQueries(query_path); + + const VectorDatabase database = readVectorDatabase(database_path.string()); + const QuerySet queries = readQuerySet(query_path.string()); + require(database.dtype == DataType::kFloat16, "database dtype 错误"); + require(queries.dtype == DataType::kFloat16, "query dtype 错误"); + require(database.values.empty() && queries.values.empty(), + "FP16 文件不应展开为 FP32 存储"); + require( + database.half_values.size() == 4 && database.half_values[2] == 0x4000, + "database half 位模式错误"); + require(queries.half_values.size() == 2 && queries.half_values[0] == 0x3c00, + "query half 位模式错误"); + SearchParams params; + params.top_k = 1; + validateInputs(database, queries, params); + params.search_mode = "ivf_flat"; + bool rejected_unimplemented_ivf = false; + try { + validateInputs(database, queries, params); + } catch (const std::runtime_error&) { + rejected_unimplemented_ivf = true; + } + require(rejected_unimplemented_ivf, + "未实现的 IVF-Flat 不应静默执行 exact search"); + + const std::filesystem::path metadata_path = directory / "memory.bin"; + MemoryMetadata written_metadata; + written_metadata.num_vectors = 3; + written_metadata.timestamps = {100, 200, 300}; + written_metadata.importance = {0.1F, 0.5F, 1.0F}; + written_metadata.session_ids = {1, 1, 2}; + written_metadata.source_types = {0, 2, 1}; + writeMemoryMetadata(metadata_path.string(), written_metadata); + const MemoryMetadata loaded_metadata = + readMemoryMetadata(metadata_path.string()); + require(loaded_metadata.timestamps == written_metadata.timestamps && + loaded_metadata.importance == written_metadata.importance && + loaded_metadata.session_ids == written_metadata.session_ids && + loaded_metadata.source_types == written_metadata.source_types, + "记忆元数据保存/加载后内容变化"); + + const std::filesystem::path params_path = directory / "adaptive.conf"; + { + std::ofstream output(params_path); + output << "top_k = 10\n" + "search_mode = ivf_flat\n" + "exact_query_tile = 2\n" + "exact_fused_layout = warp_query\n" + "exact_fused_blocks = 96\n" + "nprobe = 224\n" + "nprobe_policy = score_mass\n" + "adaptive_execution = grouped\n" + "adaptive_nprobe_min = 64\n" + "adaptive_nprobe_step = 16\n" + "adaptive_target_mass = 0.85\n" + "adaptive_temperature = 0.2\n" + "memory_mode = fused\n" + "memory_importance_weight = 0.15\n" + "memory_recency_weight = 0.1\n" + "memory_time_scale = 100\n" + "memory_now = 300\n" + "filter_session_id = any\n" + "filter_source_type = 2\n"; + } + const SearchParams adaptive = readSearchParams(params_path.string()); + require(adaptive.nprobe_policy == "score_mass" && + adaptive.exact_query_tile == 2 && + adaptive.exact_fused_layout == "warp_query" && + adaptive.exact_fused_blocks == 96 && + adaptive.adaptive_execution == "grouped" && + adaptive.adaptive_nprobe_min == 64 && + adaptive.adaptive_nprobe_step == 16 && + adaptive.adaptive_target_mass == 0.85F && + adaptive.adaptive_temperature == 0.2F && + adaptive.memory_mode == "fused" && + adaptive.memory_importance_weight == 0.15F && + adaptive.memory_now == 300 && + adaptive.filter_session_id == UINT32_MAX && + adaptive.filter_source_type == 2, + "自适应 nprobe 或记忆参数解析错误"); + + const std::filesystem::path bad_magic_path = directory / "bad-magic.bin"; + { + std::ofstream output(bad_magic_path, std::ios::binary); + output << "NOTAVECTORFILE"; + } + requireThrows([&] { (void)readVectorDatabase(bad_magic_path.string()); }, + "错误的向量库 magic/version 应被拒绝"); + + const std::filesystem::path truncated_path = directory / "truncated.bin"; + writeQueries(truncated_path); + std::filesystem::resize_file( + truncated_path, std::filesystem::file_size(truncated_path) - 1); + requireThrows([&] { (void)readQuerySet(truncated_path.string()); }, + "截断的查询文件应被拒绝"); + + const std::filesystem::path extra_bytes_path = directory / "extra.bin"; + writeDatabase(extra_bytes_path); + { + std::ofstream output(extra_bytes_path, std::ios::binary | std::ios::app); + output.put('\0'); + } + requireThrows([&] { (void)readVectorDatabase(extra_bytes_path.string()); }, + "包含额外字节的向量库文件应被拒绝"); + + std::filesystem::remove_all(directory); + std::cout << "FP16 文件读取与损坏文件测试通过\n"; + return EXIT_SUCCESS; + } catch (const std::exception& error) { + std::filesystem::remove_all(directory); + std::cerr << "测试失败: " << error.what() << '\n'; + return EXIT_FAILURE; + } +} diff --git a/09_vector_retrieval/PurplePulse/tests/ivf_flat_tests.cpp b/09_vector_retrieval/PurplePulse/tests/ivf_flat_tests.cpp new file mode 100644 index 00000000..cfecb7b9 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/ivf_flat_tests.cpp @@ -0,0 +1,351 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "ivf_flat.h" +#include "search.h" + +namespace { + +void require(bool condition, const std::string& message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +VectorDatabase makeDatabase(Metric metric, DataType dtype) { + VectorDatabase database; + database.num_vectors = 12; + database.dim = 2; + database.metric = metric; + database.dtype = dtype; + const std::vector values = { + 1.0F, 0.0F, 1.0F, 0.25F, 0.75F, 0.0F, 0.0F, 1.0F, + 0.25F, 1.0F, 0.0F, 0.75F, -1.0F, 0.0F, -1.0F, -0.25F, + -0.75F, 0.0F, 0.0F, -1.0F, -0.25F, -1.0F, 0.0F, -0.75F, + }; + if (dtype == DataType::kFloat32) { + database.values = values; + } else { + // 测试数据只使用 0、±1、±0.75、±0.25,均可被 binary16 精确表示。 + const auto half = [](float value) -> std::uint16_t { + if (value == 1.0F) return 0x3c00; + if (value == -1.0F) return 0xbc00; + if (value == 0.75F) return 0x3a00; + if (value == -0.75F) return 0xba00; + if (value == 0.25F) return 0x3400; + if (value == -0.25F) return 0xb400; + return 0x0000; + }; + for (const float value : values) { + database.half_values.push_back(half(value)); + } + } + return database; +} + +QuerySet makeQueries(DataType dtype) { + QuerySet queries; + queries.num_queries = 4; + queries.dim = 2; + queries.dtype = dtype; + if (dtype == DataType::kFloat32) { + queries.values = {1.0F, 0.0F, 0.0F, 1.0F, -1.0F, 0.0F, 0.0F, -1.0F}; + } else { + queries.half_values = {0x3c00, 0x0000, 0x0000, 0x3c00, + 0xbc00, 0x0000, 0x0000, 0xbc00}; + } + return queries; +} + +MemoryMetadata makeMemoryMetadata(std::uint64_t num_vectors) { + MemoryMetadata metadata; + metadata.num_vectors = num_vectors; + for (std::uint64_t id = 0; id < num_vectors; ++id) { + metadata.timestamps.push_back(900 + id * 10); + metadata.importance.push_back(static_cast(id) / + static_cast(num_vectors)); + metadata.session_ids.push_back(static_cast(id % 2)); + metadata.source_types.push_back(static_cast(id % 3)); + } + return metadata; +} + +std::uint16_t exactHalf(float value) { + if (value == 1.0F) return 0x3c00; + if (value == -1.0F) return 0xbc00; + if (value == 0.75F) return 0x3a00; + if (value == -0.75F) return 0xba00; + if (value == 0.25F) return 0x3400; + if (value == -0.25F) return 0xb400; + return 0x0000; +} + +VectorDatabase makeLargeKDatabase(Metric metric, DataType dtype) { + constexpr float levels[] = {-1.0F, -0.75F, -0.25F, 0.0F, 0.25F, 0.75F, 1.0F}; + VectorDatabase database; + database.num_vectors = 128; + database.dim = 4; + database.metric = metric; + database.dtype = dtype; + std::vector values; + values.reserve(database.num_vectors * database.dim); + for (std::uint64_t vector_id = 0; vector_id < database.num_vectors; + ++vector_id) { + std::uint64_t code = vector_id; + for (std::uint32_t d = 0; d < database.dim; ++d) { + values.push_back(levels[code % 7]); + code /= 7; + } + } + if (dtype == DataType::kFloat32) { + database.values = std::move(values); + } else { + database.half_values.reserve(values.size()); + for (const float value : values) { + database.half_values.push_back(exactHalf(value)); + } + } + return database; +} + +QuerySet makeLargeKQueries(DataType dtype) { + const std::vector values = { + 1.0F, 0.25F, -0.75F, 0.0F, -0.25F, 1.0F, + 0.75F, -1.0F, 0.0F, -0.75F, 1.0F, 0.25F, + }; + QuerySet queries; + queries.num_queries = 3; + queries.dim = 4; + queries.dtype = dtype; + if (dtype == DataType::kFloat32) { + queries.values = values; + } else { + for (const float value : values) { + queries.half_values.push_back(exactHalf(value)); + } + } + return queries; +} + +void testLargeK(Metric metric, DataType dtype) { + const VectorDatabase database = makeLargeKDatabase(metric, dtype); + const QuerySet queries = makeLargeKQueries(dtype); + const IvfFlatIndex index = buildIvfFlatIndex(database, 8, 5, 128); + for (const std::uint32_t top_k : {50U, 100U}) { + SearchParams params; + params.top_k = top_k; + params.search_mode = "ivf_flat"; + params.nlist = 8; + params.nprobe = 8; + params.batch_size = 4; + params.distance_mode = "warp"; + SearchParams exact_params = params; + exact_params.search_mode = "exact"; + exact_params.topk_mode = "block"; + const SearchResults exact = cpuExactSearch(database, queries, exact_params); + const SearchResults cpu_ivf = cpuIvfFlatSearch(index, queries, params); + std::string error; + require(resultsMatch(exact, cpu_ivf, 0.0F, &error), + "大 K CPU IVF 与 exact 不一致: " + error); + SearchResults warp8_results; + for (const std::string& distance_mode : + {"warp8", "warp4", "warp2", "warp1", "warp_compact", + "bucket_major"}) { + params.distance_mode = distance_mode; + GpuIvfFlatSearchEngine engine(index, queries, params); + const SearchResults gpu_ivf = engine.search(queries); + require(resultsMatch(cpu_ivf, gpu_ivf, 1e-5F, &error), + "大 K " + distance_mode + " GPU IVF 与 CPU IVF 不一致: " + error); + if (distance_mode == "warp8") { + warp8_results = gpu_ivf; + } else { + require(resultsMatch(warp8_results, gpu_ivf, 0.0F, &error), + "大 K compact warp 与 warp8 结果不一致: " + error); + } + } + } +} + +void testRoundTrip(Metric metric, DataType dtype, + const std::filesystem::path& directory) { + const VectorDatabase database = makeDatabase(metric, dtype); + const QuerySet queries = makeQueries(dtype); + const IvfFlatIndex built = buildIvfFlatIndex(database, 4, 8, 12); + const IvfFlatIndex parallel_built = + buildIvfFlatIndex(database, 4, 8, 12, 4); + const IvfFlatIndex parallel_repeated = + buildIvfFlatIndex(database, 4, 8, 12, 4); + require(parallel_built.centers == parallel_repeated.centers && + parallel_built.offsets == parallel_repeated.offsets && + parallel_built.ids == parallel_repeated.ids && + parallel_built.values == parallel_repeated.values && + parallel_built.half_values == parallel_repeated.half_values, + "固定线程数的并行 IVF 建库结果应可重复"); + const std::filesystem::path path = + directory / + (std::string("index-") + std::to_string(static_cast(metric)) + "-" + + std::to_string(static_cast(dtype)) + ".bin"); + writeIvfFlatIndex(path.string(), built); + const IvfFlatIndex loaded = readIvfFlatIndex(path.string()); + require(loaded.centers == built.centers && loaded.offsets == built.offsets && + loaded.ids == built.ids && loaded.values == built.values && + loaded.half_values == built.half_values, + "IVF 索引保存/加载后内容变化"); + + SearchParams exact_params; + exact_params.top_k = 3; + const SearchResults exact = cpuExactSearch(database, queries, exact_params); + SearchParams ivf_params = exact_params; + ivf_params.search_mode = "ivf_flat"; + ivf_params.nlist = 4; + ivf_params.nprobe = 4; + const SearchResults exhaustive_ivf = + cpuIvfFlatSearch(loaded, queries, ivf_params); + std::string error; + require(resultsMatch(exact, exhaustive_ivf, 0.0F, &error), + "nprobe=nlist 应与 exact 完全一致: " + error); + require(recallAtK(exact, exhaustive_ivf) == 1.0, + "nprobe=nlist 的 recall@K 应为 1"); + + ivf_params.nprobe = 2; + const SearchResults approximate = + cpuIvfFlatSearch(loaded, queries, ivf_params); + const double recall = recallAtK(exact, approximate); + require(recall >= 0.0 && recall <= 1.0, "IVF recall@K 必须位于 [0, 1]"); + + ivf_params.distance_mode = "simple"; + GpuIvfFlatSearchEngine scalar_gpu_engine(loaded, queries, ivf_params); + const SearchResults scalar_gpu = scalar_gpu_engine.search(queries); + require(resultsMatch(approximate, scalar_gpu, 1e-5F, &error), + "scalar GPU IVF 与 CPU IVF 不一致: " + error); + + ivf_params.distance_mode = "warp"; + GpuIvfFlatSearchEngine gpu_engine(loaded, queries, ivf_params); + SearchStats first_stats; + const SearchResults gpu_first = gpu_engine.search(queries, &first_stats); + const SearchResults gpu_second = gpu_engine.search(queries); + require(resultsMatch(approximate, gpu_first, 1e-5F, &error), + "GPU IVF 与 CPU IVF 不一致: " + error); + require(resultsMatch(gpu_first, gpu_second, 0.0F, &error), + "GPU IVF 常驻引擎重复查询不一致: " + error); + require(first_stats.host_selection_ms >= 0.0 && + first_stats.distance_kernel_ms >= 0.0 && + gpu_engine.indexH2DMilliseconds() >= 0.0 && + gpu_engine.deviceBytes() > 0, + "GPU IVF 计时不应为负数且设备缓冲区应非空"); + + SearchParams adaptive_params = ivf_params; + adaptive_params.nprobe = 4; + adaptive_params.nprobe_policy = "score_mass"; + adaptive_params.adaptive_nprobe_min = 2; + adaptive_params.adaptive_nprobe_step = 1; + adaptive_params.adaptive_target_mass = 0.5F; + adaptive_params.adaptive_temperature = 0.2F; + GpuIvfFlatSearchEngine adaptive_engine(loaded, queries, adaptive_params); + SearchStats adaptive_stats; + const SearchResults adaptive_results = + adaptive_engine.search(queries, &adaptive_stats); + require(adaptive_results.size() == queries.num_queries && + adaptive_stats.selected_probe_queries == queries.num_queries && + adaptive_stats.selected_probe_min >= 2 && + adaptive_stats.selected_probe_max <= 4 && + adaptive_stats.selected_probe_sum >= 2 * queries.num_queries && + adaptive_stats.selected_probe_sum <= 4 * queries.num_queries, + "自适应 nprobe 统计或边界错误"); + + adaptive_params.adaptive_nprobe_min = 4; + adaptive_params.adaptive_target_mass = 0.1F; + adaptive_params.adaptive_execution = "grouped"; + GpuIvfFlatSearchEngine capped_adaptive_engine(loaded, queries, + adaptive_params); + SearchStats capped_stats; + const SearchResults capped_adaptive = + capped_adaptive_engine.search(queries, &capped_stats); + require(resultsMatch(exhaustive_ivf, capped_adaptive, 1e-5F, &error), + "min_nprobe=max_nprobe 时自适应结果应与固定全桶一致: " + error); + require(capped_stats.selected_probe_min == 4 && + capped_stats.selected_probe_max == 4, + "自适应 nprobe 上下限相同时统计错误"); + + const MemoryMetadata metadata = makeMemoryMetadata(database.num_vectors); + SearchParams memory_params = ivf_params; + memory_params.nprobe = 4; + memory_params.top_k = 3; + memory_params.memory_mode = "fused"; + memory_params.memory_importance_weight = 0.2F; + memory_params.memory_recency_weight = 0.1F; + memory_params.memory_time_scale = 50.0F; + memory_params.memory_now = 1000; + memory_params.filter_session_id = 0; + const SearchResults cpu_fused = + cpuIvfFlatSearch(loaded, queries, memory_params, &metadata); + GpuIvfFlatSearchEngine fused_engine(loaded, queries, memory_params, + &metadata); + const SearchResults gpu_fused = fused_engine.search(queries); + require(resultsMatch(cpu_fused, gpu_fused, 1e-5F, &error), + "融合记忆评分的 GPU IVF 与 CPU baseline 不一致: " + error); + for (const auto& query_results : gpu_fused) { + require(query_results.size() == memory_params.top_k, + "过滤后候选充足时应返回完整 Top-K"); + for (const Neighbor& neighbor : query_results) { + require(neighbor.id % 2 == 0, "GPU session filter 返回了不匹配候选"); + } + } + + memory_params.filter_source_type = 99; + const SearchResults cpu_empty = + cpuIvfFlatSearch(loaded, queries, memory_params, &metadata); + GpuIvfFlatSearchEngine empty_filter_engine(loaded, queries, memory_params, + &metadata); + const SearchResults gpu_empty = empty_filter_engine.search(queries); + require(resultsMatch(cpu_empty, gpu_empty, 0.0F, &error), + "过滤后不足 K 个候选时 CPU/GPU 结果不一致: " + error); + for (const auto& query_results : gpu_empty) { + require(query_results.empty(), "完全不匹配的过滤条件应返回空结果"); + } + + memory_params.memory_mode = "rerank"; + memory_params.filter_source_type = UINT32_MAX; + memory_params.memory_rerank_factor = 4; + const SearchResults cpu_rerank = + cpuIvfFlatSearch(loaded, queries, memory_params, &metadata); + GpuIvfFlatSearchEngine rerank_engine(loaded, queries, memory_params, + &metadata); + SearchStats rerank_stats; + const SearchResults gpu_rerank = rerank_engine.search(queries, &rerank_stats); + require(resultsMatch(cpu_rerank, gpu_rerank, 1e-5F, &error), + "独立记忆重排的 GPU IVF 与 CPU baseline 不一致: " + error); + require(rerank_stats.memory_rerank_ms >= 0.0, "独立记忆重排计时不应为负数"); +} + +} // namespace + +int main() { + const auto unique = + std::chrono::steady_clock::now().time_since_epoch().count(); + const std::filesystem::path directory = + std::filesystem::temp_directory_path() / + ("purplepulse-ivf-test-" + std::to_string(unique)); + try { + std::filesystem::create_directories(directory); + for (const DataType dtype : {DataType::kFloat32, DataType::kFloat16}) { + for (const Metric metric : + {Metric::kL2, Metric::kInnerProduct, Metric::kCosine}) { + testRoundTrip(metric, dtype, directory); + testLargeK(metric, dtype); + } + } + std::filesystem::remove_all(directory); + std::cout << "IVF-Flat 建库、持久化、查询与 recall 测试通过\n"; + return EXIT_SUCCESS; + } catch (const std::exception& error) { + std::filesystem::remove_all(directory); + std::cerr << "测试失败: " << error.what() << '\n'; + return EXIT_FAILURE; + } +} diff --git a/09_vector_retrieval/PurplePulse/tests/stability_tests.cpp b/09_vector_retrieval/PurplePulse/tests/stability_tests.cpp new file mode 100644 index 00000000..3bfad033 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/stability_tests.cpp @@ -0,0 +1,317 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ivf_flat.h" +#include "search.h" + +namespace { + +void require(bool condition, const std::string& message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +template +void requireThrows(Operation operation, const std::string& message) { + try { + operation(); + } catch (const std::runtime_error&) { + return; + } + throw std::runtime_error(message); +} + +constexpr std::array kLevels = { + -1.0F, -0.75F, -0.5F, -0.25F, 0.0F, + 0.25F, 0.5F, 0.75F, 1.0F, +}; + +std::uint16_t exactHalf(float value) { + if (value == -1.0F) return 0xbc00; + if (value == -0.75F) return 0xba00; + if (value == -0.5F) return 0xb800; + if (value == -0.25F) return 0xb400; + if (value == 0.25F) return 0x3400; + if (value == 0.5F) return 0x3800; + if (value == 0.75F) return 0x3a00; + if (value == 1.0F) return 0x3c00; + return 0x0000; +} + +float deterministicValue(std::uint64_t row, std::uint32_t dimension) { + const std::uint64_t mixed = row * 37U + dimension * 17U + + (row / 3U) * 5U + dimension / 7U; + return kLevels[mixed % kLevels.size()]; +} + +void appendValue(std::vector* fp32, std::vector* fp16, + DataType dtype, float value) { + if (dtype == DataType::kFloat32) { + fp32->push_back(value); + } else { + fp16->push_back(exactHalf(value)); + } +} + +VectorDatabase makeCoverageDatabase(std::uint32_t dim, Metric metric, + DataType dtype, + std::uint64_t num_vectors = 107) { + VectorDatabase database; + database.num_vectors = num_vectors; + database.dim = dim; + database.metric = metric; + database.dtype = dtype; + database.values.reserve(dtype == DataType::kFloat32 ? num_vectors * dim : 0); + database.half_values.reserve(dtype == DataType::kFloat16 ? num_vectors * dim + : 0); + for (std::uint64_t row = 0; row < num_vectors; ++row) { + // Rows 0 and 1 are deliberately identical. This validates stable ID + // tie-breaking for every dimension, dtype, metric, batch, and K. + const std::uint64_t source_row = row == 1 ? 0 : row; + for (std::uint32_t d = 0; d < dim; ++d) { + appendValue(&database.values, &database.half_values, dtype, + deterministicValue(source_row, d)); + } + } + return database; +} + +QuerySet makeCoverageQueries(std::uint32_t dim, DataType dtype, + std::uint64_t num_queries = 9) { + QuerySet queries; + queries.num_queries = num_queries; + queries.dim = dim; + queries.dtype = dtype; + queries.values.reserve(dtype == DataType::kFloat32 ? num_queries * dim : 0); + queries.half_values.reserve(dtype == DataType::kFloat16 ? num_queries * dim + : 0); + for (std::uint64_t row = 0; row < num_queries; ++row) { + for (std::uint32_t d = 0; d < dim; ++d) { + // The first query is all zero, making every IP/cosine score tie. The + // second query exactly matches duplicate database rows 0 and 1. + const float value = row == 0 ? 0.0F : deterministicValue(row - 1, d); + appendValue(&queries.values, &queries.half_values, dtype, value); + } + } + return queries; +} + +void compareExact(const VectorDatabase& database, const QuerySet& queries, + const SearchParams& params, const std::string& label) { + const SearchResults cpu = cpuExactSearch(database, queries, params); + GpuExactSearchEngine engine(database, queries, params); + const SearchResults gpu = engine.search(queries); + std::string error; + require(resultsMatch(cpu, gpu, 5e-5F, &error), label + ": " + error); + if ((database.metric == Metric::kInnerProduct || + database.metric == Metric::kCosine) && + !gpu.empty()) { + const std::uint32_t expected = std::min( + params.top_k, static_cast(database.num_vectors)); + for (std::uint32_t rank = 0; rank < expected; ++rank) { + require(gpu[0][rank].id == rank, + label + ": equal-score candidates must use ascending IDs"); + } + } +} + +void testExactCoverageMatrix() { + constexpr std::array dimensions = {64, 128, 384, 768}; + constexpr std::array batches = {1, 8, 32, 40, 64, 128}; + constexpr std::array top_ks = {1, 10, 50, 100}; + std::uint32_t cases = 0; + for (const DataType dtype : {DataType::kFloat32, DataType::kFloat16}) { + for (const Metric metric : + {Metric::kL2, Metric::kInnerProduct, Metric::kCosine}) { + for (const std::uint32_t dim : dimensions) { + const VectorDatabase database = makeCoverageDatabase(dim, metric, dtype); + const QuerySet queries = makeCoverageQueries(dim, dtype); + for (const std::uint32_t top_k : top_ks) { + for (const std::uint32_t batch_size : batches) { + SearchParams params; + params.top_k = top_k; + params.batch_size = batch_size; + params.distance_mode = "warp"; + params.topk_mode = "fused"; + compareExact(database, queries, params, + "Exact coverage dim=" + std::to_string(dim) + + " batch=" + std::to_string(batch_size) + + " K=" + std::to_string(top_k)); + ++cases; + } + } + } + } + } + require(cases == 576, "Exact coverage matrix case count changed"); + std::cout << "Exact coverage matrix: " << cases << " cases\n"; +} + +void testBatchCapacityAndNonWarpDimension() { + constexpr std::array batches = {1, 8, 32, 40, 64, 128}; + for (const std::uint32_t batch_size : batches) { + const VectorDatabase database = + makeCoverageDatabase(65, Metric::kL2, DataType::kFloat32, 101); + const QuerySet queries = + makeCoverageQueries(65, DataType::kFloat32, batch_size + 1U); + SearchParams params; + params.top_k = 10; + params.batch_size = batch_size; + params.distance_mode = "warp"; + params.topk_mode = "fused"; + compareExact(database, queries, params, + "non-warp dim=65 full batch=" + std::to_string(batch_size)); + } + + for (const DataType dtype : {DataType::kFloat32, DataType::kFloat16}) { + for (const Metric metric : + {Metric::kL2, Metric::kInnerProduct, Metric::kCosine}) { + const VectorDatabase database = makeCoverageDatabase(65, metric, dtype); + const QuerySet queries = makeCoverageQueries(65, dtype); + SearchParams params; + params.top_k = 100; + params.batch_size = 8; + params.distance_mode = "warp"; + params.topk_mode = "fused"; + compareExact(database, queries, params, + "non-warp dim=65 dtype/metric coverage"); + } + } +} + +void testExactRecommendedAndFallbackPaths() { + struct RecommendedCase { + std::uint32_t dim; + std::uint32_t top_k; + std::uint32_t query_tile; + std::uint32_t blocks; + }; + constexpr std::array cases = { + RecommendedCase{128, 10, 4, 64}, + RecommendedCase{384, 10, 8, 160}, + RecommendedCase{384, 50, 4, 64}, + }; + for (const RecommendedCase& item : cases) { + const VectorDatabase database = makeCoverageDatabase( + item.dim, Metric::kCosine, DataType::kFloat32); + const QuerySet queries = makeCoverageQueries(item.dim, DataType::kFloat32); + SearchParams params; + params.top_k = item.top_k; + params.batch_size = 64; + params.distance_mode = "warp"; + params.topk_mode = "fused"; + params.exact_query_tile = item.query_tile; + params.exact_fused_blocks = item.blocks; + compareExact(database, queries, params, + "recommended query-tile dim=" + std::to_string(item.dim) + + " K=" + std::to_string(item.top_k)); + } + + VectorDatabase database = makeCoverageDatabase( + 768, Metric::kCosine, DataType::kFloat32); + QuerySet queries = makeCoverageQueries(768, DataType::kFloat32); + SearchParams params; + params.top_k = 10; + params.batch_size = 64; + params.distance_mode = "warp"; + params.topk_mode = "fused"; + params.exact_query_tile = 8; + params.exact_fused_layout = "block_tile"; + requireThrows([&] { (void)GpuExactSearchEngine(database, queries, params); }, + "FP32 dim=768 block-tile must fall back instead of launching"); + + params.exact_fused_layout = "warp_query"; + params.exact_query_tile = 1; + compareExact(database, queries, params, + "FP32 dim=768 safe warp-query fallback"); + + params.top_k = 50; + params.exact_query_tile = 8; + requireThrows([&] { (void)GpuExactSearchEngine(database, queries, params); }, + "K=50 query-tile=8 must be rejected"); + params.exact_query_tile = 1; + compareExact(database, queries, params, + "K=50 query-tile=1 safe fallback"); +} + +IvfFlatIndex makePathologicalIndex(Metric metric, DataType dtype) { + constexpr std::uint64_t num_vectors = 128; + constexpr std::uint32_t dim = 65; + constexpr std::uint32_t nlist = 8; + const VectorDatabase database = + makeCoverageDatabase(dim, metric, dtype, num_vectors); + IvfFlatIndex index; + index.num_vectors = num_vectors; + index.dim = dim; + index.nlist = nlist; + index.dtype = dtype; + index.metric = metric; + index.offsets = {0, 0, 1, 1, 3, 3, 3, 3, num_vectors}; + index.ids.resize(num_vectors); + for (std::uint64_t id = 0; id < num_vectors; ++id) { + index.ids[id] = id; + } + index.values = database.values; + index.half_values = database.half_values; + index.centers.resize(static_cast(nlist) * dim); + for (std::uint32_t center = 0; center < nlist; ++center) { + for (std::uint32_t d = 0; d < dim; ++d) { + index.centers[static_cast(center) * dim + d] = + deterministicValue(center + 11U, d); + } + } + validateIvfFlatIndex(index); + return index; +} + +void testEmptyAndSkewedIvfBuckets() { + for (const DataType dtype : {DataType::kFloat32, DataType::kFloat16}) { + for (const Metric metric : + {Metric::kL2, Metric::kInnerProduct, Metric::kCosine}) { + const IvfFlatIndex index = makePathologicalIndex(metric, dtype); + const QuerySet queries = makeCoverageQueries(65, dtype); + for (const std::uint32_t top_k : {1U, 10U, 50U, 100U}) { + SearchParams params; + params.search_mode = "ivf_flat"; + params.top_k = top_k; + params.batch_size = 8; + params.nlist = index.nlist; + params.nprobe = index.nlist; + params.distance_mode = "warp"; + const SearchResults cpu = cpuIvfFlatSearch(index, queries, params); + std::string error; + for (const std::string& mode : {"warp", "bucket_major"}) { + params.distance_mode = mode; + GpuIvfFlatSearchEngine engine(index, queries, params); + const SearchResults gpu = engine.search(queries); + require(resultsMatch(cpu, gpu, 5e-5F, &error), + "empty/skewed IVF " + mode + ": " + error); + } + } + } + } + std::cout << "IVF empty/skewed buckets: 48 cases\n"; +} + +} // namespace + +int main() { + try { + testExactCoverageMatrix(); + testBatchCapacityAndNonWarpDimension(); + testExactRecommendedAndFallbackPaths(); + testEmptyAndSkewedIvfBuckets(); + std::cout << "Stage 8 stability coverage passed\n"; + return EXIT_SUCCESS; + } catch (const std::exception& error) { + std::cerr << "Stage 8 stability failure: " << error.what() << '\n'; + return EXIT_FAILURE; + } +} diff --git a/09_vector_retrieval/PurplePulse/tests/test_benchmark_adaptive_nprobe.py b/09_vector_retrieval/PurplePulse/tests/test_benchmark_adaptive_nprobe.py new file mode 100644 index 00000000..436d1267 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/test_benchmark_adaptive_nprobe.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 + +import importlib.util +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).parents[1] / "scripts" / "benchmark_adaptive_nprobe.py" +SPEC = importlib.util.spec_from_file_location("benchmark_adaptive_nprobe", SCRIPT) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +SPEC.loader.exec_module(MODULE) + + +class BenchmarkAdaptiveNprobeTests(unittest.TestCase): + def test_extracts_actual_probe_triple(self): + values = MODULE.extract_triple( + "实际 nprobe min/avg/max: 64/137.25/224", + r"实际 nprobe min/avg/max: ([0-9.eE+-]+)/([0-9.eE+-]+)/([0-9.eE+-]+)", + ) + self.assertEqual(values, (64.0, 137.25, 224.0)) + + def test_recall(self): + mean, minimum = MODULE.recall([[1, 2], [3, 4]], [[1, 9], [4, 3]]) + self.assertEqual((mean, minimum), (0.75, 0.5)) + + +if __name__ == "__main__": + unittest.main() diff --git a/09_vector_retrieval/PurplePulse/tests/test_benchmark_exact_breakdown.py b/09_vector_retrieval/PurplePulse/tests/test_benchmark_exact_breakdown.py new file mode 100644 index 00000000..543a7d28 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/test_benchmark_exact_breakdown.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 + +import importlib.util +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).parents[1] +SPEC = importlib.util.spec_from_file_location( + "benchmark_exact_breakdown", ROOT / "scripts" / "benchmark_exact_breakdown.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +SPEC.loader.exec_module(MODULE) + + +class BenchmarkExactBreakdownTests(unittest.TestCase): + def test_parses_breakdown_and_shares(self): + text = """\ +向量库: 1000000 x 384 +查询数: 1000 +top_k: 50 +batch_size: 64 +GPU 缓冲区: 1005.2 MiB +平均常驻查询时间: 300.0 ms +run P50: 299.0 ms +run P99: 305.0 ms +常驻 QPS: 3333.3 +剖析距离-only kernel: 100.0 ms +剖析局部 Top-K 估算: 150.0 ms +剖析融合 kernel: 250.0 ms +剖析最终归并 kernel: 10.0 ms +""" + row = MODULE.parse_profile_output(text) + self.assertEqual(row["top_k"], 50) + self.assertEqual(row["kernel_pipeline_ms"], 260.0) + self.assertAlmostEqual(row["distance_share"], 100.0 / 260.0) + self.assertAlmostEqual(row["local_topk_share"], 150.0 / 260.0) + + def test_compares_reference_results(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + first = root / "first.txt" + second = root / "second.txt" + first.write_text("0 7 1.25\n0 8 1.0\n") + second.write_text("0 7 1.25001\n0 8 1.0\n") + MODULE.compare_results(first, second, 2e-5) + + def test_rejects_candidate_mismatch(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + first = root / "first.txt" + second = root / "second.txt" + first.write_text("0 7 1.25\n") + second.write_text("0 8 1.25\n") + with self.assertRaises(ValueError): + MODULE.compare_results(first, second, 1e-5) + + def test_rejects_rank_order_mismatch(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + first = root / "first.txt" + second = root / "second.txt" + first.write_text("0 7 1.25\n0 8 1.0\n") + second.write_text("0 8 1.0\n0 7 1.25\n") + with self.assertRaises(ValueError): + MODULE.compare_results(first, second, 1e-5) + + +if __name__ == "__main__": + unittest.main() diff --git a/09_vector_retrieval/PurplePulse/tests/test_benchmark_exact_query_tile.py b/09_vector_retrieval/PurplePulse/tests/test_benchmark_exact_query_tile.py new file mode 100644 index 00000000..3db35588 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/test_benchmark_exact_query_tile.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +import importlib.util +import sys +import unittest +from pathlib import Path + + +ROOT = Path(__file__).parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +SPEC = importlib.util.spec_from_file_location( + "benchmark_exact_query_tile", ROOT / "scripts" / "benchmark_exact_query_tile.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +SPEC.loader.exec_module(MODULE) + + +class BenchmarkExactQueryTileTests(unittest.TestCase): + def test_parses_variant(self): + label, configs = MODULE.parse_variant( + f"tile2=10:{ROOT / 'README.md'},50:{ROOT / 'CMakeLists.txt'}" + ) + self.assertEqual(label, "tile2") + self.assertEqual([top_k for top_k, _ in configs], [10, 50]) + + def test_rejects_unsafe_label(self): + with self.assertRaises(ValueError): + MODULE.parse_variant(f"../tile=10:{ROOT / 'README.md'}") + + def test_parses_search_output(self): + text = """\ +向量库: 1000000 x 128 +查询数: 1000 +top_k: 10 +batch_size: 64 +exact_query_tile: 4 +exact_fused_layout: block_tile +exact_fused_blocks: 128 +GPU 缓冲区: 488.4 MiB +平均常驻查询时间: 50.0 ms +run P50: 49.0 ms +run P99: 52.0 ms +常驻 QPS: 20000.0 +平均融合距离+局部 Top-K kernel: 48.0 ms +平均最终 Top-K kernel: 0.2 ms +""" + row = MODULE.parse_search_output(text, "tile4") + self.assertEqual(row["exact_query_tile"], 4) + self.assertEqual(row["exact_fused_layout"], "block_tile") + self.assertEqual(row["exact_fused_blocks"], 128) + self.assertEqual(row["qps"], 20000.0) + self.assertEqual(row["fused_kernel_ms"], 48.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/09_vector_retrieval/PurplePulse/tests/test_benchmark_faiss.py b/09_vector_retrieval/PurplePulse/tests/test_benchmark_faiss.py new file mode 100644 index 00000000..ef82d465 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/test_benchmark_faiss.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 + +import importlib.util +import struct +import sys +import tempfile +import unittest +from pathlib import Path + +import numpy as np + + +SCRIPT = Path(__file__).parents[1] / "scripts" / "benchmark_faiss.py" +SPEC = importlib.util.spec_from_file_location("benchmark_faiss", SCRIPT) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +sys.modules[SPEC.name] = MODULE +SPEC.loader.exec_module(MODULE) + + +class BenchmarkFaissTests(unittest.TestCase): + def test_reads_custom_vector_files_as_memmap(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + database = root / "database.bin" + queries = root / "queries.bin" + values = np.arange(12, dtype=" None: + value_dtype = " None: + with path.open("w", newline="") as destination: + writer = csv.DictWriter(destination, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +class PlotResultsTests(unittest.TestCase): + def test_generates_all_figures_from_minimal_fixture(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + results = root / "results" + output = root / "figures" + results.mkdir() + + quality_fields = ["nprobe", "average_ms", "qps", "recall_at_k"] + for top_k in (10, 50, 100): + write_csv( + results / f"ivf_k{top_k}.csv", + quality_fields, + [ + { + "nprobe": 16, + "average_ms": 2.0 + top_k / 100.0, + "qps": 5000 - top_k, + "recall_at_k": 0.9, + }, + { + "nprobe": 32, + "average_ms": 3.0 + top_k / 100.0, + "qps": 4000 - top_k, + "recall_at_k": 0.97, + }, + ], + ) + + faiss_fields = [ + "backend", + "index_type", + "top_k", + "nprobe", + "average_query_ms", + "qps", + "recall_at_k", + ] + write_csv( + results / "faiss_gpu.csv", + faiss_fields, + [ + { + "backend": "gpu", + "index_type": "ivf_flat", + "top_k": top_k, + "nprobe": nprobe, + "average_query_ms": 2.5 if nprobe == 16 else 3.5, + "qps": 4500 if nprobe == 16 else 3500, + "recall_at_k": 0.89 if nprobe == 16 else 0.96, + } + for top_k in (10, 50, 100) + for nprobe in (16, 32) + ], + ) + + batch_fields = ["top_k", "batch_size", "qps"] + write_csv( + results / "optimized_v1_batch_sweep.csv", + batch_fields, + [ + {"top_k": top_k, "batch_size": batch, "qps": 1000 + batch} + for top_k in (10, 50, 100) + for batch in (8, 64) + ], + ) + + paths = MODULE.generate_figures(results, output) + + self.assertEqual( + {path.name for path in paths}, + {"recall-latency.svg", "recall-qps.svg", "batch-qps.svg"}, + ) + for path in paths: + contents = path.read_text() + self.assertIn("", contents) + + +if __name__ == "__main__": + unittest.main() diff --git a/09_vector_retrieval/PurplePulse/tests/test_stage6_tools.py b/09_vector_retrieval/PurplePulse/tests/test_stage6_tools.py new file mode 100644 index 00000000..afe2ad84 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/test_stage6_tools.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 + +import importlib.util +import csv +import sys +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + + +def load_module(name: str, filename: str): + spec = importlib.util.spec_from_file_location(name, ROOT / "scripts" / filename) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +EXACT = load_module("benchmark_exact_stage6", "benchmark_exact.py") +RUNNER = load_module("run_real_benchmarks_stage6", "run_real_benchmarks.py") +PREPARE = load_module("prepare_real_datasets_stage6", "prepare_real_datasets.py") + + +class Stage6ToolTests(unittest.TestCase): + def test_partitioned_result_falls_back_on_recall_loss(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + fields = ["nprobe", "recall_at_k", "qps"] + for name, recall, qps in ( + ("partitioned.csv", 0.89, 1200), + ("full.csv", 0.90, 1000), + ): + with (root / name).open("w", newline="") as output: + writer = csv.DictWriter(output, fieldnames=fields) + writer.writeheader() + writer.writerow({"nprobe": 64, "recall_at_k": recall, "qps": qps}) + decision = RUNNER.choose_partitioned_result( + root / "partitioned.csv", + root / "full.csv", + root / "effective.csv", + maximum_recall_loss=1e-4, + ) + self.assertEqual(decision["selected_mode"], "full_heap") + self.assertEqual( + (root / "effective.csv").read_text(), + (root / "full.csv").read_text(), + ) + + def test_exact_config_parser_and_output_parser(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + first = root / "k10.conf" + second = root / "k100.conf" + first.write_text("top_k = 10\n") + second.write_text("top_k = 100\n") + self.assertEqual( + EXACT.parse_configs(f"10:{first},100:{second}"), + [(10, first), (100, second)], + ) + self.assertEqual(EXACT.extract("常驻 QPS: 1234.5", r"常驻 QPS: ([0-9.]+)"), 1234.5) + + def test_build_metadata_parser(self): + output = """\ +迭代/训练样本: 15/100000 +建库线程: 16 +构建时间: 1234.5 ms +保存时间: 67.8 ms +桶大小 min/avg/max: 10/1000.25/2048 +空桶: 3 +索引大小: 987654 bytes +""" + row = RUNNER.parse_build_stats(output, "fixture", 1024) + self.assertEqual(row["training_iterations"], 15) + self.assertEqual(row["maximum_bucket"], 2048) + self.assertEqual(row["index_bytes"], 987654) + + def test_known_public_checksums_are_pinned(self): + self.assertEqual(len(PREPARE.SIFT_MD5), 32) + self.assertEqual(len(PREPARE.VIBE_SHA256), 64) + + +if __name__ == "__main__": + unittest.main() diff --git a/09_vector_retrieval/PurplePulse/tests/test_stage9_tools.py b/09_vector_retrieval/PurplePulse/tests/test_stage9_tools.py new file mode 100644 index 00000000..fe3812ce --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/test_stage9_tools.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 + +import importlib.util +import sys +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + + +def load_module(name: str, filename: str): + spec = importlib.util.spec_from_file_location(name, ROOT / "scripts" / filename) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +REPRODUCE = load_module("stage9_reproduce", "reproduce.py") +VALIDATE = load_module("stage9_validate", "validate_release.py") + + +class Stage9ToolTests(unittest.TestCase): + def test_reproduction_plan_is_project_rooted_and_complete(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + args = REPRODUCE.parse_args([ + "--project-root", str(root), + "--dataset", "sift1m", + "--skip-download", + "--dry-run", + ]) + state_root, steps = REPRODUCE.build_plan(args) + names = [step["name"] for step in steps] + self.assertEqual( + names, + ["configure", "build", "test", "prepare", + "benchmark:sift1m", "plot:sift1m", "report", "validate"], + ) + self.assertTrue(str(state_root).startswith(str(root))) + for step in steps: + self.assertTrue(str(step["log"]).startswith(str(root))) + + def test_checkpoint_round_trip(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "checkpoint.json" + state = {"completed": ["configure"], "steps": {}} + REPRODUCE.write_checkpoint(path, state) + self.assertEqual(REPRODUCE.load_checkpoint(path), state) + + def test_csv_and_pdf_validation_helpers(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + csv_path = root / "rows.csv" + csv_path.write_text("name,status\nfixture,passed\n", encoding="utf-8") + self.assertEqual( + VALIDATE.validate_csv(csv_path, {"name", "status"}), 1 + ) + pdf_path = root / "report.pdf" + pdf_path.write_bytes(b"%PDF-1.4\n" + b"0" * 2048) + self.assertGreater(VALIDATE.validate_pdf(pdf_path), 1024) + + +if __name__ == "__main__": + unittest.main() diff --git a/09_vector_retrieval/PurplePulse/tests/unit_tests.cpp b/09_vector_retrieval/PurplePulse/tests/unit_tests.cpp new file mode 100644 index 00000000..a3055391 --- /dev/null +++ b/09_vector_retrieval/PurplePulse/tests/unit_tests.cpp @@ -0,0 +1,365 @@ +#include +#include +#include +#include +#include + +#include "file_io.h" +#include "search.h" + +namespace { + +void require(bool condition, const std::string& message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +template +void requireThrows(Operation operation, const std::string& message) { + try { + operation(); + } catch (const std::runtime_error&) { + return; + } + throw std::runtime_error(message); +} + +VectorDatabase makeDatabase(Metric metric, DataType dtype) { + VectorDatabase database; + database.num_vectors = 5; + database.dim = 2; + database.metric = metric; + database.dtype = dtype; + if (dtype == DataType::kFloat32) { + database.values = { + 1.0F, 0.0F, // id 0 + 0.0F, 1.0F, // id 1 + 1.0F, 1.0F, // id 2 + 2.0F, 0.0F, // id 3 + -1.0F, 0.0F // id 4 + }; + } else { + // IEEE 754 binary16: 0=0x0000, 1=0x3c00, 2=0x4000, -1=0xbc00。 + database.half_values = {0x3c00, 0x0000, 0x0000, 0x3c00, 0x3c00, + 0x3c00, 0x4000, 0x0000, 0xbc00, 0x0000}; + } + return database; +} + +QuerySet makeQueries(DataType dtype) { + QuerySet queries; + queries.num_queries = 2; + queries.dim = 2; + queries.dtype = dtype; + if (dtype == DataType::kFloat32) { + queries.values = {1.0F, 0.0F, 0.0F, 1.0F}; + } else { + queries.half_values = {0x3c00, 0x0000, 0x0000, 0x3c00}; + } + return queries; +} + +void testMetric(Metric metric, DataType dtype) { + const VectorDatabase database = makeDatabase(metric, dtype); + const QuerySet queries = makeQueries(dtype); + SearchParams params; + params.top_k = 3; + params.batch_size = 2; + + const SearchResults cpu = cpuExactSearch(database, queries, params); + params.topk_mode = "simple"; + const SearchResults gpu_simple = gpuExactSearch(database, queries, params); + params.topk_mode = "block"; + const SearchResults gpu_block = gpuExactSearch(database, queries, params); + params.topk_mode = "two_stage"; + const SearchResults gpu_two_stage = gpuExactSearch(database, queries, params); + params.topk_mode = "fused"; + const SearchResults gpu_fused = gpuExactSearch(database, queries, params); + params.exact_query_tile = 2; + const SearchResults gpu_fused_tile2 = + gpuExactSearch(database, queries, params); + params.exact_query_tile = 4; + const SearchResults gpu_fused_tile4 = + gpuExactSearch(database, queries, params); + params.exact_query_tile = 8; + const SearchResults gpu_fused_tile8 = + gpuExactSearch(database, queries, params); + params.exact_fused_layout = "block_tile"; + const SearchResults gpu_fused_block_tile = + gpuExactSearch(database, queries, params); + params.exact_fused_layout = "warp_query"; + params.exact_query_tile = 1; + std::string error; + require(resultsMatch(cpu, gpu_simple, 1e-5F, &error), + "simple Top-K: " + error); + require(resultsMatch(cpu, gpu_block, 1e-5F, &error), "block Top-K: " + error); + require(resultsMatch(cpu, gpu_two_stage, 1e-5F, &error), + "two-stage Top-K: " + error); + require(resultsMatch(cpu, gpu_fused, 1e-5F, &error), "fused Top-K: " + error); + require(resultsMatch(cpu, gpu_fused_tile2, 1e-5F, &error), + "fused query-tile=2 Top-K: " + error); + require(resultsMatch(cpu, gpu_fused_tile4, 1e-5F, &error), + "fused query-tile=4 Top-K: " + error); + require(resultsMatch(cpu, gpu_fused_tile8, 1e-5F, &error), + "fused query-tile=8 Top-K: " + error); + require(resultsMatch(cpu, gpu_fused_block_tile, 1e-5F, &error), + "fused block-tile Top-K: " + error); + + QuerySet initial_queries = queries; + initial_queries.num_queries = 1; + if (dtype == DataType::kFloat32) { + initial_queries.values.resize(initial_queries.dim); + } else { + initial_queries.half_values.resize(initial_queries.dim); + } + // 首次校验只传一个 query,引擎仍应按 params.batch_size 分配, + // 并在后续查询中处理更多 query。 + GpuExactSearchEngine resident_engine(database, initial_queries, params); + SearchStats first_stats; + SearchStats second_stats; + const SearchResults resident_first = + resident_engine.search(queries, &first_stats); + const SearchResults resident_second = + resident_engine.search(queries, &second_stats); + require(resultsMatch(cpu, resident_first, 1e-5F, &error), + "常驻引擎首次查询: " + error); + require(resultsMatch(resident_first, resident_second, 0.0F, &error), + "常驻引擎重复查询: " + error); + require(resident_engine.databaseH2DMilliseconds() >= 0.0 && + resident_engine.deviceBytes() > 0, + "数据库 H2D 计时不应为负数且设备缓冲区应非空"); + require( + first_stats.database_h2d_ms == 0.0 && second_stats.database_h2d_ms == 0.0, + "常驻查询不应重复计入数据库 H2D"); + const double distance_only_ms = + resident_engine.profileDistanceOnlyMilliseconds(queries, 0, 1); + require(distance_only_ms >= 0.0, + "fused distance-only 差分剖析时间不应为负数"); + + require(cpu.size() == 2 && cpu[0].size() == 3, "结果形状不正确"); + if (metric == Metric::kL2 || metric == Metric::kCosine) { + require(cpu[0][0].id == 0, "L2 第一名应当是 id 0"); + } else { + require(cpu[0][0].id == 3, "内积第一名应当是 id 3"); + } +} + +void testBoundaryCases() { + VectorDatabase database; + database.num_vectors = 5; + database.dim = 2; + database.metric = Metric::kCosine; + database.dtype = DataType::kFloat32; + database.values = { + 0.0F, 0.0F, // id 0: zero vector + 1.0F, 0.0F, // id 1 + 1.0F, 0.0F, // id 2: tie with id 1 + 0.0F, 1.0F, // id 3 + -1.0F, 0.0F // id 4 + }; + + QuerySet queries; + queries.num_queries = 5; // 故意不能被 batch_size=2 整除。 + queries.dim = 2; + queries.dtype = DataType::kFloat32; + queries.values = { + 0.0F, 0.0F, // zero query: every score is zero + 1.0F, 0.0F, 0.0F, 1.0F, -1.0F, 0.0F, 1.0F, 1.0F, + }; + + SearchParams params; + params.top_k = static_cast(database.num_vectors); + params.batch_size = 2; + const SearchResults cpu = cpuExactSearch(database, queries, params); + require(cpu.size() == queries.num_queries && + cpu.front().size() == database.num_vectors, + "top_k=num_vectors 的结果形状不正确"); + for (std::uint64_t id = 0; id < database.num_vectors; ++id) { + require(cpu[0][id].id == id && cpu[0][id].score == 0.0F, + "零向量 cosine 应按较小 ID 打破平局"); + } + require(cpu[1][0].id == 1 && cpu[1][1].id == 2, + "相同 cosine 分数应按较小 ID 打破平局"); + + std::string error; + for (const std::string& distance_mode : {"simple", "warp"}) { + params.distance_mode = distance_mode; + for (const std::string& topk_mode : + {"simple", "block", "two_stage", "fused"}) { + if (topk_mode == "fused" && distance_mode != "warp") { + continue; + } + params.topk_mode = topk_mode; + const SearchResults gpu = gpuExactSearch(database, queries, params); + require(resultsMatch(cpu, gpu, 1e-5F, &error), + distance_mode + "/" + topk_mode + " 边界测试: " + error); + } + } +} + +VectorDatabase makeLargeKDatabase(DataType dtype) { + VectorDatabase database; + database.num_vectors = 128; + database.dim = 4; + database.metric = Metric::kL2; + database.dtype = dtype; + const std::uint16_t positive_one = 0x3c00; + const std::uint16_t negative_one = 0xbc00; + for (std::uint64_t vector_id = 0; vector_id < database.num_vectors; + ++vector_id) { + for (std::uint32_t d = 0; d < database.dim; ++d) { + const bool positive = ((vector_id >> d) & 1U) != 0; + if (dtype == DataType::kFloat32) { + database.values.push_back(positive ? 1.0F : -1.0F); + } else { + database.half_values.push_back(positive ? positive_one : negative_one); + } + } + } + return database; +} + +QuerySet makeLargeKQueries(DataType dtype) { + QuerySet queries; + queries.num_queries = 3; + queries.dim = 4; + queries.dtype = dtype; + const std::vector values = {1.0F, 1.0F, 1.0F, 1.0F, -1.0F, 1.0F, + -1.0F, 1.0F, 1.0F, -1.0F, 1.0F, -1.0F}; + if (dtype == DataType::kFloat32) { + queries.values = values; + } else { + for (const float value : values) { + queries.half_values.push_back(value > 0.0F ? 0x3c00 : 0xbc00); + } + } + return queries; +} + +void testFusedLargeK() { + for (const DataType dtype : {DataType::kFloat32, DataType::kFloat16}) { + const VectorDatabase database = makeLargeKDatabase(dtype); + const QuerySet queries = makeLargeKQueries(dtype); + for (const std::uint32_t top_k : {50U, 100U}) { + SearchParams params; + params.top_k = top_k; + params.batch_size = 2; + params.distance_mode = "warp"; + params.topk_mode = "fused"; + const SearchResults cpu = cpuExactSearch(database, queries, params); + GpuExactSearchEngine fused_engine(database, queries, params); + const SearchResults fused = fused_engine.search(queries); + std::string error; + require(resultsMatch(cpu, fused, 1e-5F, &error), + "fused large-K: " + error); + } + } +} + +void testFusedDeviceMemory() { + VectorDatabase database; + database.num_vectors = 10000; + database.dim = 1; + database.metric = Metric::kL2; + database.dtype = DataType::kFloat32; + database.values.resize(database.num_vectors, 0.0F); + + QuerySet queries; + queries.num_queries = 1; + queries.dim = 1; + queries.dtype = DataType::kFloat32; + queries.values = {0.0F}; + + SearchParams params; + params.top_k = 100; + params.batch_size = 64; + params.distance_mode = "warp"; + params.topk_mode = "block"; + GpuExactSearchEngine matrix_engine(database, queries, params); + params.topk_mode = "fused"; + GpuExactSearchEngine fused_engine(database, queries, params); + require(fused_engine.deviceBytes() < matrix_engine.deviceBytes(), + "规模化 fused exact 应减少设备缓冲区占用"); +} + +void testInvalidInputs() { + VectorDatabase database = makeDatabase(Metric::kL2, DataType::kFloat32); + QuerySet queries = makeQueries(DataType::kFloat32); + SearchParams params; + + params.top_k = 0; + requireThrows([&] { validateInputs(database, queries, params); }, + "top_k=0 应被拒绝"); + params.top_k = 1; + params.batch_size = 0; + requireThrows([&] { validateInputs(database, queries, params); }, + "batch_size=0 应被拒绝"); + params.batch_size = 1; + + params.distance_mode = "simple"; + params.topk_mode = "fused"; + requireThrows([&] { validateInputs(database, queries, params); }, + "fused Top-K 与 simple distance 组合应被拒绝"); + params.distance_mode = "warp"; + params.topk_mode = "two_stage"; + + params.exact_query_tile = 3; + requireThrows([&] { validateInputs(database, queries, params); }, + "不支持的 exact_query_tile 应被拒绝"); + params.exact_query_tile = 2; + requireThrows([&] { validateInputs(database, queries, params); }, + "非 fused Top-K 不应接受 query tile"); + params.exact_query_tile = 1; + params.exact_fused_blocks = 32; + requireThrows([&] { validateInputs(database, queries, params); }, + "非 fused Top-K 不应接受 exact_fused_blocks"); + params.exact_fused_blocks = 0; + params.topk_mode = "fused"; + params.exact_fused_layout = "invalid"; + requireThrows([&] { validateInputs(database, queries, params); }, + "未知 exact_fused_layout 应被拒绝"); + params.exact_fused_layout = "block_tile"; + requireThrows([&] { validateInputs(database, queries, params); }, + "block_tile 不应接受 query tile 1"); + params.exact_fused_layout = "warp_query"; + params.topk_mode = "two_stage"; + + VectorDatabase empty_database = database; + empty_database.num_vectors = 0; + empty_database.values.clear(); + requireThrows([&] { validateInputs(empty_database, queries, params); }, + "空向量库应被拒绝"); + + QuerySet empty_queries = queries; + empty_queries.num_queries = 0; + empty_queries.values.clear(); + requireThrows([&] { validateInputs(database, empty_queries, params); }, + "空查询集应被拒绝"); + + QuerySet wrong_length = queries; + wrong_length.values.pop_back(); + requireThrows([&] { validateInputs(database, wrong_length, params); }, + "数据长度与元数据不一致时应被拒绝"); +} + +} // namespace + +int main() { + try { + for (const DataType dtype : {DataType::kFloat32, DataType::kFloat16}) { + testMetric(Metric::kL2, dtype); + testMetric(Metric::kInnerProduct, dtype); + testMetric(Metric::kCosine, dtype); + } + testBoundaryCases(); + testFusedLargeK(); + testFusedDeviceMemory(); + testInvalidInputs(); + std::cout << "FP32/FP16 的 CPU/GPU 正确性与边界测试通过\n"; + return EXIT_SUCCESS; + } catch (const std::exception& error) { + std::cerr << "测试失败: " << error.what() << '\n'; + return EXIT_FAILURE; + } +}