omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / bench / multipl-e / build_prompts.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Translate MultiPL-E's Python benchmarks to Omega and report coverage. |
| 4 | |
| 5 | Foreign-harness adapter (see bench/DEPENDENCIES.md). It runs MultiPL-E's own |
| 6 | dataset_builder/generic_translator.py, at the pinned MultiPL-E commit, with |
| 7 | humaneval_to_om.Translator, exactly as prepare_prompts_for_hfhub.py would, but |
| 8 | without the Hugging Face `datasets` dependency, and it records WHY each refused |
| 9 | problem was refused. |
| 10 | |
| 11 | bench/multipl-e/build_prompts.py --multipl-e /path/to/MultiPL-E [--out bench/prompts] |
| 12 | |
| 13 | Writes, per benchmark: <bench>-om.jsonl (MultiPL-E prompt records) and |
| 14 | <bench>-om.coverage.json, plus COVERAGE.md summarising both. |
| 15 | """ |
| 16 | |
| 17 | import argparse |
| 18 | import collections |
| 19 | import contextlib |
| 20 | import importlib |
| 21 | import io |
| 22 | import json |
| 23 | import os |
| 24 | import shutil |
| 25 | import subprocess |
| 26 | import sys |
| 27 | from pathlib import Path |
| 28 | |
| 29 | HERE = Path(__file__).resolve().parent |
| 30 | BENCH = HERE.parent |
| 31 | MULTIPLE_E_PIN = "3025a531af7450e7df8b96fe0440e9804480bbad" |
| 32 | # The upstream HumanEval has 164 problems; MultiPL-E's originals keep 161 (it drops |
| 33 | # HumanEval_32, _38 and _50, whose tests call helpers outside the prompt). |
| 34 | UPSTREAM_SIZES = {"humaneval": 164, "mbpp": None} |
| 35 | # (benchmark, originals directory, doctests mode, prompt terminology): the |
| 36 | # configurations MultiPL-E publishes as humaneval-<lang> and mbpp-<lang>. |
| 37 | CONFIGS = [ |
| 38 | ("humaneval", "originals-with-cleaned-doctests", "transform", "reworded"), |
| 39 | ("mbpp", "mbpp-typed", "transform", "reworded"), |
| 40 | ] |
| 41 | # Columns: name, ext, list, array, tuple, dictionary, None, True, False. Omega has no |
| 42 | # dictionary or None value; problems that use them are refused, so those words never land. |
| 43 | TERMS_ROW = "Omega,om,array,array,array,dictionary,none,true,false\n" |
| 44 | |
| 45 | |
| 46 | def pinned_multiple_e(root: Path) -> None: |
| 47 | head = subprocess.run( |
| 48 | ["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, check=True |
| 49 | ).stdout.strip() |
| 50 | if head != MULTIPLE_E_PIN: |
| 51 | sys.exit(f"build_prompts: MultiPL-E at {head}, pin is {MULTIPLE_E_PIN}; refusing") |
| 52 | |
| 53 | |
| 54 | def workdir(root: Path) -> Path: |
| 55 | """A scratch dataset_builder: MultiPL-E's translator modules plus ours, and |
| 56 | terms.csv with the Omega row (generic_translator reads ./terms.csv on import).""" |
| 57 | wd = BENCH / "build" / "dataset_builder" |
| 58 | if wd.exists(): |
| 59 | shutil.rmtree(wd) |
| 60 | wd.mkdir(parents=True) |
| 61 | for f in ("generic_translator.py", "base_language_translator.py", "terms.csv"): |
| 62 | shutil.copy(root / "dataset_builder" / f, wd / f) |
| 63 | shutil.copy(HERE / "humaneval_to_om.py", wd / "humaneval_to_om.py") |
| 64 | terms = (wd / "terms.csv").read_text() |
| 65 | if "\nOmega,om," not in terms: |
| 66 | (wd / "terms.csv").write_text(terms.rstrip("\n") + "\n" + TERMS_ROW) |
| 67 | return wd |
| 68 | |
| 69 | |
| 70 | def reason_from_log(log: str) -> str: |
| 71 | if "Failed to translate tests" in log: |
| 72 | return "tests:not all asserts are `assert f(...) == v` (MultiPL-E generic translator)" |
| 73 | if "Conflicting tests" in log: |
| 74 | return "tests:conflicting duplicate asserts" |
| 75 | if "Exception translating prompt" in log: |
| 76 | return "prompt:docstring or doctest not parseable (MultiPL-E generic translator)" |
| 77 | if "Exception translating test case" in log: |
| 78 | return "tests:expression outside MultiPL-E's literal grammar" |
| 79 | if "No tests were translated" in log: |
| 80 | return "tests:none" |
| 81 | return "unknown" |
| 82 | |
| 83 | |
| 84 | def build(root: Path, out: Path) -> dict: |
| 85 | pinned_multiple_e(root) |
| 86 | wd = workdir(root) |
| 87 | cwd = os.getcwd() |
| 88 | os.chdir(wd) |
| 89 | sys.path.insert(0, str(wd)) |
| 90 | try: |
| 91 | gt = importlib.import_module("generic_translator") |
| 92 | om = importlib.import_module("humaneval_to_om") |
| 93 | summary = {} |
| 94 | for bench, originals, doctests, terminology in CONFIGS: |
| 95 | translator = om.Translator() |
| 96 | files = sorted( |
| 97 | (root / "datasets" / originals).glob("*.py"), |
| 98 | key=lambda p: int(p.name.split("_")[1]), |
| 99 | ) |
| 100 | records, rows = [], [] |
| 101 | for f in files: |
| 102 | name = f.name[: -len(".py")] |
| 103 | buf = io.StringIO() |
| 104 | with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): |
| 105 | result = gt.translate_prompt_and_tests(f, translator, doctests, terminology) |
| 106 | if result is None: |
| 107 | r = translator.refusal |
| 108 | code = r.code if r is not None else reason_from_log(buf.getvalue()) |
| 109 | detail = r.detail if r is not None else "" |
| 110 | rows.append({"name": name, "translated": False, "reason": code, "detail": detail}) |
| 111 | continue |
| 112 | prompt, tests = result |
| 113 | records.append( |
| 114 | { |
| 115 | "name": name, |
| 116 | "language": translator.file_ext(), |
| 117 | "prompt": prompt, |
| 118 | "doctests": doctests, |
| 119 | "original": f"datasets/{originals}/{f.name}", |
| 120 | "prompt_terminology": terminology, |
| 121 | "tests": tests, |
| 122 | "stop_tokens": gt.get_stop_from_translator(translator), |
| 123 | } |
| 124 | ) |
| 125 | rows.append({"name": name, "translated": True, "cases": len(translator.cases)}) |
| 126 | with open(out / f"{bench}-om.jsonl", "w") as fh: |
| 127 | for rec in records: |
| 128 | fh.write(json.dumps(rec) + "\n") |
| 129 | reasons = collections.Counter(r["reason"] for r in rows if not r["translated"]) |
| 130 | cov = { |
| 131 | "benchmark": bench, |
| 132 | "originals": f"datasets/{originals}", |
| 133 | "multipl_e_commit": MULTIPLE_E_PIN, |
| 134 | "omega_mv_pin": om.OMEGA_MV_PIN, |
| 135 | "doctests": doctests, |
| 136 | "prompt_terminology": terminology, |
| 137 | "upstream_size": UPSTREAM_SIZES[bench], |
| 138 | "originals_count": len(files), |
| 139 | "translated": len(records), |
| 140 | "refused": len(files) - len(records), |
| 141 | "reasons": dict(reasons.most_common()), |
| 142 | "problems": rows, |
| 143 | } |
| 144 | with open(out / f"{bench}-om.coverage.json", "w") as fh: |
| 145 | json.dump(cov, fh, indent=1) |
| 146 | fh.write("\n") |
| 147 | summary[bench] = cov |
| 148 | return summary |
| 149 | finally: |
| 150 | os.chdir(cwd) |
| 151 | sys.path.remove(str(wd)) |
| 152 | |
| 153 | |
| 154 | def coverage_md(summary: dict) -> str: |
| 155 | lines = [ |
| 156 | "# MultiPL-E Omega coverage", |
| 157 | "", |
| 158 | "Generated by `bench/multipl-e/build_prompts.py`; do not edit by hand.", |
| 159 | f"MultiPL-E `{MULTIPLE_E_PIN}`, omega-mv pin `{next(iter(summary.values()))['omega_mv_pin']}`.", |
| 160 | "", |
| 161 | ] |
| 162 | for bench, cov in summary.items(): |
| 163 | up = cov["upstream_size"] |
| 164 | lines.append(f"## {bench}") |
| 165 | lines.append("") |
| 166 | if up: |
| 167 | lines.append( |
| 168 | f"{cov['translated']} of {up} translate ({up - cov['originals_count']} are already " |
| 169 | f"dropped by MultiPL-E's originals, {cov['refused']} of its {cov['originals_count']} are refused here)." |
| 170 | ) |
| 171 | else: |
| 172 | lines.append(f"{cov['translated']} of {cov['originals_count']} translate; {cov['refused']} refused.") |
| 173 | lines += ["", "| refusal reason | problems |", "|---|---|"] |
| 174 | for reason, n in cov["reasons"].items(): |
| 175 | lines.append(f"| `{reason}` | {n} |") |
| 176 | lines.append("") |
| 177 | return "\n".join(lines) |
| 178 | |
| 179 | |
| 180 | def main(): |
| 181 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 182 | ap.add_argument("--multipl-e", default=os.environ.get("MULTIPL_E"), help="MultiPL-E checkout at the pin") |
| 183 | ap.add_argument("--out", default=str(BENCH / "prompts")) |
| 184 | args = ap.parse_args() |
| 185 | if not args.multipl_e: |
| 186 | sys.exit("build_prompts: pass --multipl-e DIR or set MULTIPL_E") |
| 187 | out = Path(args.out) |
| 188 | out.mkdir(parents=True, exist_ok=True) |
| 189 | summary = build(Path(args.multipl_e).resolve(), out) |
| 190 | (out / "COVERAGE.md").write_text(coverage_md(summary)) |
| 191 | for bench, cov in summary.items(): |
| 192 | print(f"{bench}: {cov['translated']}/{cov['upstream_size'] or cov['originals_count']} translated " |
| 193 | f"({cov['originals_count']} originals, {cov['refused']} refused)") |
| 194 | |
| 195 | |
| 196 | if __name__ == "__main__": |
| 197 | main() |