Skip to content

TQ Scoring - #8753

Merged
IvanPleshkov merged 5 commits into
devfrom
tq-cosine-scoring
Apr 23, 2026
Merged

IvanPleshkov merged 5 commits into
devfrom
tq-cosine-scoring

Conversation

@JojiiOfficial

@JojiiOfficial JojiiOfficial commented Apr 21, 2026 •

Copy link
Copy Markdown
Member

Implements scoring (internal + query) for cosine and dot distances.

Not included:

  • 1.5 bit
  • SIMD
  • L1
  • L2

This PR also implements all required functions of the EncodedVectors trait, meaning that TQ can now be used E2E from the API.

@JojiiOfficial JojiiOfficial mentioned this pull request Apr 21, 2026
63 of 69 tasks
Base automatically changed from tq-encoding to dev April 21, 2026 08:14
@JojiiOfficial JojiiOfficial added this to the TurboQuant milestone Apr 21, 2026
@JojiiOfficial JojiiOfficial changed the title [WIP] TQ Cosine Scoring [WIP] TQ Scoring Apr 22, 2026
@JojiiOfficial JojiiOfficial changed the title [WIP] TQ Scoring TQ Scoring Apr 22, 2026
@JojiiOfficial
JojiiOfficial marked this pull request as ready for review April 22, 2026 08:13
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds Cosine distance support and completes TurboQuant implementation: new DistanceType::Cosine and VectorParameters now Copy; propagates Cosine into encoding and u8/PQ/binary paths; replaces some metadata clones with dereferenced copies. Reworks TurboQuant internals: extras (l2_length) stored/packed, extras sizing/encoding/decoding, pack/unpack API changed (pack now takes scaled f64s, unpack returns extras + iterator), retained encoding buffer, query precompute (Precomputed) and new scoring APIs (precompute_query, score_precomputed, score_symmetric). Adds benchmarks for dot and precomputed dot and updates encoded-query storage to hold rotated queries.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Suggested reviewers

  • JojiiOfficial
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'TQ Scoring' clearly and specifically summarizes the main change: implementing scoring functionality for TurboQuant, which is the primary focus across all file modifications.
Description check ✅ Passed The description is directly related to the changeset, explaining that it implements scoring for cosine and dot distances, specifies what's excluded, and notes the completion of EncodedVectors trait implementation.
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-cosine-scoring

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
lib/segment/src/vector_storage/quantized/quantized_vectors.rs (1)

816-839: ⚠️ Potential issue | 🔴 Critical

Persist the TQ cosine override in QuantizedVectorsConfig.

The let mut vector_parameters = vector_parameters; bindings on Lines 817 and 958 only mutate a match-arm shadow. Lines 838 and 982 still save the outer parameters from construct_vector_parameters, where Cosine is intentionally mapped to Dot. For TQ Cosine this makes quantized.config.json persist Dot, so reload computes the wrong quantized vector size and expects Dot extras for Cosine-packed vectors.

Proposed fix
-        let vector_parameters =
+        let mut vector_parameters =
             Self::construct_vector_parameters(distance, dim, count, storage_type);
+        if matches!(quantization_config, QuantizationConfig::Turbo(_))
+            && distance == Distance::Cosine
+        {
+            vector_parameters.distance_type = quantization::DistanceType::Cosine;
+        }
 
         let quantized_storage = match quantization_config {
@@
             QuantizationConfig::Turbo(TurboQuantization {
                 turbo: turbo_config,
-            }) => {
-                let mut vector_parameters = vector_parameters;
-                // TODO(turbo): Remove this manual hack after releasing TQ. For more details see the TODO inside [`Self::construct_vector_parameters`]
-                if distance == Distance::Cosine {
-                    vector_parameters.distance_type = quantization::DistanceType::Cosine;
-                }
-
-                Self::create_turbo(
+            }) => Self::create_turbo(
                     vectors,
                     &vector_parameters,
                     count,
@@
                     on_disk_vector_storage,
                     stopped,
-                )?
-            }
+                )?,
         };

Apply the same pattern in create_multi_impl before its match so the saved multi-vector config also matches the encoded TQ metadata.

