import argparse from collections import Counter from concurrent.futures import ThreadPoolExecutor, as_completed import csv from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import random import re import sys import threading import time from time import monotonic from urllib.request import urlopen import httpx STEER = ( 'Your previous response was cut off by the output-token limit. Use the work ' 'already done and finish the original question. Do not restart or repeat the ' 'derivation. Give your final choice as ANSWER: $LETTER.' ) def solve(exchange, prompt, max_continuations=2): messages = [{'role': 'user', 'content': prompt}] start = monotonic() usage = Counter() finishes = [] for continuations in range(max_continuations + 1): response, partial = exchange(messages) if 'error' in response: if not finishes: return response record['continuation_error'] = response['error'] break record = response finishes.append(record['finish']) usage.update({ key: value for key, value in record.get('tokens', {}).items() if isinstance(value, int) }) if record['finish'] != 'length' or record['picked'] is not None or not partial.strip(): break if continuations < max_continuations: messages.extend([ {'role': 'assistant', 'content': partial}, {'role': 'user', 'content': STEER}, ]) return {**record, 'continuation_policy': 'cutoff-context-v1', 'continuations': continuations, 'call_finishes': finishes, 'tokens': dict(usage), 'seconds': round(monotonic() - start, 2)} parser = argparse.ArgumentParser() mode = parser.add_mutually_exclusive_group(required=True) mode.add_argument('--only', choices=('bharat-deepseek', 'mistral-deepseek')) mode.add_argument('--summarize', action='store_true') parser.add_argument('--workers', type=int) parser.add_argument('--recover-cutoffs', action='store_true') args = parser.parse_args() if args.workers is not None and args.workers < 1: parser.error('--workers must be at least 1') if args.summarize and args.recover_cutoffs: parser.error('--recover-cutoffs requires --only') targets = { 'bharat-deepseek': ('https://bharatcode.ai/api/model/v1', 'deepseek-v4.1-flash', 'BHARATCODE_API_KEY'), 'mistral-deepseek': ('https://api.mistral.ai/v1', 'deepseek-v4-1-flash-1017', 'MISTRAL_API_KEY'), } dataset_path = Path('diamond.csv') dataset_url = 'https://openaipublic.blob.core.windows.net/simple-evals/gpqa_diamond.csv' dataset_sha256 = '41d1213cd7a4998605a26c2798500652572007161b3a92817ba46b35befcd305' if not dataset_path.exists(): with urlopen(dataset_url, timeout=30) as response: data = response.read() if hashlib.sha256(data).hexdigest() != dataset_sha256: sys.exit('GPQA Diamond checksum mismatch') dataset_path.write_bytes(data) if hashlib.sha256(dataset_path.read_bytes()).hexdigest() != dataset_sha256: sys.exit('GPQA Diamond checksum mismatch') with open('diamond.csv', newline='', encoding='utf-8-sig') as dataset: rows = list(csv.DictReader(dataset)) assert len(rows) == len({row['Record ID'] for row in rows}) == 198 letters = 'ABCD' rng = random.Random(42) samples = [] for row in rows: columns = ['Correct Answer', 'Incorrect Answer 1', 'Incorrect Answer 2', 'Incorrect Answer 3'] rng.shuffle(columns) choices = '\n'.join(f'{letter}) {row[column]}' for letter, column in zip(letters, columns)) prompt = ( "Answer the following multiple choice question. The last line of your response should be of " "the following format: 'ANSWER: $LETTER' (without quotes) where LETTER is one of A,B,C,D. " f"Think step by step before answering.\n\n{row['Question']}\n\n{choices}" ) samples.append((row['Record ID'], row['High-level domain'], letters[columns.index('Correct Answer')], prompt)) def answer(text): text = re.sub(r'\$\s*([A-Za-z\d][A-Za-z\d ,]*?)\s*\$', r'\1', text) text = re.sub(r'\*\*\s*([A-Za-z\d][A-Za-z\d ,]*?)\s*\*\*', r'\1', text) text = re.sub(r'(?i)(^|[:,])(\s*)\(([A-Za-z\d])\)(?=\s*(?:,|\.|\n|\Z))', r'\1\2\3', text) matches = re.findall(r'(?im)^ANSWER\s*:\s*([A-Za-z\d ,]+)\s*(?:$|\n|\.)', text) if not matches: matches = re.findall(r'(?i)ANSWER\s*:\s*([A-Za-z\d ,]+)(?:[^\w]|\n|$|\.)', text) if matches: result = [t for t in matches[-1].strip().upper().split(',') if t] if len(result) == 1 and result[0] in tuple(letters): return result[0] assert answer('Step 1.\n**ANSWER: B**') == 'B' assert answer('ANSWER: C\nANSWER: D') == 'D' assert answer('ANSWER: (A)') == 'A' assert answer('ANSWER: A,C') is None client = httpx.Client(timeout=httpx.Timeout(240, connect=15), follow_redirects=False) halt = {label: threading.Event() for label in targets} gates = {label: threading.Lock() for label in targets} cooldowns = {label: 0.0 for label in targets} def request(label, sample, messages, max_tokens): sample_id, domain, expected, _ = sample base, model, key_name = targets[label] key = os.environ[key_name] body = {'model': model, 'messages': messages, 'temperature': 0, 'max_tokens': max_tokens, 'stream': True, 'stream_options': {'include_usage': True}, 'reasoning_effort': 'high'} if label == 'mistral-deepseek': body.pop('stream_options') start = time.monotonic() record = {'id': sample_id, 'domain': domain, 'expected': expected} if not key: return {**record, 'error': 'missing credential'}, '' for attempt in range(1, 5): if halt[label].is_set(): return {**record, 'error': 'skipped after terminal provider error'}, '' with gates[label]: delay = cooldowns[label] - time.monotonic() if delay > 0: time.sleep(delay) tokens = {} content = [] reasoning = [] finish = None served = None policy = None try: with client.stream('POST', f'{base}/chat/completions', headers={'Authorization': f'Bearer {key}'}, json=body) as response: policy = response.headers.get('x-data-policy') if response.is_error: error = f'HTTP {response.status_code}' if response.status_code in (400, 401, 402, 403, 404, 422): halt[label].set() return {**record, 'error': error, 'attempts': attempt}, '' if response.status_code == 429: try: delay = min(300, max(5, float(response.headers.get('retry-after', 8 * attempt)))) except ValueError: delay = 8 * attempt with gates[label]: cooldowns[label] = max(cooldowns[label], time.monotonic() + delay) raise RuntimeError(error) for line in response.iter_lines(): if not line.startswith('data:'): continue data = line[5:].strip() if data == '[DONE]': break frame = json.loads(data) if frame.get('error'): raise RuntimeError('API stream error') if frame.get('id') != 'chatcmpl-bharatcode-keepalive': served = frame.get('model') or served tokens = frame.get('usage') or tokens for choice in frame.get('choices', []): delta = choice.get('delta', {}) chunk = delta.get('content') if isinstance(chunk, str): content.append(chunk) elif isinstance(chunk, list): for item in chunk: if item.get('type') == 'text': content.append(item.get('text') or '') elif item.get('type') == 'thinking': reasoning.extend(part.get('text') or '' for part in item.get('thinking', [])) reasoning.append(delta.get('reasoning_content') or delta.get('reasoning') or '') finish = choice.get('finish_reason') or finish if not finish: raise RuntimeError('incomplete stream') completion = ''.join(content) picked = answer(completion) thought = ''.join(reasoning) partial = '\n\n'.join(filter(None, (thought, completion))) if finish == 'length' and picked is None else '' return {**record, 'picked': picked, 'correct': picked == expected, 'finish': finish, 'served': served, 'data_policy': policy, 'tokens': tokens, 'reasoning_chars': len(thought), 'content_chars': len(completion), 'attempts': attempt, 'seconds': round(time.monotonic() - start, 2)}, partial except (RuntimeError, ValueError, httpx.HTTPError) as exc: error = str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__ if attempt < 4: time.sleep(2 ** attempt) return {**record, 'error': error, 'attempts': attempt, 'seconds': round(time.monotonic() - start, 2)}, '' def run(label, sample): prompt = sample[3] if args.recover_cutoffs: return solve(lambda messages: request(label, sample, messages, 32000), prompt) record, _ = request(label, sample, [{'role': 'user', 'content': prompt}], 32000) return record def is_unanswered_cutoff(record): return record.get('finish') == 'length' and record.get('picked') is None def read_results(path): if not path.exists(): return {} with path.open() as log: return {row['id']: row for row in map(json.loads, log)} def eval_model(label): baseline_path = Path(f'{label}.jsonl') path = Path(f'{label}-recovery.jsonl') if args.recover_cutoffs else baseline_path existing = read_results(path) pending = [sample for sample in samples if 'correct' not in existing.get(sample[0], {})] if args.recover_cutoffs: baseline = read_results(baseline_path) if not baseline: sys.exit(f'Run the initial benchmark first: {baseline_path}') pending = [sample for sample in pending if is_unanswered_cutoff(baseline.get(sample[0], {})) and not baseline[sample[0]].get('continuation_policy')] workers = args.workers or (8 if label == 'bharat-deepseek' else 12) print(label, 'queued', len(pending), 'cutoff replays' if args.recover_cutoffs else 'questions', flush=True) with path.open('a') as log, ThreadPoolExecutor(max_workers=workers) as pool: futures = [pool.submit(run, label, sample) for sample in pending] for future in as_completed(futures): row = future.result() existing[row['id']] = row log.write(json.dumps(row) + '\n') log.flush() count = len(existing) if count in (1, 198) or count % 20 == 0: status = Counter('ok' if 'correct' in r else r['error'] for r in existing.values()) print(datetime.now(timezone.utc).isoformat(), label, count, dict(status), flush=True) def summarize(): scored = {} for label in targets: initial = read_results(Path(f'{label}.jsonl')) recovery = read_results(Path(f'{label}-recovery.jsonl')) combined = {**initial, **{key: row for key, row in recovery.items() if 'correct' in row}} scored[label] = {key: row for key, row in combined.items() if 'correct' in row} print(label, json.dumps({ 'initial_correct': sum(row.get('correct', False) for row in initial.values()), 'final_correct': sum(row['correct'] for row in scored[label].values()), 'scored': len(scored[label]), 'unscored': len(samples) - len(scored[label]), 'recovered_correct': sum(row.get('correct', False) for row in recovery.values()), }, sort_keys=True)) first, second = (scored[label] for label in targets) shared = first.keys() & second.keys() outcomes = Counter((first[key]['correct'], second[key]['correct']) for key in shared) print(json.dumps({ 'shared': len(shared), 'both_correct': outcomes[True, True], 'bharatcode_only': outcomes[True, False], 'mistral_only': outcomes[False, True], 'both_incorrect': outcomes[False, False], }, sort_keys=True)) if args.summarize: summarize() else: key_name = targets[args.only][2] if not os.getenv(key_name, '').strip(): parser.error(f'Set {key_name} before running the benchmark') eval_model(args.only)