File size: 9,284 Bytes
24918f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python3
"""Choose decision thresholds from validation answers.

Replays a validation set through the engine and picks the thresholds that
meet the experiment's bars, printing a decisions.yaml fragment:

  turn.tools.load_at         the P(true) that maximizes F-beta with beta=2
                             across loadable tools (a missed tool costs a
                             round trip, an extra one costs schema bytes)
  turn.guides.omit_below and turn.guides.confidence_floor
                             the pair that omits the most units while keeping
                             omission precision at or above --omission-precision
                             (an omitted unit that was needed is a silent drop)
  request.load_at            the unit-rank score that maximizes F-beta over
                             the tools each request_tools need was for (the
                             tools the turn used after it, and those the
                             judge scored 3 or more)
  turn.skills.preload_at     the lowest top score that preloads the most turns
                             while the preloaded skill was judged relevant
                             (skill_scores of 3 or more) at or above
                             --preload-precision; a wrong preload steers the
                             whole turn

Each is reported with its support; tools also with the expected calibration
error, and the tool threshold also per host (coordinator turns and worker
legs), so a host that would want a different threshold shows up. Rows are
training rows (rows.py) and every question is the one the row's turn offered.

Usage: calibrate.py --corpus C --examples FILE [--engine PATH] [--beta 2.0]
                    [--omission-precision 0.97] [--preload-precision 0.8]
"""

import argparse
import collections
import os
import sys

sys.path.insert(0, os.path.dirname(__file__))
import rows as rowfile  # noqa: E402
from corpus import Corpus  # noqa: E402
from replay_eval import Engine, ece, option_answer  # noqa: E402


