Skip to content

[diskann-quantization] Add fused f32 TopK to multi-vector kernels - #1583

Open
juchen-ms (partychen) wants to merge 12 commits into
microsoft:mainfrom
partychen:fused-f32-topk
Open

juchen-ms (partychen) wants to merge 12 commits into
microsoft:mainfrom
partychen:fused-f32-topk

Conversation

@partychen

@partychen juchen-ms (partychen) commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor
  • Does this PR have a descriptive title that could go in our release notes?
  • Does this PR add any new dependencies?
  • Does this PR modify any existing APIs?
  • Is the change to the API backwards compatible?
  • Should this result in any changes to our documentation, either updating existing docs or adding new ones?

No new dependencies or changes to existing public API signatures in the remaining diff. Adds TopKKernel, its result/error types, and generic sorted insertion. The fallible packing and k-means API changes landed separately in #1618.

Reference Issues/PRs

Built on merged #1618. Main is integrated; the constructor migration, training callers and k-means error-interface changes are no longer part of this diff.

What does this implement/fix? Briefly explain your changes.

Add exhaustive f32 TopK for inner product and squared L2, updating nearest candidates directly from dot-product tiles without allocating the M x N score matrix. Reuse the existing matrix kernels and share generic sorted insertion through diskann_utils::slice. Quantization and PiPNN keep separate candidate types; the new public result type is diskann_quantization::multi_vector::Candidate. PiPNN graph construction itself is not migrated to fused computation.

How to call

Bind the centroids once. Each queries below is a rowmajor::Ref<f32>; output has one row per query and k columns. Reuse the buffer for equal-sized batches and resize it for a different batch shape.

// Prepare the centroids and their L2 norms once for all batches.
let kernel = TopKKernel::new(MaxSimIsa::Auto, Metric::L2, centroids)?;
for queries in query_batches {
    kernel.compute_top_k(queries, output.as_view_mut())?;
    // Use this batch's results before reusing the output buffer.
}

For Graph-IVF, bind the centroids once and pass each incoming vector or query batch to compute_top_k; the output width is the assignment count or nprobe. A future PiPNN leader-assignment caller can construct one kernel per leader set and search successive point stripes. This is rectangular search, not a replacement for symmetric leaf selection. Concurrent calls need separate outputs, not caller-owned scratch. Native calls pack the incoming query batch internally. Candidate indices are local to the bound matrix; unfilled slots are Candidate::EMPTY.

Review follow-up and validation

Kernel-boundary cleanup at 53e0afb4

Shared packed-f32 dot arithmetic now lives in matrix_kernels/packed_f32_x_unpacked_f32.rs; MaxSim keeps its own reduction. Traversal accepts independent subview sizes rather than Params. TopK consumes B norms sequentially within each subview while preserving global candidate IDs, and separates distance conversion from selection updates. Public APIs, distance formulas and PiPNN SIMD behavior are unchanged. Added a local-norm/global-ID regression test and removed redundant comments.

Validation on the final code:

  • cargo fmt --all -- --check: passed.
  • cargo test -p diskann-quantization --lib --quiet: passed, 538 tests.
  • cargo clippy --workspace --all-targets -- -D warnings: passed.
  • cargo clippy -p diskann-quantization --all-targets --all-features -- -D warnings: passed.
  • cargo check -p diskann-quantization --all-targets --all-features --target aarch64-pc-windows-msvc --quiet: passed, compile only.
  • git diff --check: passed.

Current before/after TopK comparison, separate from the historical Faer/Neon measurements below:

Baseline 79467f4c300a005c2af0027368cc4023efe39d7d versus this revision, Windows / Intel Core Ultra 7 268V, rustc 1.97.1, identical dependency lockfiles and release settings (opt-level=3, codegen-units=1), one thread pinned to processor group 0 / CPU 2. Candidate preparation and output allocation are outside timing; query packing is included. Each process warms/calibrates each case. Baseline/current execution order alternates; no concurrent builds were running.

