Repository navigation
feat(vectorindex/metric): arm64 NEON SIMD distance kernels; build with Go 1.27 - #29496
Conversation
Extend the arch-specific SIMD distance kernels in pkg/vectorindex/metric to arm64 alongside amd64, so vector search on Apple/ARM servers uses NEON kernels instead of the scalar fallback. - New arm64 kernels: distance_func_arm64.go and the narrow-type (int8/uint8 + shared) arm64 kernels, tagged `arm64 && go1.27 && goexperiment.simd`, with cover tests that check each SIMD kernel against the scalar reference. - Scalar fallback tag widened to `!((amd64 || arm64) && go1.27 && goexperiment.simd)` so exactly one kernel set compiles per build; untagged resolve.go still picks the kernel for all callers. - Require Go 1.27: simd/archsimd gained arm64 (NEON) types in 1.27 and the same release renamed the amd64 slice loaders (LoadFloat32x16Slice -> LoadFloat32x16) and vector store (Store -> StoreArray); amd64 kernels + tags updated to match, go.mod bumped to go 1.27.0. - Makefile: enable ARCHSIMD by default on arm64 (NEON is ARMv8 baseline, no GOAMD64-style knob needed) as well as x86_64; GOEXPERIMENT defaults to simd on both. `make ARCHSIMD=0 build` still selects the scalar path. Verified on darwin/arm64 (go1.27): scalar and `GOEXPERIMENT=simd` builds both compile; metric tests pass in both configs (SIMD kernels match scalar). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lators The arm64 NEON f32 kernels (L2DistanceSqFloat32, InnerProductFloat32, L1DistanceFloat32, SphericalDistanceFloat32) were a 1:1 port of the amd64 shape: 4 Float32x4 accumulators, 16 f32/iter. That accumulator count was tuned for AVX-512 (16-wide, 1-2 FMA ports). On wide NEON cores (Apple M-class / Neoverse: ~4 FP pipes, 128-bit regs) 4 dependent FMLA chains issue ~1/cycle and use only ~1 of 4 pipes, so the port under-utilized FMA throughput. Deepen to 8 accumulators (32 f32/iter), with a 16-block SIMD cleanup so n in [16,32) still runs vectorized (never slower than before). Measured on Apple M2 Max (go1.27, GOEXPERIMENT=simd), compute-bound L2 f32: dim768: 45 -> 54 GFLOP/s (+21%) dim1536: 43 -> 56 GFLOP/s (+30%) dim128: ~flat (loop overhead dominates tiny vectors) Streaming/bandwidth-bound regime is unchanged (acc4 == acc8, ~51 GB/s), so the win applies to cache-resident hot queries / IVF short-lists. Left unchanged, verified by sweep: - f64 (Float64x2): acc8 measured slower than acc4 (2-wide is bandwidth-bound). - int8/uint8: acc4 slower than acc1 (unpack/widening-bound, not FMA-latency-bound). Correctness: parity + all SIMD-vs-scalar cover tests pass in both the GOEXPERIMENT=simd and scalar builds; go build/vet clean under both tags. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… kernels
Rewrite the int8/uint8 distance kernels on both AVX-512 and AVX2 tiers using
two archsimd ops that Go 1.27 exposes:
- SumOf8AbsDiff (VPSADBW) -- abs-diff plus horizontal sum in one op
- DotProductPairs (VPMADDWD) -- int16 multiply plus pairwise add in one op
Both replace a 4-way unpack to 32-bit lanes followed by VPMULLD, which has
poor latency. L1 additionally drops from ~20 SIMD ops per 64 elements to ~4.
int8 L1 cannot use VPSADBW directly because the instruction is unsigned-only.
Biasing both operands by XOR 0x80 reinterprets int8 as uint8 while preserving
differences -- (a+128)-(b+128) == a-b -- so it is exact for every input, not an
approximation.
Measured on Zen5 at dim=1024 (ns/op, median of 3):
AVX-512 L2sq 53.1->22.9 IP 47.3->20.7 L1 58.5->15.4 Cos 105.9->68.6
AVX2 L2sq 51.4->29.9 IP 46.5->27.9 L1 58.1->16.1 Cos 78.4->49.1
Scores are unchanged, verified three ways: 8862 (AVX-512) and 10128 (AVX2)
evaluations bit-identical to the kernels they replace; an 880-row dump through
the public ResolveDistanceFn compared four ways (old/new x AVX-512/AVX2) with
zero diff; and the new test checks all 8 kernels against the scalar reference
over dims 0..200 plus block boundaries, extremes, and the zero-vector cosine
branch.
The AVX2 tier was verified to contain no AVX-512 instructions by disassembly:
all 16 AVX2 kernels are free of EVEX-prefixed (0x62) encodings, which also
excludes AVX-512VL ops on xmm/ymm registers that a zmm-register scan would
miss. Instructions used are VPMADDWD, VPSADBW, VPMOVSXBW, VPMOVZXBW,
VEXTRACTI128 and VPBROADCASTB, all AVX2.
Two recorded negative results, so they are not retried:
- Widening the AVX-512 loop to 64 elements/iteration was slower (L2sq
25.0->32.2): VEXTRACTI64X4 on a zmm costs more than the load it saves.
- The AVX2 cosine kernel is faster than the AVX-512 one at every dimension
tested; init() still prefers AVX-512 because the balance is
microarchitecture specific and this is one CPU's measurement.
Also removes six now-dead unpack/reinterpret helpers, fixes a benchmark that
sized its working set by b.N (which made every ns/op figure a cache-miss
measurement rather than a kernel measurement), and refreshes the two file
headers that still described the replaced shift-and-unpack scheme.
arm64 kernels are untouched.
Co-Authored-By: Claude Opus 5 <[email protected]>
# Conflicts: # Makefile
…kernels Merging main brought the finite-extreme rejection contract and its tests (finite_extreme_test.go, matrixorigin#29040/matrixorigin#29050): a distance/cosine result that leaves the element domain must error, not surface Inf/NaN. The amd64 NEON kernels already honor it, but the arm64 kernels predated the contract and returned raw results, so the new tests failed only on the arm64 SIMD path (TestCosineFiniteExtremes, TestCosineUnderflowVsZeroVector, TestCosineRejectsSubnormalNorms, Test_L2Distance_Float32SquaredOverflow). Port the amd64 handling verbatim into the arm64 kernels (all helpers are already arch-independent): - L2Distance: return via L2FromSquared (finite check on the squared intermediate) instead of a bare math.Sqrt. - CosineDistance/CosineSimilarity F32 and F64: guard the accumulated norms with cosineNormsOK; on a float32-domain overflow recompute in float64 (cosineRecomputeF64) and reject only when that also overflows; distinguish a true zero vector from an underflowed one via anyNonZero. Verified: pkg/vectorindex/metric passes both with GOEXPERIMENT=simd (arm64 NEON) and without (generic scalar); full arm64+simd build succeeds. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
go.mod now requires go 1.27.0 for the simd/archsimd arm64 types and the renamed amd64 loaders. golang:1.26.4-bookworm sets GOTOOLCHAIN=local, so the GPU image build stops with "go.mod requires go >= 1.27.0". Move both GPU Dockerfiles to golang:1.27.0-bookworm. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
go.mod requires go 1.27.0. The matrixorigin/golang:1.26.4-ubuntu22.04* and matrixorigin/tester:go1.26.4-jdk8 images run go1.26.4 with GOTOOLCHAIN=local, so builds from them stop with "go.mod requires go >= 1.27.0". Point Dockerfile, Dockerfile.ci, Dockerfile.ci-builder, Dockerfile.dev, the BVT tester Dockerfiles and the jstfu notes at the 1.27.0 tags, and update the documented minimum Go version. The matrixorigin/golang:1.27.0-* and matrixorigin/tester:go1.27.0-jdk8 images are not published yet; these builds need them. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
REQUEST_CHANGES on 90c1efc.
The previous inner-product cancellation / lost-winner blocker is fixed: the current f32/f64/BF16 metric tests, actual brute-force inner-product selection test, and moarray regression passed in this review. Moving the unrolled reference into one shared metric owner and removing the old duplicate/commented scalar bodies is the right direction.
One P2 remains: BF16 cosine can still silently lose the correct candidate under the newly enabled ARM64 NEON path. This is not merely an overflow error or a deferred optimization. The inline finding gives an accepted finite-input reproducer and both actual search-entry-point results. Consequently the v3 design premise that a +Inf sentinel is always rejected at the serve boundary and can never produce a wrong finite winner is false. I cannot approve the current design/default activation on that premise.
History / change quality:
- Read all six prior review threads and the subsequent author responses. Their GitHub resolved flags are not proof of behavioral closure: the IP reproducer is closed, but the accepted-input / final-ranking concern remains through narrow cosine.
- Implementation: reuse the existing metric-owned exceptional recovery, keeping ordinary SIMD processing and existing search ownership. This does not call for a second selector, additional retained state, or unconditional element-by-element validation.
- Tests: the new
cosine_bf16_still_posinfassertion protects the sentinel implementation, not correct public behavior. Replace that oracle with the finite cosine result and the unique winning candidate, in both default and opt-out modes. - Design documentation: remove the demonstrated unsafe deferral; align the description of recovery precision with the actual unrolled T-domain reference rather than claiming every recompute is float64. The large test/document increment does not independently establish the numerical contract.
Fresh evidence: exact-head native artifacts built with top-level make -j8 cgo; Go 1.27.0, darwin/arm64, GOEXPERIMENT=simd. Focused author regressions and independent external-overlay probes were run via mo-cgo-test -v -count=1 -timeout=120s -p=1 for metric, brute_force and moarray. Default NEON: terminal failure with cosine +Inf and both searches returning key 1 / finite distance ~2 / nil error. Same head with MO_METRIC_NO_NEON=1: terminal pass, cosine 1 and both searches returning key 0 / distance 1. The nearby ordinary-magnitude cosine control and BF16 literal-admission check pass. This isolates the default kernel rather than a toolchain-only difference.
Scope: inventoried all 197 files (+4709/-1226), read the current design and the latest 15-file repair, and traced the numerical owner/resolver/ranking/IVF-centroid consumer closure. The demonstrated design failure short-circuits approval of the remaining full-PR implementation/build/test details; they are not claimed cleared. Exact-head CI is green, but does not close this counterexample. No new SQL-server BVT, Linux/amd64/GPU runtime validation or throughput benchmark is claimed. A separate extreme unnormalized spherical-helper counterexample was excluded as a merge blocker after tracing production kmeans normalization. No product source was changed and no subagents were used.
# Conflicts: # pkg/frontend/authenticate_test.go
…ixorigin#29496) The narrow bf16/f16 cosine SIMD kernels still mapped a lane-cancellation NaN to +Inf via cosineDistClamped, which could silently drop the true nearest: BF16 q=2^60, cand0=+/-2^67 (orthogonal, cosine distance 1), cand1=-1 (antiparallel, distance 2) -- every product a finite +/-2^127 -- selected cand1 on NEON (key 1, dist ~2) while the scalar path returns cand0 (key 0, dist 1). Close it at the metric owner like inner product / spherical: on a non-finite SIMD result, recoverCosineBF16/F16 recompute via the scalar cosineDistanceBF16/F16 reference (source order, with its own f64 norm recompute), fast-failing genuine overflow. Wired into all bf16/f16 cosine tiers (NEON/AVX-512/AVX2). f16 cannot overflow float32, so its recover is a no-op guard; int8/uint8 cosine accumulate in integers and cannot NaN. Tests: TestBruteForceRecoversNarrowCosineWinner29496 (the reproducer; selects key 0 in default and MO_METRIC_NO_NEON modes, proven to pick the wrong key 1 with recovery disabled); the contract test cosine_bf16 now asserts the recovered distance 1 instead of +Inf. Design doc: remove the "deferred gap"/"never a wrong finite winner" language and correct the recompute precision to the native accumulation type (float32 for f32/bf16/f16, float64 for f64), not unconditionally float64. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
fixed |
…#29496) The Go 1.27 / golangci-lint v2 toolchain move (this branch) surfaces six pre-existing latent findings the older analyzer never reported; resolve them in place per the delivery contract (the gate stays fail-closed and un-scoped). prealloc (3) -- preallocate each slice to its known final capacity: - func_cast_temporal_numeric_test.go: 3 literals + 10 + 64 = 77 - prepared_binding_test.go: 1 + 2 = 3 - privilege_cache_test.go: 2 users x 5 queries = 10 sqlclosecheck (3) -- false positives, not leaks: each flagged *sql.Stmt IS closed by the deferred Close immediately below it; the analyzer loses tracking only because the Stmt is captured as a free variable by a closure (stmt -> updateOne, read -> checkRead, binary -> run). The structurally identical update, which no closure captures, is correctly seen as closed and not flagged. Suppressed narrowly with //nolint:sqlclosecheck carrying the reason. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Reviewed exact head e9a71d2cc50f0a436c5ebeccc6b2dfd768f942a4, merge-base 43c37847b16d37cfa8b9eef4235ba4388b5e25ce. No subagents or product changes.
Decision: REQUEST_CHANGES on the mandatory v3 design contract, NOT a repetition of the old lost-winner defect.
Historical numerical closure: the inner-product cancellation and the BF16 cosine lost-winner counterexamples now PASS on this exact head. Independent finite-input admission, ordinary-magnitude controls, both real brute-force entry points (SearchFloat32 and Search), and the author lane-cancellation/selection regressions were freshly run in default NEON and MO_METRIC_NO_NEON=1, Go 1.27.0 darwin/arm64 with GOEXPERIMENT=simd. Both runs terminate successfully; the cosine winner is key 0 / distance 1. The previous 90c1efc review's cosine blocker is resolved. Reuse of one shared metric-owned exceptional recovery, deletion of duplicate scalar bodies and replacing the +Inf-only test by public-result/unique-winner oracles are appropriate improvements.
[P2] Close a self-consistent v3 numerical/cost contract before default-activation approval. The current design explicitly marks v3 Pending, and the available approvals are for af0eb99/90c1efc, before this narrow-cosine amendment. More importantly, substantive assumptions still disagree:
- Sections 2/7 say finite stored vectors never produce a non-finite SIMD result. The exact accepted, finite-component BF16 cancellation input used to justify this repair does produce that intermediate/result and therefore takes an O(d) source-order recompute. The ordinary finite-SIMD fast path is cheap; a finite-input workload can nevertheless take the second pass on each distance. State this workload/cost boundary accurately instead of excluding it by an invalid premise.
- Section 2 chooses source-order accumulation in T (f32/BF16/F16 use float32), but section 5 still describes an in-order float64 reference. Those are different overflow/cancellation contracts.
- Sections 2/7 require genuine overflow to become the same +Inf everywhere, while recoverInnerProduct calls nanToPosInf, which normalizes NaN but preserves signed infinity; genuine negative-inner-product overflow can remain -Inf. Define whether preserving signed non-finite scalar results and rejecting them at the existing consumer boundary is the accepted contract, rather than documenting a normalization that does not occur. This does NOT ask for a new per-consumer validator or indiscriminate widening.
The recovery direction is reasonable; the precise proposal needs these choices reconciled and the exact updated v3 design decision recorded. This review does not claim a new observable wrong-winner defect after the fix. It also does not treat an old blank implementation approval as closure of the amended numerical design.
Scope/gates: complete inventory 201 files, +4774/-1235, ARM64 kernels/default activation plus Go 1.27/build/tooling and repository-wide lint cleanup. Hot-path/default/toolchain and >500 non-generated production-line feature triggers require design-first review. Read the full current design, historical findings and latest numerical repair, and traced scalar/NEON/AMD64 narrow recovery and actual selection consumers. Because the numerical design gate remains unresolved, full downstream implementation approval of all 201 files is stopped; those files are not claimed cleared. No new Linux/amd64/GPU execution, SQL-server BVT or throughput benchmark is claimed. Native reuse was qualified by clean, identical tracked native inputs and verified provenance; whitespace check PASS. Logs 29496-default-probes-final.log and 29496-optout-probes.log under /private/tmp/mo-review-five.HHHg3U.
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
Reviewed exact PR head e9a71d2 against merge-base 43c3784 after loading existing reviews, issue comments, and inline threads. The remaining remap_errors metadata delta is a regenerated result-only baseline: the relevant source path is unchanged, BVT executes with metadata comparison disabled, and Go 1.27 documents JSON error-text and flate-output changes without establishing a server metadata regression. No independent blocking or non-blocking findings. The existing unresolved design-document inconsistency raised by XuPeng-SH remains unaddressed but is intentionally not duplicated.
…xorigin#29496) Address XuPeng-SH's P2 on the amended, still-Pending v3 design contract (doc only; the code behavior was already correct, the doc over-claimed). 1. Cost no longer excludes finite-data workloads. The O(d) in-order second pass runs on ANY non-finite SIMD result -- including finite extreme-magnitude vectors whose lanes overflow/cancel before reduction, the exact case the fix targets and the counterexamples exercise -- so a finite-data workload is not exempt. Framed as: one finiteness test always; a bounded ~2x O(d) pass only on the pairs that actually go non-finite, never on the ordinary finite case. 2. Align 5's wording with 2/7: the recompute is in the kernel's native accumulation type (float32 for f32/bf16/f16, float64 for f64), not "the in-order float64 reference". 3. Decide/document signed genuine overflow (doc matches code). nanToPosInf normalizes ONLY NaN (unordered -> silent lost-winner); a genuine +/-Inf is well-ordered and kept with its own sign -- inner product (-dot) can return -Inf, the non-negative/bounded metrics return +Inf. Every serve boundary rejects non-finite sign-agnostically (d-d != 0 / math.IsInf(_,0)), so the sign is irrelevant to rejection; forcing +Inf is unnecessary and would mis-rank a genuine IP overflow (a maximal dot) as farthest. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # pkg/util/export/merge_test.go
…origin#29496) Two findings the Go 1.27 / golangci-lint v2 toolchain surfaces in files the latest main merge brought in; resolve them in place (gate stays fail-closed). prealloc -- filter_test.go: testCases is a 7-entry literal later appended with 3 more (final capacity 10). Wrap the literal in append(make([]testCase, 0, 10), []testCase{...}...) so it is preallocated; the later append fits without realloc. sqlclosecheck -- prepared_numeric_temporal_contract_test.go: false positive. stmt IS closed by the deferred Close immediately below, but the queryRow closure captures stmt, which defeats the intraprocedural analyzer. Suppressed narrowly with //nolint:sqlclosecheck carrying the reason. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
fixed sca |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Reviewed exact head 4201f1e7b1bf4b1059b331ed87a37f6eef94eca1 against declared base / verified merge-base 5c449cfe837ac90667c2a85ee3f442263440552c. No subagents.
REQUEST_CHANGES: the metric-owned recovery direction is appropriate, but the amended numerical contract is not closed. Two independently exercised gaps remain: build-time scalar fallback can return NaN into ranking, and the result-only recovery predicate cannot establish the promised cross-mode overflow/selection equivalence. Inline comments give concrete admitted inputs and observed public-search results. The exceptional-path ~2x cost bound also needs correction.
Historical closure: all eight existing inline threads are marked resolved. The old inner-product and BF16 cosine lost-winner witnesses are fixed, and the latest document resolves the three precise inconsistencies from review 5416608522 (finite inputs may require recompute, native accumulation type, signed infinities). Those points are not being reopened. Numerical source trees are unchanged from the earlier real-ARM review at e9a71d2, so its scoped evidence remains applicable. Fresh Linux/amd64 runs of the author metric, brute-force and moarray tests ending in 29496 pass. These passing historical witnesses do not prove the broader v3 invariant.
Independent validation on Go1.27.0 Linux/amd64 with real AVX-512:
make -j8 cgo: PASS.- New admitted-input probes through both
SearchFloat32andSearch: default SIMD controls PASS; compile-time scalar fallback challenges FAIL. The runtime AVX opt-out also changes the BF16 unique winner. - A temporary source overlay adding only scalar metric-result NaN normalization makes both f32 top-2 probes PASS. This is an attribution/control experiment, not a delivered fix.
- Three 200ms samples at dim768: ordinary f32 cancellation 37.60–37.82 ns/op; finite-input exceptional recovery 842.1–864.6 ns/op; standalone scalar cancellation 203.0–233.5 ns/op. All zero allocations. This does not establish a base-to-head throughput regression or an ARM estimate.
- Exact-head required CI/SCA and executed UT/BVT jobs are green; skipped jobs are not counted as executed. Whitespace check passes. This round did not execute fresh ARM hardware, GPU, or a SQL server.
Keep the fix at the existing metric owner, reuse its scalar kernels and existing dispatch, and add a few compact sign-order/build-mode selection scenarios to existing fixtures. No duplicated consumer validators, additional state machine, or unconditional widening is justified by these findings.
Scope: 201 files, +4801/-1237; production/config 90 files +2504/-900, tests/BVT 106 files +2088/-331, docs 5 files +209/-6. The complete inventory is recorded, but this review does not approve every changed implementation/test hunk. Default activation, toolchain compatibility and the hot path trigger the mandatory design-first gate. Because the revised numerical design fails concrete counterexamples, downstream full hunk approval, including repository-wide lint cleanup, stops at that gate. The word Pending alone is not the reason for this decision.
…atrixorigin#29496) Address XuPeng-SH's review of the amended v3 contract. P2 #1 (code) -- the build-time scalar fallback could return NaN into ranking. The *Unrolled oracles are 8-wide unrolled, not strictly sequential, so a block of same-sign extreme-but-finite products overflows to +/-Inf and two opposite-sign blocks cancel to NaN -- the same artifact as the SIMD lanes, at block width. The non-SIMD wrappers (distance_func.go, selected when GOEXPERIMENT is unset) returned that NaN raw, unlike the SIMD recover* and the narrow scalar kernels. Witness (f32, dim64): query all 2^63; cand0 = 2^63 at 0..7, -2^63 at 32..39; cands [1,0,...] and [2,0,...]; top-2 returned [2,0] with a NaN distance instead of the finite [2,1]. Fix: bake the no-NaN finalizer into each ranking-distance oracle at its own return (matching innerProductBF16 / cosineDistClamped): InnerProductUnrolled -> nanToPosInf(-sum); CosineDistanceUnrolled -> cosineDistClamped (dropping its duplicate manual clamp); SphericalDistanceUnrolled -> nanToPosInf. CosineSimilarity is untouched (not a ranking metric; its only consumer is the boundary-checked moarray builtin, and +Inf is wrong-direction for a similarity). The non-SIMD wrappers need no change; the SIMD recover* outer nanToPosInf is now redundant and simplified away. Tests: a build-independent oracle test asserts the three oracles never return NaN on the block witness, and a non-SIMD-build brute-force test reproduces the reviewer's selection witness ([2,1], not a NaN winner). Both builds green. P2 #2 and P3 (design doc) -- narrow the cross-mode equivalence claim to exclude a genuine overflow a SIMD tier cancels across lanes to a finite (wrong) value, which the result-only recovery predicate cannot see (explicit domain limit, no precheck or widening); correct the first-bullet "sequential scalar sum stays finite" over-simplification (the oracle is unrolled); and replace the unsupported ~2x exceptional-path bound with bounded O(d) plus representative measurements. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
P2 #1 — code fix (the no-NaN hole in the build-time scalar fallback) Root cause confirmed exactly as you spotted: *Unrolled is 8-wide unrolled, not sequential, so it can itself return NaN — yet
Tests: build-independent oracle test (TestUnrolledOraclesNeverReturnNaN29496) — it caught a real slip in my own edit (I'd P2 #2 — doc (narrow the cross-mode equivalence claim) The block witness is also a P2 #2 case: a genuine overflow the SIMD lanes cancel to a finite-wrong 0, which the result-only P3 — doc (cost bound) Replaced "bounded at ~2×" with "bounded O(d), not a fixed 2×" + representative measurements (~850 ns/op exceptional vs ~38 |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of 5c449cfe837a...e5b07efab291, including implementation, tests, build/toolchain changes, design revisions, and the previous review threads. One confirmed P2 remains; see the inline comment. No subagents used.
Design and previous findings
The overall ownership is sensible: architecture-specific leaf kernels remain under the existing metric resolver; scalar arithmetic and non-finite result handling have shared owners rather than separate consumer-side implementations. The scalar-kernel move and removal of duplicate normalization/dead commented implementations are justified. I did not find a new state machine, persistent format, or asynchronous lifecycle introduced by these kernels.
The previous scalar NaN/fallback hole is now handled in the shared scalar implementation. SIMD non-finite IP/spherical/narrow-cosine recovery is connected to the native-type reference path. The cost claim now correctly describes a bounded extra O(d) pass, not a universal ~2× slowdown.
I accept the explicitly documented limited equivalence domain as the performance/design decision offered in the previous review: this does not establish universal scalar/SIMD equivalence for all extreme finite vectors, especially when the scalar accumulation overflows while a SIMD accumulation remains finite. This is an acknowledged domain restriction, not a numerical fix for that reverse case. Non-blocking documentation correction: §2 should not say finite stored vectors cannot produce the excluded case; accumulation order, rather than adding IEEE +Inf and −Inf to obtain zero, explains it.
The historical threads are marked resolved, and the substantive prior requests are addressed by code changes or this explicit design decision. That does not close the newly demonstrated platform-test failure.
Validation at this head
- Built the current native dependencies on darwin/arm64; reused only the checksum-verified, pinned ONNX prebuilt artifact.
- Ran the complete
metric,brute_force, andmoarraypackage tests with-count=1 -timeout=180sin three modes:GOEXPERIMENT=simd, no SIMD experiment, and SIMD withMO_METRIC_NO_NEON=1. All nine package runs passed. Expected NEON-only skips in the opt-out run are not counted as execution of that path. - Independent review-only boundary checks passed: public uint8 resolver results at dimension 65,535 against closed-form integer oracles, plus every finite Float16 bit pattern through the NEON decoder against the existing scalar decoder.
- Challenged CPU capability separately: the unchanged uint8 AVX-512 arithmetic body, isolated from MO's CGo dependencies, crashes with SIGILL under an amd64 environment reporting
AVX2=true, AVX512=false; a CPU-guarded control exits successfully. This was a Go 1.27 Rosetta probe compiled withGOAMD64=v1, not a claimed full amd64 MO package run. Source tracing confirms the new tests bypass the production dispatch. - Exact-head CI run completed successfully. Its green status does not validate the missing AVX-512-negative test boundary.
git diff --checkpassed.
Performance and test quality
Local Apple M4 microbenchmarks, dimension 1,024, three 100-ms samples: median float32 IP ~138.3 ns scalar vs ~73.82 ns SIMD (~1.87×); narrow L2-squared speedups ~3.34× BF16, ~1.92× F16, ~2.02× int8, ~1.99× uint8. All measured cases reported 0 B/op and 0 allocs/op. These establish normal-path kernel benefits, not end-to-end query throughput or worst-case recovery cost.
The new boundary, conversion, non-finite, public-search/SQL, and build-mode checks cover distinct contracts; their value is not inferred from added line counts. Implementation/build, test, and documentation changes were reviewed separately. No local full BVT or physical amd64/AVX-512 performance run is claimed; exact-head CI and the targeted local evidence have different scopes.
Please add the runtime capability guards identified inline and verify both AVX-512-present and AVX-512-absent execution. No production dispatch redesign is needed for this finding.
…out AVX-512 (matrixorigin#29496) TestL1DistanceUint8SIMD, TestNarrowSIMDMatchesScalar and BenchmarkL1DistanceUint8SIMD call the AVX-512 kernels directly; on an AVX2-only amd64 CPU they raised SIGILL. They now skip when hasAVX512 is false, as the neighbouring tests do; the AVX2 tests keep covering the narrow kernels there. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Re: [P2] direct AVX-512 tests/benchmark. Fixed in 1510785. TestL1DistanceUint8SIMD, TestNarrowSIMDMatchesScalar and |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-reviewed head 151078558a64e7189816e6d247bb4a76f94a5f11 against declared base 5c449cfe837ac90667c2a85ee3f442263440552c, carrying forward the complete implementation/design/test review and validation from the previous review. No subagents used.
The entire delta from the reviewed head is nine lines in one amd64 test file. All three affected entry points—TestL1DistanceUint8SIMD, TestNarrowSIMDMatchesScalar, and BenchmarkL1DistanceUint8SIMD—now skip before any kernel call when hasAVX512 is false. This closes the demonstrated SIGILL path. The existing capability owner includes the real CPU capability and the test opt-out; neighboring AVX2 tests retain their independent hasAVX2 guards and remain selected when AVX-512 is disabled. The change reuses the existing selection contract without adding a separate mechanism.
The author reports the focused tests and full metric package passing with AVX-512 enabled and disabled, including the expected three skips and continued AVX2 execution. I checked the complete delta and the guarding/selection paths. The previous ARM64 three-mode package runs, boundary checks, performance measurements, and production-path review remain applicable because production code, dependencies, build configuration, and the numerical design did not change. These are reused evidence, not newly claimed amd64 executions. git diff --check also passes at this head.
All blocking review requests are closed. The accepted extreme-value equivalence restriction remains a deliberate design limit; this approval does not expand it to universal cross-mode numerical equivalence. The previously noted non-blocking documentation inaccuracies about finite stored inputs and infinity cancellation remain unchanged and are still worth correcting.
No remaining blocking finding. Approve. The new CI run is still in progress at the time of review; this review does not represent it as completed or green.
Merge Queue Status
This pull request spent 1 hour 11 minutes 37 seconds in the queue, with no time running CI. ReasonThe pull request #29496 has been manually updated Waiting for any of
All conditions
Requeued — the merge queue status continues in this comment ↓. |
|
@mergify/Mergify |
golangci-lint v2.14.0 (the Go 1.27 toolchain's linter) reports six prealloc findings in code merged from main; each slice is now made with its final capacity. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@Mergifyio queue |
Merge Queue Status
This pull request spent 16 seconds in the queue, including 1 second running CI. Required conditions to merge
|
☑️ Command
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #29495
What this PR does / why we need it:
Adds arm64 (NEON) SIMD distance kernels to
pkg/vectorindex/metricand moves the build to Go 1.27, whosesimd/archsimdprovides the arm64 vector types.ARCHSIMD=1/GOEXPERIMENT=simdis now the default on arm64 as well as x86_64.LoadFloat32x16Slice→LoadFloat32x16,Store→StoreArray); int8/uint8 kernels use VPSADBW and VPMADDWD. SIMD file build tags move fromgo1.26togo1.27.go.mod→go 1.27.0. Build images and docs move to 1.27.0:optools/images/gpu/{Dockerfile,Dockerfile.dev}→golang:1.27.0-bookworm.optools/images/{Dockerfile,Dockerfile.ci,Dockerfile.ci-builder,Dockerfile.dev}→matrixorigin/golang:1.27.0-ubuntu22.04*.optools/bvt_ut/Dockerfile,optools/compose_bvt/Dockerfile.tester→matrixorigin/tester:go1.27.0-jdk8.BUILD.md,INSTALLATION.md,README.md: minimum Go 1.27.0.Static-check / linter (required by the Go 1.27 move)
Go 1.27 emits unified-IR export data at version 4. The
golangci-lintpinned ininstall-static-check-tools(v2.6.2) bundles anx/toolsthat caps export data at version 2, so under Go 1.27 every typecheck fails withexport data version 4 > max 2; its bundledhonnef.co/go/tools(v0.7.0) also panics inbuildiron Go 1.27 stdlib. CI runsgolangci-lint run -v -c .golangci.yml ./...over the full package graph withissues-exit-code: 2, so this is a hard gate, not advisory.golangci-lint→ v2.14.0 (x/tools that decodes export-data v4;honnefv0.8.1 that no longer panics).molintis unchanged. No.golangci.ymlrules were disabled or relaxed.prealloc(pre-size slices built in a loop), plus a fewgo/fixmodernizations (constraints.Ordered→cmp.Ordered,reflect.Ptr→reflect.Pointer) and oneineffassign. A handful of genuinely-intentional cases carry a scoped//nolintwith a reason (e.g. an append that must not pre-size).make static-check-analysisis clean on Go 1.27 (golangci-lintexit 0,molintexit 0).Validation (Linux amd64, AMD Ryzen AI 9 365 with AVX-512, RTX 5070)
MO_CL_CUDA=0 make -j8(aftermake clean): builds withgo1.27.0-X:simd,GOAMD64=v3; the amd64 SIMD kernels are linked (metric.hasAVX512present).MO_CL_CUDA=1 make -j8(aftermake clean, Pixi GPU profile): builds with-tags=gpu, cuVS/CUDA/RMM from the Pixi prefix, SIMD kernels linked.pkg/vectorindex/metrictests: pass on the AVX-512 tier and the AVX2 tier (MO_METRIC_NO_AVX512=1).golang:1.26.4-bookwormfailsgo list -mwith the error above;golang:1.27.0-bookwormbuildsoptools/images/gpu/Dockerfilefrom a clean clone andverify-runtime-image.shpasses.Validation (arm64 NEON — Apple Silicon, macOS, Go 1.27)
The NEON kernels this PR adds were exercised directly on real arm64 silicon (macOS/Darwin arm64,
go1.27.0 darwin/arm64,GOEXPERIMENT=simd). The build tags arearm64 && go1.27 && goexperiment.simd(no OS gate), so the same kernel set that ships for linux/arm64 is what is compiled and tested here.GOEXPERIMENT=simd go build ./pkg/vectorindex/metric/→ exit 0; the NEON file set (distance_func_arm64.go,distance_func_narrow_arm64.go,distance_func_narrow_{int8,uint8}_arm64.go) is selected by the build.pkg/vectorindex/metricfull suite: 65 subtests pass, including the NEON-vs-scalar equivalence checksTestARM64NeonMatchesScalarTail,TestBF16NeonMatchesScalar,TestF16NeonMatchesScalar,TestInt8NeonMatchesScalar,TestUint8NeonMatchesScalar,TestNarrowNeonExtremes, plusTestARM64KernelsAcrossDims, clamp/zero edges, and dimension-mismatch guards. Each NEON kernel is asserted bit-for-bit against its scalar reference.NEON vs scalar (
Benchmark_Narrow_NeonVsScalar, l2sq, 0 allocs/op):GPU (cuVS/CUDA) and the amd64 AVX-512/AVX2 kernels cannot run on this arch and are covered by the Linux amd64 box above; the arm64 NEON path — the feature this PR is named for — is covered here.
amd64 distance benchmarks: no regression on SIMD paths
Base:
mainat 9e50a0f (the branch's merge base) built with go1.26.5; head: this branch with go1.27.0. Both use this branch'sdistance_func_bench_test.go(fixed 256-vector pool; main'sb.N-sized pool measures memory bandwidth).GOEXPERIMENT=simd GOAMD64=v3, 10 alternating runs × 94 benchmarks,benchstat -alpha 0.01.~)The f16 scalar fallback runs only for vector tails and in
ARCHSIMD=0builds; this branch changes only Go 1.27 API names in that file.Full benchstat
🤖 Generated with Claude Code