Skip to content

IVFFLAT/IVFPQ/CAGRA support bf16, float16, int8 and uint8 quantization - #25095

Merged
fengttt merged 960 commits into
matrixorigin:mainfrom
cpegeric:cuvs_quantize
Jul 23, 2026
Merged

fengttt merged 960 commits into
matrixorigin:mainfrom
cpegeric:cuvs_quantize

Conversation

@cpegeric

@cpegeric cpegeric commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #25026 24882 20567

What this PR does / why we need it:

  1. IVFFLAT support bf16, float16, int8 and uint8 quantization
  2. bug fix GPU concurrent Kmeans clustering
  3. IVFPQ/CAGRA support float32, float16 as base type and its quantization int8 and uint8
  4. bug fix slow int8 quantization in GPU. moved to CPU computation
  5. basic array function for bf16, float16, int8, and uint8

cpegeric and others added 30 commits June 5, 2026 10:29
…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]>
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
@cpegeric

Copy link
Copy Markdown
Contributor Author

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
the "explicit/proven range" the review asks for:

  • It drives both staging and training — want = min(quantizer_train_limit_, INT64_MAX) (index_base.hpp:1200), then capped only by free VRAM
    (cap_train_rows_to_gpu_mem). Setting it ≥ nrow (within GPU memory) stages and trains on the whole dataset, so [min,max] is exact and the tail cannot
    clamp. Nothing prevents a user from doing this.
  • The default is already 100000, so every table up to 100k rows trains on all of its rows out of the box. The 20k example only degrades because the
    review's config sets the limit to 1000 — deliberately below the row count. That is the user asking for a 20× sample, and it behaves like one. A
    smaller sample being less representative than a larger one is the meaning of the knob, not a silent bug.

So the design loses nothing relative to the "must be representative" requirement: the exact-range behavior is available on request via a single
parameter, on a single pass — no replay/spool/two-pass. What the review implicitly demands instead — always accumulate the entire dataset just to
derive a scale+offset — is precisely the full-table staging this PR replaced (~3 GB → ~0.31 GB host, recall within run-to-run noise). Reintroducing
that as a mandatory cost, to defend a case the user can already avoid by raising one limit, is a strict regression for no real-world gain.

On reachability of the failure itself: it additionally requires coordinates that increase monotonically with arrival order (value ≈ row_id). Real ANN
inputs have per-dimension ranges that are stable across rows regardless of storage order, which is why a file-order prefix — and the parallel-ingest
interleaving measured at 1M (first 200k arrivals span 93% of the value range) — is representative in practice, and why the wiki recall holds. The
monotonic-coordinate dataset is synthetic; combined with an explicit sub-nrow limit, it describes a user who has opted out of a representative sample
on data that doesn't occur in vector search.

If the concern is visibility rather than capability, the proportionate change is a warning (or a note in SHOW CREATE) when QUANTIZER_TRAIN_LIMIT <
nrow, so a user lowering the budget below the table size is told the sample may not span the full range. I'm happy to add that. But "set the limit
high for an exact range, low to bound host memory" is a sound, single-pass design — not a P1 blocker.

