Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复 BM25 算法计算得分超过 1 导致记忆相似度计算错误的问题 #350

Merged
merged 8 commits into from
Jan 1, 2025

Conversation

Hoshino-Yumetsuki
Copy link
Contributor

@Hoshino-Yumetsuki Hoshino-Yumetsuki commented Jan 1, 2025

Summary by CodeRabbit

  • Improvements
    • Enhanced similarity calculation algorithm for more precise document scoring.
    • Updated BM25 scoring method to include bidirectional scoring and improved error handling for empty inputs.
    • Adjusted similarity weights for more balanced scoring across different metrics.

Copy link

coderabbitai bot commented Jan 1, 2025

Warning

Rate limit exceeded

@Hoshino-Yumetsuki has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b2d28e9 and a9d6cc7.

📒 Files selected for processing (1)
  • packages/long-memory/src/similarity.ts (3 hunks)

Walkthrough

The pull request introduces modifications to the calculateBM25Similarity method within the SimilarityCalculator class. Key changes include adjustments to similarity weights, improved error handling that returns a score of 0 for empty tokenized inputs, a restructuring of the scoring mechanism to compute BM25 scores bidirectionally, and an updated Inverse Document Frequency (IDF) calculation that includes an additional 1 in the denominator.

Changes

File Change Summary
packages/long-memory/src/similarity.ts Modified calculateBM25Similarity method:
- Adjusted similarity weights for cosine, levenshtein, jaccard, and bm25
- Added error handling for empty tokenized inputs
- Introduced bidirectional scoring with score1to2 and score2to1
- Updated IDF calculation to include 1 in the denominator

Poem

🐰 A Rabbit's Ode to Similarity Scoring 🔍

In lines of code, a tweak so slight,
BM25's math takes a new height
One plus, some lengths combined with care
Similarity's dance, beyond compare!

hop hop 🦊📊


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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

@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)
packages/long-memory/src/similarity.ts (1)

219-219: Split the expression for improved readability.
Although the updated IDF formula helps avoid negative or undefined values, consider breaking the expression into multiple lines to make the logic clearer and aid maintainability.

A possible change:

-const idf = Math.log((2 - docFreq + epsilon) / (docFreq + epsilon) + 1)
+const idf = Math.log(
+  (2 - docFreq + epsilon) / (docFreq + epsilon) + 1
+)
🧰 Tools
🪛 eslint

