Repository navigation
TQ Scoring - #8753
TQ Scoring#8753
Conversation
1fd1fa4 to
bb63278
Compare
2db4aaf to
5815be6
Compare
ef37c62 to
98c53b0
Compare
c9de35a to
e3f1e75
Compare
📝 WalkthroughWalkthroughAdds 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
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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 | 🔴 CriticalPersist 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 fromconstruct_vector_parameters, where Cosine is intentionally mapped to Dot. For TQ Cosine this makesquantized.config.jsonpersist 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_implbefore 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 | 🟡 MinorAccount for the new encoding buffer in heap reporting.
encoding_bufferis now persistent heap memory, butEncodedVectorsTQstill falls back toEncodedVectors::heap_size_bytes()returning0. 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_lenwithquantized_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. UseTqVectorExtras::size_forhere.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 redundantuse rand::...lines inside test bodies.
StdRng,RngExt, andSeedableRngare already brought into scope at the top of thetestsmodule (lines 144–145). The re-imports insidequantize_deterministic(273–274),quantize_non_power_of_two_dims(325–326),pack_unpack_vector_roundtrip(363–364), andgenerate_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
📒 Files selected for processing (9)
lib/quantization/benches/turboquant.rslib/quantization/src/encoded_vectors.rslib/quantization/src/encoded_vectors_binary.rslib/quantization/src/encoded_vectors_pq.rslib/quantization/src/encoded_vectors_u8.rslib/quantization/src/turboquant/encoding.rslib/quantization/src/turboquant/mod.rslib/quantization/src/turboquant/quantization.rslib/segment/src/vector_storage/quantized/quantized_vectors.rs
| 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) | ||
| } |
There was a problem hiding this comment.
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.
| /// 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 | ||
| } |
There was a problem hiding this comment.
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.
| /// 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I guess the approach in this commit is fine in combination with your changes
6333d53
IvanPleshkov
left a comment
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
lib/quantization/src/turboquant/encoding.rslib/quantization/src/turboquant/quantization.rslib/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
| 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()); | ||
| } | ||
| } |
There was a problem hiding this comment.
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 == 0early-return is effectively dead (dim-bytes are always > 0), so theCosinecase falls through and relies on theif let Some(l2)guard to do nothing. buf.reserve(extra_len)over-reserves byquantized_dim_sizebytes 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.
* [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]>
Implements scoring (internal + query) for cosine and dot distances.
Not included:
This PR also implements all required functions of the
EncodedVectorstrait, meaning that TQ can now be used E2E from the API.