The local session harness was built with cargo build --manifest-path "$base\$revision\Cargo.toml" --release --quiet for each revision (passed), then run as & "$base\$revision.exe" (six balanced pairs) and & "$base\$revision.exe" --large (four balanced pairs), all passed. $base is the local session benchmark directory; the harness and raw CSVs are retained there, not added to the repository.

  • Standard sweep: 20 workload/backend combinations, IP/L2, K=1/10; M/N/D = 257/1025/17 and 1024/4096/128 on Scalar/AVX2, plus 8192/16384/128 on AVX2. Median paired current/baseline ratios ranged from 0.947 to 1.028; their geometric mean was 0.987.
  • Focused follow-up: rebuilt with cargo build --manifest-path "$base\$revision\Cargo.toml" --release --quiet --locked (passed), then & "$base\medium-$revision.exe" --medium (eight balanced pairs, passed), using approximately one second of timed calls per case. At 1024/4096/128, AVX2 IP ratios were 1.023 (K=1) and 1.021 (K=10); L2 ratios were 1.007 and 0.984.
  • All compared output checksums matched, including candidate IDs and distance bit patterns.

At M=32768, N=65536, D=128, K=10 on AVX2:

Metric Baseline median Current median Median paired current/baseline ratio
Inner product 4861.755 ms 4766.295 ms 0.999
Squared L2 4895.723 ms 4787.563 ms 0.991

Paired-ratio medians and ratios of independently computed time medians need not agree. The largest-case paired ranges were 0.957-1.011 (IP) and 0.943-1.013 (L2). This shared host also had substantial timing outliers in the medium runs, so these results do not prove zero regression or a speedup: largest workloads were comparable, while medium IP measured about 2% slower. No AVX-512/Neon runtime or end-to-end PiPNN performance claim is made.

Integrated main through #1618 in 2c842418bfa0de3fe42e61da82f4813897e9bd1a, without rewriting the existing commits. The remaining diff contains 25 files; the foundation-only changes are gone.

Post-integration validation:

  • cargo fmt --all --check: passed.
  • cargo test -p diskann-quantization -p diskann-utils --lib --quiet: passed, 537 quantization and 165 utils tests.
  • cargo test -p diskann --features pipnn --lib graph::pipnn --quiet: passed, 148 tests.
  • cargo test -p diskann-quantization -p diskann-utils --doc --quiet: passed, 41 passed and 7 ignored.
  • cargo clippy --workspace --all-targets -- -D warnings: passed.
  • cargo clippy -p diskann --features pipnn --all-targets -- -D warnings: passed.
  • cargo check -p diskann-quantization --all-targets --all-features --target aarch64-pc-windows-msvc --quiet: passed, compile only.

Shared packed-by-unpacked traversal now lives in blocks/packed_x_unpacked.rs with distinct panel/row index types (6944efa). Matrix storage owns its associated L2 norms, including packed padding; IP/L2 have separate entry points, and cache parameters stay inside matrix_kernels (7ec5d19). Generic insertion lives only in utils, with independent candidate types (78c9e42). The final follow-up removes the panicking convenience tiling constructor, makes legacy MaxSim callers handle failure explicitly, restricts parameter visibility and documents TopK input contracts (523dea4). Existing closure-level #[inline(always)] annotations are retained.

Earlier validation on Windows x86-64 at 523dea426b11405717360f78cd2c7cb9d64168a4:

  • cargo fmt --all --check: passed.
  • cargo test -p diskann-quantization -p diskann-utils --lib --quiet: passed, 537 quantization and 157 utils tests.
  • cargo test -p diskann --features pipnn --lib graph::pipnn --quiet: passed, 148 tests.
  • cargo test -p diskann-quantization -p diskann-utils --doc --quiet: passed, 41 passed and 7 ignored across doctest groups.
  • cargo clippy --workspace --all-targets -- -D warnings: passed.
  • cargo clippy -p diskann --features pipnn --all-targets -- -D warnings: passed.
  • cargo check -p diskann-quantization --all-targets --all-features --target aarch64-pc-windows-msvc --quiet: passed; compile only, not ARM64 runtime.
  • $env:RUSTDOCFLAGS='-D warnings -D rustdoc::all'; cargo doc -p diskann-quantization -p diskann-utils --no-deps --all-features --document-private-items --quiet: passed.

A separate release smoke harness exercised IP/L2, K=1/10, M/N/D=257/1025/17 and 1024/4096/128 on available Scalar and AVX2 backends. Distances matched the reference within 1e-4 * max(1, abs(reference)); five warmed calls per case included query packing and reused candidate state/output. This was an unpinned run on a shared host, not a controlled comparison with the earlier revision or Faer. No new performance-regression claim is made; the historical measurements below remain labeled with their original revisions. AVX-512/Neon runtime, SDE baseline execution, full workspace tests and coverage were not rerun.

