File size: 6,809 Bytes
2c343df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""IFEval (Zhou et al. 2023) verifiable-instruction following, re-implemented for the subset of
instruction types we can check exactly. `lm-evaluation-harness` is not installed here, so the
verifiers below follow the reference implementation's semantics
(github.com/google-research/google-research/tree/master/instruction_following_eval).

We keep only prompts whose EVERY instruction is in the supported set, and report strict
prompt-level accuracy (all instructions satisfied) plus instruction-level accuracy. Chance is ~0:
these are generation-time constraints, not multiple choice, so a model that has not acquired
instruction-following scores near the floor set by accidental satisfaction.
"""
from __future__ import annotations
import re, json, os
from datasets import load_dataset

CACHE = os.environ.get("MA_DATA_CACHE", "/root/hf_cache_mergeacc/datasets")
_CMP = {"less than": lambda a, b: a < b, "at least": lambda a, b: a >= b,
        "at most": lambda a, b: a <= b, "exactly": lambda a, b: a == b,
        None: lambda a, b: a >= b}

def _words(t): return re.findall(r"\b\w+\b", t)
def _sentences(t):
    s = re.split(r"(?<=[.!?])\s+", t.strip())
    return [x for x in s if x.strip()]
def _paras(t): return [p for p in re.split(r"\n\n+", t.strip()) if p.strip()]

def _v(iid, kw, r, prompt):
    k = lambda n: kw.get(n)
    if iid == "punctuation:no_comma":                 return "," not in r
    if iid == "change_case:english_lowercase":        return r == r.lower()
    if iid == "change_case:english_capital":          return r == r.upper()
    if iid == "change_case:capital_word_frequency":
        n = sum(1 for w in _words(r) if w.isupper() and len(w) > 1)
        return _CMP[k("capital_relation")](n, k("capital_frequency"))
    if iid == "keywords:existence":
        return all(re.search(re.escape(w), r, re.I) for w in (k("keywords") or []))
    if iid == "keywords:frequency":
        n = len(re.findall(re.escape(k("keyword")), r, re.I))
        return _CMP[k("relation")](n, k("frequency"))
    if iid == "keywords:forbidden_words":
        return not any(re.search(r"\b" + re.escape(w) + r"\b", r, re.I) for w in (k("forbidden_words") or []))
    if iid == "keywords:letter_frequency":
        n = r.lower().count((k("letter") or "").lower())
        return _CMP[k("let_relation")](n, k("let_frequency"))
    if iid == "length_constraints:number_sentences":
        return _CMP[k("relation")](len(_sentences(r)), k("num_sentences"))
    if iid == "length_constraints:number_words":
        return _CMP[k("relation")](len(_words(r)), k("num_words"))
    if iid == "length_constraints:number_paragraphs":
        return len(_paras(r)) == k("num_paragraphs")
    if iid == "length_constraints:nth_paragraph_first_word":
        ps = _paras(r); n = k("nth_paragraph")
        if not n or len(ps) < n: return False
        w = _words(ps[n - 1])
        return bool(w) and w[0].lower() == str(k("first_word")).lower()
    if iid == "detectable_format:number_highlighted_sections":
        n = len(re.findall(r"\*[^\*\n]+\*", r))
        return n >= (k("num_highlights") or 0)
    if iid == "detectable_format:title":
        return bool(re.search(r"<<[^\n]+>>", r))
    if iid == "detectable_format:number_bullet_lists":
        return len(re.findall(r"^\s*\*\s+", r, re.M)) == k("num_bullets")
    if iid == "detectable_format:json_format":
        t = re.sub(r"^```(json)?|```$", "", r.strip(), flags=re.M).strip()
        try: json.loads(t); return True
        except Exception: return False
    if iid == "detectable_format:multiple_sections":
        sp = k("section_spliter") or ""
        return len(re.findall(re.escape(sp) + r"\s*\d+", r)) >= (k("num_sections") or 0)
    if iid == "detectable_format:constrained_response":
        return any(o in r for o in ("My answer is yes.", "My answer is no.", "My answer is maybe."))
    if iid == "detectable_content:number_placeholders":
        return len(re.findall(r"\[[^\]\n]*\]", r)) >= (k("num_placeholders") or 0)
    if iid == "detectable_content:postscript":
        m = (k("postscript_marker") or "P.S.")
        return m.lower() in r.lower()
    if iid == "startend:end_checker":
        return r.strip().lower().endswith(str(k("end_phrase") or "").strip().lower())
    if iid == "startend:quotation":
        t = r.strip()
        return len(t) >= 2 and t.startswith('"') and t.endswith('"')
    if iid == "combination:repeat_prompt":
        p = (k("prompt_to_repeat") or "").strip()
        return bool(p) and r.strip().lower().startswith(p.lower()[:min(len(p), 120)])
    if iid == "combination:two_responses":
        return len(re.split(r"\*\*\*+", r)) >= 2
    return None                                            # unsupported

SUPPORTED = {"punctuation:no_comma", "change_case:english_lowercase", "change_case:english_capital",
             "change_case:capital_word_frequency", "keywords:existence", "keywords:frequency",
             "keywords:forbidden_words", "keywords:letter_frequency",
             "length_constraints:number_sentences", "length_constraints:number_words",
             "length_constraints:number_paragraphs", "length_constraints:nth_paragraph_first_word",
             "detectable_format:number_highlighted_sections", "detectable_format:title",
             "detectable_format:number_bullet_lists", "detectable_format:json_format",
             "detectable_format:multiple_sections", "detectable_format:constrained_response",
             "detectable_content:number_placeholders", "detectable_content:postscript",
             "startend:end_checker", "startend:quotation", "combination:repeat_prompt",
             "combination:two_responses"}

_D = None
def docs(n=None, seed=1234):
    global _D
    if _D is None:
        ds = load_dataset("google/IFEval", split="train", cache_dir=CACHE)
        out = []
        for r in ds:
            ids = list(r["instruction_id_list"])
            if not ids or any(i not in SUPPORTED for i in ids): continue
            kws = [{k: v for k, v in kw.items() if v is not None} for kw in r["kwargs"]]
            out.append({"prompt": r["prompt"], "ids": ids, "kwargs": kws})
        _D = out
    rows = list(_D)
    if n and len(rows) > n:
        import random; random.Random(seed).shuffle(rows); rows = rows[:n]
    return rows

def score(rows, responses):
    """strict prompt-level and instruction-level accuracy."""
    ok_p, ok_i, tot_i = 0, 0, 0
    for d, r in zip(rows, responses):
        good = True
        for iid, kw in zip(d["ids"], d["kwargs"]):
            v = _v(iid, kw, r, d["prompt"])
            if v is None: continue
            tot_i += 1; ok_i += int(v); good &= bool(v)
        ok_p += int(good)
    return {"ifeval_prompt": ok_p / max(len(rows), 1),
            "ifeval_inst": ok_i / max(tot_i, 1), "n": len(rows)}