|
| 1 | +"""Build a QE training dataset from ``*_generations.jsonl`` files. |
| 2 | +
|
| 3 | +Each generation row (written by ``cre evaluate --save-generations``) already |
| 4 | +carries everything the QE classifier needs -- ``prompt``, ``full_output``, |
| 5 | +``num_tokens`` and ``correct`` -- so this converter only relabels it into the |
| 6 | +schema ``cre qe-train`` expects: ``decision_label`` is 1 (accept) when the |
| 7 | +efficient model was correct, else 0 (route/escalate). It writes ``train.jsonl`` |
| 8 | +and ``test.jsonl`` into an output directory that ``cre qe-train --dataset <dir>`` |
| 9 | +loads directly, no Hugging Face Hub round-trip needed. |
| 10 | +
|
| 11 | +Usage: |
| 12 | + python data/prep_qe.py \ |
| 13 | + --train tm_train_instruct_nothink_r5_..._generations.jsonl \ |
| 14 | + --test tm_test_instruct_nothink_r5_..._generations.jsonl \ |
| 15 | + --out data/telemath_router |
| 16 | + cre qe-train --dataset data/telemath_router --max-length 4096 --output-dir ./qe-telemath |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import argparse |
| 22 | +import json |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | + |
| 26 | +def qe_row(gen: dict) -> dict: |
| 27 | + """One generation row -> one QE example (columns match ymoslem/*-router).""" |
| 28 | + correct = bool(gen["correct"]) |
| 29 | + full_output = gen["full_output"] |
| 30 | + return { |
| 31 | + "question": gen.get("question", gen.get("prompt", "")), |
| 32 | + "prompt": gen.get("prompt", ""), |
| 33 | + "ground_truth_answer": gen.get("ground_truth_answer"), |
| 34 | + "full_output": full_output, |
| 35 | + "answer": gen.get("answer"), |
| 36 | + "accuracy": float(correct), |
| 37 | + "num_words": len(full_output.split()), |
| 38 | + "num_tokens": gen["num_tokens"], |
| 39 | + "score": float(correct), |
| 40 | + "decision_label": 1 if correct else 0, |
| 41 | + "decision_str": "accept" if correct else "route", |
| 42 | + "cluster": gen.get("cluster"), |
| 43 | + "qid": gen.get("qid"), |
| 44 | + "run": gen.get("run"), |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | +def to_qe_rows(generations: list[dict]) -> list[dict]: |
| 49 | + """Convert generation rows to QE examples, pooling multiple files/models.""" |
| 50 | + return [qe_row(g) for g in generations] |
| 51 | + |
| 52 | + |
| 53 | +def _read_jsonl(path: Path) -> list[dict]: |
| 54 | + with path.open() as f: |
| 55 | + return [json.loads(line) for line in f if line.strip()] |
| 56 | + |
| 57 | + |
| 58 | +def _write_jsonl(rows: list[dict], path: Path) -> None: |
| 59 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 60 | + with path.open("w") as f: |
| 61 | + for r in rows: |
| 62 | + f.write(json.dumps(r, ensure_ascii=False) + "\n") |
| 63 | + |
| 64 | + |
| 65 | +def build(train_files: list[str], test_files: list[str], out_dir: str) -> dict[str, int]: |
| 66 | + """Write ``{out_dir}/train.jsonl`` and ``test.jsonl``; return split sizes.""" |
| 67 | + out = Path(out_dir) |
| 68 | + sizes = {} |
| 69 | + for split, files in (("train", train_files), ("test", test_files)): |
| 70 | + rows: list[dict] = [] |
| 71 | + dropped = 0 |
| 72 | + for f in files: |
| 73 | + gens = _read_jsonl(Path(f)) |
| 74 | + # num_tokens feeds the QE input verbatim; a null (a generations file |
| 75 | + # written without output_lens) would render the string "None", so drop |
| 76 | + # those rows rather than poison the dataset. |
| 77 | + kept = [g for g in gens if g.get("num_tokens") is not None] |
| 78 | + dropped += len(gens) - len(kept) |
| 79 | + rows.extend(to_qe_rows(kept)) |
| 80 | + if dropped: |
| 81 | + print(f"WARNING: dropped {dropped} {split} row(s) with null num_tokens") |
| 82 | + _write_jsonl(rows, out / f"{split}.jsonl") |
| 83 | + sizes[split] = len(rows) |
| 84 | + return sizes |
| 85 | + |
| 86 | + |
| 87 | +def main(argv: list[str] | None = None) -> None: |
| 88 | + parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) |
| 89 | + parser.add_argument("--train", nargs="+", required=True, help="generations JSONL file(s) for the train split") |
| 90 | + parser.add_argument("--test", nargs="+", required=True, help="generations JSONL file(s) for the test split") |
| 91 | + parser.add_argument("--out", required=True, help="output directory for train.jsonl / test.jsonl") |
| 92 | + parser.add_argument("--push-to-hub", default=None, help="also push the DatasetDict to this HF hub id") |
| 93 | + parser.add_argument("--hub-private", action="store_true") |
| 94 | + args = parser.parse_args(argv) |
| 95 | + |
| 96 | + sizes = build(args.train, args.test, args.out) |
| 97 | + print(f"Wrote {args.out}/train.jsonl ({sizes['train']}) and test.jsonl ({sizes['test']})") |
| 98 | + label_pos = sum( |
| 99 | + 1 for line in open(Path(args.out) / "train.jsonl") if json.loads(line)["decision_label"] == 1 |
| 100 | + ) |
| 101 | + print(f"Train accept/route balance: {label_pos} accept / {sizes['train'] - label_pos} route") |
| 102 | + |
| 103 | + if args.push_to_hub: |
| 104 | + from datasets import load_dataset |
| 105 | + |
| 106 | + ds = load_dataset("json", data_files={ |
| 107 | + "train": str(Path(args.out) / "train.jsonl"), |
| 108 | + "test": str(Path(args.out) / "test.jsonl"), |
| 109 | + }) |
| 110 | + ds.push_to_hub(args.push_to_hub, private=args.hub_private) |
| 111 | + print(f"Pushed to {args.push_to_hub}") |
| 112 | + |
| 113 | + |
| 114 | +if __name__ == "__main__": |
| 115 | + main() |
0 commit comments