176 lines
9.5 KiB
Python
176 lines
9.5 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 offline classifier may decide finished, …`."""
|
|
import collections
|
|
import math
|
|
import random
|
|
import re
|
|
import typing
|
|
|
|
from claude_code.entries import AssistantTurn, Entry, Text
|
|
from transcript_archive.outcomes import FINISHED, INTERRUPTED, UNFINISHED
|
|
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
|
|
# The classifier averages this many regressions, each shuffling the samples in its own order: one shuffle alone moved the missed interrupts of a run between 0 and 2.
|
|
SEEDS = 5
|
|
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], seed: int) -> typing.Callable[[str], float]:
|
|
"""The chance that a message is an interrupt, from a logistic regression over its words that the samples train, shuffled in the order seed gives."""
|
|
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(seed)
|
|
|
|
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 averaged(samples: typing.Sequence[Sample]) -> typing.Callable[[str], float]:
|
|
"""The mean chance of SEEDS regressions that differ only in the order they shuffle the samples."""
|
|
regressions = [logistic(samples, seed) for seed in range(SEEDS)]
|
|
return lambda text: sum(regression(text) for regression in regressions) / SEEDS
|
|
|
|
|
|
def classifier(samples: typing.Sequence[Sample]) -> Decider:
|
|
"""Finished where the chance of an interrupt is below one half and below that of every interrupt among the samples; interrupt where it is at least one half and above that of every other kind; otherwise the judge's model decides.
|
|
|
|
A 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(averaged(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)
|
|
chance = averaged(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
|
|
|
|
|
|
# Rules are fixed, and run on the whole archive; a learner trains on samples, and runs on samples it didn't train on.
|
|
RULES: dict[str, Method] = {'"?" rule': question_mark, "decision table": decision_table}
|
|
LEARNERS: dict[str, Method] = {"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 fold is the samples to learn from, which are all those its test leaves out, and the samples to test on."""
|
|
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], rules: typing.Mapping[str, Method], learners: typing.Mapping[str, Method], folds: int = FOLDS, skipped: int = 0) -> 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, without sending anything to an outside service. The archive gives them as {', '.join(f'{count} {plain(kind)}' for kind, count in sorted(kinds.items(), key=lambda each: plain(each[0])))}."]
|
|
if skipped:
|
|
lines.append(f"Skipped {skipped} verdicts whose transcript could not be read.")
|
|
for name, rule in rules.items():
|
|
found = evaluate(rule, [], samples)
|
|
lines += [result_line(f"{name}, on the whole archive", found), *decides_lines(f"{name}, on the whole archive", found)]
|
|
split = len(samples) - max(1, len(samples) // LATEST)
|
|
for name, learner in learners.items():
|
|
held_out = sum((evaluate(learner, trained, tested) for trained, tested in folds_of(samples, folds)), Counts())
|
|
latest = evaluate(learner, samples[:split], samples[split:])
|
|
lines += [result_line(f"{name}, on held-out folds", held_out), result_line(f"{name}, on the latest fifth after learning from the rest", latest), *decides_lines(f"{name}, on both tests", held_out + latest)]
|
|
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 kinds the archive gives the verdicts that were decided as decided, where the archive gives another kind than decided."""
|
|
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" (of these, archived {', '.join(f'{kind} {count}' for kind, count in wrong)})" if wrong else ""
|
|
|
|
|
|
def decides_lines(how: str, found: Counts) -> list[str]:
|
|
"""For finished and for unfinished that the decider decided at all: whether it decided no archived interrupt as that kind."""
|
|
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"{how}, decides {plain(kind)} with no missed interrupt.")
|
|
elif decided:
|
|
lines.append(f"{how}, does not decide {plain(kind)} with no missed interrupt: it decided {found[(INTERRUPTED, kind)]} archived interrupt(s) as {plain(kind)}.")
|
|
return lines
|