Repository navigation
Refactor TQ before SIMD integration - #8783
Conversation
|
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:
📝 WalkthroughWalkthroughThe PR introduces a padded dimension concept used across turboquant: Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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)
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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
lib/quantization/src/turboquant/encoding.rs (2)
136-150:⚠️ Potential issue | 🟡 Minor
pack_extras_intocomputes the wrong length; rename/fix to useTqVectorExtras::size_for.
extra_lenhere is derived fromquantized_size_for, which returns the full quantized size (vector data + extras), not the extras size. As a result:
- The
if extra_len == 0 { return; }guard at line 140 is effectively unreachable —vector_data_sizeis always nonzero, so the function proceeds even for distance variants with zero extras (currentlyCosine). It happens to be a no-op today becauseextras.l2_lengthisNoneforCosine, but the intent is no longer expressed.buf.reserve(extra_len)over-allocates by the size of the vector data.Use
TqVectorExtras::size_for(...)here, mirroring the symmetricunpack_extras_fromside (line 158).♻️ Proposed fix
- fn pack_extras_into(&self, extras: &TqVectorExtras, buf: &mut Vec<u8>) { - let extra_len = - Self::quantized_size_for(self.padded_dim, self.bits, self.distance, self.mode); - - if extra_len == 0 { - return; - } - - buf.reserve(extra_len); + fn pack_extras_into(&self, extras: &TqVectorExtras, buf: &mut Vec<u8>) { + let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode); + + if extra_len == 0 { + return; + } + + buf.reserve(extra_len);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/encoding.rs` around lines 136 - 150, pack_extras_into currently computes extra_len with Self::quantized_size_for (full quantized size) causing an unreachable zero-check and over-reservation; change it to call TqVectorExtras::size_for(self.padded_dim, self.bits, self.distance, self.mode) so extra_len represents only extras, keep the early return if extras size is zero, and call buf.reserve(extra_len) with that value; mirror the logic used by unpack_extras_from and ensure you still conditionally extend buf with extras.l2_length as before.
93-115:⚠️ Potential issue | 🟡 MinorPassing
self.padded_dimintoquantized_size_fordouble-pads the dimension.
quantized_size_fortreats its first argument as the raw (unpadded) dim and computesSelf::padded_dim(dim, bits)internally (line 102). The callers at line 88 and line 138 passself.padded_dim, so padding is applied twice. ForBits1/Bits2/Bits4,padded_dimhappens to be idempotent (since the already-padded value is still a multiple of the target), so this is currently harmless. ForBits1_5, however, it is not idempotent — e.g.padded_dim(10, Bits1_5) = 16, butpadded_dim(16, Bits1_5) = 24— so any future wiring up ofBits1_5would silently produce the wrong size here.Consider either making the helper take an already-padded
dimand dropping the innerSelf::padded_dim(..)call, or keeping the inner padding and passing the raw dim (which would require storing it onTurboQuantizer).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/encoding.rs` around lines 93 - 115, quantized_size_for currently double-pads the dimension because callers already pass self.padded_dim while the function calls Self::padded_dim(dim, bits) again; change quantized_size_for(dim, bits, distance, mode) to treat its dim parameter as already-padded (remove the internal Self::padded_dim(...) call and compute vector_data_size using dim directly) and update its comment to reflect that it expects a padded dim; keep callers that pass self.padded_dim as-is (no other logic changes needed) and ensure TQBits::Bits1_5 no longer gets double-padded.lib/quantization/src/turboquant/mod.rs (1)
162-169:⚠️ Potential issue | 🔴 Critical
encoding_buffermust be sized topadded_dim, notdim.The
encoding_bufferfed toTurboQuantizer::quantizeinupsert_vector(line 283) needs to be as large aspadded_dim—quantizezero-pads it pastvec.len()and then callsself.rotation.apply(buf)against aHadamardRotationthat was constructed withpadded_dim. Ifdim < padded_dim(any non-aligned dim, e.g.dim = 127withBits1, ordim = 300withBits1), this buffer is too short and the rotation/packing will go wrong (or panic on the assertion against the rotation's configured dim).The
encodepath already does this correctly at line 121 (vec![0.0f64; quantizer.padded_dim]). The stored buffer in both theencodeconstructor (line 167) andload(line 183) needs the same treatment. This also makeslet dim = …at line 177 unused.🐛 Proposed fix
Ok(Self { encoded_vectors, metadata, metadata_path: meta_path.map(PathBuf::from), + encoding_buffer: vec![0.0f64; quantizer.padded_dim], quantizer, - encoding_buffer: vec![0.0f64; dim], }) }let quantizer = TurboQuantizer::new_from_metadata(&metadata); - - let dim = metadata.vector_parameters.dim; + let encoding_buffer = vec![0.0f64; quantizer.padded_dim]; let result = Self { encoded_vectors, metadata, metadata_path: Some(meta_path.to_path_buf()), quantizer, - encoding_buffer: vec![0.0f64; dim], + encoding_buffer, };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/mod.rs` around lines 162 - 169, The stored encoding_buffer is currently sized to dim but must be sized to padded_dim to match the HadamardRotation and TurboQuantizer::quantize expectations; update the constructors/load paths that set encoding_buffer (the block returning Self with encoding_buffer, the encode constructor at line ~121, and the load path) to allocate vec![0.0f64; quantizer.padded_dim] (or padded_dim) instead of vec![0.0f64; dim], remove the now-unused local dim in load, and ensure upsert_vector's call into TurboQuantizer::quantize receives a buffer with length padded_dim so the rotation.apply and packing logic use the correct size.
🧹 Nitpick comments (2)
lib/quantization/src/turboquant/encoding.rs (1)
67-84:unpack_vectornow yieldspadded_dimelements — callers need updating.Worth making explicit in the doc comment that the iterator length is
padded_dim, notdim, and that values beyonddimare padding (zeros in the rotated space). The test atquantization.rs:761-765already accounts for this with.take(dim), and the symmetric/asymmetric scoring paths are internally consistent (both sides iterate overpadded_dim). A brief note on the iterator's length here would save future callers from the same footgun.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/encoding.rs` around lines 67 - 84, unpack_vector currently returns an iterator that yields self.padded_dim values (using (0..self.padded_dim).map(...)), but callers may expect only dim elements; update the function's doc comment for unpack_vector to explicitly state the iterator length is padded_dim and that elements beyond dim are padding (zeros in rotated space), and add guidance for callers to trim the iterator (e.g., .take(self.dim)) when they need only the original dimension; reference the function unpack_vector, the fields padded_dim and dim, and the iterator returned so future maintainers and tests (like those around quantization.rs:761-765) handle padding correctly.lib/quantization/src/turboquant/quantization.rs (1)
109-122: Minor: guardquery.len() <= padded_diminprecompute_query.
self.padded_dim - query.len()will underflow-panic in debug (and wrap in release) if a caller passes an over-sized query. A small upfrontdebug_assert!would make the contract explicit and fail with a clearer message:pub fn precompute_query(&self, query: &[f32]) -> EncodedQueryTQ { + debug_assert!(query.len() <= self.padded_dim); let mut rotated: Vec<f64> = query .iter() .map(|&x| f64::from(x)) .chain(std::iter::repeat_n(0.0, self.padded_dim - query.len())) .collect();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` around lines 109 - 122, The function precompute_query currently subtracts query.len() from self.padded_dim which can underflow for oversized inputs; add a defensive check such as debug_assert!(query.len() <= self.padded_dim, "precompute_query: query length {} exceeds padded_dim {}", query.len(), self.padded_dim) at the start of precompute_query to make the contract explicit and fail fast with a clear message before computing the zero padding and calling self.rotation.apply; update the assertion message to reference precompute_query and keep the rest of the function (rotation.apply and returning EncodedQueryTQ::Native(Precomputed(rotated))) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 107-115: The Bits1_5 branch in padded_dim is wrong: update the
comment and padding logic so elements are rounded up to a multiple that yields
whole bytes at 1.5 bits/element; specifically change TQBits::Bits1_5 handling in
padded_dim to return dim.next_multiple_of(16) and update the comment to note "16
elements per 24 bytes" (so padded_dim produces a multiple of 16 elements); keep
an eye on TQBits::Bits1_5::bit_size() when wiring it up.
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 58-71: The current debug_assert in quantize allows buf.len() to
differ from the required padded size, which can break self.rotation.apply(buf);
change the check in quantize to enforce buf.len() == self.padded_dim (use assert
or debug_assert_eq as appropriate) and update the function contract comment to
state that buf must be exactly self.padded_dim; ensure callers (encoding_buffer
/ mod.rs) pass a buffer of length self.padded_dim or adjust them to allocate
that exact size so rotation.apply always receives the expected length.
- Around line 33-45: The asymmetry bug is that TurboQuantizer::new stores
dim_sqrt as (dim as f32).sqrt() but the encoding uses sqrt(padded_dim); change
the stored sqrt to use padded_dim (e.g. set dim_sqrt = (self.padded_dim as
f32).sqrt() or rename to padded_dim_sqrt) so all asymmetric score normalization
uses sqrt(padded_dim) rather than sqrt(dim); update every place that currently
uses dim_sqrt (the asymmetric undo/normalization code and the other affected
block around lines 137-140) to reference the new padded-dimension sqrt value to
restore consistency for unaligned dims.
---
Outside diff comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 136-150: pack_extras_into currently computes extra_len with
Self::quantized_size_for (full quantized size) causing an unreachable zero-check
and over-reservation; change it to call
TqVectorExtras::size_for(self.padded_dim, self.bits, self.distance, self.mode)
so extra_len represents only extras, keep the early return if extras size is
zero, and call buf.reserve(extra_len) with that value; mirror the logic used by
unpack_extras_from and ensure you still conditionally extend buf with
extras.l2_length as before.
- Around line 93-115: quantized_size_for currently double-pads the dimension
because callers already pass self.padded_dim while the function calls
Self::padded_dim(dim, bits) again; change quantized_size_for(dim, bits,
distance, mode) to treat its dim parameter as already-padded (remove the
internal Self::padded_dim(...) call and compute vector_data_size using dim
directly) and update its comment to reflect that it expects a padded dim; keep
callers that pass self.padded_dim as-is (no other logic changes needed) and
ensure TQBits::Bits1_5 no longer gets double-padded.
In `@lib/quantization/src/turboquant/mod.rs`:
- Around line 162-169: The stored encoding_buffer is currently sized to dim but
must be sized to padded_dim to match the HadamardRotation and
TurboQuantizer::quantize expectations; update the constructors/load paths that
set encoding_buffer (the block returning Self with encoding_buffer, the encode
constructor at line ~121, and the load path) to allocate vec![0.0f64;
quantizer.padded_dim] (or padded_dim) instead of vec![0.0f64; dim], remove the
now-unused local dim in load, and ensure upsert_vector's call into
TurboQuantizer::quantize receives a buffer with length padded_dim so the
rotation.apply and packing logic use the correct size.
---
Nitpick comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 67-84: unpack_vector currently returns an iterator that yields
self.padded_dim values (using (0..self.padded_dim).map(...)), but callers may
expect only dim elements; update the function's doc comment for unpack_vector to
explicitly state the iterator length is padded_dim and that elements beyond dim
are padding (zeros in rotated space), and add guidance for callers to trim the
iterator (e.g., .take(self.dim)) when they need only the original dimension;
reference the function unpack_vector, the fields padded_dim and dim, and the
iterator returned so future maintainers and tests (like those around
quantization.rs:761-765) handle padding correctly.
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 109-122: The function precompute_query currently subtracts
query.len() from self.padded_dim which can underflow for oversized inputs; add a
defensive check such as debug_assert!(query.len() <= self.padded_dim,
"precompute_query: query length {} exceeds padded_dim {}", query.len(),
self.padded_dim) at the start of precompute_query to make the contract explicit
and fail fast with a clear message before computing the zero padding and calling
self.rotation.apply; update the assertion message to reference precompute_query
and keep the rest of the function (rotation.apply and returning
EncodedQueryTQ::Native(Precomputed(rotated))) unchanged.
🪄 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: f70d8097-425e-424c-a072-39965528aedb
📒 Files selected for processing (4)
lib/quantization/src/turboquant/encoding.rslib/quantization/src/turboquant/mod.rslib/quantization/src/turboquant/quantization.rslib/quantization/src/turboquant/rotation.rs
💤 Files with no reviewable changes (1)
- lib/quantization/src/turboquant/rotation.rs
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
lib/quantization/src/turboquant/quantization.rs (1)
243-243:⚠️ Potential issue | 🟠 MajorStandardize all test buffers to use
tq.padded_diminstead ofdim.Nine tests still size buffers as
vec, while others were already updated tovec. Now thatquantizeenforcesdebug_assert_eq!(buf.len(), self.padded_dim)at line 62, buffers must match the padded dimension for theirTQBitsvariant:
Bits1:dim.next_multiple_of(8)Bits1_5:(dim * 3 / 2).next_multiple_of(8)Bits2:dim.next_multiple_of(4)Bits4:dim.next_multiple_of(2)While none of the current tests trigger the assertion (because dims like 300 and 1000 are only tested with
Bits4, which aligns with even numbers), this will break as soon asBits1_5is tested or any test is refactored to useBits1orBits2with unaligned dimensions. Usetq.padded_dimto make all tests robust to future bit-width variants and dimension combinations.🧪 Example fix pattern (apply to all 9 affected tests)
- let tq = make_tq(dim, bits, DistanceType::Cosine); - let mut buf = vec![0.0f64; dim]; + let tq = make_tq(dim, bits, DistanceType::Cosine); + let mut buf = vec![0.0f64; tq.padded_dim];Also applies to: 318-318, 420-420, 475-475, 519-519, 565-565, 604-604, 639-639, 713-713
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` at line 243, Tests allocate buffers using the raw dimension `dim` which can mismatch the quantizer's required length; update each test that creates `let mut buf = vec![0.0f64; dim];` to use the quantizer's padded dimension instead (e.g., `vec![0.0f64; tq.padded_dim]`) so the buffer length matches the `debug_assert_eq!(buf.len(), self.padded_dim)` check in `quantize`; apply this change to all occurrences noted (lines creating `buf` in the tests) so they are robust across `TQBits` variants (`Bits1`, `Bits1_5`, `Bits2`, `Bits4`) and their padding rules.
♻️ Duplicate comments (1)
lib/quantization/src/turboquant/quantization.rs (1)
13-14:⚠️ Potential issue | 🟡 MinorStale
dim_sqrtnaming and comments after thepadded_dimswitch.Line 36 now stores
sqrt(padded_dim)into the field still calleddim_sqrt, and the docstring at line 13-14 ("Pre-calculatedsqrt(dim)used in scoring.") plus the block comment at line 139-140 ("dividing by sqrt(dim)") still describe the pre-padding behavior. Math is correct now, but a future reader will be misled when these disagree with the implementation.Suggest at least updating the comments (or, ideally, renaming the field to
padded_dim_sqrtas the prior review suggested):✏️ Proposed comment-only tweak
- // Pre-calculated `sqrt(dim)` used in scoring. - dim_sqrt: f32, + // Pre-calculated `sqrt(padded_dim)` used in scoring. + dim_sqrt: f32,- // Only the stored vector carries the sqrt(dim)/||v|| scaling, so we - // compensate by multiplying by ||v|| and dividing by sqrt(dim). + // Only the stored vector carries the sqrt(padded_dim)/||v|| scaling, + // so we compensate by multiplying by ||v|| and dividing by + // sqrt(padded_dim). dot * l2 / self.dim_sqrtAlso applies to: 36-36, 141-141
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` around lines 13 - 14, The field dim_sqrt is now storing sqrt(padded_dim) but its name and doc comments still reference sqrt(dim); rename the field to padded_dim_sqrt (or at minimum update the docstrings) and update every usage and comment that references dim_sqrt/padding math (e.g., where padded_dim is sqrt'd and where the code comments say "dividing by sqrt(dim)"), including struct definition, constructor/initialization, any methods that read the field, and tests/serialization code so names stay consistent; ensure comments explain it's sqrt(padded_dim) and run cargo check/tests to validate no unresolved references remain.
🧹 Nitpick comments (1)
lib/quantization/src/turboquant/quantization.rs (1)
64-72: Optional: unify the convert + zero-pad loops with the same chain-repeat idiom used inprecompute_query.The two sequential loops produce the same result as the pattern already used at lines 111-116, and collapsing them keeps the intent obvious in one pass.
♻️ Proposed refactor
- // Convert to f64 - for (v, b) in vec.iter().zip(buf.iter_mut()) { - *b = f64::from(*v); - } - - // Fill any extra buffer space with zeros (for padded dimensions) - for b in buf.iter_mut().skip(vec.len()) { - *b = 0.0; - } + // Convert to f64 and zero-pad up to `padded_dim`. + let padded = vec + .iter() + .map(|&x| f64::from(x)) + .chain(std::iter::repeat(0.0)); + for (b, v) in buf.iter_mut().zip(padded) { + *b = v; + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` around lines 64 - 72, Replace the two sequential loops that convert vec elements to f64 and then zero-pad buf with a single iterator chain like in precompute_query: iterate over vec.iter().map(|v| f64::from(*v)).chain(std::iter::repeat(0.0)).zip(buf.iter_mut()) and assign each value into the buffer; locate the conversion/zeroing code around the buf/vec handling in quantization.rs and replace the for loops with this single-pass pattern so conversion and padding happen together.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Line 243: Tests allocate buffers using the raw dimension `dim` which can
mismatch the quantizer's required length; update each test that creates `let mut
buf = vec![0.0f64; dim];` to use the quantizer's padded dimension instead (e.g.,
`vec![0.0f64; tq.padded_dim]`) so the buffer length matches the
`debug_assert_eq!(buf.len(), self.padded_dim)` check in `quantize`; apply this
change to all occurrences noted (lines creating `buf` in the tests) so they are
robust across `TQBits` variants (`Bits1`, `Bits1_5`, `Bits2`, `Bits4`) and their
padding rules.
---
Duplicate comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 13-14: The field dim_sqrt is now storing sqrt(padded_dim) but its
name and doc comments still reference sqrt(dim); rename the field to
padded_dim_sqrt (or at minimum update the docstrings) and update every usage and
comment that references dim_sqrt/padding math (e.g., where padded_dim is sqrt'd
and where the code comments say "dividing by sqrt(dim)"), including struct
definition, constructor/initialization, any methods that read the field, and
tests/serialization code so names stay consistent; ensure comments explain it's
sqrt(padded_dim) and run cargo check/tests to validate no unresolved references
remain.
---
Nitpick comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 64-72: Replace the two sequential loops that convert vec elements
to f64 and then zero-pad buf with a single iterator chain like in
precompute_query: iterate over vec.iter().map(|v|
f64::from(*v)).chain(std::iter::repeat(0.0)).zip(buf.iter_mut()) and assign each
value into the buffer; locate the conversion/zeroing code around the buf/vec
handling in quantization.rs and replace the for loops with this single-pass
pattern so conversion and padding happen together.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: da22865e-75d4-4378-b0b7-4db21c24b18e
📒 Files selected for processing (1)
lib/quantization/src/turboquant/quantization.rs
|
We're missing qdrant/lib/quantization/src/turboquant/mod.rs Line 167 in cbafe19 qdrant/lib/quantization/src/turboquant/mod.rs Line 183 in cbafe19 Some tests are using the non-padded |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
lib/quantization/src/turboquant/encoding.rs (2)
136-142:⚠️ Potential issue | 🟡 Minor
pack_extras_intouses total quantized size instead of extras-only size.
extra_lenis assignedSelf::quantized_size_for(self.padded_dim, ...), which returnsvector_data_size + extras_size— not just the extras length. Consequences:
if extra_len == 0 { return; }becomes dead code (vector_data_size is always > 0), so the early-return guard no longer protects against writing into buffers for configurations with no extras.buf.reserve(extra_len)over-reserves by the packed vector bytes.- The name
extra_lenno longer matches the value.Current behavior happens to stay correct only because the
if let Some(l2)guards each extras field, but the function no longer reflects its intent and will drift further as more extras are added.♻️ Proposed fix
fn pack_extras_into(&self, extras: &TqVectorExtras, buf: &mut Vec<u8>) { - let extra_len = - Self::quantized_size_for(self.padded_dim, self.bits, self.distance, self.mode); + let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode); if extra_len == 0 { return; } buf.reserve(extra_len);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/encoding.rs` around lines 136 - 142, The function pack_extras_into incorrectly computes extra_len using Self::quantized_size_for (which includes vector data plus extras); change it to compute only the extras length (e.g., call a dedicated extras-size helper like Self::quantized_extras_size_for(self.padded_dim, self.bits, self.distance, self.mode) or subtract the vector-data size from quantized_size_for using a vector-data helper), then use that extras-only value for the early-return check, buf.reserve, and any naming (rename to extras_len) so the guard and buffer reservation only account for extras and the guard remains effective for configurations with no extras; update references to Self::quantized_size_for in pack_extras_into and keep the existing per-field Some(l2) guards.
87-105:⚠️ Potential issue | 🟡 MinorFix double-padding bug in
quantized_size_forbefore enablingBits1_5.
quantized_size_foraccepts adimparameter and internally appliesSelf::padded_dim(dim, bits). However, two call sites (lines 88 inquantized_size()and 138 inpack_extras_into()) passself.padded_dim—an already-padded value—causing padding to be applied twice.Currently masked: For
Bits1/Bits2/Bits4, the padding function is idempotent (multiples of 8/4/2 round-trip). ForBits1_5with formula(dim * 3 / 2).next_multiple_of(8), it is not idempotent:dim=16 → padded=24 → double-padded=40. This becomes a live sizing bug the momentBits1_5::bit_size()is implemented (currently aTODOstub).Standardize the contract: either accept raw
dim(and passself.dimat call sites, applying padding at boundaries) or accept already-paddedpadded_dim(and remove the internalSelf::padded_dim()call).Example fix (Option A)
pub(super) fn quantized_size_for( - dim: usize, + padded_dim: usize, bits: TQBits, distance: DistanceType, mode: TQMode, ) -> usize { Self::assert_supported_distance(distance); - let vector_data_size = - Self::padded_dim(dim, bits) * bits.bit_size() as usize / u8::BITS as usize; + let vector_data_size = padded_dim * bits.bit_size() as usize / u8::BITS as usize; let extras_size = TqVectorExtras::size_for(bits, distance, mode); vector_data_size + extras_size }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/encoding.rs` around lines 87 - 105, quantized_size_for currently applies padding internally but callers (quantized_size and pack_extras_into) are passing self.padded_dim, causing double-padding for non-idempotent schemes like Bits1_5; fix by standardizing on raw dim: keep the internal call to Self::padded_dim(dim, bits) in quantized_size_for and change the call sites to pass the unpadded dimension (pass self.dim instead of self.padded_dim in quantized_size() and in pack_extras_into()), ensuring the function names to modify are quantized_size(), quantized_size_for(...), and pack_extras_into(), and keep TqVectorExtras::size_for(...) usage unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 136-142: The function pack_extras_into incorrectly computes
extra_len using Self::quantized_size_for (which includes vector data plus
extras); change it to compute only the extras length (e.g., call a dedicated
extras-size helper like Self::quantized_extras_size_for(self.padded_dim,
self.bits, self.distance, self.mode) or subtract the vector-data size from
quantized_size_for using a vector-data helper), then use that extras-only value
for the early-return check, buf.reserve, and any naming (rename to extras_len)
so the guard and buffer reservation only account for extras and the guard
remains effective for configurations with no extras; update references to
Self::quantized_size_for in pack_extras_into and keep the existing per-field
Some(l2) guards.
- Around line 87-105: quantized_size_for currently applies padding internally
but callers (quantized_size and pack_extras_into) are passing self.padded_dim,
causing double-padding for non-idempotent schemes like Bits1_5; fix by
standardizing on raw dim: keep the internal call to Self::padded_dim(dim, bits)
in quantized_size_for and change the call sites to pass the unpadded dimension
(pass self.dim instead of self.padded_dim in quantized_size() and in
pack_extras_into()), ensuring the function names to modify are quantized_size(),
quantized_size_for(...), and pack_extras_into(), and keep
TqVectorExtras::size_for(...) usage unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f1dc7ca0-4779-4d96-a619-ba8b2c2cbe55
📒 Files selected for processing (1)
lib/quantization/src/turboquant/encoding.rs
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
lib/quantization/src/turboquant/quantization.rs (2)
242-242: Tests still sizingbufoffdiminstead oftq.padded_dim— latent fragility.
quantizenow requiresbuf.len() == self.padded_dim(line 62). The three tests that exercise non-aligned dims were updated tovec, but the remaining tests still dovec![0.0f64; dim]:
- Line 242 (
quantize_extreme_values)- Line 317 (
quantize_zero_vector)- Line 419 (
score_approximates_true_similarity)- Line 474 (
score_self_similarity)- Line 518 (
score_antipodal_is_negative)- Line 564 (
higher_bits_reduce_error)- Line 603 (
score_extreme_magnitudes_finite)- Line 638 (
rank_preservation)- Line 712 (
score_linearity_dot)They pass only because the chosen dims (128/256/300/512/1000/1024/2000/4000) happen to already be aligned to the bit widths used — anyone extending these with a non-aligned
dim(e.g.,127withBits1) will trip the newdebug_assert_eq!(buf.len(), self.padded_dim). Sincetq.padded_dimispub(super)and in scope, flipping all remainingvec![0.0f64; dim]over tovec would remove the footgun and also give these tests genuine coverage when someone eventually adds a non-aligned case.Relevant to the SIMD-integration follow-up: the reviewer comment on the PR already pointed at this class of masked-by-alignment issue — the same principle applies here.
Also applies to: 317-317, 419-419, 474-474, 518-518, 564-564, 603-603, 638-638, 712-712
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` at line 242, Several tests allocate buf with vec![0.0f64; dim] but quantize requires buf.len() == self.padded_dim; update those tests to allocate using tq.padded_dim (e.g., replace vec![0.0f64; dim] with vec![0.0f64; tq.padded_dim]) for the tests quantize_extreme_values, quantize_zero_vector, score_approximates_true_similarity, score_self_similarity, score_antipodal_is_negative, higher_bits_reduce_error, score_extreme_magnitudes_finite, rank_preservation, and score_linearity_dot; if tq is not in scope where the allocation occurs, move the buf allocation inside the loop/block where tq is visible (the same scope that calls quantize/score) so the buffer length matches TurboQuant::padded_dim and avoids the debug_assert_eq! failure in quantize.
13-14: Doc comment fordim_sqrtis now stale.The field doc still says
sqrt(dim), but line 36 now computes(padded_dim as f32).sqrt()(the fix from the earlier review round). Worth updating the comment (and arguably the field name) so future readers don't get misled back into the same inconsistency.📝 Proposed doc-comment tweak
- // Pre-calculated `sqrt(dim)` used in scoring. + // Pre-calculated `sqrt(padded_dim)` used in scoring. dim_sqrt: f32,🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` around lines 13 - 14, The doc comment for the struct field dim_sqrt is stale (it says "sqrt(dim)") even though the code computes (padded_dim as f32).sqrt(); update the comment to say it holds the square root of the padded dimension (sqrt(padded_dim)), and optionally rename the field to padded_dim_sqrt to make intent explicit; if you rename, update all references and initializations that set dim_sqrt from (padded_dim as f32).sqrt() (e.g., constructors or builders) and any callers that read the field so behavior remains identical.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 109-117: precompute_query currently silently truncates queries
longer than padded_dim and the debug_assert_eq! is tautological; add the same
invariant check used in quantize by asserting (in debug builds) that query.len()
<= self.padded_dim at the start of precompute_query, then proceed with the
existing conversion logic, and remove the meaningless
debug_assert_eq!(rotated.len(), self.padded_dim); reference precompute_query,
quantize, and self.padded_dim to locate where to add the debug_assert.
---
Nitpick comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Line 242: Several tests allocate buf with vec![0.0f64; dim] but quantize
requires buf.len() == self.padded_dim; update those tests to allocate using
tq.padded_dim (e.g., replace vec![0.0f64; dim] with vec![0.0f64; tq.padded_dim])
for the tests quantize_extreme_values, quantize_zero_vector,
score_approximates_true_similarity, score_self_similarity,
score_antipodal_is_negative, higher_bits_reduce_error,
score_extreme_magnitudes_finite, rank_preservation, and score_linearity_dot; if
tq is not in scope where the allocation occurs, move the buf allocation inside
the loop/block where tq is visible (the same scope that calls quantize/score) so
the buffer length matches TurboQuant::padded_dim and avoids the debug_assert_eq!
failure in quantize.
- Around line 13-14: The doc comment for the struct field dim_sqrt is stale (it
says "sqrt(dim)") even though the code computes (padded_dim as f32).sqrt();
update the comment to say it holds the square root of the padded dimension
(sqrt(padded_dim)), and optionally rename the field to padded_dim_sqrt to make
intent explicit; if you rename, update all references and initializations that
set dim_sqrt from (padded_dim as f32).sqrt() (e.g., constructors or builders)
and any callers that read the field so behavior remains identical.
🪄 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: de89f89d-d05d-4820-ab8d-b247b5e36314
📒 Files selected for processing (1)
lib/quantization/src/turboquant/quantization.rs
| fn pack_extras_into(&self, extras: &TqVectorExtras, buf: &mut Vec<u8>) { | ||
| let extra_len = | ||
| Self::quantized_size_for(self.rotation.dim(), self.bits, self.distance, self.mode); | ||
| Self::quantized_size_for(self.padded_dim, self.bits, self.distance, self.mode); |
There was a problem hiding this comment.
We're already applying padding inside quantized_size_for. Applying a second time is a no-op but maybe it'd be cleaner to pad only once.
As it's currently not a 'real' issue, I'll let you decide whether to apply it or not.
There was a problem hiding this comment.
Rotation also has a padded dimension; TurboQuantizer has no information about its original dimension (and TurboQuantizer does not require the original dimension).
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
lib/quantization/src/turboquant/mod.rs (1)
111-111:⚠️ Potential issue | 🔴 CriticalBlocker — unused binding fails
clippy -D warningsin CI.
dimis bound but never read inencode(all subsequent sizing usesquantizer.padded_dimandvector_parametersdirectly). As reported in the pipeline, clippy rejects this withunused-variablesunder-D warnings.🐛 Proposed fix
- let dim = vector_parameters.dim; debug_assert!(validate_vector_parameters(data.clone(), vector_parameters).is_ok());🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/mod.rs` at line 111, The unused local binding `dim` in the `encode` function is causing Clippy failures; remove the line `let dim = vector_parameters.dim;` (or if you intended to use it, replace occurrences of `quantizer.padded_dim` or direct uses of `vector_parameters` with `dim`) so that no unused variable remains; ensure all sizing continues to reference `quantizer.padded_dim` or the appropriate `vector_parameters` field and that no other code expects `dim` to exist.
🧹 Nitpick comments (2)
lib/quantization/src/turboquant/quantization.rs (2)
239-258: Several tests still size the quantize buffer withdim, nottq.padded_dim.Lines 242, 317, 419, 474, 518, 564, 603, 638, and 712 allocate
buf = vec![0.0f64; dim], whereasquantizenowdebug_assert_eq!(buf.len(), self.padded_dim). The tests happen to pass because everydimhere is already aligned to the chosenTQBits(e.g. 128/300/512/… are all multiples of 2 forBits4), sopadded_dim == dim. But this is latent — any future test dim that isn't aligned will hit the debug assert inquantize, and these tests silently stop protecting the padding path.Two already-updated tests (
quantize_output_byte_length,quantize_deterministic,quantize_non_power_of_two_dimsat lines 269, 294, 353) usetq.padded_dim— recommend aligning the rest for consistency and to actually exercise padded sizing. Example:♻️ Proposed fix (apply similarly to each callsite)
- let mut buf = vec![0.0f64; dim]; + let mut buf = vec![0.0f64; tq.padded_dim];🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` around lines 239 - 258, Tests allocate the quantize buffer using dim but quantize asserts buf.len() == self.padded_dim; update quantize_extreme_values (and the other listed tests that create buf = vec![0.0f64; dim]) to use the target TQ instance's padded_dim (i.e., buf = vec![0.0f64; tq.padded_dim]) so the buffer length matches the quantize debug assertion; locate the buf allocations in functions like quantize_extreme_values and replace dim with tq.padded_dim wherever tq is available before calling tq.quantize.
128-141: Enum match is fine today, but keep the exhaustive pattern when adding SIMD variants.Per the repo coding guideline preferring explicit exhaustive matches, when you add the planned non-
NativeEncodedQueryTQDatavariants for SIMD precomputations, avoid adding a_ => ...arm here — list each variant explicitly so new data carriers can't silently fall throughscore_precomputed. As per coding guidelines: "Prefer explicit exhaustive matches over catch-all_arm in Rust match expressions, so we don't miss handling new enum variants when they are added later".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/quantization/src/turboquant/quantization.rs` around lines 128 - 141, The match in score_precomputed currently handles only EncodedQueryTQData::Native; when adding SIMD or other EncodedQueryTQData variants, replace any catch-all `_` arms and explicitly enumerate and handle each variant in the match (e.g., add branches for the planned SIMD precomputed variants) so new enum variants cannot silently fall through; update the match in score_precomputed (and related consumers of EncodedQueryTQData) to list every variant and implement the appropriate dot computation for each, or deliberately return an error/unreachable! for impossible cases.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@lib/quantization/src/turboquant/mod.rs`:
- Line 111: The unused local binding `dim` in the `encode` function is causing
Clippy failures; remove the line `let dim = vector_parameters.dim;` (or if you
intended to use it, replace occurrences of `quantizer.padded_dim` or direct uses
of `vector_parameters` with `dim`) so that no unused variable remains; ensure
all sizing continues to reference `quantizer.padded_dim` or the appropriate
`vector_parameters` field and that no other code expects `dim` to exist.
---
Nitpick comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 239-258: Tests allocate the quantize buffer using dim but quantize
asserts buf.len() == self.padded_dim; update quantize_extreme_values (and the
other listed tests that create buf = vec![0.0f64; dim]) to use the target TQ
instance's padded_dim (i.e., buf = vec![0.0f64; tq.padded_dim]) so the buffer
length matches the quantize debug assertion; locate the buf allocations in
functions like quantize_extreme_values and replace dim with tq.padded_dim
wherever tq is available before calling tq.quantize.
- Around line 128-141: The match in score_precomputed currently handles only
EncodedQueryTQData::Native; when adding SIMD or other EncodedQueryTQData
variants, replace any catch-all `_` arms and explicitly enumerate and handle
each variant in the match (e.g., add branches for the planned SIMD precomputed
variants) so new enum variants cannot silently fall through; update the match in
score_precomputed (and related consumers of EncodedQueryTQData) to list every
variant and implement the appropriate dot computation for each, or deliberately
return an error/unreachable! for impossible cases.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b796ebbb-f6a8-4081-a287-001cb519a2dd
📒 Files selected for processing (2)
lib/quantization/src/turboquant/mod.rslib/quantization/src/turboquant/quantization.rs
Fixed, thanks! Also, I added odd dimensions in the tests where we don't cover non-padded dimensions |
* refactor TQ before SIMD integration * review remarks * review remarks * rusty padding * review remarks * review remarks
There are a couple of changes which block SIMD integration: