Skip to content

TurboQuant basic Quantization + Encoding - #8692

Merged
JojiiOfficial merged 8 commits into
devfrom
tq-encoding
Apr 21, 2026
Merged

JojiiOfficial merged 8 commits into
devfrom
tq-encoding

Conversation

@JojiiOfficial

@JojiiOfficial JojiiOfficial commented Apr 16, 2026 •

Copy link
Copy Markdown
Member

Implements basic TurboQuant quantization (Cosine only).

@JojiiOfficial JojiiOfficial added this to the TurboQuant milestone Apr 16, 2026
@JojiiOfficial JojiiOfficial mentioned this pull request Apr 16, 2026
63 of 69 tasks
@JojiiOfficial
JojiiOfficial marked this pull request as ready for review April 17, 2026 13:23
@JojiiOfficial JojiiOfficial changed the title [WIP] TurboQuant basic Quantization + Encoding TurboQuant basic Quantization + Encoding Apr 17, 2026
@coderabbitai

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

Adds a new TurboQuant Criterion benchmark and implements a complete TurboQuant module: TurboQuantizer (construction from Metadata/dimension, Hadamard rotation, quantize), packing/unpacking and quantized size helpers, and TqVectorExtras. Refactors Lloyd–Max centroid storage to fixed-size arrays with compile-time boundary calculation and exposes centroid accessors on TQBits. Exposes lloyd_max and quantization modules, makes encoding crate-visible, adds HadamardRotation::dim(), and updates EncodedVectorsTQ to construct/store a TurboQuantizer and reuse a buffer across encode/load/upsert paths.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • IvanPleshkov
  • generall
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main focus of the changeset: implementing basic TurboQuant quantization and encoding functionality.
Description check ✅ Passed The description is related to the changeset, mentioning that it implements basic TurboQuant quantization, which aligns with the quantization and encoding changes present.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tq-encoding

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

272-285: Per-call Vec<f64> allocation on the upsert hot path.

upsert_vector allocates a fresh vec![0.0f64; vector.len()] workspace on every insert, unlike the batch encode path which reuses a single buffer. For high-QPS upsert workloads this is avoidable heap churn; consider pooling the workspace on self (e.g., behind a parking_lot::Mutex<Vec<f64>> or a thread-local), or having TurboQuantizer::quantize own its scratch buffer.

Non-blocking — flagging for follow-up since the rest of the encode pipeline is explicitly buffer-aware.

