File size: 6,954 Bytes
510314e | 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | """Banco ALB v2: normalizzatore del SOLO formato e contratto di "interamente corretta".
Regola (BRIEF-BENCH-ALB-V2 §1, pareri Sol/Argon): si avvolge in <answer>...</answer> solo se l'INTERA risposta,
tolti i blocchi <think>...</think> chiusi e un recinto ``` che avvolge tutto, rispetta la grammatica del tipo di
domanda. Niente estrazione dell'ultima riga, niente conversione da prosa, nessun valore cambiato o canonicalizzato.
grammatica tipi ufficiali forma accettata (intera stringa)
integer Count Frequency(Tool), Count Correctness(Env), -?\\d+
Count Frequency(Env), Find Round with Largest
Value(Env), Weighted Summation(Env)
yesno Find Duplicates(Tool) yes|no|true|false (maiuscole libere,
al più un punto finale)
pair Find Target Offsets(Tool) lista JSON valida di 2 id
["0728", "0137"] (stringhe di cifre)
id Intersection (Concise-Response) un id: \\d+
idlist Intersection (Verbose-Response) lista JSON valida di id
Non si avvolge MAI: risposta che contiene già un tag <answer (la si lascia allo scorer ufficiale così com'è),
<think> non chiuso (generazione tagliata), stringa vuota, rifiuti, prosa, più righe, alternative.
Idempotenza: N(N(x)) = N(x) (l'uscita avvolta contiene <answer> e quindi non viene più toccata).
Nota sulla forma "id1 and id2" (quella che il system ufficiale di Find Target Offsets chiede dentro <answer>): NON è
nella grammatica del normalizzatore (il brief ammette solo intero, sì/no, lista JSON). Una risposta "0728 and 0137"
senza tag resta sbagliata anche dopo la normalizzazione; il conteggio di questi casi è riportato a parte.
"""
from __future__ import annotations
import json
import re
INTEGER_TYPES = {"Count Frequency(Tool)", "Count Correctness(Env)", "Count Frequency(Env)",
"Find Round with Largest Value(Env)", "Weighted Summation(Env)"}
YESNO_TYPES = {"Find Duplicates(Tool)"}
PAIR_TYPES = {"Find Target Offsets(Tool)"}
INTERSECTION = "Intersection"
_THINK_CLOSED = re.compile(r"<think>.*?</think>", re.S | re.I)
_FENCE = re.compile(r"\A```[A-Za-z0-9_+-]*[ \t]*\n(.*?)\n?```\Z", re.S)
_INT = re.compile(r"\A-?\d+\Z")
_ID = re.compile(r"\A\d+\Z")
_YESNO = re.compile(r"\A(?:yes|no|true|false)\.?\Z", re.I)
def grammar_of(question_type: str, history_label: str | None = None) -> str | None:
if question_type in INTEGER_TYPES:
return "integer"
if question_type in YESNO_TYPES:
return "yesno"
if question_type in PAIR_TYPES:
return "pair"
if question_type == INTERSECTION:
return "idlist" if history_label == "Verbose-Response" else "id"
return None
def _json_list(s: str):
if not (s.startswith("[") and s.endswith("]")):
return None
try:
v = json.loads(s)
except ValueError:
return None
return v if isinstance(v, list) else None
def matches(grammar: str, s: str) -> bool:
if grammar == "integer":
return bool(_INT.match(s))
if grammar == "yesno":
return bool(_YESNO.match(s))
if grammar == "id":
return bool(_ID.match(s))
if grammar in ("pair", "idlist"):
v = _json_list(s)
if v is None or not all(isinstance(x, str) and _ID.match(x) for x in v):
return False
return len(v) == 2 if grammar == "pair" else len(v) >= 1
return False
def strip_wrappers(raw: str) -> str | None:
"""Toglie <think>...</think> chiusi e un recinto ``` che avvolge TUTTO. None = mai avvolgibile (think aperto)."""
t = _THINK_CLOSED.sub("", raw or "")
if re.search(r"</?think\b", t, re.I): # <think> non chiuso o </think> spaiato: generazione tagliata
return None
t = t.strip()
m = _FENCE.match(t)
if m:
t = m.group(1).strip()
return t
def normalize_format(raw: str, question_type: str, history_label: str | None = None) -> str:
"""N(raw): raw invariata, oppure "<answer>" + intera risposta + "</answer>" se rispetta la grammatica."""
raw = raw or ""
if re.search(r"<answer", raw, re.I):
return raw
g = grammar_of(question_type, history_label)
if g is None:
return raw
t = strip_wrappers(raw)
if not t or not matches(g, t):
return raw
return "<answer>%s</answer>" % t
# ---------------------------------------------------------------------------------------------------------------
# "Interamente corretta" (terza misura), contratto per tipo, verificato contro eval/evaluate.py ufficiale:
# integer _to_number(pred) == _to_number(gold) (= ufficiale, già binario)
# yesno _normalize_boolean(pred) == _normalize_boolean(gold) (= ufficiale, già binario)
# pair due id, NELL'ORDINE del gold, dopo _normalize_name ufficiale (= ufficiale score 1.0; il credito
# parziale 0,5 per il solo primo id NON è interamente corretto). Il vecchio confronto fra liste
# ordinate di str() ignorava l'ordine: ["b","a"] contro gold ["a","b"] risultava corretto.
# id _normalize_name(pred) == _normalize_name(gold) (= ufficiale)
# idlist F1 ufficiale == 1.0 (insiemi uguali)
# In più, STRUTTURA completa (Sol: "struttura e valori completi"): i parser ufficiali sono tolleranti (l'ultimo numero
# di "<answer>3 or 4</answer>", la prima negazione di "<answer>yes, no</answer>"), quindi l'ufficiale = 1 non basta:
# fully_correct = 1 sse punteggio ufficiale (sulla risposta normalizzata) == 1.0
# e tutti i tag <answer> hanno lo stesso contenuto (nessuna risposta multipla discordante)
# e quel contenuto rispetta per intero la grammatica del tipo (per Find Target Offsets anche
# la forma ufficiale "id1 and id2" chiesta dal system).
_PAIR_AND = re.compile(r"\A(\d+)\s+and\s+(\d+)\Z", re.I)
def strict_inner_ok(text: str, question_type: str, history_label: str | None = None) -> bool:
inners = [x.strip() for x in re.findall(r"<answer>(.*?)</answer>", text or "", flags=re.S | re.I)]
if not inners or len(set(inners)) != 1:
return False
s, g = inners[0], grammar_of(question_type, history_label)
if g is None:
return False
return matches(g, s) or (g == "pair" and bool(_PAIR_AND.match(s)))
def fully_correct(score, text: str, question_type: str, history_label: str | None = None) -> int:
try:
ok = abs(float(score) - 1.0) < 1e-9
except (TypeError, ValueError):
return 0
return int(ok and strict_inner_ok(text, question_type, history_label))
|