Skip to content

feat(index): add a PCA model and vector pre-transform - #9967

Merged
BubbleCal merged 10 commits into
lance-format:mainfrom
beautygua:feat/pca-model
Oct 21, 2026
Merged

BubbleCal merged 10 commits into
lance-format:mainfrom
beautygua:feat/pca-model

Conversation

@beautygua

@beautygua beautygua commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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-debug profile. 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.

Scenario / metric Baseline This PR Benefit
4,096 rows / peak additional allocation (lower is better) 1,121,472 bytes 597,184 bytes 1.88x lower
65,536 rows / peak additional allocation (lower is better) 8,982,768 bytes 594,160 bytes 15.12x lower

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:

  • 55 PCA-related tests, including Float16/Float32/Float64 sliced inputs across batch boundaries
  • 12 pre-transform tests
  • cargo fmt --all
  • cargo clippy --all --tests --benches -- -D warnings
  • Local allocation regression assertion fails on the baseline and passes on this head

Benchmark code and measurement artifacts are retained locally and are not included in this PR.

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.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@github-actions github-actions Bot added A-python Python bindings A-index Vector index, linalg, tokenizer A-java Java bindings + JNI A-deps Dependency updates A-format On-disk format: protos and format spec docs format-change A change to the format spec, which requires a vote. Remove if minor (e.g. fixing typo). enhancement New feature or request labels Oct 14, 2026
@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Important

Format specification vote

This 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

Approvals none (0/3)
Latest commit approved by none — one PMC member must approve the latest commit
Vetoes none
Voting period elapsed — ended Mon 2026-10-19 09:55 UTC (02:55 PDT)

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 format-waived label to waive the vote for a trivial edit (typo, wording, formatting).

Comment thread Cargo.toml Resolved
Comment thread rust/lance-index/src/vector/pca.rs Outdated
}

let mean = compensated_mean(&values, row_count, input_dimension)?;
let (eigenvalues, basis) = if row_count >= input_dimension {

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.

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.

Comment thread rust/lance-index/src/vector/pca.rs Outdated
let matrix = Mat::from_fn(dimension, dimension, |row, column| {
gaussian[row * dimension + column]
});
let mut rotation = matrix.qr().compute_Q();

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.

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.

Comment thread rust/lance-index/src/vector/pca.rs Outdated
/// 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,

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.

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.

Comment thread rust/lance-index/src/vector/pca.rs Outdated
/// `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(

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.

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>,

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.

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.

Comment thread rust/lance-index/src/vector/pca.rs Outdated
) -> Result<()> {
debug_assert_eq!(input.len(), input_dimension);
debug_assert_eq!(mean.len(), input_dimension);
debug_assert_eq!(matrix.len(), input_dimension * output_dimension);

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.

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.

Comment thread rust/lance-index/src/vector/pca.rs Outdated
*hasher.finalize().as_bytes()
}

fn validate_trained(&self, training_data: &FixedSizeListArray) -> Result<()> {

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.

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.
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 16, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
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.
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. and removed K-approved Latest Gatekeeper recommendation permits acceptance. labels Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
Merge main at 98079a5. Keep its dependency resolutions and add only the PCA dependencies to all three Cargo lockfiles.
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026

@lance-gatekeeper lance-gatekeeper Bot 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.

✅ Gate recommendation: approve.

No merge-blocking issues found in this PCA foundation. End-to-end dataset behavior remains for the IVF_RQ integration.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 2026

@BubbleCal BubbleCal 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.

As this is experimental, let's merge it first

@Xuanwo Xuanwo added the format-waived Author attests no format vote is needed label Oct 21, 2026
@BubbleCal
BubbleCal merged commit 489ca31 into lance-format:main Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-deps Dependency updates A-format On-disk format: protos and format spec docs A-index Vector index, linalg, tokenizer A-java Java bindings + JNI A-python Python bindings enhancement New feature or request format-change A change to the format spec, which requires a vote. Remove if minor (e.g. fixing typo). format-waived Author attests no format vote is needed K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants