Skip to content

feat(compression): Add 8 bit PQ - #494

Open
ahuber21 wants to merge 11 commits into
mainfrom
dev/ahuber/pq-upstream
Open

ahuber21 wants to merge 11 commits into
mainfrom
dev/ahuber/pq-upstream

Conversation

@ahuber21

@ahuber21 ahuber21 commented Dec 1, 2026

Copy link
Copy Markdown
Member

Adds 8-bit product quantization (svs/quantization/pq/pq.h): codebook training, encode/decode, save/load, and an
asymmetric table-lookup distance with AVX-512, AVX2 and scalar kernels in the multi-arch dispatch. It plugs into
static Vamana (build and search) and flat search, and the C++ runtime gets VamanaIndexPQ (StorageKind::PQ).

Things a reviewer should know:

  • IVF k-means moved. The generic k-means moved verbatim from ivf/common.h to svs/core/kmeans_training.h
    (svs::kmeans), so PQ training does not depend on the IVF index. ivf/common.h re-exports the old names, so IVF
    call sites do not change. Commit 35a81417 is only the move.
  • Flags. SVS_EXPERIMENTAL_ENABLE_PQ (core, off by default, needs MKL) and SVS_RUNTIME_ENABLE_PQ (runtime,
    off). The runtime option fails at configure time together with SVS_RUNTIME_ENABLE_LVQ_LEANVEC, because the
    pre-built LVQ/LeanVec library is built without PQ.
  • CI. PQ uses the existing ivf matrix axis in build-linux.yml, so the matrix does not grow. In the runtime
    workflow, only the leg without LVQ/LeanVec builds PQ.
  • Static only. No dynamic index, no Python bindings, no cosine. The table type (Auto/f32/f16/u8) is chosen at
    search time and is not saved, so runtime load and map_to_memory take it as an argument.
  • Graph build on PQ codes is slow. Each time the prune step accepts a neighbor, and for each back-edge source,
    it builds a new lookup table (num_centroids x dims work). A 1M x 768 build takes about an hour per width
    (extrapolated from a 20k build) against about 2 minutes on f32. Building the graph on full-precision vectors and
    searching on codes avoids this. A symmetric centroid-to-centroid table would be the follow-up fix.
  • Auto table type. It picks the widest table that fits half the per-core L2. At 1,024 subspaces the f32 table
    is exactly 1 MiB, so on SPR Auto still picks f32, which was 1.7x slower there than f16 or u8.

Flat scan against Faiss IndexPQ (Faiss 1.12.0, same 8-bit codes, 256 centroids), SVS QPS / Faiss QPS, one SPR
socket (112 threads), AVX-512:

data M f32 f16 u8
DPR 1M x 768 96 1.04 1.17 1.33
DPR 1M x 768 192 1.06 1.11 1.20
MS MARCO 1M x 4096 512 1.11 1.13 1.10
MS MARCO 1M x 4096 1024 1.11 1.91 1.89

AVX2 gives about the same numbers. Recall@10 is within 0.004 of Faiss. Caveats:

  • IndexPQ's 8-bit scan is not SIMD. IndexPQFastScan (4-bit) is the stronger baseline and was not run.
  • AVX2 and the scalar path were forced on SPR by clearing the CPU flags. They were not measured on older CPUs.
  • On the scalar path (no AVX2), f16 and u8 run at 0.26x to 0.69x of Faiss, one case at 1.15x, and f32 at 0.77x
    to 0.91x. The scalar f16 path converts each entry in software (Float16, no F16C), and the scalar u8 path does a
    second load and a multiply for each entry. That this causes the gap is inferred, not profiled.
  • Vamana numbers use a graph built on f32 vectors, not on PQ codes.
  • The numbers were measured on 963c6c4d, one commit before the fp16 range fix. That fix adds one multiply per
    distance on the f16 path only.

ahuber21 and others added 11 commits December 2, 2026 02:25
Shared k-means building blocks (centroid assignment/adjustment/split,
GEMM-backed distance computation, training-set sampling) now live in
svs::kmeans under include/svs/core/kmeans_training.h, so other codebook
trainers can reuse them without depending on the IVF index. Function
bodies are moved verbatim; the IVF-specific
kmeans_training(IVFBuildParameters, ...) overload now forwards to the
shared one via a small KMeansTrainingParameters struct.
include/svs/index/ivf/common.h re-exports every moved name with
using-declarations so existing IVF call sites, tests, bindings and
benchmarks compile unchanged.

