Run this model with HF Jobs

Run enver/rootformer-code-v19.2-qwen38-nwp on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 9,934 Bytes
c5a2aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff008a
 
 
 
 
c5a2aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
eval_code_sandbox.py
====================
Fast, isolated multiprocessing Python 3 execution sandbox for evaluating:
  1. **HumanEval+** (`164` EvalPlus tasks)
  2. **MBPP+** (`378` EvalPlus tasks)
  3. **TurāthCode-50** (`50` identifier-morphology, API-contract, AST/compiler, systems, & Arabic-spec tasks)

Every task runs in a clean child subprocess with strict wall-clock timeout (default `6.0s`) and clean
stdout/stderr suppression so infinite loops, recursion overflows, or crashes never hang the harness.
"""

from __future__ import annotations

import ast
import concurrent.futures
import json
import os
import re
import subprocess
import sys
import tempfile
import textwrap
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple


_CODE_FENCE_RE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", flags=re.DOTALL | re.IGNORECASE)
_THINK_RE = re.compile(r"<think>.*?</think>", flags=re.DOTALL)


def extract_python_code(raw_output: str) -> str:
    """Robustly extracts Python code from fenced or raw LLM output (strictly post-</think>)."""
    txt = _THINK_RE.sub("", raw_output)
    if "</think>" in txt:
        txt = txt.rsplit("</think>", 1)[-1]
    txt = txt.replace("<|im_end|>", "").strip()
    blocks = _CODE_FENCE_RE.findall(txt)
    if blocks:
        # Pick the longest valid-looking Python code block
        for b in sorted(blocks, key=len, reverse=True):
            b_clean = b.strip()
            try:
                ast.parse(b_clean)
                return b_clean
            except SyntaxError:
                pass
        return blocks[-1].strip()

    # Fallback: strip any leading prose before `def ` / `class ` / `import ` / `from `
    lines = txt.splitlines()
    for idx, line in enumerate(lines):
        if re.match(r"^(?:from\s+\S+\s+import|import\s+\S+|def\s+|async\s+def\s+|class\s+|@)", line):
            return "\n".join(lines[idx:]).strip()
    return txt


def _run_script_subprocess(script_code: str, timeout_sec: float = 6.0, use_temp_cwd: bool = False) -> Tuple[bool, str]:
    """Executes `script_code` in an isolated Python 3 child process with hard timeout."""
    tmp_dir_obj = tempfile.TemporaryDirectory() if use_temp_cwd else None
    cwd_path = tmp_dir_obj.name if tmp_dir_obj is not None else None
    with tempfile.NamedTemporaryFile("w", suffix=".py", encoding="utf-8", delete=False, dir=cwd_path) as tf:
        tf.write(script_code)
        tmp_path = tf.name
    try:
        proc = subprocess.run(
            [sys.executable, "-I", tmp_path],
            cwd=cwd_path,
            capture_output=True,
            text=True,
            timeout=timeout_sec,
            env={"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "PYTHONHASHSEED": "0"},
        )
        if proc.returncode == 0:
            return True, ""
        err = (proc.stderr or proc.stdout or f"exit={proc.returncode}").strip()
        return False, err[-400:]
    except subprocess.TimeoutExpired:
        return False, f"TimeoutError: exceeded {timeout_sec:.1f}s"
    except Exception as e:
        return False, f"SandboxError: {type(e).__name__}: {e}"
    finally:
        try:
            os.unlink(tmp_path)
        except OSError:
            pass
        if tmp_dir_obj is not None:
            try:
                tmp_dir_obj.cleanup()
            except Exception:
                pass


def eval_humaneval_plus_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 8.0) -> Tuple[bool, str]:
    """Evaluates a single HumanEval+ task against the full EvalPlus hardened `check(candidate)` harness."""
    code = extract_python_code(generated_code)
    entry = task["entry_point"]
    # If model output omitted the function header and only emitted the indented body, prepend prompt!
    try:
        tree = ast.parse(code)
        has_entry = any(
            isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == entry
            for n in tree.body
        )
    except SyntaxError:
        has_entry = False

    if not has_entry:
        # Try combining original HumanEval prompt header + raw completion
        combined = task["prompt"] + "\n" + textwrap.indent(code, "    ") if not code.startswith((" ", "\t")) else task["prompt"] + code
        full_prog = f"{combined}\n\n{task['test']}\n\ncheck({entry})\n"
    else:
        # Keep imports from prompt (e.g. `from typing import List`) before model's full implementation
        prompt_imports = "\n".join(
            l for l in task["prompt"].splitlines()
            if l.startswith(("from ", "import "))
        )
        full_prog = f"{prompt_imports}\n{code}\n\n{task['test']}\n\ncheck({entry})\n"
    return _run_script_subprocess(full_prog, timeout_sec=timeout_sec)


def eval_mbpp_plus_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 8.0) -> Tuple[bool, str]:
    """Evaluates a single MBPP+ task against the full EvalPlus hardened test script."""
    code = extract_python_code(generated_code)
    imports = "\n".join(task.get("test_imports") or [])
    test_body = task.get("test") or "\n".join(task.get("test_list") or [])
    full_prog = f"{imports}\n{code}\n\n{test_body}\n"
    return _run_script_subprocess(full_prog, timeout_sec=timeout_sec)


def eval_turath_code_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 6.0) -> Tuple[bool, str]:
    """Evaluates a single TurāthCode-50 task (with optional pre-provided `setup_code` library stubs)."""
    code = extract_python_code(generated_code)
    setup = task.get("setup_code", "")
    test_code = task["test_code"]
    full_prog = f"{setup}\n\n{code}\n\n{test_code}\n"
    return _run_script_subprocess(full_prog, timeout_sec=timeout_sec)


def eval_bigcodebench_one(task: Dict[str, Any], generated_code: str, timeout_sec: float = 10.0) -> Tuple[bool, str]:
    """Evaluates a single BigCodeBench-Hard task against its full `unittest` suite in a clean temp cwd."""
    code = extract_python_code(generated_code)
    entry = task.get("entry_point", "task_func")
    code_prompt = task.get("code_prompt", "")
    try:
        tree = ast.parse(code)
        has_entry = any(
            isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == entry
            for n in tree.body
        )
    except SyntaxError:
        has_entry = False

    if not has_entry:
        combined = code_prompt + "\n" + textwrap.indent(code, "    ") if not code.startswith((" ", "\t")) else code_prompt + code
        full_prog = f"{combined}\n\n{task['test']}\n\nif __name__ == '__main__':\n    unittest.main()\n"
    else:
        prompt_imports = "\n".join(
            l for l in code_prompt.splitlines()
            if l.startswith(("from ", "import "))
        )
        full_prog = f"{prompt_imports}\n{code}\n\n{task['test']}\n\nif __name__ == '__main__':\n    unittest.main()\n"
    return _run_script_subprocess(full_prog, timeout_sec=timeout_sec, use_temp_cwd=True)


def evaluate_batch_parallel(
    suite_kind: str,
    tasks: List[Dict[str, Any]],
    outputs: List[str],
    max_workers: int = 8,
    timeout_sec: float = 8.0,
) -> Dict[str, Any]:
    """Evaluates an entire benchmark suite in parallel across CPU workers."""
    fn_map = {
        "humaneval_plus": eval_humaneval_plus_one,
        "mbpp_plus": eval_mbpp_plus_one,
        "turath_code_50": eval_turath_code_one,
        "bigcodebench_hard": eval_bigcodebench_one,
    }
    eval_fn = fn_map[suite_kind]
    results: List[Dict[str, Any]] = [{} for _ in range(len(tasks))]

    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
        fut_to_idx = {
            ex.submit(eval_fn, t, out, timeout_sec): i
            for i, (t, out) in enumerate(zip(tasks, outputs))
        }
        for fut in concurrent.futures.as_completed(fut_to_idx):
            idx = fut_to_idx[fut]
            ok, err = fut.result()
            t = tasks[idx]
            results[idx] = {
                "task_id": str(t.get("task_id", t.get("id", idx))),
                "category": t.get("category", suite_kind),
                "passed": bool(ok),
                "error": err,
            }

    passed = sum(1 for r in results if r["passed"])
    by_cat: Dict[str, Dict[str, int]] = {}
    for r in results:
        c = r["category"]
        by_cat.setdefault(c, {"passed": 0, "total": 0})
        by_cat[c]["total"] += 1
        if r["passed"]:
            by_cat[c]["passed"] += 1

    return {
        "suite": suite_kind,
        "passed": passed,
        "total": len(tasks),
        "pass_at_1_pct": round(100.0 * passed / max(1, len(tasks)), 2),
        "by_category": {k: f"{v['passed']}/{v['total']}" for k, v in sorted(by_cat.items())},
        "details": results,
    }


def _self_test_evalplus() -> None:
    bdir = Path("/root/rootformer/stage15.2/data/stage18_1/benchmarks")
    he = [json.loads(l) for l in (bdir / "humanevalplus.jsonl").read_text().splitlines() if l.strip()]
    mb = [json.loads(l) for l in (bdir / "mbppplus.jsonl").read_text().splitlines() if l.strip()]

    # Verify canonical solutions on first 10 HumanEval+ and first 10 MBPP+ tasks
    he_sols = [t["prompt"] + t["canonical_solution"] for t in he[:10]]
    mb_sols = [t["code"] for t in mb[:10]]
    r_he = evaluate_batch_parallel("humaneval_plus", he[:10], he_sols, max_workers=6)
    r_mb = evaluate_batch_parallel("mbpp_plus", mb[:10], mb_sols, max_workers=6)
    print(f"SANDBOX_SELF_TEST: HumanEval+[:10]={r_he['passed']}/{r_he['total']} | MBPP+[:10]={r_mb['passed']}/{r_mb['total']}")
    assert r_he["passed"] == 10, f"HumanEval+ canonical failed: {[d for d in r_he['details'] if not d['passed']]}"
    assert r_mb["passed"] == 10, f"MBPP+ canonical failed: {[d for d in r_mb['details'] if not d['passed']]}"
    print("EVAL_CODE_SANDBOX_SELF_TEST_PASSED")


if __name__ == "__main__":
    _self_test_evalplus()