Download training/code-rank/scripts/decide/calibrate.py from paintedwolfcode/bialy-dataset: direct link, hf CLI and curl.
- Browser
- Download file 9.28 kB
-
https://huggingface.co/datasets/paintedwolfcode/bialy-dataset/resolve/main/training/code-rank/scripts/decide/calibrate.py
- Command line
-
hf download hf://datasets/paintedwolfcode/bialy-dataset/training/code-rank/scripts/decide/calibrate.py
-
curl -L -o calibrate.py https://huggingface.co/datasets/paintedwolfcode/bialy-dataset/resolve/main/training/code-rank/scripts/decide/calibrate.py
9.28 kB
| #!/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() | |