Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions app/nullius/catalogue/benchmarks/gpqa/benchmark.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
{
"key": "gpqa",
"title": "GPQA",
"category": "Science",
"domain": "Graduate-level multiple-choice questions in biology, physics and chemistry, written by domain experts.",
"scoring": "Answer accuracy",
"harness": [
"standard",
"harbor"
],
"origin": "official",
"good_to_know": [
"Leaderboards report Diamond. The authors recommend Main as the primary set. Extended holds every question, and each smaller set is part of the larger one.",
"An answer counts only with its letter in parentheses, as in 'The correct answer is (B)': a bare letter is a miss, and the first such phrase in the reply is the one read. Random guessing scores 25%.",
"Do not post its questions or answers in plain text online. The authors ask this of everyone and ship the data under a password, so the task list shows no question text.",
"Like the paper runs on OpenRouter only: OpenAI has retired the paper's GPT-4 and GPT-3.5-turbo-16k.",
"On Harbor the tasks are numbered 0 to 197, the choices are shuffled another way and the agent writes its letter to a file, so its trials do not pair by name with Nullius's."
],
"upstream_limitations": [
"The authors' script never asks the 70th question of a file and counts it wrong: Original tops out at 197 of 198 on Diamond. An agent is asked every question.",
"The script sends a temperature and a limit of 1,000 output tokens. A model that refuses either cannot run, and a reasoning model can spend the 1,000 tokens before it answers.",
"The few-shot prompts show five examples with their answers: two are Diamond and Main questions, three are Extended questions.",
"One Extended question is over 12,000 tokens long, more than GPT-4's window of 8,191.",
"The open-book baselines need the Bing Search API, which Microsoft retired, and the paper's Llama-2-70B-chat rows have no code in the repository: neither can run."
],
"limitations": [
"When a call fails six times in a row, the authors' script ends with no accuracy. Here that question is an error and the others are scored.",
"The answer-only baselines, which train a classifier on the choices, are not offered."
],
"datasets": [
{
"key": "gpqa-diamond",
"title": "GPQA Diamond",
"tasks": 198,
"official": "https://github.com/idavidrein/gpqa",
"source": "Harbor hub",
"registry": "gpqa-diamond/gpqa-diamond",
"hub": "gpqa-diamond/gpqa-diamond",
"verifier": "On Nullius, the authors' parse_sampled_answer reads the letter in the last message. On Harbor, the task's test reads the letter the agent wrote to /app/answer.txt.",
"notes": "The authors' highest-quality set: both experts agree and at most one of three non-experts is right. CC BY 4.0."
},
{
"key": "gpqa-main",
"title": "GPQA Main",
"tasks": 448,
"official": "https://github.com/idavidrein/gpqa",
"source": "GitHub",
"registry": "",
"hub": "",
"verifier": "The authors' parse_sampled_answer reads the letter in the last message; it must be the correct choice's.",
"notes": "The authors' primary set: at least one of two experts agrees and at most two of three non-experts are right. CC BY 4.0."
},
{
"key": "gpqa-extended",
"title": "GPQA Extended",
"tasks": 546,
"official": "https://github.com/idavidrein/gpqa",
"source": "GitHub",
"registry": "",
"hub": "",
"verifier": "The authors' parse_sampled_answer reads the letter in the last message; it must be the correct choice's.",
"notes": "Every published question. CC BY 4.0."
}
],
"report": {
"sources": [
"gpqa-diamond"
]
},
"task_count": 546,
"citation": "@inproceedings{rein2024gpqa,\n title={{GPQA}: A Graduate-Level Google-Proof Q\\&A Benchmark},\n author={David Rein and Betty Li Hou and Asa Cooper Stickland and Jackson Petty and Richard Yuanzhe Pang and Julien Dirani and Julian Michael and Samuel R. Bowman},\n booktitle={First Conference on Language Modeling},\n year={2024},\n url={https://openreview.net/forum?id=Ti67584b98}\n}",
"citation_source": "https://github.com/idavidrein/gpqa",
"evidence": [
{
"label": "Not asked",
"path": "not_asked"
},
{
"label": "Extracted answer",
"path": "extracted"
},
{
"label": "Expected answer",
"path": "expected"
},
{
"label": "Reply",
"path": "answer"
}
]
}
242 changes: 242 additions & 0 deletions app/nullius/catalogue/benchmarks/gpqa/driver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
"""GPQA's driver for the Nullius standard (JSON lines on stdin and stdout).

The upstream is the authors' repository ($NULLIUS_UPSTREAM): baselines/utils.py
holds its loader, which shuffles each question's four choices with a seed, and
its prompts; baselines/run_baseline.py its answerer, AnswerPredictor, and the
parser that reads a reply's letter. Every op calls them as published:

units - one per question, named by the data's own Record ID
describe - each question's domain, subdomain and writer's difficulty estimate,
never its words: the authors ask that no example be shown in plain
text online, and a listing is kept in plain text and shown on a page
setup - the upstream's zero-shot prompt, its default prompt type, built by
its create_prompts; the workspace stays empty
score - the upstream's parse_sampled_answer on the last message; the letter
it reads must be the correct choice's place after the shuffle
(AnswerPredictor.LETTER_TO_INDEX against the example's
correct_index, the comparison its main() makes)
oracle - the correct choice's letter, written as the prompt asks for it
answer - the original and model setups: the upstream's AnswerPredictor asks
the question as its main() does for one question - create_prompts
for the chosen prompt type, then sample_answer, or for
self_consistency sample_consistent_answer - its OpenAI client
started again for the unit's relay. Each question runs in a folder of
its own, where the upstream finds its prompts/ and keeps its caches,
removed afterwards: every attempt asks the model anew. The place of
the file main() goes past without asking, and counts wrong (its
'question_id == 69', read from its source), is not asked here either:
score gives that question 0, as main() counts it
preflight - a setup's first request, from the upstream's own client: the same
steps on a made-up question, the request caught before it is sent

The questions ship in the upstream's dataset.zip ($NULLIUS_DATASET), under the
password its README gives. The driver reads the README for it, opens the
dataset's CSV in memory and hands that to the upstream's load_examples: the
opened CSV is never written to disk, and no reference reaches the workspace.
One load_examples call per driver gives every op its examples, so the prompt,
the scored letter and the oracle agree on the order of the choices (the seed
option; 0 is the upstream's default).

The upstream reads its keys from a .env file (utils.py's load_dotenv()). Here
that call reads nothing: its client gets the unit's relay and the relay's
word, and no .env of the user's is loaded into this process.
"""
import contextlib
import inspect
import io
import json
import os
import re
import shutil
import sys
import tempfile
import zipfile

