Skip to content

PiPNN 1/6: add numerical kernels - #1287

Open
SeliMeli wants to merge 26 commits into
mainfrom
pipnn-stack/01-kernels
Open

PiPNN 1/6: add numerical kernels#1287
SeliMeli wants to merge 26 commits into
mainfrom
pipnn-stack/01-kernels

Conversation

@SeliMeli

@SeliMeli SeliMeli commented Jul 29, 2026

Copy link
Copy Markdown

PiPNN (Pick-in-Partitions Nearest Neighbors) builds ANN graph candidates with overlapping partitions and dense matrix work instead of running beam search against a partially built graph for every inserted point. This first layer adds the numerical kernels used by later PiPNN stages. It does not yet build or persist a graph.

PiPNN now lives under diskann::graph::pipnn; there is no separate implementation crate. This keeps graph construction beside DiskANN graph policy and lets later layers reuse crate-private graph internals without publishing them.

Concepts

  • A leader is a sampled point that names a child partition.
  • fanout is the number of nearest leaders retained for each point, creating overlapping child partitions.
  • A leaf is a bounded partition processed with one lower-triangular all-pairs dot-product matrix.
  • Leaf k is the number of local companions retained per point; it is construction policy, not final graph degree R.

Code map

  1. diskann-linalg::sgemm_aat_lower computes A · Aᵀ and writes only the lower triangle. Callers may leave the upper triangle uninitialized.
  2. diskann/src/graph/pipnn/kernel_metric.rs owns metric formulas, scale units, zero/NaN behavior, and runtime metric selection shared by both kernels.
  3. partition_kernel.rs converts point-by-leader dot products into sorted nearest leader IDs. Metric-specific scale handling happens before fixed-size top-k insertion.
  4. leaf_kernel.rs scans each strict-lower-triangle pair once and updates both endpoint top-k trackers. k <= 3 uses fixed-size insertion; larger k uses the dynamic fallback.
  5. diskann/tests/pipnn_{partition,leaf}_kernel.rs are public-interface differential tests with independent formulas. Private tests stay beside branch-heavy tracker and workspace seams.
  6. diskann/benches/bench_main_iai.rs is the single DiskANN IAI-Callgrind target. This layer registers partition and leaf kernel groups with instruction/cache regression limits.

End-to-end flow

Caller computes dense dot products → typed kernel input validates matrix/scales/output → diskann-wide selects the runtime architecture once → scalar/SIMD chunks convert dots to metric distances → stable top-k insertion writes caller-owned IDs/neighbors.

The kernels do not own providers, graph IDs, recursion, edge merging, thread pools, persistence, or search.

Invariants and boundaries

  • Matrix shapes, scale lengths, fanout, output widths, and usize area overflow are validated before dispatch.
  • Partition output contains leader-local u32 positions; leaf output contains leaf-local target positions.
  • Leaf traversal reads only the diagonal and strict lower triangle, updating each unordered pair exactly once.
  • Ties preserve encounter order. NaN candidates are non-rankable; finite f32::MAX remains rankable.
  • Cosine zero/subnormal norms produce zero similarity without erasing unrelated NaN behavior.
  • Scalar tails and dispatched chunks preserve the documented rounding/order contract.
  • PiPNN names no ISA, target feature, or raw architecture intrinsic; dispatch remains owned by diskann-wide.

Review path

  1. Start with kernel_metric.rs: metric formulas, scale kinds, zero thresholds, NaN handling, and scalar equivalents.
  2. Review PartitionKernel validation and tracker insertion, then compare scalar tails with SIMD chunks.
  3. Review LeafKernel lower-triangle traversal, dual-endpoint updates, fixed/dynamic top-k paths, and workspace reuse.
  4. Verify sgemm_aat_lower never touches the upper triangle.
  5. Finish with independent public differential tests around 4/8/16-lane and second-chunk boundaries.

Validation

  • 33 PiPNN kernel tests at this layer: 11 private seam tests plus 22 public-interface tests.
  • Differential coverage spans all four metrics, k/fanout paths, dimensions around lane boundaries, tails, ties, NaN, infinities, signed zero, zero/singleton/capacity inputs, and validation failures.
  • x86-64 baseline and AVX-512 SDE jobs explicitly enable diskann/pipnn; nightly feature/coverage jobs include the moved module.
  • AArch64 and Windows cross-target checks compile the feature.
  • IAI-Callgrind kernel scenarios run through cargo bench -p diskann --bench bench_main_iai --features pipnn,testing.

