Repository navigation
IVFFLAT/IVFPQ/CAGRA support bf16, float16, int8 and uint8 quantization - #25095
Conversation
…column types Add SupportedVectorTypes(), SupportedPrimaryKeyTypes(), and SupportedIncludeColumnTypes() to the index-plugin catalog Hooks (plus helper predicates), so plan validators and table functions can query what each index plugin supports instead of hardcoding type lists. Nil-slice semantics: vector nil = none supported; primary-key nil = any type; include-column nil = none. Each plugin (cagra / ivfpq / ivfflat / hnsw / fulltext) declares its supported types in runtime/schema; consumed by validateIncludeColumns in build_ddl / plugin_builder and by the GPU/CPU create+search table functions through a shared CatalogHooks. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Verify the pkg/vectorindex/metric distance types (L2 / L2sq -> L2Expanded, inner_product -> InnerProduct, cosine -> CosineExpanded) are supported by the CAGRA and IVF-PQ GPU indexes: each builds, searches, returns the correct nearest neighbor, and returns a score with the right sign (InnerProduct is negated on the C++ side to match MatrixOne's inner_product ordering). Behind the `gpu` build tag. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-metric error
Two bugs found in branch self-review:
1. RunCuvs / runHnsw leaked the sync (GPU/native index resources) when the
factory/NewSync constructed it inside the txn callback but the wrapping
transaction commit then failed: the early `if err != nil { return }` was
placed before the `defer sync.Destroy()`, so the constructed index was never
released. Destroy it in the error branch (pkg/iscp/cuvs_writer.go,
index_consumer.go).
2. CagraSearch/IvfpqSearch.buildMultiIndex returned a nil index on an
unsupported metric, which Load swallowed and Search treated as an (empty)
success — masking a real misconfiguration. buildMultiIndex now returns
(idx, error): a bad metric is an error, while the legitimate empty-index case
still returns (nil, nil). Load propagates it (the existing defer cleans up).
Updated the 5 search_test.go call sites.
go vet -tags gpu clean for cagra/ivfpq/iscp.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…apshot docs From branch self-review (non-bug nits): - idxcron CuvsUpdatable counts CDC-tail growth straight from the chunk frame header (UnframeCdcChunk -> n_inserts + n_upserts), so deriveCuvsRecordShape (which parsed the TableDef + resolved INCLUDE columns every tick to produce a dim/includeBytesPerRow that countTag1Records discarded) was pure waste. Remove it and includedColumnsFromAlgoParams, the orphaned pb/plan import, and the unused params; fix the stale countTag1Records doc. The real decode path (cdc.go DecodeEventRecord, used by replay/load) is untouched. (+8 / -86) - cuvs_worker.hpp: add a "DECLARATION ORDER IS LOAD-BEARING" guard comment at the search-workspace uvectors — they must be declared after res_ so they're freed (into the stream-ordered pool) before the worker stream is destroyed; reordering would re-introduce the cudaErrorInvalidResourceHandle pool poisoning. Also refresh the now-stale "ensure_rmm_pool_for_device" comments to reference worker_pool_mr (it's a no-op post-plan-C) in cuvs_worker.hpp / ivf_pq.hpp. - cagra/ivfpq create table functions: document that the CDC-cutoff COUNT(*) runs via NewSqlProcess(proc) on the same txn/snapshot as the source-row stream, so the rowsSeen >= cdcCutoff split can't drift under concurrent writes. Verified: idxcron + cuvs + iscp unit tests pass; go vet -tags gpu clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In SHARDED mode each rank owns one shard with its own shard_offset, but the
per-shard deleted-bitset cache (gpu_index_base_t::device_shard_bitsets_) was
keyed by physical device_id. Under the gpu_multi_simulation [0,0,...] device
list multiple ranks map to one physical device, so two shards collided on a
single device-0 cache entry; with version-based invalidation the second shard
saw the same bitset_version_ and reused the first shard's slice — dropping that
shard's deletes, so filtered SHARDED search returned soft-deleted rows. Real
multi-GPU is unaffected (device_id is unique per shard there).
Fix: key device_shard_bitsets_ / sync_shard_bitset / acquire_delete_bitset_device
by rank (consistent with replicated_indices_/replicated_datasets_). The full
deleted-bitset cache (device_deleted_bitsets_, REPLICATED/SINGLE) stays
device_id-keyed since replicas share an identical bitset per physical device.
Tests:
- C++ cgo/cuvs/test/ivf_flat_test.cu::SimulatedShardedDeleteSearch
- Go pkg/cuvs/simulation_test.go::TestSimulatedShardedDeleteIvfFlat
(build a SHARDED [0,0] index, soft-delete one row per shard, assert excluded;
cross-shard is guaranteed via the explicit in-order dataset)
- BVT test/distributed/gpu_cases/vector/vector_sharded_filtered.sql
(filtered SHARDED search under simulation; the per-shard user-filter half)
- BVT pessimistic_transaction/vector/vector_{ivfpq,cagra}_sharded_delete.sql
(end-to-end CDC/ISCP soft-delete across shards)
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…key doc drift Follow-ups from the SHARDED rekey review (the device_shard_bitsets_ rank fix is in 32aa19c): - brute_force build: wrap cuvs::neighbors::brute_force::build in device_build_mutex(get_device_id()) for consistency with ivf/cagra's per-physical-device serialization of index-mutating GPU calls. brute_force has no device-global kmeans workspace, so this is policy consistency rather than a known race; nesting it innermost under this->mutex_ is deadlock-free (ivf/cagra never hold this->mutex_ while holding device_build_mutex, so no lock-order cycle). - doc drift: replicated_indices_/replicated_datasets_ are rank-keyed now, but several comments still said [dev_id]/[last_dev_id]. Updated them to [rank] (index_base.hpp, ivf_flat.hpp, ivf_pq.hpp). The "serialize ... same physical device" comments are left as-is — they describe device_build_mutex, which is correctly physical-device-keyed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…to gpu_multi_simulate
The CAGRA/IVF-PQ GPU create path derived the small-tail CDC cutoff from a plain COUNT(*), but the row loop advanced the build cursor (rowsSeen) before skipping NULL-vector rows. NULL rows could shrink the final build chunk below the cuVS minimum graph size. - fetchSrcTableRowCount now counts only rows with a non-NULL indexed vector (WHERE <vec> IS NOT NULL), passed via tblcfg.KeyPart. - The build cursor advances only after the NULL check, so NULL rows no longer move the chunk/cutoff position. - Shared identically between CAGRA and IVF-PQ. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ALTER TABLE COPY's cloneUnaffectedIndex inferred "skip the whole index" from SyncDescriptor.UsesCDC, which wrongly caught async IVF-FLAT: its metadata + centroids were never cloned, so CDC rebuilt entries against an empty seed k-means model. - Add AlterTableCloneBehavior.SkipWholeIndex; alter.go reads it instead of inferring from UsesCDC. - HNSW/CAGRA/IVF-PQ/fulltext set it true (they rebuild every hidden table via CDC from ts=0); IVF-FLAT leaves it false and uses its per-hidden-table policy (delete all three, clone metadata+centroids, skip only entries when async). UsesCDC stays: it still gates CDC task creation / sinker type in iscp_util.go, which is orthogonal to the clone decision. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Index plugins and the cuVS CDC/idxcron helpers assembled identifiers and literals by string concat, which breaks (or injects) on a backtick in a db/table/column name or a single quote in a JSON params blob. - Add pkg/common/sqlquote: Ident / QualifiedIdent (backtick-quote, doubling embedded backticks) and EscapeString / String (single-quote escape), with property + injection tests. - Route the CAGRA/IVF-PQ/HNSW plugin compile builders, the cuVS cdc/idxcron/model/build helpers, and the fulltext/IVF-FLAT iscp sinker through it. For ordinary names/literals the generated SQL is byte-identical to before (proven by Ident/String no-op property tests + golden CROSS APPLY templates); the helpers only change output for the special-char inputs that were already producing broken SQL. Identifiers stay column references (backticks), params/config stay string literals (single quotes) -- kinds preserved. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
encodeInsertOrUpsert mapped both an absent vector AND a non-nil value of the wrong type to a DELETE (`if !ok || v == nil`). A type mismatch is a real schema error, not a NULL vector — silently turning it into a DELETE drops the row from the index without any signal. Split the cases (mirrors the HNSW sinker): a nil interface or typed-nil []float32 slice still maps to DELETE (actually-absent vector), but a non-nil wrong-type value now returns an error. Adds a table-driven test covering all four cases. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a CPU-reachable BVT that pins the new index-plugin dispatch and
experimental-flag behavior for the GPU-backed algorithms:
- experimental_ivfpq_index / experimental_cagra_index default to 0, are
settable to 1, and read back.
- With the flag enabled, CREATE INDEX ... USING ivfpq/cagra on a CPU-only
build is rejected cleanly ("unsupported index type") rather than
crashing or silently building an empty index.
- Both flags are reset to 0 after use so they don't leak into other cases
sharing the session.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vector_ivfpq_cagra_cpu asserted CREATE INDEX USING ivfpq/cagra fails with "unsupported index type" — but that outcome is build-dependent: on a GPU build the same DDL succeeds. A CPU cases/ case whose .result flips by build can't be run or regenerated on a GPU box, so it doesn't belong there. The experimental-flag + plugin-dispatch coverage it was meant to provide is covered build-independently by vector_index_plugin_smoke and fulltext_plugin_smoke (HNSW/IVF-FLAT/fulltext), plus the GPU snapshot case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Build-independent CPU BVTs exercising the new index-plugin framework on the non-GPU surface: - vector_ivfpq_cagra_experimental_var: the experimental_ivfpq_index / experimental_cagra_index variable surface only (default, SET, SET GLOBAL, SHOW VARIABLES) — no index is created, so the result is identical on CPU and GPU builds. - vector_index_plugin_smoke: HNSW (flag gate off->error, on->build) and IVF-FLAT dispatch end to end — plugin registration in mo_catalog.mo_indexes, SHOW CREATE TABLE round-trip, and a vector search. - fulltext_plugin_smoke: the fulltext plugin dispatch — registration, SHOW CREATE TABLE round-trip, and a MATCH query. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a gpu_cases/snapshot BVT (mirroring cases/snapshot/fulltext_snapshot_ restore.sql) that builds an IVF-PQ / CAGRA index, snapshots, mutates, then restores the snapshot view and confirms the index survived: row count restored, index def intact via SHOW CREATE TABLE, and — after a sleep for the async CDC tail to catch up — the vector search returns the restored rows (1,2,3). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a gpu_cases/snapshot BVT that exercises the real restore path (not a data-level re-insert): a sub-account owns ivfpq/cagra indexes, sys snapshots the account, the account turns the experimental flags OFF and drops its database, then `restore account ... to account ...` recreates the tables and replays CREATE INDEX in a background context. Verifies: - restore succeeds with the flags off — confirming the experimental gate is bypassed on background re-entry (IsFrontend()=false); - row count + index defs are restored (count=20, SHOW CREATE TABLE); - both indexes are searchable (1,2,3) after a sleep for the async CDC tail to rebuild — restore excludes the index hidden tables (snapshot.go:1945) and rebuilds the model from re-inserted main-table data via CDC, so the sleep is required by design. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…reBehavior hook Make snapshot/restore (and idxcron/async builds) reconstruct a vector index using the session variables it was CREATEd with — kmeans_train_percent, capacity, thread counts — instead of background-session defaults, so a restored index matches the original rather than a degenerate seed. Index-plugin framework: - RestoreBehavior() catalog hook (mirrors AlterTableCloneBehavior) + the IsTableClone() compile signal — all plugins return the zero value, the foundation for direct hidden-table restore - RestoreInitSQL() compile hook drives the post-clone rebuild; vector plugins emit ALTER ... REINDEX ... FORCE_SYNC (new grammar) Session-var preservation: - BuildSessionVars() per plugin names the build-determining vars - CreateIndexDef (now ctx-threaded) captures them into algo_params.session_vars (typed, sorted/deterministic) at CREATE INDEX - the clone (preserveIndexSessionVars) and ALTER REINDEX rewrites keep them - ISCP ProcessInitSQL reads session_vars and runs the InitSQL build via sqlexec (background) with an overlay resolver, so the cuvs/ivfflat build resolves the captured values; load/parse errors are surfaced fulltext restore: register the CDC with startFromNow=true + a no-op "SELECT 1" InitSQL (post-clone watermark, no snapshot-TS replay). Tests: plugin RestoreBehavior/BuildSessionVars assertions; regenerated the affected gpu_cases .result files; added serial account-restore + session_vars BVTs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Index-defining build knobs (kmeans_train_percent, kmeans_max_iteration, max_index_capacity) become first-class CREATE INDEX options, parsed and stored in algo_params, instead of relying on ambient session variables. - Parser/tree/catalog: new index options + SHOW CREATE round-trip. - Per-algo param parsing moves from catalog.indexParamsToMap into each plugin's Catalog().ParamsFromTree hook (dispatched from build_ddl); catalog keeps only the algo-agnostic marshalling helpers. - types.go: IndexCapacity moves IndexTableConfig -> IndexConfig; kmeans fields move into IvfflatIndexConfig. Build read sites resolve each param as: flat algo_params key -> session variable -> hardcoded default (pkg/indexplugin/buildparam.go). - Keys appear in algo_params only when set in CREATE INDEX; otherwise the session variable still controls the build (backward compatible), so an unset option never pollutes algo_params/SHOW CREATE. - BuildSessionVars emptied for ivfflat/hnsw/fulltext (algo_params stays byte-compatible with pre-session_vars indexes); BuildAlgoParams hook removed. - Tests + BVTs (vector smoke, GPU ivfpq/cagra account-restore serial) updated to set the params via DDL so restore reproduces the build. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
idxcron now resolves index-defining build knobs from the index's algo_params (set via CREATE INDEX), the same source restore uses — closing the asymmetry where idxcron preserved create-time session-var values that restore did not. - Drop kmeans_* / *_max_index_capacity from the IdxcronVarSpec.Capture sets (ivfflat, ivfpq, cagra). The idxcron reindex reads them from algo_params (DDL) -> default, like restore. - IVF-FLAT Updatable: read kmeans_train_percent from algo_params for the nsample heuristic, and drop the per-tick Metadata.Modify clamp. The clamp was already inert for DDL-specified indexes (ivf_create reads the flat key first) and contradicted the DDL-authoritative model; the 2*interval cadence band on large training sets is kept. - Tests updated: idxcron drives the gate via algo_params; compile tests assert capacity is no longer captured into idxcron metadata. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The experimental-flag gate in each plugin's handleCreate is guarded by `if ctx.IsFrontend()`, so the background reindex (restore ProcessInitSQL, idxcron — both IsFrontend=false) never evaluates it. Capturing the flag into algo_params.session_vars (ivfpq/cagra BuildSessionVars) and the idxcron task Metadata (ivfflat/ivfpq/cagra IdxcronVarSpec.Capture) was dead weight; drop it. lower_case_table_names is kept: it is ScopeGlobal but the background resolver (executor.DefaultResolveVariable) returns the hardcoded default rather than the deployment's live global, so the create-time value is still needed for source-table name resolution in the rebuild SQL. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # pkg/txn/storage/memorystorage/memorytable/vector_utils.go
|
Re: [P1] prefix-only quantizer training — contesting the blocking status The mechanism is correctly described, but the conclusion treats a user-controlled sampling budget as a correctness defect. quantizer_train_limit is
So the design loses nothing relative to the "must be representative" requirement: the exact-range behavior is available on request via a single On reachability of the failure itself: it additionally requires coordinates that increase monotonically with arrival order (value ≈ row_id). Real ANN If the concern is visibility rather than capability, the proportionate change is a warning (or a note in SHOW CREATE) when QUANTIZER_TRAIN_LIMIT < The prior blockers are closed on this head: narrow generic paths covered; IVF-FLAT int8/uint8 allowlisted to L2/L2sq with REINDEX params merged |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes — re-reviewed exact head 858aa01ce0461ad6b81890e6d28b3b410f2698d0 and reconsidered the latest author comments.
I am withdrawing the previous prefix-training blocker. quantizer_train_limit is an explicit quality/memory budget, the default covers up to 100k rows, setting it at least to the row count restores whole-table training when memory permits, and mandatory full-table retention/replay would undo this PRs main bounded-memory benefit. The ordered-input case remains a quality caveat worth documenting, but it is not a P1 correctness blocker under this contract. I also verified that the generic narrow-type closure, IVF-FLAT L2/L2sq gate, result rescaling, full-table staging, async result draining, and the latest batch CSV/JSONL export fix are closed.
One independent merge blocker remains:
[P1] Make IVF-FLAT int8/uint8 encoding bit-identical across sync build, CDC, and search
The stated invariant that entry and query use the same q(x)=round(x*mul+add) is not true at float32 boundaries.
The synchronous build serializes mul and add with only 9 significant digits in Int8EntrySQL/Uint8EntrySQL. For a vecf32 base, the arithmetic type rules then coerce those literals to float32 and the engine rounds once after multiplication and again after addition. Search instead keeps the parameters as float64, performs one float64 multiply-add in ApplyInt8/ApplyUint8, and rounds only the final float32. For a vecf64 base there is another asymmetry: the entry expression applies the transform to f64, while runIvfSearchVectorToF32 first discards the querys f64 precision. The CDC expression is independently re-derived in SQL, so there is currently no single canonical rounding contract across the three writers/readers.
Concrete reachable reproduction for int8: trained bounds [0.1, 0.99] produce mul=286.51685393258424, add=-156.65168539325842. For a stored vecf32 component 0.367, synchronous entry SQL is emitted as cast(v * 286.516854 + (-156.651685) as vecint8(...)); with the actual vecf32 scalar-arithmetic rules its intermediate is exactly -51.5, so it stores -52. Search receives the same float32 value but ApplyInt8 produces -51.499996, so it sends -51. A nearby row 0.3670001 is stored as -51; therefore an exact query for 0.367 can give the nearby row zero quantized distance while its own row has non-zero distance. Repeating the boundary component across dimensions magnifies the error. Uint8 has the same defect.
Please define one canonical precision and operation ordering, use it for synchronous entries, CDC entries, and query encoding, and add cross-path boundary regressions for f32 and f64 bases with both int8 and uint8. The regression should compare actual entry-expression execution against query encoding, not only test the SQL string and Go helper separately.
Relevant code:
matrixone/pkg/vectorindex/quantizer/quantizer.go
Lines 148 to 179 in 858aa01
matrixone/pkg/vectorindex/quantizer/quantizer.go
Lines 216 to 245 in 858aa01
matrixone/pkg/sql/plan/function/type_check.go
Lines 1197 to 1221 in 858aa01
matrixone/pkg/sql/colexec/table_function/ivf_search.go
Lines 272 to 289 in 858aa01
Non-blocking documentation cleanup: cagra_create_gpu.go and ivfpq_create_gpu.go still say the C++ default is 1000, and both quantizer-train-limit GPU cases still describe strided sampling/default 1000. The implementation/header now use prefix staging/default 100000; these comments should match the contract relied upon in the author response.
Validation: focused CPU/CGo tests passed across changed container, planner/function, frontend, CDC/ISCP, colexec, all CPU-visible vector-index plugin, disttae, and TAE packages. Targeted race tests passed for types/vector/cache/cuvs/ivfflat/quantizer. Current GitHub UT/SCA/BVT/Coverage checks are green. GPU-only packages cannot execute on this Darwin host and were audited statically.
jiangxinmeng1
left a comment
There was a problem hiding this comment.
Reviewed the current head (858aa01). The earlier
issues appear resolved, but one merge blocker remains.
[P1] Use identical int8/uint8 encoding across build, CDC, and search
The three paths do not currently implement a bit-identical q(x) = round(x * mul + add)
operation:
-
The synchronous build serializes mul and add with only 9 significant digits. For
vecf32, SQL arithmetic also rounds after multiplication and again after addition. -
Search performs the multiply-add in float64, converts the final result to float32,
and only then rounds to int8/uint8. -
The CDC path independently reconstructs the expression in SQL.
-
For a vecf64 base, build quantizes the original float64 value, while search first
downcasts the query to float32.
Values near a bucket boundary can therefore be stored in one bucket but encoded into
another during search. An exact query may have a non-zero distance from its own row
while a nearby row has zero distance.
Please define a single precision and operation-ordering contract and reuse it for
synchronous build, CDC, and query encoding. Add end-to-end boundary tests for both
float32 and float64 bases with int8 and uint8 storage.
Relevant code:
matrixone/pkg/vectorindex/quantizer/quantizer.go
Lines 148 to 179
in
858aa01
matrixone/pkg/vectorindex/quantizer/quantizer.go
Lines 148 to 179 in 858aa01
matrixone/pkg/vectorindex/quantizer/quantizer.go
Lines 216 to 245
in
858aa01
matrixone/pkg/vectorindex/quantizer/quantizer.go
Lines 216 to 245 in 858aa01
matrixone/pkg/sql/plan/function/type_check.go
Lines 1197 to 1221
in
858aa01
matrixone/pkg/sql/plan/function/type_check.go
Lines 1197 to 1221 in 858aa01
matrixone/pkg/sql/colexec/table_function/ivf_search.go
Lines 272 to 289 in 858aa01
…/search The int8/uint8 scalar quantizer encoded q(x)=x*mul+add inconsistently on the three paths, so the same vector could get different codes on build vs query and an exact NN query could rank a neighbor above its own row (IVF-FLAT re-ranks in the quantized domain with no source-vector re-rank, so the mismatch reaches the result): - entry SQL evaluated `vecf32 * scalar + scalar` in float32 (VECF32<op>Scalar => VECF32, two roundings) with float32-coerced literals, while a vecf64 base evaluated in float64; ApplyInt8/ApplyUint8 used a single float64 multiply-add with full-precision params. Define one canonical contract — q(x)=clamp(round_int8( f32(x)*f32(mul)+f32(add) )) in float32 — and use it everywhere: 1. ApplyInt8/ApplyUint8 compute in float32 with float32-narrowed params, forcing the intermediate to a float32 var so it rounds twice like the SQL (not one fused f64 op). 2. Int8/Uint8EntrySQL and the *FromBounds (CDC) variants wrap the column in cast(... as vecf32) so both a vecf32 and a vecf64 base evaluate on the same float32 value the query is narrowed to; CDC `add` grouped as min*(255.0/rng) to match the build's divide-then-multiply order before the f32 coercion. Regressions: TestQueryEntryEncodingContract asserts ApplyInt8/ApplyUint8 are bit-identical to the float32 entry arithmetic across a sweep and diverge from the old float64 path at the documented [0.1,0.99]/0.367 boundary; the vector_ivf_quant_boundary BVT executes the actual entry SQL and asserts a vecf32 base and a vecf64 base produce identical codes (0.367 -> -52, 0.3670001 -> -51 on both). Also fix stale cagra/ivfpq quantizer-train-limit comments (prefix staging, default 100000, not 1000). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
fixed. please review again. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes — deep-reviewed exact head 1b66d898ce6d9c73fd34267a34ff834bf80c2e81 and the latest “fixed” comment.
[P1] Explicitly round the float32 product; a temporary variable does not prevent FMA
ApplyInt8 and ApplyUint8 claim that m := x * fmul forces the product to be rounded before the add. That is not a Go guarantee. The Go spec explicitly permits fusing t = x*y; r = t+z across statements; an explicit conversion is required to prevent fusion. This is directly reachable in MatrixOne because the Makefile defaults GOAMD64 to v3, and the current compiler emits VFMADD231SS for these loops.
With trained bounds [0.1, 0.99]:
- int8,
x = math.Float32frombits(0x3de5d15a)(0.11221571): SQL's separate float32 operations produce-124.5and encode-125; the v3 query encoder fuses to-124.49999and encodes-124. - uint8,
x = math.Float32frombits(0x3dd05fbc)(0.1017451): SQL produces0.5 -> 1; fused query encoding produces0.49999908 -> 0.
A focused regression passes with GOAMD64=v1 and fails with the repository-default GOAMD64=v3 (expected -125, actual -124). Therefore build/CDC and search are still not bit-identical, and an exact query can be assigned to the adjacent bucket. The new TestQueryEntryEncodingContract masks this because entryInt8/entryUint8 use the same fusible temporary-variable pattern as production, so both sides fuse together.
Please force the product rounding with an explicit conversion (for example m := float32(x * fmul)) or define the SQL path to use the identical fused contract. The reference test must model actual SQL's separate operator execution, and should include these int8/uint8 FMA-boundary cases under GOAMD64=v3.
I rechecked the related discussion: the quantizer_train_limit explanation is reasonable and remains non-blocking; the prior generic-type, IVF-FLAT metric/scale, full-staging, async-drain, and export blockers are closed. Focused v3 tests for quantizer, IVF-FLAT, compile hooks, and the IVF search table function pass, but they do not exercise this FMA boundary.
…conversion)
ApplyInt8/ApplyUint8 computed q(x)=x*mul+add as `m := x*fmul; sq[i]=m+fadd`.
A plain temp var does NOT prevent the compiler from fusing the multiply-add
into one FMA (Go spec: only an explicit conversion is a rounding barrier), and
the build defaults have hardware FMA (GOAMD64 ?= v3 -> VFMADD231SS; arm64
always). A fused MAD rounds once, but the entry SQL
`cast(cast(v as vecf32) * mul + add as vecint8)` evaluates as two separate
float32 operations (two roundings), so at a bucket boundary the query encoded a
component into the adjacent bucket -> an exact query could rank a neighbor above
its own row.
Wrap the product in an explicit float32() conversion so build/CDC/search all
round the product identically:
m := float32(x * fmul)
sq[i] = m + fadd
Tests: entryInt8/entryUint8 helpers now use the same explicit-conversion form so
they model SQL's separate operations instead of fusing alongside production and
masking the bug; TestApplyFMABoundaryMatchesSQL is an independent oracle asserting
ApplyInt8/ApplyUint8 reproduce the live-verified SQL codes (-125, 1) at the exact
float32 bit-patterns where a fused MAD lands in the adjacent bucket. Passes on
arm64 hardware FMA (equivalent to GOAMD64=v3).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Re: [P1] explicitly round the float32 product — fixed in 6cba7fe You're right on all counts — a temp var is not an FMA barrier, and with GOAMD64 ?= v3 (VFMADD231SS) / arm64 hardware FMA the multiply-add fused to
Fix: wrap the product in an explicit float32() conversion in ApplyInt8/ApplyUint8 — the Go spec's guaranteed rounding barrier — so build/CDC/search m := float32(x * fmul) // explicit conversion rounds the product; blocks FMA fusion Test fixes (you correctly caught the masking):
Closure verified: ApplyInt8/ApplyUint8's only caller is the IVF-FLAT query re-rank (ivfflat/search.go), and build/CDC write via the SQL entry |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The FMA barrier fixes the latest reported case, but synchronous int8/uint8 build encoding can still differ from CDC/search because its float64 parameters are formatted before narrowing to float32.
P1 - Narrow quantizer parameters before serializing entry SQL (pkg/vectorindex/quantizer/quantizer.go:199)
%.9g guarantees round-trip only when formatting a float32 value, but these builders format the original float64 mul/add. The emitted decimal can therefore parse to an adjacent float32 from float32(mul) used by ApplyInt8/ApplyUint8. Concrete reachable example: stored bounds [0, 7.75195541] yield mul=32.89492605582467; search narrows this to float32 bits 0x42039467, while entry SQL emits 32.8949261, which parses to 0x42039468. For component bits 0x3ea36df5 (0.31919828057289124), the separate float32 operations produce -117.5 -> -118 in search but -117.499992 -> -117 in the synchronous int8 entry; uint8 similarly differs by one bucket. CDC computes the parameter from bounds in SQL and therefore follows the search-side narrowing, so rows can also change buckets depending on whether they arrived during build or through CDC. Format explicitly narrowed parameters (including add) and add a regression where formatting the float64 directly crosses a float32 boundary.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes — deep-reviewed exact head 6cba7fe2984141144b2160d582cacff3cf4fd4ee, including the latest review and the author's FMA response.
The explicit float32(x * fmul) conversion is correct and closes the previous FMA-fusion blocker. One independent deterministic correctness issue remains:
[P1] Narrow mul/add before formatting synchronous entry SQL
Int8EntrySQL and Uint8EntrySQL use %.9g on the original float64 parameters. Nine significant digits round-trip a float32 value, but formatting an adjacent float64 first can emit a decimal that narrows to the neighboring float32 from float32(mul)/float32(add) used by search.
I independently reproduced the current head with stored bounds [0, 7.75195541]:
mul=32.89492605582467- search parameter:
float32(mul)= bits0x42039467 - synchronous build emits
32.8949261, which the vecf32 scalar-arithmetic rule narrows to bits0x42039468 - int8 component
0x3ea36df5(0.31919828): search encodes-118, synchronous build encodes-117 - uint8 component
0x3c79090d(0.015199912): search encodes0, synchronous build encodes1
This is reachable because type_check.go coerces a scalar paired with VECF32 to FLOAT32. Search reads the metadata bounds and narrows the computed parameters directly; CDC computes them from the same bounds in SQL and is narrowed by that rule. Only synchronous build serializes the pre-narrowed float64 values, so initial rows and CDC rows can occupy adjacent buckets for the same source value.
Please format explicitly narrowed values for both parameters (for example, serialize float32(mul) and float32(add) with float32 round-trip semantics) and add a regression that parses/executes the generated SQL at a float32-format boundary and compares it with ApplyInt8/ApplyUint8 for both int8 and uint8.
Related-comment disposition: the FMA comment is correctly fixed; the quantizer_train_limit explanation remains a non-blocking quality/memory contract; the prior generic-type, IVF-FLAT metric/scale, full-staging, async-drain, and export findings remain closed.
Validation on this head: quantizer tests and -race passed under GOAMD64=v3; focused IVF-FLAT build/search hooks and narrow-vector function tests passed. A one-off exact regression reproduces the adjacent-bucket mismatch, which the current tests do not model because they reuse the in-memory float64 parameters instead of reparsing the generated SQL literals.
Int8EntrySQL/Uint8EntrySQL formatted the original float64 mul/add with %.9g. Nine significant digits round-trip a float32, but formatting the float64 first can emit a decimal that narrows to the NEIGHBORING float32 from float32(mul) — which ApplyInt8/ApplyUint8 (search) and the CDC SQL narrowing (type_check.go: VECF32 <op> Scalar => VECF32) both use — so the synchronous build could store a boundary component one bucket off from search/CDC. Reproduced: bounds [0, 7.75195541] give mul=32.89492605582467; float32(mul) is bits 0x42039467, but %.9g(float64)="32.8949261" narrows to 0x42039468. At int8 component 0x3ea36df5 search encodes -118 while build encoded -117; at uint8 component 0x3c79090d search 0 vs build 1. Format the float32-narrowed params (float32(mul)/float32(add)) so the emitted literal round-trips to exactly the float32 all other paths use. The *FromBounds (CDC) builders compute params in SQL from bounds and already follow that narrowing, so only the literal-bounds builders change. Tests: TestEntrySQLParamNarrowedToFloat32 parses the generated SQL literals, asserts the precondition (raw-float64 %.9g crosses a float32 boundary), that the emitted literals round-trip to float32(mul)/float32(add), and that build and search encode the reported int8 AND uint8 boundary components to the same bucket. Existing builder-string tests updated to the narrowed literals. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # pkg/sql/plan/function/function_id.go # pkg/sql/plan/function/function_id_test.go
|
Re: [P1] narrow mul/add before formatting entry SQL — fixed in bea21bc Correct, and thanks for the second reachable component — reviewed head 6cba7fe was the FMA-fix commit, one before this. I reproduced both cases
Fix (Int8EntrySQL/Uint8EntrySQL): format the float32-narrowed params so the literal round-trips to the exact float32 search/CDC use: Regression (TestEntrySQLParamNarrowedToFloat32) — exactly your ask, for both int8 and uint8: it parses the generated SQL literals, asserts the Closure: build (literal params, now narrowed), CDC (SQL-computed, narrowed by coercion), and search (float32(mul) in ApplyInt8) all resolve to the |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The merge from main preserved the PR’s narrow-vector integrations but did not touch any of the three prior findings. All remain reproducible on head 32d014f.
P1 - Do not globally raise the default x86 CPU baseline to GOAMD64=v3 (Makefile:247)
Before this PR, make build used Go's x86-64-v1 default. This assignment compiles every package in mo-service, mo-tool, musl builds, and repository Docker artifacts for x86-64-v3, so binaries that previously ran on v1/v2 CPUs will no longer start. Runtime feature checks inside metric kernels cannot protect a binary globally compiled for v3, and default builds do not pass ARCHSIMD=0. Preserve the compatible default baseline or make the v3 artifact explicit.
P1 - Clamp SIMD cosine similarity to [-1, 1] (pkg/vectorindex/metric/distance_func_amd64.go:483)
The scalar implementation clamps dot/den, but both SIMD similarity implementations return the raw quotient. Float32 vectors with bit patterns [bb667df6,3ea790ea,c31cb60c,3d8855cd] and [be9dc4d1,41e564b9,c6568888,40baa3a1] compute dot=2151674.5, normA=24558.486328125 and normB=188517392, returning 0x3f800001 (1.000000119). That invalid value reaches SQL when both operands are constants or both are columns, while the const-versus-column batch path derives similarity from clamped cosine distance and returns 1.0. Clamp both F32 and F64 results and test the range across query shapes.
P2 - Quote narrow-vector fields in checkpoint SQL-load CSV (pkg/tools/checkpointtool/table_dump.go:3137)
shouldQuoteSQLLoadType quotes vecf32/vecf64 but omits vecbf16, vecf16, vecint8, and vecuint8. The default streaming dump therefore sends these values through the unquoted path; RowToString emits forms such as [1, 2], whose comma becomes a CSV column separator during LOAD DATA. Checkpoint dumps containing the new vector types are malformed. Quote every array-related OID and add round-trip coverage for all four new types.
Address two Codex review findings on the narrow-vector PR: - Clamp CosineSimilarityF32/F64 SIMD kernels to [-1,1]. The scalar CosineSimilarity clamps, but the SIMD variants returned the raw quotient, so float32 accumulation could emit 1.000000119 (0x3f800001). Mirror the scalar path and cosineDistClamped. Add TestAMD64CosineSimilarityUpperClamp. - Quote vecbf16/vecf16/vecint8/vecuint8 in the checkpoint SQL-load CSV dump. shouldQuoteSQLLoadType only quoted vecf32/vecf64; the four new narrow types render as "[1, 2]" whose comma splits the CSV column under LOAD DATA. Add the four OIDs and a round-trip test for all of them. Also document the intentional GOAMD64=v3 default in the Makefile: the narrow-vector SIMD kernels and the Go simd experiment require the Haswell baseline; pre-Haswell CPUs build with ARCHSIMD=0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
P1 — GOAMD64=v3 default (Makefile:247): Noted your decision. Owned as intended (v3 needed for bf16), won't re-raise. P1 — SIMD cosine similarity not clamped (distance_func_amd64.go:483) — FIXED. P2 — narrow-vector fields unquoted in checkpoint CSV (table_dump.go:3137) — FIXED. Verification
|
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
One non-blocking planner omission remains: narrow-vector IVFFLAT joins do not use the index. No blocking correctness regression remains after accounting for the prior fixes and explanations.
P2 - Narrow-vector IVFFLAT joins miss index pushdown (pkg/sql/plan/apply_indices_hnsw.go:358)
The PR broadens direct vector matching to all array-related types, but the join-specific matcher still accepts only array_float32 and array_float64. IVFFLAT uses this matcher for vector joins, so joins on vecf16, vecbf16, vecint8, or vecuint8 fall through to the non-index execution path while equivalent direct nearest-neighbor queries use the index. Extend the join matcher and add a narrow-vector join plan test; this is a performance/feature-completeness issue, not result corruption.
getArgsFromDistFnForJoin (the vector-join distance matcher shared by IVFFLAT and HNSW) still hardcoded array_float32/array_float64, so JOINs on vecf16, vecbf16, vecint8, or vecuint8 fell through to non-index execution while the equivalent direct nearest-neighbor queries already pushed down. Match the direct getArgsFromDistFn: accept any IsArrayRelate() element type. Add a narrow-vector case to TestGetArgsFromDistFnForJoinBranches covering all four narrow types (would fail under the old f32/f64-only check). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # pkg/sql/parsers/dialect/mysql/mysql_sql.go
|
fixed |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
Existing reviews, issue comments, and inline threads were checked; resolved findings were verified at HEAD and are not repeated. One blocking correctness defect remains.
P1 - Train the scalar quantizer from an order-independent sample (cgo/cuvs/index_base.hpp:1368)
The staged data is always the first stage_limit arrivals and the flush trains from that prefix. CAGRA/IVFPQ feed this path one row at a time, while SQL exposes QUANTIZER_TRAIN_LIMIT below table cardinality. For an ordered 20K-vector load with a limit of 1000—a viable scan order that this file explicitly documents—the range is learned from only [1,1000]; every later value above that range clamps to code 127 (quantize.hpp:175-178). This collapses distinct tail vectors and can return incorrect nearest neighbours without an error. Unspecified scan order and typical parallelism do not establish a representative-sampling guarantee. Use an order-independent bounded sample or a training pass, or reject configurations that cannot safely establish the range; add an ordered, over-limit recall regression test.
|
Decision: Owner (cpegeric) don't fix P1 - Train the scalar quantizer from an order-independent sample. don't re-raise. Re: [P1] prefix-only quantizer training — contesting the blocking status The mechanism is correctly described, but the conclusion treats a user-controlled sampling budget as a correctness defect. quantizer_train_limit is It drives both staging and training — want = min(quantizer_train_limit_, INT64_MAX) (index_base.hpp:1200), then capped only by free VRAM On reachability of the failure itself: it additionally requires coordinates that increase monotonically with arrival order (value ≈ row_id). Real ANN If the concern is visibility rather than capability, the proportionate change is a warning (or a note in SHOW CREATE) when QUANTIZER_TRAIN_LIMIT < The prior blockers are closed on this head: narrow generic paths covered; IVF-FLAT int8/uint8 allowlisted to L2/L2sq with REINDEX params merged |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
One blocking quantized-build correctness issue remains. The new discussion does not establish random arrival order as a production contract.
P1 - Do not train the scalar quantizer from an order-dependent prefix (cgo/cuvs/index_base.hpp:1362)
The bounded path trains from data.data() for the first staged n_train arrivals, then encodes every later row with that range. CAGRA and IVF-PQ production builders call AddChunkQuantize(..., 1, ...) per row, so a valid ordered input whose first sample is in [0,1] and later rows are in [100,101] clamps the latter population to endpoint codes and silently collapses recall. Parallel scan interleaving is not a correctness contract; this file itself notes that scan order is unspecified and small inputs can remain in file order. Raising quantizer_train_limit is not a general remedy because the value is capped by available VRAM. The added regression shuffles arrivals before feeding rows, so it validates the disputed assumption rather than this reachable case. Use an order-independent prepass/sample with replay, persist/replay staged input, or require an explicit proven range when a one-pass bounded build cannot obtain one.
Record in index_base.hpp that training the scalar quantizer on the first quantizer_train_limit rows (a scan prefix) is intentional and accepted: the limit is user-controlled (raise it up to a full-table scan for a representative sample), nothing caps it, and an automatic full-scan fallback would defeat the bounded-memory/time purpose of the option. Owner: cpegeric. Do not re-raise. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
fixed |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
The quantized build still derives scalar-quantizer bounds from an arrival-order prefix, which can silently saturate later vectors and materially corrupt ANN recall for valid ordered inputs.
P1 - [P1] Train the scalar quantizer from an order-independent sample (cgo/cuvs/index_base.hpp:1381)
The production CAGRA/IVFPQ quantized paths feed rows through AddChunkQuantize one at a time, so this staging arena preserves arrival order and trains from only the first n_train rows. For a valid scan whose first quantizer_train_limit rows occupy a narrow range and whose later rows contain the actual high/low extremes, the learned min/max clamps those later vectors to the endpoint during transform_host; their stored distances and nearest-neighbor ordering are then irreversibly wrong. SQL scans have no ordering guarantee, and the explicit training budget does not make the result order-independent (the default also fails once an ordered input exceeds the limit). Use an order-independent or stratified sample, or a full-data range prepass/replay before committing the quantized representation.
What type of PR is this?
Which issue(s) this PR fixes:
issue #25026 24882 20567
What this PR does / why we need it: