Skip to content

Commit 13ec9ae

Browse files
committed
fix: stabilize normalized multiple-choice probability
1 parent 932e1f2 commit 13ec9ae

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

‎src/lighteval/metrics/metrics_sample.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,12 @@ def compute(
347347
if self.log_prob_normalization
348348
else choices_logprobs
349349
)
350+
normalized_log_probs = np.asarray(normalized_log_probs, dtype=np.float64)
351+
if normalized_log_probs.size > 0:
352+
max_normalized_log_prob = np.max(normalized_log_probs)
353+
if np.isfinite(max_normalized_log_prob):
354+
normalized_log_probs = normalized_log_probs - max_normalized_log_prob
355+
350356
normalized_probs = np.exp(normalized_log_probs)
351357

352358
normalized_probs = safe_divide(normalized_probs[gold_ixs], np.sum(normalized_probs))

‎tests/test_unit_base_metrics.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,16 @@ def test_mc_probability_metric(self):
228228
)
229229
assert result[prob_norm_metric.metric_name] == pytest.approx(0.7)
230230

231+
def test_mc_probability_metric_avoids_logprob_underflow(self):
232+
doc = Doc(query="Test query", choices=["A", "B"], gold_index=0, task_name="test")
233+
model_response = ModelResponse(logprobs=[-1000.0, -1001.0])
234+
235+
metric = NormalizedMultiChoiceProbMetric()
236+
result = metric.compute_sample(doc=doc, model_response=model_response)
237+
238+
expected = 1 / (1 + np.exp(-1))
239+
assert result[metric.metric_name] == pytest.approx(expected)
240+
231241
def test_acc(self):
232242
# Test without normalization
233243
doc = Doc(query="Test query", choices=["A", "B", "C", "D"], gold_index=0, task_name="test")

0 commit comments

Comments
 (0)