File size: 13,494 Bytes
9d6c277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build benchmark-ready JSONL files for the KV-cache quantization study.

Reads raw downloads from ~/datasets and writes ~/bench/data/:
  ruler_{4k,16k,32k,64k,128k}.jsonl  13 tasks x 40 samples per length
  gpqa_x4.jsonl                      198 questions x 4 shuffled samples
  docvqa_1000.jsonl (+ docvqa_img/)   seeded 1,000-question subset
  lcb_v6_x2.jsonl                    175 problems x 2 samples
  swe_kl_50.jsonl                    50 trajectories, 50K-150K tokens

Usage: python prep_data.py [--stage all|ruler|gpqa|docvqa|lcb|swe] [--workers N]
Other models: KVQ_TOK=<model dir> KVQ_DATA=<folder under ~/bench> (default Qwen3.8-27B, data);
  KVQ_RULER_TASKS / KVQ_RULER_LENGTHS (comma lists) limit the RULER grid.
"""
import argparse
import concurrent.futures as cf
import hashlib
import json
import os
import random
import subprocess
import sys
from pathlib import Path

HOME = Path.home()
RAW = HOME / "datasets"
OUT = HOME / "bench" / os.environ.get("KVQ_DATA", "data")
TOK = Path(os.environ.get("KVQ_TOK", HOME / "models" / "Qwen3.8-27B"))
RULER_RAW = OUT.parent / ("ruler_raw" + OUT.name.removeprefix("data"))  # per-tokenizer raw RULER output
SEED = 0

RULER_DIR = RAW / "ruler" / "RULER" / "scripts" / "data"
RULER_TASKS = [
    "niah_single_1", "niah_single_2", "niah_single_3",
    "niah_multikey_1", "niah_multikey_2", "niah_multikey_3",
    "niah_multivalue", "niah_multiquery", "vt", "cwe", "fwe", "qa_1", "qa_2",
]
RULER_LENGTHS = {"4k": 4096, "16k": 16384, "32k": 32768, "64k": 65536, "128k": 131072}
if os.environ.get("KVQ_RULER_TASKS"):
    RULER_TASKS = os.environ["KVQ_RULER_TASKS"].split(",")
if os.environ.get("KVQ_RULER_LENGTHS"):
    RULER_LENGTHS = {n: RULER_LENGTHS[n] for n in os.environ["KVQ_RULER_LENGTHS"].split(",")}
RULER_SAMPLES = 40
SHORT_OUT = 16384  # RULER / DocVQA: reasoning_effort=low; cap leaves room for thinking
LONG_OUT = 65536   # GPQA / LCB: reasoning_effort=xhigh (model default)


def write_jsonl(path, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"wrote {path} ({len(rows)} rows)", flush=True)


# ---------------------------------------------------------------- RULER
def _ruler_job(task, length_name, length):
    save_dir = RULER_RAW / length_name
    out_file = save_dir / task / "validation.jsonl"
    if out_file.exists() and sum(1 for _ in open(out_file)) == RULER_SAMPLES:
        return task, length_name, "cached"
    cmd = [sys.executable, "prepare.py", "--save_dir", str(save_dir), "--benchmark", "synthetic",
           "--task", task, "--tokenizer_path", str(TOK), "--tokenizer_type", "hf",
           "--max_seq_length", str(length), "--model_template_type", "base",
           "--num_samples", str(RULER_SAMPLES), "--random_seed", "42"]
    p = subprocess.run(cmd, cwd=RULER_DIR, capture_output=True, text=True)
    if p.returncode != 0:
        return task, length_name, "FAILED: " + (p.stderr or p.stdout)[-800:]
    return task, length_name, "ok"


def ruler(workers):
    jobs = [(t, n, L) for n, L in RULER_LENGTHS.items() for t in RULER_TASKS]
    # Longest contexts first so the slow jobs start early.
    jobs.sort(key=lambda j: -j[2])
    failed = []
    with cf.ProcessPoolExecutor(max_workers=workers) as ex:
        for task, n, status in ex.map(_ruler_job, *zip(*jobs)):
            print(f"ruler {n:>4} {task:<16} {status[:300]}", flush=True)
            if status.startswith("FAILED"):
                failed.append((task, n))
    for n in RULER_LENGTHS:
        rows = []
        for task in RULER_TASKS:
            f = RULER_RAW / n / task / "validation.jsonl"
            if not f.exists():
                continue
            for line in open(f):
                o = json.loads(line)
                prompt = o["input"].rstrip() + "\n\n" + o["answer_prefix"].strip()
                rows.append({"id": f"{task}-{o['index']}", "task": task, "length": n,
                             "answers": o["outputs"], "input_tokens": o["length"],
                             "prompt": prompt, "output_tokens": SHORT_OUT})
        write_jsonl(OUT / f"ruler_{n}.jsonl", rows)
    if failed:
        print("RULER FAILED JOBS:", failed, flush=True)


# ---------------------------------------------------------------- GPQA
GPQA_TEMPLATE = (
    "Answer the following multiple choice question. The last line of your response should be "
    "of the following format: 'ANSWER: $LETTER' (without quotes) where LETTER is one of ABCD. "
    "Think step by step before answering.\n\n{question}\n\nA) {A}\nB) {B}\nC) {C}\nD) {D}"
)


def gpqa():
    import pandas as pd
    df = pd.read_csv(RAW / "gpqa" / "gpqa_diamond.csv")
    rows = []
    for _, r in df.iterrows():
        opts = [r["Correct Answer"], r["Incorrect Answer 1"], r["Incorrect Answer 2"], r["Incorrect Answer 3"]]
        opts = [str(o).strip() for o in opts]
        for s in range(4):
            order = list(range(4))
            random.Random(f"{r['Record ID']}-{s}").shuffle(order)
            shuffled = [opts[i] for i in order]
            letter = "ABCD"[order.index(0)]
            prompt = GPQA_TEMPLATE.format(question=str(r["Question"]).strip(),
                                          A=shuffled[0], B=shuffled[1], C=shuffled[2], D=shuffled[3])
            rows.append({"id": r["Record ID"], "sample": s, "domain": r["High-level domain"],
                         "correct_letter": letter, "prompt": prompt, "output_tokens": LONG_OUT})
    write_jsonl(OUT / "gpqa_x4.jsonl", rows)


# ---------------------------------------------------------------- DocVQA
def docvqa():
    import pyarrow.parquet as pq
    files = sorted((RAW / "docvqa" / "DocVQA").glob("validation-*.parquet"))
    cols = ["questionId", "question", "answers", "question_types", "docId", "image"]
    meta = []  # (file, row) index first, images loaded only for chosen rows
    for fi, f in enumerate(files):
        n = pq.ParquetFile(f).metadata.num_rows
        meta += [(fi, i) for i in range(n)]
    chosen = sorted(random.Random(SEED).sample(range(len(meta)), 1000))
    by_file = {}
    for k in chosen:
        fi, i = meta[k]
        by_file.setdefault(fi, []).append(i)
    img_dir = OUT / "docvqa_img"
    img_dir.mkdir(parents=True, exist_ok=True)
    rows = []
    for fi, idxs in sorted(by_file.items()):
        t = pq.read_table(files[fi], columns=cols).take(idxs).to_pylist()
        for r in t:
            b = r["image"]["bytes"]
            ext = "png" if b[:8] == b"\x89PNG\r\n\x1a\n" else "jpg"
            p = img_dir / f"{r['questionId']}.{ext}"
            p.write_bytes(b)
            rows.append({"id": str(r["questionId"]), "doc_id": r["docId"], "answers": r["answers"],
                         "question_types": r["question_types"],
                         "prompt": f"{r['question']}\nAnswer the question using a single word or phrase.",
                         "image_files": [str(p)], "output_tokens": SHORT_OUT})
    print(f"docvqa: {len(meta)} validation questions, sampled {len(rows)}", flush=True)
    write_jsonl(OUT / "docvqa_1000.jsonl", rows)


# ---------------------------------------------------------------- LiveCodeBench
LCB_SYSTEM = ("You are an expert Python programmer. You will be given a question (problem specification) "
              "and will generate a correct Python program that matches the specification and passes all tests.")
LCB_WITH_STARTER = ("You will use the following starter code to write the solution to the problem and "
                    "enclose your code within delimiters.")
LCB_NO_STARTER = ("Read the inputs from stdin solve the problem and write the answer to stdout (do not directly "
                  "test on the sample inputs). Enclose your code within delimiters as follows. Ensure that when "
                  "the python program runs, it reads the inputs, runs the algorithm and writes output to STDOUT.")


def lcb_prompt(q):
    # Mirrors lcb_runner/prompts/code_generation.py:get_generic_question_template_answer,
    # with the generic system message prepended (the chat endpoint gets one user turn).
    p = f"{LCB_SYSTEM}\n\n### Question:\n{q['question_content']}\n\n"
    if q.get("starter_code"):
        p += f"### Format: {LCB_WITH_STARTER}\n```python\n{q['starter_code']}\n```\n\n"
    else:
        p += f"### Format: {LCB_NO_STARTER}\n```python\n# YOUR CODE HERE\n```\n\n"
    p += "### Answer: (use the provided format with backticks)\n\n"
    return p


def lcb():
    rows = []
    with open(RAW / "livecodebench" / "test6.jsonl") as f:
        problems = [json.loads(line) for line in f]
    for q in problems:
        for s in range(2):
            rows.append({"id": q["question_id"], "sample": s, "platform": q["platform"],
                         "difficulty": q["difficulty"], "contest_date": q["contest_date"],
                         "prompt": lcb_prompt(q), "output_tokens": LONG_OUT})
    print(f"lcb: {len(problems)} v6 problems", flush=True)
    write_jsonl(OUT / "lcb_v6_x2.jsonl", rows)


# ---------------------------------------------------------------- SWE trajectories
def _clean_msg(m):
    out = {"role": m["role"], "content": m.get("content") or ""}
    if m.get("tool_calls"):
        out["tool_calls"] = [{"id": c.get("id"), "type": c.get("type") or "function",
                              "function": {"name": c["function"]["name"],
                                           "arguments": c["function"]["arguments"]}}
                             for c in m["tool_calls"]]
    if m["role"] == "tool":
        out["name"] = m.get("name")
        out["tool_call_id"] = m.get("tool_call_id")
    return out


def _strip_none(x):
    if isinstance(x, dict):
        return {k: _strip_none(v) for k, v in x.items() if v is not None}
    if isinstance(x, list):
        return [_strip_none(v) for v in x]
    return x


def swe():
    import pyarrow.parquet as pq
    from transformers import AutoTokenizer
    tok = AutoTokenizer.from_pretrained(TOK)
    pf = pq.ParquetFile(RAW / "swe" / "swe-rebench-openhands" / "trajectories.parquet")
    lo_chars, hi_chars = 50_000 * 2.5, 150_000 * 4.5   # loose char window before exact tokenization
    cands = []
    for g in range(pf.metadata.num_row_groups):
        t = pf.read_row_group(g, columns=["trajectory_id", "repo", "trajectory"]).to_pylist()
        for i, r in enumerate(t):
            n = sum(len(m.get("content") or "") + sum(len(c["function"]["arguments"] or "")
                    for c in (m.get("tool_calls") or [])) for m in r["trajectory"])
            if lo_chars <= n <= hi_chars:
                cands.append((g, i, r["repo"]))
    print(f"swe: {pf.metadata.num_rows} trajectories, {len(cands)} in the char window", flush=True)
    random.Random(SEED).shuffle(cands)
    picked, repos, seen = [], set(), 0
    for g, i, repo in cands:
        if len(picked) >= 50:
            break
        if repo in repos:          # one trajectory per repo for diversity
            continue
        seen += 1
        r = pf.read_row_group(g).slice(i, 1).to_pylist()[0]
        msgs = [_clean_msg(m) for m in r["trajectory"]]
        tools = _strip_none(r["tools"])
        ids = None
        for attempt in range(2):
            try:
                ids = tok.apply_chat_template(msgs, tools=tools, tokenize=True)
                if not isinstance(ids, list):
                    ids = ids["input_ids"]
                break
            except Exception as e:
                if attempt == 0:  # some templates need tool-call arguments as dicts
                    for m in msgs:
                        for c in m.get("tool_calls", []):
                            try:
                                c["function"]["arguments"] = json.loads(c["function"]["arguments"])
                            except Exception:
                                pass
                else:
                    print("swe skip render:", r["trajectory_id"], repr(e)[:150], flush=True)
        if ids is None:
            continue
        if not (50_000 <= len(ids) <= 150_000):
            continue
        repos.add(repo)
        picked.append({"id": r["trajectory_id"], "instance_id": r["instance_id"], "repo": repo,
                       "resolved": r["resolved"], "n_tokens": len(ids), "n_messages": len(msgs),
                       "assistant_turns": [k for k, m in enumerate(msgs) if m["role"] == "assistant"],
                       "messages": msgs, "tools": tools})
    print(f"swe: tokenized {seen} candidates, kept {len(picked)}", flush=True)
    write_jsonl(OUT / "swe_kl_50.jsonl", picked)


def manifest():
    m = {}
    for p in sorted(OUT.glob("*.jsonl")):
        h = hashlib.sha256(p.read_bytes()).hexdigest()
        m[p.name] = {"rows": sum(1 for _ in open(p)), "sha256": h}
    (OUT / "MANIFEST.json").write_text(json.dumps(m, indent=1))
    print(json.dumps(m, indent=1), flush=True)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--stage", default="all", choices=["all", "ruler", "gpqa", "docvqa", "lcb", "swe"])
    ap.add_argument("--workers", type=int, default=20)
    a = ap.parse_args()
    stages = ["gpqa", "lcb", "docvqa", "swe", "ruler"] if a.stage == "all" else [a.stage]
    for s in stages:
        print(f"===== {s}", flush=True)
        if s == "ruler":
            ruler(a.workers)
        else:
            globals()[s]()
    manifest()
    print("PREP_DONE", flush=True)