maitri01 commited on
Commit
e647bdb
·
verified ·
1 Parent(s): a14a9d8

Create task_template.py

Browse files
Files changed (1) hide show
  1. task_template.py +209 -0
task_template.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model equality challenge - task template (task 33-model-equality).
2
+
3
+ You are given
4
+ 18 API endpoints, ep-01 ... ep-18 (in this order), some of which serve the same model.
5
+ Each team can collect up to 100 answers per endpoint (at most 256 generated tokens per answer, prompts up to 1,024
6
+ tokens), with at most 4 requests at a time.
7
+
8
+ Goal: decide for every pair of endpoints whether they serve the same model (same checkpoint, quantization and LoRA
9
+ adapter; a different decoding watermark, system prompt or decoding strategy does not change the model).
10
+
11
+ This file shows you how to
12
+ 1. check your query budget on every endpoint,
13
+ 2. send prompts to the endpoints and save the answers (query()),
14
+ 3. write a random, valid submission file (make_random_submission()), as an example of the file format.
15
+ Put your method in solve().
16
+
17
+ Submission file: a plain 18 x 18 matrix of 0 and 1 in a .csv file (no header, no ID column), one line per endpoint,
18
+ rows and columns in the order ep-01 ... ep-18. Entry [i][j] = 1 means "endpoint i and endpoint j serve the same
19
+ model". The matrix must be symmetric with 1 on the diagonal. Submit it with submission.py.
20
+
21
+ Score: Matthews correlation coefficient (MCC), clipped at 0, over the 153 endpoint pairs. Answering "all different" or
22
+ "all same" scores 0. The leaderboard shows the score on a public part of the pairs; the final ranking uses the rest.
23
+
24
+ Needs: pip install requests
25
+ """
26
+ import csv
27
+ import json
28
+ import random
29
+ import sys
30
+ import threading
31
+ import time
32
+ from concurrent.futures import ThreadPoolExecutor
33
+ from pathlib import Path
34
+
35
+ import requests
36
+
37
+ # CONFIG
38
+ API_KEY = "YOUR_API_KEY_HERE" # replace with your team's API key (keep the double quotes)
39
+ SERVER_URL = "http://34.147.229.55"
40
+ TASK_ID = "33-model-equality" # do not change
41
+ PROMPTS_FILE = Path("prompts.txt") # one prompt per line (a .csv with columns id,prompt or a .jsonl also works)
42
+ ANSWERS_FILE = Path("answers.jsonl") # the answers are appended here, one JSON line each
43
+ OUTPUT_FILE = Path("submission.csv")
44
+
45
+ QUERY = False # set to True to query the endpoints
46
+ RANDOM_SUBMISSION = False # set to True to write a random example submission
47
+
48
+ ENDPOINTS = [f"ep-{i:02d}" for i in range(1, 19)]
49
+ REPEATS = 1 # answers per prompt and endpoint (answers are sampled, so they differ)
50
+ MAX_TOKENS = 256 # the server caps answers at 256 tokens
51
+ PARALLEL = 4 # the most requests the server allows at once per team
52
+
53
+ BASE_URL = f"{SERVER_URL.rstrip('/')}/{TASK_ID}/v1"
54
+
55
+
56
+ def make_session() -> requests.Session:
57
+ session = requests.Session()
58
+ session.headers["X-API-Key"] = API_KEY
59
+ return session
60
+
61
+
62
+ def get_budget(session: requests.Session) -> dict:
63
+ """Answers left on every endpoint, e.g. {"ep-01": 100, ...}."""
64
+ reply = session.get(f"{BASE_URL}/models", timeout=60)
65
+ if reply.status_code != 200:
66
+ raise RuntimeError(f"Error (HTTP {reply.status_code}): {reply.text[:300]}")
67
+ return {m["id"]: m["budget"]["limit"] - m["budget"]["used"] for m in reply.json()["data"]}
68
+
69
+
70
+ def read_prompts(path: Path) -> list:
71
+ """Returns [(id, prompt), ...] from a .txt (one prompt per line), .csv (id,prompt) or .jsonl file."""
72
+ if path.suffix == ".csv":
73
+ with path.open(newline="", encoding="utf-8") as f:
74
+ return [(row["id"], row["prompt"]) for row in csv.DictReader(f)]
75
+ if path.suffix == ".jsonl":
76
+ with path.open(encoding="utf-8") as f:
77
+ return [(str(r["id"]), r["prompt"]) for r in (json.loads(line) for line in f if line.strip())]
78
+ with path.open(encoding="utf-8") as f:
79
+ return [(str(i), line.rstrip("\n")) for i, line in enumerate(f)]
80
+
81
+
82
+ def query(prompts: list, output: Path = ANSWERS_FILE, endpoints: list = ENDPOINTS, repeats: int = REPEATS,
83
+ max_tokens: int = MAX_TOKENS) -> None:
84
+ """Sends every prompt to every chosen endpoint and appends each answer to `output` as one JSON line:
85
+ {"endpoint": "ep-07", "id": "3", "repeat": 0, "prompt": "...", "response": "..."}
86
+ Each answer costs one query from that endpoint's budget, so only as many requests as you have left are planned.
87
+ Stopping and restarting is safe: answers already in `output` are skipped."""
88
+ session = make_session()
89
+ left = get_budget(session)
90
+ unknown = [e for e in endpoints if e not in left]
91
+ if unknown:
92
+ raise ValueError(f"unknown endpoints {unknown}; valid: {', '.join(left)}")
93
+
94
+ done = set()
95
+ if output.exists():
96
+ with output.open(encoding="utf-8") as f:
97
+ done = {(r["endpoint"], r["id"], r["repeat"]) for r in (json.loads(line) for line in f if line.strip())}
98
+ # Round-robin over endpoints, so a run that stops early has covered all of them evenly.
99
+ jobs, planned, over_budget = [], {ep: 0 for ep in endpoints}, 0
100
+ for repeat in range(repeats):
101
+ for pid, prompt in prompts:
102
+ for ep in endpoints:
103
+ if (ep, pid, repeat) in done:
104
+ continue
105
+ if planned[ep] < left[ep]:
106
+ planned[ep] += 1
107
+ jobs.append((ep, pid, repeat, prompt))
108
+ else:
109
+ over_budget += 1
110
+ print(f"{len(prompts)} prompts x {len(endpoints)} endpoints x {repeats} repeats: {len(done)} answers already "
111
+ f"in {output}, {len(jobs)} to query" + (f", {over_budget} left out (over budget)" if over_budget else ""))
112
+
113
+ lock, exhausted, counter = threading.Lock(), set(), [0]
114
+ out = output.open("a", encoding="utf-8")
115
+
116
+ def one(job):
117
+ ep, pid, repeat, prompt = job
118
+ while ep not in exhausted:
119
+ try:
120
+ r = session.post(f"{BASE_URL}/chat/completions", timeout=180,
121
+ json={"model": ep, "max_tokens": max_tokens,
122
+ "messages": [{"role": "user", "content": prompt}]})
123
+ except requests.RequestException as exc:
124
+ print(f"Server unreachable ({type(exc).__name__}); retrying in 30 s.")
125
+ time.sleep(30)
126
+ continue
127
+ if r.status_code == 200:
128
+ body = r.json()
129
+ line = {"endpoint": ep, "id": pid, "repeat": repeat, "prompt": prompt,
130
+ "response": body["choices"][0]["message"]["content"]}
131
+ with lock:
132
+ out.write(json.dumps(line, ensure_ascii=False) + "\n")
133
+ out.flush()
134
+ counter[0] += 1
135
+ if counter[0] % 20 == 0 or counter[0] == len(jobs):
136
+ b = body["budget"]
137
+ print(f"{counter[0]}/{len(jobs)} answers ({ep}: {b['used']}/{b['limit']} used)")
138
+ return
139
+ detail = r.json().get("detail", r.text[:300]) if r.headers.get("content-type", "").startswith(
140
+ "application/json") else r.text[:300]
141
+ if r.status_code == 429 and "Retry-After" in r.headers: # busy: wait for a free slot
142
+ time.sleep(int(r.headers["Retry-After"]))
143
+ elif r.status_code == 429: # this endpoint's budget is used up
144
+ with lock:
145
+ if ep not in exhausted:
146
+ exhausted.add(ep)
147
+ print(detail)
148
+ elif r.status_code in (502, 503, 504):
149
+ print(f"{detail} Retrying in 15 s.")
150
+ time.sleep(15)
151
+ else:
152
+ print(f"{ep} id {pid}: HTTP {r.status_code}: {detail}", file=sys.stderr)
153
+ return
154
+
155
+ try:
156
+ with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
157
+ list(pool.map(one, jobs))
158
+ finally:
159
+ out.close()
160
+ print(f"Finished: {output}")
161
+
162
+
163
+ def write_submission(matrix: list, path: Path = OUTPUT_FILE) -> None:
164
+ """Writes an n x n 0/1 matrix as a plain CSV (no header, no ID column)."""
165
+ with path.open("w", newline="") as handle:
166
+ csv.writer(handle).writerows(matrix)
167
+
168
+
169
+ def make_random_submission(n: int = len(ENDPOINTS), groups: int = None, seed: int = None) -> list:
170
+ """A random valid submission: the endpoints are split into random groups, so "same" is consistent
171
+ (if i~j and j~k then i~k). The matrix is symmetric with a diagonal of 1."""
172
+ rng = random.Random(seed)
173
+ groups = groups or max(1, n // 2)
174
+ group_of = [rng.randrange(groups) for _ in range(n)]
175
+ return [[int(group_of[i] == group_of[j]) for j in range(n)] for i in range(n)]
176
+
177
+
178
+ def solve() -> list:
179
+ """TODO: your method. Must return an 18 x 18 symmetric 0/1 matrix (list of lists) with 1 on the diagonal,
180
+ rows and columns in the order ep-01 ... ep-18. This baseline says "all different" (it scores 0)."""
181
+ n = len(ENDPOINTS)
182
+ return [[int(i == j) for j in range(n)] for i in range(n)]
183
+
184
+
185
+ def main() -> None:
186
+ if API_KEY == "YOUR_API_KEY_HERE" or not API_KEY.strip():
187
+ print("Set API_KEY at the top of task_template.py to your team's API key.", file=sys.stderr)
188
+ raise SystemExit(1)
189
+
190
+ print("Budget left per endpoint:")
191
+ for ep, n in get_budget(make_session()).items():
192
+ print(f" {ep}: {n}")
193
+
194
+ if QUERY:
195
+ if not PROMPTS_FILE.exists():
196
+ print(f"Error: {PROMPTS_FILE} not found. Write your prompts there (one per line).", file=sys.stderr)
197
+ raise SystemExit(1)
198
+ query(read_prompts(PROMPTS_FILE))
199
+
200
+ if RANDOM_SUBMISSION:
201
+ matrix = make_random_submission()
202
+ else:
203
+ matrix = solve()
204
+ write_submission(matrix)
205
+ print(f"Saved submission to {OUTPUT_FILE}. Upload it with submission.py.")
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()