Repository navigation
Apply p square for TQ+ (dont use std+mean) - #8877
Conversation
91a51c6 to
e2a8177
Compare
6499ae1 to
4493cfe
Compare
| /// 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 { |
There was a problem hiding this comment.
Thats a conversation function between codebook position and quantile value
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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
Suggested reviewers
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
lib/quantization/tests/integration/test_tq.rs (1)
128-138: ⚡ Quick winPlease 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 oneTQMode::Pluscase withnum_threads > 1would 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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (6)
lib/quantization/Cargo.tomllib/quantization/src/p_square.rslib/quantization/src/quantile.rslib/quantization/src/turboquant/mod.rslib/quantization/tests/integration/test_tq.rslib/segment/src/vector_storage/quantized/quantized_vectors.rs
| return Ok(None); | ||
| } | ||
|
|
||
| // Auto-create path runs at segment-load time, with no `permit` |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
it's a placeholder for an empty appendable quantization. changed to 1 to make it more clear
| @@ -122,53 +339,237 @@ fn find_min_max_interval_per_coordinate<'a>( | |||
| } | |||
|
|
|||
| fn find_interval_per_coordinate_p2<'a>( | |||
There was a problem hiding this comment.
This function is currently only used in tests and benches. Is this intentional?
There was a problem hiding this comment.
removed completely, thanks!
| #[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, |
There was a problem hiding this comment.
I don't think we need the Send bound.
There was a problem hiding this comment.
You are right, it was an artefact after the first attempt at the parallel P2 estimator
4493cfe to
574e9fa
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (2)
lib/segment/src/vector_storage/quantized/quantized_vectors.rs (1)
990-1003:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftAvoid 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
NCPUworkers 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 winAlign the test reference with the selected arithmetic path.
update_desired_positions()only uses fused semantics onaarch64and onx86_64when bothavx2andfmaare available. This test always computesexpectedwithf64::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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (7)
lib/quantization/Cargo.tomllib/quantization/benches/p_square.rslib/quantization/src/p_square.rslib/quantization/src/quantile.rslib/quantization/src/turboquant/mod.rslib/quantization/tests/integration/test_tq.rslib/segment/src/vector_storage/quantized/quantized_vectors.rs
✅ Files skipped from review due to trivial changes (1)
- lib/quantization/Cargo.toml
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
lib/quantization/src/quantile.rslib/quantization/src/turboquant/mod.rs
63c7f05 to
c8ecff6
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
lib/quantization/benches/p_square.rslib/quantization/src/p_square.rslib/quantization/src/quantile.rslib/quantization/src/turboquant/mod.rslib/quantization/tests/integration/test_tq.rslib/segment/src/vector_storage/quantized/quantized_vectors.rs
* apply p square * review remarks and reduce ram * review remarks * clean tmp logs * review remarks * review remarks * trigger ci
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_outeris the outermost Lloyd-Max centroid magnitude for the chosenTQBits.Why: for ideally-N(0, 1) data the empirical quantile at
Φ(c_outer)equalsc_outer, so shift/scale collapse to(0, 1)and the codebook sees the designdistribution. 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 estimatorthat accepts an arbitrary odd marker count
N ≥ 5. DefaultN = 7: Bits4anchors on
p ≈ 0.997andN = 5markers don't track that tail accuratelyon small samples (failed the
recall_skewed_datatest). Includes SIMDfind_marker(NEON / AVX2) for the hot path; the extra two markers cost onlyin 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 + lengthrescale + f64→f32 narrowing) in-place into a pooled chunk buffer, feeds the
result into per-coord reservoirs concurrently. Drops the previous
ChunkedParallelRotateadapter — noVec<Vec<f32>>materialization, noper-vector clone, no per-vector f64 scratch.
TQBits::reservoir_size()— sizes the per-coord reservoir so that theabsolute σ 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.