alea-runs / alea /gen_jb2.py
Akahsizrr's picture
Upload alea/gen_jb2.py with huggingface_hub
6626a06 verified
Raw History Blame
16.1 kB
"""gen_jb2: deeper synthetic — real-looking multi-section policy docs.
The hard tier of JevBench is ~1-4k token documents with interacting
clauses: base terms + endorsements that override + exception chains +
effective dates. gen_jb.py was too shallow (one clause). These generators
emit full policy/regulation/contract docs with a concrete claim and a
correct outcome derived from the controlling clause hierarchy — plus
rubric-judging and table-reasoning families.
"""
import argparse
import json
import random
rng = random.Random(9090)
def choice(state, instr, crit, correct_key, family):
keys = list(crit.keys())
tgt = [0.0] * len(keys)
tgt[keys.index(correct_key)] = 1.0
return {"state": state,
"questions": {"q0": {"type": "choice", "instructions": instr,
"criteria": crit}},
"targets": {"q0": tgt}, "family": family}
def noul(state, instr, val, family):
return {"state": state,
"questions": {"q0": {"type": "noul", "instructions": instr}},
"targets": {"q0": float(val)}, "family": family}
# ---------- deep policy docs ----------
INSURANCE_PERILS = {
"water_damage": "Section 3.1 covers sudden and accidental water damage "
"originating within the premises.",
"flood": "Section 3.2 excludes damage caused by flood, defined as "
"surface water entering from outside the premises.",
"wind": "Section 3.3 excludes wind damage for properties located in "
"designated coastal zones (Schedule C).",
"theft": "Section 3.4 covers theft up to the sub-limit stated in the "
"Declarations, subject to Section 4 exclusions.",
"fire": "Section 3.5 covers fire damage in full, except as limited by "
"Endorsement E-2 where applicable.",
}
ENDORSEMENTS = {
"E-1": ("Endorsement E-1 (effective {eff}): notwithstanding Section "
"3.2, flood damage IS covered for properties that have "
"installed a certified sump-pump system."),
"E-2": ("Endorsement E-2 (effective {eff}): fire damage caused by "
"kitchen appliances is capped at ${cap} per occurrence."),
"E-3": ("Endorsement E-3 (effective {eff}): the wind exclusion in "
"Section 3.3 is waived for properties certified to windstorm "
"standard W-{w}."),
"E-4": ("Endorsement E-4 (effective {eff}): theft coverage requires "
"that the premises be equipped with a monitored alarm system."),
}
MISREP = ("Section 4.1: coverage is void if the insured materially "
"misrepresented the risk on the application.")
LATE = ("Section 4.2: claims must be reported within {days} days of the "
"loss; later reports are barred.")
DEDUCT = ("Section 4.3: a deductible of ${ded} applies to every covered "
"claim.")
def gen_policy_deep(n):
"""Long policy doc + claim -> adjudication outcome."""
out = []
for _ in range(n):
# build a doc: base coverages + exclusions + 1-2 endorsements
peril = rng.choice(list(INSURANCE_PERILS))
end_ids = rng.sample(list(ENDORSEMENTS), rng.randint(1, 2))
days = rng.choice([30, 45, 60])
ded = rng.choice([250, 500, 1000])
cap = rng.choice([5000, 10000])
wind = rng.choice([1, 2, 3])
eff_years = {e: rng.choice([2023, 2025]) for e in end_ids}
secs = ["POLICY — PROPERTY PROTECTION FORM PP-" +
str(rng.randint(100, 999)),
"Effective period: 01 Jan 2024 to 31 Dec 2026.",
"SECTION 2 — DECLARATIONS: insured premises; policy "
"deductible per Section 4.3.",
"SECTION 3 — COVERAGES AND EXCLUSIONS:"]
secs += [" " + t for t in INSURANCE_PERILS.values()]
secs += ["SECTION 4 — GENERAL CONDITIONS:",
" " + MISREP,
" " + LATE.format(days=days),
" " + DEDUCT.format(ded=ded),
"SECTION 5 — ENDORSEMENTS:"]
secs += [" " + ENDORSEMENTS[e].format(
eff="%d-01-01" % eff_years[e], cap=cap, w=wind)
for e in end_ids]
doc = "\n".join(secs)
# the claim: pick a controlling fact pattern
has_sump = rng.random() < 0.5
has_alarm = rng.random() < 0.5
coastal = rng.random() < 0.5
cert_w = rng.random() < 0.5
reported_late = rng.random() < 0.4
misrep = rng.random() < 0.15
kitchen_fire = rng.random() < 0.5
facts = [f"Loss date: {rng.choice(['Mar', 'Jun', 'Sep'])} "
f"{rng.randint(1,28)}, 2025.",
f"Peril: {peril.replace('_', ' ')}."]
if peril == "flood":
facts.append("Property has %sa certified sump-pump system."
% ("" if has_sump else "no "))
if peril == "wind":
facts.append("Property is %sin a Schedule C coastal zone."
% ("" if coastal else "not "))
facts.append("Property is %scertified to W-%d."
% ("" if cert_w else "not ", wind))
if peril == "theft":
facts.append("Premises %shave a monitored alarm system."
% ("" if has_alarm else "do not "))
if peril == "fire":
facts.append("Fire originated %s." %
("in a kitchen appliance" if kitchen_fire
else "in the electrical panel"))
if reported_late:
facts.append("Claim was reported %d days after the loss."
% (days + rng.randint(5, 30)))
else:
facts.append("Claim was reported %d days after the loss."
% rng.randint(3, days - 2))
if misrep:
facts.append("Investigation found the application understated "
"the property's prior loss history.")
# adjudicate
if misrep:
correct = "deny_misrep"
elif reported_late:
correct = "deny_late"
elif peril == "flood":
correct = ("pay" if (has_sump and "E-1" in end_ids)
else "deny_excluded")
elif peril == "wind":
if coastal and not (cert_w and "E-3" in end_ids):
correct = "deny_excluded"
else:
correct = "pay"
elif peril == "theft":
correct = ("pay" if (has_alarm or "E-4" not in end_ids)
else "deny_condition")
elif peril == "fire":
correct = ("pay_capped" if (kitchen_fire and "E-2" in end_ids)
else "pay")
else: # water_damage
correct = "pay"
crit = {
"pay": "Pay the claim in full less deductible",
"pay_capped": "Pay subject to the endorsement cap",
"deny_excluded": "Deny: peril is excluded",
"deny_condition": "Deny: a coverage condition was not met",
"deny_late": "Deny: claim reported after the deadline",
"deny_misrep": "Deny: material misrepresentation voids coverage",
}
st = doc + "\n\nCLAIM:\n" + "\n".join(facts)
out.append(choice(st, "Apply the policy to the claim. Endorsements "
"modify sections; conditions in Section 4 can "
"override coverage.", crit, correct,
"jb2_policy_deep"))
return out
# ---------- rubric judging ----------
RUBRIC_AXES = [
("correctness", "the answer states the correct value/conclusion"),
("grounding", "every claim is supported by the provided document"),
("completeness", "all parts of the question are addressed"),
("format", "the answer follows the required output format"),
]
def gen_rubric(n):
"""(doc, question, candidate answer, rubric) -> verdict."""
out = []
docs = [
("Policy excerpt: 'Returns accepted within 30 days of purchase "
"for unused items in original packaging.'",
"Can a customer return an item 45 days after purchase?",
{"good": "No. Returns are only accepted within 30 days.",
"bad": ["Yes, if the item is unused.",
"The policy does not address returns.",
"Yes, returns are always accepted."]},
"correctness"),
("Spec excerpt: 'The API rate limit is 120 requests per minute per "
"key; bursts above the limit receive HTTP 429.'",
"What happens when a key exceeds 120 req/min?",
{"good": "Requests receive HTTP 429 responses.",
"bad": ["The key is permanently banned.",
"Nothing happens; limits are advisory.",
"Requests are queued for later."]},
"correctness"),
("Record: 'Invoice #4471, amount $2,340, status: PAID, paid "
"2026-02-14.'",
"What is the status of invoice 4471 and when was it settled?",
{"good": "It is paid; settled on 2026-02-14.",
"bad": ["It is pending.",
"It is paid on 2024-02-14.",
"It is paid; the date is not recorded."]},
"correctness"),
]
for _ in range(n):
doc, q, ans, axis = rng.choice(docs)
good = rng.random() < 0.5
a = ans["good"] if good else rng.choice(ans["bad"])
st = ("SOURCE DOCUMENT:\n%s\n\nQUESTION:\n%s\n\nCANDIDATE ANSWER:\n%s"
"\n\nRUBRIC — %s: %s." % (doc, q, a, axis,
dict(RUBRIC_AXES)[axis]))
out.append(choice(st, "Judge the candidate answer against the "
"rubric.", {"pass": "Answer satisfies the rubric",
"fail": "Answer fails the rubric"},
"pass" if good else "fail", "jb2_rubric"))
return out
# ---------- table reasoning ----------
def gen_table(n):
out = []
for _ in range(n):
rows = []
n_dep = rng.randint(3, 6)
deps = rng.sample(["Eng", "Sales", "Ops", "Legal", "Finance",
"Support"], n_dep)
for d in deps:
rows.append({"dept": d, "q1": rng.randint(10, 400),
"q2": rng.randint(10, 400),
"q3": rng.randint(10, 400)})
kind = rng.choice(["argmax", "sum", "diff", "threshold"])
hdr = "Quarterly spend ($k):\n" + "\n".join(
" %s: Q1=%d Q2=%d Q3=%d" % (r["dept"], r["q1"], r["q2"],
r["q3"]) for r in rows)
if kind == "argmax":
col = rng.choice(["q1", "q2", "q3"])
best = max(rows, key=lambda r: r[col])
st = hdr + "\n\nWhich department had the highest %s spend?" % col
opts = [r["dept"] for r in rows]
ci = opts.index(best["dept"])
elif kind == "sum":
col = rng.choice(["q1", "q2", "q3"])
tot = sum(r[col] for r in rows)
st = hdr + "\n\nWhat is the total %s spend across departments?" % col
ds_ = [tot + rng.choice([-1, 1]) * rng.randint(5, 60)
for _ in range(3)]
opts = [tot] + ds_
ci = 0
elif kind == "diff":
a, b = rng.sample(rows, 2)
col = rng.choice(["q1", "q2", "q3"])
d = a[col] - b[col]
st = (hdr + "\n\nWhat is %s minus %s in %s?" %
(a["dept"], b["dept"], col))
ds_ = [d + rng.choice([-1, 1]) * rng.randint(3, 50)
for _ in range(3)]
opts = [d] + ds_
ci = 0
else:
th = rng.randint(50, 350)
col = rng.choice(["q1", "q2", "q3"])
over = [r["dept"] for r in rows if r[col] > th]
st = (hdr + "\n\nHow many departments exceeded %dk in %s?"
% (th, col))
opts = [len(over)] + [len(over) + d for d in (-1, 1, 2)]
ci = 0
order = list(range(len(opts))); rng.shuffle(order)
if isinstance(opts[0], str):
shuffled = [opts[j] for j in order]
correct = "opt_%d" % order.index(ci)
else:
shuffled = [str(opts[j]) for j in order]
correct = "opt_%d" % order.index(ci)
crit = {"opt_%d" % i: shuffled[i] for i in range(len(shuffled))}
out.append(choice(st, "Read the table and answer exactly.", crit,
correct, "jb2_table"))
return out
# ---------- multi-constraint routing ----------
def gen_routing(n):
"""Route request to queue given a multi-rule routing policy."""
out = []
for _ in range(n):
rules = []
queues = ["billing", "technical", "legal", "sales", "vip"]
pol = []
# random priority chain: if-else rules
feats = rng.sample(
["amount > $%d" % rng.choice([500, 1000, 5000]),
"customer tier = VIP",
"topic mentions '%s'" % rng.choice(["lawsuit", "outage",
"refund", "discount"]),
"region = %s" % rng.choice(["EU", "APAC", "LATAM"]),
"channel = %s" % rng.choice(["phone", "email", "chat"])],
3)
q_assigned = rng.sample(queues, 3)
for f, q in zip(feats, q_assigned):
pol.append("IF %s THEN route to %s." % (f, q))
pol.append("OTHERWISE route to general.")
ticket_feats = []
# decide which rule fires (first match)
fire = rng.randint(0, 3)
correct = "general"
for i, f in enumerate(feats):
applies = (i <= fire) if fire < 3 else False
if i == fire:
correct = q_assigned[i]
applies = True
if applies:
if "amount" in f:
v = int(f.split("$")[1]) + rng.randint(1, 2000)
ticket_feats.append("amount $%d" % v)
elif "tier" in f:
ticket_feats.append("customer tier VIP")
elif "mentions" in f:
ticket_feats.append("mentions '%s'" %
f.split("'")[1])
elif "region" in f:
ticket_feats.append("region %s" % f.split("= ")[1])
elif "channel" in f:
ticket_feats.append("channel %s" % f.split("= ")[1])
else:
# ensure rule does NOT match
if "amount" in f:
ticket_feats.append("amount $%d" % rng.randint(1, 400))
elif "tier" in f:
ticket_feats.append("customer tier standard")
elif "mentions" in f:
ticket_feats.append("mentions 'upgrade'")
elif "region" in f:
ticket_feats.append("region NA")
elif "channel" in f:
ticket_feats.append("channel web")
st = ("ROUTING POLICY (first match wins):\n%s\n\nTICKET:\n%s"
% ("\n".join(pol), "\n".join(ticket_feats)))
crit = {q: "Route to the %s queue" % q for q in
queues + ["general"]}
out.append(choice(st, "Apply the routing rules in order; the first "
"matching rule wins.", crit, correct,
"jb2_routing"))
return out
GENS = {
"policy_deep": gen_policy_deep,
"rubric": gen_rubric,
"table": gen_table,
"routing": gen_routing,
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="data/jb2.jsonl")
ap.add_argument("--per", type=int, default=5000)
args = ap.parse_args()
rows = []
for name, fn in GENS.items():
got = fn(args.per)
print(name, len(got))
rows += got
rng.shuffle(rows)
with open(args.out, "w") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print("TOTAL", len(rows), "->", args.out)
if __name__ == "__main__":
main()