6ff8f34666af0f9d72d40cf40cee5c98ad090dc0 / bench/tasks/needle.py · 14234 bytes · raw
"""Needle-in-a-haystack instrument, built to rank quants.
* Items are (depth, position, seed, variant); item_id = "ndl-" + sha1 of those four, so ids are
stable across --depths order, --positions subsets and lanes, and independent of --cpt.
Positions come from the fixed POSITION_GRID.
* Variants
plain one needle: "the access code for the <place> is CODE".
decoy an OLD code for the SAME place, stated as rotated out, plus the CURRENT code
elsewhere (decoy before or after the current one, order varied by seed).
The question asks for the current code.
multikey K=5 places with codes at the five grid positions; ask for the one at `position`.
* Scoring: take every `[A-Z]+-\\d+` token in the answer *content* (never the reasoning).
correct iff the gold code is present and no decoy / other-key code is present.
* Depth: --depths in tokens, built with a chars-per-token estimate (--cpt, default 4.4); the
server-reported prompt_tokens is recorded next to the estimate, so a lane with a different
tokenizer is visible instead of silently mislabeled.
* Speed: llama-server lanes send override={"cache_prompt": False} and the row records
cached_tokens; prefill speed is averaged over uncached rows only.
"""
import argparse
import hashlib
import json
import random
import re
import sys
from bench.core import client, results, stats
INSTRUMENT = "needle"
GEN_VERSION = "2"
DEFAULT_MAX_TOKENS = 8192 # instrument default; the lane's max_tokens wins
DEFAULT_TEMPERATURE = 0.0 # likewise (lane wins)
DEFAULT_CPT = 4.4
DEPTH_GRID = [1000, 4000, 16000, 32000, 64000]
POSITION_GRID = [0.1, 0.3, 0.5, 0.7, 0.9]
DEFAULT_POSITIONS = [0.1, 0.5, 0.9]
VARIANTS = ["plain", "decoy", "multikey"]
MULTIKEY_K = len(POSITION_GRID)
CODE_RE = re.compile(r"[A-Z]+-\d+")
PLACES = ["north stairwell", "server room", "loading dock", "rooftop hatch", "maintenance office",
"freight elevator", "parking garage level two", "electrical closet", "boiler room",
"west fire exit", "records archive", "cold storage vault"]
CODE_WORDS = ["EMERALD", "COPPER", "GRANITE", "LANTERN", "HARBOR", "MERIDIAN", "SAPPHIRE",
"THISTLE", "OBSIDIAN", "FALCON", "JUNIPER", "QUARTZ", "ZEPHYR", "BASALT"]
# Filler: neutral office-log prose built from templates x slots (more varied than a fixed
# sentence pool, so the haystack is not trivially self-similar). No digit-bearing uppercase
# tokens may appear here — the scorer would read them as codes (checked by `validate`).
_DEPTS = ["facilities", "procurement", "the finance office", "reception", "the warehouse team",
"the safety committee", "IT support", "the landscaping crew", "human resources",
"the print room", "the mailroom", "the records team"]
_THINGS = ["the heating schedule", "the vendor terms", "the expense policy", "the courier log",
"the generator test", "the patch window", "the seasonal pruning", "the slotting plan",
"the visitor badges", "the printer fleet", "the supply order", "the walkthrough minutes"]
_WHEN = ["on Monday", "before noon", "late on Thursday", "earlier this week", "at the start of the month",
"during the afternoon shift", "ahead of the audit", "after the all-hands"]
_NUMS = ["three", "four", "six", "eight", "eleven", "twelve", "fifteen", "twenty"]
_TEMPLATES = [
"{d} confirmed {t} {w} without any material discrepancies.",
"{d} circulated an update on {t} {w}, and the floor staff acknowledged it.",
"A reminder from {d}: {t} will be reviewed {w}.",
"{d} logged {n} items related to {t} {w} and routed each to the right department.",
"Attendance at the briefing on {t} was recorded by {d} {w}, which is typical for this month.",
"{d} reported that {t} passed its routine check {w} and no follow-up is needed.",
"{d} asked everyone to read {t} {w}; {n} questions were collected for the next meeting.",
"Following {w}, {d} closed {n} open tickets about {t}.",
]
def _rng(*parts):
return random.Random("|".join(str(p) for p in parts))
def item_id(depth, position, seed, variant):
h = hashlib.sha1(("%d|%.3f|%d|%s" % (depth, position, seed, variant)).encode()).hexdigest()
return "ndl-" + h[:10]
def depth_bucket(depth):
return ("%gk" % (depth / 1000.0)) if depth >= 1000 else str(depth)
def category(depth, variant):
return "needle/%s/%s" % (depth_bucket(depth), variant)
def _paragraph(rng):
sents = []
for _ in range(4):
sents.append(rng.choice(_TEMPLATES).format(
d=rng.choice(_DEPTS), t=rng.choice(_THINGS), w=rng.choice(_WHEN), n=rng.choice(_NUMS)))
p = " ".join(sents)
return p[0].upper() + p[1:] + "\n\n"
def _cap(s):
return s[0].upper() + s[1:]
def filler_paragraphs(target_chars, rng):
paras, total = [], 0
while total < target_chars:
p = _paragraph(rng)
# sentences starting with a department name in lower case get capitalised per sentence
p = ". ".join(_cap(x) if x else x for x in p.split(". "))
paras.append(p)
total += len(p)
return paras
def _codes(rng, n):
words = rng.sample(CODE_WORDS, n)
nums = rng.sample(range(1000, 10000), n)
return ["%s-%d" % (w, k) for w, k in zip(words, nums)]
def _splice(paras, inserts):
"""inserts: list of (fraction, text). Insert by paragraph index on the ORIGINAL list."""
n = len(paras)
out = list(paras)
placed = sorted(((min(n, max(0, int(round(f * n)))), i, t) for i, (f, t) in enumerate(inserts)),
key=lambda x: (x[0], x[1]), reverse=True)
for idx, _i, text in placed:
out.insert(idx, text + "\n\n")
return "".join(out)
def _current_sentence(place, code):
return ("Maintenance note: the access code for the %s is %s until the end of the quarter."
% (place, code))
def _old_sentence(place, code):
return ("Maintenance note: the access code for the %s was %s until it was rotated out "
"last month." % (place, code))
def _key_sentence(place, code):
return "Maintenance note: the access code for the %s is %s." % (place, code)
def build_item(depth, position, seed, variant, cpt=DEFAULT_CPT):
"""Deterministic item. Returns dict(prompt, gold, others, place, decoy_order, ...)."""
rng = _rng("needle", GEN_VERSION, depth, "%.3f" % position, seed, variant)
needle_chars = 0
place = rng.choice(PLACES)
inserts, others, decoy_order = [], [], None
if variant == "plain":
(gold,) = _codes(rng, 1)
inserts.append((position, _current_sentence(place, gold)))
elif variant == "decoy":
gold, old = _codes(rng, 2)
decoy_order = rng.choice(["old_first", "old_last"])
dpos = max(0.02, position - 0.2) if decoy_order == "old_first" else min(0.98, position + 0.2)
inserts.append((position, _current_sentence(place, gold)))
inserts.append((dpos, _old_sentence(place, old)))
others = [old]
elif variant == "multikey":
places = rng.sample(PLACES, MULTIKEY_K)
codes = _codes(rng, MULTIKEY_K)
# the asked key sits at `position`; the other four fill the remaining grid slots
slots = list(POSITION_GRID)
if position not in slots:
slots = sorted(set(slots[:-1] + [position]))[:MULTIKEY_K]
order = sorted(range(MULTIKEY_K), key=lambda i: slots[i])
gold_slot = slots.index(position)
place, gold = places[gold_slot], codes[gold_slot]
for i in order:
inserts.append((slots[i], _key_sentence(places[i], codes[i])))
others = [c for i, c in enumerate(codes) if i != gold_slot]
else:
raise ValueError("unknown variant %r" % variant)
needle_chars = sum(len(t) + 2 for _f, t in inserts)
question = ("QUESTION: According to the maintenance notes above, what is the %saccess code for the %s? "
"Answer with the code exactly as written, nothing else."
% ("CURRENT " if variant == "decoy" else "", place))
target_chars = max(200, int(depth * cpt) - needle_chars - len(question) - 8)
paras = filler_paragraphs(target_chars, rng)
doc = _splice(paras, inserts)
prompt = doc + "\n" + question
return {"item_id": item_id(depth, position, seed, variant), "depth": depth,
"position": position, "seed": seed, "variant": variant, "place": place,
"gold": gold, "others": others, "decoy_order": decoy_order,
"prompt": prompt, "est_tokens": int(len(prompt) / cpt)}
def score_answer(content, gold, others):
toks = CODE_RE.findall(content or "")
has_gold = gold in toks
bad = sorted({t for t in toks if t in set(others)})
return {"correct": bool(has_gold and not bad), "has_gold": has_gold,
"answer_tokens": toks[:8], "wrong_codes": bad}
def item_set(cpt=DEFAULT_CPT):
defs = {"v": GEN_VERSION, "cpt": cpt, "templates": _TEMPLATES, "depts": _DEPTS, "things": _THINGS,
"when": _WHEN, "nums": _NUMS, "places": PLACES, "words": CODE_WORDS,
"positions": POSITION_GRID, "variants": VARIANTS}
return "needle@" + hashlib.sha256(json.dumps(defs, sort_keys=True).encode()).hexdigest()[:12]
def grid(depths, positions, variants, seeds):
return [(d, p, s, v) for d in depths for v in variants for p in positions for s in range(seeds)]
# ---------------------------------------------------------------- run
def _attempt(store, lane, key, k):
it = build_item(*key, cpt=store.run["args"]["cpt"])
override = {"cache_prompt": False} if lane.snapshot_kind == "llama-server" else None
def grade(resp):
content, u = client.content(resp), client.usage(resp)
sc = score_answer(content, it["gold"], it["others"])
pt = u["prompt_tokens"]
return {"correct": sc["correct"], "answer_tokens": sc["answer_tokens"],
"wrong_codes": sc["wrong_codes"], "has_gold": sc["has_gold"],
"content_head": content[:200],
"chars_per_token": round(len(it["prompt"]) / pt, 3) if pt else None,
"cached_prefill": bool(u["cached_tokens"])}
fields = {"depth": it["depth"], "position": it["position"], "seed": it["seed"],
"variant": it["variant"], "gold": it["gold"], "est_tokens": it["est_tokens"],
"decoy_order": it["decoy_order"], "cache_prompt_off": bool(override)}
results.call_attempt(store, lane, it["item_id"], k, category(it["depth"], it["variant"]),
[{"role": "user", "content": it["prompt"]}], grade, fields,
max_tokens=DEFAULT_MAX_TOKENS, temperature=DEFAULT_TEMPERATURE,
override=override)
def _uncached(rows):
return [r["prefill_ps"] for r in rows if r.get("prefill_ps") and not r.get("cached_prefill")]
SUMMARY = {"mean_prompt_tokens": lambda rs: stats.mean(r["prompt_tokens"] for r in rs
if r.get("prompt_tokens")),
"mean_prefill_ps_uncached": lambda rs: stats.mean(_uncached(rs)),
"n_uncached_speed_rows": lambda rs: len(_uncached(rs))}
def validate(cpt=DEFAULT_CPT):
ok = True
for d, p, s, v in grid([1000, 4000], POSITION_GRID, VARIANTS, 2):
a, b = build_item(d, p, s, v, cpt), build_item(d, p, s, v, cpt)
problems = []
if a != b:
problems.append("not deterministic")
codes = CODE_RE.findall(a["prompt"])
expect = 1 + len(a["others"])
if sorted(codes) != sorted([a["gold"]] + a["others"]) or len(codes) != expect:
problems.append("stray or missing codes %s" % codes)
if a["prompt"].count(a["gold"]) != 1:
problems.append("gold not unique")
if v == "decoy" and not all(a["place"] in x for x in re.findall(r"[^.\n]*rotated out[^.\n]*", a["prompt"])):
problems.append("decoy not about the same place")
if problems:
ok = False
print("[BAD] %s %s: %s" % (a["item_id"], (d, p, s, v), "; ".join(problems)))
ids = {item_id(*k) for k in grid(DEPTH_GRID, POSITION_GRID, VARIANTS, 3)}
if len(ids) != len(DEPTH_GRID) * len(POSITION_GRID) * len(VARIANTS) * 3:
ok = False
print("[BAD] item id collision")
print("item_set %s: %s" % (item_set(cpt), "OK" if ok else "FAILED"))
return ok
def run(a):
args = results.run_args(a, depths=[int(x) for x in a.depths.split(",")],
positions=[float(x) for x in a.positions.split(",")],
variants=a.variants.split(","), seeds=a.seeds, cpt=a.cpt)
if not (set(args["positions"]) <= set(POSITION_GRID) and set(args["variants"]) <= set(VARIANTS)):
print("ERROR: --positions must come from %s and --variants from %s."
% (POSITION_GRID, VARIANTS))
return 2
def plan(g):
keys = grid(g["depths"], g["positions"], g["variants"], g["seeds"])
return item_set(g["cpt"]), [(item_id(*key), key) for key in keys]
_store, summary = results.run_attempts(INSTRUMENT, args, plan, _attempt, resume=a.resume,
extra=SUMMARY)
return 3 if summary["stopped"] else 0
def main(argv=None):
ap = argparse.ArgumentParser(prog="bench.py needle")
sub = ap.add_subparsers(dest="cmd")
v = sub.add_parser("validate")
v.add_argument("--cpt", type=float, default=DEFAULT_CPT)
sub.add_parser("report")
r = sub.add_parser("run")
r.add_argument("--depths", default=",".join(str(d) for d in DEPTH_GRID))
r.add_argument("--positions", default=",".join(str(p) for p in DEFAULT_POSITIONS))
r.add_argument("--variants", default=",".join(VARIANTS))
r.add_argument("--seeds", type=int, default=1)
r.add_argument("--cpt", type=float, default=DEFAULT_CPT)
results.add_run_args(r)
args = ap.parse_args(sys.argv[1:] if argv is None else argv)
if args.cmd == "run":
sys.exit(run(args))
elif args.cmd == "report":
results.print_report(INSTRUMENT, SUMMARY)
else:
sys.exit(0 if validate(getattr(args, "cpt", DEFAULT_CPT)) else 1)
if __name__ == "__main__":
main()