Skip to content

Fix scalar L2 quantized score shift - #9518

Merged
IvanPleshkov merged 3 commits into
qdrant:devfrom
RitwijParmar:codex/qdrant-l2-scalar-translation-invariance
Jun 23, 2026
Merged

IvanPleshkov merged 3 commits into
qdrant:devfrom
RitwijParmar:codex/qdrant-l2-scalar-translation-invariance

Conversation

@RitwijParmar

@RitwijParmar RitwijParmar commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes the scalar int8 L2 scoring path so rescore=false scores do not include the dot-product quantizer offset-squared shift.

For squared L2, a common quantizer offset cancels before squaring. Reusing the dot/cosine shift made approximate Euclid scores depend on translating every stored vector and the query by the same constant.

I also expanded the regression into scalar-quantization metamorphic score contracts:

  • L1 and L2 scores stay invariant when every stored vector and the query are translated by the same constant.
  • Dot and L2 scores scale by scale^2 under positive scaling.
  • L1 scores scale by scale under positive scaling.
  • Both normal and inverted scoring are covered.

That keeps this from being a one-off reproduction and makes the affine score behavior explicit for future quantization changes.

Closes #9515.

Tests

  • cargo test -p quantization scalar_quantized
  • cargo test -p quantization test_l2_
  • rustfmt --check lib/quantization/src/encoded_vectors_u8.rs lib/quantization/tests/integration/test_simple.rs

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 7e511fea-d5ea-4030-974a-0076d830e3cd

📥 Commits

Reviewing files that changed from the base of the PR and between a3e7a1c and c4caaf9.

📒 Files selected for processing (1)
  • lib/quantization/tests/integration/test_simple.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/quantization/tests/integration/test_simple.rs

📝 Walkthrough

Walkthrough

The fix targets MetadataInt8::get_shift in encoded_vectors_u8.rs, modifying the distance-type-specific shift computation. Previously, DistanceType::L1 and L2 both computed a non-zero shift of actual_dim * offset². This change makes both L1 and L2 return 0.0, while Dot and Cosine retain the original formula, with updated documentation explaining that offset² contributions cancel out for L2 due to the squared code-difference formulation. Three new test helper functions enable comprehensive parametrized integration tests: scalar_quantized_scores_for encodes vectors and queries under Int8 quantization, deterministic_affine_vectors and map_affine generate reproducible affine-transformed test data, and assert_scores_match_transform validates per-vector score stability. Two new parametrized integration tests validate the fix: test_scalar_quantized_distance_scores_are_translation_invariant covers L1 and L2 with offset translation, and test_scalar_quantized_scores_follow_positive_scaling covers Dot, L1, and L2 with positive scaling, confirming that Dot and Cosine behavior remains unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related issues

  • #9515 — Scalar-quantized Euclid scores violate translation invariance when rescore=false: This PR directly implements the fix for the shift computation described in that issue by modifying MetadataInt8::get_shift to return 0.0 for L1/L2 distances, and adds comprehensive parametrized tests covering both the translation-invariance fix and validation of unchanged Dot/Cosine behavior under translation and scaling transforms.

  • #9352 — Scalar quantization Dot/Inner Product distance metric scaling behavior: The PR's additions to MetadataInt8::get_shift differentiate shift computation between Dot/Cosine and L1/L2, directly targeting the scaling invariance problem, as evidenced by the newly added positive scaling invariance tests that validate Dot and Cosine retain their expected scaling behavior.

Suggested reviewers

  • IvanPleshkov
  • JojiiOfficial

Poem

🐇 Hop hop, the offset bug now fades,
No more L2 scores in endless trades.
L1 and L2 stand firm and true—
Translation-invariant through and through!
We test them well with shifting scales,
While Dot and Cosine tell their tales. 🌿✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the core fix: adjusting the L2 quantized score shift calculation to address the translation invariance bug.
Description check ✅ Passed The description provides a clear summary of the fix, explains the mathematical reasoning for the change, details the regression tests added, and references the linked issue.
Linked Issues check ✅ Passed The PR directly addresses issue #9515 by fixing the L2 shift computation in MetadataInt8::get_shift to return 0.0 instead of actual_dim * offset^2, ensuring translation invariance. Comprehensive metamorphic tests validate this fix and extend coverage to L1/Dot distance types with scaling behavior validation.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue #9515: fixing L2 shift computation in encoded_vectors_u8.rs and adding targeted regression tests in test_simple.rs to validate the translation invariance fix.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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.

@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/tests/integration/test_simple.rs (1)

243-290: ⚡ Quick win

Exercise the intended quantile path in this regression test.

With vectors_count = 80, the Some(0.99) quantile argument is ignored because find_quantile_interval returns None for counts below 127. Bump the count to at least 127 so this test covers the quantile-based scalar encoding path it appears to target.

