Skip to content

Apply p square for TQ+ (dont use std+mean) - #8877

Merged
IvanPleshkov merged 7 commits into
devfrom
apply-p-square
May 6, 2026
Merged

IvanPleshkov merged 7 commits into
devfrom
apply-p-square

Conversation

@IvanPleshkov

@IvanPleshkov IvanPleshkov commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Replaces the TQ+ mean/stddev pre-pass with a quantile-anchored fit, and rebuilds
the pre-pass on a fused parallel P² estimator.

Fit change (turboquant/mod.rs)

Before: per-coord shift = −mean, scale = 1/stddev.
After: per-coord shift = −(q_lo + q_hi) / 2, scale = 2·c_outer / (q_hi − q_lo),
where (q_lo, q_hi) are the empirical quantiles at probabilities Φ(±c_outer)
and c_outer is the outermost Lloyd-Max centroid magnitude for the chosen
TQBits.

Why: for ideally-N(0, 1) data the empirical quantile at Φ(c_outer) equals
c_outer, so shift/scale collapse to (0, 1) and the codebook sees the design
distribution. On anisotropic / heavy-tailed coords, anchoring on tail quantiles
avoids the bias of mean/stddev where outliers dominate the variance estimate.

Pre-pass machinery

  • p_square.rs — extended Jain & Chlamtac (1985) P² one-quantile estimator
    that accepts an arbitrary odd marker count N ≥ 5. Default N = 7: Bits4
    anchors on p ≈ 0.997 and N = 5 markers don't track that tail accurately
    on small samples (failed the recall_skewed_data test). Includes SIMD
    find_marker (NEON / AVX2) for the hot path; the extra two markers cost only
    in the per-coord finalize, which is parallel across coords.
  • quantile.rs::find_quantile_interval_per_coordinate_with_preprocess —
    fused producer/consumer pipeline: pulls raw vectors straight from the input
    iterator, runs caller-supplied preprocess (Hadamard rotation + length
    rescale + f64→f32 narrowing) in-place into a pooled chunk buffer, feeds the
    result into per-coord reservoirs concurrently. Drops the previous
    ChunkedParallelRotate adapter — no Vec<Vec<f32>> materialization, no
    per-vector clone, no per-vector f64 scratch.
  • TQBits::reservoir_size() — sizes the per-coord reservoir so that the
    absolute σ of the order-statistic estimator stays roughly flat
    (~0.03–0.06 in N(0, 1) units) across codebooks: 2048 for Bits1/Bits1_5,
    4096 for Bits2, 8192 for Bits4.

