"""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()