🤖 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 272 - 285, upsert_vector
currently allocates a fresh vec![0.0f64; vector.len()] on every call causing
heap churn; change it to reuse a scratch buffer owned by the TurboQuantizer
instance (e.g., add a workspace field on the struct such as a
parking_lot::Mutex<Vec<f64>> or a dedicated scratch Vec<f64> accessed safely)
and have upsert_vector borrow and resize that buffer before calling
encode_vector, or alternatively move the scratch ownership into
TurboQuantizer::quantize and call that from upsert_vector so encode_vector uses
the pooled buffer; update references to encoded_vectors.upsert_vector and
encode_vector accordingly so no per-call heap allocation occurs.
🤖 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/benches/turboquant.rs`:
- Around line 45-51: The benchmark currently calls tq.quantize with a single
argument but TurboQuantizer::quantize requires a mutable f64 workspace (&mut
[f64]); fix the iter_batched setup to allocate a workspace of length dim and
pass it as the second argument. Concretely, change the setup closure to return
both the random vec and a mutable Vec<f64> (e.g., vec![0.0f64; dim]) and update
the measurement closure to call tq.quantize(black_box(&vec), &mut buf)
(references: TurboQuantizer::quantize, tq.quantize, random_vector, the
iter_batched closure).

In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 44-50: The debug_assert_eq!(vec.len(), buf.len()) is unsafe in
release; change to a hard assert or bound the write to avoid corrupting buf:
ensure the function validates sizes then copy only into buf[..vec.len()] and
call self.rotation.apply on the same limited slice (or use assert_eq! to enforce
exact equality). Concretely, in the function containing debug_assert_eq!,
replace the debug assertion with assert!(vec.len() <= buf.len()) (or
assert_eq!(vec.len(), buf.len())), then write into buf[..vec.len()] by iterating
and assigning buf[i] = f64::from(component) for i in 0..vec.len(), and finally
call self.rotation.apply on the exact slice you populated (e.g., &mut
buf[..vec.len()]) to avoid processing stale tail data.

---

Nitpick comments:
In `@lib/quantization/src/turboquant/mod.rs`:
- Around line 272-285: upsert_vector currently allocates a fresh vec![0.0f64;
vector.len()] on every call causing heap churn; change it to reuse a scratch
buffer owned by the TurboQuantizer instance (e.g., add a workspace field on the
struct such as a parking_lot::Mutex<Vec<f64>> or a dedicated scratch Vec<f64>
accessed safely) and have upsert_vector borrow and resize that buffer before
calling encode_vector, or alternatively move the scratch ownership into
TurboQuantizer::quantize and call that from upsert_vector so encode_vector uses
the pooled buffer; update references to encoded_vectors.upsert_vector and
encode_vector accordingly so no per-call heap allocation occurs.
🪄 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: 22110f28-8a44-46ed-84c2-5ff0c093b249

📥 Commits

Reviewing files that changed from the base of the PR and between 8e281ce and d0df4a3.

📒 Files selected for processing (6)
  • lib/quantization/Cargo.toml
  • lib/quantization/benches/turboquant.rs
  • lib/quantization/src/turboquant/lloyd_max.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/src/turboquant/quantization.rs
  • lib/quantization/src/turboquant/rotation.rs

Comment thread lib/quantization/benches/turboquant.rs Resolved
@JojiiOfficial
JojiiOfficial marked this pull request as draft April 17, 2026 14:10
@JojiiOfficial
JojiiOfficial marked this pull request as ready for review April 20, 2026 09:04

@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

♻️ Duplicate comments (1)
lib/quantization/src/turboquant/quantization.rs (1)

42-48: ⚠️ Potential issue | 🟠 Major

Keep the buffer-length invariant enforced in release builds.

This remains the same release-mode risk already flagged earlier: if buf is longer than vec, stale tail values are rotated and quantized; if it is shorter, the copy can panic. Use a hard invariant or operate on the exact initialized slice.

Defensive fix
-        debug_assert_eq!(vec.len(), buf.len());
+        assert_eq!(
+            vec.len(),
+            buf.len(),
+            "TurboQuant quantize buffer length must match vector length"
+        );
 
         // Rotate the vector
         for (i, &component) in vec.iter().enumerate() {
             buf[i] = f64::from(component);
         }
🤖 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 42 - 48,
Replace the debug-only check with a hard runtime invariant: change
debug_assert_eq!(vec.len(), buf.len()) to assert_eq!(vec.len(), buf.len(), "vec
and buf must have equal length in {}()", /* optionally include function name */)
so the lengths are validated in release builds before copying into buf and
before calling self.rotation.apply(buf); this ensures no stale tail or
out-of-bounds copy when using vec, buf, and self.rotation.apply.
🤖 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 47-66: unpack_vector must validate input lengths before slicing
and unpacking: compute the expected dimension-bytes (the quantized payload
length for self.bits and self.rotation.dim()), compute extra_len =
TqVectorExtras::size_for(self.bits, self.distance, self.mode), then ensure
vec.len() >= expected_dim_bytes + extra_len and out.len() ==
self.rotation.dim(); if these invariants fail, return an Err (or None) instead
of slicing/continuing. Also avoid slicing with vec.len()-extra_len until after
the check, and only call self.unpack_extras_from(extra_part) when extra_part is
present. Apply these checks inside unpack_vector (and keep use of BitReader.read
/ centroids lookup guarded by the validated sizes).

---

Duplicate comments:
In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 42-48: Replace the debug-only check with a hard runtime invariant:
change debug_assert_eq!(vec.len(), buf.len()) to assert_eq!(vec.len(),
buf.len(), "vec and buf must have equal length in {}()", /* optionally include
function name */) so the lengths are validated in release builds before copying
into buf and before calling self.rotation.apply(buf); this ensures no stale tail
or out-of-bounds copy when using vec, buf, and self.rotation.apply.
🪄 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: 3abad9a2-ca43-48b8-92fe-655683ef4e30

📥 Commits

Reviewing files that changed from the base of the PR and between 4d11a94 and 8bb0a30.

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

Comment on lines +47 to +66
pub fn unpack_vector(&self, vec: &[u8], out: &mut [f64]) -> Option<TqVectorExtras> {
let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode);

let dim_part = &vec[..vec.len() - extra_len];
let extra_part = &vec[vec.len() - extra_len..];

debug_assert_eq!(out.len(), self.rotation.dim());

// Unpack dimensions.
let centroids = self.bits.get_centroids();
let mut reader = BitReader::new(dim_part);
reader.set_bits(self.bits.bit_size());
for slot in out.iter_mut() {
let idx: u8 = reader.read();
*slot = f64::from(centroids[idx as usize]);
}

// Unpack and return extras if available.
(!extra_part.is_empty()).then(|| self.unpack_extras_from(extra_part))
}

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.

⚠️ Potential issue | 🟠 Major

Validate encoded and output lengths before unpacking.

In release builds, a short vec can panic at vec.len() - extra_len, and a wrong out length can leave stale values or read past the encoded payload. Split using the expected quantized size and fail loudly or return a Result.

Safer invariant check
     pub fn unpack_vector(&self, vec: &[u8], out: &mut [f64]) -> Option<TqVectorExtras> {
         let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode);
+        let expected_len = self.quantized_size();
+        assert_eq!(
+            vec.len(),
+            expected_len,
+            "encoded TurboQuant vector length must match metadata"
+        );
+        assert_eq!(
+            out.len(),
+            self.rotation.dim(),
+            "TurboQuant unpack output length must match quantizer dimension"
+        );
 
-        let dim_part = &vec[..vec.len() - extra_len];
-        let extra_part = &vec[vec.len() - extra_len..];
-
-        debug_assert_eq!(out.len(), self.rotation.dim());
+        let dim_len = expected_len - extra_len;
+        let (dim_part, extra_part) = vec.split_at(dim_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 47 - 66,
unpack_vector must validate input lengths before slicing and unpacking: compute
the expected dimension-bytes (the quantized payload length for self.bits and
self.rotation.dim()), compute extra_len = TqVectorExtras::size_for(self.bits,
self.distance, self.mode), then ensure vec.len() >= expected_dim_bytes +
extra_len and out.len() == self.rotation.dim(); if these invariants fail, return
an Err (or None) instead of slicing/continuing. Also avoid slicing with
vec.len()-extra_len until after the check, and only call
self.unpack_extras_from(extra_part) when extra_part is present. Apply these
checks inside unpack_vector (and keep use of BitReader.read / centroids lookup
guarded by the validated sizes).

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

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

262-275: Size the buffer from metadata.vector_parameters.dim and consider reusing it across upserts.

Two small concerns on the upsert hot path:

  1. The buffer is sized to vector.len(), but the TurboQuantizer was constructed from self.metadata.vector_parameters.dim. If a caller ever passes a mis-sized vector, the two will disagree and quantize() may silently misbehave instead of failing. Using the metadata dim matches the quantizer and aligns with the encode() path.
  2. A fresh Vec<f64> is allocated on every upsert_vector call. The encode() loop already reuses a single buffer; consider the same here (either stack-allocated within the call, or a small scratch buffer on Self) to avoid per-upsert allocation.
♻️ Minimal fix: size from metadata dim
-        let mut buf = vec![0.0f64; vector.len()];
+        let mut buf = vec![0.0f64; self.metadata.vector_parameters.dim];
         let encoded_vector = Self::encode_vector(vector, &self.quantizer, &mut buf);
🤖 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 262 - 275, The
upsert_vector implementation currently sizes a temporary buf from vector.len(),
which can diverge from the TurboQuantizer's configured dimension and also
allocates per call; change it to size the buffer from
self.metadata.vector_parameters.dim (the same source used when constructing the
quantizer and in the encode() path) and reuse a persistent scratch buffer on
Self (e.g., a Vec<f64> field) or a preallocated stack/scratch to avoid
per-upsert allocation; call Self::encode_vector with that sized/reused buffer
and then pass the bytes to self.encoded_vectors.upsert_vector so behavior
matches encode() and prevents silent mis-quantization and repeated allocations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/quantization/src/turboquant/mod.rs`:
- Around line 262-275: The upsert_vector implementation currently sizes a
temporary buf from vector.len(), which can diverge from the TurboQuantizer's
configured dimension and also allocates per call; change it to size the buffer
from self.metadata.vector_parameters.dim (the same source used when constructing
the quantizer and in the encode() path) and reuse a persistent scratch buffer on
Self (e.g., a Vec<f64> field) or a preallocated stack/scratch to avoid
per-upsert allocation; call Self::encode_vector with that sized/reused buffer
and then pass the bytes to self.encoded_vectors.upsert_vector so behavior
matches encode() and prevents silent mis-quantization and repeated allocations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c9827efc-2b46-4d5a-a879-fe051ac54f7b