@IvanPleshkov IvanPleshkov added this to the TurboQuant milestone May 3, 2026
@IvanPleshkov
IvanPleshkov changed the base branch from master to dev May 3, 2026 17:00
@IvanPleshkov
IvanPleshkov force-pushed the apply-p-square branch 2 times, most recently from 91a51c6 to e2a8177 Compare May 4, 2026 20:30
@IvanPleshkov
IvanPleshkov force-pushed the apply-p-square branch 3 times, most recently from 6499ae1 to 4493cfe Compare May 4, 2026 22:21
/// Standard normal CDF Φ(x) = (1 + erf(x/√2)) / 2 via the Abramowitz & Stegun
/// 7.1.26 rational approximation (max error ≈ 1.5e-7). Used once per encode to
/// turn `c_outer` into the symmetric quantile probability for the TQ+ pre-pass.
fn phi(x: f64) -> f64 {

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.

Thats a conversation function between codebook position and quantile value

@IvanPleshkov
IvanPleshkov requested a review from JojiiOfficial May 5, 2026 00:12
@IvanPleshkov
IvanPleshkov marked this pull request as ready for review May 5, 2026 06:28
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR refactors the P-square quantile estimator from an array-of-structures (Marker) layout to a struct-of-arrays (heights, n_positions, n_desired, target_probabilities) and replaces per-marker logic with array-based operations. It adds SIMD-accelerated routines (NEON, AVX2) for marker search and desired-position updates with scalar fallbacks and parity tests. A new public API, find_quantile_interval_per_coordinate_with_preprocess, streams preprocessed vectors into per-coordinate P2 estimators. TurboQuant encoding now uses a quantile-interval pre-pass (driven by a new phi() normal-CDF helper) to derive per-coordinate shift/scale instead of mean/stddev statistics. EncodedVectorsTQ::encode gained count and num_threads parameters, and threading is propagated through quantized vector creation paths. Tests and benches updated accordingly.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • qdrant/qdrant#8788: Touches TurboQuant integration tests and EncodedVectorsTQ::encode call sites similarly updated here.
  • Empty turbo quant #8677: Modifies the turboquant module and EncodedVectorsTQ::encode API; closely related to the new quantile pre-pass and signature changes.
  • TQ variant for QuantizedVectorStorage #8678: Adjusts TurboQuant integration and quantized vector creation paths that now propagate max_threads/num_threads as in this PR.

Suggested reviewers

  • JojiiOfficial
  • dancixx
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main objective of replacing the mean/stddev-based pre-pass with a quantile-anchored approach using the P² algorithm for TQ+ encoding.
Description check ✅ Passed The description comprehensively explains the fit change, pre-pass machinery improvements, and API modifications related to implementing quantile-based P² estimation for TQ+.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch apply-p-square

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
lib/quantization/tests/integration/test_tq.rs (1)

128-138: ⚡ Quick win

Please exercise the threaded TQ+ pre-pass in at least one integration case.

Every updated call site hard-codes num_threads = 1, so the new parallel reservoir/rayon path never runs under integration coverage. Adding one TQMode::Plus case with num_threads > 1 would catch races and nondeterministic regressions in the new hot path before merge.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/quantization/tests/integration/test_tq.rs` around lines 128 - 138, Update
the integration test to exercise the threaded TQ+ pre-pass by adding at least
one case that uses TQMode::Plus and sets the num_threads argument to >1 when
calling EncodedVectorsTQ::encode (replace the hard-coded 1 currently passed for
num_threads). Locate the call sites in test_tq.rs that invoke
EncodedVectorsTQ::encode (using variables like vector_data, vector_parameters,
VECTORS_COUNT, bits, mode) and add a test variant or parameterized loop that
sets mode = TQMode::Plus and num_threads = 2 (or more) so the parallel
reservoir/rayon path runs; keep other args (e.g., TestEncodedStorageBuilder,
AtomicBool abort flag) as appropriate for the integration scenario.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/quantization/src/p_square.rs`:
- Around line 534-559: The test test_update_desired_positions_simd_parity is
asserting bitwise equality even though the SIMD path uses fused multiply-add and
can legitimately differ; modify the test in lib/quantization/src/p_square.rs to
compare got against expected using a floating-point tolerant check instead of
assert_eq!: compute the reference with f64::mul_add (or compare with allowable
epsilon/ULP) for each element and assert that |got[i] - reference[i]| <=
small_tol (or within N ulps), referencing the test function name
test_update_desired_positions_simd_parity and the function under test
update_desired_positions::<7> to locate and update the assertion logic.

In `@lib/quantization/src/quantile.rs`:
- Around line 268-297: Thread the cancellation flag `stopped` (e.g. an
Arc<AtomicBool>) into both parallel phases so work can abort: capture `stopped`
in the pool.install closures used for sample preprocessing (the for_each_init
closure over sample_buf/par_chunks_mut that calls `preprocess`) and in the
per-coordinate `into_par_iter().map(...)` closure that constructs `P2Quantile`
and loops over `actual_sample`; inside each closure check `stopped.load(...)`
periodically (before expensive work or each loop iteration) and return early
with a cancel-style error (e.g. `Err(EncodingError::Cancelled)`) so the outer
`collect::<Result<_, _>>()?` or function caller short-circuits; ensure the
preprocessing closure similarly skips/returns on cancel so the whole phase
becomes interruptible.

---

Nitpick comments:
In `@lib/quantization/tests/integration/test_tq.rs`:
- Around line 128-138: Update the integration test to exercise the threaded TQ+
pre-pass by adding at least one case that uses TQMode::Plus and sets the
num_threads argument to >1 when calling EncodedVectorsTQ::encode (replace the
hard-coded 1 currently passed for num_threads). Locate the call sites in
test_tq.rs that invoke EncodedVectorsTQ::encode (using variables like
vector_data, vector_parameters, VECTORS_COUNT, bits, mode) and add a test
variant or parameterized loop that sets mode = TQMode::Plus and num_threads = 2
(or more) so the parallel reservoir/rayon path runs; keep other args (e.g.,
TestEncodedStorageBuilder, AtomicBool abort flag) as appropriate for the
integration scenario.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6b8efa94-ac36-4063-aeee-7662b3d60618

📥 Commits

Reviewing files that changed from the base of the PR and between cb34d95 and 4493cfe.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • lib/quantization/Cargo.toml
  • lib/quantization/src/p_square.rs
  • lib/quantization/src/quantile.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/tests/integration/test_tq.rs
  • lib/segment/src/vector_storage/quantized/quantized_vectors.rs

Comment thread lib/quantization/src/p_square.rs Resolved
Comment thread lib/quantization/src/quantile.rs Resolved
return Ok(None);
}

