Skip to content

[mmr] compute similarities lazily#6877

Merged
generall merged 2 commits intodevfrom
lazy-similarity-matrix-mmr
Jul 17, 2025
Merged

[mmr] compute similarities lazily#6877
generall merged 2 commits intodevfrom
lazy-similarity-matrix-mmr

Conversation

@coszio
Copy link
Contributor

@coszio coszio commented Jul 15, 2025

Another optimization for MMR.

MMR is usually used as a reranker with more candidate points than selected points.

Without this PR, MMR computes the entire similarity matrix by calculating m*m/2 similiarites, where m=# of candidates.

However, what we actually need to compute is m*n/2 similarities, where m=# of candidates, and n=limit.

For cases where there are many candidates and small limit, this improves performance more dramatically, for example:

Case dev (similarities, request timing) PR (similarities, request_timing)
limit=10, candidates_limit=1000 1M, 44.8ms 10k, 16.1ms
limit=10, candidates_limit=500 250k, 19.7ms 5k, 12.4ms
limit=10, candidates_limit=100 10k, 9.5ms 1k, 9.0ms

Notice that PR is a bit slower on fewer similarities (10k on dev is faster than 5k on PR). But I believe this is fine considering the amortization for larger number of candidates.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 15, 2025

📝 Walkthrough

Walkthrough

This change introduces a new LazyMatrix struct in Rust for computing and caching similarity scores between vectors on demand, replacing the previous approach that used an eagerly computed symmetric similarity matrix. The LazyMatrix is constructed from a collection of vectors and a storage backend, storing computed similarities in a symmetric matrix of optional values to avoid redundant calculations. The Maximal Marginal Relevance (MMR) implementation is refactored to use this lazy matrix, updating function signatures and error handling accordingly, and consolidating similarity computation and MMR calculation into a single blocking task. The module structure is updated to include and re-export the relevant functionality.

Possibly related PRs

  • [MMR] Optimize SymmetricMatrix #6813: Optimizes the underlying symmetric matrix storage by using a flattened vector for eager computation, whereas the current PR introduces a lazy evaluation approach for similarity matrices.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cee7176 and 16c924b.

📒 Files selected for processing (1)
  • lib/collection/src/collection/mmr/lazy_matrix.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/collection/src/collection/mmr/lazy_matrix.rs
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
lib/collection/src/collection/mmr/lazy_matrix.rs (1)

13-17: Valid performance concern about memory overhead.

The use of Option<ScoreType> indeed adds memory overhead. For large matrices, consider using a sparse representation (e.g., HashMap) or a separate BitVec to track computed entries if memory becomes a bottleneck.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between edb460a and cee7176.

📒 Files selected for processing (3)
  • lib/collection/src/collection/mmr/lazy_matrix.rs (1 hunks)
  • lib/collection/src/collection/mmr/maximum_marginal_relevance.rs (8 hunks)
  • lib/collection/src/collection/mmr/mod.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
lib/collection/src/collection/mmr/mod.rs (1)
Learnt from: generall
PR: qdrant/qdrant#6088
File: lib/segment/src/index/field_index/mod.rs:18-18
Timestamp: 2025-03-03T15:54:45.553Z
Learning: In the Qdrant codebase, modules can be organized as directories with their own `mod.rs` file, rather than single files, following standard Rust module organization patterns.
lib/collection/src/collection/mmr/maximum_marginal_relevance.rs (4)
Learnt from: generall
PR: qdrant/qdrant#6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Learnt from: coszio
PR: qdrant/qdrant#6528
File: lib/posting_list/src/view.rs:118-118
Timestamp: 2025-05-19T14:40:20.068Z
Learning: In the bitpacking crate, the BitPacker::decompress_strictly_sorted function takes an Option<PointOffsetType> as its first parameter, which means using checked_sub(1) without unwrapping is intentional and correct.
Learnt from: generall
PR: qdrant/qdrant#6479
File: lib/segment/src/index/hnsw_index/graph_layers_builder.rs:137-182
Timestamp: 2025-05-30T15:26:14.488Z
Learning: In the subgraph_connectivity method in graph_layers_builder.rs, the previous_visited_points vector and visited BitVec entry point marking are automatically re-initialized at the start of each retry loop iteration, so manual clearing is not needed.
Learnt from: xzfc
PR: qdrant/qdrant#6245
File: lib/segment/src/vector_storage/async_raw_scorer.rs:48-56
Timestamp: 2025-04-22T23:19:51.232Z
Learning: In the AsyncRawScorerImpl implementation, the unwrap() call on read_vectors_async results is intentional, with an explanatory comment noting that this experimental feature is meant to crash rather than silently fall back to synchronous implementation.
🧬 Code Graph Analysis (2)
lib/collection/src/collection/mmr/mod.rs (1)
lib/collection/src/collection/mmr/maximum_marginal_relevance.rs (1)
  • mmr_from_points_with_vector (40-117)
lib/collection/src/collection/mmr/maximum_marginal_relevance.rs (1)
lib/collection/src/collection/mmr/lazy_matrix.rs (2)
  • new (23-47)
  • vectors (35-45)
🔇 Additional comments (7)
lib/collection/src/collection/mmr/mod.rs (1)

1-4: LGTM! Clean module organization.

The module structure follows standard Rust patterns with appropriate submodule declarations and public API re-export.

lib/collection/src/collection/mmr/lazy_matrix.rs (2)

49-56: LGTM! Efficient lazy evaluation with caching.

The implementation correctly implements lazy evaluation with caching. Note that the mutable self requirement makes this unsuitable for concurrent access, but it's fine for the current single-threaded usage within the blocking task.


58-60: LGTM! Simple delegation to scorer.

The implementation correctly delegates to the appropriate scorer. The cast to PointOffsetType is safe in practice given the expected size constraints.

lib/collection/src/collection/mmr/maximum_marginal_relevance.rs (4)

92-116: LGTM! Consistent error handling.

The changes properly update the error handling to use CollectionResult and CollectionError consistently throughout the async function.


179-198: LGTM! Clean refactoring to use LazyMatrix.

The function now properly delegates similarity matrix creation to the LazyMatrix implementation, maintaining good separation of concerns.


212-219: LGTM! Correct implementation of lazy similarity computation.

The changes properly implement the lazy evaluation pattern:

  • Function visibility reduced to private as it's an internal implementation detail
  • Takes ownership of LazyMatrix as required for mutable access
  • Uses get_similarity to compute similarities on-demand

This achieves the PR's goal of computing only mn/2 similarities instead of mm/2.

Also applies to: 259-261


17-17: Error type consistency across lib/collection confirmed

  • No remaining references to SegmentResult in lib/collection/.
  • All async APIs in lib/collection/ consistently return CollectionResult<…>.

No further changes needed.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@generall generall merged commit 4f3d64a into dev Jul 17, 2025
16 checks passed
@generall generall deleted the lazy-similarity-matrix-mmr branch July 17, 2025 08:41
@generall generall added this to the MMR milestone Jul 17, 2025
generall pushed a commit that referenced this pull request Jul 17, 2025
* compute similarities lazily

* Update lib/collection/src/collection/mmr/lazy_matrix.rs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This was referenced Jul 17, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 26, 2025
3 tasks
@coderabbitai coderabbitai bot mentioned this pull request Oct 22, 2025
10 tasks
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