📥 Commits

Reviewing files that changed from the base of the PR and between 8bb0a30 and 1fd1fa4.

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

@JojiiOfficial JojiiOfficial mentioned this pull request Apr 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
lib/quantization/src/turboquant/encoding.rs (1)

47-66: ⚠️ Potential issue | 🟠 Major

Validate encoded and output lengths before unpacking.

This still slices with vec.len() - extra_len before proving the input has the expected length, and out.len() is only debug-checked. A malformed or mismatched vector can panic or decode into the wrong output shape in release builds.

Safer invariant check
     pub fn unpack_vector(&self, vec: &[u8], out: &mut [f64]) -> Option<TqVectorExtras> {
         let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode);
+        let expected_len = self.quantized_size();
+        assert_eq!(
+            vec.len(),
+            expected_len,
+            "encoded TurboQuant vector length must match quantizer metadata"
+        );
+        assert_eq!(
+            out.len(),
+            self.rotation.dim(),
+            "TurboQuant unpack output length must match quantizer dimension"
+        );
 
-        let dim_part = &vec[..vec.len() - extra_len];
-        let extra_part = &vec[vec.len() - extra_len..];
-
-        debug_assert_eq!(out.len(), self.rotation.dim());
+        let dim_len = expected_len - extra_len;
+        let (dim_part, extra_part) = vec.split_at(dim_len);
 
         // Unpack dimensions.
