File size: 2,053 Bytes
ed9f38e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | # MGSM answer extraction used to score mgsm_hj_en / mgsm_hj_fr (lm-eval process_results functions).
# Reads English and French number formats. Standalone: no lm_eval import needed.
# MGSM (human-translated GSM8K): numeric answer extraction that reads French and English number formats. Stock
# strict-match wants "The answer is N" / "La réponse est N", which chat models rarely write, and flexible-extract
# breaks on "70 000 $". Order: the number after a final-answer cue, else the last bold number, else the last number.
import re as _re
_NUM = r"-?\d[\d\s .,]*"
_CUE = _re.compile(r"(?:r[ée]ponse finale|final answer|r[ée]ponse|answer|la r[ée]ponse est|the answer is|conclusion)\s*\**\s*:", _re.I)
def _to_num(s, lang):
s = _re.sub(r"[\s\u00a0\u202f]", "", s).rstrip(".,")
if lang == "fr":
s = s.replace(".", "").replace(",", ".") if s.count(",") <= 1 else s.replace(",", "")
else:
s = s.replace(",", "")
try:
return float(s)
except ValueError:
return None
def _first_num(part, lang, last=False):
bold = [b for b in _re.findall(r"\*\*([^*\n]{1,60}?)\*\*", part) if _re.search(r"\d", b)]
nums = _re.findall(_NUM, (bold[-1] if last else bold[0]) if bold else part)
for n in (nums[-1:] if last or not bold else nums[:1]) if nums else []:
return _to_num(n, lang)
return None
def _extract(text, lang):
cues = list(_CUE.finditer(text))
if cues: # the last final-answer cue: its first (bold) number
v = _first_num(text[cues[-1].end():], lang)
if v is not None:
return v
return _first_num(text, lang, last=True) # else the last bold number, else the last number
def _mgsm(doc, results, lang):
v = _extract(results[0], lang)
return {"exact_match": float(v is not None and abs(v - float(doc["answer_number"])) < 1e-6)}
def mgsm_en(doc, results):
return _mgsm(doc, results, "en")
def mgsm_fr(doc, results):
return _mgsm(doc, results, "fr")
|