AVX2 batch performance

Across 32 small and medium IP/L2 workloads, runtime-K TopK was within 1% of the earlier fused kernel (batch time ratio: 0.994–1.008×). At the largest shape, both metrics were within 0.3%:

Metric Fused baseline Runtime-K TopK
Inner product 6.348 s 6.332 s
Squared L2 6.359 s 6.375 s

The table shows three-run medians for 32,768 queries × 65,536 candidates, D=128, K=10 (AMD EPYC 7763, Windows, Release, one pinned AVX2 thread). Both kernels reused candidate state and output; batch time includes query packing. Output checksums matched. Baseline: d3f58c40; measured revision: eb3d7ff8 (before the constructor-only cutoff check).

SIMD screening uses one f32 cutoff per padded query row: 128 KiB at this shape. That is the cutoff buffer size, not total peak memory. Neither fused kernel materializes the full score matrix.

Historical x86 comparison against Faer (previous fused kernel)

Earlier fused kernel (d3f58c40), compared with Faer: 1.31-1.63x faster with 431-440x smaller auxiliary heap than faer GEMM + TopK (M=32768, N=65536, D=128, k=10).

ISA Metric faer / fused time (ms) Speedup faer / fused auxiliary heap (MiB)
AVX2 Inner product 7469.55 / 5712.45 1.31x 8198.50 / 18.63
AVX2 Squared L2 8654.95 / 5814.31 1.49x 8198.88 / 19.00
AVX-512 Inner product 5682.90 / 4189.72 1.36x 8198.50 / 18.63
AVX-512 Squared L2 6911.08 / 4238.39 1.63x 8198.88 / 19.00

Across 80 complete M x N shapes and every k=2..10, geometric-mean speedup is:

ISA Inner product Squared L2
AVX2 1.11x 1.33x
AVX-512 1.06x 1.31x

Latency, auxiliary-memory and speedup-vs-k curves for AVX2 and AVX-512

Any other comments?

Historical comparison against Faer at d3f58c40: Xeon Platinum 8370C, Windows x86-64, release build, one pinned thread, D=128, synthetic inputs. M/N independently range from 256 to 65536 in powers of two.

Times are warmed compute medians, excluding input preparation and score/output allocation. Auxiliary heap includes packed queries, norms, output, scratch and faer workspace, excludes common inputs, and is not process RSS. Each point checks three rows against an exhaustive f64 reference. Fused is not faster in every case, especially for smaller inner-product workloads; these are kernel results, not PiPNN graph-build speedups.

Historical Neon runtime and compute-workspace comparison (d3f58c40, prepared A)

The attached Neon results show fused compute workspace at approximately 0.5%–4% of Faer + TopK across the completed groups (roughly 96%–99.5% lower). These are approximate ranges read from the chart, not per-configuration measurements.

  • A rows: 256–65,536; B rows: 256, 512, or 1,024.
  • Each plotted point is the geometric mean of 40 settings: dimensions 384/897, IP/L2, and K=1–10.
  • 26 of 27 A/B groups are complete, covering 1,040 configurations. A=65,536, B=1,024 is pending (17/40); incomplete groups are omitted, not extrapolated.
  • Workspace includes output, the score matrix where materialized, and scratch. It excludes prepared inputs and norms, and is not process RSS or total auxiliary heap. This is a different measurement scope from the x86 auxiliary-heap results above, which include packed queries, norms, output, scratch and Faer workspace.

The Neon runtime chart shows broadly comparable runtime: most plotted group means are approximately 94%–104% of Faer + TopK, with the two smallest A groups at B=256 around 82% and 85%. These are approximate readings of geometric means, not a guarantee for every configuration. The AVX2/AVX-512 results above are separate measurements on different hardware and workloads.

Neon runtime comparison: fused TopK versus Faer plus TopK with prepared A

Neon compute-workspace comparison: fused TopK versus Faer plus TopK with prepared A

@partychen
juchen-ms (partychen) requested review from a team and a balanced review from Copilot November 7, 2026 06:22

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.

🟡 Changes recommended