Stack relation

Stack 1/6. This layer supplies numerical selection. #1288 extracts crate-private shared RobustPrune; #1290 adds partition/leaf orchestration.

Stack 1/6 → #1288

@SeliMeli
SeliMeli requested review from a team and a lite review from Copilot July 29, 2026 11:51

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.

Pull request overview

This PR adds the first set of PiPNN “kernel” building blocks to the DiskANN Rust workspace: SIMD-accelerated top‑k selection for partition assignment and leaf neighbor selection, along with supporting SIMD division and a new lower-triangular A·Aᵀ helper in diskann-linalg.

Changes:

  • Add a new diskann-pipnn crate with partition_kernel and leaf_kernel implementations plus extensive correctness tests and Criterion benchmarks.
  • Extend diskann-wide to support Div on relevant f32 SIMD types (native, doubled, and scalar/emulated) and add a corresponding division test macro.
  • Add diskann_linalg::sgemm_aat_lower (lower-triangle-only AAT) and wire new crate/tests/CI/mutants exclusions into the workspace.

Reviewed changes

Copilot reviewed 26 out of 27 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
diskann-wide/src/test_utils/ops.rs Adds test_div! macro to validate lane-wise SIMD division correctness.
diskann-wide/src/emulated.rs Adds Div for scalar/emulated Emulated<f32, N, A> to support division in scalar dispatch.
diskann-wide/src/doubled.rs Adds Div for Doubled<T> to support composite SIMD widths.
diskann-wide/src/arch/x86_64/v4/f32x8_.rs Adds AVX Div op mapping + division tests.
diskann-wide/src/arch/x86_64/v4/f32x4_.rs Adds SSE Div op mapping + division tests.
diskann-wide/src/arch/x86_64/v4/f32x16_.rs Adds AVX-512 Div op mapping + division tests.
diskann-wide/src/arch/x86_64/v3/f32x8_.rs Adds AVX Div op mapping + division tests for V3.
diskann-wide/src/arch/x86_64/v3/f32x4_.rs Adds SSE Div op mapping + division tests for V3.
diskann-wide/src/arch/x86_64/v3/f32x16_.rs Adds division tests for the f32x16 V3 path (likely via doubled composition).
diskann-wide/src/arch/aarch64/f32x4_.rs Adds Neon Div op mapping + division tests.
diskann-wide/src/arch/aarch64/f32x2_.rs Adds Neon Div op mapping + division tests.
diskann-pipnn/tests/partition_kernel.rs New integration tests for partition top‑k dispatch correctness and edge cases.
diskann-pipnn/tests/leaf_kernel.rs New integration tests for leaf neighbor top‑k dispatch correctness and edge cases.
diskann-pipnn/src/partition_kernel/tests.rs New unit tests comparing scalar reference vs runtime dispatch and metric contracts.
diskann-pipnn/src/partition_kernel.rs New partition-assignment distance + top‑k kernel with validation and SIMD dispatch.
diskann-pipnn/src/lib.rs New crate root exporting PiPNN kernel modules.
diskann-pipnn/src/leaf_kernel/tests.rs New unit tests for scalar reference parity and workspace behavior.
diskann-pipnn/src/leaf_kernel.rs New fused lower-triangle leaf neighbor kernel with SIMD dispatch and workspace support.
diskann-pipnn/Cargo.toml Defines new diskann-pipnn crate, dev-deps, and benches.
diskann-pipnn/benches/kernels.rs Adds benchmarks for partition top‑k, lower AAT, leaf top‑k, and full leaf workflow.
diskann-linalg/tests/sgemm_aat_lower.rs New tests for lower-triangle AAT behavior and validation errors.
diskann-linalg/src/lib.rs Adds public sgemm_aat_lower API with dimension checks.
diskann-linalg/src/faer.rs Implements sgemm_aat_lower_impl using Faer triangular matmul.
Cargo.toml Adds diskann-pipnn to workspace members and workspace dependencies.
Cargo.lock Records the new diskann-pipnn package entry.
.github/workflows/ci.yml Adds diskann-pipnn to CI test package lists.
.cargo/mutants.toml Adds mutation-test exclusions for kernel code paths and equivalent transformations.
Comments suppressed due to low confidence (2)