🤖 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 47 - 66, Before
slicing and decoding in unpack_vector, perform runtime validation: check
out.len() == self.rotation.dim() (not just debug_assert), compute extra_len =
TqVectorExtras::size_for(self.bits, self.distance, self.mode) and verify
vec.len() >= extra_len + expected_dim_bytes (where expected_dim_bytes
corresponds to the number of encoded slots implied by self.bits.bit_size() / 8
or self.rotation.dim()), and ensure dim_part.len()*8 >= self.bits.bit_size(); if
any check fails return None. Also validate each read index against
centroids.len() (ensure idx as usize < centroids.len()) before indexing to avoid
panics; keep the existing call to unpack_extras_from(extra_part) only after
these checks succeed.
lib/quantization/src/turboquant/quantization.rs (1)

42-48: ⚠️ Potential issue | 🟠 Major

Keep the vector/buffer/dimension invariant in release builds.

debug_assert_eq! disappears in release, so a short vector leaves stale values in buf, and a long vector can panic while copying. This is the same unresolved invariant previously flagged here; make it a hard check or return a fallible result before rotating/packing.

Proposed invariant check
-        debug_assert_eq!(vec.len(), buf.len());
+        assert_eq!(
+            vec.len(),
+            self.rotation.dim(),
+            "TurboQuant input vector length must match quantizer dimension"
+        );
+        assert_eq!(
+            buf.len(),
+            self.rotation.dim(),
+            "TurboQuant scratch buffer length must match quantizer dimension"
+        );
 
         // Rotate the vector
         for (i, &component) in vec.iter().enumerate() {
🤖 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 42 - 48,
Replace the debug-only check with a real invariant check: instead of
debug_assert_eq!(vec.len(), buf.len!), verify vec.len() == buf.len() at runtime
before writing into buf and before calling self.rotation.apply; if they differ
return a fallible error (update the enclosing function's signature to return
Result and define/propagate a suitable error) or, if you prefer a hard failure,
use assert_eq! so it never disappears in release. Ensure the check references
the current symbols (vec, buf, self.rotation.apply) and happens prior to copying
the components into buf.
🤖 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 14-19: The current helpers (TqVectorExtras::size_for,
calculate_extras, and pack_extras_into) treat all TQMode variants as "no extras"
which silently encodes TQMode::Plus incorrectly; update each function to
explicitly match on the TQMode enum and reject/unwind when encountering
TQMode::Plus (or implement the Plus branch if you prefer) instead of falling
through to the default zero/no-op behavior—specifically, add a match on the mode
in TqVectorExtras::size_for, in calculate_extras, and in pack_extras_into that
either handles Plus properly or immediately panics/returns an Err (consistent
with the surrounding API) with a clear message like "TQMode::Plus not
implemented" so Plus vectors cannot be silently encoded as Normal.

In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 37-40: The guard in quantization.rs currently only allows
DistanceType::Dot and panics for Cosine; change the predicate to accept
DistanceType::Cosine instead of Dot (i.e., replace the matches check on
self.distance to require Cosine) and update the unimplemented! message to state
"Quantization currently only implemented for cosine similarity" (or vice-versa
if you prefer Dot-only—ensure consistency), and then update the duplicated guard
in encoding.rs::assert_supported_distance to match the same allowed DistanceType
so both checks remain in sync.

---

Duplicate comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 47-66: Before slicing and decoding in unpack_vector, perform
runtime validation: check out.len() == self.rotation.dim() (not just
debug_assert), compute extra_len = TqVectorExtras::size_for(self.bits,
self.distance, self.mode) and verify vec.len() >= extra_len + expected_dim_bytes
(where expected_dim_bytes corresponds to the number of encoded slots implied by
self.bits.bit_size() / 8 or self.rotation.dim()), and ensure dim_part.len()*8 >=
self.bits.bit_size(); if any check fails return None. Also validate each read
index against centroids.len() (ensure idx as usize < centroids.len()) before
indexing to avoid panics; keep the existing call to
unpack_extras_from(extra_part) only after these checks succeed.

In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 42-48: Replace the debug-only check with a real invariant check:
instead of debug_assert_eq!(vec.len(), buf.len!), verify vec.len() == buf.len()
at runtime before writing into buf and before calling self.rotation.apply; if
they differ return a fallible error (update the enclosing function's signature
to return Result and define/propagate a suitable error) or, if you prefer a hard
failure, use assert_eq! so it never disappears in release. Ensure the check
references the current symbols (vec, buf, self.rotation.apply) and happens prior
to copying the components into buf.
🪄 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: 3185fc40-d7e0-4de1-8903-fddb9314ea7c

📥 Commits

Reviewing files that changed from the base of the PR and between 1fd1fa4 and bb63278.

📒 Files selected for processing (7)
  • lib/quantization/Cargo.toml
  • lib/quantization/benches/turboquant.rs
  • lib/quantization/src/turboquant/encoding.rs
  • lib/quantization/src/turboquant/lloyd_max.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/src/turboquant/quantization.rs
  • lib/quantization/src/turboquant/rotation.rs
✅ Files skipped from review due to trivial changes (2)
  • lib/quantization/Cargo.toml
  • lib/quantization/benches/turboquant.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/quantization/src/turboquant/rotation.rs

Comment on lines +14 to +19
impl TqVectorExtras {
/// Returns the size (in bytes) required for the extras.
pub(super) fn size_for(_bits: TQBits, _distance: DistanceType, _mode: TQMode) -> usize {
// TODO(turbo): fully implement
0
}

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.

⚠️ Potential issue | 🟠 Major

Reject TQMode::Plus until extras are implemented.

size_for, calculate_extras, and pack_extras_into currently treat every mode as “no extras”, so a Plus vector is silently encoded like Normal while metadata says otherwise. Please either implement Plus extras or fail explicitly before encoding/sizing Plus configs.

Safer explicit mode handling
-    pub(super) fn size_for(_bits: TQBits, _distance: DistanceType, _mode: TQMode) -> usize {
-        // TODO(turbo): fully implement
-        0
+    pub(super) fn size_for(_bits: TQBits, _distance: DistanceType, mode: TQMode) -> usize {
+        match mode {
+            TQMode::Normal => 0,
+            TQMode::Plus => unimplemented!("TurboQuant Plus mode extras are not implemented yet"),
+        }
     }
-    pub(super) fn calculate_extras(&self, _rotated_vec: &[f64]) -> TqVectorExtras {
+    pub(super) fn calculate_extras(&self, _rotated_vec: &[f64]) -> TqVectorExtras {
         // TODO(turbo): fully implement
         Self::assert_supported_distance(self.distance);
 
-        TqVectorExtras::default()
+        match self.mode {
+            TQMode::Normal => TqVectorExtras::default(),
+            TQMode::Plus => unimplemented!("TurboQuant Plus mode extras are not implemented yet"),
+        }
     }

Also applies to: 97-101, 111-115

🤖 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 14 - 19, The
current helpers (TqVectorExtras::size_for, calculate_extras, and
pack_extras_into) treat all TQMode variants as "no extras" which silently
encodes TQMode::Plus incorrectly; update each function to explicitly match on
the TQMode enum and reject/unwind when encountering TQMode::Plus (or implement
the Plus branch if you prefer) instead of falling through to the default
zero/no-op behavior—specifically, add a match on the mode in
TqVectorExtras::size_for, in calculate_extras, and in pack_extras_into that
either handles Plus properly or immediately panics/returns an Err (consistent
with the surrounding API) with a clear message like "TQMode::Plus not
implemented" so Plus vectors cannot be silently encoded as Normal.

Comment on lines +37 to +40
if !matches!(self.distance, DistanceType::Dot) {
// TODO(turbo): implement for other metrics too.
unimplemented!("Quantization currently only implemented for dot product");
}

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.

⚠️ Potential issue | 🟠 Major

Align the supported distance with the Cosine-only objective.

This currently panics for DistanceType::Cosine and only allows Dot, so a Cosine TurboQuant config cannot be quantized. Please either switch this predicate/message to Cosine support, or update the PR/config validation to make Dot-only support explicit. The duplicated guard in encoding.rs::assert_supported_distance should be kept in sync.

🤖 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 37 - 40, The
guard in quantization.rs currently only allows DistanceType::Dot and panics for
Cosine; change the predicate to accept DistanceType::Cosine instead of Dot
(i.e., replace the matches check on self.distance to require Cosine) and update
the unimplemented! message to state "Quantization currently only implemented for
cosine similarity" (or vice-versa if you prefer Dot-only—ensure consistency),
and then update the duplicated guard in encoding.rs::assert_supported_distance
to match the same allowed DistanceType so both checks remain in sync.

@JojiiOfficial
JojiiOfficial merged commit e1a4af7 into dev Apr 21, 2026
15 checks passed
@JojiiOfficial
JojiiOfficial deleted the tq-encoding branch April 21, 2026 08:14
This was referenced Apr 24, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
* [AI + Manual] TurboQuant quantization

* Code spell

* [Ai + Manual] Integrate TurboQuantizer

* [Ai + Manual] Review tests

* Add Todos for unimplemented parts

* Fix bench

* [manual + ai] Add TqVectorExtras for additional metadata in quantized vectors

* Direct get_centroids implementation
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