File size: 3,587 Bytes
d9aaa5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""benak_reward: a verifiable GRPO reward for "think in the user's language" (TRL GRPOTrainer-compatible).

reward = correctness * (0.5 + 0.5 * in_language_share_of_thinking)
  - correctness: 1 if the final \\boxed{} answer matches `answer` (numeric, tolerant to 1.250.000 / 1,250,000 / 12,5)
  - in_language_share: GlotLID share of the thinking text in `lang`, after dropping sentences that quote the prompt
So a right answer reasoned in English earns 0.5, a right answer reasoned in the target language earns 1.0, and a wrong
answer earns 0. This fixes Qi et al.'s accuracy-vs-language trade-off in the reward rather than the prompt.

Thinking is read from <think>...</think> in the completion, or from a separate `thinking` column if TRL passes one.
    trainer = GRPOTrainer(model=..., reward_funcs=[benak_reward], train_dataset=ds)   # ds has `answer`, `lang`, `prompt`
"""
import re
from lid import profile

_THINK = re.compile(r"<think>(.*?)</think>", re.S)


def _text(c):
    return c if isinstance(c, str) else c[-1]["content"]


def _boxed(t):
    i = t.rfind("\\boxed{")
    if i < 0:
        return None
    i += 7; d = 1; j = i
    while j < len(t) and d:
        d += {"{": 1, "}": -1}.get(t[j], 0); j += 1
    return t[i:j - 1] if d == 0 else None


def _num(s):
    s = re.sub(r"(?i)rp\.?|\s|%|\\[a-z]+\{|\}", "", s or "")
    m = re.findall(r"-?\d[\d.,]*", s)
    if not m:
        return None
    t = m[-1].rstrip(".,")
    if "," in t and "." in t:
        t = t.replace(".", "").replace(",", ".") if t.rfind(",") > t.rfind(".") else t.replace(",", "")
    elif t.count(".") > 1 or t.count(",") > 1 or re.fullmatch(r"-?\d{1,3}[.,]\d{3}", t):
        t = t.replace(".", "").replace(",", "")
    else:
        t = t.replace(",", ".")
    try:
        return float(t)
    except ValueError:
        return None


def score(completion, answer, lang, prompt="", thinking=None):
    text = _text(completion)
    th = thinking if thinking is not None else "\n".join(_THINK.findall(text))
    final = _THINK.sub("", text)
    got = _num(_boxed(final) or "")
    if got is None or abs(got - float(answer)) > max(0.011, 1e-4 * abs(float(answer))):
        return 0.0
    share = profile(th, lang, exclude=prompt or None)["target_share"]
    return round(0.5 + 0.5 * (share or 0.0), 4)


def benak_reward(completions, answer, lang, prompts=None, thinking=None, **_):
    """TRL reward_funcs signature: one float per completion."""
    n = len(completions)
    prompts = prompts or [""] * n
    thinking = thinking or [None] * n
    return [score(c, a, l, _text(p) if p else "", t) for c, a, l, p, t in zip(completions, answer, lang, prompts, thinking)]


if __name__ == "__main__":
    idn = "<think>Pak Budi membeli tiga karung beras, masing-masing dua puluh lima kilogram. Jadi totalnya tujuh puluh lima kilogram dikali harga per kilogram.</think> Jadi \\boxed{937.500}"
    eng = "<think>Mr Budi buys three sacks of rice, each twenty five kilograms. So the total is seventy five kilograms times the price per kilogram.</think> So \\boxed{937500}"
    bad = "<think>Pak Budi membeli tiga karung beras, masing-masing dua puluh lima kilogram dan seterusnya.</think> \\boxed{900000}"
    r = benak_reward([idn, eng, bad], [937500, 937500, 937500], ["ind_Latn"] * 3)
    assert r[0] > 0.95 and abs(r[1] - 0.5) < 0.05 and r[2] == 0.0, r
    assert benak_reward([[{"role": "assistant", "content": idn}]], [937500], ["ind_Latn"])[0] > 0.95
    assert _num("Rp1.250.000,50") == 1250000.5 and _num("12,5") == 12.5 and _num("1,250") == 1250.0
    print("benak_reward self-check ok", r)