diskann-pipnn/src/leaf_kernel.rs:651

  • Same issue as the L2 arm: using max_simd for lower clamping can erase NaNs on the Scalar/Emulated backend, making NaN distances rankable. Clamp with lt_simd + select to preserve NaNs consistently.
        Metric::CosineNormalized => {
            let distance = F::splat(arch, 1.0) - dot;
            zero.max_simd(distance)
        }

diskann-pipnn/src/leaf_kernel.rs:664

  • The cosine path also uses zero.max_simd(distance) for clamping, which can collapse NaNs to zero on the Scalar/Emulated backend (via f32::max). That contradicts the comment about preserving non-rankable NaNs and can change output ordering. Prefer an lt_simd + select clamp here as well.
            let distance = one - cosine;
            // Comparisons with NaN are false, so this explicit lower clamp
            // preserves non-rankable NaNs while matching the existing PiPNN
            // distance formulas for finite values.
            zero.max_simd(distance)

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel/tests.rs Outdated
@SeliMeli SeliMeli changed the title Pipnn stack/01 kernels PiPNN 1/6: add numerical kernels Jul 29, 2026
Copilot AI review requested due to automatic review settings July 30, 2026 08:26
@SeliMeli
SeliMeli force-pushed the pipnn-stack/01-kernels branch from e204cb9 to b046174 Compare July 30, 2026 08:26

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.

Pull request overview

Copilot reviewed 26 out of 27 changed files in this pull request and generated no new comments.

@codecov-commenter

codecov-commenter commented Jul 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.97938% with 39 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.46%. Comparing base (59dd048) to head (e265ecb).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
diskann/src/graph/pipnn/partition_kernel.rs 91.13% 29 Missing ⚠️
diskann/src/graph/pipnn/leaf_kernel.rs 97.90% 9 Missing ⚠️
diskann/src/graph/pipnn/kernel_metric.rs 99.30% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1287      +/-   ##
==========================================
- Coverage   90.59%   90.46%   -0.14%     
==========================================
  Files         513      547      +34     
  Lines       99091   106211    +7120     
==========================================
+ Hits        89775    96086    +6311     
- Misses       9316    10125     +809     
Flag Coverage Δ
miri 90.46% <95.97%> (-0.14%) ⬇️
unittests 90.16% <95.97%> (-0.12%) ⬇️

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

Files with missing lines Coverage Δ
diskann-linalg/src/faer.rs 100.00% <100.00%> (ø)
diskann-linalg/src/lib.rs 99.68% <100.00%> (+1.18%) ⬆️
diskann-wide/src/arch/x86_64/v3/f32x16_.rs 100.00% <ø> (ø)
diskann-wide/src/arch/x86_64/v3/f32x4_.rs 100.00% <ø> (ø)
diskann-wide/src/arch/x86_64/v3/f32x8_.rs 100.00% <ø> (ø)
diskann-wide/src/arch/x86_64/v4/f32x16_.rs 14.11% <ø> (ø)
diskann-wide/src/arch/x86_64/v4/f32x4_.rs 16.90% <ø> (ø)
diskann-wide/src/arch/x86_64/v4/f32x8_.rs 16.90% <ø> (ø)
diskann-wide/src/doubled.rs 86.89% <100.00%> (+0.17%) ⬆️
diskann-wide/src/emulated.rs 98.31% <100.00%> (+0.01%) ⬆️
... and 5 more

... and 304 files with indirect coverage changes

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

Copilot AI review requested due to automatic review settings July 30, 2026 08:55

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.

Pull request overview

Copilot reviewed 26 out of 27 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (2)