Named the shared header kmeans_training.h rather than kmeans.h: an
unrelated legacy generic k-means utility (svs::find_nearest, svs::train,
KMeansParameters) already owns include/svs/core/kmeans.h and its
always-built test tests/svs/core/kmeans.cpp; reusing that path would
have threaded an MKL dependency into the default build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Covers the L2 centroid update formula (initial centroid plus assigned
points, divided by count+1, not a plain mean), unit-norm centroids under
IP distance, and centroid_assignment agreeing with a brute-force
nearest-centroid oracle for both distances. Registered under the IVF
option, which is what links the header's MKL dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds PQ codebook training (per-subspace k-means on the shared
svs::kmeans trainer), encoding, an asymmetric table-lookup distance with
an AVX-512 gather kernel and a scalar fallback, PQDataset save/load
(including the single-stream pair the type-erased Vamana and flat
orchestrators need), and the Vamana and flat extension hooks, so a
static Vamana index can be built directly on PQ codes or assembled from
an existing graph plus PQ data.

The k-means trainer needs Intel(R) MKL, so PQ sits behind the new
SVS_EXPERIMENTAL_ENABLE_PQ option (default OFF), which links MKL the way
SVS_EXPERIMENTAL_ENABLE_IVF does and defines SVS_ENABLE_PQ. The PQ
extension headers fail with #error when the option is off, and the PQ
unit and integration tests are registered only when it is on. The
Vamana build tests set alpha per distance (<= 1.0 for MIP and cosine,
> 1.0 for L2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…types

Moves the asymmetric-distance table-lookup kernel off its
[[gnu::target("avx512f")]] function and onto SVS's per-ISA translation
unit pattern (PQTableLookupImpl<AVX_AVAILABILITY>, extern template in
the header, explicit instantiation in multi-arch/x86/avx512.cpp), as the
distance kernels do. The AVX-512 case keeps an unused second template
parameter so it stays a partial, not full, specialization: a full
specialization's in-class bodies get ordinary per-TU inline linkage and
the optimizer drops them whenever the TU never calls them, which
silently breaks the cross-TU extern-template link.

Also wraps pq.h in the SVS_ENABLE_PQ guard the extension headers use,
and makes the table element type selectable: fp32 (the default), fp16,
or a Faiss/ScaNN-style per-subspace-scaled uint8 table, chosen through
AsymmetricDistance's table_type argument. A microbenchmark showed no
single-core speed gain from fp16 or uint8 at any size, and uint8 costs
up to 10% relative distance error, so both are opt-in.

pq_benchmark.cpp (ns/call, 16-2560 subspaces at width 8, hidden behind
[!benchmark] like the distance benchmarks) found that unrolling to four
accumulators plus a code-row prefetch made every size measured slightly
slower, so the kernel keeps a single accumulator. The remaining overhead
at small num_subspaces is the dispatch's own cross-TU call, unavoidable
without LTO.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PQDataset now carries its own table type (member, getter/setter), separate from the
save format so codes saved before this change still load. The Vamana and flat PQ
search extensions construct AsymmetricDistance with the dataset's table type instead
of always defaulting to fp32.

Default is Auto: picks the widest table (fp32, then fp16, then uint8) whose bytes fit
half the per-core L2, read via sysconf(_SC_LEVEL2_CACHE_SIZE) with a 1 MiB fallback.
Tables spilling L2 send gathers to DRAM under full-socket load, which a single-core
microbenchmark cannot show. Falls back to uint8 (narrowest) when nothing fits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds PQTableLookupImpl<AVX2> for the f32, f16 and u8 lookup tables,
instantiated in avx2.cpp (-march=haswell) like the AVX-512 level. The
three table_lookup_sum entry points now share one dispatch function, so a
new ISA level is listed in one place.

Kernel choice was measured on a Sapphire Rapids socket with a throwaway
gather-vs-scalar-load microbenchmark at 512 and 2,560 subspaces, 1 and 112
threads: f32 and u8 use vpgatherdd/vpgatherdps (u8 gather 1.3x faster than
scalar loads at 112 threads, 2,560 subspaces); f16 assembles its eight
halves with scalar loads, 1.4x faster than the gather on one core and
within 5% at 112 threads. Gather offsets are relative to the block's base
row, so 32-bit indices cannot overflow.

The kernel test now calls every compiled level (NONE, AVX2, AVX512)
directly against the scalar reference, so an AVX-512 host still checks
AVX2, and pads the f16/u8 tables as QuantizedTable does. pq_benchmark
gains AVX2 columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add StorageKind::PQ and VamanaIndexPQ (build, load, map_to_memory)
behind the new SVS_RUNTIME_ENABLE_PQ option. Subspace width, centroids
per subspace and the lookup-table type are caller parameters. The table
type is not part of the saved index, so every load names it; a thin
dataset wrapper applies it before the type-erased index hides the
dataset.

PQ is static-Vamana only: the generic storage dispatch has no PQ case,
so DynamicVamanaIndex and VamanaIndex::build reject it. Like IVF, the
option turns on the matching SVS build option and needs MKL; it builds
only from source, so it cannot be combined with
SVS_RUNTIME_ENABLE_LVQ_LEANVEC. SVS_RUNTIME_HAVE_PQ is exported for
consumers, as SVS_RUNTIME_HAVE_LVQ_LEANVEC is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Linux matrix enables SVS_EXPERIMENTAL_ENABLE_PQ together with IVF,
which already installs and links MKL, so the job count and names stay
unchanged. The C++ runtime build enables SVS_RUNTIME_ENABLE_PQ on the
public-only leg, the one configuration without the pre-built LVQ/LeanVec
library, which PQ cannot be combined with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A table entry above 65504 (unnormalized data, e.g. raw-pixel L2 or large
inner products) converted to an fp16 inf/NaN bit pattern. The AVX-512 and
AVX2 kernels widen those with vcvtph2ps, so distances came out wrong by
orders of magnitude, and TableType::Auto can pick fp16 without the caller
asking. The fp16 table is now stored divided by a power of two that brings
the largest entry into range, and the lookup sum is multiplied back; a
power of two only moves the exponent, so no mantissa precision is lost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The default entry point is the medioid of `get_datum`, which for a PQ
dataset is the code span (one byte per subspace) while `dimensions()` is
the decoded width. The mean was accumulated over mismatched sizes: a heap
over-read and a meaningless entry point with asserts off, an abort in
`CountSum::add` with asserts on (C++ runtime CI leg, which builds with no
build type).

Customize `compute_entry_point` for PQ datasets to pass a `Decoder` as
the medioid map, so the mean and the nearest point are computed on the
decoded vectors. `find_medioid` copies the map per worker, so each
thread reuses one decode buffer. Its size assert now checks the mapped
datum, the one it actually reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The PQ code was developed and benchmarked against Faiss IndexPQ, so it may contain
portions derived from Faiss. List Faiss in THIRD-PARTY-PROGRAMS and point to it from pq.h.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ahuber21
ahuber21 force-pushed the dev/ahuber/pq-upstream branch from 72bc32c to c309c70 Compare December 2, 2026 10:26
@mihaic
mihaic requested a balanced review from Copilot December 3, 2026 18:28

Copilot AI 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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

7 open issues
What changed in this PR

Adds native 8-bit Product Quantization (PQ) support (training, encode/decode, distance table lookup w/ multi-arch SIMD kernels) and integrates it into static Vamana + flat search, along with runtime support behind opt-in build flags.

Changes:

  • Introduces svs/quantization/pq implementation (codebooks, dataset, asymmetric distance, AVX-512/AVX2/scalar kernels + dispatch).
  • Moves shared k-means training utilities into svs/core/kmeans_training.h and re-exports from IVF.
  • Adds unit/integration/runtime tests and wires PQ into CMake and CI behind SVS_EXPERIMENTAL_ENABLE_PQ / SVS_RUNTIME_ENABLE_PQ.
File Description
tests/​svs/​quantization/​pq/​pq_benchmark.cpp Adds PQ kernel microbenchmark (Catch2 benchmark tag).
tests/​svs/​quantization/​pq/​pq.cpp Adds PQ unit tests (training, encode/decode, LUT distance accuracy, save/load, etc.).
tests/​svs/​core/​kmeans_training.cpp Adds unit tests for the extracted shared k-means trainer.
tests/​integration/​vamana/​pq_search.cpp Adds integration coverage for assembling/searching Vamana with PQ codes.
tests/​integration/​vamana/​pq_build.cpp Adds integration coverage for building Vamana directly on PQ data.
tests/​integration/​flat/​pq_search.cpp Adds integration coverage for exhaustive flat PQ scan.
tests/​CMakeLists.txt Wires PQ + shared k-means tests behind build flags.
include/​svs/​quantization/​pq/​pq.h Implements PQ (training, dataset, LUT distance, SIMD kernels, save/load).
include/​svs/​multi-arch/​x86/​avx512.cpp Instantiates PQ LUT AVX-512 kernel when PQ is enabled.
include/​svs/​multi-arch/​x86/​avx2.cpp Instantiates PQ LUT AVX2 kernel when PQ is enabled.
include/​svs/​index/​ivf/​common.h Re-exports moved k-means utilities from svs::kmeans.
include/​svs/​extensions/​vamana/​pq.h Adds Vamana extension points for PQ datasets (distance, decode adaptor, entry point).
include/​svs/​extensions/​flat/​pq.h Adds flat index distance extension for PQ datasets.
include/​svs/​core/​medioid.h Fixes assertion to validate mapped size, not raw datum size.
include/​svs/​core/​kmeans_training.h New shared k-means training header (MKL-backed GEMM utilities).
cmake/​options.cmake Adds SVS_EXPERIMENTAL_ENABLE_PQ and sets SVS_ENABLE_PQ compile option.
cmake/​mkl.cmake Uses the IVF MKL function list when PQ is enabled (PQ shares MKL needs).
bindings/​cpp/​tests/​pq_runtime_test.cpp Adds runtime tests for PQ build/search/save/load/map_to_memory.
bindings/​cpp/​tests/​CMakeLists.txt Adds PQ runtime tests behind SVS_RUNTIME_ENABLE_PQ.
bindings/​cpp/​src/​vamana_pq_index_impl.h Implements runtime VamanaIndexPQ (build/load/map) using PQ dataset.
bindings/​cpp/​src/​vamana_index.cpp Adds VamanaIndexPQ entry points and adjusts storage kind checks.
bindings/​cpp/​src/​svs_runtime_utils.h Adds StorageKind::PQ helpers and excludes PQ from generic factories.
bindings/​cpp/​include/​svs/​runtime/​vamana_index.h Adds runtime PQ API surface (PQParameters, PQTableType, VamanaIndexPQ).
bindings/​cpp/​include/​svs/​runtime/​api_defs.h Adds StorageKind::PQ.
bindings/​cpp/​CMakeLists.txt Adds SVS_RUNTIME_ENABLE_PQ option, build wiring, and LVQ/LeanVec incompatibility check.
THIRD-PARTY-PROGRAMS Adds Faiss attribution for the PQ implementation.
CMakeLists.txt Includes MKL when IVF or PQ is enabled.
.github/​workflows/​build-linux.yml Enables PQ on existing IVF axis to avoid expanding the CI matrix.
.github/​scripts/​build-cpp-runtime-bindings.sh Enables PQ only on the runtime leg that builds SVS from source (no LVQ/LeanVec prebuilt).

Review effort: Lite

Comment on lines +113 to +164
double f32_avx512_ns = 0.0;
double f16_avx512_ns = 0.0;
double u8_avx512_ns = 0.0;
#if defined(__x86_64__)
if (svs::detail::avx_runtime_flags.is_avx512f_supported()) {
f32_avx512_ns = ns_per_call([&] {
return pq::detail::table_lookup_sum_avx512(
table_f32.data(), codes.data(), num_subspaces, num_centroids
);
});
f16_avx512_ns = ns_per_call([&] {
return pq::detail::table_lookup_sum_f16(
table_f16.data(), codes.data(), num_subspaces, num_centroids
);
});
u8_avx512_ns = ns_per_call([&] {
return pq::detail::table_lookup_sum_u8(
table_u8.data(),
scale.data(),
codes.data(),
num_subspaces,
num_centroids
);
});
}
double f32_avx2_ns = 0.0;
double f16_avx2_ns = 0.0;
double u8_avx2_ns = 0.0;
if (svs::detail::avx_runtime_flags.is_avx2_supported()) {
using Avx2 =
pq::detail::PQTableLookupImpl<svs::distance::AVX_AVAILABILITY::AVX2>;
f32_avx2_ns = ns_per_call([&] {
return Avx2::compute(
table_f32.data(), codes.data(), num_subspaces, num_centroids
);
});
f16_avx2_ns = ns_per_call([&] {
return Avx2::compute_f16(
table_f16.data(), codes.data(), num_subspaces, num_centroids
);
});
u8_avx2_ns = ns_per_call([&] {
return Avx2::compute_u8(
table_u8.data(),
scale.data(),
codes.data(),
num_subspaces,
num_centroids
);
});
}
#endif
Comment on lines +202 to +209
static Status map_to_memory(
VamanaIndex** index,
void* data,
size_t size,
MetricType metric,
PQTableType table_type,
size_t* read_bytes = nullptr
) noexcept;
Comment on lines 127 to 138
Status VamanaIndex::check_storage_kind(StorageKind storage_kind) noexcept {
bool supported = false;
auto status = runtime_error_wrapper([&] {
supported = storage::is_supported_storage_kind(storage_kind);
#ifdef SVS_RUNTIME_ENABLE_PQ
constexpr bool pq_enabled = true;
#else
constexpr bool pq_enabled = false;
#endif
supported = storage::is_pq_storage(storage_kind)
? pq_enabled
: storage::is_supported_storage_kind(storage_kind);
});
Comment on lines +34 to +35
// Intel(R) MKL
#include <mkl.h>
Comment on lines +29 to +30
#include <cmath>
#include <random>
#include <random>
#include <span>
#include <sstream>
#include <string>
Comment on lines +473 to +474
return decltype(impl
)::compute_u8(table, scale, codes, num_subspaces, num_centroids);

@mihaic mihaic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please have a look at the Copilot suggestions. They look reasonable to me.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants