File size: 4,452 Bytes
53d5fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""13-gram + exact-string index over the eval splits of EVERY CodeSOTA task (research/common/zadania.py @ 2f4c0491) plus the

older Slayer suite, so the s3 mix can be decontaminated against all benchmarks we report. Same format as prepare.py

(bench_index.npz + bench_items.json). Run with the eval venv (has `datasets`):

  research/.venv-eval/bin/python bench_decon_index.py /workspace/s3decon

"""
import hashlib
import json
import re
import sys
import unicodedata
from pathlib import Path

import numpy as np
import xxhash

sys.path.insert(0, "/workspace/benchrepo/research/common")
import zadania as Z  # noqa: E402
from datasets import load_dataset  # noqa: E402

WORD = re.compile(r"\w+")


def norm(s):
    return " ".join(unicodedata.normalize("NFKC", s or "").lower().split())


def grams13(text, cap=3000):
    w = WORD.findall((text or "").lower())[:cap]
    return {xxhash.xxh64_intdigest(" ".join(w[i:i + 13]).encode()) for i in range(max(0, len(w) - 12))}


def strings(v, out):
    if isinstance(v, str):
        if len(v) >= 30:
            out.append(v)
    elif isinstance(v, (list, tuple)):
        for x in v:
            strings(x, out)
    elif isinstance(v, dict):
        for x in v.values():
            strings(x, out)


def main():
    dst = Path(sys.argv[1])
    dst.mkdir(parents=True, exist_ok=True)
    defs = {k: v for k, v in vars(Z).items() if isinstance(v, dict)}
    tasks = {}
    for d in defs.values():
        for tid, t in d.items():
            if isinstance(t, dict) and t.get("repo") and re.fullmatch(r"T\d+", str(tid)):
                tasks[tid] = t
    extra = {"X_belebele_pl": {"repo": "facebook/belebele", "nazwa_hf": "pol_Latn", "split": "test"},
             "X_gsm8k": {"repo": "openai/gsm8k", "nazwa_hf": "main", "split": "test"},
             "X_math": {"repo": "EleutherAI/hendrycks_math", "nazwa_hf": None, "split": "test"}}
    gram_owner, item_len, exact, items, meta = {}, [], {}, [], {}
    for tid, t in {**tasks, **extra}.items():
        names = [t.get("nazwa_hf")]
        if t["repo"] == "EleutherAI/hendrycks_math":
            names = ["algebra", "counting_and_probability", "geometry", "intermediate_algebra", "number_theory", "prealgebra", "precalculus"]
        n = 0
        if names == [None] or names == [""]:
            try:
                from datasets import get_dataset_config_names
                cn = get_dataset_config_names(t["repo"], revision=t.get("rewizja"))
                if cn and "default" not in cn:
                    names = ["all"] if "all" in cn else cn
                if t["repo"].endswith("multiblimp"):
                    names = [c for c in cn if c.startswith("pol")] or names
            except Exception:
                pass
        for nm in names:
            try:
                ds = load_dataset(t["repo"], nm, revision=t.get("rewizja"), split=t.get("split", "test"))
            except Exception as e:
                meta.setdefault(tid, {})["error"] = f"{type(e).__name__}: {str(e)[:160]}"
                continue
            for r in ds:
                txt = []
                strings(r, txt)
                if not txt:
                    continue
                k = len(items)
                items.append(tid)
                n += 1
                g = set()
                for s in txt:
                    g |= grams13(s)
                    ns = norm(s)
                    if 30 <= len(ns) <= 2000:
                        exact.setdefault(int(hashlib.sha256(ns.encode()).hexdigest()[:16], 16), k)
                item_len.append(len(g))
                for h in g:
                    gram_owner.setdefault(h, k)
        meta.setdefault(tid, {}).update({"repo": t["repo"], "split": t.get("split"), "items": n})
        print(tid, t["repo"], n, meta[tid].get("error", ""), flush=True)
    G = np.array(sorted(gram_owner), dtype=np.uint64)
    E = sorted(exact)
    np.savez(dst / "bench_index.npz", G=G, O=np.array([gram_owner[int(h)] for h in G], dtype=np.int32), L=np.array(item_len, dtype=np.int32),
             E=np.array(E, dtype=np.uint64), EO=np.array([exact[h] for h in E], dtype=np.int32))
    (dst / "bench_items.json").write_text(json.dumps(items))
    (dst / "bench_meta.json").write_text(json.dumps(meta, indent=1))
    print("items", len(items), "grams", len(G))


if __name__ == "__main__":
    main()