diskann-pipnn/src/partition_kernel/tests.rs:20

  • The PartitionTopK contract for Metric::L2 expects leader_scales to contain squared leader norms (see docs and distance(Metric::L2, ..) test). This helper currently populates unsquared norms, which makes the test data inconsistent with the public API contract and could hide contract-related bugs.
    let leader_scales = match metric {
        Metric::L2 => (0..leaders).map(|leader| (leader + 1) as f32).collect(),
        Metric::Cosine => (0..leaders)
            .map(|leader| {

diskann-pipnn/src/partition_kernel.rs:61

  • InvalidFanout’s error message says the maximum is {maximum}, but validation also rejects fanout > leaders. When leaders < maximum this message is misleading (it implies the only limit is {maximum}). Consider spelling out both constraints in the message so callers immediately see why it failed.
    #[error("invalid fanout {fanout} for {leaders} leaders; maximum is {maximum}")]

Copilot AI review requested due to automatic review settings July 31, 2026 04:24
@SeliMeli
SeliMeli force-pushed the pipnn-stack/01-kernels branch from 8fb4e92 to 20ab8a0 Compare July 31, 2026 04:24

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated no new comments.

Suppressed comments (1)

diskann-pipnn/src/partition_kernel.rs:294

  • For Metric::Cosine, NaN norms currently produce a finite distance (1.0) because denominator.gt_simd(0) is false for NaN, so the lane falls back to cosine = 0. That makes NaN-derived pairs/leaders “rankable”, which contradicts the module’s stated NaN-rejection behavior and differs from diskann-vector cosine semantics (NaN norms propagate to a NaN similarity/distance). Consider explicitly preserving NaN denominators so the resulting distance stays NaN and is ignored by insert_topk.
        let denominator = row_norm * leader_norm;
        let valid = denominator.gt_simd(zero);
        let safe_denominator = valid.select(denominator, one);
        let cosine = valid.select(dot / safe_denominator, zero);
        one - cosine

Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann/src/graph/pipnn/partition_kernel.rs
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated
Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated

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

Nice work overall. I found one correctness issue in the cosine handling that should be resolved before merge. The remaining comments are mostly about reducing duplicated or unsafe code and tightening the API contracts.

Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated
Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
check_length("leader scales", input.leader_scales.len(), leader_scales)
}

fn checked_area(

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.

checked_area, check_length, ShapeOverflow and InvalidBufferLength are duplicated character-for-character with leaf_kernel. Small enough to shrug at now, but with four more PRs coming it's probably worth a src/shape.rs with a shared ShapeError that each kernel error wraps via #[from].

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I kept the two tiny checked-area/length adapters local because they construct different public kernel error types and sit immediately before each module's unsafe accesses. MatrixView adoption removed the other duplicated shape state; introducing a shared wrapped error would enlarge the public error interface for two call sites.

Comment thread diskann-pipnn/src/leaf_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann-pipnn/src/partition_kernel.rs Outdated
Comment thread diskann-linalg/src/lib.rs Outdated
Comment thread diskann-wide/src/emulated.rs

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings August 3, 2026 11:33

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings August 3, 2026 11:39

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated no new comments.

Suppressed comments (1)

.github/workflows/nightly.yml:23

  • DISKANN_FEATURES is defined as a folded scalar with commas at line ends. YAML folding inserts spaces at line breaks, producing a value like tracing, experimental_diversity_search,... which can be parsed as having empty/whitespace-prefixed feature names depending on Cargo’s splitting rules. This is brittle and can break the cargo ... --features "${{ env.DISKANN_FEATURES }}" steps.
  DISKANN_FEATURES: >-
    virtual_storage,spherical-quantization,product-quantization,tracing,
    experimental_diversity_search,disk-index,flatbuffers,linalg,codegen,
    multi-vector,bftree,inmem2,integration-test

Use output columns as the sole leaf-specific neighbor count and reserve row/column terminology for matrix shapes.

BREAKING CHANGE: LeafKernel::new no longer takes k, nearest_neighbors returns (), and kernel input/neighbor/error fields use source-target and point-leader names.
Copilot AI review requested due to automatic review settings August 3, 2026 16:57

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated no new comments.

Suppressed comments (1)

diskann-pipnn/src/leaf_kernel.rs:467

  • The comment claims no output or scratch mutation occurs on error, but after validate(...) the call to prepare_workspace(...) can return LeafKernelError::Allocation after partially resizing/filling workspace.norms (before workspace.worst is reserved). This makes the comment/documentation inaccurate and could mislead callers relying on workspace immutability on error.
        // Validation establishes every shape and active-prefix invariant used by
        // unchecked loads below. No output or scratch mutation occurs on error.
        validate(call.input, &call.output)?;

@partychen

Copy link
Copy Markdown
Contributor

I went through the full PiPANN implementation, and it appears to be entirely in-memory. How does it handle datasets that cannot fit into memory?

One possible out-of-core approach would be to stream the input, load vectors only when processing each leaf partition, compute distances locally, and then stitch the partial graphs into the final graph. However, this would introduce additional I/O and graph-merging overhead.

Do we have experimental results for datasets large enough that loading all vectors into memory is infeasible? It would be helpful to understand the memory–build-time tradeoff and whether out-of-core construction has been evaluated.

Keep PiPNN beside graph policy so later layers can reuse private RobustPrune state without publishing it across a crate boundary. Preserve independent kernel oracles while removing duplicate formula-sharing differential wrappers.

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.

Pull request overview

Copilot reviewed 28 out of 29 changed files in this pull request and generated no new comments.

Suppressed comments (2)

diskann/benches/benchmarks_iai/pipnn_kernels.rs:34

  • PartitionScales::L2 requires squared leader norms, but this benchmark fixture fills leader_squared_norms with unsquared values (1.0 + leader/LEADERS). That makes the benchmark exercise a different scoring formula than the real kernel contract (and can skew perf/regression tracking if the score distribution changes).

Compute actual squared norms here (or rename+document if you intentionally want non-norm values, but that would violate PartitionScales::L2’s stated units).

    let leader_squared_norms = (0..LEADERS)
        .map(|leader| 1.0 + leader as f32 / LEADERS as f32)
        .collect();

diskann/benches/benchmarks_iai/pipnn_kernels.rs:91

  • setup_leaf sizes output using neighbors = leaf_neighbor_count(LEAF_POINTS, LEAF_K), but select_leaf_neighbors creates the output view with LEAF_K columns instead of the computed neighbors. This works only as long as LEAF_K <= LEAF_POINTS - 1; if the constants change (or if you copy this pattern elsewhere with small leaves), it will panic at runtime due to a shape/len mismatch.

Use the effective neighbor count when constructing the output view to keep the fixture consistent with the kernel API.

            LeafInput {
                dots: MatrixView::try_from(dots.as_slice(), LEAF_POINTS, LEAF_POINTS).unwrap(),
            },
            MutMatrixView::try_from(output.as_mut_slice(), LEAF_POINTS, LEAF_K).unwrap(),
            &mut workspace,

Copilot AI review requested due to automatic review settings August 5, 2026 09:56

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.

Pull request overview

Copilot reviewed 28 out of 29 changed files in this pull request and generated 1 comment.

Suppressed comments (2)

.github/workflows/ci.yml:422

  • Same issue as above: --features diskann/pipnn is not a valid Cargo feature flag and will cause the SDE AVX-512 test job to error before running tests. Switch to --features pipnn.
          cargo test --locked \
            --package diskann-wide \
            --package diskann-vector \
            --package diskann-quantization \
            --package diskann \
            --features diskann/pipnn \
            -- --skip compile_tests

diskann/benches/benchmarks_iai/pipnn_kernels.rs:88

  • The output buffer is allocated using neighbors = leaf_neighbor_count(LEAF_POINTS, LEAF_K), but the view passed to nearest_neighbors uses LEAF_K directly. This is only correct while LEAF_K <= LEAF_POINTS - 1; if the constants change (or this benchmark is copied with a larger K), the view shape will no longer match the allocation and will panic/fail validation. Use neighbors (or recompute it) consistently for the output-column count.
        .nearest_neighbors(
            LeafInput {
                dots: MatrixView::try_from(dots.as_slice(), LEAF_POINTS, LEAF_POINTS).unwrap(),
            },
            MutMatrixView::try_from(output.as_mut_slice(), LEAF_POINTS, LEAF_K).unwrap(),
            &mut workspace,

Comment thread .github/workflows/ci.yml
Comment on lines 354 to 360
cargo test --locked \
--package diskann-wide \
--package diskann-vector \
--package diskann-quantization \
--package diskann \
--features diskann/pipnn \
-- --skip compile_tests \
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.

6 participants