Cancellation in fused and Reference L2 calculations can select the wrong nearest neighbor, requiring direct squared-difference computation before selection rather than clamping.

1 open issue
What changed in this PR

This PR extracts reusable TopK selectors into diskann-vector and adds fused f32 matrix TopK to the multi-vector framework, without migrating PiPNN’s distance computation.

Changes:

  • Share sorted-array selection helpers and replace PiPNN’s SIMD adapter with existing architecture types.
  • Add prepared-query and document APIs for inner-product and squared-L2 TopK.
  • Reuse dot tiles and cache traversal while retaining MaxSim’s separate reduction, with tests for selection and API behavior.
File Description
diskann/​src/​graph/​pipnn/​topk.rs Uses shared selectors and adds tie-order regression coverage.
diskann/​src/​graph/​pipnn/​simd.rs Removes the redundant SIMD adapter.
diskann/​src/​graph/​pipnn/​partition_kernel.rs Switches leader assignment to Architecture bounds.
diskann/​src/​graph/​pipnn/​mod.rs Updates module wiring, documentation, and test architecture bounds.
diskann/​src/​graph/​pipnn/​leaf_kernel.rs Switches leaf selection to Architecture bounds.
diskann-vector/​src/​topk.rs Adds shared candidate types, selectors, and tests.
diskann-vector/​src/​lib.rs Exports the TopK module.
diskann-quantization/​src/​multi_vector/​mod.rs Exports public TopK APIs.
diskann-quantization/​src/​multi_vector/​distance/​topk.rs Implements TopK preparation, dispatch, validation, and API tests.
diskann-quantization/​src/​multi_vector/​distance/​mod.rs Registers and re-exports TopK functionality.
diskann-quantization/​src/​matrix_kernels/​topk/​packed_f32_x_unpacked_f32.rs Adds fused tile-to-TopK selection and blocking tests.
diskann-quantization/​src/​matrix_kernels/​topk/​mod.rs Introduces the TopK kernel module.
diskann-quantization/​src/​matrix_kernels/​mod.rs Registers TopK alongside MaxSim.
diskann-quantization/​src/​matrix_kernels/​maxsim/​packed_f32_x_unpacked_f32.rs Shares dot tiles and traversal while preserving MaxSim reduction.
diskann-quantization/​src/​matrix_kernels/​blocks/​packed.rs Adds inlining to packed-panel traversal helpers.

Review effort: Balanced

