Skip to content

Refactor TQ before SIMD integration - #8783

Merged
IvanPleshkov merged 6 commits into
devfrom
refactor-TQ-before-SIMD-integration
Apr 24, 2026
Merged

IvanPleshkov merged 6 commits into
devfrom
refactor-TQ-before-SIMD-integration

Conversation

@IvanPleshkov

Copy link
Copy Markdown
Contributor

There are a couple of changes which block SIMD integration:

  1. We need to have padded dimension because of bit packing. SIMD relies on full-packed vector data where all bits contain vector data, not just zeroed.
  2. TQ query has a enum of data variant, we will extend it by SIMD scalar quantized query data

@IvanPleshkov IvanPleshkov added this to the TurboQuant milestone Apr 24, 2026
@coderabbitai

coderabbitai Bot commented Apr 24, 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

The PR introduces a padded dimension concept used across turboquant: pub(crate) fn padded_dim(dim: usize, bits: TQBits) -> usize and a stored padded_dim on TurboQuantizer. Encoding, packing/unpacking, buffer allocation, rotation, quantize/decode, and scoring now use padded_dim. EncodedQueryTQ was refactored to hold EncodedQueryTQData::Native(Precomputed) and query precomputation/score APIs were adjusted. The HadamardRotation::dim() accessor was removed.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • JojiiOfficial
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: refactoring TQ to enable SIMD integration with padded dimensions and query data variants.
Description check ✅ Passed The description clearly relates to the changeset by explaining the rationale for padded dimensions and enum variants needed for SIMD integration.
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 refactor-TQ-before-SIMD-integration

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: 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_into computes the wrong length; rename/fix to use TqVectorExtras::size_for.

