Skip to content

fix(python): train cosine PQ codebook with L2 on normalized residuals in accelerated IVF_PQ - #9755

Merged
Xuanwo merged 2 commits into
lance-format:mainfrom
Chastrlove:fix/gpu-cosine-pq-codebook
Oct 23, 2026
Merged

Xuanwo merged 2 commits into
lance-format:mainfrom
Chastrlove:fix/gpu-cosine-pq-codebook

Conversation

@Chastrlove

Copy link
Copy Markdown
Contributor

Fixes #9754

create_index(..., index_type="IVF_PQ", metric="cosine", accelerator=...) built indices with much lower recall than the CPU build (for example 0.387 vs 1.000 on 500k x 2048-d embeddings with CUDA). The torch path trains the PQ codebook and computes the PQ codes in Python, and the Rust builder uses them unchanged. For cosine the two sides disagreed:

  • Rust normalizes the vectors, takes residuals of the normalized vectors, and treats the PQ codebook as an L2 codebook over them.
  • The torch path trained the PQ codebook with cosine k-means, which normalizes codewords and residual sub-vectors to unit length and so drops the residual norms. It also took residuals of the unnormalized vectors.

Changes

All in python/python/lance/vector.py, cosine only:

  • train_pq_codebook_on_accelerator: train the per-sub-vector k-means with l2. PQ encoding in one_pass_assign_ivf_pq_on_accelerator goes through the same KMeans objects, so it uses L2 as well.
  • compute_partitions (residual sample for PQ training) and one_pass_assign_ivf_pq_on_accelerator (final encoding): normalize the vectors before subtracting the IVF centroid, as the Rust build does.

l2 and dot are unchanged.

Not changed here: cosine IVF centroids from the torch k-means are still normalized to unit length (#1759), while the CPU build keeps the mean of the normalized vectors. Encoding and search both use the stored centroids, so the index is consistent, but the residuals are larger. This explains the remaining PQ-only gap in the table below: on the pre-normalized 50k data, PQ-only recall@100 is 0.765 with this PR and 0.832 when the torch k-means also keeps unnormalized cosine centroids (CPU build 0.827). With refine_factor=10 every variant is at 1.000. The centroid change is in lance.torch.kmeans.KMeans, which is public and also used by IndicesBuilder, so I left it for a follow-up.

Tests

Added test_torch_cosine_ivf_pq_recall to python/python/tests/test_vector_index.py, next to the other torch-path index tests. It builds a cosine IVF_PQ index on 4096 x 32-d vectors with varying norms, once without accelerator and once with accelerator=torch.device("cpu"), and checks that the recall@10 of the accelerated build is within 0.1 of the CPU build. It needs only torch (pytest.importorskip("torch")), no GPU, and runs in about 3 s.

  • Without the fix: CPU 0.840, torch 0.179 (fails).
  • With the fix, 15 runs: torch recall 0.821 to 0.847, CPU recall 0.834 to 0.864, largest gap 0.035.

All Python numbers here come from the released pylance 11.0.0 wheel with this vector.py change applied (the changed functions are identical on main). I have not built main from source. On that setup the torch-related tests of the 11.0.0 test suite (test_vector_index.py, test_indices.py, test_f16.py, torch_tests/, filtered with -k "torch or accelerator or f16 or centroid or cuda or gpu") give 49 passed, 26 skipped, 1 failed both with and without the change. The failure is torch_tests/test_data.py::test_bf16_to_tensor_clones_when_nulls_present, which does not use vector.py.

Recall before / after

recall@100 against exact cosine top-100, 50k x 512-d synthetic data, 64 partitions, 64 sub-vectors, accelerator="mps":

Variant Before: refine 10, nprobes 32 Before: PQ only, all partitions After: refine 10, nprobes 32 After: PQ only, all partitions
CPU build, cosine 1.000 0.835 1.000 0.827
MPS, cosine, raw vectors 1.000 0.502 1.000 0.768
MPS, cosine, pre-normalized vectors 0.690 0.110 1.000 0.765
MPS, l2, pre-normalized vectors (reference) 1.000 0.834 1.000 0.833

recall@10, 4096 x 32-d (script in the issue), accelerator=torch.device("cpu"):

Data Before: CPU build Before: torch build After: CPU build After: torch build
raw vectors 0.839 0.188 0.857 0.827
pre-normalized vectors 0.846 0.269 0.844 0.838

The CPU build is not seeded, so its numbers vary by about 0.02 between runs.

@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 bug Something isn't working labels Oct 7, 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 with a non-blocking risk.

The fix addresses the representation mismatch in #9754. The existing accelerated/CPU centroid-training difference can still lower PQ-only recall; refinement mitigates that remaining limitation.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 7, 2026
@Xuanwo
Xuanwo merged commit ec8691a into lance-format:main Oct 23, 2026
Xuanwo pushed a commit that referenced this pull request Nov 19, 2026
…11199)

