Akahsizrr commited on
Commit
6cbdce9
·
verified ·
1 Parent(s): 1e09221

Upload scripts/gen_hard2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/gen_hard2.py +300 -0
scripts/gen_hard2.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gen_hard2 — procedurally generated REASONING puzzles with verified unique solutions.
2
+ Unlike v1, labels come from brute-force solvers over combinatorial spaces, and
3
+ surface wording is drawn from large paraphrase pools -> memorization-resistant."""
4
+ import hashlib, itertools, json, random
5
+ from datetime import date, timedelta
6
+
7
+ random.seed(31337)
8
+ D = "/root/alea/data/"
9
+ ROWS = []
10
+
11
+ FIRST = ["Avery", "Blair", "Casey", "Devon", "Emery", "Finley", "Gray", "Harper",
12
+ "Indigo", "Jordan", "Kai", "Logan", "Morgan", "Nico", "Onyx", "Parker",
13
+ "Quinn", "Reese", "Sage", "Tatum", "Uma", "Vale", "Wren", "Xander", "Yael", "Zion"]
14
+ OBJSETS = [
15
+ ("book", ["red", "green", "blue", "yellow", "purple", "orange", "white", "black"]),
16
+ ("runner", ["Ana", "Bo", "Cy", "Dee", "Eli", "Fay", "Gil", "Hal"]),
17
+ ("vehicle", ["sedan", "truck", "motorcycle", "bicycle", "scooter", "bus", "van", "limo"]),
18
+ ("fruit", ["apple", "pear", "plum", "kiwi", "mango", "peach", "melon", "fig"]),
19
+ ("dog", ["labrador", "poodle", "beagle", "husky", "corgi", "boxer", "collie", "shiba"]),
20
+ ]
21
+ ORDS = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth"]
22
+ LEFT = ["is somewhere to the left of", "is positioned left of", "comes before", "is earlier than", "precedes"]
23
+ ADJ = ["is immediately to the left of", "is right next to", "sits directly beside on the left of", "is adjacent and just before"]
24
+ ABS = ["is in position {k}", "occupies spot {k}", "is number {k}", "takes the {o} place"]
25
+ LAST_CLUE = ["is last", "comes last", "is in the final position", "is at the end"]
26
+
27
+
28
+ def emit(state, instr, kind, crit, tgval, src, gid):
29
+ qs = {"q": {"type": kind, "instructions": instr, "criteria": crit}}
30
+ ROWS.append({"state": state, "id": gid, "questions": qs,
31
+ "targets": {"q": tgval}, "source": src,
32
+ "group_id": gid, "family": src})
33
+
34
+
35
+ # ---------- 1. ordering CSP (logical_deduction-style, brute-force verified) ----------
36
+ def gen_order(i):
37
+ n = random.choice([4, 5, 5, 5, 6])
38
+ objtype, names = random.choice(OBJSETS)
39
+ items = random.sample(names, n)
40
+ perm = list(range(n))
41
+ random.shuffle(perm)
42
+ pos_of = {items[k]: perm[k] for k in range(n)} # item -> 0-indexed pos
43
+ contexts = {
44
+ "book": "On a shelf, {} books are arranged left to right.",
45
+ "runner": "In a race, {} runners finished in some order.",
46
+ "vehicle": "{} vehicles are parked in a row, left to right.",
47
+ "fruit": "{} fruits are arranged on a table left to right.",
48
+ "dog": "{} dogs are lined up in a parade.",
49
+ }
50
+ intro = contexts[objtype].format(n)
51
+ listing = "The {}s are: " + ", ".join(items) + "."
52
+ if objtype == "runner":
53
+ listing = "The runners are: " + ", ".join(items) + "."
54
+ # build clue set until unique solution
55
+ perms = list(itertools.permutations(range(n)))
56
+ def sat(clues):
57
+ cnt = 0; sol = None
58
+ for prm in perms:
59
+ p = {items[k]: prm[k] for k in range(n)}
60
+ ok = True
61
+ for c in clues:
62
+ if c[0] == "lt" and not p[c[1]] < p[c[2]]: ok = False
63
+ if c[0] == "adj" and not p[c[1]] + 1 == p[c[2]]: ok = False
64
+ if c[0] == "abs" and not p[c[1]] == c[2]: ok = False
65
+ if c[0] == "last" and not p[c[1]] == n - 1: ok = False
66
+ if not ok: break
67
+ if ok:
68
+ cnt += 1; sol = prm
69
+ if cnt > 1: return None, cnt
70
+ return sol, cnt
71
+ clues = []
72
+ tries = 0
73
+ while True:
74
+ sol, cnt = sat(clues)
75
+ if cnt == 1:
76
+ break
77
+ if tries > 400 or len(clues) > n + 2:
78
+ return # couldn't pin unique
79
+ a, b = random.sample(items, 2)
80
+ typ = random.choice(["lt", "lt", "adj", "abs", "last"])
81
+ if typ == "lt":
82
+ c = ("lt", a, b)
83
+ txt = f"{a} {random.choice(LEFT)} {b}."
84
+ elif typ == "adj":
85
+ c = ("adj", a, b)
86
+ txt = f"{a} {random.choice(ADJ)} {b}."
87
+ elif typ == "abs":
88
+ k = random.randint(0, n - 1)
89
+ c = ("abs", a, k)
90
+ txt = f"{a} {random.choice(ABS).format(k=k + 1, o=ORDS[k])}."
91
+ else:
92
+ c = ("last", a)
93
+ txt = f"{a} {random.choice(LAST_CLUE)}."
94
+ if c not in clues:
95
+ clues.append(c)
96
+ tries += 1
97
+ sol, _ = sat(clues)
98
+ solpos = {items[k]: sol[k] for k in range(n)}
99
+ clue_texts = []
100
+ for c in clues:
101
+ if c[0] == "lt": clue_texts.append(f"{c[1]} {random.choice(LEFT)} {c[2]}.")
102
+ elif c[0] == "adj": clue_texts.append(f"{c[1]} {random.choice(ADJ)} {c[2]}.")
103
+ elif c[0] == "abs": clue_texts.append(f"{c[1]} {random.choice(ABS).format(k=c[2] + 1, o=ORDS[c[2]])}.")
104
+ else: clue_texts.append(f"{c[1]} {random.choice(LAST_CLUE)}.")
105
+ st = {"setup": intro + " " + listing.replace("{}s", objtype + "s"),
106
+ "clues": clue_texts}
107
+ k = random.randint(0, n - 1)
108
+ truth = items[sol.index(k)]
109
+ crit = {chr(65 + j): it for j, it in enumerate(items)}
110
+ vec = [0.0] * n
111
+ vec[items.index(truth)] = 1.0
112
+ emit(st, f"Which {objtype if objtype != 'runner' else 'runner'} is in the {ORDS[k]} position?",
113
+ "choice", crit, vec, "gh2:order", f"gh2:ord:{i}")
114
+
115
+
116
+ # ---------- 2. truth-tellers and liars (web_of_lies-style) ----------
117
+ def gen_liar(i):
118
+ n = random.choice([3, 4, 4, 5])
119
+ people = random.sample(FIRST, n)
120
+ assign = {p: random.random() < 0.5 for p in people} # True = truth-teller
121
+ stmts = []
122
+ for p in people[1:]:
123
+ tgt = random.choice([q for q in people if q != p])
124
+ claim = random.random() < 0.5 # claims tgt is truthful
125
+ stmts.append((p, tgt, claim))
126
+ # verify: assignment must be the unique consistent one
127
+ def consistent(a):
128
+ for (p, t, c) in stmts:
129
+ said = (a[t] == c)
130
+ if a[p] != said:
131
+ return False
132
+ return True
133
+ sols = [a for a in (dict(zip(people, combo)) for combo in itertools.product([False, True], repeat=n)) if consistent(a)]
134
+ if len(sols) != 1 or sols[0] != assign:
135
+ return
136
+ st = {"scenario": "Each person either always tells the truth or always lies.",
137
+ "statements": [f"{p} says that {t} {'tells the truth' if c else 'lies'}." for p, t, c in stmts]}
138
+ ask = random.choice(people)
139
+ emit(st, f"Does {ask} tell the truth?", "noul", {},
140
+ float(assign[ask]), "gh2:liar", f"gh2:liar:{i}")
141
+
142
+
143
+ # ---------- 3. swap tracking ----------
144
+ def gen_swaps(i):
145
+ n = random.choice([4, 5])
146
+ items = random.sample(FIRST, n)
147
+ gifts = random.sample(["book", "lamp", "scarf", "clock", "vase", "mug", "plant", "radio"], n)
148
+ hold = dict(zip(items, gifts))
149
+ nsw = random.randint(3, 7)
150
+ log = []
151
+ for _ in range(nsw):
152
+ a, b = random.sample(items, 2)
153
+ log.append(f"{a} swaps with {b}.")
154
+ hold[a], hold[b] = hold[b], hold[a]
155
+ who = random.choice(items)
156
+ st = {"initial": {p: hold0 for p, hold0 in zip(items, gifts)},
157
+ "sequence": log}
158
+ crit = {chr(65 + j): g for j, g in enumerate(gifts)}
159
+ vec = [0.0] * n
160
+ vec[gifts.index(hold[who])] = 1.0
161
+ emit(st, f"After all the swaps, what does {who} have?", "choice", crit, vec,
162
+ "gh2:swaps", f"gh2:swp:{i}")
163
+
164
+
165
+ # ---------- 4. compositional multi-constraint policy ----------
166
+ def gen_comp_policy(i):
167
+ dom = random.choice(["expense report", "access request", "leave request", "vendor onboarding", "content publish"])
168
+ thr = random.choice([50, 75, 100, 150, 200, 250])
169
+ roles = ["intern", "contractor", "analyst", "senior analyst", "manager", "director"]
170
+ role = random.choice(roles)
171
+ need2 = random.random() < 0.5
172
+ conds = [
173
+ (f"amount exceeds {thr} USD", f"amount {thr + 1}+ requires finance sign-off"),
174
+ ("requester is a contractor or intern", "contractors and interns are never auto-approved"),
175
+ ("no receipt attached", "missing receipts block approval"),
176
+ ("weekend submission", "weekend submissions queue until Monday"),
177
+ ("requester is on probation", "probationary staff need HR clearance"),
178
+ ("amount exceeds 1000 USD", "amounts over 1000 require director approval"),
179
+ ]
180
+ random.shuffle(conds)
181
+ use = conds[:3]
182
+ trig = [random.random() < 0.5 for _ in use]
183
+ # rule: approved iff zero conditions triggered (conjunctive policy)
184
+ approved = not any(trig)
185
+ st = {"domain": dom,
186
+ "policy": [f"Rule {j+1}: when {c[0]}, {c[1]}." for j, c in enumerate(use)]
187
+ + ["A request is auto-approved only when no blocking rule triggers."],
188
+ "request": {"role": role,
189
+ **{f"condition_{j+1}": t for j, t in enumerate(trig)},
190
+ "triggered_conditions": [use[j][0] for j in range(3) if trig[j]]}}
191
+ emit(st, "Is the request auto-approved?", "noul", {}, float(approved),
192
+ "gh2:comp_policy", f"gh2:cp:{i}")
193
+
194
+
195
+ # ---------- 5. multi-step arithmetic with step-distractors ----------
196
+ def gen_arith(i):
197
+ n1 = random.randint(8, 60)
198
+ n2 = random.randint(3, 30)
199
+ n3 = random.randint(2, 9)
200
+ style = i % 3
201
+ if style == 0:
202
+ total = (n1 + n2) * n3
203
+ st = {"problem": f"A crew packs {n1} boxes in the morning and {n2} boxes in the afternoon. "
204
+ f"Each box holds {n3} items. How many items are packed in total?"}
205
+ wrong = [n1 * n3 + n2, (n1 + n2) * (n3 - 1), n1 + n2 * n3]
206
+ elif style == 1:
207
+ price, disc, qty = n1 + 20, random.choice([5, 10, 15, 20]), n3
208
+ total = round((price - price * disc / 100) * qty, 2)
209
+ st = {"problem": f"An item costs ${price}. There is a {disc}% discount, and a customer buys {qty}. "
210
+ f"What is the total paid?"}
211
+ wrong = [round(price * qty, 2), round(price * (100 - disc) / 100, 2), round(price * qty * (100 - disc) / 100, 2)]
212
+ total = wrong[2]
213
+ wrong = wrong[:2] + [round(price * qty - disc, 2)]
214
+ else:
215
+ speed, t1, t2 = random.choice([40, 50, 60, 70]), n2, random.randint(1, 6)
216
+ total = speed * (t1 + t2) / 60.0
217
+ st = {"problem": f"A vehicle travels at {speed} km/h for {t1} minutes, then for {t2} more minutes at the same speed. "
218
+ f"How many kilometres does it cover?"}
219
+ wrong = [round(speed * t1 / 60, 2), round(speed * (t1 + t2), 2), round(speed * t2 / 60, 2)]
220
+ opts = [total] + wrong[:3]
221
+ opts = list(dict.fromkeys(opts))[:4]
222
+ while len(opts) < 4:
223
+ opts.append(round(total * random.uniform(0.5, 1.5), 2))
224
+ random.shuffle(opts)
225
+ crit = {chr(65 + j): (f"{o:g}" if isinstance(o, float) else str(o)) for j, o in enumerate(opts)}
226
+ vec = [0.0] * len(opts)
227
+ vec[opts.index(total)] = 1.0
228
+ emit(st, "What is the correct answer?", "choice", crit, vec, "gh2:arith", f"gh2:ar:{i}")
229
+
230
+
231
+ # ---------- 6. temporal compositional ----------
232
+ def gen_temporal2(i):
233
+ base = date(2026, random.randint(1, 12), random.randint(1, 25))
234
+ sub = i % 3
235
+ if sub == 0: # business days
236
+ nbd = random.randint(3, 15)
237
+ d = base
238
+ cnt = 0
239
+ while cnt < nbd:
240
+ d += timedelta(days=1)
241
+ if d.weekday() < 5:
242
+ cnt += 1
243
+ st = {"policy": f"Responses are due within {nbd} business days (Mon-Fri) of submission.",
244
+ "submitted": base.isoformat(),
245
+ "response_sent": (base + timedelta(days=nbd + random.randint(-3, 3))).isoformat()}
246
+ resp = date.fromisoformat(st["response_sent"])
247
+ due = d
248
+ emit(st, "Was the response sent by the deadline?", "noul", {},
249
+ float(resp <= due), "gh2:temp_biz", f"gh2:tb:{i}")
250
+ elif sub == 1: # multi-constraint scheduling
251
+ a_len = random.choice([30, 45, 60, 90])
252
+ b_len = random.choice([30, 45, 60])
253
+ gap = random.choice([0, 15, 30])
254
+ start = random.randint(8, 16)
255
+ end_avail = random.randint(17, 20)
256
+ total_min = a_len + gap + b_len
257
+ feasible = start * 60 + total_min <= end_avail * 60
258
+ st = {"meeting_a_minutes": a_len, "break_minutes": gap, "meeting_b_minutes": b_len,
259
+ "earliest_start": f"{start:02d}:00", "hard_end": f"{end_avail:02d}:00"}
260
+ emit(st, "Can both meetings plus the break fit between the earliest start and the hard end?",
261
+ "noul", {}, float(feasible), "gh2:temp_sched", f"gh2:ts:{i}")
262
+ else: # interval overlap
263
+ s1, s2 = random.randint(8, 18), random.randint(8, 18)
264
+ l1, l2 = random.choice([1, 2, 3]), random.choice([1, 2, 3])
265
+ overlap = s1 < s2 + l2 and s2 < s1 + l1
266
+ st = {"booking_a": {"start_hour": s1, "duration_hours": l1},
267
+ "booking_b": {"start_hour": s2, "duration_hours": l2}}
268
+ emit(st, "Do the two bookings overlap?", "noul", {}, float(overlap),
269
+ "gh2:temp_overlap", f"gh2:to:{i}")
270
+
271
+
272
+ GENS = [(gen_order, 8000), (gen_liar, 5000), (gen_swaps, 5000),
273
+ (gen_comp_policy, 6000), (gen_arith, 6000), (gen_temporal2, 6000)]
274
+ for fn, cnt in GENS:
275
+ made = 0
276
+ i = 0
277
+ while made < cnt and i < cnt * 3:
278
+ before = len(ROWS)
279
+ fn(i)
280
+ if len(ROWS) > before:
281
+ made += 1
282
+ i += 1
283
+ print(fn.__name__, "->", made)
284
+
285
+ fps, rows = set(), []
286
+ for r in ROWS:
287
+ fp = hashlib.sha256((json.dumps(r["state"], sort_keys=True) +
288
+ json.dumps(r["questions"], sort_keys=True)).encode()).hexdigest()
289
+ if fp in fps:
290
+ continue
291
+ fps.add(fp)
292
+ rows.append(r)
293
+ random.shuffle(rows)
294
+ dev = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] == "0"]
295
+ train = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] != "0"]
296
+ tgg = {r["group_id"] for r in train}
297
+ dev = [r for r in dev if r["group_id"] not in tgg]
298
+ open(D + "gh2_train.jsonl", "w").write("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in train))
299
+ open(D + "gh2_dev.jsonl", "w").write("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in dev))
300
+ print("train", len(train), "dev", len(dev), "dupes_removed", len(ROWS) - len(rows))