Metric::L2 => {
// SAFETY: L2 A norms have the same padded extent as the thresholds.
let a_norm = unsafe { V::load_simd(arch, rows.a_norms.as_ptr()) };
(a_norm + V::splat(arch, b_norm)) - V::splat(arch, 2.0) * dot

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The cancellation example is valid, but the expanded L2 formula is intentional and matches the existing PiPNN leaf path in leaf_metric.rs. This preserves the formula, not bitwise-identical results across backends. The agreed spec explicitly requires (q_norm + d_norm) - 2*dot without clamping; selection operates on those computed f32 distances. Direct squared differences or selective recomputation would change that numerical contract and are outside this extraction.

@partychen juchen-ms (partychen) changed the title Extract shared TopK selectors and add fused f32 matrix kernels [diskann-quantization] Add fused f32 TopK to multi-vector kernels Nov 7, 2026
@codecov-commenter

Codecov Comments Bot (codecov-commenter) commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.09302% with 40 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.40%. Comparing base (cdea177) to head (e605a57).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...c/matrix_kernels/topk/packed_f32_x_unpacked_f32.rs 95.77% 18 Missing ⚠️
...ann-quantization/src/multi_vector/distance/topk.rs 97.79% 8 Missing ⚠️
...kann-quantization/src/multi_vector/distance/isa.rs 91.17% 6 Missing ⚠️
...-quantization/src/multi_vector/distance/factory.rs 86.20% 4 Missing ⚠️
...quantization/src/matrix_kernels/blocks/unpacked.rs 92.85% 3 Missing ⚠️
...on/src/matrix_kernels/packed_f32_x_unpacked_f32.rs 98.91% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1583      +/-   ##
==========================================
+ Coverage   91.31%   91.40%   +0.09%     
==========================================
  Files         633      637       +4     
  Lines      133627   134969    +1342     
==========================================
+ Hits       122018   123367    +1349     
+ Misses      11609    11602       -7     
Flag Coverage Δ
miri 91.40% <97.09%> (+0.09%) ⬆️
unittests 91.13% <94.63%> (+0.09%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...n-quantization/src/matrix_kernels/blocks/packed.rs 99.71% <100.00%> (+<0.01%) ⬆️
...ion/src/matrix_kernels/blocks/packed_x_unpacked.rs 100.00% <100.00%> (ø)
...matrix_kernels/maxsim/packed_f32_x_unpacked_f16.rs 100.00% <100.00%> (ø)
...matrix_kernels/maxsim/packed_f32_x_unpacked_f32.rs 97.97% <100.00%> (-0.19%) ⬇️
...c/matrix_kernels/maxsim/packed_i8_x_unpacked_i8.rs 96.01% <100.00%> (+0.05%) ⬆️
..._kernels/maxsim/packed_minmax_x_unpacked_minmax.rs 95.27% <100.00%> (+<0.01%) ⬆️
diskann-quantization/src/matrix_kernels/mod.rs 100.00% <ø> (ø)
diskann-quantization/src/minmax/multi/factory.rs 97.85% <100.00%> (+0.79%) ⬆️
diskann-utils/src/lib.rs 100.00% <ø> (ø)
diskann-utils/src/slice.rs 100.00% <100.00%> (ø)
... and 11 more

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I did a skim over this and I have some high-level concerns, mainly with how this compounds on top some shaky fundamentals and poor composition already present in matrix_kernels.

The matrix tiling infrastructure is more or less something I slapped together in a few days. There are parts of it that are not great: it has no ability to partition across the k dimension, and the cache sizing is basically something I did some napkin math on and has not had a lot of empirical tuning.

Doubling down on these decisions without a better understanding of how to solve these problems seems like it will make it that much harder to come back and do it correctly, or at all.

In addition, fusing the topk implementation so deep into implementation (like the minmax kernel) feels like it's missing some more fundamental abstraction that would make writing custom kernels (and quantized kernels for different quantization schemes), overall easier and with less unsafe code.

Is running this on small matrices indicative of running it how it will be used in pipnn on datasets with millions of points? Does the performance still hold in an integration test scenario?

I like the idea of self-hosting our own dense computations if there is a meaningful performance improvement, but we also need to balance it with the maintenance tax. Which for this I think is quite high.

Comment thread diskann-vector/src/topk.rs Resolved
@partychen

Copy link
Copy Markdown
Contributor Author

Mark Hildebrand (@hildebrandmw), following up on your review: this isn't just for PiPNN. Graph-IVF needs the same TopK operation for centroid assignment and query routing, and I'd rather share that code than maintain another implementation.

I've benchmarked query counts from 256 to 65536, candidate counts of 256/512/1024, and k=2..10. Runtime is roughly comparable for IP (AVX-512 is slightly slower on average), while L2 is about 1.2x faster. Peak auxiliary heap is about 7.6-7.7x lower on geometric average in that range, with reductions reaching hundreds-fold when the candidate matrix is larger. Avoiding the score matrix is the main benefit here, not a claim of a big speedup everywhere.

These are kernel benchmarks, not an end-to-end PiPNN integration test, and this PR doesn't switch PiPNN graph construction to the fused path. I agree the tiling and kernel-composition concerns still need work. The reason I think the extraction is worth doing is that it gives PiPNN and Graph-IVF shared TopK building blocks rather than two implementations to maintain and optimize.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A general them for my feedback is this: please make contracts as correct by construction as possible. Keep invariants as local as possible and please avoid implicit coupling between different parts.

The Metric is a great example. As is, the low level kernels are relying on the factor to exclude metrics outside of L2 and InnerProduct further, elements in the middle layer are supposed to know how to handle the norm scratch space depending on the metric value. This is a long-range implicit coupling that should be avoided in favor of explicit and local contracts.

Additionally, Rows is under-specified. The relationships among its members should be explicitly described. Even better, build a proper abstraction out of it rather than treating it as a bundle of arguments the user of which must handle with care. This more-or-less self documents how it's expected to be used.

I generally don't like including text from LLMs in my reviews, but in the spirit of getting feedback done, some of them do include LLM text. These have a disclaimer indicating such.

Comment thread diskann-vector/src/topk.rs Resolved
Prepare the candidate metric once and scan successive query batches using runtime K. Validate panel and norm extents at the scan boundary and propagate packing overflow through callers.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@partychen

Copy link
Copy Markdown
Contributor Author

Mark Hildebrand (@hildebrandmw), I addressed your review in c1ae103. The updated benchmarks are in the description. Could you take another look?

Bind candidate rows and contiguous cutoffs in a validated selection view. Restore vector threshold rejection and sparse lane insertion while keeping every TopK width on the generic runtime-K path. Include cutoff storage in cache sizing and cover subview updates with a focused regression test.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 94eaf7c2-882d-46f4-8696-cf8e59e92702
Check the cutoff extent against the row count rounded up to the panel width before initializing selection state. Cover a partial panel with an undersized cutoff buffer.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks - this is moving in a good direction. I'm a bit worried, though, that the topk implementation makes too many infrastructure details pub(crate). Also, the contract for the compute entry point is validated with a lot of assertions with the necessary pre-conditions not really documented.

I think taking the point of view that matrix_kernels is like a mini-crate within diskann-quantization that only exposes what is absolutely necessary is generally a good idea to keep the interfaces focused and decoupled enough that we can still change the implementations.

Comment thread diskann-vector/src/topk.rs Resolved
juchen-ms (partychen) and others added 3 commits December 1, 2026 12:04
Move cache tiling into matrix-kernel blocks and distinguish global A-panel indices from B-row offsets.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Prepare padded query norms once, split IP and L2 entry points, and retain dimension checks at the micro-kernel boundary.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Move comparator-driven insertion into diskann-utils slices, keep PiPNN candidate storage private, and expose quantization's own result type.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
juchen-ms (partychen) added a commit that referenced this pull request Dec 2, 2026
…ible (#1618)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `34731cea319dc35a7c283365df3d1deb86d55c14`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 9/10 | ↑ 518 default-feature and 517
no-default-feature unit tests pass; workspace all-targets Clippy and
ARM64 Windows cross-check pass.<br>↓ Linux and ARM64 runtime behavior,
emulated ISA paths, and coverage were not validated locally. |
| Diagnosis confidence | 9/10 | ↑ Regression tests demonstrate valid
row-major views whose padded packing overflows; packing now returns
typed errors before row scratch allocation. |
| Evidence fit | 8/10 | ↑ Tests directly cover padded-extent overflow
and duplicated error-chain presentation.<br>↓ No production incident
trace was supplied. |
<!-- /copilot-assessment -->

<!--
Thanks for contributing a pull request! Please ensure you have taken a
look at
the contribution guidelines:
https://github.com/microsoft/DiskANN/blob/main/CONTRIBUTING.md
-->
- [x] Does this PR have a descriptive title that could go in our release
notes?
- [ ] Does this PR add any new dependencies?
- [x] Does this PR modify any existing APIs?
- [ ] Is the change to the API backwards compatible?
- [x] Should this result in any changes to our documentation, either
updating existing docs or adding new ones?

#### Reference Issues/PRs
<!--
Example: Fixes #1234. See also #3456.
Please use keywords (e.g., Fixes) to create link to the issues or pull
requests
you resolved, so that they will automatically be closed when your pull
request
is merged. See
https://github.com/blog/1506-closing-issues-via-pull-requests
-->
Relates to #1583. Extracts its fallible-constructor foundation without
TopK, traversal, SIMD, or ISA-dispatch refactors.

#### What does this implement/fix? Briefly explain your changes.

Replace panicking block-transposed constructors with `try_new`,
`try_from_strided`, and `try_from_matrix_view`. Propagate packing
overflow through MaxSim preparation, k-means initialization, product
training, and pivot construction, including widened query conversion.
Preserve same-layout cloning.

Expose a dedicated transparent `LloydsError`, document 16-row tail
padding and byte-budget overflow, and separate k-means++ selection
counts, packing context, and overflow details into nonduplicating
error-chain layers.

This intentionally changes constructor names and Lloyd's return type. No
dependencies are added. Two commits separate the constructor migration
from error-interface improvements.

#### Any other comments?

Validation on Windows x86-64:

- `cargo fmt --all --check` — passed.
- `cargo test -p diskann-quantization --lib --quiet` — passed, 518
tests.
- `cargo test -p diskann-quantization --no-default-features --lib
--quiet` — passed, 517 tests.
- `cargo test -p diskann-quantization --doc --quiet` — passed, 31 tests;
6 ignored.
- `cargo clippy --workspace --all-targets -- -D warnings` — passed.
- `cargo clippy -p diskann-quantization --all-targets --all-features --
-D warnings` — passed.
- `cargo check -p diskann-quantization --all-targets --all-features
--target aarch64-pc-windows-msvc --quiet` — passed (cross-compilation
only).
- With `RUSTDOCFLAGS='-D warnings -D rustdoc::all'`, `cargo doc -p
diskann-quantization --no-deps --all-features --document-private-items
--quiet` — passed.
- `git diff --check origin/main...HEAD` — passed.

Not run locally: full workspace tests, Linux tests, ARM64 runtime tests,
SDE baseline/AVX-512 emulation, and coverage collection.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
juchen-ms (partychen) and others added 3 commits December 2, 2026 09:59
Integrate microsoft#1618 and remove the foundation migration from the TopK diff.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Move packed f32 dot arithmetic out of MaxSim, decouple traversal sizes from cache parameters, and consume L2 norms locally. Separate distance conversion from selection updates and trim redundant comments.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks Junkui - this is really a step in the right direction! I think factoring out the joint traversal into blocks is the right move, and I especially like WithNorms.

I think there's still some work to be done on the kernel level. Right now, there's a lot of fluidity between dynamically sized slices and static extents with assertions in the middle. In some of these cases, I think the static extents could be encoded in types earlier to turn some of these asserts into compile time type signatures.

Another part I keep coming back to is the use of ExtraWide, but not necessarily as a full abstraction since it relies on knowing the exact associated types, when they should really be treated as opaque types.

One thought I had is that a lot of this awkwardness comes from offer_distances building its implementation from the ground-up and insisting on using the bitmask iterator.

While this is functionality that really should exist in diskann-wide, what if we tried an intermediate trait in the interim:

trait IntoMaskIter {
    type IntoIter: Iterator<Item = usize>,

    fn into_mask_iter(self) -> Self::IntoIter;
}

// This does what we're doing already with the bits.
#[derive(Debug)]
struct Ones(u64);

impl Iterator for Ones {
    type Item = usize;
    fn next(&mut self) -> Option<usize> {
        if self.0 == 0 {
            None
        } else {
            let next = self.0.trailing_zeros() as usize;
            self.0 &= self.0 - 1;
            Some(next)
        }
    }
}

// Stamp out implementations for the SIMD types of interest.

Then maybe using this as a trait bound would help simplify some of the generics? Like I said, the ability to construct an efficient iterator from a mask is really something that should live in diskann-wide, but that it a much bigger undertaking.

Note that this is just a suggestion - it might not actually help. I think there can be a bit clearer boundary between the SIMD code and the tiling. One possibility would be to take a page from unpacked::View to make an unpacked::ViewMut for the various tiling needs (and using ptr::Slice/ptr::MutSlice as needed). The panel visitors already return valid sub-regions and the indices for those regions. Those indices of the main A/B panels can be safely used to access sub-regions of the candidates/scores. More generally, I'd look at which access patterns occur and build small helpers to help encode those invariants. If done correctly, those helpers can be used to build other kernels as well.

Comment thread diskann-utils/src/slice.rs Resolved
Make insert_sorted non-panicking on empty slices without inner bounds checks, move PanelIndex/BandIndex into packed/unpacked visitors, make Params::new infallible, and replace dynamic slice assertions in TopK with static-width arrays and a TopKWide extension trait.
@partychen

Copy link
Copy Markdown
Contributor Author

Pushed e605a57 addressing this round of feedback.

A couple of notes on the optional ideas from the review summary:

  • Used a small Ones(u64) iterator for the bitmask scan, without adding an IntoMaskIter trait or changing diskann-wide yet.
  • Skipped adding unpacked::ViewMut for now. SelectionPanels wrapping rowmajor::Mut::subview_mut + Vec<[f32; MR]> already keeps panel rows and cutoffs together in one place, and TopK is the only caller so far.

Ready for another look whenever you have time.

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.

Add fused f32 TopK to the multi-vector kernel framework

5 participants