The prior blockers are closed on this head: narrow generic paths covered; IVF-FLAT int8/uint8 allowlisted to L2/L2sq with REINDEX params merged
pre-validation.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • // ApplyInt8 applies q(x)=x*mul+add to a float32 query vector and narrows to int8
    // (round+clamp), matching the entry build. (mul,add)=(1,0) is identity (no
    // quantizer trained), so the raw narrowing cast is used. The multiply-add is done
    // in float64 (then narrowed) to match the build side, whose entry SQL
    // `cast(base*mul+add as vecint8)` evaluates the f64 literals in the base column's
    // arithmetic — doing it in float32 here could bucket a boundary component
    // differently. qf32 is never mutated.
    func ApplyInt8(qf32 []float32, mul, add float64) []int8 {
    if mul == 1.0 && add == 0.0 {
    return types.Float32ToInt8Slice(qf32)
    }
    sq := make([]float32, len(qf32))
    for i, x := range qf32 {
    sq[i] = float32(float64(x)*mul + add)
    }
    return types.Float32ToInt8Slice(sq)
    }
    // CastSQL builds `cast(<colExpr> as <type>(dim))` for narrowing an entry to a
    // quantization type without scaling — float formats (float16/bf16/float32), or
    // int8 when no [min,max] bounds were trained (the implicit cast does identity
    // round+clamp). colExpr is the already-quoted column reference or sub-expression.
    func CastSQL(colExpr string, t types.T, dim int32) string {
    return fmt.Sprintf("cast(%s as %s(%d))", colExpr, SQLTypeName(t), dim)
    }
    // Int8EntrySQL builds the int8 entry projection `cast(<colExpr> * mul + add as
    // vecint8(dim))` from precomputed literal bounds (the synchronous build path,
    // where compile has already read the trained [min,max] from metadata). colExpr is
    // the already-quoted column reference.
    func Int8EntrySQL(colExpr string, mul, add float64, dim int32) string {
    return fmt.Sprintf("cast(%s * %.9g + (%.9g) as vecint8(%d))", colExpr, mul, add, dim)
  • // ApplyUint8 is the uint8 analog of ApplyInt8: applies q(x)=x*mul+add to a float32
    // query vector and narrows to uint8 (round+clamp to [0,255]). (mul,add)=(1,0) is
    // identity. The multiply-add is done in float64 to match the build side. qf32 is
    // never mutated.
    func ApplyUint8(qf32 []float32, mul, add float64) []uint8 {
    if mul == 1.0 && add == 0.0 {
    return types.Float32ToUint8Slice(qf32)
    }
    sq := make([]float32, len(qf32))
    for i, x := range qf32 {
    sq[i] = float32(float64(x)*mul + add)
    }
    return types.Float32ToUint8Slice(sq)
    }
    // Uint8EntrySQL is the uint8 analog of Int8EntrySQL: the build-side entry
    // projection `cast(<colExpr> * mul + add as vecuint8(dim))` from literal bounds.
    func Uint8EntrySQL(colExpr string, mul, add float64, dim int32) string {
    return fmt.Sprintf("cast(%s * %.9g + (%.9g) as vecuint8(%d))", colExpr, mul, add, dim)
    }
    // Uint8EntrySQLFromBounds is the uint8 analog of Int8EntrySQLFromBounds (CDC delta
    // path). q(x)=x*mul+add with mul=255/(max-min) and add=-min*255/(max-min) — no -128
    // shift — wrapped in COALESCE for identity fallback when a bound is absent.
    func Uint8EntrySQLFromBounds(colExpr, minExpr, maxExpr string, dim int32) string {
    // 255.0 == uint8Span; no offset term since Uint8Lo == 0.
    rng := fmt.Sprintf("(%s - %s)", maxExpr, minExpr)
    mul := fmt.Sprintf("COALESCE(255.0 / %s, 1.0)", rng)
    add := fmt.Sprintf("COALESCE(0.0 - %s * 255.0 / %s, 0.0)", minExpr, rng)
    return fmt.Sprintf("cast(%s * %s + %s as vecuint8(%d))", colExpr, mul, add, dim)
  • /** VEC <Op> Scalar => VEC **/
    // VECF32 <Op> Scalar => VECF32
    {types.T_array_float32, types.T_uint8, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_uint16, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_uint32, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_uint64, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_int8, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_int16, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_int32, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_int64, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_float32, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_float64, types.T_array_float32, types.T_float32},
    {types.T_array_float32, types.T_decimal64, types.T_array_float32, types.T_float32},
    // VECF64 <Op> Scalar => VECF64
    {types.T_array_float64, types.T_uint8, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_uint16, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_uint32, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_uint64, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_int8, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_int16, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_int32, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_int64, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_float32, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_float64, types.T_array_float64, types.T_float64},
    {types.T_array_float64, types.T_decimal64, types.T_array_float64, types.T_float64},
  • // runIvfSearchVectorToF32 decodes the query (of any vector column type: f32, f64,
    // or narrow bf16/f16/int8) to float32 and runs the float32 centroid search. The
    // SQL re-rank then encodes the query in the entry/quantization type.
    func runIvfSearchVectorToF32(tf *TableFunction, u *ivfSearchState, proc *process.Process, faVec *vector.Vector, nthRow int) error {
    if faVec.IsNull(uint64(nthRow)) {
    return nil
    }
    b := faVec.GetBytesAt(nthRow)
    var fa []float32
    switch faVec.GetType().Oid {
    case types.T_array_float32:
    fa = types.BytesToArray[float32](b)
    case types.T_array_float64:
    f64 := types.BytesToArray[float64](b)
    fa = make([]float32, len(f64))
    for i, x := range f64 {
    fa[i] = float32(x)
    }

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 jiangxinmeng1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

// ApplyInt8 applies q(x)=x*mul+add to a float32 query vector and narrows to int8
// (round+clamp), matching the entry build. (mul,add)=(1,0) is identity (no
// quantizer trained), so the raw narrowing cast is used. The multiply-add is done
// in float64 (then narrowed) to match the build side, whose entry SQL
// `cast(base*mul+add as vecint8)` evaluates the f64 literals in the base column's
// arithmetic — doing it in float32 here could bucket a boundary component
// differently. qf32 is never mutated.
func ApplyInt8(qf32 []float32, mul, add float64) []int8 {
if mul == 1.0 && add == 0.0 {
return types.Float32ToInt8Slice(qf32)
}
sq := make([]float32, len(qf32))
for i, x := range qf32 {
sq[i] = float32(float64(x)*mul + add)
}
return types.Float32ToInt8Slice(sq)
}
// CastSQL builds `cast(<colExpr> as <type>(dim))` for narrowing an entry to a
// quantization type without scaling — float formats (float16/bf16/float32), or
// int8 when no [min,max] bounds were trained (the implicit cast does identity
// round+clamp). colExpr is the already-quoted column reference or sub-expression.
func CastSQL(colExpr string, t types.T, dim int32) string {
return fmt.Sprintf("cast(%s as %s(%d))", colExpr, SQLTypeName(t), dim)
}
// Int8EntrySQL builds the int8 entry projection `cast(<colExpr> * mul + add as
// vecint8(dim))` from precomputed literal bounds (the synchronous build path,
// where compile has already read the trained [min,max] from metadata). colExpr is
// the already-quoted column reference.
func Int8EntrySQL(colExpr string, mul, add float64, dim int32) string {
return fmt.Sprintf("cast(%s * %.9g + (%.9g) as vecint8(%d))", colExpr, mul, add, dim)

// ApplyUint8 is the uint8 analog of ApplyInt8: applies q(x)=x*mul+add to a float32
// query vector and narrows to uint8 (round+clamp to [0,255]). (mul,add)=(1,0) is
// identity. The multiply-add is done in float64 to match the build side. qf32 is
// never mutated.
func ApplyUint8(qf32 []float32, mul, add float64) []uint8 {
if mul == 1.0 && add == 0.0 {
return types.Float32ToUint8Slice(qf32)
}
sq := make([]float32, len(qf32))
for i, x := range qf32 {
sq[i] = float32(float64(x)*mul + add)
}
return types.Float32ToUint8Slice(sq)
}
// Uint8EntrySQL is the uint8 analog of Int8EntrySQL: the build-side entry
// projection `cast(<colExpr> * mul + add as vecuint8(dim))` from literal bounds.
func Uint8EntrySQL(colExpr string, mul, add float64, dim int32) string {
return fmt.Sprintf("cast(%s * %.9g + (%.9g) as vecuint8(%d))", colExpr, mul, add, dim)
}
// Uint8EntrySQLFromBounds is the uint8 analog of Int8EntrySQLFromBounds (CDC delta
// path). q(x)=x*mul+add with mul=255/(max-min) and add=-min*255/(max-min) — no -128
// shift — wrapped in COALESCE for identity fallback when a bound is absent.
func Uint8EntrySQLFromBounds(colExpr, minExpr, maxExpr string, dim int32) string {
// 255.0 == uint8Span; no offset term since Uint8Lo == 0.
rng := fmt.Sprintf("(%s - %s)", maxExpr, minExpr)
mul := fmt.Sprintf("COALESCE(255.0 / %s, 1.0)", rng)
add := fmt.Sprintf("COALESCE(0.0 - %s * 255.0 / %s, 0.0)", minExpr, rng)
return fmt.Sprintf("cast(%s * %s + %s as vecuint8(%d))", colExpr, mul, add, dim)

/** VEC <Op> Scalar => VEC **/
// VECF32 <Op> Scalar => VECF32
{types.T_array_float32, types.T_uint8, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_uint16, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_uint32, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_uint64, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_int8, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_int16, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_int32, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_int64, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_float32, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_float64, types.T_array_float32, types.T_float32},
{types.T_array_float32, types.T_decimal64, types.T_array_float32, types.T_float32},
// VECF64 <Op> Scalar => VECF64
{types.T_array_float64, types.T_uint8, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_uint16, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_uint32, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_uint64, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_int8, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_int16, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_int32, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_int64, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_float32, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_float64, types.T_array_float64, types.T_float64},
{types.T_array_float64, types.T_decimal64, types.T_array_float64, types.T_float64},

// runIvfSearchVectorToF32 decodes the query (of any vector column type: f32, f64,
// or narrow bf16/f16/int8) to float32 and runs the float32 centroid search. The
// SQL re-rank then encodes the query in the entry/quantization type.
func runIvfSearchVectorToF32(tf *TableFunction, u *ivfSearchState, proc *process.Process, faVec *vector.Vector, nthRow int) error {
if faVec.IsNull(uint64(nthRow)) {
return nil
}
b := faVec.GetBytesAt(nthRow)
var fa []float32
switch faVec.GetType().Oid {
case types.T_array_float32:
fa = types.BytesToArray[float32](b)
case types.T_array_float64:
f64 := types.BytesToArray[float64](b)
fa = make([]float32, len(f64))
for i, x := range f64 {
fa[i] = float32(x)
}

…/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]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed. please review again.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.5 and encode -125; the v3 query encoder fuses to -124.49999 and encodes -124.
  • uint8, x = math.Float32frombits(0x3dd05fbc) (0.1017451): SQL produces 0.5 -> 1; fused query encoding produces 0.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]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

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
one rounding while the entry SQL rounds twice. I reproduced your exact cases:

  • x = 0x3de5d15a (0.11221571), int8: fused viaVar = -124.49999 → -124; explicit float32(x*fmul) = -124.5 → -125; SQL confirms -125 on the live
    engine.
  • x = 0x3dd05fbc (0.1017451), uint8: fused 0.49999908 → 0 vs SQL 0.5 → 1.

Fix: wrap the product in an explicit float32() conversion in ApplyInt8/ApplyUint8 — the Go spec's guaranteed rounding barrier — so build/CDC/search
all round the product before the add:

m := float32(x * fmul) // explicit conversion rounds the product; blocks FMA fusion
sq[i] = m + fadd

Test fixes (you correctly caught the masking):

  • entryInt8/entryUint8 now use the same explicit-conversion form, so they model SQL's two separate operations instead of fusing alongside production.
  • Added TestApplyFMABoundaryMatchesSQL: an independent oracle using your exact bit patterns with the hardcoded, live-verified SQL codes (-125, 1), so
    it catches a fused encoder regardless of any Go-side replication. It passes on arm64 hardware FMA (≡ GOAMD64=v3); the fused version fails it
    (expected -125, actual -124).

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
expression (two materialized vecf32 ops), so all three paths now round identically.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) = bits 0x42039467
  • synchronous build emits 32.8949261, which the vecf32 scalar-arithmetic rule narrows to bits 0x42039468
  • int8 component 0x3ea36df5 (0.31919828): search encodes -118, synchronous build encodes -117
  • uint8 component 0x3c79090d (0.015199912): search encodes 0, synchronous build encodes 1

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.

cpegeric and others added 2 commits July 23, 2026 14:16
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
@cpegeric

Copy link
Copy Markdown
Contributor Author

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
exactly:

  • int8, bounds [0, 7.75195541], mul=32.89492605582467: float32(mul)=0x42039467, but %.9g(float64)="32.8949261" narrows to 0x42039468; at component
    0x3ea36df5 search -118 vs build -117.
  • uint8, component 0x3c79090d: search 0 vs build 1.

Fix (Int8EntrySQL/Uint8EntrySQL): format the float32-narrowed params so the literal round-trips to the exact float32 search/CDC use:
fmt.Sprintf("... %.9g + (%.9g) ...", f32col, float32(mul), float32(add), dim)
286.516854 → 286.516846, etc. The *FromBounds (CDC) builders compute params in SQL from the same bounds and are narrowed by the VECF32 Scalar
rule, so they already match — only the literal-bounds builders changed.

Regression (TestEntrySQLParamNarrowedToFloat32) — exactly your ask, for both int8 and uint8: it parses the generated SQL literals, asserts the
precondition (raw-float64 %.9g crosses a float32 boundary for this mul), that the emitted literals round-trip to float32(mul)/float32(add), and that
build (emitted param) and search (ApplyInt8/ApplyUint8) encode the reported boundary components to the same bucket. Passes under -race/GOAMD64=v3;
the existing builder-string tests now match the narrowed literals.

Closure: build (literal params, now narrowed), CDC (SQL-computed, narrowed by coercion), and search (float32(mul) in ApplyInt8) all resolve to the
identical float32(mul) and round the product identically.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

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.
Confirmed valid: the scalar CosineSimilarity (distance_func.go:350–355) clamps to [-1,1], but the SIMD CosineSimilarityF32/CosineSimilarityF64
returned the raw quotient — so float32 accumulation could emit 1.000000119 (0x3f800001). Clamped both kernels to [-1,1] to mirror the scalar path and
cosineDistClamped. Added TestAMD64CosineSimilarityUpperClamp using the reviewer's exact bit patterns asserting the result never exceeds 1.0.

P2 — narrow-vector fields unquoted in checkpoint CSV (table_dump.go:3137) — FIXED.
Confirmed valid: shouldQuoteSQLLoadType quoted vecf32/vecf64 but omitted vecbf16/vecf16/vecint8/vecuint8. Those render via RowToString as [1, 2],
whose comma splits the CSV column under LOAD DATA. Added all four OIDs (T_array_bf16, T_array_float16, T_array_int8, T_array_uint8) to the quoted
set. Added TestWriteSQLLoadCSVFieldFromVec_NarrowVectorsQuoted — round-trips each of the four types through the CSV parser and asserts a single
field.

Verification

  • checkpointtool (native, CGo env): build + vet clean; new test PASS, existing CSV-field tests still PASS.
  • metric: native build + Cosine tests PASS (scalar path). The amd64+simd file can't execute on this arm64 host, so I cross-compiled GOARCH=amd64
    GOEXPERIMENT=simd — package and the new test binary type-check/compile cleanly (only the expected x86_64 link failure for the absent amd64 libmo).
    The amd64 SIMD test runs in CI.
  • All four changed files gofmt-clean.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

cpegeric and others added 2 commits July 23, 2026 16:47
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
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cpegeric

Copy link
Copy Markdown
Contributor Author

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
the "explicit/proven range" the review asks for:

It drives both staging and training — want = min(quantizer_train_limit_, INT64_MAX) (index_base.hpp:1200), then capped only by free VRAM
(cap_train_rows_to_gpu_mem). Setting it ≥ nrow (within GPU memory) stages and trains on the whole dataset, so [min,max] is exact and the tail cannot
clamp. Nothing prevents a user from doing this.
The default is already 100000, so every table up to 100k rows trains on all of its rows out of the box. The 20k example only degrades because the
review's config sets the limit to 1000 — deliberately below the row count. That is the user asking for a 20× sample, and it behaves like one. A
smaller sample being less representative than a larger one is the meaning of the knob, not a silent bug.
So the design loses nothing relative to the "must be representative" requirement: the exact-range behavior is available on request via a single
parameter, on a single pass — no replay/spool/two-pass. What the review implicitly demands instead — always accumulate the entire dataset just to
derive a scale+offset — is precisely the full-table staging this PR replaced (~3 GB → ~0.31 GB host, recall within run-to-run noise). Reintroducing
that as a mandatory cost, to defend a case the user can already avoid by raising one limit, is a strict regression for no real-world gain.

On reachability of the failure itself: it additionally requires coordinates that increase monotonically with arrival order (value ≈ row_id). Real ANN
inputs have per-dimension ranges that are stable across rows regardless of storage order, which is why a file-order prefix — and the parallel-ingest
interleaving measured at 1M (first 200k arrivals span 93% of the value range) — is representative in practice, and why the wiki recall holds. The
monotonic-coordinate dataset is synthetic; combined with an explicit sub-nrow limit, it describes a user who has opted out of a representative sample
on data that doesn't occur in vector search.

If the concern is visibility rather than capability, the proportionate change is a warning (or a note in SHOW CREATE) when QUANTIZER_TRAIN_LIMIT <
nrow, so a user lowering the budget below the table size is told the sample may not span the full range. I'm happy to add that. But "set the limit
high for an exact range, low to bound host memory" is a sound, single-pass design — not a P1 blocker.

The prior blockers are closed on this head: narrow generic paths covered; IVF-FLAT int8/uint8 allowlisted to L2/L2sq with REINDEX params merged
pre-validation.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cpegeric

Copy link
Copy Markdown
Contributor Author

fixed

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants