File size: 12,027 Bytes
6118bac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python3
"""Deterministic CoT loop detector and verifiable capability graders for Inkling-2-Mini Anti-Loop."""
from __future__ import annotations

import collections
import json
import math
import os
import re
import subprocess
import sys
import tempfile


def has_loop(text: str) -> dict:
    """Detect repetitive / spiraling CoT degeneration deterministically.

    Returns dict with:
      - loop: bool (True if high-confidence loop detected)
      - reasons: list[str]
      - distinct5_tail: float (distinct 5-gram ratio on tail 400 words)
      - max_ngram_rep: int (max repetitions of any 10-word n-gram)
    """
    if not text or len(text) < 250:
        return {"loop": False, "reasons": [], "distinct5_tail": 1.0, "max_ngram_rep": 0}

    reasons = []
    # 1. Word-level 10-gram repetition (catches repeated thoughts/sentences in EN & mixed code)
    words = re.findall(r"\S+", text)
    max_rep = 0
    if len(words) >= 40:
        ng = collections.Counter(tuple(words[i : i + 10]) for i in range(len(words) - 9))
        if ng:
            max_rep = ng.most_common(1)[0][1]
            if max_rep >= 4:
                reasons.append(f"word10_rep={max_rep}")

    # 2. Character-level 36-char chunk repetition (catches CJK / zh-TW / table / code loops)
    # Sample every 4 chars for speed on long traces
    if len(text) >= 400:
        cng = collections.Counter(text[i : i + 36] for i in range(0, len(text) - 36, 4))
        c_rep = cng.most_common(1)[0][1] if cng else 0
        if c_rep >= 5:
            reasons.append(f"char36_rep={c_rep}")

    # 3. Tail distinct 5-gram ratio (REXL3#196 criterion: distinct n-gram < 0.48 on tail)
    tail_w = words[-400:] if len(words) >= 120 else words
    d5 = 1.0
    if len(tail_w) >= 80:
        grams = [tuple(tail_w[i : i + 5]) for i in range(len(tail_w) - 4)]
        d5 = len(set(grams)) / max(1, len(grams))
        if d5 < 0.48:
            reasons.append(f"tail_d5={d5:.3f}")

    # 4. CJK tail distinct 8-char ratio (for zh-TW prose without spaces)
    cjk_chars = re.findall(r"[\u4e00-\u9fff]", text)
    if len(cjk_chars) >= 160:
        tc = cjk_chars[-400:]
        cgrams = ["".join(tc[i : i + 8]) for i in range(len(tc) - 7)]
        cd8 = len(set(cgrams)) / max(1, len(cgrams))
        if cd8 < 0.50:
            reasons.append(f"cjk_d8={cd8:.3f}")

    # 5. Paragraph-level repetition detector (catches Inkling's classic multi-sentence / paragraph loops at 4K-12K)
    onset_char = -1
    paras = [p.strip() for p in re.split(r"\n\s*\n+", text) if len(p.strip()) >= 80]
    if len(paras) >= 4:
        p_sets = [set(re.findall(r"[\w\u4e00-\u9fff]{2,}", p.lower())) for p in paras]
        dup_hits = 0
        for i in range(1, len(paras)):
            if len(p_sets[i]) < 8:
                continue
            for j in range(max(0, i - 12), i):
                u = len(p_sets[i] | p_sets[j])
                if u > 0 and len(p_sets[i] & p_sets[j]) / u >= 0.62:
                    dup_hits += 1
                    if onset_char == -1:
                        onset_char = text.find(paras[i])
                    break
        if dup_hits >= 3:
            reasons.append(f"para_dup={dup_hits}")

    # 6. Classic Inkling self-doubt spiral phrase flood in tail
    tail_s = text[-3500:].lower()
    spiral_hits = len(
        re.findall(
            r"(i keep repeating|let me actually|wait,\s*let me|let me double[- ]check|"
            r"wait a (second|minute)|actually,\s*wait|let me re-?check|let me check again|"
            r"wait,\s*no|hold on,\s*let me|等一下|等等,我再確認|重新確認一次|我一直在重複)",
            tail_s,
        )
    )
    if spiral_hits >= 5 and (d5 < 0.78 or len(text) > 5000):
        reasons.append(f"spiral_hits={spiral_hits}")

    # Estimate loop onset char if not already set by paragraph detector
    if reasons and onset_char == -1:
        # Find first repeated 36-char chunk
        seen_c = {}
        for pos in range(0, max(0, len(text) - 36), 8):
            ck = text[pos : pos + 36]
            if ck in seen_c:
                onset_char = seen_c[ck]
                break
            seen_c[ck] = pos

    return {
        "loop": bool(reasons),
        "reasons": reasons,
        "distinct5_tail": round(d5, 4),
        "max_ngram_rep": max_rep,
        "onset_char": onset_char,
    }


# ------------------------------------------------------------------ MATH Grader
def _extract_boxed(s: str) -> str | None:
    idx = s.rfind("\\boxed{")
    if idx == -1:
        return None
    depth = 0
    start = idx + len("\\boxed{")
    for i in range(start, len(s)):
        if s[i] == "{":
            depth += 1
        elif s[i] == "}":
            if depth == 0:
                return s[start:i]
            depth -= 1
    return None


def _norm_math(ans: str) -> str:
    s = ans.strip()
    s = s.replace("$", "").replace("\\left", "").replace("\\right", "")
    s = s.replace("\\,", "").replace("\\!", "").replace("\\ ", "")
    s = s.replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac")
    s = re.sub(r"\\text\{([^}]*)\}", r"\1", s)
    s = re.sub(r"\s+", "", s)
    s = s.rstrip(".")
    # Remove thousands commas inside numbers
    s = re.sub(r"(?<=\d),(?=\d{3}\b)", "", s)
    return s


def _to_float(s: str) -> float | None:
    s = _norm_math(s)
    # Handle \frac{a}{b}
    m = re.fullmatch(r"(-?)\\frac\{(-?\d+(?:\.\d+)?)\}\{(-?\d+(?:\.\d+)?)\}", s)
    if m:
        sign = -1.0 if m.group(1) == "-" else 1.0
        den = float(m.group(3))
        return sign * float(m.group(2)) / den if den != 0 else None
    m2 = re.fullmatch(r"(-?\d+(?:\.\d+)?)/(-?\d+(?:\.\d+)?)", s)
    if m2:
        den = float(m2.group(2))
        return float(m2.group(1)) / den if den != 0 else None
    try:
        return float(s)
    except Exception:
        return None


def grade_math(response: str, gold: str) -> tuple[bool, str]:
    """Compare model response against MATH-500 gold answer."""
    if not response:
        return False, ""
    pred = _extract_boxed(response)
    if pred is None:
        # Fallback: last "Answer:" line or last number
        m = re.findall(r"(?:answer|答案)\s*(?:is|:|:|=)\s*([^\n]+)", response, re.I)
        if m:
            pred = m[-1].strip()
        else:
            nums = re.findall(r"-?\d+(?:\.\d+)?(?:/\d+)?", response)
            pred = nums[-1] if nums else ""
    np_ = _norm_math(pred)
    ng_ = _norm_math(gold)
    if np_ == ng_ and np_ != "":
        return True, pred
    fp, fg = _to_float(np_), _to_float(ng_)
    if fp is not None and fg is not None:
        if math.isclose(fp, fg, rel_tol=1e-4, abs_tol=1e-5):
            return True, pred
    return False, pred


# ------------------------------------------------------------------ HumanEval Grader
def extract_python_code(resp: str, prompt: str) -> str:
    """Extract Python code from markdown fence or raw completion."""
    if not resp:
        return ""
    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", resp, re.S | re.I)
    if blocks:
        # Prefer the last block that contains 'def ' or return, else last block
        for b in reversed(blocks):
            if "def " in b or "return " in b:
                return b
        return blocks[-1]
    return resp


def grade_humaneval(resp: str, prompt: str, test_code: str, entry_point: str, timeout: float = 5.0) -> tuple[bool, str]:
    """Execute HumanEval unit tests in an isolated subprocess."""
    code = extract_python_code(resp, prompt)
    if not code.strip():
        return False, "empty_code"
    # If extracted code already defines the function, prepend imports from prompt; else append indented body to prompt
    if re.search(rf"^\s*def\s+{re.escape(entry_point)}\s*\(", code, re.M):
        # Keep any typing/import lines from prompt that may be missing
        imp_lines = [l for l in prompt.splitlines() if l.startswith(("from ", "import "))]
        full = "\n".join(imp_lines) + "\n\n" + code + "\n\n" + test_code + f"\ncheck({entry_point})\n"
    else:
        # Indented completion
        if not code.startswith((" ", "\t")):
            code = "\n".join("    " + l if l.strip() else l for l in code.splitlines())
        full = prompt + "\n" + code + "\n\n" + test_code + f"\ncheck({entry_point})\n"

    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as tf:
        tf.write(full)
        tf_path = tf.name
    try:
        p = subprocess.run(
            [sys.executable, tf_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=timeout,
            text=True,
        )
        if p.returncode == 0:
            return True, "ok"
        err = (p.stderr or p.stdout or "nonzero").strip().splitlines()
        return False, err[-1][:140] if err else "fail"
    except subprocess.TimeoutExpired:
        return False, "timeout"
    except Exception as e:
        return False, repr(e)[:120]
    finally:
        try:
            os.unlink(tf_path)
        except OSError:
            pass


# ------------------------------------------------------------------ MMLU-Pro Grader
def grade_mmlu_pro(resp: str, gold_letter: str) -> tuple[bool, str]:
    if not resp:
        return False, ""
    gold = gold_letter.strip().upper()
    # Priority 1: \boxed{X}
    b = _extract_boxed(resp)
    if b:
        m = re.search(r"\b([A-J])\b", b.upper())
        if m:
            return m.group(1) == gold, m.group(1)
    # Priority 2: explicit Answer: (X) or Answer is X
    pats = [
        r"(?:final\s+answer|answer|答案|選項)\s*(?:is|:|:|為)?\s*\*{0,2}\(?([A-J])\)?\*{0,2}\b",
        r"\b\(([A-J])\)\s*\.?\s*$",
    ]
    for pat in pats:
        ms = re.findall(pat, resp, re.I | re.M)
        if ms:
            pred = ms[-1].upper()
            return pred == gold, pred
    # Priority 3: last standalone capital A-J in last 200 chars
    ms = re.findall(r"\b([A-J])\b", resp[-200:])
    if ms:
        pred = ms[-1].upper()
        return pred == gold, pred
    return False, ""


# ------------------------------------------------------------------ zh-TW Multi-Rule Grader
def grade_zhtw_rules(resp: str, checks: list[dict]) -> tuple[bool, dict]:
    """Programmatically verify multi-rule zh-TW instruction adherence."""
    if not resp or not resp.strip():
        return False, {"passed": 0, "total": len(checks), "failed": ["empty"]}
    failed = []
    for ck in checks:
        t = ck["type"]
        if t == "must_contain":
            if ck["val"] not in resp:
                failed.append(f"missing:{ck['val']}")
        elif t == "must_end_line_prefix":
            last_line = [l.strip() for l in resp.strip().splitlines() if l.strip()][-1]
            if not last_line.startswith(ck["val"]):
                failed.append(f"end_line:{ck['val']}")
        elif t == "exact_bullets":
            n = len(re.findall(r"^\s*(?:[-*•]|\d+[.、)])\s+\S", resp, re.M))
            if n != ck["val"]:
                failed.append(f"bullets:{n}!={ck['val']}")
        elif t == "forbid_regex":
            if re.search(ck["val"], resp):
                failed.append(f"forbid:{ck['val']}")
        elif t == "max_chars":
            if len(resp.strip()) > ck["val"]:
                failed.append(f"len:{len(resp.strip())}>{ck['val']}")
        elif t == "min_chars":
            if len(resp.strip()) < ck["val"]:
                failed.append(f"len:{len(resp.strip())}<{ck['val']}")
        elif t == "valid_json_keys":
            raw = resp.strip()
            m = re.search(r"```(?:json)?\s*\n(.*?)```", raw, re.S)
            if m:
                raw = m.group(1).strip()
            try:
                obj = json.loads(raw)
                missing = [k for k in ck["val"] if k not in obj]
                if missing:
                    failed.append(f"json_keys:{missing}")
            except Exception:
                failed.append("invalid_json")
    return len(failed) == 0, {"passed": len(checks) - len(failed), "total": len(checks), "failed": failed}