UPSTREAM = os.environ["NULLIUS_UPSTREAM"]
WORK = os.getcwd() # the job's driver folder
FILES = {"gpqa-diamond": "dataset/gpqa_diamond.csv", "gpqa-main": "dataset/gpqa_main.csv",
"gpqa-extended": "dataset/gpqa_extended.csv"} # each dataset's CSV in the zip
PASSWORD = re.compile(r"password:\s*`([^`]+)`") # as the upstream's README writes it
CATEGORIES = {"domain": "High-level domain", "subdomain": "Subdomain", "difficulty": "Writer's Difficulty Estimate"}
AGENT_PROMPT = "zero_shot" # run_baseline.py's default prompt_type
SEED = int(os.environ.get("NULLIUS_OPTION_SEED", "0"))
PROMPT_TYPE = os.environ.get("NULLIUS_OPTION_PROMPT_TYPE", AGENT_PROMPT)
NOWHERE = "http://relay.invalid/v1" # the upstream's client, until a unit's relay is named


def quiet():
return contextlib.redirect_stdout(sys.stderr) # stdout carries the replies


# The upstream's modules read these as they are imported: utils.py starts an OpenAI client, which
# refuses to start without a key, and open_book.py reads Bing's. None is a credential: the client
# is given an address that leads nowhere until answer() names a unit's relay, and the open-book
# baselines are not run.
os.environ.update(OPENAI_API_KEY="none", OPENAI_BASE_URL=NOWHERE, BING_SEARCH_V7_SUBSCRIPTION_KEY="none")
sys.path.insert(0, os.path.join(UPSTREAM, "baselines"))
with quiet():
import dotenv # noqa: E402
import pandas # noqa: E402 the upstream's own reader of its CSV
# utils.py calls load_dotenv() as it is imported, which reads the first .env it finds from baselines/ up to the
# root: by default the user's home is one of those folders. A run's upstream gets the relay's word and nothing
# of the user's, and the pinned python-dotenv has no switch for it: the load_dotenv utils.py imports reads nothing.
dotenv.load_dotenv = lambda *args, **kwargs: False
import utils # noqa: E402 baselines/utils.py, as published
from run_baseline import AnswerPredictor # noqa: E402 baselines/run_baseline.py, as published

LETTERS = {place: letter for letter, place in AnswerPredictor.LETTER_TO_INDEX.items()}
# main()'s loop goes past one place of the file it reads ('hack to deal with long answers'): no call, logged as not
# correct, and still in the count its accuracy divides by. Read from its source: a version without it skips nothing.
GUARD = re.search(r"if question_id == (\d+):", inspect.getsource(AnswerPredictor.main))
EXAMPLES, ROWS = {}, {}


def load():
"""Every question of the dataset by its Record ID: the upstream's Example for it."""
if EXAMPLES:
return EXAMPLES
dataset = os.environ.get("NULLIUS_DATASET_ID", "")
if dataset not in FILES:
raise ValueError(f"GPQA has no dataset {dataset}")
with open(os.path.join(UPSTREAM, "README.md"), encoding="utf-8") as f:
password = PASSWORD.search(f.read())
if not password:
raise RuntimeError("the upstream's README gives no password for dataset.zip")
with zipfile.ZipFile(os.environ["NULLIUS_DATASET"]) as z:
raw = z.read(FILES[dataset], pwd=password.group(1).encode())
examples = utils.load_examples(io.BytesIO(raw), seed=SEED) # its loader: read_csv, then each row's choices shuffled, in the file's order
rows = pandas.read_csv(io.BytesIO(raw)).to_dict("records") # the same read again, for what an Example leaves out
ids = [str(r["Record ID"]) for r in rows]
if len(ids) != len(examples) or len(set(ids)) != len(ids) or any(e.question != r["Question"] for e, r in zip(examples, rows)):
raise ValueError(f"{FILES[dataset]}: its rows do not give each example one Record ID")
ROWS.update(zip(ids, rows))
EXAMPLES.update(zip(ids, examples))
return EXAMPLES


def units(dataset, setup=None):
return {"units": list(load())}


def describe(dataset=None, **_):
load()
out = {}
for unit, row in ROWS.items():
said = {name: row.get(column) for name, column in CATEGORIES.items()}
said = {name: value.strip() for name, value in said.items() if isinstance(value, str) and value.strip()}
if "difficulty" in said: # without its gloss in parentheses: 'Hard graduate level (could be ...)'
said["difficulty"] = said["difficulty"].split(" (")[0]
out[unit] = {"title": "", "text": "", "categories": said}
return {"units": out}


def setup(unit, dir, **_):
"""The upstream's zero-shot prompt: its create_prompts, on that question alone."""
return {"prompt": utils.create_prompts([load()[unit]], AGENT_PROMPT, None, None)[0][0]}


@contextlib.contextmanager
def upstream_folder():
"""A folder of its own for one question's run of the upstream, which reads prompts/ from where it
runs and writes its response caches there: a cache left by another question would answer for this one."""
folder = tempfile.mkdtemp(prefix="gpqa-", dir=WORK)
try:
os.symlink(os.path.join(UPSTREAM, "prompts"), os.path.join(folder, "prompts"))
os.chdir(folder)
yield
finally:
os.chdir(WORK)
shutil.rmtree(folder, ignore_errors=True)


