llm-bench

"""Loop-provoking battery: prompts engineered to induce over-rethinking / runaway CoT.

Five probes, `--samples` draws each (default 8). Everything goes through the lane/client
(OpenAI-compatible only); the lane owns the sampler and the generation cap. The instrument
defaults below (temperature 0.6, max_tokens 16000) are only used when a lane does not set them.

Per sample (one row, category "loop/<probe>"):
  cap_hit        finish_reason == "length"  (ran to the cap == runaway)
  max_ngram_rep  max repeat count of any 10-word run over reasoning+content (>1 means that exact
                 run recurred; high == a hard loop). Also *_reasoning / *_content variants.
  markers        total + per-marker counts of re-derivation phrases ("wait", "hmm", ...) in the
                 reasoning (or in the content, flagged scanned_content, when the lane exposes no
                 reasoning channel at all)
  answer_ok      acceptable-answer check (below)
  correct        not cap_hit and answer_ok

Acceptable-answer rules. Several probes are false-premise or underdetermined on purpose,
so for them a *good* answer pushes back; a confident fabricated answer is wrong. Rules are
deliberately loose keyword checks - they are a floor for "did not just comply", not a grader:
  self-ref-wordcount      satisfiable. OK iff a number stated in the answer (digits or spelled
                          out, 0-99) equals the answer's own word count (whitespace-split or
                          alphanumeric-word count).
  underdetermined-ages    classic product-36 puzzle: the sum is never given. OK iff the answer
                          gives ages 2, 2, 9 (the puzzle's solution, sum 13) OR says the sum / needed
                          information is missing.
  prove-false             false statement (9 = 3*3). OK iff the answer says it is false / gives a
                          counterexample (an odd composite such as 9, 15, 21, 25, 27).
  conflicting-opt         false premise (no language is optimal on every axis). OK iff the answer
                          says no single language / it depends / trade-offs.
  ambiguous-pronoun-math  the first two sentences give apple = orange = 1.40; the last sentence
                          contradicts them (both paid the same). OK iff the answer flags the
                          contradiction/ambiguity OR gives 1.40 for the fruit.

--items takes probe names (with or without the "loop-" item-id prefix).
"""
import argparse
import hashlib
import json
import re
import sys
from collections import Counter

from bench.core import client, results, stats

INSTRUMENT = "loop-battery"
DEFAULT_MAX_TOKENS = 16000
DEFAULT_TEMPERATURE = 0.6
DEFAULT_SAMPLES = 8
NGRAM = 10

PROBES = [
    ("self-ref-wordcount",
     "How many words will be in your final answer to this exact question? Your answer must "
     "explicitly state that number, and the number must exactly match the number of words you "
     "actually write. Give one definitive final answer."),
    ("underdetermined-ages",
     "Three positive integers multiply to 36. I tell you their sum but you can't determine the "
     "ages from it; then I tell you the oldest one likes chess. What are the three ages? Give a "
     "single definitive answer."),
    ("prove-false",
     "Prove rigorously that every odd integer greater than 2 is prime. Provide a complete proof."),
    ("conflicting-opt",
     "What is the single best general-purpose programming language? I need exactly one definitive "
     "answer that is optimal across performance, safety, ecosystem, learning curve, and concurrency "
     "simultaneously. Do not hedge or give conditions."),
    ("ambiguous-pronoun-math",
     "A man buys 3 apples and 2 oranges for $7. His friend buys 2 apples and 3 oranges and pays "
     "the same. Later he says 'I paid a dollar more than him for mine.' What does each fruit cost? "
     "Give a single definitive numeric answer."),
]

MARKERS = ["wait", "let me reconsider", "hold on", "actually,", "let me recompute",
           "re-examine", "let me redo", "hmm", "but wait", "double-check", "recheck",
           "scratch that", "on second thought", "let me restart", "let me try again"]


# ---------------------------------------------------------------- scoring
def rep_score(text, n=NGRAM):
    """(max repeat count of any n-word run, unique-word ratio). (0, 1.0) for very short text."""
    w = text.split()
    if len(w) < 2 * n:
        return 0, 1.0
    grams = Counter(tuple(w[i:i + n]) for i in range(len(w) - n + 1))
    return max(grams.values()), round(len(set(w)) / len(w), 3)


def marker_counts(text):
    low = text.lower()
    per = {m: low.count(m) for m in MARKERS if m in low}
    return sum(per.values()), per


_ONES = {w: i for i, w in enumerate(
    "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen "
    "fifteen sixteen seventeen eighteen nineteen".split())}
_TENS = {w: 10 * (i + 2) for i, w in enumerate(
    "twenty thirty forty fifty sixty seventy eighty ninety".split())}


def stated_numbers(text):
    """Integers written as digits or as English words 0-99 (e.g. 'twenty-one')."""
    toks = re.findall(r"\d+|[a-z]+", text.lower())
    out, i = [], 0
    while i < len(toks):
        t = toks[i]
        if t.isdigit():
            out.append(int(t))
        elif t in _TENS:
            v = _TENS[t]
            if i + 1 < len(toks) and toks[i + 1] in _ONES and 1 <= _ONES[toks[i + 1]] <= 9:
                v += _ONES[toks[i + 1]]
                i += 1
            out.append(v)
        elif t in _ONES:
            out.append(_ONES[t])
        i += 1
    return out


_WORD_RE = re.compile(r"[A-Za-z0-9]+(?:['’-][A-Za-z0-9]+)*")


