[Bug]: FP16 cosine / inner-product search accumulates in FP16 on AVX-512 FP16 CPUs, costing recall (0.965 against 0.998)

未关闭
#786 1 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 1 天内回复

@richyreachy 已经在做这个了。

开始于 2026年9月29日。

评估

这个 Issue 还没有评估数据。

描述

Description

On a CPU with AVX-512 FP16 (Sapphire Rapids and later), HNSW search over a VECTOR_FP16 field with the COSINE or IP metric returns noticeably wrong neighbours. The cause is the distance kernel: it multiplies and accumulates in FP16 (vfmadd231ph into __m512h accumulators) and widens to FP32 only for the final horizontal add. The same data searched with L2 is accurate, because the L2 batch path goes through turbo, which widens to FP32.

Measured through the C API (zvec-rust 0.7.2 prebuilt, x86_64-unknown-linux-gnu), with 1024-d unit vectors, HNSW m=32, ef_construction=500, ef=700, and 4 segments:

Field / metric recall@10, 50k synthetic recall@10, 131,924 real BGE-M3 vectors max |score − exact cosine|
FP32 / COSINE 0.9975 1.0000 1.0e-6
FP16 / COSINE 0.9650 0.9985 3.7e-4 / 4.7e-4
FP16 / IP 0.9755 0.9994 2.3e-4 / 2.7e-4
FP16 / L2 (same unit vectors) 0.9960 0.9998 2.1e-5 / 4.1e-5
Exact f32 search over the FP16-rounded vectors (the floor that storage rounding sets) 0.9970 0.9998 1.3e-5 / 2.9e-5

The loss is not the graph. A linear scan (is_linear=true) over the FP16 field loses the same amount: 0.9820 against 1.0000 at 5,000 documents. Rounding a unit vector to FP16 perturbs a cosine by about 1e-5. The engine's scores are off by 30 times that.

Because the fast path is selected at runtime, the same index returns different neighbours on different machines. On CPUs without AVX-512 FP16 (for example AMD Zen 4 or Ice Lake), dispatch falls through to the AVX-512F or AVX2 kernels, which convert with vcvtph2ps and accumulate in FP32.

Where it happens (paths on main, 53c1bb6; the ailego kernels have the same design in v0.7.0):

  • src/ailego/math_batch/inner_product_distance_batch_impl_fp16_avx512fp16.cc:32,51,71: accs[i] = _mm512_setzero_ph(), then accs[i] = _mm512_fmadd_ph(data_regs[i], q, accs[i]) over the whole dimension. At dim 1024, each of the 32 lanes sums 32 products in FP16, and the result is widened only by HorizontalAdd_FP16_V512 (src/ailego/math/matrix_utility.i:257).
  • src/ailego/math_batch/inner_product_distance_batch_dispatch.cc:113-117,184-188 prefers this kernel whenever AVX512_FP16 is set.
  • src/core/metric/cosine_metric.cc:210 (the batch distance) and :183 (the single distance) route FP16 cosine to it through CosineDistanceMatrix / CosineDistanceBatch → InnerProductMatrix<Float16> / InnerProductDistanceBatch<Float16>, as does the IP metric.
  • The single-pair kernel src/ailego/math/inner_product_matrix_fp16_avx512fp16.cc:29-38,62 is the same design: two __m512h accumulators, which are also added together in FP16 (_mm512_add_ph). The dispatch is at inner_product_matrix_fp16_dispatch.cc:62-66.
  • The squared-Euclidean single-pair kernel euclidean_distance_matrix_fp16_avx512fp16.cc:29-39 accumulates in FP16 the same way. The L2 batch path uses turbo (euclidean_metric.cc:614-620), which is why L2 search stays accurate.

The turbo registry already rejects this design for the same reason. src/turbo/turbo.cc:359-362: "the AVX512-FP16 kernels under distance/avx512_fp16/ are not registered: they accumulate in FP16, which loses enough precision to reorder close neighbors", and turbo.cc:190: "Raw FP16 distances always use FP32 arithmetic". The ailego cosine and IP paths are the ones still using FP16 accumulation.