def skipped(unit):
"""Whether the upstream's main() goes past the question without asking it: its place in the file."""
return bool(GUARD) and list(load()).index(unit) == int(GUARD.group(1))


def connect(base_url, key):
"""The upstream's own client, started as utils.py starts it, from the variables it reads."""
os.environ.update(OPENAI_BASE_URL=base_url, OPENAI_API_KEY=key)
utils.client = utils.OpenAI()


def ask(example, model):
"""What the upstream's main() does with one question: its prompt for the prompt type, then its answer to it."""
with upstream_folder(), quiet():
predictor = AnswerPredictor(data_filename=FILES[os.environ["NULLIUS_DATASET_ID"]], model_name=model,
prompt_type=PROMPT_TYPE, seed=SEED)
prompt = utils.create_prompts([example], PROMPT_TYPE, None, model)[0][0]
if PROMPT_TYPE == "self_consistency": # main()'s own branch: its samples' most common letter, and no reply
letter = predictor.sample_consistent_answer(prompt)
return f"({letter}), the most common letter of the samples" if letter else "No sample gave a letter"
return predictor.sample_answer(prompt)[1]


def answer(unit, dir, setup, model, base_url, key, **_):
"""The upstream's answerer on one question. model is a name its code accepts (gpt-4 for the
model setup); the relay sends the run's model in its place."""
if setup not in ("original", "model"):
raise ValueError(f"GPQA has no {setup} setup")
example = load()[unit]
if skipped(unit): # main() asks nothing
return {"answer": "", "model": model}
connect(base_url, key) # now at this unit's relay
return {"answer": ask(example, model), "model": model}


def preflight(participant, model, roles, setup=None, **_):
"""A setup's first request as the upstream's own client would send it: main()'s steps on a made-up question,
the request caught before it leaves. An agent's requests are its own: not captured."""
import httpx
from unittest.mock import patch

class Captured(BaseException): # not an Exception: the upstream's retries catch those
def __init__(self, request):
self.request = {"role": "agent", "path": request.url.raw_path.decode(), "body": json.loads(request.content)}

def send(client, request, **kw):
raise Captured(request)

if participant != "setup" or "agent" not in roles:
return {"requests": []}
connect(NOWHERE, "none")
try:
with patch.object(httpx.Client, "send", send):
ask(utils.Example("Compatibility check: which choice reads OK?", "OK", "No", "Never", "None", 0), model)
except Captured as captured:
return {"requests": [captured.request]}
raise RuntimeError("the upstream's answerer made no request")


def score(unit, dir, transcript, answer, setup=None, **_):
example = load()[unit]
if setup and skipped(unit): # a setup's: not asked, and counted wrong as main() counts it
said = f"run_baseline.py main() never asks question {int(GUARD.group(1)) + 1} of a file ('{GUARD.group(0)}') and counts it wrong"
return {"reward": 0.0, "passed": False, "detail": {"not_asked": said, "expected": LETTERS[example.correct_index]}}
letter = AnswerPredictor.parse_sampled_answer(answer or "")
ok = letter is not None and AnswerPredictor.LETTER_TO_INDEX[letter] == example.correct_index
return {"reward": 1.0 if ok else 0.0, "passed": ok,
"detail": {"extracted": letter, "expected": LETTERS[example.correct_index], "answer": (answer or "")[-4000:]}}


def oracle(unit, dir, **_):
return {"answer": f"The correct answer is ({LETTERS[load()[unit].correct_index]})"}


HANDLERS = {"units": units, "describe": describe, "setup": setup, "answer": answer, "score": score, "oracle": oracle,
"preflight": preflight}


def main():
for line in sys.stdin:
try:
req = json.loads(line)
with quiet():
out = HANDLERS[req.pop("op")](**req)
except Exception as e:
out = {"error": f"{type(e).__name__}: {e}"}
print(json.dumps(out), flush=True)


if __name__ == "__main__":
main()
Loading