Repository navigation
fix(vectorindex): standardize vector distances on the float32 domain (#29040 #29050) - #29100
Conversation
…atrixorigin#29040 matrixorigin#29050) Vector index distances are physically float32 -- usearch returns usearch_distance_t (typedef float) and cuvs is float32-only -- while MO's scalar l2_distance already delivers a float32-precision value for f32 and the narrow bf16/f16/int8/uint8 bases. The index runtime and the pushed range gate, however, kept float64, so an index-served distance disagreed with the same scalar expression by a float32 ULP: a projected value and a `<=`/`>` boundary predicate could observe different values in one row (matrixorigin#29050), and a pushed distance-range gate could flip membership at an exact boundary (matrixorigin#29040). Standardize every distance path on the float32 domain (DOUBLE return type unchanged): - metric.DistanceTransform{Hnsw,Ivfflat} round the transformed distance to float32 via RoundDistanceToElemDomain (inlined), covering ivfflat/hnsw/brute_force/cagra/ivfpq. - moarray's six scalar metrics round to float32 too, so mode=force / the plain scalar agree with the index for a float64 base (cosine_similarity's 1.0/-1.0 corner snap is subsumed by the round). k-means build is unaffected -- it uses metric.L2Distance directly. - readutil.squareL2BoundOutward widens the L2 bound to the next float32 before squaring, and ivfflat.filterEntryDistanceRange rounds its bounds, so the squared-domain gate and the exact post-filter agree with the float32 distance a row is gated on (matrixorigin#29040). A float64 base can still hold a finite value whose squared distance overflows float32; usearch then saturates to +/-Inf while the scalar stays finite -- corrupting the value, Top-K order, and outer predicates (incl. silent derived-table row loss). Since vector distances are a float32 domain, hnsw/ivfflat fail fast on such an overflow (float64 base only, checked once per search) rather than serve the saturated score. Tests: metric/moarray/readutil/func_binary UT updated to the float32-domain contract; BVT vector_func / vector_ivf_prepare_dist_range / vector_ivf_quantization / vector_hnsw_f64 regenerated. IVF f32 boundary matrix, HNSW f32 consistency, f64 overflow rejection, and f64/f32 build all verified live. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
…ject Factor the float64-overflow fail-fast in hnsw/ivfflat Search into a single metric.HasFloat64DistanceOverflow[T] helper (type-check once, then Inf-scan), replacing the two inline gated loops. This makes the reject logic directly unit-testable and drops the now-unused math import from ivfflat/search.go. Add UTs so every changed distance line is covered on the CPU path: - metric: TestRoundDistanceToElemDomain, TestHasFloat64DistanceOverflow - moarray: TestL2DistanceSq - hnsw: TestHnswSearchFloat64Overflow (f64 query, 1e40 sq-dist -> +Inf -> reject) - ivfflat: TestIvfSearchFloat64Overflow (mocked +Inf entry distance -> reject) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… thresholds) The two qrange range predicates used thresholds equal to a row's exact distance (a2 for `<=`, a4 for `>=`) against an int8-quantized IVF index. The quantized range check computes a distance up to ~1 float32 ULP from the exact scalar, so a boundary-exact threshold makes that row's membership depend on which path runs -- the async-built index (a4 >= threshold -> [4,2,3]) vs brute-force before the build finishes (a4 < threshold -> [2,3]). Verified both deterministically. Move the thresholds strictly between rows (<=0.5, >=0.02); the expected rows are unchanged ([1,4,2], [2,3]) but now path-independent (identical on index and brute-force). No product change; asserting exact boundary membership on an approximate quantized index is invalid (same class as matrixorigin#29050). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
l2DistanceF64 accumulated the float32 L2 squared sum in float64 so matrixorigin#29083 could return a distance whose square overflows float32. It cost more than it bought. It is a plain Go loop, so routing L2Distance[float32] through it dropped AVX-512 entirely: 457ns vs 47.7ns per dim-768 pair. ResolveKmeansDistanceFn routes every metric to L2Distance[T], making it the distance function for both Elkan and balanced k-means -- the ivfflat index build -- as well as SQL per-row l2_distance. Isolating just that routing change, BalancedKMeans (10000 x 128, k=100) ran 195.2ms on main's routing against 242.7ms on this branch's, +24.31% (p=0.002, n=6). It also broke the equivalence the batch path documents: the batch kernel stays in float32, so the same query answered differently depending on whether an operand was constant. At dim 768, 313 of 2000 random pairs differed, by up to 1.2e-07 relative. L2Distance now uses the float32 SIMD kernel main uses and rejects a squared sum that left the element domain (L2FromSquared), which is the rule this branch already applies everywhere else: error out, never recompute. matrixorigin#29083 no longer silently returns +Inf -- it fails -- and the batch and scalar kernels agree again, bit for bit, because they are the same kernel. BalancedKMeans is back to +1.52% over main's routing (p=0.041, n=6), the residual being the finite checks themselves. Widening the batch kernel to float64 instead was the alternative and costs 2.1x (L2DistanceSqFloat64 at 99.6ns vs 47.7ns), on the hottest kernel in the system. l2_distance_f64.go is renamed l2_finite.go: nothing in it computes in float64 any more. BVT regenerated -- the const, column-vs-column and NULL-disabled-batch forms now all reject the same pair with the same error. vector_finite_extreme 29/29, full cases/vector 2218 statements with no failures. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
|
All five blockers are fixed, plus three further defects the audit led to — one of them a 24% regression this PR was carrying. Three commits:
The rule: reject, never recomputeMy first pass recomputed an overflowed distance in float64. That was wrong in kind — it made a path answer with a value none of its kernels can produce, and for bf16 it created a divergence, since bf16 runs the same kernel in batch and scalar. A non-finite distance is not a distance. Everything below now follows one rule: compute in the element domain, and error where that domain runs out.
Three more, found while verifying1.
Isolating just that routing change,
2. 3. The cosine batch path's zero-vector fallback keys on Correcting myself on the ULP gapI earlier called the batch-vs-per-row divergence pre-existing. It wasn't — this PR introduced it. On
Validation
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
GPT-6 high force review at exact head b52b5ac (base df41cc2): REQUEST_CHANGES.
[P1] Finite float32 overflow can leave centroid selection at -1 and reach a downstream panic. brute_force.SearchFloat32 keeps minIdx=-1 when the squared distance becomes Inf; ProductL2.probeRun only checks result length before passing -1 to UnionOne. For centroid [0] and query [2e19], this is reachable. Return an error or otherwise prevent invalid indices from reaching callers; apply the same overflow contract to float32 indexes.
[P2] Restored HNSW cosine ANN validates only the query, not stored vectors. Actual usearch tests with stored [1e-30,0,0] or [1e20,0,0] and a unit query return native distance 1 instead of cosine distance 0; [1e20,0,0] against itself can return NaN without error. Enforce or validate the stored-vector/build contract, including existing indexes, and reject non-finite magnitude cases.
[P2] Batch cosine_similarity derives similarity from rounded distance (1-distance32), causing large precision errors (for [1e-6,1] vs [1,0], about 116k float32 ULP) and threshold divergence. Compute similarity directly rather than recovering it from rounded distance.
[P2] IVF public L2sq output is float32-rounded while the storage gate compares raw float64 squared distance, so a row whose exposed score is <=1 can be filtered out by a raw value >1. Unify the comparison domain and clarify public versus internal squared-distance contracts.
[P2] float64 cosine treats nonzero vectors whose squared norm underflows as zero and can return distance 1 for identical [1e-200,0] vectors. Handle underflow consistently with the zero-vector contract.
[P2] Reverting StableInnerProduct/summation allows finite inputs to return NaN/Inf without error (for example [1e20,1e20] dot [1e20,-1e20], and [1e308,1e308,-1e308,-1e308] summation). Restore safe accumulation or a consistent fail-fast contract.
[P2] C/CUDA L2 paths do not implement the same float32 rounding and overflow contract: C returns success with Inf, and the CUDA f64 kernel uses float diff. Align native/device behavior or explicitly gate unsupported paths.
The NormalizeL2 consolidation itself reviewed clean, but the current CI still has UT/SCA/PROXY/PESSIMISTIC BVT pending. These correctness findings block approval even if CI later turns green.
…ive boundary
Review found the overflow contract was only on L2Distance, so paths that take
the squared kernel or a native result could still return a non-finite score.
- brute force returned key -1. minIdx starts at -1 and only moves on
`dist < minDist`, which +Inf never satisfies, so a query whose every
candidate distance overflowed returned -1 with no error and a fabricated
MaxFloat32 distance. ProductL2 passes that key straight to vector.UnionOne,
which has no row -1. Reproduced with centroid [0] and query [2e19].
L2DistanceSq now rejects its own overflow, and both search loops refuse to
emit a negative index.
- InnerProduct and L1Distance returned NaN/+Inf for finite inputs with no
error ([1e20,1e20] dot [1e20,-1e20]). They now fail like L2.
- float64 cosine reported distance 1 -- maximally dissimilar -- for two
IDENTICAL [1e-200,0] vectors, because their squared norms underflow float64
and the zero-magnitude convention caught them. A zero denominator is now
only that convention when a vector really is all zeros; two non-zero
vectors with a zero denominator are rejected.
- batch cosine_similarity derived similarity from the rounded float32
distance as 1-distance. For [1e-6,1] against [1,0] that recovers
1.0132789611816406e-06 where the kernel answers 1e-06 -- about 116k float32
ULP, enough to move any threshold built on it. cosine_similarity no longer
has a batch path; the batch kernels compute distance, and only the per-row
kernel computes similarity directly.
- native results (usearch, cuVS index search, cuVS brute force, cuVS
pairwise) are checked where they cross back into Go, rather than teaching
the contract to each C and CUDA kernel.
Every L2 path now reports one error text, so which kernel answered a query
cannot change the error a user sees. Per the author's standing direction the
fix is fail-fast throughout; no Stable* accumulation is restored.
BVT extended with the inner-product and cosine-underflow paths and regenerated:
vector_finite_extreme 39/39 under -m run. Suites green on both build flavours.
The one failure in the wider cases/vector run is vector_index_optype_matrix's
checked-in EXPLAIN core count (12 core vs this host's 8), unrelated.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
Two gaps the review pointed at, both now reproduced. l2_distance_sq exposes the squared distance float32-rounded (DistanceTransformIvfflat), while the storage gate compares the raw float64 square. The gate's two mitigations for L2 -- the conservative bound widening in reader.go and the exact source-domain post-filter in relation_search.go -- are guarded by `OrigFuncName == DistFn_L2Distance`, and l2_distance_sq is a fully pushable predicate that takes neither: vector_topn.go excludes L2sq from its float32 rounding, and reader.go skips the widening. A row whose raw square is 1+1e-10 therefore exposes a score of 1.0, satisfies `<= 1`, and is still dropped by the gate before the post-filter can see it. The l2sq bound is now widened to the adjacent float32, and NOT squared: an l2sq bound is already in the squared domain, so squaring would narrow a bound below 1 (0.5 -> 0.25) and drop valid rows. squareL2BoundOutward keeps the L2 behaviour and now shares f32BoundOutward with it. HNSW's main search calls usearch's SearchUnsafe directly rather than going through usearchex, so the boundary check added in d473640 did not cover it. usearch computes cosine in float32: a stored [1e20,0,0] against a unit query returns NaN with no error, and against itself also NaN. Those results are now checked where they cross back into Go. The remaining half of that finding is not fixed: a stored [1e-30,0,0] against a unit query returns a FINITE 1 where the cosine distance is 0, because the squared norm underflows float32 to zero and usearch reports its zero-vector answer. Only build-time validation of stored vectors catches that; the criterion is the one metric.CosineVectorL2Norm already applies to the query. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
The per-distance check added in d473640 sat on the scan path and broke it: pkg/objectio's column/vector TopN reads one distance per candidate, and its tests store NaN and +/-Inf elements deliberately and assert they come back as distances. Four UT cases failed in CI. The check does not belong there. A distance that left the element domain can never win a min-comparison, so it cannot change a ranking -- it matters only where a distance is handed back as a RESULT. So L2DistanceSq, InnerProduct and L1Distance pass their value through again, and the contract moves to: - moarray's SQL entry points, where each distance IS the returned value; - GoBruteForceIndex.SearchFloat32/Search, checked once over the result set rather than per candidate. This also covers BF16 -- it carries float32's exponent range, so its kernels reach +Inf where float32 does -- without paying for it on the hot path: a per-kernel check measured +6.8% (AVX2) and +5.0% (AVX512) on the BF16 kernels, in every form tried. - the native (usearch/cuVS) boundaries and the negative-index guard, both already in place. metricWhat is exported as MetricWhat. It had only a gpu.go caller, and gpu.go is behind //go:build gpu, so the untagged SCA build reported it unused. The kernel-level rejection tests move with the contract: metric keeps the L2Distance case, moarray gains the SQL-boundary cases, and brute_force covers BF16 on the heap path, where a non-winning out-of-domain distance is returned as a score. Balanced k-means keeps its own fail-fast test -- its distFn errors propagate, so clustering still fails rather than continuing from a bad bound. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
|
fixed |
HNSW validated the cosine QUERY vector but nothing on the way in, so a row usearch cannot score was indexed silently. Measured against usearch with two distinct stored vectors: [1e-30,0,0] / [2e-30,0,0] L2sq -> distances 0 and 0, ranking inverted [1e20,0,0] / [2e20,0,0] L2sq -> distances +Inf and +Inf [1e20,0,0] / [2e20,0,0] IP -> distances -Inf and -Inf all with addErr and searchErr nil. The reported cosine case is not special: usearch computes in float32, so a squared norm outside that domain breaks every metric. Cosine is only where the norm is also the divisor. CheckIndexableVector therefore takes no metric, and HnswModel.Add / AddWithoutIncr call it beside the existing dimension check -- model.go stays metric-agnostic. An all-zero vector stays legal: l2sq to it is the other vector's squared norm and cosine_distance returns 1 by convention. What is rejected is a vector that HOLDS a value yet is scored as though it were zero, or as +/-Inf. Scoped to float32 elements, and the doc says so rather than implying more: a narrower quantization has a narrower bound this does not test. Under F16, [70000,0,0] and [140000,0,0] are ordinary float32 -- squared norm 4.9e9 -- yet store as +Inf and invert the ranking, which this would pass. Covering that needs the configured quantization, not the element type; f16/int8/uint8 are left uncovered rather than given false assurance. The accumulation is unrolled four-wide: 164ns at dim 768 against a 148,565ns Add, so 0.11% of the graph insertion it precedes (475ns before unrolling). The test walks every length across the 4-wide body and tail, and every position for a single out-of-range element. Search-side non-finite results were already rejected (698669f); this closes the half no result check can catch, where usearch returns a finite but wrong score. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
The unrolling test asserted only accept/reject verdicts on values far from the boundary, while its comment claimed the accumulation "agrees with a plain sum". It did not check that, so a mis-summed lane could pass. Now it does: a reference implementation with an ordinary loop, run against vectors at every length 1..40 and at seven scales chosen so the squared norm sits just inside or just outside the float32 normal range -- where a dropped or double-counted lane flips the verdict -- plus the same vectors with each position zeroed in turn. Mutation-checked, all three caught: dropping s3 from the final sum, double counting s0, and skipping the tail loop. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
e7959b2 rejected an unindexable stored vector in HnswModel.Add / AddWithoutIncr. Self-review shows that trades a wrong score for a silent, permanent index outage. Reverting it; the search-side checks stay. HNSW has no synchronous DML writer -- maintenance is ISCP/CDC-only -- so the rejection never reaches the inserting session. `INSERT INTO t VALUES (1,'[1e20,0,0]')` commits (the cast boundary rejects only NaN/Inf, matrixorigin#28688), then HnswSync.Update -> Add returns the error, runHnsw reports it, and the iteration aborts before Save and before the watermark update. moerr's internal error is not a permanentError, so iteration.go flushes state Completed with watermark = status.From: the next iteration replays the same range and fails identically, forever. Every later INSERT/UPDATE/DELETE for that index is then never applied, with only a log line. The affected set is every vector whose L2 norm is below ~1.08e-19 or above ~1.8e19, not just extreme literals. The CDC update path is destructive on top of that. sync.go:502-509 does Remove then Add, so a rejected UPDATE leaves the row removed and not re-added: after insert: contains(1)=true len=1 after update: contains(1)=false len=1 addErr=<rejected> Len reads 1 while the index holds 0, because Remove decremented and the failed Add incremented before validating. Checking at the vector cast/parse boundary instead was tried and rejected: it is a type-contract change made for an index problem, and it breaks SQL that never touches an index. Three BVT files carry literals it would reject -- vector_result_dimensions.sql ('[1e300,...]' as vecf64), vector_hnsw_cosine_boundary.sql (query constant '[1e-20,1e-20,1e-20]'), and vector_finite_extreme.sql, whose every INSERT would fail, leaving the distance error paths it exists to test unreachable from SQL. Kept: the search-side CheckFiniteDists on usearch results (model.go, 698669f), the brute-force result check and negative-index guard, and the l2sq storage-gate widening. Only the Add-time check and its now-callerless helper are removed -- CheckIndexableVector had no production caller after the revert and would trip the same 'unused' SCA failure that already hit metricWhat. DECISION LOG -- stored-vector validation remains an open gap. usearch returns a finite but wrong score for such a vector ([1e-30,0,0] against a unit query returns 1 where the cosine distance is 0), which no result check can catch. Options, in increasing cost: (1) accept and document; (2) validate before the destructive Remove and skip the row so the sync still advances; (3) index-aware DML validation, which also requires CREATE INDEX to fail on pre-existing rows. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
|
fixed. please review |
XuPeng-SH
left a comment
There was a problem hiding this comment.
GPT-6 high review — REQUEST_CHANGES
当前 head 仍有 5 个可复现的 P2 数值/契约问题:
-
HNSW stored-vector cosine 结果错误
search.go:101。存储向量为[1e-30,0,0]或[1e20,0,0]、查询为[1,0,0]时,保存并 reload 后 HNSW 返回距离 1,而 scalar 结果为 0,且没有错误,影响距离过滤和排序。 -
L2sq scalar/IVF 阈值语义不一致
external.go:229。F64[1.00000001,0]对零向量时,scalar 结果约为1.00000002(不满足<=1),而 IVF 舍入为 1,后置过滤会错误保留该行。 -
C/CUDA 距离 domain 契约仍未统一
xcall.c:67。C 对有限 F32 输入可返回Inf但状态码仍成功,F64 输出也未统一到 float32 domain;CUDA 侧存在对应的float中间计算差异,需统一契约并补跨后端验证。C 侧已实测复现,CUDA 侧为源码确认。 -
inner-product/summation 静默溢出
external.go:373。输入[1e308,1e308,-1e308,-1e308]返回+Inf,nil,数学结果应为 0;请定义并实现 overflow/invalid 语义。 -
L2 中间平方下溢产生错误零距离
finite.go:27。F32[1e-30]对[0]返回0,nil,但最终距离仍应为非零,影响零距离判断和阈值语义。
此前 centroid minIdx=-1、batch cosine rounding、F64 cosine 下溢问题已闭合;当前 CI 通过及 native contract 不能覆盖上述边界反例。请补实现和针对性测试。
Two of the five findings in the latest review, both reproduced at HEAD.
l2_distance_xc / l2_distance_sq_xc are a second, C implementation of the same
distance, registered as ordinary builtins (function_id.go, list_builtIn.go).
cgo/xcall.c computes the element difference and its square in float32 and
returns 0 whatever comes out, so a finite input pair reached SQL as +Inf:
l2_distance_xc([2e19,2e19],[0,0]) -> +Infinity (no error)
l2_distance ([2e19,2e19],[0,0]) -> error
The check goes on the Go side of the boundary, as the usearch and cuVS results
already do, rather than into the C kernel. Both now raise the same text, and
ordinary values still agree across the two implementations (5, 5, 25).
Summation returned +Inf with a nil error for [1e308,1e308,-1e308,-1e308], whose
mathematical total is 0 -- the +Inf on the second term never comes back. It now
uses metric.CheckFiniteDist like its siblings in this file.
Not addressed here, and still open:
- l2_distance_sq's domain split. moarray.L2DistanceSq deliberately returns the
RAW float64 square while this PR added RoundDistanceToElemDomain to
DistanceTransformIvfflat, so on a vecf64 base a threshold can split the
scalar and index-served answers: with v='[3.1]', raw 9.6100000000000012 vs
float32 9.6099996566772461, `l2_distance_sq(v,'[0]') < 9.61` returns 1 row
with an ivfflat index and 0 rows without. One function serves two roles --
public SQL value and IVF's internal squared intermediate -- and separating
them changes the entries-query semantics, so it needs a decision rather than
a patch.
- the CUDA l2distance_f64 kernels take their element difference in float32
(mocl.cu). Same root cause as the C path: commit 95f22f2 on this branch
reverts matrixorigin#29143's stable reduction. Reachable only on a MO_CL_CUDA build with
cl_runtime='CUDA' through the same experimental _xc builtins.
- HNSW stored-vector validation, decision-logged in 2417b5d.
BVT: vector 2229/2231 (0 failed, 2 ignored), array 1501/1501. The new cases pin
both _xc forms erroring and agreeing with the Go path on ordinary values.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
…that proves it
The l2distance_f64 CUDA kernels declared `float diff` while reading `double *`,
so the element difference was rounded to float32 before squaring. The C twin at
cgo/xcall.c uses `double diff`, so the two backends answered the same query
differently. The f32 kernels keep `float`, which is correct for them.
Reproduced with a new standalone test rather than asserted from the source.
cgo/test/test_xcall_cuda.c runs one batch through xcall_l2distance_f64 twice,
once per runtime, and requires them to agree. Against a fatbin built from the
old kernel it fails exactly as predicted:
C 0.010000000000000002 (also what exact double arithmetic gives)
CUDA 0.010000000707805157
That value is the float-difference signature, so the test discriminates rather
than passing vacuously -- which matters here, because SQL cannot reach this
code: the GPU dispatch needs a batch of >= CUDA_THREADS_PER_BLOCK rows and a
vector wider than 128 bytes, and mutating the kernel changed no SQL result at
all. The test calls the xcall entry point directly to get past that, and is
built only under MO_CL_CUDA=1, where the dispatch exists. Running it needs
MO_CUDA_FATBIN_PATH pointing at the staged fatbin, as the Go CGo test wrapper
already does.
Two findings fell out of writing it. cuda_l2distance_impl writes to errBuf on
its "CUDA not initialised" branch, so passing NULL there segfaults rather than
returning -1111; production always passes a buffer (cxcall.go), so only a
direct caller can hit it. And the deleted cgo/test/test_xcall.c never covered
this: it ran RUNTIME_C only, on a single row, and its Makefile target was
excluded from CUDA builds.
Also in this commit, from the same review:
- DistanceTransformIvfflat no longer rounds l2_distance_sq. Its scalar twin
returns the raw float64 square on purpose (moarray.L2DistanceSq: IVF reuses
l2_distance_sq as its own squared intermediate), so rounding only the
index-served side split them -- a vecf64 [3.1] gives raw 9.6100000000000012
against float32 9.6099996566772461, and `l2_distance_sq(v,'[0]') < 9.61`
matched under an ivfflat index and not without one. Verified on the query
shape that actually engages the index (ORDER BY ... LIMIT -> Vector Index
Scan); a plain WHERE stays a table scan and proves nothing.
- L2FromSquared records why the mirror underflow case is NOT rejected: a
float32 pair 1e-30 apart squares to zero and reads as identical, but
detecting it needs the vectors, and comparing them whenever the square is
zero costs 447ns against 36ns at dim 768 -- an exact match is the common
case in vector search, and it is exactly the case that walks both vectors
to the end.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
|
Thanks — this round found four real defects and I've fixed all four. Two findings are deliberately not fixed, and I want to give the reasoning rather than just close them, because in both cases I implemented the fix, measured it, and backed it out.
FixedXCall returned The check goes on the Go side of the boundary, as the usearch and cuVS results already do. Both now raise the same text; ordinary values still agree across the two implementations (5, 5, 25). Summation overflowed silently. CUDA f64 kernels rounded the element difference to float32. I did not take this one on source inspection.
That mattered: SQL cannot reach this code. The GPU dispatch needs a batch ≥ l2_distance_sq split between scalar and index. Verified on the query shape that actually engages the index — Not fixed, by designBoth of these are extreme-magnitude cases that cost real users nothing, where the fix costs every user something. I implemented each, measured it, and reverted it. 1. HNSW scores a stored vector whose norm leaves the float32 domain. A stored I fixed this by rejecting such vectors in Checking at the vector parse boundary instead was also tried and rejected: that is a type-contract change made for an index problem, and it breaks SQL that never touches an index — three existing BVT files carry literals it would reject. So the trade is: a wrong score on synthetic magnitudes, versus a silent permanent index outage on a legal INSERT. Ignoring the extreme case is the better failure mode. Left open and documented. Worth recording for whoever revisits it: pre-normalizing the stored vector fixes it cleanly, because cosine is scale-invariant — 2. L2 intermediate square underflows to zero. A float32 pair Detecting it needs the vectors, since all the kernel has is a zero square. Comparing them whenever the square is zero measured:
12.5× slower on an exact match — and an exact match is the common case in vector search (querying a row that exists, dedup, self-join), not a degenerate one. It is also precisely the case that walks both vectors to the end. Paying that on every zero-distance result to catch vectors closer than ~1e-19 is the wrong trade. Validation
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
GPT-6 high review — REQUEST_CHANGES
当前 head 仍有 5 个可复现的 P2 数值/契约问题:
- hnsw/search.go:101:存储
[1e-30,0,0]或[1e20,0,0]、查询[1,0,0]时,保存并 reload 后 HNSW 距离返回 1 而非 0,影响 top-1、过滤和排序。 - metric/cosine_f64.go:37:f32
[3e-23,3e-23]对[1,0]返回约0.433316,正确值约0.292893,导致<0.35判断错误。 - metric/normalize.go:37:f64
normalize_l2([2e-162])返回约[0.899783],应为[1],且无错误。 - function/cxcall.go:199:f64
[1e40]对零向量时,普通 L2 拒绝,但 Go→C XCall 成功返回1e40;有限值结果域仍未统一。 - metric/finite.go:33:f32
[1e-30]对零向量返回0,nil,但最终可表示距离应非零,导致错误零距离判断。
IVF L2-squared threshold 和 summation overflow 已修复;上述 HNSW、cosine/normalize 次正规数、XCall 有限域逃逸及 L2 下溢仍需实现修复并补针对性回归。CI 通过及 native workflow 不能覆盖这些边界反例。
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed head 49237b6774533c64819e8ac14f6c8370b09be197. The final IVF bound now preserves the raw SQL threshold; that closes my earlier bound finding. I still request changes for these independent correctness regressions against current main:
-
[P1] Restoring HNSW cosine without a stored-vector invariant reintroduces wrong ANN results (
pkg/sql/plan/apply_indices_hnsw.go,pkg/vectorindex/hnsw/search.go:101-111,pkg/vectorindex/hnsw/model.go:404-429). Only the query norm is checked. A valid stored[1e-30,0,0]or[1e20,0,0]is added unchanged; usearch's float32 norm underflows/overflows and its score for unit[1,0,0]differs from the scalar cosine distance 0. This can change Top-K membership, not merely the displayed last bit. Main's exact-scan guard prevents that regression. The fix must also account for indexes built before any new invariant is introduced; rejecting asynchronous CDC updates would strand index maintenance. -
[P2] Positive but subnormal float32 norm sums bypass the cosine fallback (
pkg/vectorindex/metric/distance_func_amd64.go:388-404; same rule in the scalar build). For[3e-23,3e-23]versus[1,0], float32 squares round to subnormals,cosineDenOKaccepts the nonzero denominator, and cosine distance becomes about 0.433316 instead of 0.292893. A< 0.35predicate flips. The fallback needs to cover inaccurate subnormal accumulation, not just zero/Inf/NaN. -
[P2]
NormalizeL2accepts a nonzero but subnormal squared sum (pkg/vectorindex/metric/normalize.go:35-56). For float64[2e-162],sumSquaresrounds to the minimum subnormal and the function returns about[0.899783], not the unit vector[1]. Main's scaled normalization handled this. Keep the fast ordinary path if desired, but use scaling or a guarded fallback at both magnitude extremes. -
[P2] The restored element-domain L2 kernel silently turns representably different float32 vectors into a zero distance (
pkg/vectorindex/metric/distance_func_amd64.go:98-101,pkg/vectorindex/metric/finite.go:24-37).[1e-30]versus[0]yields a zero square and0,nil, while the distance1e-30is representable; current main's stable path preserves it. A zero-distance filter and Top-K ties can therefore change. The performance argument in the comment does not make that wrong answer safe; a selective fallback or different distance formulation is needed. -
[P2] The C SQL overload still escapes the newly declared float32 result domain (
pkg/sql/plan/function/cxcall.go:182-204,cgo/xcall.c:112-133).l2_distance_xcon float64[1e40]and[0]returns finite1e40and passesd-d != 0; ordinaryl2_distancerounds to float32 and errors. Check the public-domain range, not only float64 non-finiteness, and test both overloads.
The above are source-traced; I independently checked the float32 and float64 numerical counterexamples. CI is green, but these cases are not covered by the changed tests. The remaining scalar/HNSW one-ULP double-rounding gap is a separately documented design tradeoff and is not the basis of this review.
… to the float32 domain Three domain checks that a zero/Inf/NaN test misses. Cosine kernels tested only that the denominator was positive and finite, which accepts a SUBNORMAL squared norm. float32 [3e-23,3e-23] squares each element below the normal range, so the accumulated norm keeps a couple of bits and the kernel answered 0.433316 where the cosine distance is 0.292893 -- enough to flip a `< 0.35` predicate. cosineNormsOK now tests each squared norm against its own accumulator's smallest normal (the f32 constant in the F32 kernels, the f64 one in the F64 kernels). Zero is deliberately still rejected so an underflowed float32 norm keeps routing to the float64 recompute, which is what lets [1e-30,0] still score 0 against itself. NormalizeL2 had the same gap at the other end: a squared sum in (0, smallest normal) is positive and finite, so neither the overflow nor the zero branch fired, and float64 [2e-162] normalized to 0.899783 instead of 1. It is now rejected with the existing underflow error, so no pinned message changes. l2_distance_xc returned values the scalar l2_distance rejects: the C kernels accumulate in double and report success whatever comes out, so float64 1e40 came back finite where float32(1e40) is +Inf. The check is now per overload, because the domains genuinely differ -- l2_distance is a float32-domain value for every base type including vecf64, as is l2_distance_sq on vecf32, but l2_distance_sq on vecf64 returns the raw float64 square by design as IVF's squared intermediate. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
… at the native boundary (matrixorigin#29090) IVFFLAT build panicked with "index out of range [-8]" in vector.UnionOne for entirely finite VECF32 input on a GPU build. -8 is not a key: it is the byte offset of row -1 on an 8-byte column. cuVS marks a slot it could not rank with -1 and pairs it with an ordinary FINITE distance, so no check on the scores catches it -- the guard has to be on the key. ProductL2 now refuses a negative key at the point of use, after the null override that supplies its own, and ivfflat's centroid probe drops one rather than emitting "IN (-1)", which would be a silently empty result instead of an error. The Go index already refuses to emit a negative index, so both only ever fire for the device index. The finite check itself was in the wrong layer, which is what let this through. It sat in three of six brute-force entry points, and CPU and GPU picked OPPOSITE ones: GoBruteForceIndex checked in SearchFloat32 but not Search, the cuVS index in Search but not SearchFloat32. So the same logical operation validated or not depending on which engine answered and which entry point the caller used, and ProductL2 -- which calls SearchFloat32 -- was never covered on the device path. Search and SearchFloat32 are internal index APIs with two caller classes: ones that hand distances back as query scores, and ones that only want ids. The check now sits where a foreign result crosses into Go, as usearchex and HnswModel.Search already did, so both entry points of an algo inherit it: cagra and ivfpq check their assembled resdistances, and brute force -- whose only consumers read ids, never scores -- checks nowhere. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01V5spSTbNWzypi8AFat9bfi
|
Decision log — not fixed, by design Both are extreme-magnitude cases that cost real users nothing where the fix costs every user something. I implemented each, #1 — HNSW scores a stored vector whose norm leaves the float32 domain A stored [1e-30,0,0] or [1e20,0,0] against a unit query returns distance 1 (or NaN) where the scalar returns 0. usearch computes What it actually costs, on a real index: nothing. The bad vector scores 1 — or NaN, which loses every comparison — so in an index An HNSW index typically holds millions of vectors. A vector whose norm leaves the float32 domain cannot be scored meaningfully by Rejecting in HnswModel.Add is strictly worse. I implemented it and measured the result: HNSW has no synchronous DML writer — after insert: contains(1)=true len=1 And there is no "skip the row and carry on" today. Classifying that rejection as an ISCP permanentError does not rescue it — it Rejecting at INSERT/UPDATE was considered and also rejected. It is the only placement that would both inform the user and keep So the trade is: a discrepancy no real query can observe, versus a permanent index outage or a rejected legal INSERT. Left open #4 — L2 intermediate square underflows to zero A float32 pair 1e-30 apart squares to 1e-60, which underflows float32 to zero, so two distinct vectors report distance 0 — the Detecting it needs the vectors, since all the kernel has is a zero square. Comparing them whenever the square is zero measured, 12.5× slower on an exact match — and an exact match is the common case in vector search (querying a row that exists, dedup, |
What type of PR is this?
Which issue(s) this PR fixes:
issue #29040 #29050 #29082 #29083 #29183 #29090
What this PR does / why we need it:
This PR bundles four vector-index distance fixes.
1. Standardize vector distances on the float32 domain (#29040 #29050)
Vector index distances are physically float32 -- usearch returns
usearch_distance_t(typedef float) and cuvs is float32-only -- while MO's scalarl2_distancealready delivers a float32-precision value for f32 and the narrow bf16/f16/int8/uint8 bases. The index runtime and the pushed range gate, however, kept float64, so an index-served distance disagreed with the same scalar expression by a float32 ULP: a projected value and a<=/>boundary predicate could observe different values in one row (#29050), and a pushed distance-range gate could flip membership at an exact boundary (#29040).Standardize every distance path on the float32 domain (DOUBLE return type unchanged):
metric.DistanceTransform{Hnsw,Ivfflat}round the transformed distance to float32 viaRoundDistanceToElemDomain(inlined), covering ivfflat/hnsw/brute_force/cagra/ivfpq.metric.L2Distancedirectly.readutil.squareL2BoundOutwardwidens the L2 bound to the next float32 before squaring, andivfflat.filterEntryDistanceRangerounds its bounds, so the squared-domain gate and the exact post-filter agree with the float32 distance a row is gated on ([Bug]: IVFFLAT l2_distance range predicates use a different boundary value than scalar evaluation #29040).2. Preserve finite-extreme overflow safety without the #29143 perf regression (#29083)
#29143 (merged) fixed the finite-extreme overflow (#29083) by adding
Stable*distance functions -- a per-vector scale pass + scalar float64 loop +big.Float-- which drop the float32 SIMD kernels and the cuVS/GPU batch path. That is a broad performance regression and, under the float32-domain model above, redundant: precision beyond float32 is discarded on the exposed distance anyway.This PR reverts #29143's
Stable*machinery and keeps #29083 safe with a focused change:L2Distanceaccumulates the squared sum in float64 before thesqrtand the float32 cast, so a float32 vector whose squared distance overflows float32 but whose distance is representable returns a finite value. The fast element-typedL2DistanceSq(the hot search/pruning kernel) is untouched. A float64 base whose distance genuinely overflows float32 is still rejected fail-fast (fix 1).3. Consolidate NormalizeL2 (refactor)
NormalizeL2was duplicated three times with identical, non-SIMD bodies (two build-tag variants inpkg/vectorindex/metricplus a copy inpkg/vectorize/moarray). Collapse them into one untaggedmetric.NormalizeL2and makemoarray.NormalizeL2delegate to it. Behavior is unchanged for every caller (elkans/balanced k-means, thel2_normalizeSQL builtin over f32/f64 and the narrow bases).4. Restore native cosine ANN for HNSW; reject a degenerate query (#29082)
#29136 (merged) fixed the usearch cosine zero/subnormal-boundary bug by disabling the HNSW index for all cosine queries -- the planner returned no index and every cosine search fell back to a full exact scan, nullifying ANN for the most common vector metric while still paying to build the cosine graph.
This PR restores native
usearch.CosineANN and scopes the guard to the actual failure. HNSW cosine assumes caller-normalized vectors; usearch computes cosine in float32, so only a zero or subnormal query vector -- whose float32 squared norm underflows -- cannot be scored to MO'scosine_distance. Such a query is rejected fail-fast (the vector is not rewritten -- silently normalizing it would disagree with the stored index); a normalized query uses the index.apply_indices_hnsw.go: drop the blanket cosine gate.metric.CosineVectorL2Norm(v) (norm, ok):ok=falseon float32 squared-norm underflow; computed once per search, not per row.hnsw/search.go: error out on!okfor a cosine query; native ANN otherwise.Validation
pkg/vectorindex/metric,pkg/vectorize/moarray,pkg/vectorindex/hnsw,pkg/sql/plan, plus the wholepkg/vectorindex/...tree. Covers the float32-domain contract, the [Bug]: vector functions underflow or overflow on finite extreme magnitudes #29083 overflow case (Test_L2Distance_Float32SquaredOverflow),CosineVectorL2Norm, and the HNSW cosine planner/search paths.vector_func,vector_ivf_prepare_dist_range,vector_ivf_quantization,vector_hnsw_f64;vector_hnsw_cosine_boundaryrewritten (normalized query ->hnsw_searchwith correct neighbours; zero/subnormal query -> error; scalar path keeps its zero-vector convention);vector_index_optype_matrixcosine block flipped to expect the index, with index score == brute force.🤖 Generated with Claude Code