Skip to content

Commit 0b288e3

Browse files
authored
Fixe Sampling Metrics and Evals (#938)
* Fixe Sampling Metrics and Evals * remove breakpoint * Apply suggestion from @NathanHB * Apply suggestion from @NathanHB
1 parent da8466b commit 0b288e3

2 files changed

Lines changed: 19 additions & 16 deletions

File tree

src/lighteval/metrics/dynamic_metrics.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,7 @@ def __init__(
220220

221221
@timeout(2)
222222
def add_to_specifics_with_timeout(
223-
formatted_doc: Doc, extracted_predictions: list[list[str]], extracted_golds: list[list[str]]
223+
self, formatted_doc: Doc, extracted_predictions: list[list[str]], extracted_golds: list[list[str]]
224224
) -> None:
225225
if formatted_doc.specific is None:
226226
formatted_doc.specific = {}
@@ -263,7 +263,7 @@ def compute(self, doc: Doc, model_response: ModelResponse) -> float:
263263
# We have to use timeout because the sypmy to str conversion can be very slow
264264
try:
265265
self.add_to_specifics_with_timeout(doc, extracted_predictions, extracted_golds)
266-
except Exception: # noqa: E722
266+
except TimeoutError: # noqa: E722
267267
logger.warning("Timeout when adding extracted predictions and golds to specific")
268268

269269
return self.aggregation_function(

src/lighteval/metrics/metrics_sample.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@
6363

6464
class SampleLevelComputation(ABC):
6565
@abstractmethod
66-
def compute(self, doc: Doc, model_response: ModelResponse, **kwargs):
66+
def compute(self, model_response: ModelResponse, doc: Doc, **kwargs):
6767
raise NotImplementedError
6868

6969

@@ -1112,13 +1112,16 @@ def __init__(
11121112
if callable(sample_scoring_function):
11131113
self.score_sample = sample_scoring_function
11141114
self.type_exact_match = None
1115+
elif isinstance(sample_scoring_function, SampleLevelComputation):
1116+
self.score_sample = sample_scoring_function.compute
11151117
else:
11161118
if isinstance(sample_scoring_function, str):
11171119
if sample_scoring_function not in ["prefix", "suffix", "full"]:
11181120
raise ValueError(
11191121
f"type_exact_match (used in parametrized_exact_match) must be one of prefix, suffix, or full. Was {sample_scoring_function} instead."
11201122
)
11211123
self.type_exact_match = sample_scoring_function
1124+
self.score_sample = self.default_sample_scoring
11221125
else:
11231126
self.type_exact_match = "full"
11241127
self.compute_score = self.default_sample_scoring
@@ -1130,7 +1133,7 @@ def preprocess(self, text: str) -> str:
11301133
if self.strip_strings:
11311134
text = text.strip()
11321135

1133-
if self.normalize:
1136+
if self.normalize is not None:
11341137
text = self.normalize(text)
11351138

11361139
return text
@@ -1161,7 +1164,7 @@ def __init__(self, k: int | None = None, **kwargs):
11611164
sample_scoring_function (callable | str, optional): Function to use to compute the score for each sample.
11621165
If None, uses the default scoring function which is a simple exact match.
11631166
"""
1164-
super().__init__(kwargs)
1167+
super().__init__(**kwargs)
11651168
self.k = k
11661169
self.attribute_must_be_set = ["k"]
11671170

@@ -1189,9 +1192,9 @@ def num_samples(self):
11891192

11901193

11911194
class MajAtK(SamplingMetric, SampleLevelComputation):
1192-
def __init__(self, k: int = None, **kwargs):
1195+
def __init__(self, k: int | None = None, **kwargs):
11931196
"""An exact match class."""
1194-
super().__init__(kwargs)
1197+
super().__init__(**kwargs)
11951198

11961199
self.k = k
11971200
self.attribute_must_be_set = ["k"]
@@ -1214,15 +1217,15 @@ def compute(self, model_response: ModelResponse, docs: Doc, **kwargs):
12141217
if len(golds) > 1:
12151218
raise Exception("Cannot compute maj@k with several golds")
12161219

1217-
processed_choices = [self.preprocess(gold=g) for g in docs.get_golds()]
1220+
processed_choices = [self.preprocess(text=g) for g in docs.get_golds()]
12181221
new_doc = Doc(
12191222
choices=processed_choices,
12201223
query=docs.query,
12211224
gold_index=docs.gold_index,
12221225
)
12231226
all_answers = []
12241227
for pred in model_response.final_text[: self.k]:
1225-
all_answers.append(self.preprocess(pred=pred))
1228+
all_answers.append(self.preprocess(text=pred))
12261229
majority_prediction = max(all_answers, key=all_answers.count)
12271230
new_model_response = ModelResponse(
12281231
text=[majority_prediction],
@@ -1241,7 +1244,7 @@ def __init__(self, k: int | None = None, n: int | None = None, **kwargs):
12411244
k (int): Threshold for the number of successful attempts.
12421245
n (int): Number of samples to generate
12431246
"""
1244-
super().__init__(kwargs)
1247+
super().__init__(**kwargs)
12451248
self.k = k
12461249
self.n = n
12471250
self.attribute_must_be_set = ["k"]
@@ -1269,7 +1272,7 @@ def compute(self, doc: Doc, model_response: ModelResponse, **kwargs) -> float:
12691272
elif len(predictions) < self.n:
12701273
logger.warning(f"Number of predictions is less than {self.n} for pass@k.")
12711274

1272-
processed_choices = [self.preprocess(gold=g) for g in doc.choices]
1275+
processed_choices = [self.preprocess(text=g) for g in doc.choices]
12731276
new_doc = Doc(
12741277
choices=processed_choices,
12751278
query=doc.query,
@@ -1278,11 +1281,11 @@ def compute(self, doc: Doc, model_response: ModelResponse, **kwargs) -> float:
12781281

12791282
all_scores = []
12801283
for pred in predictions[: self.n]:
1281-
cur_pred = self.preprocess(pred=pred)
1284+
cur_pred = self.preprocess(text=pred)
12821285
new_model_response = ModelResponse(
12831286
text=[cur_pred],
12841287
)
1285-
all_scores.append(self.score_sample(new_doc, new_model_response))
1288+
all_scores.append(self.score_sample(doc=new_doc, model_response=new_model_response))
12861289

12871290
return self.pass_at_k(all_scores)
12881291

@@ -1314,7 +1317,7 @@ def __init__(
13141317
n (int): Number of samples to generate.
13151318
thresholds (list): Thresholds to control successful attempts in k generate.
13161319
"""
1317-
super().__init__(kwargs)
1320+
super().__init__(**kwargs)
13181321
self._k = k
13191322
self.n = n
13201323
self.attribute_must_be_set = ["k"]
@@ -1356,7 +1359,7 @@ def compute(self, model_response: ModelResponse, doc: Doc, **kwargs) -> float:
13561359
elif len(predictions) < self.n:
13571360
logger.warning(f"Number of predictions is less than {self.n} for G-Pass@k.")
13581361

1359-
processed_choices = [self.preprocess(gold=g) for g in doc.choices]
1362+
processed_choices = [self.preprocess(text=g) for g in doc.choices]
13601363
new_doc = Doc(
13611364
choices=processed_choices,
13621365
query=doc.query,
@@ -1365,7 +1368,7 @@ def compute(self, model_response: ModelResponse, doc: Doc, **kwargs) -> float:
13651368

13661369
all_scores = []
13671370
for pred in predictions[: self.n]:
1368-
cur_pred = self.preprocess(pred=pred)
1371+
cur_pred = self.preprocess(text=pred)
13691372
new_model_response = ModelResponse(
13701373
text=[cur_pred],
13711374
)

0 commit comments

Comments
 (0)