Skip to content

[MMR] Optimize SymmetricMatrix#6813

Merged
coszio merged 8 commits intodevfrom
add_diagonal_matrix_for_mmr
Jul 11, 2025
Merged

[MMR] Optimize SymmetricMatrix#6813
coszio merged 8 commits intodevfrom
add_diagonal_matrix_for_mmr

Conversation

@JojiiOfficial
Copy link
Contributor

Builds on #6797

Optimizes the diagonal matrix used in MMR to only store half of the data in a single, flattened vector.

@JojiiOfficial JojiiOfficial force-pushed the add_diagonal_matrix_for_mmr branch from 7e68a29 to a7815c4 Compare July 4, 2025 15:40
@JojiiOfficial JojiiOfficial marked this pull request as ready for review July 4, 2025 15:40
@JojiiOfficial JojiiOfficial requested a review from coszio July 4, 2025 15:40
@coszio coszio force-pushed the expose-mmr branch 2 times, most recently from 1095229 to 3a256e9 Compare July 8, 2025 01:13
@coszio coszio force-pushed the add_diagonal_matrix_for_mmr branch from a7815c4 to 64574c3 Compare July 8, 2025 16:07
if !upper_offsets.is_empty() {
let mut scores = vec![0.0; upper_offsets.len()];
raw_scorers[i].score_points(&upper_offsets, &mut scores);
scores.resize(upper_offsets.len(), 0.0);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Also added a minor optimization here to reduce allocations and share scores across loops.

Note: we don't need to clear it because we always overwrite all items before using them.

Copy link
Contributor

@coszio coszio left a comment

Choose a reason for hiding this comment

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

Let's merge after #6797

@coszio coszio changed the title [MMR] Optimize DiagonalMatrix [MMR] Optimize SymmetricMatrix Jul 9, 2025
Base automatically changed from expose-mmr to dev July 11, 2025 14:39
@JojiiOfficial JojiiOfficial force-pushed the add_diagonal_matrix_for_mmr branch from 5e26ae9 to 6aa9f13 Compare July 11, 2025 15:25
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 11, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new generic SymmetricMatrix struct that efficiently stores symmetric matrices by keeping only the upper triangular elements in a flattened vector, with methods for creation, value access, and mutation. This struct is publicly exposed via a new symmetric_matrix module. The MMR (Maximal Marginal Relevance) implementation is refactored to replace the previous Vec<Vec<ScoreType>> similarity matrix with this SymmetricMatrix type, now aliased as SimilarityMatrix. Corresponding function signatures and internal logic are updated to use the new matrix abstraction, with similarity values accessed and modified through its API. Tests verify correct behavior of the symmetric matrix implementation.


📜 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 39ab0eb and 378e9d5.

📒 Files selected for processing (1)
  • lib/collection/src/collection/mmr.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/collection/src/collection/mmr.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: test-consistency
  • GitHub Check: test-consensus-compose
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: integration-tests-consensus
  • GitHub Check: integration-tests
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: storage-compat-test
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: rust-tests-no-rocksdb (ubuntu-latest)
  • GitHub Check: lint
✨ 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: 0

🧹 Nitpick comments (1)
lib/collection/src/common/symmetric_matrix.rs (1)

53-72: Mathematically correct index calculation.

The index calculation logic is sound:

  • Uses the formula ((row * size) + column) - triangular(row) to map 2D coordinates to the flattened upper triangle
  • Triangular number calculation (x * (x + 1)) / 2 is correct
  • Debug assertion helps catch column out-of-bounds during development

Consider adding a debug assertion for row bounds as well for consistency:

 debug_assert!(
     column < self.size,
     "Column index {column} out of bounds for {}x{} matrix",
     self.size,
     self.size
 );
+debug_assert!(
+    row < self.size,
+    "Row index {row} out of bounds for {}x{} matrix",
+    self.size,
+    self.size
+);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6307510 and 6aa9f13.

📒 Files selected for processing (3)
  • lib/collection/src/collection/mmr.rs (6 hunks)
  • lib/collection/src/common/mod.rs (1 hunks)
  • lib/collection/src/common/symmetric_matrix.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: lint
  • GitHub Check: integration-tests
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test-low-resources
  • GitHub Check: test-consensus-compose
  • GitHub Check: integration-tests-consensus
  • GitHub Check: test-consistency
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: storage-compat-test
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: rust-tests-no-rocksdb (ubuntu-latest)
🔇 Additional comments (11)
lib/collection/src/common/mod.rs (1)

14-14: Clean module export addition.

The new symmetric_matrix module export follows the existing pattern and correctly makes the SymmetricMatrix struct publicly available for use in the MMR implementation.

lib/collection/src/common/symmetric_matrix.rs (4)

1-24: Well-designed constructor with proper validation.

The struct definition and constructor are well-implemented:

  • Generic design allows flexibility for different numeric types
  • Proper validation prevents matrices smaller than 2x2 (which wouldn't benefit from the optimization)
  • Clear documentation about the storage approach
  • Correct size calculation using triangular numbers

26-41: Efficient and correct access methods.

The get and set methods properly handle the symmetric matrix abstraction:

  • Both methods correctly delegate to handle_index for symmetry handling
  • Inline annotations are appropriate for performance-critical code
  • The API is intuitive and maintains the illusion of a full 2D matrix

43-51: Correct symmetry handling.

The handle_index method correctly ensures that matrix accesses always target the upper triangle by swapping indices when column < row. This is essential for maintaining the symmetric property while storing only half the data.


75-152: Comprehensive test coverage validates the implementation.

The test suite is excellent:

  • test_matrix() verifies basic functionality and symmetry
  • test_oob() ensures proper bounds checking
  • test_matrix_vs_naive_implementation() validates correctness against a reference implementation
  • Tests cover diagonal elements, off-diagonal elements, and edge cases
lib/collection/src/collection/mmr.rs (6)

18-24: Clean integration with appropriate type alias.

The import and type alias definition are well-structured:

  • Import follows Rust conventions
  • SimilarityMatrix alias makes the domain-specific usage clear
  • Type alias improves code readability in the MMR context

191-191: Function signature correctly updated.

The return type change from Vec<Vec<ScoreType>> to SimilarityMatrix properly reflects the new symmetric matrix abstraction.


205-207: Proper matrix initialization with error handling.

The matrix initialization correctly:

  • Uses SymmetricMatrix::new() with appropriate size and initial value
  • Handles the unwrap safely since the size validation is already performed above
  • Maintains the same semantic behavior (zero-initialized matrix)

225-239: Excellent performance optimization with buffer reuse.

The optimization to reuse the scores buffer across loop iterations is well-implemented:

  • Preallocates buffer once outside the loop
  • Reuses different slices of the buffer for each iteration
  • Reduces memory allocations while maintaining correctness
  • Properly sets values using the new set method

261-261: Parameter type correctly updated.

The function parameter type change to &SimilarityMatrix maintains the same interface semantics while using the new optimized data structure.


305-305: Correct API usage for matrix access.

The change from direct 2D indexing to using the get method correctly adapts to the new symmetric matrix API while maintaining the same functionality.

@coszio coszio merged commit d9a83cd into dev Jul 11, 2025
18 checks passed
@coszio coszio deleted the add_diagonal_matrix_for_mmr branch July 11, 2025 21:44
@generall generall added this to the MMR milestone Jul 17, 2025
generall pushed a commit that referenced this pull request Jul 17, 2025
* Add DiagonalMatrix for mmr

* Add column OOB checking in debug mode

* Fix Clippy; Reduce allocations in scorers loop

* rename to symmetric matrix

* extra test

* Don't call 'resize' in each iteration

* Clippy

* review nits

---------

Co-authored-by: Luis Cossío <luis.cossio@outlook.com>
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