Also applies to: 957-983

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/vector_storage/quantized/quantized_vectors.rs` around lines
816 - 839, The saved QuantizedVectorsConfig is using the outer vector_parameters
(from construct_vector_parameters) so the temporary match-arm override for
Cosine (let mut vector_parameters = vector_parameters) isn't persisted; update
create_multi_impl to apply the same mutating pattern before the match so the
vector_parameters that are stored in QuantizedVectorsConfig reflect the
Turbo-Quantization cosine override: find where
create_multi_impl/construct_vector_parameters produce vector_parameters and
ensure you mutate that outer variable (set vector_parameters.distance_type =
quantization::DistanceType::Cosine when distance == Distance::Cosine) prior to
calling Self::create_turbo and before constructing QuantizedVectorsConfig so the
persisted config matches the encoded TQ metadata (also mirror this change in the
other occurrence around lines 957-983 where the same shadowing bug appears).
lib/quantization/src/turboquant/mod.rs (1)

56-64: ⚠️ Potential issue | 🟡 Minor

Account for the new encoding buffer in heap reporting.

encoding_buffer is now persistent heap memory, but EncodedVectorsTQ still falls back to EncodedVectors::heap_size_bytes() returning 0. This underreports TQ memory usage; include the storage heap and buffer capacity.

Proposed fix
     fn immutable_files(&self) -> Vec<PathBuf> {
         let mut files = self.encoded_vectors.immutable_files();
         if let Some(meta_path) = &self.metadata_path {
             files.push(meta_path.clone());
         }
         files
     }
+
+    fn heap_size_bytes(&self) -> usize {
+        self.encoded_vectors.heap_size_bytes()
+            + self.encoding_buffer.capacity() * std::mem::size_of::<f64>()
+    }
 
     type SupportsBytes = True;
🤖 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 56 - 64, The heap-size
reporting for EncodedVectorsTQ must include the persistent encoding_buffer and
the underlying storage; update the EncodedVectorsTQ implementation of
heap_size_bytes() to return encoded_vectors.heap_size_bytes() +
(self.encoding_buffer.capacity() * std::mem::size_of::<f64>()) (and include any
other storage-owned heap from fields if missing), referencing the struct fields
encoded_vectors and encoding_buffer and the method heap_size_bytes() on
EncodedVectorsTQ so the reported value accounts for the buffer capacity in bytes
as well as the storage's reported heap usage.
🧹 Nitpick comments (2)
lib/quantization/src/turboquant/encoding.rs (1)

127-140: Reserve the extras size, not the full vector size.

Line 128 computes extra_len with quantized_size_for, so Dot vectors reserve roughly an extra full packed-vector capacity on every pack, and the zero-extras fast path never triggers for Cosine. Use TqVectorExtras::size_for here.

Proposed fix
-        let extra_len =
-            Self::quantized_size_for(self.rotation.dim(), self.bits, self.distance, self.mode);
+        let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode);
 
         if extra_len == 0 {
             return;
         }
🤖 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 127 - 140, The
reserve size is computed from quantized_size_for (packed vector size) causing
over-reservation and wrong fast-path behavior; in pack_extras_into change the
extra_len calculation to use TqVectorExtras::size_for(...) (the extras size)
instead of Self::quantized_size_for(...), then keep the existing early return on
zero and buf.reserve(extra_len) so only the true extras bytes (e.g., l2) are
reserved; update references around pack_extras_into, TqVectorExtras::size_for,
quantized_size_for, extras.l2_length, and buf.reserve accordingly.
lib/quantization/src/turboquant/quantization.rs (1)

144-145: Drop the redundant use rand::... lines inside test bodies.

StdRng, RngExt, and SeedableRng are already brought into scope at the top of the tests module (lines 144–145). The re-imports inside quantize_deterministic (273–274), quantize_non_power_of_two_dims (325–326), pack_unpack_vector_roundtrip (363–364), and generate_random_vector_pair_with_similarity (172) are noise.

🧹 Suggested cleanup
     fn quantize_deterministic() {
-        use rand::prelude::StdRng;
-        use rand::{RngExt, SeedableRng};
-
         let mut rng = StdRng::seed_from_u64(123);

(and analogously in the other three locations)

Also applies to: 272-274, 324-326, 362-364

🤖 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 144 - 145,
Remove the redundant in-function imports of StdRng, RngExt, and SeedableRng that
duplicate the top-level test-module imports: delete the extra use lines inside
the test functions named quantize_deterministic, quantize_non_power_of_two_dims,
pack_unpack_vector_roundtrip, and the helper
generate_random_vector_pair_with_similarity so the code relies on the
module-level imports already declared (StdRng, RngExt, SeedableRng).
🤖 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 55-85: The quantize method can produce +∞/NaN when
extras.l2_length is 0 (Dot path); change the scale computation in quantize to
guard against zero length by checking extras.l2_length (or length) and using a
finite fallback (e.g., scale = 0.0 or 1.0) instead of dividing by zero, so (val
* scale) never yields NaN; update the block that sets let length = ... and let
scale = ... to handle length == 0 (or length.is_finite()) before mapping with
boundaries.partition_point, leaving rotation.apply, boundaries, and pack_vector
untouched.
- Around line 106-128: Update the documentation and add a debug-time check to
enforce the unit-norm contract for cosine scoring: in the doc comment for
precompute_query and score_precomputed explicitly state that for
DistanceType::Cosine the caller must pass a unit-norm query (mirror the
normalize-before-quantize contract), and in precompute_query check when
self.distance == DistanceType::Cosine that the input query norm ≈ 1.0 (compute
||query|| from the f32 slice) using a debug_assert! with a small epsilon (e.g.
1e-6) and an explanatory message; this will catch misuse at debug time while
leaving release behavior unchanged.

---

Outside diff comments:
In `@lib/quantization/src/turboquant/mod.rs`:
- Around line 56-64: The heap-size reporting for EncodedVectorsTQ must include
the persistent encoding_buffer and the underlying storage; update the
EncodedVectorsTQ implementation of heap_size_bytes() to return
encoded_vectors.heap_size_bytes() + (self.encoding_buffer.capacity() *
std::mem::size_of::<f64>()) (and include any other storage-owned heap from
fields if missing), referencing the struct fields encoded_vectors and
encoding_buffer and the method heap_size_bytes() on EncodedVectorsTQ so the
reported value accounts for the buffer capacity in bytes as well as the
storage's reported heap usage.

In `@lib/segment/src/vector_storage/quantized/quantized_vectors.rs`:
- Around line 816-839: The saved QuantizedVectorsConfig is using the outer
vector_parameters (from construct_vector_parameters) so the temporary match-arm
override for Cosine (let mut vector_parameters = vector_parameters) isn't
persisted; update create_multi_impl to apply the same mutating pattern before
the match so the vector_parameters that are stored in QuantizedVectorsConfig
reflect the Turbo-Quantization cosine override: find where
create_multi_impl/construct_vector_parameters produce vector_parameters and
ensure you mutate that outer variable (set vector_parameters.distance_type =
quantization::DistanceType::Cosine when distance == Distance::Cosine) prior to
calling Self::create_turbo and before constructing QuantizedVectorsConfig so the
persisted config matches the encoded TQ metadata (also mirror this change in the
other occurrence around lines 957-983 where the same shadowing bug appears).

---

Nitpick comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 127-140: The reserve size is computed from quantized_size_for
(packed vector size) causing over-reservation and wrong fast-path behavior; in
pack_extras_into change the extra_len calculation to use
TqVectorExtras::size_for(...) (the extras size) instead of
Self::quantized_size_for(...), then keep the existing early return on zero and
buf.reserve(extra_len) so only the true extras bytes (e.g., l2) are reserved;
update references around pack_extras_into, TqVectorExtras::size_for,
quantized_size_for, extras.l2_length, and buf.reserve accordingly.

In `@lib/quantization/src/turboquant/quantization.rs`:
- Around line 144-145: Remove the redundant in-function imports of StdRng,
RngExt, and SeedableRng that duplicate the top-level test-module imports: delete
the extra use lines inside the test functions named quantize_deterministic,
quantize_non_power_of_two_dims, pack_unpack_vector_roundtrip, and the helper
generate_random_vector_pair_with_similarity so the code relies on the
module-level imports already declared (StdRng, RngExt, SeedableRng).
🪄 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: a9b231c3-0027-4098-9e94-c544d9bd482e

📥 Commits

Reviewing files that changed from the base of the PR and between 61f3bd1 and e3f1e75.

📒 Files selected for processing (9)
  • lib/quantization/benches/turboquant.rs
  • lib/quantization/src/encoded_vectors.rs
  • lib/quantization/src/encoded_vectors_binary.rs
  • lib/quantization/src/encoded_vectors_pq.rs
  • lib/quantization/src/encoded_vectors_u8.rs
  • lib/quantization/src/turboquant/encoding.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/src/turboquant/quantization.rs
  • lib/segment/src/vector_storage/quantized/quantized_vectors.rs

Comment on lines 55 to 85
pub fn quantize(&self, vec: &[f32], buf: &mut [f64]) -> Vec<u8> {
if !matches!(self.distance, DistanceType::Dot) {
// TODO(turbo): implement for other metrics too.
unimplemented!("Quantization currently only implemented for dot product");
}
Self::assert_supported_distance(self.distance);

debug_assert_eq!(vec.len(), buf.len());

// Rotate the vector
// Convert to f64
for (i, &component) in vec.iter().enumerate() {
buf[i] = f64::from(component);
}

// Rotate the vector.
self.rotation.apply(buf);

// Calculate data that needs to be stored additionally.
let extras = self.calculate_extras(buf);

// Find rotated vectors centroids.
// Rescale so per-coordinate variance is ~1 — matching the Lloyd-Max
// N(0, 1) centroid grid.
let length = f64::from(extras.l2_length.unwrap_or(1.0));
let scale = (self.rotation.dim() as f64).sqrt() / length;

// Picking the corresponding centroid indices.
let boundaries = self.bits.get_centroid_boundaries();
let encoded = buf
.iter()
.map(|&val| boundaries.partition_point(|&b| val > f64::from(b)) as u8);
let encoded = buf.iter().map(|&val| {
let scaled = (val * scale) as f32;
boundaries.partition_point(|&b| scaled > b) as u8
});

// Encode centroid indices and return packed vector.
// Encode and return packed vector.
self.pack_vector(encoded, extras)
}

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 | 🟡 Minor

Zero / near-zero vector with DistanceType::Dot produces NaN intermediates during centroid selection.

When extras.l2_length is Some(0.0) (all-zero or exactly-orthogonal-after-rotation input on the Dot path), scale = sqrt(dim) / 0 = +∞, and each val * scale = 0 * ∞ = NaN. partition_point(|&b| NaN > b) evaluates to false for every boundary, so every coordinate gets index 0. The scoring side happens to recover 0 because the stored l2_length = 0 zeroes the product, so the end-to-end result is harmless today — but the NaN path through partition_point is fragile and would bite if the scoring formula ever changes.

A cheap guard (skip rescaling when length == 0, e.g. treat it as scale = 0 or 1) would remove the NaN without affecting any valid input. Not a blocker, just flagging since there's no test exercising a zero Dot vector.

🤖 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 55 - 85, The
quantize method can produce +∞/NaN when extras.l2_length is 0 (Dot path); change
the scale computation in quantize to guard against zero length by checking
extras.l2_length (or length) and using a finite fallback (e.g., scale = 0.0 or
1.0) instead of dividing by zero, so (val * scale) never yields NaN; update the
block that sets let length = ... and let scale = ... to handle length == 0 (or
length.is_finite()) before mapping with boundaries.partition_point, leaving
rotation.apply, boundaries, and pack_vector untouched.

Comment on lines +106 to +128
/// Precompute the Hadamard rotation of `query` so subsequent
/// [`Self::score_precomputed`] calls skip the per-call rotation.
pub fn precompute_query(&self, query: &[f32]) -> Precomputed {
let mut rotated: Vec<f64> = query.iter().map(|&x| f64::from(x)).collect();
self.rotation.apply(&mut rotated);
Precomputed(rotated)
}

/// Similarity score with a query that has already been rotated via
/// [`Self::precompute_query`]. Returns an approximate `<query, v>` for Dot
/// and `cos(θ)` for Cosine.
pub fn score_precomputed(&self, query: &Precomputed, vec: &[u8]) -> f32 {
let (vector_extras, unpacked) = self.unpack_vector(vec);
let dot = dot_impl(query.as_slice().iter().copied(), unpacked);

let l2 = vector_extras
.and_then(|extras| extras.l2_length)
.unwrap_or(1.0);

// Only the stored vector carries the sqrt(dim)/||v|| scaling, so we
// compensate by multiplying by ||v|| and dividing by sqrt(dim).
dot * l2 / self.dim_sqrt
}

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 | 🟡 Minor

Document (and consider enforcing) the unit-norm requirement on the query for the Cosine path.

For DistanceType::Cosine, score_precomputed returns cos(θ) only if the query is unit-norm, because the formula dot * l2 / dim_sqrt restores the stored vector's magnitude but does not divide by ||query||. If a caller passes a non-normalized query to the Cosine quantizer, they silently get a raw dot product rather than cosine similarity. The doc comment states "cos(θ) for Cosine" without calling out this caller contract, and there is no debug assertion to catch the misuse.

Worth either tightening the doc (mirroring the normalize-before-quantize contract that the Cosine encoding pipeline already relies on) or adding a debug_assert! on ||query|| ≈ 1.0 in precompute_query when self.distance == DistanceType::Cosine.

📝 Proposed doc tightening
     /// Precompute the Hadamard rotation of `query` so subsequent
     /// [`Self::score_precomputed`] calls skip the per-call rotation.
+    ///
+    /// For [`DistanceType::Cosine`], the caller is responsible for passing a
+    /// unit-norm `query`; otherwise `score_precomputed` will return a raw dot
+    /// product rather than `cos(θ)`.
     pub fn precompute_query(&self, query: &[f32]) -> Precomputed {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// Precompute the Hadamard rotation of `query` so subsequent
/// [`Self::score_precomputed`] calls skip the per-call rotation.
pub fn precompute_query(&self, query: &[f32]) -> Precomputed {
let mut rotated: Vec<f64> = query.iter().map(|&x| f64::from(x)).collect();
self.rotation.apply(&mut rotated);
Precomputed(rotated)
}
/// Similarity score with a query that has already been rotated via
/// [`Self::precompute_query`]. Returns an approximate `<query, v>` for Dot
/// and `cos(θ)` for Cosine.
pub fn score_precomputed(&self, query: &Precomputed, vec: &[u8]) -> f32 {
let (vector_extras, unpacked) = self.unpack_vector(vec);
let dot = dot_impl(query.as_slice().iter().copied(), unpacked);
let l2 = vector_extras
.and_then(|extras| extras.l2_length)
.unwrap_or(1.0);
// Only the stored vector carries the sqrt(dim)/||v|| scaling, so we
// compensate by multiplying by ||v|| and dividing by sqrt(dim).
dot * l2 / self.dim_sqrt
}
/// Precompute the Hadamard rotation of `query` so subsequent
/// [`Self::score_precomputed`] calls skip the per-call rotation.
///
/// For [`DistanceType::Cosine`], the caller is responsible for passing a
/// unit-norm `query`; otherwise `score_precomputed` will return a raw dot
/// product rather than `cos(θ)`.
pub fn precompute_query(&self, query: &[f32]) -> Precomputed {
let mut rotated: Vec<f64> = query.iter().map(|&x| f64::from(x)).collect();
self.rotation.apply(&mut rotated);
Precomputed(rotated)
}
/// Similarity score with a query that has already been rotated via
/// [`Self::precompute_query`]. Returns an approximate `<query, v>` for Dot
/// and `cos(θ)` for Cosine.
pub fn score_precomputed(&self, query: &Precomputed, vec: &[u8]) -> f32 {
let (vector_extras, unpacked) = self.unpack_vector(vec);
let dot = dot_impl(query.as_slice().iter().copied(), unpacked);
let l2 = vector_extras
.and_then(|extras| extras.l2_length)
.unwrap_or(1.0);
// Only the stored vector carries the sqrt(dim)/||v|| scaling, so we
// compensate by multiplying by ||v|| and dividing by sqrt(dim).
dot * l2 / self.dim_sqrt
}
🤖 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 106 - 128,
Update the documentation and add a debug-time check to enforce the unit-norm
contract for cosine scoring: in the doc comment for precompute_query and
score_precomputed explicitly state that for DistanceType::Cosine the caller must
pass a unit-norm query (mirror the normalize-before-quantize contract), and in
precompute_query check when self.distance == DistanceType::Cosine that the input
query norm ≈ 1.0 (compute ||query|| from the f32 slice) using a debug_assert!
with a small epsilon (e.g. 1e-6) and an explanatory message; this will catch
misuse at debug time while leaving release behavior unchanged.

}) => {
let mut vector_parameters = vector_parameters;
// TODO(turbo): Remove this manual hack after releasing TQ. For more details see the TODO inside [`Self::construct_vector_parameters`]
if distance == Distance::Cosine {

@JojiiOfficial JojiiOfficial Apr 22, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We need to differentiate between Cosine and Dot distance in TQ. Therefore Cosine was added as new enum kind in the quantization crate's DistanceType enum.
However, this enum is persisted for all quantization storages (not only TQ).
To allow downgrading, we're skipping this newly added kind in currently existing quantization storages and only add it for turboquant, which is a new feature anyway.

In a later release, we can remove this hack and allow persisting the correct Distance for other quantiaztion types too.
For non-TQ quantiaztion types it doesn't matter which type it is because dot and cosine haven't been differentiated before.

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.

I guess the approach in this commit is fine in combination with your changes
6333d53

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

List of changes:

  • Use Vec::split_at in unpack_vector.
  • unpack_vector always returns TqVectorExtras, no Option.
  • unpack_extras_from check for extras size, no just empty vector.
  • pack takes centroid indices, unpack returns centroid positions - no symmetry. Changed to floats, pack checks boundaries inside.
  • change cosine metric setting for TQ
    Another review remarks will be fixed while L2/L1 metrics implementation

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/quantization/src/turboquant/encoding.rs`:
- Around line 130-144: The pack_extras_into function currently computes
extra_len using Self::quantized_size_for(...) which includes both
quantized_dim_size and extras_size; replace that with
TqVectorExtras::size_for(self.rotation.dim(), self.bits, self.distance,
self.mode) so extra_len refers only to the extras bytes to be appended, keep the
early-return if extra_len == 0, and call buf.reserve(extra_len) based on that
value; retain the existing if let Some(l2) = extras.l2_length guard to append
l2.to_le_bytes() when present.
🪄 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: e670e226-e800-48cc-a7d4-d740a3345e00

