alea-runs / alea /gen_structured.py
Akahsizrr's picture
Upload alea/gen_structured.py with huggingface_hub
7379c29 verified
Raw History Blame
23.6 kB
"""Synthetic STRUCTURED/DATA-HEAVY states for the decision-model corpus.
Jev accepts text, JSON objects and JSON arrays as `state`; these families
exercise structured-state comprehension: serialized JSON record sets, log
excerpts, markdown/CSV tables, date arithmetic, metric comparisons,
nested order documents and mixed-type JSON arrays. Most rows serialize
`state` with json.dumps (as real callers do); log/table rows stay text.
Targets are exact one-hot / 0-1 for lookups and comparisons; soft q only
for inherently fuzzy judgments (log-burst severity).
"""
import json
import random
from datetime import date, timedelta
from alea.genbase import (generate, emit, q_choice, q_noul, q_score,
validate_row, write_jsonl)
rng = random.Random()
FIRST = ["Mara", "Tobias", "Priya", "Kenji", "Lucia", "Omar", "Ingrid",
"Felix", "Sofia", "Dmitri", "Amara", "Jonas", "Nadia", "Pablo"]
SERVICES = ["auth", "billing", "gateway", "search", "notify", "cache",
"payments", "uploads"]
PRODUCTS = ["headset", "coffee grinder", "keyboard", "standing lamp",
"backpack", "monitor arm", "water bottle", "desk mat"]
CITIES = ["Oslo", "Lima", "Nairobi", "Osaka", "Porto", "Austin", "Lyon",
"Hanoi"]
COUNTRIES = ["US", "DE", "FR", "JP", "BR", "IN", "GB", "CA", "NL", "SE"]
# inclusive sampling ranges for record fields (salary is in $1000s)
FRANGES = {"units": (1, 40), "total": (20, 900), "stock": (0, 150),
"price": (5, 300), "salary": (45, 180), "yrs": (1, 20),
"temp_c": (-5, 45), "humidity": (10, 95)}
def _one_hot(idx, n):
return [1.0 if j == idx else 0.0 for j in range(n)]
def _softq(idx, n):
"""Fuzzy judgment target: 0.7 on `idx`, remainder on neighbours."""
q = [0.0] * n
q[idx] = 0.7
if idx - 1 >= 0 and idx + 1 < n:
q[idx - 1], q[idx + 1] = 0.2, 0.1
elif idx - 1 >= 0:
q[idx - 1] = 0.3
elif idx + 1 < n:
q[idx + 1] = 0.3
else:
q[idx] = 1.0
return q
def _count_opts(true, hi):
"""3-4 option count window containing `true`, clipped to [0, hi]."""
lo = max(0, true - 1)
opts = list(range(lo, min(hi, true + 2) + 1))
while len(opts) < 3 and opts[0] > 0:
opts.insert(0, opts[0] - 1)
while len(opts) < 3 and opts[-1] < hi:
opts.append(opts[-1] + 1)
return [str(i) for i in opts]
# ---------- json_records: flat JSON arrays of records ----------
def gen_json_records():
kind = rng.choice(["orders", "inventory", "employees", "sensors"])
n = rng.randint(4, 6)
group = None
if kind == "orders":
custs = rng.sample(FIRST, 2)
recs = [{"order_id": f"O-{1000 + i}", "customer": rng.choice(custs),
"units": rng.randint(1, 40),
"total": rng.randint(20, 900)} for i in range(n)]
label, fields, group = "order_id", ["units", "total"], "customer"
noun = "order"
elif kind == "inventory":
names = rng.sample(PRODUCTS, n)
recs = [{"sku": f"SKU-{200 + i}", "name": names[i],
"stock": rng.randint(0, 150),
"price": rng.randint(5, 300)} for i in range(n)]
label, fields = "sku", ["stock", "price"]
noun = "item"
elif kind == "employees":
depts = rng.sample(["eng", "sales", "ops", "hr"], 2)
names = rng.sample(FIRST, n)
recs = [{"name": names[i], "dept": rng.choice(depts),
"salary": rng.randint(45, 180) * 1000,
"yrs": rng.randint(1, 20)} for i in range(n)]
label, fields, group = "name", ["salary", "yrs"], "dept"
noun = "employee"
else:
zones = rng.sample(["north", "south", "roof", "cellar"], 2)
recs = [{"sensor_id": f"S-{i + 1}", "zone": rng.choice(zones),
"temp_c": rng.randint(-5, 45),
"humidity": rng.randint(10, 95)} for i in range(n)]
label, fields, group = "sensor_id", ["temp_c", "humidity"], "zone"
noun = "sensor"
state = json.dumps(recs, separators=(",", ":"))
qs = []
# 1) extreme-value lookup — resample the field so the argmax/min is strict
f = rng.choice(fields)
lo, hi = FRANGES[f]
for r, v in zip(recs, rng.sample(range(lo, hi + 1), n)):
r[f] = v * 1000 if f == "salary" else v
vals = [r[f] for r in recs]
want_max = rng.random() < 0.5
correct = vals.index(max(vals) if want_max else min(vals))
instr = rng.choice([
f"Which {noun} has the {'highest' if want_max else 'lowest'} {f}?",
f"Identify the {noun} with the "
f"{'greatest' if want_max else 'smallest'} {f}."])
qs.append(q_choice("extreme", instr, [str(r[label]) for r in recs],
_one_hot(correct, n)))
# 2) threshold predicate
f2 = rng.choice(fields)
v2 = [r[f2] for r in recs]
if min(v2) >= max(v2):
raise ValueError("degenerate threshold")
if rng.random() < 0.5:
t = rng.randint(min(v2) + 1, max(v2))
ans = any(v > t for v in v2)
instr = rng.choice([
f"Is any {noun}'s {f2} above {t}?",
f"Does any {noun} have {f2} exceeding {t}?"])
else:
t = rng.randint(min(v2), max(v2) - 1)
ans = any(v < t for v in v2)
instr = rng.choice([
f"Is any {noun}'s {f2} below {t}?",
f"Does any {noun} have {f2} under {t}?"])
qs.append(q_noul("thresh", instr, float(ans)))
# 3) group aggregation or count (where a grouping field exists)
agg = {"orders": ("customer", "total"),
"employees": ("dept", "salary")}.get(kind)
if agg and rng.random() < 0.6:
gk, fk = agg
ga, gb = rng.sample(sorted({r[gk] for r in recs}), 2)
sa = sum(r[fk] for r in recs if r[gk] == ga)
sb = sum(r[fk] for r in recs if r[gk] == gb)
if sa == sb:
raise ValueError("tie")
instr = (f"Do the orders for {ga} total more than those for {gb}?"
if kind == "orders" else
f"Does department {ga} have a larger payroll than {gb}?")
qs.append(q_noul("group", instr, float(sa > sb)))
elif group:
gv = rng.choice(sorted({r[group] for r in recs}))
c = sum(1 for r in recs if r[group] == gv)
gword = {"orders": "belong to customer",
"employees": "are in department",
"sensors": "are in zone"}[kind]
opts_c = _count_opts(c, n)
qs.append(q_choice("count",
f"How many {noun}s {gword} '{gv}'?", opts_c,
_one_hot(opts_c.index(str(c)), len(opts_c))))
else: # inventory: stock-value aggregate
tot = sum(r["stock"] * r["price"] for r in recs)
t = rng.randint(int(tot * 0.5), int(tot * 1.5))
qs.append(q_noul("value", f"Is the total stock value above ${t}?",
float(tot > t)))
return state, qs
# ---------- log_lines: timestamped log excerpt (text state) ----------
_LOG_MSGS = {"INFO": ["request completed", "health check ok", "cache hit",
"job finished", "config reloaded"],
"WARN": ["retrying upstream", "slow query 1200ms",
"rate limit approaching"],
"ERROR": ["unhandled exception", "db connection failed",
"upstream timeout", "payment rejected"],
"CRITICAL": ["oom killed", "data corruption detected"]}
def gen_log_lines():
day = f"2024-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}"
svcs = rng.sample(SERVICES, rng.randint(3, 4))
n = rng.randint(6, 9)
err_idx = set(rng.sample(range(n), rng.randint(2, 3)))
crit_i = rng.choice(sorted(err_idx)) if rng.random() < 0.3 else -1
force5 = rng.choice(sorted(err_idx - {crit_i})) \
if rng.random() < 0.75 and len(err_idx - {crit_i}) else -1
lines, events = [], []
t = rng.randint(0, 600)
for i in range(n):
t += rng.randint(5, 240)
ts = f"{day}T{8 + t // 3600:02d}:{t % 3600 // 60:02d}:{t % 60:02d}"
svc = rng.choice(svcs)
if i in err_idx:
lvl = "CRITICAL" if i == crit_i else "ERROR"
else:
lvl = "WARN" if rng.random() < 0.2 else "INFO"
has5 = i in err_idx and i != crit_i and \
(i == force5 or rng.random() < 0.4)
code = f" status={rng.choice([500, 502, 503, 504])}" if has5 else ""
lines.append(f"{ts} [{lvl}] {svc}: {rng.choice(_LOG_MSGS[lvl])}{code}")
events.append((ts, svc, lvl, has5))
state = "\n".join(lines)
qs = []
# 1) which service errored first (timestamps strictly increase)
first_svc = next(e[1] for e in events if e[2] in ("ERROR", "CRITICAL"))
opts = svcs[:]
rng.shuffle(opts)
qs.append(q_choice("first_err",
rng.choice([
"Which service logged an error first?",
"Which service was the first to report an ERROR "
"or CRITICAL line?"]),
opts, _one_hot(opts.index(first_svc), len(opts))))
# 2) did a 5xx occur before T
T = events[rng.randrange(1, n - 1)][0]
ans = any(e[3] and e[0] < T for e in events)
qs.append(q_noul("early5xx",
f"Did any HTTP 5xx response occur before "
f"{T.split('T')[1]}?", float(ans)))
# 3) error-rate bucket (exact) or severity (fuzzy)
err_events = [e for e in events if e[2] in ("ERROR", "CRITICAL")]
if rng.random() < 0.5:
frac = len(err_events) / n
levels = ["0: no error lines", "1: under a quarter of lines",
"2: a quarter to a half of lines",
"3: over half of lines"]
idx = (0 if frac == 0 else 1 if frac < 0.25
else 2 if frac <= 0.5 else 3)
qs.append(q_score("err_rate",
"What share of the log lines are ERROR or "
"CRITICAL?", levels, _one_hot(idx, 4)))
else:
sev = ["0: benign — routine noise", "1: minor — worth a look",
"2: serious — page the on-call",
"3: severe — incident response"]
ncrit = sum(1 for e in events if e[2] == "CRITICAL")
n5xx = sum(1 for e in events if e[3])
base = 1
if len(err_events) >= 3 or n5xx >= 2 or ncrit:
base = 2
if ncrit >= 2 or (ncrit and n5xx):
base = 3
qs.append(q_score("severity",
"How severe is the incident reflected in this log?",
sev, _softq(base, 4)))
return state, qs
# ---------- tables: markdown or CSV table (text state) ----------
def gen_tables():
kind = rng.choice(["sales", "weather", "servers"])
n = rng.randint(4, 6)
if kind == "sales":
cols = ["product", "units", "revenue"]
names = rng.sample(PRODUCTS, n)
rows = [[names[i], u, r] for i, u, r in
zip(range(n), rng.sample(range(5, 200), n),
rng.sample(range(100, 5000), n))]
nums = {"units": 1, "revenue": 2}
noun = "product"
elif kind == "weather":
cols = ["city", "high_c", "rain_mm"]
names = rng.sample(CITIES, n)
rows = [[names[i], h, r] for i, h, r in
zip(range(n), rng.sample(range(-5, 40), n),
rng.sample(range(0, 80), n))]
nums = {"high_c": 1, "rain_mm": 2}
noun = "city"
else:
cols = ["host", "cpu_pct", "mem_gb"]
hosts = [f"web-{i}" for i in rng.sample(range(1, 30), n)]
rows = [[hosts[i], c, m] for i, c, m in
zip(range(n), rng.sample(range(5, 99), n),
rng.sample(range(1, 128), n))]
nums = {"cpu_pct": 1, "mem_gb": 2}
noun = "host"
if rng.random() < 0.5:
state = f"{kind} report:\n" + "\n".join(
["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)] +
["| " + " | ".join(str(v) for v in r) + " |" for r in rows])
else:
state = "\n".join([",".join(cols)] +
[",".join(str(v) for v in r) for r in rows])
qs = []
# 1) argmax/argmin lookup (values distinct by construction)
f = rng.choice(list(nums))
vals = [r[nums[f]] for r in rows]
want_max = rng.random() < 0.5
correct = vals.index(max(vals) if want_max else min(vals))
qs.append(q_choice("arg",
f"Which {noun} has the "
f"{'highest' if want_max else 'lowest'} {f}?",
[str(r[0]) for r in rows], _one_hot(correct, n)))
# 2) count of rows over a threshold
f2 = rng.choice(list(nums))
v2 = [r[nums[f2]] for r in rows]
t = rng.randint(min(v2), max(v2) - 1)
c = sum(1 for v in v2 if v > t)
opts_c = _count_opts(c, n)
qs.append(q_choice("count",
f"How many {noun}s have {f2} above {t}?", opts_c,
_one_hot(opts_c.index(str(c)), len(opts_c))))
# 3) universal predicate
f3 = rng.choice(list(nums))
v3 = [r[nums[f3]] for r in rows]
m = rng.randint(min(v3), max(v3))
qs.append(q_noul("all",
f"Does every {noun} have {f3} above {m}?",
float(all(v > m for v in v3))))
return state, qs
# ---------- temporal: dates and durations (JSON state) ----------
def gen_temporal():
base = date(2024, 1, 1) + timedelta(days=rng.randint(0, 300))
if rng.random() < 0.5:
task = rng.choice(["report", "migration", "audit", "prototype",
"rollout"])
est = rng.randint(3, 30)
due = base + timedelta(days=rng.randint(3, 30))
end = base + timedelta(days=est)
state = json.dumps({"task": task, "start": base.isoformat(),
"estimate_days": est, "due": due.isoformat()})
late = end > due
slack = (due - end).days
qs = [q_noul("late",
rng.choice([f"Will the {task} miss its due date?",
f"Is the {task} going to be late?"]),
float(late))]
levels = ["0: over a week of slack", "1: up to a week of slack",
"2: finishes exactly on the due date", "3: late"]
idx = 3 if late else 2 if slack == 0 else 1 if slack <= 7 else 0
qs.append(q_score("slack",
f"How much slack does the {task} have against "
f"its due date?", levels, _one_hot(idx, 4)))
k = rng.randint(5, 25)
qs.append(q_noul("est",
f"Is the estimated effort at least {k} days?",
float(est >= k)))
return state, qs
names = rng.sample(["design", "build", "test", "deploy", "review",
"docs"], rng.randint(3, 5))
stag = rng.random() < 0.5
ms, ends = [], []
for nm, d in zip(names, rng.sample(range(3, 40), len(names))):
s = base + timedelta(days=rng.randint(0, 10) if stag else 0)
ms.append({"name": nm, "start": s.isoformat(), "days": d})
ends.append(s + timedelta(days=d))
if len(set(ends)) != len(ends):
raise ValueError("tie")
state = json.dumps({"project": rng.choice(["atlas", "boreal", "cinder"]),
"milestones": ms})
qs = [q_choice("first", "Which milestone completes first?", names,
_one_hot(ends.index(min(ends)), len(names)))]
w = rng.randint(2, 6)
min_start = min(date.fromisoformat(m["start"]) for m in ms)
qs.append(q_noul("allin",
f"Do all milestones finish within {w} weeks of the "
f"earliest start?",
float(all(e <= min_start + timedelta(weeks=w)
for e in ends))))
k = rng.randint(5, 35)
qs.append(q_noul("long",
f"Is any single milestone longer than {k} days?",
float(max(m["days"] for m in ms) > k)))
return state, qs
# ---------- numeric_compare: two metric objects (JSON state) ----------
def gen_numeric_compare():
scen = rng.choice(["models", "servers", "products"])
if scen == "models":
metrics = {"accuracy_pct": (70, 99, True),
"latency_ms": (10, 200, False),
"cost_per_1k": (1, 50, False)}
na, nb = rng.sample(["falcon-7b", "kestrel-13b", "merlin-3b",
"osprey-8b"], 2)
elif scen == "servers":
metrics = {"uptime_pct": (90, 100, True),
"load_pct": (5, 95, False),
"cost_hr": (1, 40, False)}
na, nb = rng.sample(["node-a", "node-b", "node-c"], 2)
else:
metrics = {"rating_pct": (50, 99, True),
"price": (5, 500, False),
"weight_g": (50, 2000, False)}
na, nb = rng.sample(PRODUCTS, 2)
A = {m: rng.randint(lo, hi) for m, (lo, hi, _) in metrics.items()}
B = {m: rng.randint(lo, hi) for m, (lo, hi, _) in metrics.items()}
state = json.dumps({"candidate_a": {"name": na, **A},
"candidate_b": {"name": nb, **B}})
qs = []
# 1) which candidate is better on metric m
m = rng.choice(list(metrics))
_, _, hb = metrics[m]
if A[m] == B[m]:
raise ValueError("tie")
better = na if (A[m] > B[m]) == hb else nb
d = "higher" if hb else "lower"
opts = [na, nb]
rng.shuffle(opts)
qs.append(q_choice("better",
rng.choice([
f"By {m} ({d} is better), which candidate wins?",
f"Which candidate has the better {m}? "
f"({d} is better)"]),
opts, _one_hot(opts.index(better), 2)))
# 2) ratio predicate
m2 = rng.choice(list(metrics))
r = rng.choice([1.1, 1.25, 1.5, 2.0])
qs.append(q_noul("ratio",
f"Is {na}'s {m2} more than {r}x {nb}'s?",
float(A[m2] / B[m2] > r)))
# 3) both-satisfy predicate, direction follows the metric
m3 = rng.choice(list(metrics))
lo3, hi3, hb3 = metrics[m3]
t = rng.randint(lo3, hi3)
if hb3:
ans, phr = A[m3] >= t and B[m3] >= t, f"at least {t}"
else:
ans, phr = A[m3] <= t and B[m3] <= t, f"at most {t}"
qs.append(q_noul("both",
f"Do both candidates keep {m3} {phr}?", float(ans)))
return state, qs
# ---------- nested_json: order + customer + items (JSON state) ----------
def gen_nested_json():
n = rng.randint(3, 4)
skus = rng.sample(["KB-01", "MS-02", "HD-04", "CB-07", "LT-11",
"DK-03"], n)
items = [{"sku": s, "qty": rng.randint(1, 6),
"unit_price": rng.randint(4, 120)} for s in skus]
totals = [it["qty"] * it["unit_price"] for it in items]
if len(set(totals)) != n:
raise ValueError("tie")
country = rng.choice(COUNTRIES)
whitelist = rng.sample(COUNTRIES, rng.randint(3, 5))
order = {"order_id": f"ORD-{rng.randint(1000, 9999)}",
"customer": {"name": rng.choice(FIRST), "country": country,
"vip": rng.random() < 0.3},
"items": items,
"shipping": {"whitelist": whitelist,
"express": rng.random() < 0.5}}
state = json.dumps(order, separators=(",", ":"))
tot = sum(totals)
t = rng.randint(int(tot * 0.5), int(tot * 1.5) + 1)
qs = [q_choice("driver",
rng.choice([
"Which line item contributes most to the order "
"total?",
"Which item drives the largest share of the total?"]),
skus, _one_hot(totals.index(max(totals)), n)),
q_noul("ship",
"Is the customer's country on the shipping whitelist?",
float(country in whitelist)),
q_noul("total", f"Does the order total exceed ${t}?",
float(tot > t))]
return state, qs
# ---------- mixed_state: JSON array mixing dicts and strings ----------
def gen_mixed_state():
mnames = rng.sample(["cpu", "mem", "disk", "net", "queue"],
rng.randint(2, 3))
arr = [{"type": "metric", "name": m, "value": rng.randint(1, 99)}
for m in mnames]
maint = rng.random() < 0.5
notes = rng.sample(["note: deploy v2.1 shipped", "note: cache flushed",
"note: on-call rotation updated",
"note: firmware update pending",
"note: backup completed"], rng.randint(1, 2))
if maint:
notes.append("note: nightly maintenance at 03:00 UTC")
lvl = rng.choice(["warn", "critical"]) if rng.random() < 0.5 else None
if lvl:
arr.append({"type": "alert", "name": rng.choice(mnames),
"level": lvl})
arr += notes
rng.shuffle(arr)
state = json.dumps(arr, separators=(",", ":"))
qs = []
# 1) count metric records
c = sum(1 for e in arr if isinstance(e, dict)
and e.get("type") == "metric")
opts_c = _count_opts(c, len(arr))
qs.append(q_choice("n_metric",
"How many metric records are in the payload?",
opts_c,
_one_hot(opts_c.index(str(c)), len(opts_c))))
# 2) string-entry predicate
qs.append(q_noul("maint", "Does any entry mention maintenance?",
float(any(isinstance(e, str) and "maintenance" in e
for e in arr))))
# 3) metric value lookup
m = rng.choice(mnames)
true_v = next(e["value"] for e in arr
if isinstance(e, dict) and e.get("name") == m)
cands = {true_v}
while len(cands) < 4:
cands.add(rng.randint(1, 99))
opts_v = [str(x) for x in cands]
rng.shuffle(opts_v)
qs.append(q_choice("lookup",
f"What value does the metric '{m}' report?",
opts_v,
_one_hot(opts_v.index(str(true_v)), 4)))
# 4) alert-level predicate
qs.append(q_noul("alert",
"Is there an alert with level 'critical'?",
float(lvl == "critical")))
return state, qs
FAMILIES = {
"json_records": gen_json_records,
"log_lines": gen_log_lines,
"tables": gen_tables,
"temporal": gen_temporal,
"numeric_compare": gen_numeric_compare,
"nested_json": gen_nested_json,
"mixed_state": gen_mixed_state,
}
WEIGHTS = {
"json_records": 0.18, "log_lines": 0.14, "tables": 0.14,
"temporal": 0.14, "numeric_compare": 0.13, "nested_json": 0.14,
"mixed_state": 0.13,
}
def make_rows(n, seed):
return generate(FAMILIES, WEIGHTS, n, seed, rng)
if __name__ == "__main__":
rows = make_rows(10, 0)
for r in rows[:3]:
validate_row(r)
print(r["id"], "|", r["state"][:100])
print(f"{len(rows)} rows OK")