Proposed test-strengthening change
-        let vectors_count = 80;
+        let vectors_count = 129;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/quantization/tests/integration/test_simple.rs` around lines 243 - 290,
The test sets vectors_count to 80, which is below the minimum threshold of 127
required by find_quantile_interval to exercise the quantile-based scalar
encoding path that the test intends to cover. Increase the vectors_count
variable from 80 to at least 127 so that when EncodedVectorsU8::encode is called
with Some(0.99) as the quantile argument, the quantile-based encoding path is
actually executed and tested rather than being ignored.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@lib/quantization/tests/integration/test_simple.rs`:
- Around line 243-290: The test sets vectors_count to 80, which is below the
minimum threshold of 127 required by find_quantile_interval to exercise the
quantile-based scalar encoding path that the test intends to cover. Increase the
vectors_count variable from 80 to at least 127 so that when
EncodedVectorsU8::encode is called with Some(0.99) as the quantile argument, the
quantile-based encoding path is actually executed and tested rather than being
ignored.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: d3304bcc-68c2-49f9-ab4b-dbe6e13c3201

📥 Commits

Reviewing files that changed from the base of the PR and between 1bab9c8 and be71f83.

📒 Files selected for processing (2)
  • lib/quantization/src/encoded_vectors_u8.rs
  • lib/quantization/tests/integration/test_simple.rs

@generall
generall requested a review from IvanPleshkov June 19, 2026 17:02
@generall

Copy link
Copy Markdown
Member

cc @IvanPleshkov

@RitwijParmar

Copy link
Copy Markdown
Contributor Author

Expanded the regression into affine metamorphic score checks, not just the original translated-L2 case.

It now covers translation invariance for L1/L2 and positive scaling behavior for Dot/L1/L2, each with normal and inverted scoring. I also bumped the fixture size so the 0.99 quantile path is actually exercised.

Focused check passes: cargo test -p quantization scalar_quantized.

@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/tests/integration/test_simple.rs (1)

352-373: 💤 Low value

Consider adding DistanceType::Cosine to positive scaling test for completeness.

While Cosine shares the same get_shift implementation path with Dot (both return actual_dim * offset²), explicitly testing Cosine would improve test coverage comprehensiveness and align with the PR objectives mentioning "each distance metric is tested."

Expected scale factor for Cosine would be 6.25 (same as Dot).

📋 Optional test case additions
     #[rstest]
     #[case(DistanceType::Dot, false, 6.25)]
     #[case(DistanceType::Dot, true, 6.25)]
+    #[case(DistanceType::Cosine, false, 6.25)]
+    #[case(DistanceType::Cosine, true, 6.25)]
     #[case(DistanceType::L1, false, 2.5)]
     #[case(DistanceType::L1, true, 2.5)]
     #[case(DistanceType::L2, false, 6.25)]
     #[case(DistanceType::L2, true, 6.25)]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/quantization/tests/integration/test_simple.rs` around lines 352 - 373,
The test function test_scalar_quantized_scores_follow_positive_scaling is
missing parametrized test cases for DistanceType::Cosine. Add two additional
#[case] attributes to the rstest macro before the function definition: one for
DistanceType::Cosine with invert=false and expected_scale=6.25, and another for
DistanceType::Cosine with invert=true and expected_scale=6.25, to ensure
consistent test coverage across all distance metrics including Cosine.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@lib/quantization/tests/integration/test_simple.rs`:
- Around line 352-373: The test function
test_scalar_quantized_scores_follow_positive_scaling is missing parametrized
test cases for DistanceType::Cosine. Add two additional #[case] attributes to
the rstest macro before the function definition: one for DistanceType::Cosine
with invert=false and expected_scale=6.25, and another for DistanceType::Cosine
with invert=true and expected_scale=6.25, to ensure consistent test coverage
across all distance metrics including Cosine.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: c4464a90-5534-4888-8e26-7d730d036bb9

📥 Commits

Reviewing files that changed from the base of the PR and between 91b3a39 and 0e2ff98.

📒 Files selected for processing (2)
  • lib/quantization/src/encoded_vectors_u8.rs
  • lib/quantization/tests/integration/test_simple.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/quantization/src/encoded_vectors_u8.rs

@IvanPleshkov

Copy link
Copy Markdown
Contributor

@RitwijParmar, fix please CI to make it possible to merge, cargo +nightly fmt --all

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

This is a totally correct fix. L2 shift should be zero, like L1.

@RitwijParmar

Copy link
Copy Markdown
Contributor Author

Thanks Ivan. Ran cargo +nightly fmt --all and pushed it.

Also checked cargo +nightly fmt --all --check and cargo test -p quantization scalar_quantized locally.

@IvanPleshkov

Copy link
Copy Markdown
Contributor

@RitwijParmar

Copy link
Copy Markdown
Contributor Author

Fixed the Clippy needless borrow too.

Checked cargo clippy -p quantization --test integration -- -D warnings, cargo +nightly fmt --all --check, and cargo test -p quantization scalar_quantized locally.

@IvanPleshkov

Copy link
Copy Markdown
Contributor

Thanks for the contribution!

@IvanPleshkov
IvanPleshkov merged commit 014c158 into qdrant:dev Jun 23, 2026
15 checks passed
generall pushed a commit that referenced this pull request Aug 4, 2026
* fix scalar L2 quantized score shift

* Format scalar quantization imports

* Fix quantization test clippy
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.

3 participants