Related, lower priority (ARM):

  • turbo/distance/neon_fp16/fp16/cosine.cc:28-49 (added in #723, not yet in a release) keeps native FP16 accumulation for the kFp16-quantized cosine path on CPUs with FEAT_FP16 (turbo.cc:397-407). It has four float16x8_t accumulators, which are also summed in FP16. The comment there already calls it approximate. Unit-normalized inputs don't avoid the problem, because the error above comes from rounding the partial sums, not from overflow.
  • ACCUM_FP16_1X1_NEON in src/ailego/math/distance_matrix_accum_fp16.i:816-837 has a single float16x8_t accumulator (vfmaq_f16), which is 128 products per lane at dim 1024. As far as we can tell, the default CMake build doesn't compile it, because the *_neon.cc and *_dispatch.cc TUs get -march=armv8-a (src/ailego/CMakeLists.txt:94-111), and that leaves __ARM_FEATURE_FP16_VECTOR_ARITHMETIC undefined. A macOS arm64 libzvec_c_api.dylib we checked has no FP16 fmla .8h. It would become live if those TUs were ever built for armv8.2-a+fp16. In emulation it gives recall@10 0.92 on the 5k synthetic set.

Confirmation that this kernel is the cause: an exact emulation of compute_one_to_many_inner_product_avx512fp16_fp16 in numpy (32 FP16 lanes, one FP16 rounding per FMA, FP32 horizontal add) reproduces the engine's numbers. At 5,000 documents it gives recall 0.9820 and max error 3.00e-4, identical to the engine's 0.9820 and 3.00e-4. At 50,000 documents it gives 0.9660 and 3.67e-4, against the engine's 0.9650 and 3.67e-4. The same emulation with FP32 accumulation over the same FP16 data gives 0.9980 and 2.8e-5.

Expected: FP16 storage costs only storage rounding (the last table row). This is what other engines do:

  • pgvector halfvec converts with F16C and accumulates in __m256 FP32.
  • Milvus/Knowhere fp16_vec_inner_product_avx512 uses _mm512_cvtph_ps with FP32 FMA.
  • Qdrant converts float16 to f32 for scoring and accumulates NEON f16 metrics in f32.
  • NumKong/SimSIMD: "Sapphire Rapids has native VFMADDPH … but NumKong does not use it for general dot products — Float16 accumulation loses precision."

Suggested fix, in order of preference:

  1. For raw FP16 dense distances (IP, cosine, squared L2; single-pair and batch), convert to FP32 and accumulate in FP32 (_mm512_cvtph_ps + _mm512_fmadd_ps, as the AVX-512F kernels and turbo already do). (Edit: an earlier version of this issue said this costs about the same per element. That was not measured. Per 32 elements the FP32 loop issues one load, one vextracti64x4, two vcvtph2ps and two FP32 FMAs, against one load and one vfmadd231ph, so compute-bound, cache-resident cases will be slower. For large dimensions, where HNSW search is dominated by memory access, we expect a small end-to-end cost, but we have not benchmarked it. turbo.cc:359-362 reports the FP16 kernels only helping for cache-resident dims <= 256.) The same applies to the NEON FP16 paths listed above.
  2. If the native FP16 FMA is kept for speed, flush the FP16 partial sums to FP32 accumulators every few iterations (for example every 4 steps, as NumKong does for its mini-float paths), and add the accumulators in FP32 rather than with _mm512_add_ph.
  3. Either way, add a precision test that compares recall with an FP32-accumulating reference, not only closeness to a scalar kernel. The FP16 scalar and SIMD kernels can agree with each other and still both be wrong.

We'd be happy to send a PR for option 1: FP32 accumulation in inner_product_distance_batch_impl_fp16_avx512fp16.cc and inner_product_matrix_fp16_avx512fp16.cc (plus the L2 single-pair kernel), with a test that fails under FP16 accumulation, either recall against exact search on skewed data like the repro below or a direct distance-error bound. Before we write it, do you agree with this direction, or would you rather drop the AVX512-FP16 dispatch for these kernels altogether?

Steps to Reproduce
# numpy only: emulates compute_one_to_many_inner_product_avx512fp16_fp16
# (32 fp16 lanes, vfmadd231ph, fp32 horizontal add) against fp32 accumulation
# over the same fp16 data.
import numpy as np
rng = np.random.default_rng(0)
dim, n, nq, k = 1024, 20000, 100, 10
# Vectors share a common direction (top cosines ~0.8), as real sentence embeddings do.
cent = rng.uniform(-1, 0, (n // 200, dim)); cent /= np.linalg.norm(cent, axis=1, keepdims=True)
def unit(x): return x / np.linalg.norm(x, axis=-1, keepdims=True)
docs = unit(cent[np.arange(n) % (n // 200)] + 0.35 * rng.uniform(-1, 0, (n, dim)))
qs = unit(cent[(np.arange(nq) * 7) % (n // 200)] + 0.35 * rng.uniform(-1, 0, (nq, dim)))
D, Q = docs.astype(np.float16), qs.astype(np.float16)

def ip_fp16_lanes(D, q, lanes=32):
    acc = np.zeros((D.shape[0], lanes), np.float16)
    for s in range(0, D.shape[1], lanes):   # one FMA per step, rounded to fp16
        acc = (acc.astype(np.float64) + D[:, s:s+lanes].astype(np.float64) * q[s:s+lanes].astype(np.float64)).astype(np.float16)
    return acc.astype(np.float32).sum(1)     # HorizontalAdd_FP16_V512: widen, then fp32 adds

hit32 = hit16 = 0; err32 = err16 = 0.0
for i in range(nq):
    exact = docs @ qs[i]
    truth = set(np.argsort(-exact)[:k])
    s32 = D.astype(np.float32) @ Q[i].astype(np.float32)
    s16 = ip_fp16_lanes(D, Q[i])
    for s, name in ((s32, 32), (s16, 16)):
        top = np.argsort(-s)[:k]
        h = len(truth & set(top)); e = np.abs(s[top] - exact[top]).max()
        if name == 32: hit32 += h; err32 = max(err32, e)
        else: hit16 += h; err16 = max(err16, e)
print(f"fp32 accumulation over fp16 data: recall@{k} {hit32/(nq*k):.4f}  max|score err| {err32:.1e}")
print(f"fp16 accumulation (32 lanes):     recall@{k} {hit16/(nq*k):.4f}  max|score err| {err16:.1e}")
# Our run prints:
# fp32 accumulation over fp16 data: recall@10 0.9970  max|score err| 3.6e-05
# fp16 accumulation (32 lanes):     recall@10 0.9700  max|score err| 3.1e-04

Against the engine itself, on a Sapphire Rapids host:

  1. Create a collection with a VECTOR_FP16 field (dim 1024), COSINE, and HNSW (m=32, ef_construction=500).
  2. Insert 50,000 unit vectors as FP16, then optimize().
  3. Query 200 FP16 unit vectors with topk=10, ef=700, and compare with exact search in FP32. Recall@10 is 0.965.
  4. Repeat with is_linear=true: the loss is the same.
  5. Repeat with metric L2 on the same vectors: recall@10 is 0.996.
  6. Run the same binary on a CPU without avx512_fp16: the COSINE result matches the L2 one. We expect this from the dispatch and have not measured it.
Logs / Stack Trace
# engine, COSINE fp16, 50k synthetic, 200 queries
half plain k=10   recall@10 0.9650  max|sim-exact| 3.67e-4
half-l2 plain     recall@10 0.9960  max|sim-exact| 2.07e-5
fp32 plain k=10   recall@10 0.9975  max|sim-exact| 9.54e-7
# engine, 131,924 BGE-M3 passage vectors, 482 real queries
half plain k=10   recall@10 0.9985  max|sim-exact| 4.70e-4
half-l2 plain     recall@10 0.9998  max|sim-exact| 4.11e-5
fp32 plain k=10   recall@10 1.0000  max|sim-exact| 1.01e-6
# the prebuilt libzvec_c_api.so contains 106 vfmadd*ph instructions (objdump -d)
Operating System

Ubuntu (Linux 6.x), Intel Xeon (Sapphire Rapids class: avx512_fp16, amx) @ 2.10GHz

Build & Runtime Environment

zvec-rust 0.7.2 with its bundled prebuilt libzvec_c_api.so (x86_64-unknown-linux-gnu), called through the C API (zvec_doc_add_field_by_value with VECTOR_FP16 codes). Source references are to zvec main @ 53c1bb6.

Additional Context
  • I've checked git status — no uncommitted submodule changes (source checkout at 53c1bb6, used for the kernel checks and #787; the measurements above used the prebuilt)
  • I built with CMAKE_BUILD_TYPE=Debug (not tried: prebuilt and Release only)
  • This occurs with or without COVERAGE=ON (not tried)
  • The issue involves Python ↔ C++ integration (pybind11) (no: C API, and the bug is in the distance kernel)
主要语言
C++
星标
16.3k
派生
1k
平均合并
2 天 10 小时
30 天内合并 PR
32

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

alibaba/zvec 的其他 Issue

查看 alibaba/zvec 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。