alea-runs / alea /data_gen.py
Akahsizrr's picture
Upload alea/data_gen.py with huggingface_hub
b93c375 verified
Raw History Blame
13.7 kB
"""Synthetic System One task generator.
Every item is one request: {state, questions{qid: {...}}}, plus targets
{qid: {key: q}}. For stochastic event families, q is the exact conditional
distribution computed in closed form — that is what lets us measure
known-q L2 and real calibration, not just accuracy.
"""
import json
import math
import random
from fractions import Fraction
rng = random.Random()
COLORS = ["red", "blue", "green", "black", "white", "amber", "violet", "gray"]
FIRST = ["Mara", "Tobias", "Priya", "Kenji", "Lucia", "Omar", "Ingrid", "Felix",
"Sofia", "Dmitri", "Amara", "Jonas", "Nadia", "Pablo", "Yuki", "Elena"]
PRODUCTS = ["a headset", "a coffee grinder", "a keyboard", "a standing lamp",
"a backpack", "a monitor arm", "a water bottle", "a desk mat"]
ISSUES = ["a billing error", "a login failure", "a shipping delay",
"a damaged item", "a feature request", "an account lockout"]
PLANS = ["free", "starter", "pro", "enterprise"]
COUNTRIES = ["US", "DE", "FR", "JP", "BR", "IN", "GB", "CA", "AU", "SE"]
EU = {"DE", "FR", "SE"}
def _q_choice(qid, instructions, options, q):
"""options: list[str] option texts; q: list[float] aligned."""
return {"qid": qid, "qtype": "choice", "instructions": instructions,
"options": options, "target": q}
def _q_noul(qid, instructions, q):
return {"qid": qid, "qtype": "noul", "instructions": instructions,
"options": [], "target": q}
def _q_score(qid, instructions, levels, q):
return {"qid": qid, "qtype": "score", "instructions": instructions,
"options": levels, "target": q}
# ---------- stochastic event families (closed-form q) ----------
def gen_urn():
n_colors = rng.randint(2, 4)
colors = rng.sample(COLORS, n_colors)
counts = {c: rng.randint(1, 12) for c in colors}
total = sum(counts.values())
balls = ", ".join(f"{counts[c]} {c}" for c in colors)
state = (f"An urn contains {balls} ball{'s' if total > 1 else ''} "
f"({total} total). One ball is drawn uniformly at random.")
if rng.random() < 0.5:
c = rng.choice(colors)
q = _q_noul("draw", f"Will the drawn ball be {c}?", counts[c] / total)
else:
opts = [f"The drawn ball is {c}." for c in colors]
q = _q_choice("draw", "Which color is drawn?", opts,
[counts[c] / total for c in colors])
return state, [q]
def gen_two_draws():
c1, c2 = rng.sample(COLORS, 2)
r, b = rng.randint(2, 10), rng.randint(2, 10)
total = r + b
rep = rng.random() < 0.5
state = (f"An urn contains {r} {c1} and {b} {c2} balls. Two balls are "
f"drawn one at a time, {'with' if rep else 'without'} replacement.")
kind = rng.choice(["both", "same", "atleast"])
if kind == "both":
p = (r / total) * ((r / total) if rep else (r - 1) / (total - 1))
q = _q_noul("two", f"Will both drawn balls be {c1}?", p)
elif kind == "same":
if rep:
p = (r / total) ** 2 + (b / total) ** 2
else:
p = r * (r - 1) / (total * (total - 1)) + \
b * (b - 1) / (total * (total - 1))
q = _q_noul("two", "Will both drawn balls be the same color?", p)
else:
if rep:
p = 1 - (b / total) ** 2
else:
p = 1 - b * (b - 1) / (total * (total - 1))
q = _q_noul("two", f"Will at least one drawn ball be {c1}?", p)
return state, [q]
def gen_dice():
n = rng.randint(1, 4)
sides = rng.choice([4, 6, 8, 20])
state = f"{n} fair {sides}-sided dice are rolled."
kind = rng.choice(["atleast_max", "single", "sum2"])
if kind == "atleast_max" or (kind == "sum2" and n != 2):
p = 1 - ((sides - 1) / sides) ** n
q = _q_noul("roll", f"Will at least one die show {sides}?", p)
elif kind == "single":
face = rng.randint(1, sides)
p = 1 - ((sides - 1) / sides) ** n
q = _q_noul("roll", f"Will at least one die show a {face}?", p)
else:
t = rng.randint(3, 2 * sides - 1)
ways = max(0, min(sides, t - 1) - max(1, t - sides) + 1)
p = ways / (sides * sides)
q = _q_noul("roll", f"Will the two dice sum to exactly {t}?", p)
return state, [q]
def gen_lottery():
n = rng.randint(3, 6)
names = rng.sample(FIRST, n)
weights = {nm: rng.randint(1, 20) for nm in names}
total = sum(weights.values())
state = ("A raffle is held. " + ", ".join(
f"{nm} holds {weights[nm]} ticket{'s' if weights[nm] > 1 else ''}"
for nm in names) + ". One ticket is drawn uniformly at random.")
if rng.random() < 0.4:
nm = rng.choice(names)
q = _q_noul("win", f"Will {nm} win the raffle?", weights[nm] / total)
else:
opts = [f"{nm} wins the raffle." for nm in names]
q = _q_choice("win", "Who wins the raffle?", opts,
[weights[nm] / total for nm in names])
return state, [q]
def gen_marble_machine():
p = rng.choice([0.1, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9])
state = (f"A sorting machine processes marbles. It outputs 'ACCEPT' with "
f"probability {p:.2f} and 'REJECT' otherwise, independently for "
f"each marble. One marble is fed in.")
q = _q_noul("m", "Will the machine output 'ACCEPT'?", p)
return state, [q]
# ---------- deterministic families ----------
def gen_plan_rules():
mrr = rng.randint(5, 400)
name = rng.choice(FIRST)
state = (f"Customer record: name={name}, mrr=${mrr}, "
f"plan={rng.choice(PLANS)}, country={rng.choice(COUNTRIES)}.")
tiers = [("basic", "Accounts with monthly revenue under $50"),
("growth", "Accounts with monthly revenue from $50 to $150"),
("scale", "Accounts with monthly revenue over $150")]
if mrr < 50:
idx = 0
elif mrr <= 150:
idx = 1
else:
idx = 2
q = _q_choice("tier", "Which revenue tier does this account fall into?",
[f"{k}: {d}" for k, d in tiers],
[1.0 if i == idx else 0.0 for i in range(3)])
return state, [q]
def gen_routing():
issue = rng.choice(ISSUES)
name = rng.choice(FIRST)
state = f"Support ticket from {name}: the customer reports {issue}."
mapping = {
"a billing error": ("billing", "Charges, refunds and invoice problems"),
"a login failure": ("account", "Sign-in, passwords and access"),
"a shipping delay": ("logistics", "Delivery status and shipping"),
"a damaged item": ("logistics", "Delivery status and shipping"),
"a feature request": ("product", "New features and improvements"),
"an account lockout": ("account", "Sign-in, passwords and access"),
}
correct = mapping[issue][0]
teams = [("billing", "Charges, refunds and invoice problems"),
("account", "Sign-in, passwords and access"),
("logistics", "Delivery status and shipping"),
("product", "New features and improvements")]
q = _q_choice("queue", "Which team should handle this ticket?",
[f"{k}: {d}" for k, d in teams],
[1.0 if k == correct else 0.0 for k, _ in teams])
if rng.random() < 0.5:
p_urgent = 0.9 if issue in ("an account lockout", "a damaged item") else 0.15
q2 = _q_noul("urgent", "Does this ticket require urgent attention?", p_urgent)
return state, [q, q2]
return state, [q]
def gen_reference_card():
values = rng.sample(["amber", "indigo", "crimson", "teal"], 3)
card_val = values[0]
n_opts = 3
card_idx = rng.randrange(n_opts)
opts = []
labels = iter(values)
for i in range(n_opts):
if i == card_idx:
opts.append(f"Reference card: status = {card_val}. "
"Reference-only option. Never select this option.")
else:
v = next(labels)
opts.append(f"Select this option if the reference card's status "
f"is {v}.")
correct = next(i for i, o in enumerate(opts)
if f"status is {card_val}" in o)
state = "A routing console displays a reference card and a rule set."
q = _q_choice("pick", "Read the reference card and select the one option "
"whose condition is satisfied.", opts,
[1.0 if i == correct else 0.0 for i in range(n_opts)])
return state, [q]
def gen_noul_compare():
a, b = rng.randint(10, 500), rng.randint(10, 500)
prod = rng.choice(PRODUCTS)
state = (f"Invoice: {prod}, unit price ${a}, quantity {b}. "
f"Customer: {rng.choice(FIRST)}.")
thr = rng.choice([500, 1000, 5000, 10000, 20000])
total = a * b
q = _q_noul("total", f"Is the invoice total over ${thr}?", float(total > thr))
return state, [q]
def gen_score_urgency():
levels = ["0: Routine — handle in normal order",
"1: Low — handle within a few days",
"2: Moderate — handle within a day",
"3: High — handle within hours",
"4: Critical — drop everything"]
issue, base = rng.choice([
("the app crashed and they lost unsaved work", 4),
("they cannot sign in and have a deadline today", 3),
("a report shows slightly wrong totals", 2),
("they ask how to change their avatar", 1),
("they want to know if a dark mode exists", 0),
])
n = rng.choice([3, 4, 5])
lv = levels[:n]
# resample base if out of range
base = min(base, n - 1)
# soft q: mass concentrated on base level with light noise
q = [0.04] * n
q[base] = 0.88
if base + 1 < n:
q[base + 1] += 0.04
if base - 1 >= 0:
q[base - 1] += 0.04
s = sum(q)
q = [x / s for x in q]
name = rng.choice(FIRST)
state = f"Ticket from {name}: {issue}."
qs = _q_score("urgency", "How urgent is this ticket?", lv, q)
return state, [qs]
def gen_decoy_choice():
cause = rng.choice(["bank", "provider", "customer"])
opts = {"bank": "The originating bank rejected the payout",
"provider": "The payment provider's API timed out",
"customer": "The customer entered wrong account details",
"unknown": "The cause cannot be determined from the evidence"}
state = ("Payout failure log: error_code=NSF, bank_response=insufficient_funds. "
"The customer's balance was verified low at attempt time.")
keys = list(opts.keys())
rng.shuffle(keys)
if rng.random() < 0.6:
opts[rng.choice(["weather", "birds", "holiday"])] = \
rng.choice(["Bad weather caused it", "Wild birds caused it",
"A public holiday caused it"])
keys = list(opts.keys())
correct = keys.index("customer")
q = _q_choice("cause", "What caused the payout failure?",
[f"{k}: {opts[k]}" for k in keys],
[1.0 if i == correct else 0.0 for i in range(len(keys))])
return state, [q]
def gen_compound():
"""Multi-question request mixing types — exercises the shared-state path."""
st1, q1 = gen_urn()
st2, q2s = gen_routing()
name = rng.choice(FIRST)
state = f"{st1} Separately, {st2.lower()}"
for q in q1 + q2s:
q["qid"] = f"{q['qid']}_{rng.randrange(1e6)}"
return state, q1 + q2s
FAMILIES = {
"urn": gen_urn,
"two_draws": gen_two_draws,
"dice": gen_dice,
"lottery": gen_lottery,
"marble": gen_marble_machine,
"plan": gen_plan_rules,
"route": gen_routing,
"refcard": gen_reference_card,
"compare": gen_noul_compare,
"urgency": gen_score_urgency,
"decoy": gen_decoy_choice,
"compound": gen_compound,
}
WEIGHTS = {
"urn": 0.15, "two_draws": 0.12, "dice": 0.10, "lottery": 0.10,
"marble": 0.06, "plan": 0.08, "route": 0.10, "refcard": 0.08,
"compare": 0.08, "urgency": 0.06, "decoy": 0.04, "compound": 0.03,
}
def generate(n, seed=0, path=None):
rng.seed(seed)
fams, ws = zip(*WEIGHTS.items())
rows = []
for i in range(n):
f = rng.choices(fams, ws)[0]
try:
state, qs = FAMILIES[f]()
except Exception:
continue
row = {"id": f"{f}-{i}", "family": f, "state": state,
"questions": {
q["qid"]: {
"type": q["qtype"],
"instructions": q["instructions"],
**({"criteria": {str(j): o for j, o in enumerate(q["options"])}}
if q["qtype"] in ("choice", "score") else {}),
} for q in qs},
"targets": {
q["qid"]: (q["target"] if isinstance(q["target"], list)
else q["target"]) for q in qs}}
rows.append(row)
if path:
with open(path, "w", encoding="utf-8") as fh:
for r in rows:
fh.write(json.dumps(r) + "\n")
return rows
if __name__ == "__main__":
import sys
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1000
seed = int(sys.argv[2]) if len(sys.argv) > 2 else 0
out = sys.argv[3] if len(sys.argv) > 3 else None
rows = generate(n, seed, out)
print(f"{len(rows)} rows" + (f" -> {out}" if out else ""))