"""Frozen label-picker request construction, copied from the original test harness. No API credentials, dataset loading, scoring or external API calls. Source SHA256: dd51049ecb5d809a352120dbcf4ad0a2020e04295acc5c90534fc0c115d9aa53 """ import random,re,time from label_facts_lib import facts_text MAXOPT=255 MODEL="" DETAILED = ("`question` is a user's question about one figure in the annual report (Form 10-K) of `company` for fiscal year `fiscal_year`. Each option is the name of one labelled " "figure from that report (a financial-statement label written out in words). Which option is the figure the question asks for? Choose the label whose reported amount " "would be the answer. Read what makes the figure specific and match it: current versus noncurrent, gross versus net, a change during the year versus a balance at year " "end, cash paid versus an expense or an amount owed, the year an amount falls due, the part versus the total.") MINIMAL = "Which of these labelled figures from the annual report is the one the `question` asks for?" ANY = ("`labels` lists labelled figures from the annual report of `company` for fiscal year `fiscal_year`. Is the exact figure that `question` asks for one of the figures in `labels`? " "Answer no if `labels` holds only related, broader or narrower figures.") FITS = ("Is the labelled figure named \"{label}\", from the annual report of `company` for fiscal year `fiscal_year`, exactly the figure that `question` asks for? " "Answer no if it is only a related, broader or narrower figure.") NONE_NAME = "none of these" NONE_DESC = ("None of the listed labels is the figure the question asks for (the report does not show that figure under any of these labels, or it would have " "to be calculated from other figures).") def money(v): return ("-" if v < 0 else "") + f"${abs(v):,.0f}" def options_for(i, setup): """[(label text, leads to the right number, amount, concept local name)] in the order sent.""" m = META[i]; base = setup.split("+")[0]; mods = setup.split("+")[1:] if base in ("s5", "s10", "n10"): k = 5 if base == "s5" else 10 loc = {t: l for t, l, _ in cands_of(i)} top = [t for t in PICKS[i]["forms"]["phrase"]["top"][:k] if t[2] is not None] rows = [(t[0], bool(t[4]), t[2], loc.get(t[0])) for t in top] random.Random(i).shuffle(rows) # for five options this is the order the 2B writer saw elif re.fullmatch(r"re\d+", base): # second look at the first five (re5; re8, re10: eight, ten) of the full-list answer (TypeSafe's two-step recipe) first = full_result(i, two="two" in mods) # +two: the five come from both option orders of the first pass info = {t: (l, vals) for t, l, vals in cands_of(i)} names = [t for t, _ in sorted(first["probs"].items(), key=lambda kv: -kv[1])[:int(base[2:])]] rows = [(t, (info[t][0] == m["local"]) or any(abs(v - m["value"]) < 0.5 for v in info[t][1]), (info[t][1][0] if info[t][1] else None), info[t][0]) for t in names] random.Random("re" + i).shuffle(rows) else: rows = [(t, (l == m["local"]) or any(abs(v - m["value"]) < 0.5 for v in vals), (vals[0] if vals else None), l) for t, l, vals in cands_of(i)] if "ord" not in mods: # +ord: the labels in the order of the filing itself (statements first, then the notes); default: shuffled random.Random("full" + i).shuffle(rows) if "rev" in mods: rows = rows[::-1] return rows def state_for(i, setup, labels=None): m = META[i] st = {"company": m["company"], "fiscal_year": m["fy"], "question": m["question"]} if "phr" in setup.split("+")[1:]: st["figure_asked_for"] = m["phrase"] if labels is not None: st["labels"] = labels return st _NUM = {"One": 1, "First": 1, "Two": 2, "Second": 2, "Three": 3, "Third": 3, "Four": 4, "Fourth": 4, "Five": 5, "Fifth": 5} _ORD = {1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth"} def year_note(local, fy): """+yr: the fiscal year a payment-schedule label covers ("...InYearTwo" in a fiscal 2023 report covers fiscal 2025), so that the year offset need not be worked out from the question's calendar year. None for labels that are not schedule labels.""" if not local or not fy: return None m = re.search(r"After(?:Year)?(Four|Fourth|Five|Fifth)(?:Year|Anniversary)?(?![a-z])", local) if m: return f"Covers the years after fiscal {fy + _NUM[m.group(1)]} (the report is for fiscal {fy})." if re.search(r"(NextTwelveMonths|NextRollingTwelveMonths|NextFiscalYear|FirstAnniversary|InYearOne(?![a-z])|RollingYearOne(?![a-z]))", local): return f"Covers fiscal {fy + 1}, the first year after the report's fiscal {fy}." m = re.search(r"(?:InYear|RollingYear|DueYear|Year)(Two|Three|Four|Five)(?![a-z])|(Second|Third|Fourth|Fifth)(?:Year|Anniversary)(?![a-z])", local) if m: n = _NUM[m.group(1) or m.group(2)] if local[m.end():].startswith(("AndThereafter", "AndAfter")): return f"Covers fiscal {fy + n} and all later years (the report is for fiscal {fy})." return f"Covers fiscal {fy + n}, the {_ORD[n]} year after the report's fiscal {fy}." return None def choice_q(rows, setup, i=None): mods = setup.split("+")[1:] caps = captions(i) if ("cap" in mods and i is not None) else {} fx = facts(i) if ("st" in mods and i is not None) else {} def describe(t, a, local): parts = ([definition(local)] if ("def" in mods and definition(local)) else []) + ([f"Reported amount {money(a)}."] if ("amt" in mods and a is not None) else []) short = [c for c in caps.get(t, []) if len(c) <= 120][:2] # table rows; long sentences are mostly chance matches of the amount if "cap" in mods and short: parts.append("Printed in the report as: " + " / ".join(f'"{c}"' for c in short)) if "st" in mods and fx.get(t): parts.append(facts_text(fx[t])) if "yr" in mods and i is not None: parts.append(year_note(local, META[i]["fy"])) return " ".join(p for p in parts if p) or None crit = {t: describe(t, a, l) for t, _, a, l in rows} if "none" in mods: # +none: the extra LAST option the v11 judges are trained with (judge_rows_v11.py --none); crit[NONE_NAME] = NONE_DESC # it is never the test answer: its probability is set aside and the labels' renormalised return {"type": "choice", "instructions": MINIMAL if "min" in mods else DETAILED, "criteria": crit} def one(i, setup): base = setup.split("+")[0] rows = options_for(i, setup) rec = {"id": i, "options": [[t, r] for t, r, _, _ in rows], "in_list": any(r for _, r, _, _ in rows)} if base == "n10": qs = {f"fit_{k}": {"type": "noul", "instructions": FITS.format(label=t)} for k, (t, _, _, _) in enumerate(rows)} j = call({"model": MODEL, "state": state_for(i, setup), "questions": qs}) if "error" in j: return {**rec, "error": j["error"]} p = [j["answers"][f"fit_{k}"]["noul"] for k in range(len(rows))] best = max(range(len(rows)), key=lambda k: p[k]) return {**rec, "choice": rows[best][0], "p": p[best], "probs": p, "tokens": j["usage"]["input_tokens"], "seconds": j["_seconds"], "model": j.get("model")} if re.fullmatch(r"u\d+", base): # three steps: the list in parts of at most N names (first five of each part), a names-only size_max = int(base[1:]); n_parts = -(-len(rows) // size_max); size = -(-len(rows) // n_parts); tokens = 0; secs = 0; short = [] # choice among those for c0 in range(0, len(rows), size): # survivors (first five), chunk = rows[c0:c0 + size] # then the second look j = call({"model": MODEL, "state": state_for(i, base), "questions": {"label": choice_q(chunk, base, i)}}) # with descriptions if "error" in j: return {**rec, "error": j["error"]} pr = j["answers"]["label"]["probabilities"]; tokens += j["usage"]["input_tokens"]; secs += j["_seconds"] short += sorted(chunk, key=lambda t: -pr.get(t[0], 0))[:5] surv = list(short) if n_parts > 1: random.Random("u" + i).shuffle(short) j = call({"model": MODEL, "state": state_for(i, base), "questions": {"label": choice_q(short, base, i)}}) if "error" in j: return {**rec, "error": j["error"]} pr = j["answers"]["label"]["probabilities"]; tokens += j["usage"]["input_tokens"]; secs += j["_seconds"] five = sorted(short, key=lambda t: -pr.get(t[0], 0))[:5] else: five = short[:5] random.Random("u5" + i).shuffle(five) if "rev" in setup.split("+")[1:]: five = five[::-1] rec["second_stage"] = [[t, r] for t, r, _, _ in five] j = call({"model": MODEL, "state": state_for(i, setup, [t for t, _, _, _ in five]), "questions": {"label": choice_q(five, setup, i), "any_fits": {"type": "noul", "instructions": ANY}}}, final=True) if "error" in j: return {**rec, "error": j["error"]} a = j["answers"]["label"] return {**rec, "choice": a["choice"], "p": a["probabilities"].get(a["choice"]), "confidence": a.get("confidence"), "probs": a["probabilities"], "any_fits": j["answers"]["any_fits"]["noul"], "tokens": tokens + j["usage"]["input_tokens"], "seconds": round(secs + j["_seconds"], 3), "model": j.get("model"), "requests": n_parts + 2, "n_options": len(rows), "in_survivors": any(r for _, r, _, _ in surv), "in_final": any(r for _, r, _, _ in five), "options": [o for o in rec["options"] if o[1] or o[0] == a["choice"]]} if re.fullmatch(r"d\d+", base): # description tournament: every label in groups of N, each shown with its descriptions G = int(base[1:]); keep = 2; tokens = 0; secs = 0; nreq = 0; cur = list(rows); rr = random.Random("d" + i) # (the mods), the first two of while len(cur) > 10: # each group go on, one request groups = [cur[k:k + G] for k in range(0, len(cur), G)] # per round, until at most ten qs = {f"g{k}": choice_q(g, base + "+" + "+".join(setup.split("+")[1:]), i) for k, g in enumerate(groups) if len(g) > 1} # remain; then the j = call({"model": MODEL, "state": state_for(i, base), "questions": qs}) # first five of those, then the if "error" in j: # second look as in re5 return {**rec, "error": j["error"]} tokens += j["usage"]["input_tokens"]; secs += j["_seconds"]; nreq += 1 nxt = [] for k, g in enumerate(groups): if len(g) == 1: nxt += g; continue pr = j["answers"][f"g{k}"]["probabilities"] nxt += sorted(g, key=lambda t: -pr.get(t[0], 0))[:keep] rr.shuffle(nxt); cur = nxt surv = list(cur) if len(cur) > 5: j = call({"model": MODEL, "state": state_for(i, base), "questions": {"label": choice_q(cur, setup, i)}}) if "error" in j: return {**rec, "error": j["error"]} pr = j["answers"]["label"]["probabilities"]; tokens += j["usage"]["input_tokens"]; secs += j["_seconds"]; nreq += 1 five = sorted(cur, key=lambda t: -pr.get(t[0], 0))[:5] else: five = cur rr.shuffle(five) rec["second_stage"] = [[t, r] for t, r, _, _ in five] nolab = "nolab" in setup.split("+")[1:] # +nolab: the last look exactly as the judges are trained (no label list in the state, one question) qs5 = {"label": choice_q(five, setup, i)} if not nolab: qs5["any_fits"] = {"type": "noul", "instructions": ANY} j = call({"model": MODEL, "state": state_for(i, setup, None if nolab else [t for t, _, _, _ in five]), "questions": qs5}, final=True) if "error" in j: return {**rec, "error": j["error"]} a = j["answers"]["label"] if "none" in setup.split("+")[1:]: # set the extra option aside (it is never the answer on a test) pr5 = dict(a["probabilities"]); pr5.pop(NONE_NAME, None); z = sum(pr5.values()) or 1.0 a = {**a, "probabilities": {t: v / z for t, v in pr5.items()}}; a["choice"] = max(a["probabilities"], key=a["probabilities"].get) return {**rec, "choice": a["choice"], "p": a["probabilities"].get(a["choice"]), "confidence": a.get("confidence"), "probs": a["probabilities"], "any_fits": (j["answers"].get("any_fits") or {}).get("noul"), "tokens": tokens + j["usage"]["input_tokens"], "seconds": round(secs + j["_seconds"], 3), "model": j.get("model"), "requests": nreq + 1, "n_options": len(rows), "in_survivors": any(r for _, r, _, _ in surv), "in_final": any(r for _, r, _, _ in five), "options": [o for o in rec["options"] if o[1] or o[0] == a["choice"]]} if re.fullmatch(r"t\d+", base): # knock-out: the list in parts of at most N names, the first five of each part, then one size_max = int(base[1:]); n_parts = -(-len(rows) // size_max); size = -(-len(rows) // n_parts); tokens = 0; secs = 0; short = [] # choice among them with descriptions for c0 in range(0, len(rows), size): chunk = rows[c0:c0 + size] j = call({"model": MODEL, "state": state_for(i, base), "questions": {"label": choice_q(chunk, base, i)}}) if "error" in j: return {**rec, "error": j["error"]} pr = j["answers"]["label"]["probabilities"]; tokens += j["usage"]["input_tokens"]; secs += j["_seconds"] short += sorted(chunk, key=lambda t: -pr.get(t[0], 0))[:5] random.Random("t" + i).shuffle(short) if "rev" in setup.split("+")[1:]: short = short[::-1] rec["second_stage"] = [[t, r] for t, r, _, _ in short] j = call({"model": MODEL, "state": state_for(i, setup, [t for t, _, _, _ in short]), "questions": {"label": choice_q(short, setup, i), "any_fits": {"type": "noul", "instructions": ANY}}}) if "error" in j: return {**rec, "error": j["error"]} a = j["answers"]["label"] return {**rec, "choice": a["choice"], "p": a["probabilities"].get(a["choice"]), "confidence": a.get("confidence"), "probs": dict(sorted(a["probabilities"].items(), key=lambda kv: -kv[1])[:10]), "any_fits": j["answers"]["any_fits"]["noul"], "tokens": tokens + j["usage"]["input_tokens"], "seconds": round(secs + j["_seconds"], 3), "model": j.get("model"), "requests": n_parts + 1, "n_options": len(rows), "in_final": any(r for _, r, _, _ in short), "options": [o for o in rec["options"] if o[1] or o[0] == a["choice"]]} if len(rows) > MAXOPT: # split the list, then a second Choice among the first few of each part n_parts = -(-len(rows) // MAXOPT); size = -(-len(rows) // n_parts); keep = max(1, min(5, MAXOPT // n_parts)); tokens = 0; secs = 0; short = [] for c0 in range(0, len(rows), size): chunk = rows[c0:c0 + size] j = call({"model": MODEL, "state": state_for(i, setup), "questions": {"label": choice_q(chunk, setup, i)}}) if "error" in j: return {**rec, "error": j["error"]} pr = j["answers"]["label"]["probabilities"]; tokens += j["usage"]["input_tokens"]; secs += j["_seconds"] short += sorted(chunk, key=lambda t: -pr.get(t[0], 0))[:keep] rows2 = short; rec["second_stage"] = [[t, r] for t, r, _, _ in rows2] j = call({"model": MODEL, "state": state_for(i, setup, [t for t, _, _, _ in rows2]), "questions": {"label": choice_q(rows2, setup, i), "any_fits": {"type": "noul", "instructions": ANY}}}) if "error" in j: return {**rec, "error": j["error"]} a = j["answers"]["label"] return {**rec, "choice": a["choice"], "p": a["probabilities"].get(a["choice"]), "confidence": a.get("confidence"), "probs": a["probabilities"], "any_fits": j["answers"]["any_fits"]["noul"], "tokens": tokens + j["usage"]["input_tokens"], "seconds": round(secs + j["_seconds"], 3), "model": j.get("model"), "requests": n_parts + 1, "n_options": len(rows), "options": [o for o in rec["options"] if o[1] or o[0] == a["choice"]]} qs = {"label": choice_q(rows, setup, i)} with_any = (base in ("s5", "s10") or base.startswith("re")) and "nolab" not in setup.split("+")[1:] # +nolab: the request is exactly what the judges if with_any: # are trained on (no label list in the state, one question) qs["any_fits"] = {"type": "noul", "instructions": ANY} rep = "rep" in setup.split("+")[1:] # +rep: the whole label list also goes into the state, before the options (prompt repetition: j = call({"model": MODEL, "state": state_for(i, setup, [t for t, _, _, _ in rows] if (with_any or rep) else None), "questions": qs}) # a causal model if "error" in j: # then sees every label while return {**rec, "error": j["error"]} # reading each option) a = j["answers"]["label"] p_none = None if "none" in setup.split("+")[1:]: # set the extra option aside: the pick is the best LABEL, probabilities renormalised over the labels pr = dict(a["probabilities"]); p_none = pr.pop(NONE_NAME, 0.0); z = sum(pr.values()) or 1.0 pr = {t: v / z for t, v in pr.items()} a = {**a, "probabilities": pr, "choice": max(pr, key=pr.get)} out = {**rec, "choice": a["choice"], "p": a["probabilities"].get(a["choice"]), "confidence": a.get("confidence"), "tokens": j["usage"]["input_tokens"], "seconds": j["_seconds"], "model": j.get("model")} if p_none is not None: out["p_none"] = p_none if len(rows) > 12: out["n_options"] = len(rows); out["options"] = [o for o in rec["options"] if o[1] or o[0] == a["choice"]] out["probs"] = a["probabilities"] if len(rows) <= 12 else dict(sorted(a["probabilities"].items(), key=lambda kv: -kv[1])[:10]) if with_any: out["any_fits"] = j["answers"]["any_fits"]["noul"] return out