Repository navigation
Expand file tree
/
Copy pathcreate_eval_harness_splits.py
More file actions
369 lines (301 loc) · 15.4 KB
/
Copy pathcreate_eval_harness_splits.py
File metadata and controls
369 lines (301 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import json
import os
import string
from datasets import Dataset
from tqdm import tqdm
import random
from itertools import product
from concurrent.futures import ProcessPoolExecutor
from functools import lru_cache
import numpy as np
import inflect
from mastermind.game import COLORS
p = inflect.engine()
# ---------------------------------------------------------------------------
# Knuth pre-play (vectorized)
# ---------------------------------------------------------------------------
#
# The classic minimax Knuth solver in src/mastermind/solvers.py is pure Python
# and O(|unused| * |remaining|) per step. That is fine for the 4x6 game
# (1296 states) but infeasible for 5x7 (16807) and 6x8 (262144) states.
#
# Below is a numpy-vectorized Knuth that:
# * encodes colors as integers and scores feedback with broadcasting,
# * restricts the minimax candidate pool to a random subsample of the
# remaining consistent codes (a well-known efficient Knuth variant that
# stays within ~1 extra guess of true minimax while bounding cost),
# * tracks the remaining-state count itself so progress_history is free.
#
# The secret code is sampled without color repetition, matching
# mastermind.game.Mastermind, so the produced games are consistent with the
# existing flair/mastermind_{24,35,46}_mcq_* datasets.
_CANDIDATE_POOL_CAP = 400
@lru_cache(maxsize=2)
def _build_all_codes(code_length: int, num_colors: int):
"""All codes (with repetition) as an (M, L) int8 array, plus per-color counts.
Cached per worker process: every game in a setting reuses the same arrays.
"""
all_codes = np.array(
list(product(range(num_colors), repeat=code_length)), dtype=np.int8
)
# counts[i, c] = number of times color c appears in code i
counts = np.zeros((all_codes.shape[0], num_colors), dtype=np.int8)
for c in range(num_colors):
counts[:, c] = (all_codes == c).sum(axis=1)
return all_codes, counts
def _feedback_vs(code_idx: int, idx, all_codes, counts, code_length: int):
"""Feedback ids of code `code_idx` evaluated against codes `idx` (an index array).
Feedback is encoded as exact * (L + 1) + white, matching
Mastermind.evaluate_guess semantics (white = total color overlap - exact).
"""
guess = all_codes[code_idx]
sub = all_codes[idx]
exact = (sub == guess).sum(axis=1)
total = np.minimum(counts[idx], counts[code_idx]).sum(axis=1)
white = total - exact
return exact * (code_length + 1) + white
def _knuth_play_one(secret_idx: int, all_codes, counts, code_length: int, rng) -> dict:
"""Play a single game with vectorized Knuth. Returns guess/progress history
in integer-code form (caller maps back to color names)."""
n_total = all_codes.shape[0]
remaining = np.arange(n_total)
guess_history = [] # list of (code_idx, (exact, white))
progress_after = [n_total] # remaining count after each played guess
while True:
if not guess_history:
# First guess is fixed (canonical Knuth): a balanced two-color
# spread. This skips the prohibitively expensive minimax over the
# full, un-reduced state space.
half = code_length // 2
first = np.array(
[0] * (code_length - half) + [1 % all_codes.shape[1]] * half,
dtype=np.int8,
)
guess_idx = int(np.where((all_codes == first).all(axis=1))[0][0])
elif remaining.shape[0] == 1:
guess_idx = int(remaining[0])
else:
# Minimax over a subsampled candidate pool of remaining codes.
if remaining.shape[0] > _CANDIDATE_POOL_CAP:
pool = rng.choice(remaining, size=_CANDIDATE_POOL_CAP, replace=False)
else:
pool = remaining
best_idx, best_worst = None, None
max_fb = code_length * (code_length + 1) + code_length + 1
for cand in pool:
fb = _feedback_vs(int(cand), remaining, all_codes, counts, code_length)
worst = np.bincount(fb, minlength=max_fb).max()
if best_worst is None or worst < best_worst:
best_worst, best_idx = worst, int(cand)
guess_idx = best_idx
# --- score against the secret ---
fb_secret = int(
_feedback_vs(guess_idx, np.array([secret_idx]), all_codes, counts, code_length)[0]
)
exact = fb_secret // (code_length + 1)
white = fb_secret % (code_length + 1)
guess_history.append((guess_idx, (int(exact), int(white))))
if exact == code_length:
break
# --- filter remaining consistent codes ---
fb_all = _feedback_vs(guess_idx, remaining, all_codes, counts, code_length)
remaining = remaining[fb_all == fb_secret]
progress_after.append(int(remaining.shape[0]))
# progress_history matches Evaluator.progress: [N, |R after g1|, ... |R after g_{n-1}|]
progress_history = progress_after[: len(guess_history)]
return {"guess_history": guess_history, "progress_history": progress_history}
def _play_game_worker(args):
code_length, num_colors, seed = args
rng = random.Random(seed)
nprng = np.random.default_rng(seed)
possible_colors = rng.sample(COLORS, k=num_colors)
color_to_int = {c: i for i, c in enumerate(possible_colors)}
# secret: no repeated colors, matching mastermind.game.Mastermind
secret_colors = rng.sample(possible_colors, k=code_length)
all_codes, counts = _build_all_codes(code_length, num_colors)
secret_idx = 0
secret_int = np.array([color_to_int[c] for c in secret_colors], dtype=np.int8)
secret_idx = int(np.where((all_codes == secret_int).all(axis=1))[0][0])
played = _knuth_play_one(secret_idx, all_codes, counts, code_length, nprng)
def idx_to_colors(i):
return [possible_colors[v] for v in all_codes[i]]
guess_history = [
[idx_to_colors(gi), [e, w]] for gi, (e, w) in played["guess_history"]
]
return {
"game": {
"code_length": code_length,
"possible_colors": possible_colors,
"secret_code": secret_colors,
},
"guess_history": guess_history,
"progress_history": played["progress_history"],
}
def preplay_games(code_length: int, num_colors: int, num_games: int, seed: int = 42, workers: int = None) -> list:
"""Pre-play `num_games` Knuth games for the given setting (parallel across games)."""
workers = workers or max(1, (os.cpu_count() or 2) - 1)
tasks = [(code_length, num_colors, seed + i) for i in range(num_games)]
data = []
with ProcessPoolExecutor(max_workers=workers) as ex:
for result in tqdm(
ex.map(_play_game_worker, tasks, chunksize=4),
total=num_games,
desc=f"Pre-playing Knuth {code_length}x{num_colors}",
):
data.append(result)
return data
def format_guesses_detail(guesses):
formatted_guesses = []
for guess, score in guesses:
if score == [0, 0]:
formatted_guesses.append(
f"Guess: {guess}. Hint: none of the guessed colors are present in the secret code."
)
elif score[0] > 0 and score[1] == 0:
formatted_guesses.append(
f"Guess: {guess}. Hint: {p.number_to_words(score[0])} color{'s are' if score[0] > 1 else ' is'} in the correct position{'s' if score[0] > 1 else ''}."
)
elif score[0] == 0 and score[1] > 0:
formatted_guesses.append(
f"Guess: {guess}. Hint: {p.number_to_words(score[1])} color{'s are' if score[1] > 1 else ' is'} in the secret code but in the wrong position{'s' if score[1] > 1 else ''}."
)
elif score[0] > 0 and score[1] > 0:
formatted_guesses.append(
f"Guess: {guess}. Hint: {p.number_to_words(score[0])} color{'s are' if score[0] > 1 else ' is'} in the correct position{'s' if score[0] > 1 else ''} "
f"and {p.number_to_words(score[1])} color{'s are' if score[1] > 1 else ' is'} in the secret code but in the wrong position{'s' if score[0] > 1 else ''}."
)
else:
raise ValueError(f"Invalid feedback scores: {score}")
return "\n".join(formatted_guesses)
def instruction_template(code_length: int, possible_colors: list, formatted_guesses: str):
instruction = (
f"Your goal is to find the secret {p.number_to_words(code_length)}-color code. The following colors are possible: {', '.join(possible_colors)}.\n"
f"Some guesses have already been made. I will provide feedback for each guess made with which it is possible to unambigiously determine the secret code.\n\n"
f"Previous Guesses:\n"
f"{formatted_guesses}"
)
return instruction
def generate_random_answers(code_length, possible_colors, already_guessed):
possible_codes = [tuple(code) for code in product(possible_colors, repeat=code_length)]
possible_codes = [code for code in possible_codes if code not in already_guessed]
return random.sample(possible_codes, k=3)
def generate_close_answers(secret_code, possible_colors, guessed_options, num_tuples=3):
"""
Generate close tuples based on a secret color code.
A close tuple replaces one random entry in the secret code with a random color.
Avoids previously guessed options.
Args:
secret_code (list): The secret color code (list of colors).
possible_colors (list): List of all possible colors.
guessed_options (list): List of already guessed tuples to avoid.
num_tuples (int): Number of tuples to generate.
Returns:
list of tuples: List containing the generated close tuples.
"""
close_tuples = set() # Use a set to avoid duplicates
while len(close_tuples) < num_tuples:
# Copy the secret code to avoid modifying the original
modified_code = secret_code.copy()
# Randomly choose a position to replace
position_to_replace = random.randint(0, len(secret_code) - 1)
# Get a random color that is not the current color at that position
original_color = modified_code[position_to_replace]
new_color = random.choice([color for color in possible_colors if color != original_color])
# Replace the color in the copied list
modified_code[position_to_replace] = new_color
# Convert the modified code to a tuple
modified_tuple = tuple(modified_code)
# Add to the result only if it is not already guessed and not in the result set
if modified_tuple not in guessed_options and modified_tuple != tuple(secret_code):
close_tuples.add(modified_tuple)
return list(close_tuples)
def prepare_shuffled_output(secret, options):
# Combine secret with options and shuffle
options = [", ".join(option) for option in options]
secret = ", ".join(secret)
all_options = options + [secret]
random.shuffle(all_options)
# Assign labels (A, B, C, ...) to the options
labels = list(string.ascii_uppercase[: len(all_options)])
label_mapping = {option: label for option, label in zip(all_options, labels)}
# Find the correct label for the secret
correct_label = label_mapping[secret]
# Prepare the final output
output = {"text": all_options, "label": labels}
return output, correct_label
def build_eval_harness(data: list):
dataset_easy = {"id": [], "instruction": [], "options": [], "answerKey": []}
dataset_difficult = {"id": [], "instruction": [], "options": [], "answerKey": []}
for game in tqdm(data, desc="Filtering data."):
progress_history = game["progress_history"]
if not progress_history[-1] == 1:
continue
guesses = game["guess_history"]
# Drop games solved on the very first guess: there are no prior hints
# to reason from, so the MCQ would be unanswerable / trivial.
if len(guesses) <= 1:
continue
game_data = game["game"]
hints = game["guess_history"][:-1]
secret_code = game_data["secret_code"]
possible_colors = game_data["possible_colors"]
code_length = game_data["code_length"]
random_answer_options = generate_random_answers(
code_length, possible_colors, [tuple(guess) for guess, _ in guesses]
)
close_answer_options = generate_close_answers(
secret_code, possible_colors, [tuple(guess) for guess, _ in guesses]
)
random_answer_options, correct_random_option = prepare_shuffled_output(secret_code, random_answer_options)
difficult_answer_options, correct_difficult_option = prepare_shuffled_output(secret_code, close_answer_options)
formatted_hints = format_guesses_detail(hints)
instruction = instruction_template(
code_length=code_length,
possible_colors=possible_colors,
formatted_guesses=formatted_hints,
)
dataset_easy["id"].append(len(dataset_easy["id"]))
dataset_easy["instruction"].append(instruction)
dataset_easy["options"].append(random_answer_options)
dataset_easy["answerKey"].append(correct_random_option)
dataset_difficult["id"].append(len(dataset_difficult["id"]))
dataset_difficult["instruction"].append(instruction)
dataset_difficult["options"].append(difficult_answer_options)
dataset_difficult["answerKey"].append(correct_difficult_option)
print(f"Dataset (easy) contains {len(dataset_easy['id'])} instructions.")
print(f"Dataset (difficult) contains {len(dataset_difficult['id'])} instructions.")
return dataset_easy, dataset_difficult
def make_eval_harness(path: str):
"""Backward-compatible path: read pre-generated raw.json and write harness files."""
with open(f"{path}/raw.json") as f:
data = json.load(f)
dataset_easy, dataset_difficult = build_eval_harness(data)
with open(f"{path}/harness_easy.json", "w") as f:
json.dump(dataset_easy, f, indent=4)
with open(f"{path}/harness_difficult.json", "w") as f:
json.dump(dataset_difficult, f, indent=4)
return dataset_easy, dataset_difficult
def _push_split(dataset_dict: dict, repo: str):
dataset = Dataset.from_dict(dataset_dict)
train_test = dataset.train_test_split(test_size=0.05, seed=42)
train_val = train_test["train"].train_test_split(test_size=0.1, seed=42)
train_val["validation"] = train_val.pop("test")
train_val["test"] = train_test["test"]
train_val.push_to_hub(repo)
if __name__ == "__main__":
# Existing 4x6-and-smaller settings: re-use the pre-generated raw.json games.
for setting in ["24", "35", "46"]:
path = f"datasets/dataset_{setting}_50k"
dataset_easy, dataset_difficult = make_eval_harness(path)
_push_split(dataset_easy, f"flair/mastermind_{setting}_mcq_random")
_push_split(dataset_difficult, f"flair/mastermind_{setting}_mcq_close")
# Larger settings: state space too big for the pure-Python Knuth solver,
# so pre-play them here with the vectorized Knuth.
# setting "57" -> code_length 5, num_colors 7 (7^5 = 16807 states)
# setting "68" -> code_length 6, num_colors 8 (8^6 = 262144 states)
NUM_GAMES = 2000
for setting, code_length, num_colors in [("57", 5, 7), ("68", 6, 8)]:
data = preplay_games(code_length, num_colors, NUM_GAMES, seed=42)
dataset_easy, dataset_difficult = build_eval_harness(data)
_push_split(dataset_easy, f"flair/mastermind_{setting}_mcq_random")
_push_split(dataset_difficult, f"flair/mastermind_{setting}_mcq_close")