// Auto-create path runs at segment-load time, with no `permit`

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.

Shouldn't we bound also the thread-budget to either a config value or some cpu_permit?
I don't think a thread-budget of max-cpus is the right approach

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.

it's a placeholder for an empty appendable quantization. changed to 1 to make it more clear

Comment thread lib/quantization/src/quantile.rs Outdated
@@ -122,53 +339,237 @@ fn find_min_max_interval_per_coordinate<'a>(
}

fn find_interval_per_coordinate_p2<'a>(

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.

This function is currently only used in tests and benches. Is this intentional?

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.

removed completely, thanks!

Comment thread lib/quantization/src/turboquant/mod.rs Outdated
#[allow(clippy::too_many_arguments)]
pub fn encode<'a>(
data: impl Iterator<Item = impl AsRef<[f32]> + 'a> + Clone,
data: impl Iterator<Item = impl AsRef<[f32]> + 'a> + Clone + Send + 'a,

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.

I don't think we need the Send bound.

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.

You are right, it was an artefact after the first attempt at the parallel P2 estimator

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.

fixed

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

♻️ Duplicate comments (2)
lib/segment/src/vector_storage/quantized/quantized_vectors.rs (1)

990-1003: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Avoid defaulting appendable auto-create to get_num_cpus().

The new TQ+ pre-pass builds a private Rayon pool per encode, so this is not capped by Rayon’s global pool. If several segments auto-create quantization concurrently, each one can spawn NCPU workers and multiply the thread count. Please keep this path on a permit- or config-derived budget instead of the machine-wide CPU count.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/vector_storage/quantized/quantized_vectors.rs` around lines
990 - 1003, The code sets max_threads := common::cpu::get_num_cpus() before
calling Self::create(..., max_threads, ...) which can spawn many Rayon pools;
instead derive the thread budget from the provided permit or quantization
configuration (e.g. use a permit-derived limit or a field like
quantization_config.thread_budget) and only fall back to a small constant (e.g.
1 or a config default) when no permit/config is present; update the max_threads
assignment and the call site (the Self::create invocation) to use that
permit/config-derived value so auto-create does not default to host CPU count.
lib/quantization/src/p_square.rs (1)

534-557: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align the test reference with the selected arithmetic path.

update_desired_positions() only uses fused semantics on aarch64 and on x86_64 when both avx2 and fma are available. This test always computes expected with f64::mul_add, so it can fail spuriously on non-FMA paths even when the implementation is correct. Please gate the reference on the same feature selection, or relax this to a tolerant comparison instead of bitwise equality.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/quantization/src/p_square.rs` around lines 534 - 557, The test
test_update_desired_positions_simd_parity compares the implementation output
from update_desired_positions against an expected value computed with
f64::mul_add unconditionally, which is only valid when fused multiply-add is
actually used on the target; change the test so the reference path matches the
same feature selection (use cfg checks for aarch64 OR x86_64 with avx2+fma) and
only compute expected with f64::mul_add when that condition holds, otherwise
compute expected with plain 1.0 + a * b or perform an approximate comparison
(e.g., relative/absolute epsilon) between got and expected; update the test
function test_update_desired_positions_simd_parity to branch on the feature
predicate and/or use a tolerant assertion when not on an FMA path.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@lib/quantization/src/p_square.rs`:
- Around line 534-557: The test test_update_desired_positions_simd_parity
compares the implementation output from update_desired_positions against an
expected value computed with f64::mul_add unconditionally, which is only valid
when fused multiply-add is actually used on the target; change the test so the
reference path matches the same feature selection (use cfg checks for aarch64 OR
x86_64 with avx2+fma) and only compute expected with f64::mul_add when that
condition holds, otherwise compute expected with plain 1.0 + a * b or perform an
approximate comparison (e.g., relative/absolute epsilon) between got and
expected; update the test function test_update_desired_positions_simd_parity to
branch on the feature predicate and/or use a tolerant assertion when not on an
FMA path.

In `@lib/segment/src/vector_storage/quantized/quantized_vectors.rs`:
- Around line 990-1003: The code sets max_threads := common::cpu::get_num_cpus()
before calling Self::create(..., max_threads, ...) which can spawn many Rayon
pools; instead derive the thread budget from the provided permit or quantization
configuration (e.g. use a permit-derived limit or a field like
quantization_config.thread_budget) and only fall back to a small constant (e.g.
1 or a config default) when no permit/config is present; update the max_threads
assignment and the call site (the Self::create invocation) to use that
permit/config-derived value so auto-create does not default to host CPU count.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1dda4d97-5dec-4eb7-8af3-f645502a8516

📥 Commits

Reviewing files that changed from the base of the PR and between 4493cfe and 574e9fa.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • lib/quantization/Cargo.toml
  • lib/quantization/benches/p_square.rs
  • lib/quantization/src/p_square.rs
  • lib/quantization/src/quantile.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/tests/integration/test_tq.rs
  • lib/segment/src/vector_storage/quantized/quantized_vectors.rs
✅ Files skipped from review due to trivial changes (1)
  • lib/quantization/Cargo.toml

@IvanPleshkov
IvanPleshkov requested a review from JojiiOfficial May 5, 2026 20:32

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/quantization/src/turboquant/mod.rs`:
- Around line 269-277: The loop that computes shift[i] and scale[i] uses
f32::EPSILON to decide if denom = q_hi - q_lo is valid, which is too small and
lets tiny widths produce huge scales; change this to guard with a practical
minimum width constant (e.g. MIN_INTERVAL_WIDTH) or equivalently cap the
computed scale to a MAX_SCALE before storing into scale[i]; update the branch
that checks denom (used with intervals, shift, scale, c_outer) to treat denom <
MIN_INTERVAL_WIDTH as "nearly constant" (set scale[i]=0 or skip EC for that
axis) and when denom >= MIN_INTERVAL_WIDTH compute scale but clamp it with
MIN(scale, MAX_SCALE) to avoid explosion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e0de8a6b-3f00-40a7-9fda-b46ce3fde721

