|
| 1 | +import re |
| 2 | + |
| 3 | +from datetime import datetime |
| 4 | +from typing import List, Dict, Any |
| 5 | +from helm.benchmark.adaptation.adapter_spec import AdapterSpec |
| 6 | +from helm.benchmark.adaptation.request_state import RequestState |
| 7 | +from helm.benchmark.metrics.metric import Metric |
| 8 | +from helm.benchmark.metrics.metric_name import MetricName |
| 9 | +from helm.benchmark.metrics.metric_service import MetricService |
| 10 | +from helm.benchmark.metrics.statistic import Stat |
| 11 | +from helm.common.hierarchical_logger import hlog |
| 12 | + |
| 13 | + |
| 14 | +class MedCalcBenchMetric(Metric): |
| 15 | + """ |
| 16 | + Metric for evaluating the MedCalc Bench dataset, assessing the model's ability to |
| 17 | + be a clinical calculator. |
| 18 | +
|
| 19 | + Exact match based on category: |
| 20 | + 1. Normal exact match: for categories "risk", "severity" or "diagnosis". |
| 21 | + 2. Variant exact match: for other categories, if the number calculated by the model falls between the values |
| 22 | + in the Lower limit and Upper limit columns, we mark it as accurate. |
| 23 | + """ |
| 24 | + |
| 25 | + def parse_duration(self, duration_str) -> int: |
| 26 | + """Parses a duration tuple (weeks, days) from a string format like ('14 weeks', '2 days').""" |
| 27 | + match = re.match(r"\('(\d+) weeks', '(\d+) days'\)", duration_str) |
| 28 | + if match: |
| 29 | + weeks, days = map(int, match.groups()) |
| 30 | + return weeks * 7 + days # Convert to total days |
| 31 | + else: |
| 32 | + raise ValueError(f"Invalid format: {duration_str}") |
| 33 | + |
| 34 | + def is_within_range(self, lower_bound, upper_bound, prediction) -> int: |
| 35 | + """ |
| 36 | + Checks if a predicted duration falls within the given range. |
| 37 | +
|
| 38 | + Args: |
| 39 | + lower_bound (str): The lower bound in format "('X weeks', 'Y days')". |
| 40 | + upper_bound (str): The upper bound in format "('X weeks', 'Y days')". |
| 41 | + prediction (str): The predicted duration in the same format. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + int: 1 if within range (inclusive), 0 otherwise. |
| 45 | + """ |
| 46 | + lower_days = self.parse_duration(lower_bound) |
| 47 | + upper_days = self.parse_duration(upper_bound) |
| 48 | + prediction_days = self.parse_duration(prediction) |
| 49 | + return 1 if lower_days <= prediction_days <= upper_days else 0 |
| 50 | + |
| 51 | + def check_date(self, prediction: str, reference: str, extra_data: Dict[str, Any]) -> int: |
| 52 | + """Checks if prediction date is withing limits""" |
| 53 | + if re.match(r"\('(\d+) weeks', '(\d+) days'\)", reference): |
| 54 | + exact_match = self.is_within_range(extra_data["lower_limit"], extra_data["upper_limit"], prediction) |
| 55 | + else: |
| 56 | + prediction_date = self._str_to_date(prediction) |
| 57 | + upper_limit_date = self._str_to_date(extra_data["upper_limit"]) |
| 58 | + lower_limit_date = self._str_to_date(extra_data["lower_limit"]) |
| 59 | + exact_match = 1 if lower_limit_date <= prediction_date <= upper_limit_date else 0 |
| 60 | + return exact_match |
| 61 | + |
| 62 | + def _str_to_date(self, date_str: str) -> datetime: |
| 63 | + """Convert string to datetime object.""" |
| 64 | + return datetime.strptime(date_str, "%m/%d/%Y") |
| 65 | + |
| 66 | + def check_in_range(self, prediction: str, reference: str, extra_data: Dict[str, Any], category: str) -> int: |
| 67 | + """Check if the prediction falls within the range specified by the reference.""" |
| 68 | + try: |
| 69 | + if category == "date": |
| 70 | + exact_match = self.check_date(prediction, reference, extra_data) |
| 71 | + elif category in ["dosage conversion", "physical"]: |
| 72 | + lower_limit = float(extra_data["lower_limit"]) |
| 73 | + upper_limit = float(extra_data["upper_limit"]) |
| 74 | + float_prediction = float(prediction) |
| 75 | + exact_match = 1 if lower_limit <= float_prediction <= upper_limit else 0 |
| 76 | + else: |
| 77 | + raise ValueError(f"Category {category} not supported") |
| 78 | + except ValueError: |
| 79 | + return 0 |
| 80 | + |
| 81 | + return exact_match |
| 82 | + |
| 83 | + def evaluate_generation( |
| 84 | + self, |
| 85 | + adapter_spec: AdapterSpec, |
| 86 | + request_state: RequestState, |
| 87 | + metric_service: MetricService, |
| 88 | + eval_cache_path: str, |
| 89 | + ) -> List[Stat]: |
| 90 | + """ |
| 91 | + Evaluate a single generation against reference labels. |
| 92 | + """ |
| 93 | + # Extract predictions |
| 94 | + assert request_state.result, "request_state.result is unexpectedly None" |
| 95 | + predictions = [completion.text.strip() for completion in request_state.result.completions] |
| 96 | + |
| 97 | + if not predictions: |
| 98 | + hlog("Warning: No predictions found in completions") |
| 99 | + return [] |
| 100 | + |
| 101 | + # Get the first prediction |
| 102 | + prediction = predictions[0] |
| 103 | + |
| 104 | + # Get references |
| 105 | + references = getattr(request_state.instance, "references", None) |
| 106 | + |
| 107 | + if not references or len(references) == 0: |
| 108 | + hlog(f"Warning: Missing references for instance {request_state.instance}") |
| 109 | + return [] |
| 110 | + |
| 111 | + reference = references[0].output.text |
| 112 | + |
| 113 | + # Extract category, upper limit and lower limit |
| 114 | + assert request_state.instance.extra_data, "Extra data dict was expected but got None" |
| 115 | + category = request_state.instance.extra_data["category"] |
| 116 | + |
| 117 | + if category in ["risk", "severity", "diagnosis"]: |
| 118 | + exact_match = 1 if prediction == reference else 0 |
| 119 | + else: |
| 120 | + exact_match = self.check_in_range(prediction, reference, request_state.instance.extra_data, category) |
| 121 | + |
| 122 | + return [ |
| 123 | + Stat(MetricName("medcalc_bench_accuracy")).add(exact_match), |
| 124 | + ] |
0 commit comments