📥 Commits

Reviewing files that changed from the base of the PR and between e139c8b and 6333d53.

📒 Files selected for processing (3)
  • lib/quantization/src/turboquant/encoding.rs
  • lib/quantization/src/turboquant/quantization.rs
  • lib/segment/src/vector_storage/quantized/quantized_vectors.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/vector_storage/quantized/quantized_vectors.rs

Comment on lines +130 to +144
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);

if extra_len == 0 {
return;
}

buf.reserve(extra_len);

// Additional l2 for dot vectors.
if let Some(l2) = extras.l2_length {
buf.extend(&l2.to_le_bytes());
}
}

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 | 🟡 Minor

pack_extras_into sizes itself against the total quantized size, not the extras size.

Self::quantized_size_for(...) returns quantized_dim_size + extras_size, so extra_len here includes the bit-packed dim bytes. Consequences:

  • The if extra_len == 0 early-return is effectively dead (dim-bytes are always > 0), so the Cosine case falls through and relies on the if let Some(l2) guard to do nothing.
  • buf.reserve(extra_len) over-reserves by quantized_dim_size bytes on every call.

Behavior happens to stay correct because the actual append is gated by extras.l2_length, but the intent is clearly "how many bytes of extras am I about to append". Please use TqVectorExtras::size_for(...) instead.

