File size: 2,202 Bytes
e6f16da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared row selection for the three code datasets: drop duplicate prompts, cap how often one unit (a reference
solution, a buggy program, a project) and one family may appear, and write the splits."""
from __future__ import annotations

import json
import os
from collections import Counter
from concurrent.futures import ProcessPoolExecutor


def generate(make_rows, n_candidates, workers, langs, base_seed):
    per = max(20, n_candidates // (workers * 6))
    jobs = [(base_seed + i, per, langs) for i in range((n_candidates + per - 1) // per)]
    rows, drops = [], Counter()
    with ProcessPoolExecutor(workers) as ex:
        for rs, ds in ex.map(make_rows, jobs):
            rows += rs
            drops.update(ds)
    return rows, drops


def select(rows, unit_of, family_of, caps):
    """caps: {split: (max rows per unit, max rows per family, max rows)}. Rows are taken in order."""
    out = {s: [] for s in caps}
    seen, per_unit, per_fam, drops = set(), Counter(), Counter(), Counter()
    for r in rows:
        sp = r["meta"]["split"]
        key = "\n".join(m["content"] for m in r["messages"] if m["role"] == "user")
        if key in seen:
            drops["duplicate prompt"] += 1
            continue
        cap_unit, cap_fam, cap_rows = caps[sp]
        u, f = unit_of(r), family_of(r)
        if per_unit[(sp, u)] >= cap_unit:
            drops[f"{sp}: unit cap"] += 1
            continue
        if per_fam[(sp, f)] >= cap_fam:
            drops[f"{sp}: family cap"] += 1
            continue
        if len(out[sp]) >= cap_rows:
            drops[f"{sp}: split full"] += 1
            continue
        seen.add(key)
        per_unit[(sp, u)] += 1
        per_fam[(sp, f)] += 1
        out[sp].append(r)
    return out, drops


def write(out_dir, prefix, split, rows):
    os.makedirs(out_dir, exist_ok=True)
    with open(os.path.join(out_dir, f"{split}.jsonl"), "w", encoding="utf-8") as f:
        for i, r in enumerate(rows):
            meta = {k: v for k, v in r["meta"].items() if k != "split"}
            f.write(json.dumps({"id": f"{prefix}-{split}-{i:06d}", "messages": r["messages"], "meta": meta},
                               ensure_ascii=False) + "\n")