Files
claude-config/bin/judge_replay/offline.py
T

161 lines
8.4 KiB
Python

"""Deciders of a verdict's kind that run offline on the worker's final message, replayed on the archive: docs/decisions.md → `routing: the judge's model keeps the verdict kind, …`."""
import collections
import math
import random
import re
import typing
from transcript_archive.outcomes import FINISHED, INTERRUPTED, UNFINISHED
from claude_code.entries import AssistantTurn, Entry, Text
from judge_replay.replay import Kind
class Sample(typing.NamedTuple):
"""What a decider reads of one archived verdict: the kind the archive gives it and the worker's final message."""
kind: Kind
text: str
# A decider names a kind, or None to leave the verdict to the judge's model. A method builds one from the samples it may learn from.
Decider = typing.Callable[[str], Kind | None]
Method = typing.Callable[[typing.Sequence[Sample]], Decider]
Counts = collections.Counter[tuple[Kind, Kind | None]]
FOLDS = 10
INNER_FOLDS = 5
# A word in fewer messages than this is left out of the classifier.
MIN_MESSAGES = 3
EPOCHS = 8
RATE = 0.05
DECAY = 1e-3
# The latest 1/LATEST of the archive is the second test: the verdicts a decider would meet next.
LATEST = 5
# The first row whose pattern matches the final message decides it; a message no row matches is left to the judge. The rows come from reading the archive's interrupts, so a run of the table on the whole archive is not a held-out test.
DECISION_TABLE = (
(INTERRUPTED, re.compile(r"(?i)\?|recommend|your call|needs? you|tell me|you answer|please|unmerged|not merged|do you|should i|i need|need your|you say|decisions? for|stays until")),
(FINISHED, re.compile(r"(?i)\bmerged\b(?!.*ready to cut)")),
)
def final_message(entries: list[Entry]) -> str:
"""The text of the worker's last turn that has any, "" where it wrote none."""
for entry in reversed(entries):
if isinstance(entry, AssistantTurn):
text = "\n".join(part.text for part in entry.parts if isinstance(part, Text) and part.text.strip())
if text:
return text
return ""
def question_mark(samples: typing.Sequence[Sample]) -> Decider:
"""The one rule: an interrupt where the message holds a "?", finished where it holds none."""
return lambda text: INTERRUPTED if "?" in text else FINISHED
def decision_table(samples: typing.Sequence[Sample]) -> Decider:
return lambda text: next((kind for kind, pattern in DECISION_TABLE if pattern.search(text)), None)
def words_of(text: str) -> frozenset[str]:
"""Each word and each pair of neighbouring words of the message, and its question marks."""
words = re.findall(r"[a-z0-9']+|\?", text.lower())
return frozenset(words) | {f"{first} {second}" for first, second in zip(words, words[1:])}
def logistic(samples: typing.Sequence[Sample]) -> typing.Callable[[str], float]:
"""The chance that a message is an interrupt, from a logistic regression over its words that the samples train."""
seen = collections.Counter(word for found in samples for word in words_of(found.text))
vocabulary = {word for word, count in seen.items() if count >= MIN_MESSAGES}
data = [(words_of(found.text) & vocabulary, 1.0 if found.kind == INTERRUPTED else 0.0) for found in samples]
weights: dict[str, float] = collections.defaultdict(float)
bias = 0.0
shuffler = random.Random(0)
def chance(words: typing.Iterable[str]) -> float:
return 1 / (1 + math.exp(-max(-30.0, min(30.0, bias + sum(weights[word] for word in words)))))
for _ in range(EPOCHS):
shuffler.shuffle(data)
for words, interrupt in data:
error = chance(words) - interrupt
bias -= RATE * error
for word in words:
weights[word] -= RATE * (error + DECAY * weights[word])
return lambda text: chance(words_of(text) & vocabulary)
def classifier(samples: typing.Sequence[Sample]) -> Decider:
"""Finished below the lowest chance any interrupt among the samples got when held out, interrupt above the highest chance any other kind got, and the judge's model between.
Each sample's chance is the one a model trained on the other folds of the samples gives it, so the bounds don't rest on how well the model fits what it trained on. A bound is where the samples held no miss; that doesn't promise the next verdict holds none."""
interrupts = [found for found in samples if found.kind == INTERRUPTED]
if not interrupts or len(interrupts) == len(samples):
return lambda text: None
held_out = [(tested.kind, chance) for trained, tests in folds_of(samples, INNER_FOLDS) for chance, tested in zip(map(logistic(trained), (found.text for found in tests)), tests)]
below = min(chance for kind, chance in held_out if kind == INTERRUPTED)
above = max((chance for kind, chance in held_out if kind != INTERRUPTED), default=0.0)
chance = logistic(samples)
def decide(text: str) -> Kind | None:
found = chance(text)
if found < below and found < 0.5:
return FINISHED
return INTERRUPTED if found > above and found >= 0.5 else None
return decide
METHODS: dict[str, Method] = {"a question mark": question_mark, "decision table": decision_table, "classifier": classifier}
def folds_of(samples: typing.Sequence[Sample], count: int) -> list[tuple[list[Sample], list[Sample]]]:
"""count folds of the samples, dealt in turn; each is what to learn from and what to test on, the samples the fold's test leaves out."""
return [([found for place, found in enumerate(samples) if place % count != fold], [found for place, found in enumerate(samples) if place % count == fold]) for fold in range(count)]
def evaluate(method: Method, trained: typing.Sequence[Sample], tested: typing.Sequence[Sample]) -> Counts:
"""How often the method, learning from trained, decided each kind for each archived kind of tested; None where it left the verdict to the judge."""
decide = method(trained)
return collections.Counter((found.kind, decide(found.text)) for found in tested)
def plain(kind: Kind) -> str:
return kind.removeprefix("Verdict: ")
def offline_report(model: str, samples: typing.Sequence[Sample], methods: typing.Mapping[str, Method], folds: int = FOLDS) -> str:
"""samples are in the order the verdicts were judged, oldest first, so the latest fifth is the newest verdicts."""
kinds = collections.Counter(found.kind for found in samples)
lines = [f"Replayed {len(samples)} archived verdicts of {model} projects offline, nothing sent to an outside service: {', '.join(f'{count} {plain(kind)}' for kind, count in sorted(kinds.items(), key=lambda each: plain(each[0])))}."]
split = len(samples) - max(1, len(samples) // LATEST)
for name, method in methods.items():
held_out = sum((evaluate(method, trained, tested) for trained, tested in folds_of(samples, folds)), Counts())
lines += [result_line(f"{name}, on held-out folds", held_out), *decides_lines(name, held_out, kinds)]
lines.append(result_line(f"{name}, on the latest fifth after learning from the rest", evaluate(method, samples[:split], samples[split:])))
return "\n".join(lines)
def result_line(how: str, found: Counts) -> str:
decided = collections.Counter({kind: sum(count for (_, said), count in found.items() if said == kind) for kind in {said for _, said in found if said}})
missed = sum(count for (archived, said), count in found.items() if archived == INTERRUPTED and said not in (None, INTERRUPTED))
parts = [f"{plain(kind)} {count}{wrong_kinds(kind, found)}" for kind, count in sorted(decided.items(), key=lambda each: plain(each[0]))]
return f"{how}: decided {sum(decided.values())} of {sum(found.values())}{': ' + ', '.join(parts) if parts else ''}. Missed interrupts: {missed}."
def wrong_kinds(decided: Kind, found: Counts) -> str:
"""The archived kinds a decider returned decided for, where the archive gave another kind."""
wrong = sorted(((plain(archived), count) for (archived, said), count in found.items() if said == decided and archived != decided), key=lambda each: each[0])
return f" (archived {', '.join(f'{kind} {count}' for kind, count in wrong)})" if wrong else ""
def decides_lines(name: str, found: Counts, kinds: collections.Counter[Kind]) -> list[str]:
"""For finished and for unfinished: whether the decider decided it where the archive holds no interrupt, and how much of that kind it got right."""
lines = []
for kind in (FINISHED, UNFINISHED):
decided = sum(count for (_, said), count in found.items() if said == kind)
if decided and not found[(INTERRUPTED, kind)]:
lines.append(f"{name} decides {plain(kind)} with no missed interrupt: {found[(kind, kind)]} of {kinds[kind]} {plain(kind)}.")
elif decided:
lines.append(f"{name} does not decide {plain(kind)} with no missed interrupt.")
return lines