♻️ Proposed fix
 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);
+    let extra_len = TqVectorExtras::size_for(self.bits, self.distance, self.mode);

     if extra_len == 0 {
         return;
     }

     buf.reserve(extra_len);

     // Additional l2 for dot vectors.
     if let Some(l2) = extras.l2_length {
         buf.extend(&l2.to_le_bytes());
     }
 }
🤖 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 130 - 144, The
pack_extras_into function currently computes extra_len using
Self::quantized_size_for(...) which includes both quantized_dim_size and
extras_size; replace that with TqVectorExtras::size_for(self.rotation.dim(),
self.bits, self.distance, self.mode) so extra_len refers only to the extras
bytes to be appended, keep the early-return if extra_len == 0, and call
buf.reserve(extra_len) based on that value; retain the existing if let Some(l2)
= extras.l2_length guard to append l2.to_le_bytes() when present.

@IvanPleshkov
IvanPleshkov merged commit 4f35b72 into dev Apr 23, 2026
15 checks passed
@IvanPleshkov
IvanPleshkov deleted the tq-cosine-scoring branch April 23, 2026 10:01
@IvanPleshkov IvanPleshkov mentioned this pull request Apr 24, 2026
8 tasks done
timvisee pushed a commit that referenced this pull request May 8, 2026
* [AI + Manual] Cosine scoring

* [ai + manual] Add support for dot product

* [ai] re-implement tests including covering both distances (dot+cosine)

* Clarify Cosine/Dot equivalence behavior for pre-TQ quantization storages

* review remarks

---------

Co-authored-by: Ivan Pleshkov <[email protected]>
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