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

Calculate official hotpot EM and F1 scores #292

Merged
merged 1 commit into from
Dec 10, 2024

Conversation

alekszievr
Copy link
Contributor

@alekszievr alekszievr commented Dec 10, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new evaluation metrics: F1 score and exact match score for enhanced performance assessment.
    • Added command-line argument help for metric selection in evaluation.
    • New file containing functions for normalizing answers and calculating evaluation metrics for the HotpotQA dataset.
  • Bug Fixes

    • Improved error handling for metric retrieval to ensure correct instantiation.
  • Documentation

    • Enhanced help descriptions for command-line arguments related to metrics.

Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Walkthrough

The changes in this pull request introduce new evaluation metrics and enhance existing functionalities in the evals module. Key modifications include the addition of two classes for F1 and exact match scoring in evals/deepeval_metrics.py, improvements to command-line argument handling in evals/eval_on_hotpot.py, and the introduction of a new metrics module in evals/official_hotpot_metrics.py. These updates collectively enhance the evaluation capabilities for the HotpotQA dataset.

Changes

File Change Summary
evals/deepeval_metrics.py - Added classes: f1_score_metric, em_score_metric with methods for scoring and success checks.
- Updated import statements and reformatted correctness_metric initialization.
evals/eval_on_hotpot.py - Enhanced command-line argument parsing for --metric with a detailed help description.
- Improved error handling for metric class instantiation.
evals/official_hotpot_metrics.py - Introduced functions for normalizing answers and calculating F1 and exact match scores.
- Added functions for updating metrics based on predictions and ground truth values.

Possibly related PRs

  • Feat/cog-544 eval on swe bench #232: The changes in this PR involve enhancements to evaluation metrics and functionalities that could relate to the new metrics introduced in the main PR, particularly since both involve evaluation processes and metrics handling.

Suggested reviewers

  • hajdul88
  • lxobr

Poem

🐰 In the meadow where metrics bloom,
New scores arise, dispelling gloom.
F1 and exact match take their stand,
Enhancing evaluations, oh so grand!
With each test case, we hop with glee,
Metrics dancing, wild and free! 🌼


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. (Experiment)
  • @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: 3

🧹 Outside diff range and nitpick comments (4)
evals/deepeval_metrics.py (1)

49-51: Docstring Formatting

The docstring does not follow PEP 257 conventions. The first line should be a concise summary.

Reformat the docstring for clarity:

 """Exact Match score taken directly from the official hotpot benchmark 
 implementation and wrapped into a deepeval metric."""
+"""
+Exact Match score metric from the official HotpotQA benchmark, wrapped into a Deepeval metric.
+"""
evals/official_hotpot_metrics.py (1)

10-11: Consider Using the Standard json Module

The use of ujson might introduce compatibility issues and does not support all features of the standard json module.

Unless there's a specific performance requirement, consider using the built-in json module:

-import ujson as json
+import json
evals/eval_on_hotpot.py (2)

115-116: Avoid Backslashes in Multiline Strings

Using backslashes for line continuation in strings can lead to syntax errors or accidental whitespace issues.

Use implicit string concatenation within parentheses for cleaner code:

 parser.add_argument("--metric", type=str, default="correctness_metric",
-                    help="Valid options are Deepeval metrics (e.g. AnswerRelevancyMetric) \
-                          and metrics defined in evals/deepeval_metrics.py, e.g. f1_score_metric")
+                    help=("Valid options are Deepeval metrics (e.g., AnswerRelevancyMetric) "
+                          "and metrics defined in evals/deepeval_metrics.py, e.g., f1_score_metric"))

125-126: Ensure Consistent Metric Instantiation

Currently, the code checks if metric is a type before instantiation. This can be simplified for clarity.

Assuming all metrics should be instantiated, remove the type check:

 try:
     metric = getattr(deepeval.metrics, args.metric)
 except AttributeError:
     metric = getattr(evals.deepeval_metrics, args.metric)
 
-if isinstance(metric, type):
-    metric = metric()
+metric = metric()

This ensures that metric is always an instance of the metric class.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d85165 and 20ff0e6.

📒 Files selected for processing (3)
  • evals/deepeval_metrics.py (1 hunks)
  • evals/eval_on_hotpot.py (2 hunks)
  • evals/official_hotpot_metrics.py (1 hunks)

Comment on lines +19 to +46
class f1_score_metric(BaseMetric):

"""F1 score taken directly from the official hotpot benchmark
implementation and wrapped into a deepeval metric."""

def __init__(self, threshold: float = 0.5):
self.threshold = threshold

def measure(self, test_case: LLMTestCase):
f1, precision, recall = f1_score(
prediction=test_case.actual_output,
ground_truth=test_case.expected_output,
)
self.score = f1
self.success = self.score >= self.threshold
return self.score

# Reusing regular measure as async F1 score is not implemented
async def a_measure(self, test_case: LLMTestCase):
return self.measure(test_case)

def is_successful(self):
return self.success

@property
def __name__(self):
return "Official hotpot F1 score"

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential Blocking in Asynchronous Methods

The a_measure methods in both f1_score_metric and em_score_metric classes directly call the synchronous measure method. This could block the event loop if measure involves long-running operations.

Consider making the measure method asynchronous if it performs I/O-bound or time-consuming tasks. Alternatively, you can offload the synchronous method to a thread using asyncio.to_thread:

async def a_measure(self, test_case: LLMTestCase):
    return await asyncio.to_thread(self.measure, test_case)

Comment on lines +43 to +45
@property
def __name__(self):
return "Official hotpot F1 score"
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Rename __name__ Property to Avoid Conflicts

Overriding the special __name__ attribute can lead to confusion and unexpected behavior since __name__ is a built-in attribute in Python.

Rename the property to avoid shadowing the built-in attribute:

 @property
-def __name__(self):
+def name(self):
     return "Official hotpot F1 score"

Ensure to update any references to __name__ accordingly.

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

Suggested change
@property
def __name__(self):
return "Official hotpot F1 score"
@property
def name(self):
return "Official hotpot F1 score"

Comment on lines +55 to +61
def measure(self, test_case: LLMTestCase):
self.score = exact_match_score(
prediction=test_case.actual_output,
ground_truth=test_case.expected_output,
)
self.success = self.score >= self.threshold
return self.score
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Boolean Comparison with Float Threshold

In em_score_metric, self.score is a boolean value resulting from exact_match_score, but it's being compared to a float threshold. This can lead to unintended behavior.

Convert the boolean to a float for a meaningful comparison:

 def measure(self, test_case: LLMTestCase):
     self.score = exact_match_score(
         prediction=test_case.actual_output,
         ground_truth=test_case.expected_output,
     )
+    self.score = float(self.score)
     self.success = self.score >= self.threshold
     return self.score

Alternatively, set the threshold to 1.0 to reflect that only a perfect match is considered successful.

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

Suggested change
def measure(self, test_case: LLMTestCase):
self.score = exact_match_score(
prediction=test_case.actual_output,
ground_truth=test_case.expected_output,
)
self.success = self.score >= self.threshold
return self.score
def measure(self, test_case: LLMTestCase):
self.score = exact_match_score(
prediction=test_case.actual_output,
ground_truth=test_case.expected_output,
)
self.score = float(self.score)
self.success = self.score >= self.threshold
return self.score

@alekszievr alekszievr merged commit 4f27455 into main Dec 10, 2024
10 checks passed
@alekszievr alekszievr deleted the feat/COG-817-EM-F1-scores branch December 10, 2024 18:16
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