Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
363 changes: 363 additions & 0 deletions doc/code/scoring/9_choosing_a_threshold.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,363 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "cb8f2c46",
"metadata": {},
"source": [
"# Choosing a Threshold for `FloatScaleThresholdScorer`\n",
"\n",
"`FloatScaleThresholdScorer` turns a float score into true/false: a score at or above its\n",
"`threshold` counts as true. The threshold decides how many real successes the scorer catches\n",
"(recall) and how many failures it marks as successes (false positives), and a value picked by\n",
"hand can be far from the best trade-off for a given scorer.\n",
"\n",
"`suggest_threshold` picks a threshold from scores that humans have labeled. It is opt-in and only\n",
"suggests a value; nothing changes until you create a scorer with it. It:\n",
"\n",
"1. splits the labeled responses into a tuning part and a holdout part, keeping the share of\n",
" successes the same in both,\n",
"2. tries every observed score on the tuning part and picks the one with the best F1 score, or,\n",
" with `min_precision`, the one with the best recall whose precision is at least `min_precision`,\n",
"3. applies that threshold, unchanged, to the holdout part. The holdout numbers are the ones to\n",
" trust: the tuning numbers look better than they will in practice, because the threshold was\n",
" picked to fit them.\n",
"\n",
"This example runs offline on made-up scores, so you can see the output without a model."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "46d30572",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>recall</th>\n",
" <th>precision</th>\n",
" <th>f1_score</th>\n",
" <th>false_positive</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>current (0.9)</th>\n",
" <td>0.011</td>\n",
" <td>1.00</td>\n",
" <td>0.022</td>\n",
" <td>0.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>suggested (0.33)</th>\n",
" <td>0.902</td>\n",
" <td>0.83</td>\n",
" <td>0.865</td>\n",
" <td>17.0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" recall precision f1_score false_positive\n",
"current (0.9) 0.011 1.00 0.022 0.0\n",
"suggested (0.33) 0.902 0.83 0.865 17.0"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"from pyrit.score import suggest_threshold\n",
"\n",
"rng = np.random.default_rng(0)\n",
"labels = rng.random(400) < 0.5 # True: humans say the objective was achieved\n",
"# A judge that is fairly good at ranking responses but rarely gives successes a very high score.\n",
"scores = np.clip(np.where(labels, rng.beta(4, 3, 400), rng.beta(1.2, 6, 400)), 0, 1).round(2)\n",
"\n",
"suggestion = suggest_threshold(scores=scores, labels=labels, current_threshold=0.9)\n",
"\n",
"rows = {\n",
" f\"current ({suggestion.current_threshold})\": suggestion.current_holdout_point,\n",
" f\"suggested ({suggestion.threshold})\": suggestion.holdout_point,\n",
"}\n",
"pd.DataFrame(\n",
" {\n",
" name: {\n",
" \"recall\": point.recall,\n",
" \"precision\": point.precision,\n",
" \"f1_score\": point.f1_score,\n",
" \"false_positive\": point.false_positive,\n",
" }\n",
" for name, point in rows.items()\n",
" }\n",
").T.round(3)"
]
},
{
"cell_type": "markdown",
"id": "f308c20f",
"metadata": {},
"source": [
"`operating_points` lists every candidate on the tuning split, which shows the whole\n",
"recall/false-positive trade-off rather than one number."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "540e6d72",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>threshold</th>\n",
" <th>recall</th>\n",
" <th>precision</th>\n",
" <th>false_positive</th>\n",
" <th>false_negative</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>0.01</td>\n",
" <td>1.000</td>\n",
" <td>0.462</td>\n",
" <td>106</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>8</th>\n",
" <td>0.10</td>\n",
" <td>1.000</td>\n",
" <td>0.535</td>\n",
" <td>79</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>16</th>\n",
" <td>0.18</td>\n",
" <td>0.989</td>\n",
" <td>0.672</td>\n",
" <td>44</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>24</th>\n",
" <td>0.27</td>\n",
" <td>0.967</td>\n",
" <td>0.772</td>\n",
" <td>26</td>\n",
" <td>3</td>\n",
" </tr>\n",
" <tr>\n",
" <th>32</th>\n",
" <td>0.37</td>\n",
" <td>0.857</td>\n",
" <td>0.857</td>\n",
" <td>13</td>\n",
" <td>13</td>\n",
" </tr>\n",
" <tr>\n",
" <th>40</th>\n",
" <td>0.46</td>\n",
" <td>0.703</td>\n",
" <td>0.877</td>\n",
" <td>9</td>\n",
" <td>27</td>\n",
" </tr>\n",
" <tr>\n",
" <th>48</th>\n",
" <td>0.55</td>\n",
" <td>0.549</td>\n",
" <td>0.943</td>\n",
" <td>3</td>\n",
" <td>41</td>\n",
" </tr>\n",
" <tr>\n",
" <th>56</th>\n",
" <td>0.66</td>\n",
" <td>0.374</td>\n",
" <td>0.971</td>\n",
" <td>1</td>\n",
" <td>57</td>\n",
" </tr>\n",
" <tr>\n",
" <th>64</th>\n",
" <td>0.77</td>\n",
" <td>0.198</td>\n",
" <td>1.000</td>\n",
" <td>0</td>\n",
" <td>73</td>\n",
" </tr>\n",
" <tr>\n",
" <th>72</th>\n",
" <td>0.90</td>\n",
" <td>0.055</td>\n",
" <td>1.000</td>\n",
" <td>0</td>\n",
" <td>86</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" threshold recall precision false_positive false_negative\n",
"0 0.01 1.000 0.462 106 0\n",
"8 0.10 1.000 0.535 79 0\n",
"16 0.18 0.989 0.672 44 1\n",
"24 0.27 0.967 0.772 26 3\n",
"32 0.37 0.857 0.857 13 13\n",
"40 0.46 0.703 0.877 9 27\n",
"48 0.55 0.549 0.943 3 41\n",
"56 0.66 0.374 0.971 1 57\n",
"64 0.77 0.198 1.000 0 73\n",
"72 0.90 0.055 1.000 0 86"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.DataFrame([vars(point) for point in suggestion.operating_points])[\n",
" [\"threshold\", \"recall\", \"precision\", \"false_positive\", \"false_negative\"]\n",
"].iloc[::8].round(3)"
]
},
{
"cell_type": "markdown",
"id": "e08d7e34",
"metadata": {},
"source": [
"If false positives matter more than missed successes, set a precision floor instead of\n",
"maximizing F1:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4136dd30",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"threshold=0.6, holdout recall=0.500, holdout precision=1.000\n"
]
}
],
"source": [
"strict = suggest_threshold(scores=scores, labels=labels, min_precision=0.95)\n",
"print(\n",
" f\"threshold={strict.threshold}, holdout recall={strict.holdout_point.recall:.3f}, \"\n",
" f\"holdout precision={strict.holdout_point.precision:.3f}\"\n",
")"
]
},
{
"cell_type": "markdown",
"id": "6f1709f0",
"metadata": {},
"source": [
"## With a real scorer\n",
"\n",
"`suggest_threshold_async` scores an OBJECTIVE `HumanLabeledDataset` with your\n",
"`FloatScaleThresholdScorer` and keeps the float value behind each true/false verdict, so you do\n",
"not need to collect the scores yourself. The scorer's own threshold is reported as\n",
"`current_threshold`. With `num_scorer_trials` above 1, every trial is counted, so the numbers\n",
"describe a single scoring run, which is how the scorer is used in an attack.\n",
"\n",
"```python\n",
"from pyrit.common.path import SCORER_EVALS_PATH\n",
"from pyrit.prompt_target import OpenAIChatTarget\n",
"from pyrit.score import (\n",
" FloatScaleThresholdScorer,\n",
" HumanLabeledDataset,\n",
" MetricsType,\n",
" SelfAskScaleScorer,\n",
" suggest_threshold_async,\n",
")\n",
"\n",
"judge = SelfAskScaleScorer.from_scale(chat_target=OpenAIChatTarget())\n",
"scorer = FloatScaleThresholdScorer(scorer=judge, threshold=0.9)\n",
"dataset = HumanLabeledDataset.from_csv(\n",
" csv_path=SCORER_EVALS_PATH / \"objective\" / \"cyber.csv\", metrics_type=MetricsType.OBJECTIVE\n",
")\n",
"\n",
"suggestion = await suggest_threshold_async(scorer=scorer, labeled_dataset=dataset, num_scorer_trials=3)\n",
"print(suggestion.threshold, suggestion.holdout_point)\n",
"\n",
"tuned_scorer = FloatScaleThresholdScorer(scorer=judge, threshold=suggestion.threshold)\n",
"```\n",
"\n",
"A threshold tuned on one dataset fits that dataset's mix of objectives and responses. Check the\n",
"holdout numbers, and tune again when the judge model, rubric, or kind of objective changes."
]
}
],
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading
Loading