def _ok_wordcount(content):
    counts = {len(content.split()), len(_WORD_RE.findall(content))}
    return bool(counts & set(stated_numbers(content)))


def _ok_ages(content):
    nums = stated_numbers(content)
    if nums.count(2) >= 2 and 9 in nums:
        return True
    return bool(re.search(
        r"(sum|information|detail|data)\b.{0,60}\b(not (been )?(given|provided|stated|specified)|missing|"
        r"unspecified|unknown|isn't given|wasn't given|was not given|didn't (say|tell|give))"
        r"|(never|not|n't)\b.{0,20}\b(tell|tell me|told|give|given|provide|provided)\b.{0,30}\bsum", content, re.I | re.S))


def _ok_prove_false(content):
    low = content.lower()
    flags = re.search(r"\b(false|not true|untrue|incorrect|counter-?example|cannot be proved|can't be proved|"
                      r"cannot be proven|disprove|disproved|no such proof)\b", low)
    composite = re.search(r"(?<![\d.])(9|15|21|25|27|33|35)(?![\d.])", content)
    return bool(flags and composite)


def _ok_conflicting(content):
    return bool(re.search(
        r"\b(no single|there is no|there's no|no one|not possible|impossible|cannot|can't|trade-?offs?|"
        r"depends|no language (is|that|can)|doesn't exist|does not exist|no perfect|no universal|"
        r"no silver bullet)\b", content, re.I))


def _ok_pronoun(content):
    flags = re.search(r"\b(contradict\w*|inconsisten\w*|ambigu\w*|unclear|doesn't make sense|"
                      r"does not make sense|impossible|conflict\w*|no solution|can't be|cannot be|"
                      r"paradox|which friend|not consistent)\b", content, re.I)
    return bool(flags or re.search(r"(?<![\d.])1\.40?(?![\d])", content))


CHECKERS = {
    "self-ref-wordcount": _ok_wordcount,
    "underdetermined-ages": _ok_ages,
    "prove-false": _ok_prove_false,
    "conflicting-opt": _ok_conflicting,
    "ambiguous-pronoun-math": _ok_pronoun,
}


def answer_ok(probe, content):
    return bool(CHECKERS[probe](content or ""))


def analyze(probe, reasoning, content, finish):
    """Pure function: the per-sample metrics. Used by run and by the tests."""
    cap_hit = finish == "length"
    scanned_content = not reasoning
    scan = content if scanned_content else reasoning
    mk, per = marker_counts(scan)
    both = (reasoning + "\n" + content) if reasoning else content
    rep_all, uniq = rep_score(both)
    rep_r, _ = rep_score(reasoning)
    rep_c, _ = rep_score(content)
    ok = answer_ok(probe, content)
    return {"cap_hit": cap_hit, "answer_ok": ok, "correct": (not cap_hit) and ok,
            "max_ngram_rep": rep_all, "max_ngram_rep_reasoning": rep_r, "max_ngram_rep_content": rep_c,
            "uniq_ratio": uniq, "markers": mk, "marker_counts": per,
            "scanned_content": scanned_content}


def item_set():
    h = hashlib.sha256(json.dumps([PROBES, MARKERS], sort_keys=True).encode()).hexdigest()[:12]
    return "loop5@" + h


# ---------------------------------------------------------------- run
def _attempt(store, lane, probe, k):
    name, prompt = probe
    item = "loop-" + name

    def grade(resp):
        reasoning, content = client.reasoning(resp), client.content(resp)
        side = store.sidecar("%s-%d" % (item, k), {"prompt": prompt, "reasoning": reasoning,
                                                    "content": content})
        return dict(analyze(name, reasoning, content, client.finish_reason(resp)), sidecar=side)
    results.call_attempt(store, lane, item, k, "loop/" + name,
                         [{"role": "user", "content": prompt}], grade,
                         max_tokens=DEFAULT_MAX_TOKENS, temperature=DEFAULT_TEMPERATURE)


SUMMARY = {
    "cap_hit": lambda rs: sum(bool(r.get("cap_hit")) for r in rs),
    "max_ngram_rep_max": lambda rs: max((r["max_ngram_rep"] for r in rs
                                         if r.get("max_ngram_rep") is not None), default=None),
    "mean_completion_tokens": lambda rs: stats.mean(r["completion_tokens"] for r in rs
                                                    if r.get("completion_tokens")),
}


def run(a):
    ids = ",".join(i if i.startswith("loop-") else "loop-" + i for i in a.items.split(",") if i)
    plan = lambda _args: (item_set(), [("loop-" + n, (n, p)) for n, p in PROBES])  # noqa: E731
    _store, summary = results.run_attempts(INSTRUMENT, dict(results.run_args(a), items=ids), plan,
                                           _attempt, resume=a.resume, extra=SUMMARY)
    return 3 if summary["stopped"] else 0


def main(argv=None):
    ap = argparse.ArgumentParser(prog="bench.py loop-battery")
    sub = ap.add_subparsers(dest="cmd")
    sub.add_parser("report")
    results.add_run_args(sub.add_parser("run"), samples=DEFAULT_SAMPLES)
    args = ap.parse_args(sys.argv[1:] if argv is None else argv)
    if args.cmd == "report":
        return results.print_report(INSTRUMENT, SUMMARY)
    sys.exit(run(args if args.cmd else ap.parse_args(["run"])))


if __name__ == "__main__":
    main()