[Bug]: FP16 cosine / inner-product search accumulates in FP16 on AVX-512 FP16 CPUs, costing recall (0.965 against 0.998)
Maintainer thường phản hồi trong vòng 1 ngày
@richyreachy đang làm issue này rồi.
Từ ngày 29/9/2026.
Đánh giá
Issue này chưa được đánh giá.
Mô tả
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(), thenaccs[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 byHorizontalAdd_FP16_V512(src/ailego/math/matrix_utility.i:257).src/ailego/math_batch/inner_product_distance_batch_dispatch.cc:113-117,184-188prefers this kernel wheneverAVX512_FP16is set.src/core/metric/cosine_metric.cc:210(the batch distance) and:183(the single distance) route FP16 cosine to it throughCosineDistanceMatrix/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,62is the same design: two__m512haccumulators, which are also added together in FP16 (_mm512_add_ph). The dispatch is atinner_product_matrix_fp16_dispatch.cc:62-66. - The squared-Euclidean single-pair kernel
euclidean_distance_matrix_fp16_avx512fp16.cc:29-39accumulates in FP16 the same way. The L2 batch path usesturbo(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 thekFp16-quantized cosine path on CPUs with FEAT_FP16 (turbo.cc:397-407). It has fourfloat16x8_taccumulators, 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_NEONinsrc/ailego/math/distance_matrix_accum_fp16.i:816-837has a singlefloat16x8_taccumulator (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.ccand*_dispatch.ccTUs get-march=armv8-a(src/ailego/CMakeLists.txt:94-111), and that leaves__ARM_FEATURE_FP16_VECTOR_ARITHMETICundefined. A macOS arm64libzvec_c_api.dylibwe checked has no FP16fmla .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
halfvecconverts with F16C and accumulates in__m256FP32. - Milvus/Knowhere
fp16_vec_inner_product_avx512uses_mm512_cvtph_pswith 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:
- 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 andturboalready 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, onevextracti64x4, twovcvtph2psand two FP32 FMAs, against one load and onevfmadd231ph, 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-362reports the FP16 kernels only helping for cache-resident dims <= 256.) The same applies to the NEON FP16 paths listed above. - 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. - 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:
- Create a collection with a
VECTOR_FP16field (dim 1024),COSINE, and HNSW (m=32,ef_construction=500). - Insert 50,000 unit vectors as FP16, then
optimize(). - Query 200 FP16 unit vectors with
topk=10,ef=700, and compare with exact search in FP32. Recall@10 is 0.965. - Repeat with
is_linear=true: the loss is the same. - Repeat with metric
L2on the same vectors: recall@10 is 0.996. - 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)
- Ngôn ngữ chính
- C++
- Star
- 16.3k
- Fork
- 1k
- Merge trung bình
- 2 ngày 10 giờ
- Pull request đã merge (30 ngày)
- 32
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Không có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của alibaba/zvec
-
[Feature]: IVF_TIEREDQ index type, with a learned variable-bit codec (25–44% less index memory than `IVF_RABITQ` at equal recall)Có thể đã có người làm @richyreachy đã nhận 7 ngày trước. Đang mởfeature
alibaba/zvec#909 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Support an opt-in portable x86 FastPFOR build without SSE4.1Có thể đã có người làm @egolearner đã nhận 20 ngày trước. Đang mở
alibaba/zvec#875 · 1 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[Enhance]: Reduce vector index block fragmentation caused by frequent flushesCó thể đã có người làm @feihongxu0824 đã nhận 22 ngày trước. Đang mởenhancement
alibaba/zvec#869 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[Performance]:High-selectivity range filter materializes a full bitmap — `bitset_set_list` ~49% CPU, dwarfing the ANN searchCó thể đã có người làm @zhourrr đã nhận 22 ngày trước. Đang mởenhancement
alibaba/zvec#868 · 13 bình luận · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[Performance] Warm-query latency on small collections with query() and query_internal_ids() in v0.8.0Có thể làm lại được @egolearner đã nhận 33 ngày trước và không có pull request nào đang mở. Đang mở
alibaba/zvec#841 · 2 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
Issue tương tự
-
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 72/100
-
deprecation internal refactor
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
Maintainer thường phản hồi trong vòng 1 ngày
-
realloc(ptr, 0) on glibc leaves the freed block in the capture as a leakCó thể đã có người làm @ADAMAMZAR đã nhận hôm nay. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 75/100
bloomberg/memray#1097 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
new-compilers request
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
compiler-explorer/compiler-explorer#9640 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 85/100
deepseek-ai/DeepEP#839 ·
Maintainer thường phản hồi trong vòng 6 ngày