`create_index(..., index_type="IVF_PQ", metric="dot", accelerator=...)`
builds an index with much lower recall than the CPU build. The torch
path trains the PQ codebook and computes the PQ codes in Python, and the
Rust builder uses them unchanged. For dot the two sides disagreed, the
same way they did for cosine in #9755:

- Rust only uses residuals for l2 and cosine
(`PQBuildParams::use_residual`), and always trains the PQ codebook with
L2. For dot it encodes the raw vectors and searches them without
subtracting the IVF centroid.
- The torch path always encoded residuals of the IVF centroids, and
trained the codebook with dot k-means.

## Changes

All in `python/python/lance/vector.py`, dot only:

- `compute_partitions` (residual sample for PQ training) and
`one_pass_assign_ivf_pq_on_accelerator` (final encoding): do not
subtract the IVF centroid when the metric is dot.
- `train_pq_codebook_on_accelerator`: train the per-sub-vector k-means
with `l2` for dot, as for cosine.

`l2` and `cosine` are unchanged.

Not changed here: at `nprobes=1` the accelerated build still trails the
CPU build, because the dot IVF k-means in `lance.torch.kmeans` stops
before its first update for vectors with norm above 1. That is fixed
separately in #11173. This PR does not depend on it: the test below
probes every partition, so it compares only the PQ encoding. With both
changes the accelerated build matches the CPU build at every `nprobes`
(last row of the table).

Both changes are needed: with only the residual change the accelerated
recall@10 at nprobes 4 is about 0.25, with only the L2 codebook about
0.41, with both 0.81.

## Tests

Added `test_torch_dot_ivf_pq_recall` to
`python/python/tests/test_vector_index.py`, next to the cosine one. It
builds a dot IVF_PQ index on 4096 x 32-d clustered vectors, once without
accelerator and once with `accelerator=torch.device("cpu")`, and checks
that the recall@10 (nprobes=4) of the accelerated build is within 0.1 of
the CPU build. It needs only torch (`pytest.importorskip("torch")`) and
runs in about 5 s.

- Without the fix: CPU 0.80-0.82, torch 0.11-0.21 (fails in 6 of 6
runs).
- With the fix: passes in 10 of 10 runs; the torch recall is within 0.02
of the CPU build.

recall@10 against exact dot top-10, 20000 x 32-d clustered data, 8
partitions, 16 sub-vectors:

| Build | nprobes 1 | nprobes 4 | nprobes 8 |
|---|---|---|---|
| CPU | 0.728 | 0.754 | 0.752 |
| `accelerator=cpu`, before | 0.204 | 0.060 | 0.040 |
| `accelerator=cpu`, after | 0.571 | 0.741 | 0.733 |
| `accelerator=mps`, after, plus #11173 | 0.757 | 0.735 | 0.742 |

Single runs; the CPU build and the torch sampling are not seeded, so the
numbers vary by a few points between runs.

Checks run on an Apple-silicon Mac using the pylance 15.0.0-beta.14
wheel with this branch's `lance/vector.py` overlaid (`vector.py` is
identical to main's apart from this change; the Rust extension is the
wheel's):
- `-k "torch or accelerator"` in `test_vector_index.py`: 8 passed.
- `ruff check` and `ruff format --check` pass on the touched files (ruff
0.11.2, the version CI pins).
- `uv run make lint` was not run: it needs `make install`, which builds
the Rust extension.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-python Python bindings bug Something isn't working K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IVF_PQ with metric="cosine" and accelerator=... builds an index with much lower recall than the CPU build

2 participants