File size: 2,398 Bytes
b16b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from __future__ import annotations

import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Literal

Same = Callable[[str, str], bool]


@dataclass(frozen=True)
class Vote:
    answer: str | None
    confidence: float


@dataclass(frozen=True)
class Decision:
    answer: str | None
    share: float
    n_used: int


def tail_confidence(logprobs: list[float], window: int = 2048) -> float:
    tail = logprobs[-window:]
    if not tail:
        raise ValueError("logprobs is empty")
    return sum(tail) / len(tail)


def cluster(answers: list[str | None], same: Same) -> list[list[int]]:
    groups: list[list[int]] = []
    for i, answer in enumerate(answers):
        if answer is None:
            continue
        for group in groups:
            if same(answers[group[0]], answer):  # type: ignore[arg-type]
                group.append(i)
                break
        else:
            groups.append([i])
    return groups


def decide(

    votes: list[Vote],

    same: Same,

    keep_top: float = 1.0,

    weighting: Literal["count", "confidence"] = "count",

) -> Decision:
    # Votes without an answer carry no information, so they neither count towards keep_top nor the share.
    answered = [v for v in votes if v.answer is not None]
    if not answered:
        return Decision(None, 0.0, 0)
    n_keep = max(1, math.ceil(round(keep_top * len(answered), 9)))
    kept = sorted(answered, key=lambda v: -v.confidence)[:n_keep]

    top = kept[0].confidence
    weights = [math.exp(v.confidence - top) if weighting == "confidence" else 1.0 for v in kept]
    groups = cluster([v.answer for v in kept], same)

    best_group = max(
        groups,
        key=lambda g: (sum(weights[i] for i in g), max(kept[i].confidence for i in g)),
    )
    winner = max(best_group, key=lambda i: kept[i].confidence)
    return Decision(
        answer=kept[winner].answer,
        share=sum(weights[i] for i in best_group) / sum(weights),
        n_used=len(kept),
    )


def should_stop(

    votes: list[Vote], same: Same, min_votes: int = 8, threshold: float = 0.75, **decide_kwargs

) -> bool:
    if len(votes) < min_votes:
        return False
    decision = decide(votes, same, **decide_kwargs)
    return decision.answer is not None and decision.share >= threshold