File size: 14,008 Bytes
6cbdce9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""gen_hard2 — procedurally generated REASONING puzzles with verified unique solutions.
Unlike v1, labels come from brute-force solvers over combinatorial spaces, and
surface wording is drawn from large paraphrase pools -> memorization-resistant."""
import hashlib, itertools, json, random
from datetime import date, timedelta

random.seed(31337)
D = "/root/alea/data/"
ROWS = []

FIRST = ["Avery", "Blair", "Casey", "Devon", "Emery", "Finley", "Gray", "Harper",
         "Indigo", "Jordan", "Kai", "Logan", "Morgan", "Nico", "Onyx", "Parker",
         "Quinn", "Reese", "Sage", "Tatum", "Uma", "Vale", "Wren", "Xander", "Yael", "Zion"]
OBJSETS = [
    ("book", ["red", "green", "blue", "yellow", "purple", "orange", "white", "black"]),
    ("runner", ["Ana", "Bo", "Cy", "Dee", "Eli", "Fay", "Gil", "Hal"]),
    ("vehicle", ["sedan", "truck", "motorcycle", "bicycle", "scooter", "bus", "van", "limo"]),
    ("fruit", ["apple", "pear", "plum", "kiwi", "mango", "peach", "melon", "fig"]),
    ("dog", ["labrador", "poodle", "beagle", "husky", "corgi", "boxer", "collie", "shiba"]),
]
ORDS = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth"]
LEFT = ["is somewhere to the left of", "is positioned left of", "comes before", "is earlier than", "precedes"]
ADJ = ["is immediately to the left of", "is right next to", "sits directly beside on the left of", "is adjacent and just before"]
ABS = ["is in position {k}", "occupies spot {k}", "is number {k}", "takes the {o} place"]
LAST_CLUE = ["is last", "comes last", "is in the final position", "is at the end"]


def emit(state, instr, kind, crit, tgval, src, gid):
    qs = {"q": {"type": kind, "instructions": instr, "criteria": crit}}
    ROWS.append({"state": state, "id": gid, "questions": qs,
                 "targets": {"q": tgval}, "source": src,
                 "group_id": gid, "family": src})


# ---------- 1. ordering CSP (logical_deduction-style, brute-force verified) ----------
def gen_order(i):
    n = random.choice([4, 5, 5, 5, 6])
    objtype, names = random.choice(OBJSETS)
    items = random.sample(names, n)
    perm = list(range(n))
    random.shuffle(perm)
    pos_of = {items[k]: perm[k] for k in range(n)}  # item -> 0-indexed pos
    contexts = {
        "book": "On a shelf, {} books are arranged left to right.",
        "runner": "In a race, {} runners finished in some order.",
        "vehicle": "{} vehicles are parked in a row, left to right.",
        "fruit": "{} fruits are arranged on a table left to right.",
        "dog": "{} dogs are lined up in a parade.",
    }
    intro = contexts[objtype].format(n)
    listing = "The {}s are: " + ", ".join(items) + "."
    if objtype == "runner":
        listing = "The runners are: " + ", ".join(items) + "."
    # build clue set until unique solution
    perms = list(itertools.permutations(range(n)))
    def sat(clues):
        cnt = 0; sol = None
        for prm in perms:
            p = {items[k]: prm[k] for k in range(n)}
            ok = True
            for c in clues:
                if c[0] == "lt" and not p[c[1]] < p[c[2]]: ok = False
                if c[0] == "adj" and not p[c[1]] + 1 == p[c[2]]: ok = False
                if c[0] == "abs" and not p[c[1]] == c[2]: ok = False
                if c[0] == "last" and not p[c[1]] == n - 1: ok = False
                if not ok: break
            if ok:
                cnt += 1; sol = prm
                if cnt > 1: return None, cnt
        return sol, cnt
    clues = []
    tries = 0
    while True:
        sol, cnt = sat(clues)
        if cnt == 1:
            break
        if tries > 400 or len(clues) > n + 2:
            return  # couldn't pin unique
        a, b = random.sample(items, 2)
        typ = random.choice(["lt", "lt", "adj", "abs", "last"])
        if typ == "lt":
            c = ("lt", a, b)
            txt = f"{a} {random.choice(LEFT)} {b}."
        elif typ == "adj":
            c = ("adj", a, b)
            txt = f"{a} {random.choice(ADJ)} {b}."
        elif typ == "abs":
            k = random.randint(0, n - 1)
            c = ("abs", a, k)
            txt = f"{a} {random.choice(ABS).format(k=k + 1, o=ORDS[k])}."
        else:
            c = ("last", a)
            txt = f"{a} {random.choice(LAST_CLUE)}."
        if c not in clues:
            clues.append(c)
        tries += 1
    sol, _ = sat(clues)
    solpos = {items[k]: sol[k] for k in range(n)}
    clue_texts = []
    for c in clues:
        if c[0] == "lt": clue_texts.append(f"{c[1]} {random.choice(LEFT)} {c[2]}.")
        elif c[0] == "adj": clue_texts.append(f"{c[1]} {random.choice(ADJ)} {c[2]}.")
        elif c[0] == "abs": clue_texts.append(f"{c[1]} {random.choice(ABS).format(k=c[2] + 1, o=ORDS[c[2]])}.")
        else: clue_texts.append(f"{c[1]} {random.choice(LAST_CLUE)}.")
    st = {"setup": intro + " " + listing.replace("{}s", objtype + "s"),
          "clues": clue_texts}
    k = random.randint(0, n - 1)
    truth = items[sol.index(k)]
    crit = {chr(65 + j): it for j, it in enumerate(items)}
    vec = [0.0] * n
    vec[items.index(truth)] = 1.0
    emit(st, f"Which {objtype if objtype != 'runner' else 'runner'} is in the {ORDS[k]} position?",
         "choice", crit, vec, "gh2:order", f"gh2:ord:{i}")


# ---------- 2. truth-tellers and liars (web_of_lies-style) ----------
def gen_liar(i):
    n = random.choice([3, 4, 4, 5])
    people = random.sample(FIRST, n)
    assign = {p: random.random() < 0.5 for p in people}  # True = truth-teller
    stmts = []
    for p in people[1:]:
        tgt = random.choice([q for q in people if q != p])
        claim = random.random() < 0.5  # claims tgt is truthful
        stmts.append((p, tgt, claim))
    # verify: assignment must be the unique consistent one
    def consistent(a):
        for (p, t, c) in stmts:
            said = (a[t] == c)
            if a[p] != said:
                return False
        return True
    sols = [a for a in (dict(zip(people, combo)) for combo in itertools.product([False, True], repeat=n)) if consistent(a)]
    if len(sols) != 1 or sols[0] != assign:
        return
    st = {"scenario": "Each person either always tells the truth or always lies.",
          "statements": [f"{p} says that {t} {'tells the truth' if c else 'lies'}." for p, t, c in stmts]}
    ask = random.choice(people)
    emit(st, f"Does {ask} tell the truth?", "noul", {},
         float(assign[ask]), "gh2:liar", f"gh2:liar:{i}")


# ---------- 3. swap tracking ----------
def gen_swaps(i):
    n = random.choice([4, 5])
    items = random.sample(FIRST, n)
    gifts = random.sample(["book", "lamp", "scarf", "clock", "vase", "mug", "plant", "radio"], n)
    hold = dict(zip(items, gifts))
    nsw = random.randint(3, 7)
    log = []
    for _ in range(nsw):
        a, b = random.sample(items, 2)
        log.append(f"{a} swaps with {b}.")
        hold[a], hold[b] = hold[b], hold[a]
    who = random.choice(items)
    st = {"initial": {p: hold0 for p, hold0 in zip(items, gifts)},
          "sequence": log}
    crit = {chr(65 + j): g for j, g in enumerate(gifts)}
    vec = [0.0] * n
    vec[gifts.index(hold[who])] = 1.0
    emit(st, f"After all the swaps, what does {who} have?", "choice", crit, vec,
         "gh2:swaps", f"gh2:swp:{i}")


# ---------- 4. compositional multi-constraint policy ----------
def gen_comp_policy(i):
    dom = random.choice(["expense report", "access request", "leave request", "vendor onboarding", "content publish"])
    thr = random.choice([50, 75, 100, 150, 200, 250])
    roles = ["intern", "contractor", "analyst", "senior analyst", "manager", "director"]
    role = random.choice(roles)
    need2 = random.random() < 0.5
    conds = [
        (f"amount exceeds {thr} USD", f"amount {thr + 1}+ requires finance sign-off"),
        ("requester is a contractor or intern", "contractors and interns are never auto-approved"),
        ("no receipt attached", "missing receipts block approval"),
        ("weekend submission", "weekend submissions queue until Monday"),
        ("requester is on probation", "probationary staff need HR clearance"),
        ("amount exceeds 1000 USD", "amounts over 1000 require director approval"),
    ]
    random.shuffle(conds)
    use = conds[:3]
    trig = [random.random() < 0.5 for _ in use]
    # rule: approved iff zero conditions triggered (conjunctive policy)
    approved = not any(trig)
    st = {"domain": dom,
          "policy": [f"Rule {j+1}: when {c[0]}, {c[1]}." for j, c in enumerate(use)]
                    + ["A request is auto-approved only when no blocking rule triggers."],
          "request": {"role": role,
                      **{f"condition_{j+1}": t for j, t in enumerate(trig)},
                      "triggered_conditions": [use[j][0] for j in range(3) if trig[j]]}}
    emit(st, "Is the request auto-approved?", "noul", {}, float(approved),
         "gh2:comp_policy", f"gh2:cp:{i}")


# ---------- 5. multi-step arithmetic with step-distractors ----------
def gen_arith(i):
    n1 = random.randint(8, 60)
    n2 = random.randint(3, 30)
    n3 = random.randint(2, 9)
    style = i % 3
    if style == 0:
        total = (n1 + n2) * n3
        st = {"problem": f"A crew packs {n1} boxes in the morning and {n2} boxes in the afternoon. "
                         f"Each box holds {n3} items. How many items are packed in total?"}
        wrong = [n1 * n3 + n2, (n1 + n2) * (n3 - 1), n1 + n2 * n3]
    elif style == 1:
        price, disc, qty = n1 + 20, random.choice([5, 10, 15, 20]), n3
        total = round((price - price * disc / 100) * qty, 2)
        st = {"problem": f"An item costs ${price}. There is a {disc}% discount, and a customer buys {qty}. "
                         f"What is the total paid?"}
        wrong = [round(price * qty, 2), round(price * (100 - disc) / 100, 2), round(price * qty * (100 - disc) / 100, 2)]
        total = wrong[2]
        wrong = wrong[:2] + [round(price * qty - disc, 2)]
    else:
        speed, t1, t2 = random.choice([40, 50, 60, 70]), n2, random.randint(1, 6)
        total = speed * (t1 + t2) / 60.0
        st = {"problem": f"A vehicle travels at {speed} km/h for {t1} minutes, then for {t2} more minutes at the same speed. "
                         f"How many kilometres does it cover?"}
        wrong = [round(speed * t1 / 60, 2), round(speed * (t1 + t2), 2), round(speed * t2 / 60, 2)]
    opts = [total] + wrong[:3]
    opts = list(dict.fromkeys(opts))[:4]
    while len(opts) < 4:
        opts.append(round(total * random.uniform(0.5, 1.5), 2))
    random.shuffle(opts)
    crit = {chr(65 + j): (f"{o:g}" if isinstance(o, float) else str(o)) for j, o in enumerate(opts)}
    vec = [0.0] * len(opts)
    vec[opts.index(total)] = 1.0
    emit(st, "What is the correct answer?", "choice", crit, vec, "gh2:arith", f"gh2:ar:{i}")


# ---------- 6. temporal compositional ----------
def gen_temporal2(i):
    base = date(2026, random.randint(1, 12), random.randint(1, 25))
    sub = i % 3
    if sub == 0:  # business days
        nbd = random.randint(3, 15)
        d = base
        cnt = 0
        while cnt < nbd:
            d += timedelta(days=1)
            if d.weekday() < 5:
                cnt += 1
        st = {"policy": f"Responses are due within {nbd} business days (Mon-Fri) of submission.",
              "submitted": base.isoformat(),
              "response_sent": (base + timedelta(days=nbd + random.randint(-3, 3))).isoformat()}
        resp = date.fromisoformat(st["response_sent"])
        due = d
        emit(st, "Was the response sent by the deadline?", "noul", {},
             float(resp <= due), "gh2:temp_biz", f"gh2:tb:{i}")
    elif sub == 1:  # multi-constraint scheduling
        a_len = random.choice([30, 45, 60, 90])
        b_len = random.choice([30, 45, 60])
        gap = random.choice([0, 15, 30])
        start = random.randint(8, 16)
        end_avail = random.randint(17, 20)
        total_min = a_len + gap + b_len
        feasible = start * 60 + total_min <= end_avail * 60
        st = {"meeting_a_minutes": a_len, "break_minutes": gap, "meeting_b_minutes": b_len,
              "earliest_start": f"{start:02d}:00", "hard_end": f"{end_avail:02d}:00"}
        emit(st, "Can both meetings plus the break fit between the earliest start and the hard end?",
             "noul", {}, float(feasible), "gh2:temp_sched", f"gh2:ts:{i}")
    else:  # interval overlap
        s1, s2 = random.randint(8, 18), random.randint(8, 18)
        l1, l2 = random.choice([1, 2, 3]), random.choice([1, 2, 3])
        overlap = s1 < s2 + l2 and s2 < s1 + l1
        st = {"booking_a": {"start_hour": s1, "duration_hours": l1},
              "booking_b": {"start_hour": s2, "duration_hours": l2}}
        emit(st, "Do the two bookings overlap?", "noul", {}, float(overlap),
             "gh2:temp_overlap", f"gh2:to:{i}")


GENS = [(gen_order, 8000), (gen_liar, 5000), (gen_swaps, 5000),
        (gen_comp_policy, 6000), (gen_arith, 6000), (gen_temporal2, 6000)]
for fn, cnt in GENS:
    made = 0
    i = 0
    while made < cnt and i < cnt * 3:
        before = len(ROWS)
        fn(i)
        if len(ROWS) > before:
            made += 1
        i += 1
    print(fn.__name__, "->", made)

fps, rows = set(), []
for r in ROWS:
    fp = hashlib.sha256((json.dumps(r["state"], sort_keys=True) +
                         json.dumps(r["questions"], sort_keys=True)).encode()).hexdigest()
    if fp in fps:
        continue
    fps.add(fp)
    rows.append(r)
random.shuffle(rows)
dev = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] == "0"]
train = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] != "0"]
tgg = {r["group_id"] for r in train}
dev = [r for r in dev if r["group_id"] not in tgg]
open(D + "gh2_train.jsonl", "w").write("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in train))
open(D + "gh2_dev.jsonl", "w").write("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in dev))
print("train", len(train), "dev", len(dev), "dupes_removed", len(ROWS) - len(rows))