File size: 7,301 Bytes
5ea2688
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""aurelius_serve.py — Aurelius v2 verifier-native serving (self-contained, no external repo deps).

Two MEASURED serving levers on the Qwen3-Coder-30B-A3B base:
  - math: maj@N self-consistency (verifier-free)               -> +8.2pp on MATH-500 level-5
  - code: best-of-N + one-step repair (caller tests = verifier) -> +10.5pp MBPP (measured on the v1 14B)

Usage:
    from aurelius_serve import AureliusServe
    s = AureliusServe()                                  # bf16 on an 80GB GPU; load_4bit=True won't help the 30B MoE
    s.solve("math", "<problem>")                         -> {answer, confidence, votes}
    s.solve("code", "<task asking for one ```python block>", tests="<assert lines>")  -> {code, how, passed, feedback}
"""
import re, subprocess, sys, tempfile, os
from collections import Counter
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

DEFAULT_MODEL = "Qwen/Qwen3-Coder-30B-A3B-Instruct"


def _boxed(t):
    i = t.rfind("\\boxed")
    if i == -1:
        nums = re.findall(r"-?\d+\.?\d*", t); return nums[-1] if nums else ""
    j = t.find("{", i)
    if j == -1: return ""
    depth = 0
    for k in range(j, len(t)):
        if t[k] == "{": depth += 1
        elif t[k] == "}":
            depth -= 1
            if depth == 0: return t[j+1:k]
    return t[j+1:]


def _norm(s):
    s = s.strip().replace("\\left", "").replace("\\right", "").replace("$", "").replace(" ", "")
    s = s.replace("\\!", "").replace("\\,", "").replace("dfrac", "frac").replace("tfrac", "frac")
    s = s.replace("^{\\circ}", "").replace("^\\circ", "").replace("\\circ", "")
    s = re.sub(r"\\text\{([^}]*)\}", r"\1", s).replace("\\%", "").replace("%", "")
    m = re.match(r"^[a-zA-Z]\=(.+)$", s)
    if m: s = m.group(1)
    s = s.rstrip(".")
    if ("," in s) or (";" in s):
        s = ",".join(sorted(p for p in re.split(r"[,;]", s) if p))
    return s


def _extract_code(text):
    text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
    text = re.sub(r"^.*?</think>", "", text, flags=re.DOTALL)
    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", text, re.DOTALL)
    return blocks[-1] if blocks else text.strip()


def _run(src, timeout=12):
    """Exec a self-contained program in a fresh subprocess -> (passed, feedback_tail)."""
    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
        f.write(src); path = f.name
    try:
        r = subprocess.run([sys.executable, path], capture_output=True, text=True, timeout=timeout)
        if r.returncode == 0: return True, ""
        return False, (r.stderr or r.stdout or "non-zero exit").strip()[-800:]
    except subprocess.TimeoutExpired:
        return False, "timeout (likely an infinite loop)"
    finally:
        os.unlink(path)


class AureliusServe:
    def __init__(self, model_id=DEFAULT_MODEL, load_4bit=False):
        self.dev = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
        self.tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
        if self.tok.pad_token is None: self.tok.pad_token = self.tok.eos_token
        self.tok.padding_side = "left"
        if load_4bit:                                            # note: 30B-A3B MoE doesn't 4-bit-shrink; use a GGUF for low-VRAM
            from transformers import BitsAndBytesConfig
            cdt = torch.bfloat16 if (self.dev == "cuda" and torch.cuda.is_bf16_supported()) else torch.float16
            bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                                     bnb_4bit_compute_dtype=cdt, bnb_4bit_use_double_quant=True)
            self.model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb,
                                                              device_map={"": 0}, trust_remote_code=True).eval()
        else:
            self.model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16,
                                                              trust_remote_code=True).to(self.dev).eval()

    def _msg(self, ask, think):
        kw = {} if think else {"enable_thinking": False}
        try:
            return self.tok.apply_chat_template([{"role": "user", "content": ask}], tokenize=False,
                                                add_generation_prompt=True, **kw)
        except TypeError:
            return self.tok.apply_chat_template([{"role": "user", "content": ask}], tokenize=False,
                                                add_generation_prompt=True)

    def _gen(self, prompt, n, temp, max_new, think):
        enc = self.tok(self._msg(prompt, think), return_tensors="pt", add_special_tokens=False).to(self.dev)
        kw = dict(max_new_tokens=max_new, pad_token_id=self.tok.eos_token_id, use_cache=True)
        kw.update(dict(num_return_sequences=n, do_sample=True, temperature=temp, top_p=0.95) if n > 1 else dict(do_sample=False))
        with torch.no_grad():
            out = self.model.generate(**enc, **kw)
        L = enc["input_ids"].shape[1]
        return [self.tok.decode(r[L:], skip_special_tokens=True) for r in out]

    def solve_math(self, problem, n=8, temp=0.8, max_new=4096):
        ask = f"Solve this problem. Put the final answer in \\boxed{{}}.\n\n{problem}"
        samples = self._gen(ask, n, temp, max_new, think=1)
        votes = Counter(a for a in (_norm(_boxed(s)) for s in samples) if a)
        if not votes: return dict(answer=None, confidence=0.0, votes={}, raw=samples)
        ans, cnt = votes.most_common(1)[0]
        return dict(answer=ans, confidence=cnt / n, votes=dict(votes), raw=samples)

    def solve_code(self, prompt, tests, n=8, repair=1, temp=0.8, max_new=768, timeout=12):
        check = lambda code: code + "\n" + tests + "\n"
        g = _extract_code(self._gen(prompt, 1, 0.0, max_new, think=0)[0])
        ok, last_fb = _run(check(g), timeout)
        if ok: return dict(code=g, how="greedy", passed=True, feedback="")
        near = None
        for c in (_extract_code(x) for x in self._gen(prompt, n, temp, max_new, think=0)):
            ok, fb = _run(check(c), timeout)
            if ok: return dict(code=c, how=f"best-of-{n}", passed=True, feedback="")
            last_fb = fb
            if near is None and c.strip(): near = c
        base_c = near or g
        for _ in range(repair):
            fb = _run(check(base_c), timeout)[1]
            rep = (prompt + f"\n\nYour previous attempt:\n```python\n{base_c}\n```\nIt FAILED with:\n{fb}\n\n"
                   f"Return a corrected COMPLETE solution in one ```python code block.")
            rc = _extract_code(self._gen(rep, 1, 0.0, max_new, think=0)[0])
            ok, fb2 = _run(check(rc), timeout)
            if ok: return dict(code=rc, how="repair", passed=True, feedback="")
            base_c, last_fb = rc, fb2
        return dict(code=base_c, how="exhausted", passed=False, feedback=last_fb)

    def solve(self, kind, problem, tests=None, n=8):
        if kind == "math": return self.solve_math(problem, n=n)
        if kind == "code":
            assert tests is not None, "code needs `tests` (assert string) as the verifier"
            return self.solve_code(problem, tests, n=n)
        raise ValueError("kind must be 'math' or 'code'")