[error] 219-219: Replace (2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1 with ⏎················(2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1⏎············

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 219-219: packages/long-memory/src/similarity.ts#L219
Replace (2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1 with ⏎················(2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1⏎············ (prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7146352 and 97e0698.

📒 Files selected for processing (1)
  • packages/long-memory/src/similarity.ts (1 hunks)
🧰 Additional context used
🪛 eslint
packages/long-memory/src/similarity.ts

[error] 219-219: Replace (2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1 with ⏎················(2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1⏎············

(prettier/prettier)

🪛 GitHub Check: CodeFactor
packages/long-memory/src/similarity.ts

[warning] 219-219: packages/long-memory/src/similarity.ts#L219
Replace (2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1 with ⏎················(2·-·docFreq·+·epsilon)·/·(docFreq·+·epsilon)·+·1⏎············ (prettier/prettier)

🔇 Additional comments (2)
packages/long-memory/src/similarity.ts (2)

224-224: Confirm BM25 parameter choices.
The denominator follows the standard BM25 formula with length normalization. However, confirm these parameters (k1, b, and avgDocLength) reflect the intended effect for your use case, as any mismatch can skew the results.


229-230: Validate the new normalization factor’s impact on scores.
Switching from a log-based normalization to doc1Length + doc2Length likely prevents scores from exceeding 1 but may compress differences in longer texts. Ensure it aligns with your objective of bounding scores without overly diminishing them for large inputs.

Copy link

@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)
packages/long-memory/src/similarity.ts (1)

220-220: Fix formatting: Add line break after opening parenthesis

The static analysis tools indicate a formatting issue. Add a line break after the opening parenthesis for consistency with the codebase style.

-            const idf = Math.log((2 - docFreq + epsilon) / (docFreq + epsilon) + 1)
+            const idf = Math.log(
+                (2 - docFreq + epsilon) / (docFreq + epsilon) + 1
+            )
🧰 Tools
🪛 eslint

[error] 220-220: Insert ⏎············

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 220-220: packages/long-memory/src/similarity.ts#L220
Insert ⏎············ (prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 97e0698 and 96a73df.

📒 Files selected for processing (1)
  • packages/long-memory/src/similarity.ts (1 hunks)
🧰 Additional context used
🪛 eslint
packages/long-memory/src/similarity.ts

[error] 220-220: Insert ⏎············

(prettier/prettier)

🪛 GitHub Check: CodeFactor
packages/long-memory/src/similarity.ts

[warning] 220-220: packages/long-memory/src/similarity.ts#L220
Insert ⏎············ (prettier/prettier)

🔇 Additional comments (2)
packages/long-memory/src/similarity.ts (2)

230-231: Approve normalization factor change

The new normalization using doc1Length + doc2Length is more appropriate than the previous Math.log(2) * doc1Length because:

  1. It considers both documents' lengths, making the score more balanced
  2. It helps prevent scores from exceeding 1, which was the original issue
  3. It's a standard approach in BM25 variants when comparing document pairs

219-220: Verify the IDF calculation modification

The addition of + 1 inside the logarithm ensures the IDF score remains positive and properly weighted. However, let's verify this change:

  1. When docFreq = 0 (term appears in no other docs):

    • New IDF = log((2 - 0 + 0.25)/(0 + 0.25) + 1) ≈ log(9) ≈ 2.2
    • This is reasonable for unique terms
  2. When docFreq = 1 (term appears in other doc):

    • New IDF = log((2 - 1 + 0.25)/(1 + 0.25) + 1) ≈ log(2) ≈ 0.7
    • This appropriately reduces the weight
✅ Verification successful

IDF calculation modification is mathematically sound and properly implemented

The IDF modification in the BM25 implementation is correct and well-justified:

  1. The formula log((2 - docFreq + epsilon) / (docFreq + epsilon) + 1) ensures:

    • Maximum IDF when term is unique (docFreq = 0)
    • Decreasing IDF as term appears in both documents (docFreq = 1)
    • Smoothing via epsilon (0.25) prevents division by zero
    • Adding 1 inside log ensures positive IDF values
  2. The implementation properly integrates with:

    • Standard BM25 parameters (k1 = 1.5, b = 0.75)
    • Length normalization using average document length
    • Final score normalization using combined document lengths

The modification achieves its goal of keeping scores properly bounded while maintaining the relative importance of terms.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other BM25 implementations in the codebase for comparison
rg -l "BM25|bm25" --type ts

Length of output: 68


Script:

#!/bin/bash
# Let's examine the entire BM25 implementation to understand the context better
rg -A 20 -B 10 "calculateBM25Similarity" packages/long-memory/src/similarity.ts

Length of output: 2091


Script:

#!/bin/bash
# Let's see the rest of the BM25 implementation to understand the complete calculation
rg -A 40 "tokens2.forEach" packages/long-memory/src/similarity.ts

Length of output: 1482

🧰 Tools
🪛 eslint

[error] 220-220: Insert ⏎············

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 220-220: packages/long-memory/src/similarity.ts#L220
Insert ⏎············ (prettier/prettier)

Hoshino-Yumetsuki and others added 2 commits January 1, 2025 17:43
…d handle empty token cases. The scoring now accounts for both directions (doc1 to doc2 and doc2 to doc1) and returns a normalized average score. Additionally, added a check to return 0 for empty token arrays.
Copy link

@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

🔭 Outside diff range comments (1)
packages/long-memory/src/similarity.ts (1)

Add test coverage for BM25 similarity calculation

The codebase lacks test coverage for the BM25 similarity calculation implementation. To ensure the reliability of the changes, you should add test cases that cover:

  • Empty documents comparison (tokens1.length === 0 || tokens2.length === 0)
  • Documents with no common terms
  • Documents with all terms in common
  • Documents with significantly different lengths
  • Edge cases with special characters
  • Verification that scores are always normalized between 0 and 1

Example test structure:

describe('calculateSimilarity', () => {
  it('should return 0 for empty documents', () => {
    expect(calculateSimilarity('', 'test')).toBe(0);
    expect(calculateSimilarity('test', '')).toBe(0);
  });
  
  it('should return 0 for documents with no common terms', () => {
    expect(calculateSimilarity('abc def', 'xyz pqr')).toBe(0);
  });
  
  it('should return high similarity for identical documents', () => {
    expect(calculateSimilarity('test document', 'test document')).toBeCloseTo(1);
  });
  
  it('should handle documents with different lengths', () => {
    const score = calculateSimilarity('short text', 'short text with more words');
    expect(score).toBeGreaterThan(0);
    expect(score).toBeLessThan(1);
  });
});
🔗 Analysis chain

Line range hint 196-257: Verify the fix with comprehensive test cases

While the implementation looks correct, please ensure it's tested with various edge cases:

  1. Documents with no common terms
  2. Documents with all common terms
  3. Documents with significantly different lengths
  4. Documents with special characters or non-standard tokens

Let me analyze the test coverage and implementation details to ensure we have proper test cases for the BM25 similarity calculation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing test cases in the codebase
echo "Searching for BM25 test cases..."
rg -l "calculateBM25Similarity|SimilarityCalculator.*test" --type ts

# Look for actual usage patterns
echo "Analyzing usage patterns..."
rg "calculateSimilarity\(|SimilarityCalculator\.calculate\(" --type ts -A 2

Length of output: 931


Script:

#!/bin/bash
# Look for test files
echo "Searching for test files..."
fd "test.*\.(ts|js)" --type f

# Check content of test files if they exist
echo "Checking test file contents..."
rg "describe|it\(" --type ts packages/long-memory/src/__tests__ -A 3 || true

# Look for the actual implementation to understand test coverage needs
echo "Checking implementation details..."
ast-grep --pattern 'export function calculateSimilarity($_) { $$$ }'

Length of output: 470

🧰 Tools
🪛 eslint

[error] 227-227: Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 229-229: Insert ⏎···················

(prettier/prettier)


[error] 234-234: Insert ⏎···················

(prettier/prettier)


[error] 242-242: Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 244-244: Insert ⏎···················

(prettier/prettier)


[error] 249-249: Insert ⏎···················

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 242-242: packages/long-memory/src/similarity.ts#L242
Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················ (prettier/prettier)


[warning] 244-244: packages/long-memory/src/similarity.ts#L244
Insert ⏎··················· (prettier/prettier)


[warning] 249-249: packages/long-memory/src/similarity.ts#L249
Insert ⏎··················· (prettier/prettier)


[warning] 234-234: packages/long-memory/src/similarity.ts#L234
Insert ⏎··················· (prettier/prettier)


[warning] 229-229: packages/long-memory/src/similarity.ts#L229
Insert ⏎··················· (prettier/prettier)


[warning] 227-227: packages/long-memory/src/similarity.ts#L227
Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················ (prettier/prettier)

🧹 Nitpick comments (2)
packages/long-memory/src/similarity.ts (2)

223-236: Consider adding documentation for the IDF formula modification

The implementation is correct, but it would be helpful to add a comment explaining why the IDF formula was modified with + 1 and how the max score calculation helps prevent scores from exceeding 1.

 // 计算 doc1 -> doc2 的方向
 const tf1 = termFreqDoc1.get(term) || 0
 const docFreq1 = (termFreqDoc2.get(term) || 0) > 0 ? 1 : 0
 if (tf1 > 0) {
+    // Add 1 to IDF calculation to ensure non-negative scores and proper normalization
     const idf1 = Math.log((2 - docFreq1 + epsilon) / (docFreq1 + epsilon) + 1)
🧰 Tools
🪛 eslint

[error] 227-227: Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 229-229: Insert ⏎···················

(prettier/prettier)


[error] 234-234: Insert ⏎···················

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 234-234: packages/long-memory/src/similarity.ts#L234
Insert ⏎··················· (prettier/prettier)


[warning] 229-229: packages/long-memory/src/similarity.ts#L229
Insert ⏎··················· (prettier/prettier)


[warning] 227-227: packages/long-memory/src/similarity.ts#L227
Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················ (prettier/prettier)


238-250: Consider extracting the direction calculation into a helper function

The calculation logic for both directions is identical. Consider refactoring into a helper function to improve maintainability and reduce code duplication.

+    private static calculateDirectionalScore(
+        sourceFreq: Map<string, number>,
+        targetFreq: Map<string, number>,
+        sourceLength: number,
+        avgLength: number,
+        k1: number,
+        b: number,
+        epsilon: number
+    ): { score: number; maxScore: number } {
+        let score = 0;
+        let maxScore = 0;
+        const terms = new Set([...sourceFreq.keys(), ...targetFreq.keys()]);
+
+        for (const term of terms) {
+            const tf = sourceFreq.get(term) || 0;
+            const docFreq = (targetFreq.get(term) || 0) > 0 ? 1 : 0;
+            if (tf > 0) {
+                const idf = Math.log((2 - docFreq + epsilon) / (docFreq + epsilon) + 1);
+                const numerator = tf * (k1 + 1);
+                const denominator = tf + k1 * (1 - b + b * (sourceLength / avgLength));
+                score += idf * (numerator / denominator);
+
+                const maxTf = Math.max(tf, targetFreq.get(term) || 0);
+                const maxNumerator = maxTf * (k1 + 1);
+                const maxDenominator = maxTf + k1 * (1 - b + b * (sourceLength / avgLength));
+                maxScore += idf * (maxNumerator / maxDenominator);
+            }
+        }
+        return { score, maxScore };
+    }
🧰 Tools
🪛 eslint

[error] 242-242: Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 244-244: Insert ⏎···················

(prettier/prettier)


[error] 249-249: Insert ⏎···················

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 242-242: packages/long-memory/src/similarity.ts#L242
Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················ (prettier/prettier)


[warning] 244-244: packages/long-memory/src/similarity.ts#L244
Insert ⏎··················· (prettier/prettier)


[warning] 249-249: packages/long-memory/src/similarity.ts#L249
Insert ⏎··················· (prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5859fa7 and 334ea5d.

📒 Files selected for processing (1)
  • packages/long-memory/src/similarity.ts (2 hunks)
🧰 Additional context used
🪛 eslint
packages/long-memory/src/similarity.ts

[error] 227-227: Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 229-229: Insert ⏎···················

(prettier/prettier)


[error] 234-234: Insert ⏎···················

(prettier/prettier)


[error] 242-242: Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 244-244: Insert ⏎···················

(prettier/prettier)


[error] 249-249: Insert ⏎···················

(prettier/prettier)

🪛 GitHub Check: CodeFactor
packages/long-memory/src/similarity.ts

[warning] 242-242: packages/long-memory/src/similarity.ts#L242
Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················ (prettier/prettier)


[warning] 244-244: packages/long-memory/src/similarity.ts#L244
Insert ⏎··················· (prettier/prettier)


[warning] 249-249: packages/long-memory/src/similarity.ts#L249
Insert ⏎··················· (prettier/prettier)


[warning] 234-234: packages/long-memory/src/similarity.ts#L234
Insert ⏎··················· (prettier/prettier)


[warning] 229-229: packages/long-memory/src/similarity.ts#L229
Insert ⏎··················· (prettier/prettier)


[warning] 227-227: packages/long-memory/src/similarity.ts#L227
Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················ (prettier/prettier)

🔇 Additional comments (3)
packages/long-memory/src/similarity.ts (3)

196-198: LGTM: Good defensive programming practice

The early return for empty token arrays prevents potential issues in subsequent calculations and correctly handles edge cases.


216-220: LGTM: Improved bidirectional scoring approach

The introduction of bidirectional scoring with max score tracking is a good solution to handle asymmetric document lengths and ensure proper score normalization.


254-257: LGTM: Proper score normalization

The normalization and averaging of bidirectional scores effectively addresses the original issue of BM25 scores exceeding 1 while maintaining a symmetric similarity measure.

Copy link

@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)
packages/long-memory/src/similarity.ts (1)

216-257: LGTM: Improved BM25 scoring with bidirectional calculation

The implementation effectively addresses the score overflow issue through:

  1. Bidirectional scoring that accounts for asymmetric document lengths
  2. Proper score normalization in both directions
  3. Modified IDF calculation that bounds the scores

Consider these readability improvements:

  1. Add documentation explaining the mathematical reasoning:
 private static calculateBM25Similarity(s1: string, s2: string): number {
+    // BM25 parameters
     const k1 = 1.5 // 词频饱和参数
     const b = 0.75 // 文档长度归一化参数
     const epsilon = 0.25 // 平滑因子

+    // Bidirectional BM25 scoring:
+    // 1. Calculate scores in both directions (doc1->doc2 and doc2->doc1)
+    // 2. Normalize each score using its maximum possible score
+    // 3. Average the normalized scores for final similarity
+    // This approach ensures:
+    // - Scores are bounded between 0 and 1
+    // - Asymmetric document lengths are properly handled
  1. Extract common calculations into helper functions:
private static calculateDirectionalBM25Score(
    sourceFreq: Map<string, number>,
    targetFreq: Map<string, number>,
    sourceLength: number,
    avgLength: number,
    k1: number,
    b: number,
    epsilon: number
): { score: number; maxScore: number } {
    let score = 0;
    let maxScore = 0;
    
    for (const [term, tf] of sourceFreq.entries()) {
        const docFreq = (targetFreq.get(term) || 0) > 0 ? 1 : 0;
        const idf = Math.log((2 - docFreq + epsilon) / (docFreq + epsilon) + 1);
        const numerator = tf * (k1 + 1);
        const denominator = tf + k1 * (1 - b + b * (sourceLength / avgLength));
        score += idf * (numerator / denominator);

        const maxTf = Math.max(tf, targetFreq.get(term) || 0);
        const maxNumerator = maxTf * (k1 + 1);
        const maxDenominator = maxTf + k1 * (1 - b + b * (sourceLength / avgLength));
        maxScore += idf * (maxNumerator / maxDenominator);
    }
    
    return { score, maxScore };
}
🧰 Tools
🪛 eslint

[error] 227-227: Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 229-229: Insert ⏎···················

(prettier/prettier)


[error] 234-234: Insert ⏎···················

(prettier/prettier)


[error] 242-242: Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 244-244: Insert ⏎···················

(prettier/prettier)


[error] 249-249: Insert ⏎···················

(prettier/prettier)

🪛 GitHub Check: CodeFactor

[warning] 242-242: packages/long-memory/src/similarity.ts#L242
Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················ (prettier/prettier)


[warning] 244-244: packages/long-memory/src/similarity.ts#L244
Insert ⏎··················· (prettier/prettier)


[warning] 249-249: packages/long-memory/src/similarity.ts#L249
Insert ⏎··················· (prettier/prettier)


[warning] 234-234: packages/long-memory/src/similarity.ts#L234
Insert ⏎··················· (prettier/prettier)


[warning] 229-229: packages/long-memory/src/similarity.ts#L229
Insert ⏎··················· (prettier/prettier)


[warning] 227-227: packages/long-memory/src/similarity.ts#L227
Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················ (prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 334ea5d and b2d28e9.

📒 Files selected for processing (1)
  • packages/long-memory/src/similarity.ts (3 hunks)
🧰 Additional context used
🪛 eslint
packages/long-memory/src/similarity.ts

[error] 227-227: Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 229-229: Insert ⏎···················

(prettier/prettier)


[error] 234-234: Insert ⏎···················

(prettier/prettier)


[error] 242-242: Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················

(prettier/prettier)


[error] 244-244: Insert ⏎···················

(prettier/prettier)


[error] 249-249: Insert ⏎···················

(prettier/prettier)

🪛 GitHub Check: CodeFactor
packages/long-memory/src/similarity.ts

[warning] 242-242: packages/long-memory/src/similarity.ts#L242
Replace (2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1 with ⏎····················(2·-·docFreq2·+·epsilon)·/·(docFreq2·+·epsilon)·+·1⏎················ (prettier/prettier)


[warning] 244-244: packages/long-memory/src/similarity.ts#L244
Insert ⏎··················· (prettier/prettier)


[warning] 249-249: packages/long-memory/src/similarity.ts#L249
Insert ⏎··················· (prettier/prettier)


[warning] 234-234: packages/long-memory/src/similarity.ts#L234
Insert ⏎··················· (prettier/prettier)


[warning] 229-229: packages/long-memory/src/similarity.ts#L229
Insert ⏎··················· (prettier/prettier)


[warning] 227-227: packages/long-memory/src/similarity.ts#L227
Replace (2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1 with ⏎····················(2·-·docFreq1·+·epsilon)·/·(docFreq1·+·epsilon)·+·1⏎················ (prettier/prettier)

🔇 Additional comments (2)
packages/long-memory/src/similarity.ts (2)

8-11: LGTM: Weight adjustments align with PR objective

The increased weights for cosine (0.35) and BM25 (0.35) similarities, balanced by reduced weights for Levenshtein (0.15) and Jaccard (0.15), appropriately emphasize the more reliable metrics for memory similarity calculation.


196-198: LGTM: Added defensive check for empty tokens

Good addition of an early return for empty token arrays, preventing potential issues in subsequent calculations and aligning with the mathematical intuition that similarity with empty text should be 0.

@dingyi222666 dingyi222666 merged commit 489ad90 into ChatLunaLab:v1-dev Jan 1, 2025
3 of 4 checks passed
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