mad3man0's picture
Inkling 2 Mini prune map: routing, keep lists, results, agent transcripts, expert map, tools
f93f1b8 verified
Raw History Blame Contribute Delete
9.16 kB
"""Task tests through a running llama-server (architecture 6.5). Extends legacy evaltasks.py and gsm.py.
python3 tasks.py --url http://127.0.0.1:PORT --test humaneval|mbpp|gsm8k|mmlu --n N --version V \
--tests /srv/prune/data/texts/tests --out /srv/prune/out [--effort 0] [--max-tokens M] [--concurrency 12]
Writes <out>/per_problem/<V>__<test>.jsonl, one line per problem (resumable by id), and prints ONE JSON line:
{version, test, n, correct, score, finished_share, tokens_mean, wall_s, effort}, computed from the per-problem file.
Only message.content is graded, never reasoning_content. finish_reason "length" = wrong and unfinished.
A file written at one (effort, max_tokens) is never continued at another: use a different --version
(e.g. full-think) for the thinking-on run. Requests that fail after retries are not written; the exit code is
then 3 and a rerun retries them.
Generated code runs with `python3 -I` (this interpreter) in a fresh temp dir, 10 s limit.
"""
import argparse
import concurrent.futures as cf
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
MAX_TOKENS = {'humaneval': 3000, 'mbpp': 3000, 'gsm8k': 2000, 'mmlu': 1000}
# ------------------------------------------------------------------------------------------- graders
def extract_code(txt):
"""Last fenced code block (```python, ```py or bare ```); the whole reply if there is none."""
blocks = re.findall(r'```[ \t]*(?:python3?|py)?[ \t]*\n(.*?)```', txt, re.S | re.I)
return blocks[-1] if blocks else txt
def last_number(txt):
nums = re.findall(r'-?\d[\d,]*(?:\.\d+)?', txt)
if not nums:
return None
try:
return float(nums[-1].replace(',', ''))
except ValueError:
return None
def gold_number(answer):
return float(answer.split('####')[-1].strip().replace(',', ''))
def last_letter(txt):
m = re.findall(r'(?<![A-Za-z0-9])([ABCD])(?![A-Za-z0-9])', txt)
return m[-1] if m else None
def run_python(prog, timeout=10):
"""True if `prog` exits 0 under `python3 -I` in a fresh temp dir within `timeout` seconds."""
d = tempfile.mkdtemp(prefix='task_')
try:
with open(os.path.join(d, 'prog.py'), 'w') as f:
f.write(prog)
p = subprocess.Popen([sys.executable, '-I', 'prog.py'], cwd=d, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
try:
return p.wait(timeout=timeout) == 0
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL) # by pid of the child we started
p.wait()
return False
finally:
shutil.rmtree(d, ignore_errors=True)
def humaneval_program(p, reply):
code = extract_code(reply)
if re.search(rf'def\s+{re.escape(p["entry_point"])}\s*\(', code):
# keep the prompt's imports and helper functions; the reply's definition replaces the stub
head = p['prompt'].rstrip('\n') + '\n pass\n\n'
else:
head = p['prompt'] # reply is the body only
return head + code + '\n\n' + p['test'] + f'\n\ncheck({p["entry_point"]})\n'
def mbpp_program(p, reply):
return '\n'.join(p.get('test_imports') or []) + '\n' + extract_code(reply) + '\n\n' + '\n'.join(p['test_list']) + '\n'
def grade(test, p, reply):
if test == 'humaneval':
return run_python(humaneval_program(p, reply))
if test == 'mbpp':
return run_python(mbpp_program(p, reply))
if test == 'gsm8k':
pred = last_number(reply)
return pred is not None and abs(pred - gold_number(p['answer'])) < 1e-6
if test == 'mmlu':
return last_letter(reply) == p['answer']
raise ValueError(test)
# ------------------------------------------------------------------------------------------- prompts
def prompt(test, p):
if test == 'humaneval':
return 'Complete this Python function. Reply with the whole function in one ```python code block.\n\n' + p['prompt']
if test == 'mbpp':
return (p['prompt'] + '\nYour code should pass these tests:\n' + '\n'.join(p['test_list'])
+ '\nReply with the Python code in one ```python code block.')
if test == 'gsm8k':
return p['question'] + '\nPut the final answer as a plain number on the last line.'
if test == 'mmlu':
opts = '\n'.join(f'{L}. {c}' for L, c in zip('ABCD', p['choices']))
return (f'{p["question"]}\n\n{opts}\n\n'
'Answer with the letter of the correct option (A, B, C or D) on the last line.')
raise ValueError(test)
def chat(url, content, effort, max_tokens):
body = {'messages': [{'role': 'user', 'content': content}], 'max_tokens': max_tokens, 'temperature': 0,
'chat_template_kwargs': {'reasoning_effort': effort}}
req = urllib.request.Request(url.rstrip('/') + '/v1/chat/completions', data=json.dumps(body).encode(),
headers={'Content-Type': 'application/json'})
return json.loads(urllib.request.urlopen(req, timeout=3600).read())
# ------------------------------------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--url', required=True)
ap.add_argument('--test', required=True, choices=list(MAX_TOKENS))
ap.add_argument('--n', type=int, default=0, help='first N problems (0 = all)')
ap.add_argument('--version', required=True)
ap.add_argument('--tests', default='/srv/prune/data/texts/tests')
ap.add_argument('--out', default='/srv/prune/out')
ap.add_argument('--effort', type=float, default=0)
ap.add_argument('--max-tokens', type=int, default=0)
ap.add_argument('--concurrency', type=int, default=12)
ap.add_argument('--reverse', action='store_true', help='helper mode: last problems first, skip ids already in the file')
a = ap.parse_args()
effort = int(a.effort) if a.effort == int(a.effort) else a.effort
max_tokens = a.max_tokens or MAX_TOKENS[a.test]
probs = [json.loads(x) for x in open(f'{a.tests}/{a.test}.jsonl')]
if a.n:
probs = probs[:a.n]
os.makedirs(f'{a.out}/per_problem', exist_ok=True)
path = f'{a.out}/per_problem/{a.version}__{a.test}.jsonl'
done = {}
if os.path.exists(path):
for line in open(path):
r = json.loads(line)
if (r['effort'], r['max_tokens']) != (effort, max_tokens):
sys.exit(f'{path} was written at effort {r["effort"]}, max_tokens {r["max_tokens"]}; use another --version')
done[r['id']] = r
todo = [p for p in probs if p['id'] not in done]
lock = threading.Lock()
errors = []
urls = a.url.split(',') # several servers (one per card): problems spread round-robin, 12 in flight per server
def seen():
try:
return {json.loads(x)['id'] for x in open(path) if x.strip()}
except OSError:
return set()
def one(ip):
i, p = ip
if a.reverse and p['id'] in seen(): # another process (the driver's) already scored it
return
d = None
for attempt in range(3):
try:
d = chat(urls[i % len(urls)], prompt(a.test, p), effort, max_tokens)
break
except Exception as e:
err = repr(e)[:200]
time.sleep(5 * (attempt + 1))
if d is None:
with lock:
errors.append(err)
return
c = d['choices'][0]
msg = c.get('message') or {}
content = msg.get('content') or ''
finished = c.get('finish_reason') != 'length'
ok = finished and grade(a.test, p, content)
rec = {'id': p['id'], 'ok': bool(ok), 'finished': finished, 'tokens': d.get('usage', {}).get('completion_tokens', 0),
'think_chars': len(msg.get('reasoning_content') or ''), 'effort': effort, 'max_tokens': max_tokens,
'reply_tail': content[-300:]}
with lock:
with open(path, 'a') as f:
f.write(json.dumps(rec) + '\n')
done[p['id']] = rec
t0 = time.time()
with cf.ThreadPoolExecutor(a.concurrency * len(urls)) as ex:
list(ex.map(one, enumerate(todo[::-1] if a.reverse else todo)))
rows = [done[p['id']] for p in probs if p['id'] in done]
n = len(rows)
correct = sum(r['ok'] for r in rows)
print(json.dumps({'version': a.version, 'test': a.test, 'n': n, 'correct': correct,
'score': round(correct / n, 4) if n else 0.0,
'finished_share': round(sum(r['finished'] for r in rows) / n, 4) if n else 0.0,
'tokens_mean': round(sum(r['tokens'] for r in rows) / n, 1) if n else 0.0,
'wall_s': round(time.time() - t0, 1), 'effort': effort,
**({'missing': len(probs) - n, 'errors': errors[:3]} if n < len(probs) else {})}))
if n < len(probs):
sys.exit(3)
if __name__ == '__main__':
main()