extra_len here is derived from quantized_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_size is always nonzero, so the function proceeds even for distance variants with zero extras (currently Cosine). It happens to be a no-op today because extras.l2_length is None for Cosine, 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 symmetric unpack_extras_from side (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 | 🟡 Minor

Passing self.padded_dim into quantized_size_for double-pads the dimension.

quantized_size_for treats its first argument as the raw (unpadded) dim and computes Self::padded_dim(dim, bits) internally (line 102). The callers at line 88 and line 138 pass self.padded_dim, so padding is applied twice. For Bits1/Bits2/Bits4, padded_dim happens to be idempotent (since the already-padded value is still a multiple of the target), so this is currently harmless. For Bits1_5, however, it is not idempotent — e.g. padded_dim(10, Bits1_5) = 16, but padded_dim(16, Bits1_5) = 24 — so any future wiring up of Bits1_5 would silently produce the wrong size here.

Consider either making the helper take an already-padded dim and dropping the inner Self::padded_dim(..) call, or keeping the inner padding and passing the raw dim (which would require storing it on TurboQuantizer).

🤖 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_buffer must be sized to padded_dim, not dim.

The encoding_buffer fed to TurboQuantizer::quantize in upsert_vector (line 283) needs to be as large as padded_dim — quantize zero-pads it past vec.len() and then calls self.rotation.apply(buf) against a HadamardRotation that was constructed with padded_dim. If dim < padded_dim (any non-aligned dim, e.g. dim = 127 with Bits1, or dim = 300 with Bits1), this buffer is too short and the rotation/packing will go wrong (or panic on the assertion against the rotation's configured dim).

The encode path already does this correctly at line 121 (vec![0.0f64; quantizer.padded_dim]). The stored buffer in both the encode constructor (line 167) and load (line 183) needs the same treatment. This also makes let 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_vector now yields padded_dim elements — callers need updating.

Worth making explicit in the doc comment that the iterator length is padded_dim, not dim, and that values beyond dim are padding (zeros in the rotated space). The test at quantization.rs:761-765 already accounts for this with .take(dim), and the symmetric/asymmetric scoring paths are internally consistent (both sides iterate over padded_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: guard query.len() <= padded_dim in precompute_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 upfront debug_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

📥 Commits

Reviewing files that changed from the base of the PR and between f689dcc and cbafe19.

📒 Files selected for processing (4)
  • lib/quantization/src/turboquant/encoding.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/src/turboquant/quantization.rs
  • lib/quantization/src/turboquant/rotation.rs
💤 Files with no reviewable changes (1)
  • lib/quantization/src/turboquant/rotation.rs

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

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 | 🟠 Major

Standardize all test buffers to use tq.padded_dim instead of dim.

Nine tests still size buffers as vec![0.0f64; dim] (lines 243, 318, 420, 475, 519, 565, 604, 639, 713), while others were already updated to vec![0.0f64; tq.padded_dim] (lines 270, 295, 354). Now that quantize enforces debug_assert_eq!(buf.len(), self.padded_dim) at line 62, buffers must match the padded dimension for their TQBits variant:

  • 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 as Bits1_5 is tested or any test is refactored to use Bits1 or Bits2 with unaligned dimensions. Use tq.padded_dim to 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 | 🟡 Minor

Stale dim_sqrt naming and comments after the padded_dim switch.

Line 36 now stores sqrt(padded_dim) into the field still called dim_sqrt, and the docstring at line 13-14 ("Pre-calculated sqrt(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_sqrt as 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_sqrt

Also 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 in precompute_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

📥 Commits

Reviewing files that changed from the base of the PR and between cbafe19 and 45bc979.

📒 Files selected for processing (1)
  • lib/quantization/src/turboquant/quantization.rs

@JojiiOfficial

JojiiOfficial commented Apr 24, 2026 •

Copy link
Copy Markdown
Member

We're missing padded_dim here:

encoding_buffer: vec![0.0f64; dim],
and here:
encoding_buffer: vec![0.0f64; dim],

Some tests are using the non-padded dim too (but don't fail because they're divisible by 2).

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

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_into uses total quantized size instead of extras-only size.

extra_len is assigned Self::quantized_size_for(self.padded_dim, ...), which returns vector_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_len no 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 | 🟡 Minor

Fix double-padding bug in quantized_size_for before enabling Bits1_5.

quantized_size_for accepts a dim parameter and internally applies Self::padded_dim(dim, bits). However, two call sites (lines 88 in quantized_size() and 138 in pack_extras_into()) pass self.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). For Bits1_5 with 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 moment Bits1_5::bit_size() is implemented (currently a TODO stub).

Standardize the contract: either accept raw dim (and pass self.dim at call sites, applying padding at boundaries) or accept already-padded padded_dim (and remove the internal Self::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

📥 Commits

Reviewing files that changed from the base of the PR and between 45bc979 and ab4dd5f.

📒 Files selected for processing (1)
  • lib/quantization/src/turboquant/encoding.rs

@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

🧹 Nitpick comments (2)
lib/quantization/src/turboquant/quantization.rs (2)

242-242: Tests still sizing buf off dim instead of tq.padded_dim — latent fragility.

quantize now requires buf.len() == self.padded_dim (line 62). The three tests that exercise non-aligned dims were updated to vec![0.0f64; tq.padded_dim] (lines 269, 294, 353), but the remaining tests still do vec![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., 127 with Bits1) will trip the new debug_assert_eq!(buf.len(), self.padded_dim). Since tq.padded_dim is pub(super) and in scope, flipping all remaining vec![0.0f64; dim] over to vec![0.0f64; tq.padded_dim] (and reallocating inside per-bits loops where tq currently lives inside) 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 for dim_sqrt is 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

📥 Commits

Reviewing files that changed from the base of the PR and between ab4dd5f and 4e8ea1f.

📒 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);

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.

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.

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.

Rotation also has a padded dimension; TurboQuantizer has no information about its original dimension (and TurboQuantizer does not require the original dimension).

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

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 | 🔴 Critical

Blocker — unused binding fails clippy -D warnings in CI.

dim is bound but never read in encode (all subsequent sizing uses quantizer.padded_dim and vector_parameters directly). As reported in the pipeline, clippy rejects this with unused-variables under -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 with dim, not tq.padded_dim.

Lines 242, 317, 419, 474, 518, 564, 603, 638, and 712 allocate buf = vec![0.0f64; dim], whereas quantize now debug_assert_eq!(buf.len(), self.padded_dim). The tests happen to pass because every dim here is already aligned to the chosen TQBits (e.g. 128/300/512/… are all multiples of 2 for Bits4), so padded_dim == dim. But this is latent — any future test dim that isn't aligned will hit the debug assert in quantize, and these tests silently stop protecting the padding path.

Two already-updated tests (quantize_output_byte_length, quantize_deterministic, quantize_non_power_of_two_dims at lines 269, 294, 353) use tq.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-Native EncodedQueryTQData variants for SIMD precomputations, avoid adding a _ => ... arm here — list each variant explicitly so new data carriers can't silently fall through score_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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e8ea1f and 1a687c5.

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

@IvanPleshkov

Copy link
Copy Markdown
Contributor Author

We're missing padded_dim here:

encoding_buffer: vec![0.0f64; dim],

and here:

encoding_buffer: vec![0.0f64; dim],

Some tests are using the non-padded dim too (but don't fail because they're divisible by 2).

We're missing padded_dim here:

encoding_buffer: vec![0.0f64; dim],

and here:

encoding_buffer: vec![0.0f64; dim],

Some tests are using the non-padded dim too (but don't fail because they're divisible by 2).

Fixed, thanks! Also, I added odd dimensions in the tests where we don't cover non-padded dimensions

@IvanPleshkov
IvanPleshkov merged commit b826d27 into dev Apr 24, 2026
15 checks passed
@IvanPleshkov
IvanPleshkov deleted the refactor-TQ-before-SIMD-integration branch April 24, 2026 09:31
This was referenced Apr 24, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 27, 2026
@coderabbitai coderabbitai Bot mentioned this pull request May 4, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
* refactor TQ before SIMD integration

* review remarks

* review remarks

* rusty padding

* review remarks

* review remarks
@coderabbitai coderabbitai Bot mentioned this pull request May 19, 2026
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