📥 Commits

Reviewing files that changed from the base of the PR and between 86e0306 and 63c7f05.

📒 Files selected for processing (2)
  • lib/quantization/src/quantile.rs
  • lib/quantization/src/turboquant/mod.rs

Comment thread lib/quantization/src/turboquant/mod.rs Resolved

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/quantization/src/p_square.rs`:
- Around line 547-557: The parity test computes expected values using mul_add()
but update_desired_positions::<7>() may dispatch to update_desired_scalar()
(which uses separate add/mul with different rounding), causing false failures;
change the test to branch the expected computation the same way
update_desired_positions does (i.e., call the same scalar fallback path when
update_desired_positions would use update_desired_scalar()), or accept either
result by computing both variants: fused = mul_add(tp[i], count_minus_one, 1.0)
and scalar = 1.0 + tp[i] * count_minus_one and compare got to either fused or
scalar; reference update_desired_positions::<7>(), update_desired_scalar(), and
mul_add in your changes so the test mirrors the implementation path.

In `@lib/quantization/src/quantile.rs`:
- Around line 240-243: Replace the debug-only check with a real runtime
validation: instead of debug_assert_eq!(v_ref.len(), raw_dim, ...), add an
explicit if v_ref.len() != raw_dim { return Err(...) } (or panic! with a clear
message if this function is not fallible) before computing row and calling
preprocess so you never leave parts of batch_scratch uninitialized; reference
the variables v_ref, raw_dim, padded_dim, batch_scratch, filled and the call to
preprocess to locate the spot to change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8971de47-e3ba-4924-b83c-90fa79d709a1

📥 Commits

Reviewing files that changed from the base of the PR and between 63c7f05 and 3602674.

📒 Files selected for processing (6)
  • lib/quantization/benches/p_square.rs
  • lib/quantization/src/p_square.rs
  • lib/quantization/src/quantile.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/tests/integration/test_tq.rs
  • lib/segment/src/vector_storage/quantized/quantized_vectors.rs

Comment thread lib/quantization/src/p_square.rs Resolved
Comment thread lib/quantization/src/quantile.rs Resolved
@IvanPleshkov IvanPleshkov mentioned this pull request May 5, 2026
63 of 69 tasks
@IvanPleshkov
IvanPleshkov merged commit 665b91d into dev May 6, 2026
15 checks passed
@IvanPleshkov
IvanPleshkov deleted the apply-p-square branch May 6, 2026 07:36
@coderabbitai coderabbitai Bot mentioned this pull request May 7, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
* apply p square

* review remarks and reduce ram

* review remarks

* clean tmp logs

* review remarks

* review remarks

* trigger ci
@coderabbitai coderabbitai Bot mentioned this pull request May 18, 2026
8 tasks done
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.

2 participants