Repository navigation
feat(index): add a PCA model and vector pre-transform - #9967
Conversation
Train a PCA model in lance-index and wrap a vector index so each query is transformed once before search. On aarch64 the query projection uses a NEON kernel; other targets use a portable kernel. Set LANCE_PCA_QUERY_TRANSFORM_SCALAR=1 to restore the scalar loop.
|
Important Format specification voteThis PR modifies the Lance format specification, so it requires 3 binding +1 votes from PMC members (excluding the proposer), at least one of them on the latest commit, and a minimum 72-hour voting period, weekends excluded, before it can merge. Vote by approving this PR (+1) or requesting changes (−1, a veto). See the voting process. Approvals carry over across pushes, so a rebase or a typo fix does not send everyone back to re-vote. Whoever approves the latest commit is vouching that nothing substantive has changed since the earlier approvals; if something has, ask for fresh votes. Status: ❌ Blocked — 0 of 3 required approvals
Updated automatically by the format-spec vote gate, which re-checks every 15 minutes — just voted? Re-check now (press Run workflow; leave the input blank to re-check every open format PR). A PMC member may apply the |
| } | ||
|
|
||
| let mean = compensated_mean(&values, row_count, input_dimension)?; | ||
| let (eigenvalues, basis) = if row_count >= input_dimension { |
There was a problem hiding this comment.
Please remove the Gram path and always use covariance/scatter. N is normally much larger than D for our indexing workloads. Covariance also supports N < D, so retain the effective-rank check without rejecting that case. The Gram implementation, train_from_centered, and its budget branches and tests can all go.
| let matrix = Mat::from_fn(dimension, dimension, |row, column| { | ||
| gaussian[row * dimension + column] | ||
| }); | ||
| let mut rotation = matrix.qr().compute_Q(); |
There was a problem hiding this comment.
Please share RQ's existing dense orthogonal-rotation implementation in bq/builder.rs. Extract a shared helper that accepts an RNG so PCA can retain its rotation seed and RQ can preserve its current behavior. Keep optional random rotation, and avoid maintaining a second Gaussian/QR implementation here.
| /// Whether to apply a deterministic orthogonal rotation after PCA. | ||
| pub random_rotation: bool, | ||
| /// Whether to scale retained components by their regularized variance. | ||
| pub whitening: bool, |
There was a problem hiding this comment.
Please defer whitening and epsilon from the initial PCA feature. Whitening changes the L2 geometry and can change nearest-neighbor ordering, so it needs separate recall evaluation and a clear distance contract. PCA dimensionality reduction with the shared optional rotation is enough for this change.
| /// `sample_count` records how many valid vectors contributed to the | ||
| /// statistics. This entry point reuses the same eigendecomposition, | ||
| /// whitening, and random-rotation kernel as [`Self::train`]. | ||
| pub fn train_from_covariance( |
There was a problem hiding this comment.
Can we keep one user-facing training entry point and only the statistics entry point needed by the streaming trainer? train_from_covariance has no production caller, and removing Gram makes train_from_centered unnecessary. The four parallel entry points and SecondMomentScale branch make the API harder to understand without a demonstrated need.
| #[derive(Debug)] | ||
| pub struct PreTransformIndex { | ||
| inner: Arc<dyn VectorIndex>, | ||
| transform: Arc<dyn QueryPreTransform>, |
There was a problem hiding this comment.
This trait has only one production implementation, wrapping PcaModel. Please store Arc directly here and keep the query decorator responsible for automatic projection. The extra QueryPreTransform trait and PcaQueryPreTransform wrapper can wait until another transform needs them.
| ) -> Result<()> { | ||
| debug_assert_eq!(input.len(), input_dimension); | ||
| debug_assert_eq!(mean.len(), input_dimension); | ||
| debug_assert_eq!(matrix.len(), input_dimension * output_dimension); |
There was a problem hiding this comment.
This safe public function can cause an out-of-bounds read on aarch64 in release builds. With input/mean lengths 8, matrix length 8, input_dimension=8 and output_dimension=4, the NEON path reads three nonexistent matrix rows. debug_assert disappears in release. Please remove this public kernel API and reuse the lance-linalg dot kernels, or validate every slice size with checked arithmetic before entering unsafe code. Add coverage for invalid sizes.
| *hasher.finalize().as_bytes() | ||
| } | ||
|
|
||
| fn validate_trained(&self, training_data: &FixedSizeListArray) -> Result<()> { |
There was a problem hiding this comment.
Please move the full-sample query/batch equivalence check into tests. This projects the entire training sample again and repeats a finite check already performed by transform. Also remove the centered-mean check in validate_model: A * (mean - mean) is zero for any finite matrix, so it cannot validate the trained basis. Keep the shape, finite-value and effective-rank checks.
Use nalgebra for the symmetric eigendecomposition and keep matrix products on ndarray, including the orthogonal rotation shared with RQ. Train only from the covariance, drop whitening, and check slice lengths before the aarch64 NEON query kernel. Restore the Gaussian matrix helper used by the Householder QR test, set the distance bound in the PCA rejection test, and delegate stored-code pairwise scoring to the wrapped index.
Unify in-memory and streaming scatter training, copy only retained principal components, and keep the runtime model limited to projection state. Borrow Arrow buffers and validate inputs at their boundaries. Remove kernel selection APIs and reuse lance-linalg dot outside ARM. Retain private NEON kernels after paired ARM benchmarks showed a regression with the generic dot path. Add a reproducible PCA benchmark.
Merge main at 98079a5. Keep its dependency resolutions and add only the PCA dependencies to all three Cargo lockfiles.
There was a problem hiding this comment.
✅ Gate recommendation: approve.
No merge-blocking issues found in this PCA foundation. End-to-end dataset behavior remains for the IVF_RQ integration.
BubbleCal
left a comment
There was a problem hiding this comment.
As this is experimental, let's merge it first
Base: main. PCA model and query pre-transform.
Discussion Link: #9122
Adds the experimental PCA model, training, projection, serialization, and query pre-transform integration. Training computes statistics and eigendecomposition in f64; the stored model and projection output use f32.
In-memory training now reads Float16/Float32/Float64 input buffers directly. Conversion to f64 happens during mean accumulation and per-batch centering, eliminating the full-size f64 input copy. The existing compensated sum, scatter calculation, model format, and projection precision are preserved.
Measured on Apple M3 Max, macOS 27.0.1, Rust 1.98.1, using the repository's
release-with-debugprofile. Baseline:5e90d99459493b73024e4ecf4af9556ba93dd632; this PR head:2425946090a3c4879a212e80fd60dd8e301b63a3. Inputs are deterministic Float32 arrays; both allocation cases reduce 16 dimensions to 4. Peak additional memory is measured through the Rust allocator during training, excludes the input array, and is not process RSS. Values are medians of three paired runs with alternating order.Criterion 0.8.2 latency checks used 20 samples, 300 ms warmup, and 1 s measurement per run, with the same allocator instrumentation in both builds. Median mean latency was 3.064 ms -> 3.155 ms for 65,536x16 -> 4 (about 3% slower) and 60.891 us -> 61.495 us for 256x32 -> 8 (about 1% slower). This is a memory reduction, with a small measured latency tradeoff in these local cases. Trained model fingerprints matched across both builds. These are isolated training measurements, not end-to-end ANN results.
Validation:
cargo fmt --allcargo clippy --all --tests --benches -- -D warningsBenchmark code and measurement artifacts are retained locally and are not included in this PR.