def fbeta(tp, fp, fn, beta):
    if tp == 0:
        return 0.0
    p = tp / (tp + fp)
    r = tp / (tp + fn)
    b2 = beta * beta
    return (1 + b2) * p * r / (b2 * p + r)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--corpus", required=True)
    ap.add_argument("--examples", required=True)
    ap.add_argument("--engine", default=os.environ.get("LYCAON_DECIDE_ENGINE"), help="a pw-decide launcher: `pw-decide serve --model ... --head turn-load=...` (default $LYCAON_DECIDE_ENGINE)")
    ap.add_argument("--beta", type=float, default=2.0)
    ap.add_argument("--omission-precision", type=float, default=0.97)
    ap.add_argument("--preload-precision", type=float, default=0.8)
    args = ap.parse_args()
    if not args.engine:
        ap.error("--engine (or LYCAON_DECIDE_ENGINE) must name a pw-decide launcher")

    corpus = Corpus.load(args.corpus)
    examples = rowfile.load(args.examples)
    tool_pairs = []
    guide_pairs = []
    skill_tops = []
    request_pairs = []
    tool_cards = corpus.tool_cards()
    cards = corpus.skill_cards()
    roster = sorted(cards)
    engine = Engine(args.engine)
    try:
        for ex in examples:
            loadable = [t for t in ex["offered"]["loadable"] if t in tool_cards]
            for request in ex["labels"].get("requests") or []:
                exact = set(request.get("exact") or [])
                rest = [t for t in loadable if t not in exact]
                wanted = set(request.get("after") or []) | {t for t, v in (request.get("scores") or {}).items() if v >= 3}
                if not rest or not wanted & set(rest):
                    continue
                scores = engine.call({"method": "rank", "head": "unit-rank", "task": request["need"], "candidates": [tool_cards[t] for t in rest]})["scores"]
                request_pairs.append([(scores[i], rest[i] in wanted) for i in range(len(rest))])
            if ex["partial"]:
                continue
            qs = corpus.row_questions(ex)
            answers = engine.call({"method": "decide", "head": "turn-load", "state": ex["state"], "questions": qs})["answers"]
            truth = rowfile.truth_tools(ex)
            for name in qs.get("tools", {}).get("options", {}):
                p, _ = option_answer(answers, "tools", name)
                tool_pairs.append((0.0 if p is None else p, name in truth, ex["host"]))
            guides = ex["labels"]["guides"]
            for uid in qs.get("guides", {}).get("options", {}):
                needed = guides.get(uid)
                if needed is None:
                    continue
                p, conf = option_answer(answers, "guides", uid)
                guide_pairs.append((0.0 if p is None else p, 0.0 if conf is None else conf, bool(needed)))
            judged = ex["labels"].get("skill_scores") or {}
            if roster and judged:
                scores = engine.call({"method": "rank", "head": "unit-rank", "task": ex["state"]["user"], "candidates": [cards[name] for name in roster]})["scores"]
                best = max(range(len(scores)), key=lambda i: scores[i])
                skill_tops.append((scores[best], judged.get(roster[best], 0) >= 3))
    finally:
        engine.close()

    def best_load_at(pairs):
        best = (0.0, 0.5)
        for step in range(5, 96):
            thr = step / 100
            tp = sum(1 for p, y, _ in pairs if p >= thr and y)
            fp = sum(1 for p, y, _ in pairs if p >= thr and not y)
            fn = sum(1 for p, y, _ in pairs if p < thr and y)
            score = fbeta(tp, fp, fn, args.beta)
            if score > best[0]:
                best = (score, thr)
        return best

    best = best_load_at(tool_pairs)
    print("turn:\n  tools:\n    load_at: %.2f  # F%.0f=%.3f support=%d ece=%.3f" % (
        best[1], args.beta, best[0], sum(1 for _, y, _ in tool_pairs if y), ece([(p, 1 if y else 0) for p, y, _ in tool_pairs])))
    for host in sorted({h for _, _, h in tool_pairs}):
        pairs = [pair for pair in tool_pairs if pair[2] == host]
        score, thr = best_load_at(pairs)
        print("    # %s alone: load_at %.2f, F%.0f=%.3f, support=%d" % (host, thr, args.beta, score, sum(1 for _, y, _ in pairs if y)))

    chosen = None
    for omit in range(5, 51):
        for floor in range(50, 100, 5):
            o, f = omit / 100, floor / 100
            omitted = [(needed) for p, c, needed in guide_pairs if p < o and c >= f]
            if not omitted:
                continue
            precision = sum(1 for needed in omitted if not needed) / len(omitted)
            if precision >= args.omission_precision and (chosen is None or len(omitted) > chosen[0]):
                chosen = (len(omitted), o, f, precision)
    if chosen is None:
        print("  guides:\n    # no threshold pair reaches omission precision %.2f on %d judged units; keep every unit until the head improves" % (args.omission_precision, len(guide_pairs)))
    else:
        print("  guides:\n    omit_below: %.2f\n    confidence_floor: %.2f  # omits %d of %d judged units at precision %.3f" % (
            chosen[1], chosen[2], chosen[0], len(guide_pairs), chosen[3]))
    counts = collections.Counter(needed for _, _, needed in guide_pairs)
    print("# judged units: needed=%d unneeded=%d" % (counts[True], counts[False]))

    max_loads = int(corpus.data.get("request", {}).get("max_loads", 12))
    best = None
    for step in range(50, 401, 5):
        thr = step / 100
        tp = fp = fn = 0
        for pairs in request_pairs:
            top = sorted(pairs, key=lambda x: -x[0])[:max_loads]
            loaded = [(s, y) for s, y in top if s >= thr]
            tp += sum(1 for _, y in loaded if y)
            fp += sum(1 for _, y in loaded if not y)
            fn += sum(1 for _, y in pairs if y) - sum(1 for _, y in loaded if y)
        score = fbeta(tp, fp, fn, args.beta)
        if best is None or score > best[0]:
            best = (score, thr, tp, fp, fn)
    if not request_pairs:
        print("request:\n  # no request_tools needs in the examples; load_at unchanged")
    else:
        print("request:\n  load_at: %.2f  # F%.0f=%.3f over %d needs, %.1f loads per need" % (
            best[1], args.beta, best[0], len(request_pairs), (best[2] + best[3]) / len(request_pairs)))

    chosen = None
    for step in range(100, 401):
        thr = step / 100
        preloads = [ok for top, ok in skill_tops if top >= thr]
        if not preloads:
            continue
        precision = sum(preloads) / len(preloads)
        if precision >= args.preload_precision and (chosen is None or len(preloads) > chosen[0]):
            chosen = (len(preloads), thr, precision)
    if not skill_tops:
        print("  skills:\n    # no judged skill_scores in the examples; preload_at unchanged")
    elif chosen is None:
        print("  skills:\n    # no top score reaches preload precision %.2f over %d judged turns; keep preload_at above every top score until the head improves" % (args.preload_precision, len(skill_tops)))
    else:
        print("  skills:\n    preload_at: %.2f  # preloads %d of %d judged turns at precision %.3f" % (chosen[1], chosen[0], len(skill_tops), chosen[2]))


if __name__ == "__main__":
    main()