Download examples/run_model.py from simonlqy/ProWM-Bench: direct link, hf CLI and curl.
- Browser
- Download file 5.35 kB
-
https://huggingface.co/datasets/simonlqy/ProWM-Bench/resolve/main/examples/run_model.py
- Command line
-
hf download hf://datasets/simonlqy/ProWM-Bench/examples/run_model.py
-
curl -L -o run_model.py https://huggingface.co/datasets/simonlqy/ProWM-Bench/resolve/main/examples/run_model.py
5.35 kB
| """Example model adapter using an HTTP chat-completions endpoint. | |
| From the unpacked directory: | |
| python3 examples/run_model.py --subset swemm --base-url http://localhost:8000/v1 --model YOUR_MODEL --output predictions.jsonl | |
| python3 -m prowm_bench score --subset swemm --predictions predictions.jsonl | |
| Only public prompts enter requests. Requires a compatible model server, not a | |
| particular SDK. The server must support PNG data URLs and the chosen generation | |
| settings. The paper uses a 131072-token context and 32768-token output budget; | |
| keep prompts unchanged and count overflow/failed requests as zero. This example | |
| makes one request per branch, with no retries or answer filtering. It records | |
| errors so scoring keeps the complete denominator. No model request is made by | |
| the loader, scorer, verification command, or tests. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import urllib.error | |
| import urllib.request | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from prowm_bench import load_dataset # noqa: E402 | |
| from prowm_bench.scoring import load_predictions # noqa: E402 | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument('--subset', choices=('swemm', 'rs'), required=True) | |
| parser.add_argument('--base-url', required=True, help='chat-completions API prefix, e.g. http://localhost:8000/v1') | |
| parser.add_argument('--model', required=True) | |
| parser.add_argument('--output', required=True, type=Path) | |
| parser.add_argument('--api-key-env', default='OPENAI_API_KEY', help='optional environment variable; keys are not saved') | |
| parser.add_argument('--max-tokens', default=32768, type=int) | |
| parser.add_argument('--timeout', default=1800, type=float) | |
| parser.add_argument('--limit', type=int, help='limit items for integration checking; incomplete results are not a paper evaluation') | |
| parser.add_argument('--resume', action='store_true', help='skip already recorded item/branch pairs, including failures') | |
| parser.add_argument('--request-options', type=Path, help='JSON object with model-specific generation fields, e.g. temperature/thinking options; saved in each output row') | |
| args = parser.parse_args() | |
| if args.max_tokens < 1 or args.timeout <= 0 or args.limit is not None and args.limit < 1: | |
| parser.error('token, timeout and limit values must be positive') | |
| options = json.loads(args.request_options.read_text(encoding='utf-8')) if args.request_options else {} | |
| if not isinstance(options, dict) or set(options) & {'messages', 'model', 'tools', 'tool_choice', 'stream', 'n', 'max_tokens'}: | |
| parser.error('request options must be an object and cannot override model/messages/tools/stream/n/max_tokens') | |
| dataset = load_dataset(args.subset) | |
| settings = {'model': args.model, 'max_tokens': args.max_tokens, **options} | |
| seen = set() | |
| if args.resume and args.output.exists(): | |
| previous = load_predictions(args.output, set(dataset.items)) | |
| if any(entry.get('generation') != settings for entry in previous.values()): | |
| parser.error('resume requires the same model and generation settings as existing records') | |
| seen = set(previous) | |
| mode = 'a' if args.resume else 'x' | |
| url = args.base_url.rstrip('/') + '/chat/completions' | |
| headers = {'Content-Type': 'application/json'} | |
| key = os.environ.get(args.api_key_env) | |
| if key: | |
| headers['Authorization'] = 'Bearer ' + key | |
| with args.output.open(mode, encoding='utf-8') as output: | |
| for request in dataset.requests(limit=args.limit): | |
| pair = request['item_id'], request['branch'] | |
| if pair in seen: | |
| continue | |
| record = {'item_id': pair[0], 'branch': pair[1], 'generation': settings, | |
| 'response': None, 'finish_reason': None} | |
| body = json.dumps({**settings, 'messages': request['messages'], 'stream': False}, | |
| ensure_ascii=False, allow_nan=False).encode() | |
| try: | |
| req = urllib.request.Request(url, data=body, headers=headers, method='POST') | |
| with urllib.request.urlopen(req, timeout=args.timeout) as response: | |
| payload = json.loads(response.read()) | |
| choices = payload['choices'] | |
| if len(choices) != 1: | |
| raise ValueError('expected exactly one completion') | |
| choice = choices[0] | |
| if choice['message'].get('tool_calls'): | |
| raise ValueError('tool calls are outside the benchmark protocol') | |
| record.update(response=choice['message']['content'], finish_reason=choice['finish_reason'], usage=payload.get('usage')) | |
| except urllib.error.HTTPError as error: | |
| record['error'] = f'HTTP {error.code}' | |
| except (OSError, ValueError, KeyError, TypeError, IndexError) as error: | |
| record['error'] = type(error).__name__ | |
| output.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + '\n') | |
| output.flush() | |
| seen.add(pair) | |
| print(f'{len(seen)} recorded: {pair[0]} / {pair[1]}', file=sys.stderr) | |
| if __name__ == '__main__': | |
| main() | |