Datasets:
File size: 9,481 Bytes
a4822b5 | 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 | """Synthetic families with programmatic verifiers: IFEval-style instruction following and planning / constraint puzzles. Fixed seed, deterministic."""
from __future__ import annotations
import itertools
import json
import random
import sys
from pathlib import Path
from .families import row, rd
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
SEED = 20261010
def hash_seed(*p) -> int:
import hashlib
return int(hashlib.sha1('|'.join(map(str, p)).encode()).hexdigest()[:8], 16)
# ---- instruction following ---------------------------------------------------------------------------------------------------------------
def instruction_following(n_synth: int = 1100):
from vendor.ifeval import instructions_registry as IR
out = []
d = rd("google/IFEval", "ifeval_input_data.jsonl")
for _, r in d.iterrows():
kw = [{k: (list(v) if hasattr(v, "tolist") else v) for k, v in dict(x).items() if v is not None} for x in r["kwargs"]]
out.append(row("instruction_following", "ifeval", r["key"], "train", r["prompt"], "ifeval_strict",
dict(instruction_id_list=list(r["instruction_id_list"]), kwargs=kw), subject="ifeval_original"))
nr = rd("HuggingFaceH4/no_robots", "data/train-00000-of-00001.parquet")
nr = nr[nr.category.isin(["Generation", "Brainstorm", "Rewrite", "Open QA", "Chat"]) & (nr.prompt.str.len() < 500)].reset_index(drop=True)
rng = random.Random(SEED)
ids = sorted(IR.INSTRUCTION_DICT)
made, tries = 0, 0
order = list(range(len(nr)))
rng.shuffle(order)
while made < n_synth and tries < 20 * n_synth and order:
tries += 1
r = nr.iloc[order[made % len(order)] if tries < len(order) else rng.choice(order)]
k = rng.choices([1, 2, 3], [0.4, 0.4, 0.2])[0]
chosen: list[str] = []
for cand in rng.sample(ids, len(ids)):
if all(cand not in IR.INSTRUCTION_CONFLICTS.get(c, set()) and c not in IR.INSTRUCTION_CONFLICTS.get(cand, set()) for c in chosen) and cand != "combination:repeat_prompt":
chosen.append(cand)
if len(chosen) == k:
break
descs, kws, ok = [], [], True
for cid in chosen:
try:
random.seed(hash_seed(r['prompt_id'], cid)) # build_description draws from the global RNG
inst = IR.INSTRUCTION_DICT[cid](cid)
desc = inst.build_description()
a = inst.get_instruction_args() or {}
a = {x: y for x, y in a.items() if y is not None}
descs.append(desc)
kws.append(a)
except Exception:
ok = False
break
if not ok:
continue
prompt = r["prompt"].strip() + "\n\n" + " ".join(descs)
out.append(row("instruction_following", "ifeval_synth_norobots", f"{r['prompt_id']}/{'+'.join(chosen)}", "train", prompt, "ifeval_strict",
dict(instruction_id_list=chosen, kwargs=kws), subject="ifeval_synthetic"))
made += 1
return out
# ---- planning & constraint puzzles --------------------------------------------------------------------------------------------------------
BW_INSTR = ("You control a robot arm that moves blocks on a table. A block can be moved only if no other block is on top of it. A move places one block either on the table or on top of "
"another block that is clear. Find a sequence of moves that transforms the initial arrangement into the goal arrangement. Think step by step, then give the final answer on the last line "
'as a JSON list of strings, each of the form "move X to Y" where Y is another block or the word table, e.g. Final answer: ["move A to table", "move B to A"].\n\n')
def _bw_state_str(stacks):
return "\n".join(f"Stack {i + 1} (bottom to top): " + ", ".join(s) for i, s in enumerate(stacks)) if stacks else "(empty)"
def blocksworld(n: int = 600):
rng = random.Random(SEED + 1)
out = []
for i in range(n):
nb = rng.choice([3, 4, 4, 5, 5, 6, 7])
names = list("ABCDEFGHIJ"[:nb])
def rand_stacks():
b = names[:]
rng.shuffle(b)
st, cur = [], []
for x in b:
cur.append(x)
if rng.random() < 0.4:
st.append(cur); cur = []
if cur:
st.append(cur)
return st
init, goal = rand_stacks(), rand_stacks()
if sorted(map(tuple, init)) == sorted(map(tuple, goal)):
continue
p = (BW_INSTR + f"Blocks: {', '.join(names)}.\n\nInitial arrangement:\n{_bw_state_str(init)}\n\nGoal arrangement:\n{_bw_state_str(goal)}\n\n"
"All blocks not shown in a stack are not present. Each listed stack is a pile on the table; the first listed block is on the table.")
out.append(row("planning", "blocksworld_synth", i, "synthetic", p, "plan_blocksworld", dict(init=init, goal=goal, blocks=names), subject=f"n{nb}"))
return out
HANOI_INSTR = ("Solve this Tower of Hanoi puzzle. Disks are numbered by size (1 is the smallest). Only the top disk of a peg can be moved, and a disk may never be placed on a smaller disk. "
"Move all disks so the final arrangement matches the goal. Think step by step, then give the final answer on the last line as a JSON list of moves, each [disk, from_peg, to_peg], "
'e.g. Final answer: [[1, "A", "C"], [2, "A", "B"]].\n\n')
def hanoi(n: int = 450):
rng = random.Random(SEED + 2)
out = []
for i in range(n):
nd = rng.choice([3, 3, 4, 4, 5, 5, 6])
pegs = ["A", "B", "C"]
def rand_cfg():
cfg = {p: [] for p in pegs}
for d in range(nd, 0, -1): # largest first so every peg is a legal stack (bottom to top = decreasing size)
cfg[rng.choice(pegs)].append(d)
return cfg
init, goal = rand_cfg(), rand_cfg()
if init == goal:
continue
fmt = lambda s: "\n".join(f"Peg {p} (bottom to top): " + (", ".join(map(str, s[p])) if s[p] else "empty") for p in pegs)
out.append(row("planning", "hanoi_synth", i, "synthetic", HANOI_INSTR + f"Initial arrangement:\n{fmt(init)}\n\nGoal arrangement:\n{fmt(goal)}", "plan_hanoi",
dict(init=init, goal=goal, n_disks=nd, optimal=None), subject=f"n{nd}"))
return out
SUDOKU_INSTR = ("Solve the Sudoku puzzle below. Each row, each column, and each box must contain every digit from 1 to {n} exactly once. Empty cells are shown as '.'. Think step by step, "
"then give the completed grid on the last lines after the text 'Final answer:' with one row per line, digits only, no spaces.\n\n")
def _solve(grid, n, br, bc, limit=2):
"""Count solutions up to `limit` (MRV backtracking); returns (count, first_solution)."""
sols = []
def cands(r, c):
used = set(grid[r]) | {grid[x][c] for x in range(n)}
r0, c0 = r // br * br, c // bc * bc
used |= {grid[x][y] for x in range(r0, r0 + br) for y in range(c0, c0 + bc)}
return [v for v in range(1, n + 1) if v not in used]
def rec():
if len(sols) >= limit:
return
best, bc_ = None, None
for r in range(n):
for c in range(n):
if grid[r][c] == 0:
cs = cands(r, c)
if best is None or len(cs) < len(bc_):
best, bc_ = (r, c), cs
if len(cs) <= 1:
break
if best is not None and len(bc_) <= 1:
break
if best is None:
sols.append([row_[:] for row_ in grid]); return
r, c = best
for v in bc_:
grid[r][c] = v
rec()
grid[r][c] = 0
if len(sols) >= limit:
return
rec()
return len(sols), (sols[0] if sols else None)
def sudoku(n_puzzles: int = 500):
rng = random.Random(SEED + 3)
out = []
cfgs = [(4, 2, 2, 0.5), (6, 2, 3, 0.5), (9, 3, 3, 0.5)]
weights = [0.3, 0.3, 0.4]
tries = 0
while len(out) < n_puzzles and tries < 10 * n_puzzles:
tries += 1
n, br, bc, frac = rng.choices(cfgs, weights)[0]
grid = [[0] * n for _ in range(n)]
# random fill of first row then solve
first = list(range(1, n + 1)); rng.shuffle(first); grid[0] = first[:]
_, full = _solve(grid, n, br, bc, 1)
if full is None:
continue
puzzle = [r[:] for r in full]
cells = [(r, c) for r in range(n) for c in range(n)]
rng.shuffle(cells)
target_blank = int(n * n * (frac if n != 9 else 0.5))
blanks = 0
for r, c in cells:
if blanks >= target_blank:
break
keep = puzzle[r][c]
puzzle[r][c] = 0
cnt, _ = _solve([x[:] for x in puzzle], n, br, bc, 2)
if cnt != 1:
puzzle[r][c] = keep
else:
blanks += 1
g = "\n".join("".join(str(v) if v else "." for v in row_) for row_ in puzzle)
out.append(row("planning", "sudoku_synth", len(out), "synthetic", SUDOKU_INSTR.format(n=n) + g, "sudoku", dict(puzzle=puzzle, solution=full, n=n, blanks=blanks), subject=f"{n}x{n}"))
return out
def planning():
return blocksworld() + hanoi() + sudoku()
|