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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Query the reference endpoints ref-01 ... ref-09 (task 33-model-equality).
|
| 2 |
+
|
| 3 |
+
The reference endpoints serve a separate small model, with the same kinds of disguises and traps as the scored
|
| 4 |
+
endpoints. Their correct answers are in practice_answers.csv. They have no query limit and are never scored, so use
|
| 5 |
+
them to build and test your method before you spend your 100 answers per scored endpoint (task_template.py).
|
| 6 |
+
|
| 7 |
+
How to use:
|
| 8 |
+
1. Set API_KEY below and write your prompts in reference_prompts.txt (one per line; a .csv with columns id,prompt
|
| 9 |
+
or a .jsonl also works).
|
| 10 |
+
2. Run: python query_reference.py
|
| 11 |
+
The answers are appended to reference_answers.jsonl, one JSON line each:
|
| 12 |
+
{"endpoint": "ref-03", "id": "3", "repeat": 0, "prompt": "...", "response": "..."}
|
| 13 |
+
Stopping and restarting is safe: answers already in the file are skipped.
|
| 14 |
+
3. Write your answer for the reference endpoints in the submission format (endpoint,family,model, one line per
|
| 15 |
+
reference endpoint) and score it with: python score_practice.py my_reference_answer.csv
|
| 16 |
+
Do not put ref- lines in a real submission: the server only accepts ep-01 ... ep-33.
|
| 17 |
+
|
| 18 |
+
Needs: pip install requests
|
| 19 |
+
"""
|
| 20 |
+
import csv
|
| 21 |
+
import json
|
| 22 |
+
import sys
|
| 23 |
+
import threading
|
| 24 |
+
import time
|
| 25 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import requests
|
| 29 |
+
|
| 30 |
+
# CONFIG
|
| 31 |
+
API_KEY = "YOUR_API_KEY_HERE" # replace with your team's API key (keep the double quotes)
|
| 32 |
+
SERVER_URL = "http://34.147.229.55"
|
| 33 |
+
TASK_ID = "33-model-equality" # do not change
|
| 34 |
+
PROMPTS_FILE = Path("reference_prompts.txt") # one prompt per line (a .csv with columns id,prompt or a .jsonl also works)
|
| 35 |
+
ANSWERS_FILE = Path("reference_answers.jsonl") # the answers are appended here, one JSON line each
|
| 36 |
+
|
| 37 |
+
NUM_ENDPOINTS = 9 # the server lists the real ones: python query_reference.py prints them
|
| 38 |
+
ENDPOINTS = [f"ref-{i:02d}" for i in range(1, NUM_ENDPOINTS + 1)]
|
| 39 |
+
REPEATS = 1 # answers per prompt and endpoint (answers are sampled, so they differ)
|
| 40 |
+
MAX_TOKENS = 256 # the server caps answers at 256 tokens
|
| 41 |
+
PARALLEL = 4 # the most requests the server allows at once per team
|
| 42 |
+
|
| 43 |
+
BASE_URL = f"{SERVER_URL.rstrip('/')}/{TASK_ID}/v1"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def make_session() -> requests.Session:
|
| 47 |
+
session = requests.Session()
|
| 48 |
+
session.headers["X-API-Key"] = API_KEY
|
| 49 |
+
return session
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_budget(session: requests.Session) -> dict:
|
| 53 |
+
"""Answers left on every endpoint, e.g. {"ep-01": 100, ...}."""
|
| 54 |
+
reply = session.get(f"{BASE_URL}/models", timeout=60)
|
| 55 |
+
if reply.status_code != 200:
|
| 56 |
+
raise RuntimeError(f"Error (HTTP {reply.status_code}): {reply.text[:300]}")
|
| 57 |
+
return {m["id"]: m["budget"]["limit"] - m["budget"]["used"] for m in reply.json()["data"]}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def read_prompts(path: Path) -> list:
|
| 61 |
+
"""Returns [(id, prompt), ...] from a .txt (one prompt per line), .csv (id,prompt) or .jsonl file."""
|
| 62 |
+
if path.suffix == ".csv":
|
| 63 |
+
with path.open(newline="", encoding="utf-8") as f:
|
| 64 |
+
return [(row["id"], row["prompt"]) for row in csv.DictReader(f)]
|
| 65 |
+
if path.suffix == ".jsonl":
|
| 66 |
+
with path.open(encoding="utf-8") as f:
|
| 67 |
+
return [(str(r["id"]), r["prompt"]) for r in (json.loads(line) for line in f if line.strip())]
|
| 68 |
+
with path.open(encoding="utf-8") as f:
|
| 69 |
+
return [(str(i), line.rstrip("\n")) for i, line in enumerate(f)]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def query(prompts: list, output: Path = ANSWERS_FILE, endpoints: list = ENDPOINTS, repeats: int = REPEATS,
|
| 73 |
+
max_tokens: int = MAX_TOKENS) -> None:
|
| 74 |
+
"""Sends every prompt to every chosen endpoint and appends each answer to `output` as one JSON line:
|
| 75 |
+
{"endpoint": "ep-07", "id": "3", "repeat": 0, "prompt": "...", "response": "..."}
|
| 76 |
+
Each answer costs one query from that endpoint's budget, so only as many requests as you have left are planned.
|
| 77 |
+
Stopping and restarting is safe: answers already in `output` are skipped."""
|
| 78 |
+
session = make_session()
|
| 79 |
+
left = get_budget(session)
|
| 80 |
+
unknown = [e for e in endpoints if e not in left]
|
| 81 |
+
if unknown:
|
| 82 |
+
raise ValueError(f"unknown endpoints {unknown}; valid: {', '.join(left)}")
|
| 83 |
+
|
| 84 |
+
done = set()
|
| 85 |
+
if output.exists():
|
| 86 |
+
with output.open(encoding="utf-8") as f:
|
| 87 |
+
done = {(r["endpoint"], r["id"], r["repeat"]) for r in (json.loads(line) for line in f if line.strip())}
|
| 88 |
+
# Round-robin over endpoints, so a run that stops early has covered all of them evenly.
|
| 89 |
+
jobs, planned, over_budget = [], {ep: 0 for ep in endpoints}, 0
|
| 90 |
+
for repeat in range(repeats):
|
| 91 |
+
for pid, prompt in prompts:
|
| 92 |
+
for ep in endpoints:
|
| 93 |
+
if (ep, pid, repeat) in done:
|
| 94 |
+
continue
|
| 95 |
+
if planned[ep] < left[ep]:
|
| 96 |
+
planned[ep] += 1
|
| 97 |
+
jobs.append((ep, pid, repeat, prompt))
|
| 98 |
+
else:
|
| 99 |
+
over_budget += 1
|
| 100 |
+
print(f"{len(prompts)} prompts x {len(endpoints)} endpoints x {repeats} repeats: {len(done)} answers already "
|
| 101 |
+
f"in {output}, {len(jobs)} to query" + (f", {over_budget} left out (over budget)" if over_budget else ""))
|
| 102 |
+
|
| 103 |
+
lock, exhausted, counter = threading.Lock(), set(), [0]
|
| 104 |
+
out = output.open("a", encoding="utf-8")
|
| 105 |
+
|
| 106 |
+
def one(job):
|
| 107 |
+
ep, pid, repeat, prompt = job
|
| 108 |
+
while ep not in exhausted:
|
| 109 |
+
try:
|
| 110 |
+
r = session.post(f"{BASE_URL}/chat/completions", timeout=180,
|
| 111 |
+
json={"model": ep, "max_tokens": max_tokens,
|
| 112 |
+
"messages": [{"role": "user", "content": prompt}]})
|
| 113 |
+
except requests.RequestException as exc:
|
| 114 |
+
print(f"Server unreachable ({type(exc).__name__}); retrying in 30 s.")
|
| 115 |
+
time.sleep(30)
|
| 116 |
+
continue
|
| 117 |
+
if r.status_code == 200:
|
| 118 |
+
body = r.json()
|
| 119 |
+
line = {"endpoint": ep, "id": pid, "repeat": repeat, "prompt": prompt,
|
| 120 |
+
"response": body["choices"][0]["message"]["content"]}
|
| 121 |
+
with lock:
|
| 122 |
+
out.write(json.dumps(line, ensure_ascii=False) + "\n")
|
| 123 |
+
out.flush()
|
| 124 |
+
counter[0] += 1
|
| 125 |
+
if counter[0] % 20 == 0 or counter[0] == len(jobs):
|
| 126 |
+
b = body["budget"]
|
| 127 |
+
print(f"{counter[0]}/{len(jobs)} answers ({ep}: {b['used']}/{b['limit']} used)")
|
| 128 |
+
return
|
| 129 |
+
detail = r.json().get("detail", r.text[:300]) if r.headers.get("content-type", "").startswith(
|
| 130 |
+
"application/json") else r.text[:300]
|
| 131 |
+
if r.status_code == 429 and "Retry-After" in r.headers: # busy: wait for a free slot
|
| 132 |
+
time.sleep(int(r.headers["Retry-After"]))
|
| 133 |
+
elif r.status_code == 429: # this endpoint's budget is used up
|
| 134 |
+
with lock:
|
| 135 |
+
if ep not in exhausted:
|
| 136 |
+
exhausted.add(ep)
|
| 137 |
+
print(detail)
|
| 138 |
+
elif r.status_code in (502, 503, 504):
|
| 139 |
+
print(f"{detail} Retrying in 15 s.")
|
| 140 |
+
time.sleep(15)
|
| 141 |
+
else:
|
| 142 |
+
print(f"{ep} id {pid}: HTTP {r.status_code}: {detail}", file=sys.stderr)
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
| 147 |
+
list(pool.map(one, jobs))
|
| 148 |
+
finally:
|
| 149 |
+
out.close()
|
| 150 |
+
print(f"Finished: {output}")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def main() -> None:
|
| 154 |
+
if API_KEY == "YOUR_API_KEY_HERE" or not API_KEY.strip():
|
| 155 |
+
print("Set API_KEY at the top of query_reference.py to your team's API key.", file=sys.stderr)
|
| 156 |
+
raise SystemExit(1)
|
| 157 |
+
if not PROMPTS_FILE.exists():
|
| 158 |
+
print(f"Error: {PROMPTS_FILE} not found. Write your prompts there (one per line).", file=sys.stderr)
|
| 159 |
+
raise SystemExit(1)
|
| 160 |
+
|
| 161 |
+
budget = get_budget(make_session())
|
| 162 |
+
endpoints = [ep for ep in budget if ep.startswith("ref-")] # the reference endpoints the server lists
|
| 163 |
+
print("Reference endpoints:", ", ".join(endpoints))
|
| 164 |
+
query(read_prompts(PROMPTS_FILE), endpoints=endpoints)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__ == "__main__":
|
| 168 |
+
main()
|