diff --git a/doc/code/scoring/2_float_scale_scorers.ipynb b/doc/code/scoring/2_float_scale_scorers.ipynb index ac4756fa46..038e5c0f34 100644 --- a/doc/code/scoring/2_float_scale_scorers.ipynb +++ b/doc/code/scoring/2_float_scale_scorers.ipynb @@ -447,7 +447,8 @@ "and evaluate it on independent data before relying on its scores.\n", "\n", "This example disables abstention and uses `FloatScaleThresholdScorer` to report both the local\n", - "numeric score and a boolean verdict. The `0.5` threshold is for demonstration; validate it on your own data.\n", + "numeric score and a boolean verdict. The `0.5` threshold is for demonstration; validate it on your own data\n", + "as in [Objective Metrics for Float-Scale Scorers](./float_scale_threshold_metrics.ipynb).\n", "All scoring below runs locally, without an LLM judge." ] }, diff --git a/doc/code/scoring/2_float_scale_scorers.py b/doc/code/scoring/2_float_scale_scorers.py index 0b2ac803f8..8b67229d16 100644 --- a/doc/code/scoring/2_float_scale_scorers.py +++ b/doc/code/scoring/2_float_scale_scorers.py @@ -252,7 +252,8 @@ # and evaluate it on independent data before relying on its scores. # # This example disables abstention and uses `FloatScaleThresholdScorer` to report both the local -# numeric score and a boolean verdict. The `0.5` threshold is for demonstration; validate it on your own data. +# numeric score and a boolean verdict. The `0.5` threshold is for demonstration; validate it on your own data +# as in [Objective Metrics for Float-Scale Scorers](./float_scale_threshold_metrics.ipynb). # All scoring below runs locally, without an LLM judge. # %% diff --git a/doc/code/scoring/3_combining_scorers.ipynb b/doc/code/scoring/3_combining_scorers.ipynb index 890d2a4fc6..03c8f04b2b 100644 --- a/doc/code/scoring/3_combining_scorers.ipynb +++ b/doc/code/scoring/3_combining_scorers.ipynb @@ -257,7 +257,8 @@ "\n", "`FloatScaleThresholdScorer` wraps a `FloatScaleScorer` and returns True when the\n", "normalized score meets the threshold. This is the standard way to turn a severity score\n", - "into a pass/fail success criterion. Below it wraps the local `PlagiarismScorer`." + "into a pass/fail success criterion. Below it wraps the local `PlagiarismScorer`. To choose the\n", + "threshold from human-labeled data, see [Objective Metrics for Float-Scale Scorers](./float_scale_threshold_metrics.ipynb)." ] }, { diff --git a/doc/code/scoring/3_combining_scorers.py b/doc/code/scoring/3_combining_scorers.py index b1968bf11e..1ee7658b3b 100644 --- a/doc/code/scoring/3_combining_scorers.py +++ b/doc/code/scoring/3_combining_scorers.py @@ -160,7 +160,8 @@ # # `FloatScaleThresholdScorer` wraps a `FloatScaleScorer` and returns True when the # normalized score meets the threshold. This is the standard way to turn a severity score -# into a pass/fail success criterion. Below it wraps the local `PlagiarismScorer`. +# into a pass/fail success criterion. Below it wraps the local `PlagiarismScorer`. To choose the +# threshold from human-labeled data, see [Objective Metrics for Float-Scale Scorers](./float_scale_threshold_metrics.ipynb). # %% from pyrit.score import FloatScaleThresholdScorer, PlagiarismScorer diff --git a/doc/code/scoring/4_scorer_metrics.ipynb b/doc/code/scoring/4_scorer_metrics.ipynb index 5fa00dc649..eaee1fcd5f 100644 --- a/doc/code/scoring/4_scorer_metrics.ipynb +++ b/doc/code/scoring/4_scorer_metrics.ipynb @@ -109,7 +109,11 @@ "**Which metric matters most?**\n", "- If false positives are costly (e.g., flagging safe content as harmful) → prioritize **precision**\n", "- If false negatives are costly (e.g., missing actual jailbreaks) → prioritize **recall**\n", - "- For balanced scenarios → use **F1 score**" + "- For balanced scenarios → use **F1 score**\n", + "\n", + "For a float-scale scorer wrapped in a `FloatScaleThresholdScorer`, all of these metrics depend on the\n", + "threshold. To measure them at every threshold and choose one from human labels, see\n", + "[Objective Metrics for Float-Scale Scorers](./float_scale_threshold_metrics.ipynb)." ] }, { diff --git a/doc/code/scoring/4_scorer_metrics.py b/doc/code/scoring/4_scorer_metrics.py index b53189ba0a..740cfaeaca 100644 --- a/doc/code/scoring/4_scorer_metrics.py +++ b/doc/code/scoring/4_scorer_metrics.py @@ -73,6 +73,10 @@ # - If false positives are costly (e.g., flagging safe content as harmful) → prioritize **precision** # - If false negatives are costly (e.g., missing actual jailbreaks) → prioritize **recall** # - For balanced scenarios → use **F1 score** +# +# For a float-scale scorer wrapped in a `FloatScaleThresholdScorer`, all of these metrics depend on the +# threshold. To measure them at every threshold and choose one from human labels, see +# [Objective Metrics for Float-Scale Scorers](./float_scale_threshold_metrics.ipynb). # %% [markdown] # ### Harm Metrics diff --git a/doc/code/scoring/float_scale_threshold_metrics.ipynb b/doc/code/scoring/float_scale_threshold_metrics.ipynb new file mode 100644 index 0000000000..55ce3ea560 --- /dev/null +++ b/doc/code/scoring/float_scale_threshold_metrics.ipynb @@ -0,0 +1,706 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "c5d27562", + "metadata": {}, + "source": [ + "# Objective Metrics for Float-Scale Scorers: Choosing a Threshold\n", + "\n", + "[Scorer metrics](./4_scorer_metrics.ipynb) compare an objective scorer's true/false verdicts with\n", + "human labels. Many objective scorers are float-scale scorers, such as `SelfAskScaleScorer`, wrapped\n", + "in a `FloatScaleThresholdScorer`: a score at or above its `threshold` counts as true. Their\n", + "precision, recall, and F1 therefore depend on the threshold, and `evaluate_async` measures only the\n", + "one the scorer uses now. A threshold picked by hand can miss most real successes, or flag many\n", + "failures as successes.\n", + "\n", + "`suggest_threshold` and `suggest_threshold_async` measure those metrics at every threshold the float\n", + "scores support, on human-labeled data, and suggest one. They only suggest a value: nothing changes\n", + "until you create a `FloatScaleThresholdScorer` with it, which you can then evaluate and record like\n", + "any other scorer.\n", + "\n", + "The suggestion is made in three steps:\n", + "\n", + "1. Split the labeled responses into a tuning part and a holdout part, keeping the share of\n", + " successes the same in both.\n", + "2. On the tuning part, try every nonzero observed score as the threshold and pick the one with the best F1,\n", + " or, with `min_precision`, the best recall among those whose precision is at least `min_precision`.\n", + "3. Apply that threshold, unchanged, to the holdout part. The holdout metrics are the ones to trust:\n", + " the tuning metrics look better than they will in practice, because the threshold was picked to\n", + " fit them." + ] + }, + { + "cell_type": "markdown", + "id": "5e825c0e", + "metadata": {}, + "source": [ + "## How the threshold changes the metrics\n", + "\n", + "`suggest_threshold` works on float scores and human labels you already have, for example from an\n", + "earlier run, and needs no model. The scores below are made up: 400 responses from a judge that ranks\n", + "responses fairly well but rarely gives a success a very high score. The comparison is on the holdout\n", + "responses, which the choice never saw." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "06f55e40", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
recallprecisionf1_scoretrue_positivefalse_positive
current (0.9)0.0111.000.02210
suggested (0.33)0.9020.830.8658317
\n", + "
" + ], + "text/plain": [ + " recall precision f1_score true_positive false_positive\n", + "current (0.9) 0.011 1.00 0.022 1 0\n", + "suggested (0.33) 0.902 0.83 0.865 83 17" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "from pyrit.score import ThresholdSuggestion, 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", + "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", + "\n", + "def holdout_comparison(suggestion: ThresholdSuggestion) -> pd.DataFrame:\n", + " \"\"\"Show the current and suggested thresholds on the holdout responses.\"\"\"\n", + " rows = {\n", + " f\"current ({suggestion.current_threshold})\": suggestion.current_holdout_point,\n", + " f\"suggested ({suggestion.threshold})\": suggestion.holdout_point,\n", + " }\n", + " columns = [\"recall\", \"precision\", \"f1_score\", \"true_positive\", \"false_positive\"]\n", + " return pd.DataFrame.from_dict(\n", + " {name: {column: getattr(point, column) for column in columns} for name, point in rows.items()},\n", + " orient=\"index\",\n", + " ).round(3)\n", + "\n", + "\n", + "holdout_comparison(suggestion)" + ] + }, + { + "cell_type": "markdown", + "id": "e0866e44", + "metadata": {}, + "source": [ + "`operating_points` lists the metrics at every candidate threshold on the tuning split, which shows\n", + "the whole recall/false-positive trade-off rather than one number:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e577829d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
thresholdrecallprecisionfalse_positivefalse_negative
00.011.0000.4621060
80.101.0000.535790
160.180.9890.672441
240.270.9670.772263
320.370.8570.8571313
400.460.7030.877927
480.550.5490.943341
560.660.3740.971157
640.770.1981.000073
720.900.0551.000086
\n", + "
" + ], + "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": "76bfe2f6", + "metadata": {}, + "source": [ + "If false positives matter more than missed successes, set a precision floor instead of maximizing\n", + "F1:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "905a6077", + "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": "d8631c63", + "metadata": {}, + "source": [ + "## Tuning a scorer's threshold\n", + "\n", + "`suggest_threshold_async` scores an OBJECTIVE `HumanLabeledDataset` with your\n", + "`FloatScaleThresholdScorer`, keeps the float value behind each true/false verdict, and suggests a\n", + "threshold from those. It takes the same `min_precision`, `holdout_fraction`, and `seed` arguments,\n", + "and reports the scorer's own threshold as `current_threshold`.\n", + "\n", + "This example scores the packaged `bias.csv` objective dataset (30 labeled responses) once, with the\n", + "`SelfAskScaleScorer` judge and 0.9 threshold that PyRIT registers as a scale scorer." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "418d0bb9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found default environment files: ['./.pyrit/.env.local']\n", + "Loaded environment file: ./.pyrit/.env.local\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Skipping target 'open_router': OPEN_ROUTER_CLAUDE_MODEL is not set. All declared env vars (endpoint, key, model) must be present for this target to register.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "tuned on 16 responses, checked on 14, left out 0 without a score\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
recallprecisionf1_scoretrue_positivefalse_positive
current (0.9)0.3331.00.50020
suggested (0.6666666666666666)0.5001.00.66730
\n", + "
" + ], + "text/plain": [ + " recall precision f1_score true_positive \\\n", + "current (0.9) 0.333 1.0 0.500 2 \n", + "suggested (0.6666666666666666) 0.500 1.0 0.667 3 \n", + "\n", + " false_positive \n", + "current (0.9) 0 \n", + "suggested (0.6666666666666666) 0 " + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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", + "from pyrit.setup import IN_MEMORY, initialize_pyrit_async\n", + "\n", + "await initialize_pyrit_async(memory_db_type=IN_MEMORY) # type: ignore\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\" / \"bias.csv\", metrics_type=MetricsType.OBJECTIVE\n", + ")\n", + "\n", + "judge_suggestion = await suggest_threshold_async(scorer=scorer, labeled_dataset=dataset) # type: ignore\n", + "\n", + "print(\n", + " f\"tuned on {judge_suggestion.num_tuning_responses} responses, \"\n", + " f\"checked on {judge_suggestion.num_holdout_responses}, \"\n", + " f\"left out {judge_suggestion.num_excluded_responses} without a score\"\n", + ")\n", + "holdout_comparison(judge_suggestion)" + ] + }, + { + "cell_type": "markdown", + "id": "78b97557", + "metadata": {}, + "source": [ + "The candidate thresholds are the distinct nonzero scores the judge gave on the tuning split:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "93c1094a", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
thresholdrecallprecisiontrue_positivefalse_positive
00.66666666666666660.5711.040
10.77777777777777780.4291.030
21.00.2861.020
\n", + "
" + ], + "text/plain": [ + " threshold recall precision true_positive false_positive\n", + "0 0.6666666666666666 0.571 1.0 4 0\n", + "1 0.7777777777777778 0.429 1.0 3 0\n", + "2 1.0 0.286 1.0 2 0" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pd.DataFrame([vars(point) for point in judge_suggestion.operating_points])[\n", + " [\"threshold\", \"recall\", \"precision\", \"true_positive\", \"false_positive\"]\n", + "].round({\"recall\": 3, \"precision\": 3}).astype({\"threshold\": str})" + ] + }, + { + "cell_type": "markdown", + "id": "9b60d5e5", + "metadata": {}, + "source": [ + "### Reading the result\n", + "\n", + "- **Few candidates are normal.** An LLM judge often uses only a few points of its scale, so there may\n", + " be only a few thresholds to choose from. Any value between two neighboring candidates behaves like\n", + " the higher one.\n", + "- **Use the exact threshold.** The suggestion is one of the judge's scores, such as 7/9 on a 1-10\n", + " scale. Rounding it up, for example from 0.7777… to 0.778, turns every response the judge scored at\n", + " that level false.\n", + "- **Compare the two rows.** They are measured on the same held-out responses. If the suggested\n", + " threshold does not do better there, keep the current one.\n", + "- **Watch the sample size.** A holdout of about 15 responses moves a lot when one response changes\n", + " side, so treat a result this small as a direction rather than a measurement.\n", + "\n", + "The suggestion keeps the judge's scores and the gold labels, so you can try another split, a\n", + "`min_precision`, or a `holdout_fraction` with `suggest_threshold` without scoring again. A different\n", + "split shows how much a small dataset moves the result:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8472794d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
recallprecisionf1_scoretrue_positivefalse_positive
current (0.9)0.5001.00.66730
suggested (0.6666666666666666)0.6671.00.80040
\n", + "
" + ], + "text/plain": [ + " recall precision f1_score true_positive \\\n", + "current (0.9) 0.500 1.0 0.667 3 \n", + "suggested (0.6666666666666666) 0.667 1.0 0.800 4 \n", + "\n", + " false_positive \n", + "current (0.9) 0 \n", + "suggested (0.6666666666666666) 0 " + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "resplit = suggest_threshold(\n", + " scores=judge_suggestion.scores,\n", + " labels=judge_suggestion.labels,\n", + " current_threshold=judge_suggestion.current_threshold,\n", + " seed=1,\n", + ")\n", + "holdout_comparison(resplit)" + ] + }, + { + "cell_type": "markdown", + "id": "2da6f425", + "metadata": {}, + "source": [ + "For a threshold you rely on, tune on a larger dataset, and pass `num_scorer_trials` above 1 so the\n", + "judge's run-to-run variation is included. Every trial is counted, so the metrics describe a single\n", + "scoring run, which is how the scorer is used in an attack, and the true and false positive counts are\n", + "counts of trials. A threshold fits the dataset it was tuned on; tune again when the judge model,\n", + "rubric, or kind of objective changes.\n", + "\n", + "To use a suggestion, create a new scorer with it. The original scorer is not changed, and the new one\n", + "can be evaluated and recorded as shown in [scorer metrics](./4_scorer_metrics.ipynb):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "34570ea0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.6666666666666666\n" + ] + } + ], + "source": [ + "tuned_scorer = FloatScaleThresholdScorer(scorer=judge, threshold=judge_suggestion.threshold)\n", + "print(tuned_scorer.threshold)" + ] + } + ], + "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.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/code/scoring/float_scale_threshold_metrics.py b/doc/code/scoring/float_scale_threshold_metrics.py new file mode 100644 index 0000000000..41e7698a21 --- /dev/null +++ b/doc/code/scoring/float_scale_threshold_metrics.py @@ -0,0 +1,179 @@ +# --- +# jupyter: +# jupytext: +# text_representation: +# extension: .py +# format_name: percent +# format_version: '1.3' +# jupytext_version: 1.19.4 +# --- + +# %% [markdown] +# # Objective Metrics for Float-Scale Scorers: Choosing a Threshold +# +# [Scorer metrics](./4_scorer_metrics.ipynb) compare an objective scorer's true/false verdicts with +# human labels. Many objective scorers are float-scale scorers, such as `SelfAskScaleScorer`, wrapped +# in a `FloatScaleThresholdScorer`: a score at or above its `threshold` counts as true. Their +# precision, recall, and F1 therefore depend on the threshold, and `evaluate_async` measures only the +# one the scorer uses now. A threshold picked by hand can miss most real successes, or flag many +# failures as successes. +# +# `suggest_threshold` and `suggest_threshold_async` measure those metrics at every threshold the float +# scores support, on human-labeled data, and suggest one. They only suggest a value: nothing changes +# until you create a `FloatScaleThresholdScorer` with it, which you can then evaluate and record like +# any other scorer. +# +# The suggestion is made in three steps: +# +# 1. Split the labeled responses into a tuning part and a holdout part, keeping the share of +# successes the same in both. +# 2. On the tuning part, try every nonzero observed score as the threshold and pick the one with the best F1, +# or, with `min_precision`, the best recall among those whose precision is at least `min_precision`. +# 3. Apply that threshold, unchanged, to the holdout part. The holdout metrics are the ones to trust: +# the tuning metrics look better than they will in practice, because the threshold was picked to +# fit them. + +# %% [markdown] +# ## How the threshold changes the metrics +# +# `suggest_threshold` works on float scores and human labels you already have, for example from an +# earlier run, and needs no model. The scores below are made up: 400 responses from a judge that ranks +# responses fairly well but rarely gives a success a very high score. The comparison is on the holdout +# responses, which the choice never saw. + +# %% +import numpy as np +import pandas as pd + +from pyrit.score import ThresholdSuggestion, suggest_threshold + +rng = np.random.default_rng(0) +labels = rng.random(400) < 0.5 # True: humans say the objective was achieved +scores = np.clip(np.where(labels, rng.beta(4, 3, 400), rng.beta(1.2, 6, 400)), 0, 1).round(2) + +suggestion = suggest_threshold(scores=scores, labels=labels, current_threshold=0.9) + + +def holdout_comparison(suggestion: ThresholdSuggestion) -> pd.DataFrame: + """Show the current and suggested thresholds on the holdout responses.""" + rows = { + f"current ({suggestion.current_threshold})": suggestion.current_holdout_point, + f"suggested ({suggestion.threshold})": suggestion.holdout_point, + } + columns = ["recall", "precision", "f1_score", "true_positive", "false_positive"] + return pd.DataFrame.from_dict( + {name: {column: getattr(point, column) for column in columns} for name, point in rows.items()}, + orient="index", + ).round(3) + + +holdout_comparison(suggestion) + +# %% [markdown] +# `operating_points` lists the metrics at every candidate threshold on the tuning split, which shows +# the whole recall/false-positive trade-off rather than one number: + +# %% +pd.DataFrame([vars(point) for point in suggestion.operating_points])[ + ["threshold", "recall", "precision", "false_positive", "false_negative"] +].iloc[::8].round(3) + +# %% [markdown] +# If false positives matter more than missed successes, set a precision floor instead of maximizing +# F1: + +# %% +strict = suggest_threshold(scores=scores, labels=labels, min_precision=0.95) +print( + f"threshold={strict.threshold}, holdout recall={strict.holdout_point.recall:.3f}, " + f"holdout precision={strict.holdout_point.precision:.3f}" +) + +# %% [markdown] +# ## Tuning a scorer's threshold +# +# `suggest_threshold_async` scores an OBJECTIVE `HumanLabeledDataset` with your +# `FloatScaleThresholdScorer`, keeps the float value behind each true/false verdict, and suggests a +# threshold from those. It takes the same `min_precision`, `holdout_fraction`, and `seed` arguments, +# and reports the scorer's own threshold as `current_threshold`. +# +# This example scores the packaged `bias.csv` objective dataset (30 labeled responses) once, with the +# `SelfAskScaleScorer` judge and 0.9 threshold that PyRIT registers as a scale scorer. + +# %% +from pyrit.common.path import SCORER_EVALS_PATH +from pyrit.prompt_target import OpenAIChatTarget +from pyrit.score import ( + FloatScaleThresholdScorer, + HumanLabeledDataset, + MetricsType, + SelfAskScaleScorer, + suggest_threshold_async, +) +from pyrit.setup import IN_MEMORY, initialize_pyrit_async + +await initialize_pyrit_async(memory_db_type=IN_MEMORY) # type: ignore + +judge = SelfAskScaleScorer.from_scale(chat_target=OpenAIChatTarget()) +scorer = FloatScaleThresholdScorer(scorer=judge, threshold=0.9) +dataset = HumanLabeledDataset.from_csv( + csv_path=SCORER_EVALS_PATH / "objective" / "bias.csv", metrics_type=MetricsType.OBJECTIVE +) + +judge_suggestion = await suggest_threshold_async(scorer=scorer, labeled_dataset=dataset) # type: ignore + +print( + f"tuned on {judge_suggestion.num_tuning_responses} responses, " + f"checked on {judge_suggestion.num_holdout_responses}, " + f"left out {judge_suggestion.num_excluded_responses} without a score" +) +holdout_comparison(judge_suggestion) + +# %% [markdown] +# The candidate thresholds are the distinct nonzero scores the judge gave on the tuning split: + +# %% +pd.DataFrame([vars(point) for point in judge_suggestion.operating_points])[ + ["threshold", "recall", "precision", "true_positive", "false_positive"] +].round({"recall": 3, "precision": 3}).astype({"threshold": str}) + +# %% [markdown] +# ### Reading the result +# +# - **Few candidates are normal.** An LLM judge often uses only a few points of its scale, so there may +# be only a few thresholds to choose from. Any value between two neighboring candidates behaves like +# the higher one. +# - **Use the exact threshold.** The suggestion is one of the judge's scores, such as 7/9 on a 1-10 +# scale. Rounding it up, for example from 0.7777… to 0.778, turns every response the judge scored at +# that level false. +# - **Compare the two rows.** They are measured on the same held-out responses. If the suggested +# threshold does not do better there, keep the current one. +# - **Watch the sample size.** A holdout of about 15 responses moves a lot when one response changes +# side, so treat a result this small as a direction rather than a measurement. +# +# The suggestion keeps the judge's scores and the gold labels, so you can try another split, a +# `min_precision`, or a `holdout_fraction` with `suggest_threshold` without scoring again. A different +# split shows how much a small dataset moves the result: + +# %% +resplit = suggest_threshold( + scores=judge_suggestion.scores, + labels=judge_suggestion.labels, + current_threshold=judge_suggestion.current_threshold, + seed=1, +) +holdout_comparison(resplit) + +# %% [markdown] +# For a threshold you rely on, tune on a larger dataset, and pass `num_scorer_trials` above 1 so the +# judge's run-to-run variation is included. Every trial is counted, so the metrics describe a single +# scoring run, which is how the scorer is used in an attack, and the true and false positive counts are +# counts of trials. A threshold fits the dataset it was tuned on; tune again when the judge model, +# rubric, or kind of objective changes. +# +# To use a suggestion, create a new scorer with it. The original scorer is not changed, and the new one +# can be evaluated and recorded as shown in [scorer metrics](./4_scorer_metrics.ipynb): + +# %% +tuned_scorer = FloatScaleThresholdScorer(scorer=judge, threshold=judge_suggestion.threshold) +print(tuned_scorer.threshold) diff --git a/doc/myst.yml b/doc/myst.yml index 3f7ef5f909..e668d15584 100644 --- a/doc/myst.yml +++ b/doc/myst.yml @@ -198,6 +198,7 @@ project: - file: code/scoring/6_file_write_scorer.ipynb - file: code/scoring/7_program_execution_scorer.ipynb - file: code/scoring/8_trace_evidence_scoring.ipynb + - file: code/scoring/float_scale_threshold_metrics.ipynb - file: code/scoring/scorer_stability.md - file: code/memory/0_memory.md children: diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index 2870d9df55..209055626f 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -113,6 +113,12 @@ ScorerStabilityMetrics, compute_scorer_stability, ) + from pyrit.score.scorer_evaluation.threshold_suggestion import ( + ThresholdOperatingPoint, + ThresholdSuggestion, + suggest_threshold, + suggest_threshold_async, + ) from pyrit.score.scorer_info import get_scorer_info from pyrit.score.scorer_prompt_validator import ScorerPromptValidator from pyrit.score.scorer_selection import ( @@ -387,6 +393,10 @@ "get_all_objective_metrics": "pyrit.score.scorer_evaluation.scorer_metrics_io", "get_scorer_info": "pyrit.score.scorer_info", "find_objective_metrics_by_eval_hash": "pyrit.score.scorer_evaluation.scorer_metrics_io", + "ThresholdOperatingPoint": "pyrit.score.scorer_evaluation.threshold_suggestion", + "ThresholdSuggestion": "pyrit.score.scorer_evaluation.threshold_suggestion", + "suggest_threshold": "pyrit.score.scorer_evaluation.threshold_suggestion", + "suggest_threshold_async": "pyrit.score.scorer_evaluation.threshold_suggestion", "ScorerPromptValidator": "pyrit.score.scorer_prompt_validator", "SelfAskCategoryScorer": "pyrit.score.true_false.self_ask_category_scorer", "SelfAskGeneralFloatScaleScorer": "pyrit.score.float_scale.self_ask_general_float_scale_scorer", diff --git a/pyrit/score/scorer_evaluation/scorer_evaluator.py b/pyrit/score/scorer_evaluation/scorer_evaluator.py index 202b05d96c..7b1ad278fa 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -33,7 +33,7 @@ from pyrit.score.true_false.true_false_scorer import TrueFalseScorer if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Callable, Sequence from pathlib import Path from pyrit.models import Message @@ -60,14 +60,66 @@ def _validate_num_scorer_trials(num_scorer_trials: int) -> None: raise ValueError(f"num_scorer_trials must be at least 1, got {num_scorer_trials}.") +def _classification_rates( + *, true_positive: int, false_positive: int, true_negative: int, false_negative: int +) -> tuple[float, float, float, float | None]: + """ + Compute precision, recall, F1 and specificity from confusion counts. + + Args: + true_positive (int): Correct positive predictions. + false_positive (int): Incorrect positive predictions. + true_negative (int): Correct negative predictions. + false_negative (int): Incorrect negative predictions. + + Returns: + tuple[float, float, float, float | None]: Precision, recall, F1 and specificity. + """ + precision = true_positive / (true_positive + false_positive) if true_positive + false_positive else 0.0 + recall = true_positive / (true_positive + false_negative) if true_positive + false_negative else 0.0 + f1_score = 2 * true_positive / (2 * true_positive + false_positive + false_negative) if true_positive else 0.0 + specificity = true_negative / (true_negative + false_positive) if true_negative + false_positive else None + return precision, recall, f1_score, specificity + + +def _human_score_matrix(human_scores_list: Sequence[Sequence[float]]) -> np.ndarray: + """ + Arrange per-response human scores as one row per rater. + + Args: + human_scores_list (Sequence[Sequence[float]]): The human scores of each response. + + Returns: + np.ndarray: Scores of shape ``(num_raters, num_responses)``. + + Raises: + ValueError: If the responses have different numbers of human scores (NumPy rejects the + inhomogeneous shape). + """ + return np.array(human_scores_list).T + + +def _majority_vote(scores: np.ndarray) -> np.ndarray: + """ + Take the majority vote of binary scores along the first axis; a split vote is 0 (false). + + Args: + scores (np.ndarray): Binary scores of shape ``(num_votes, num_responses)``. + + Returns: + np.ndarray: The majority vote of each response. + """ + return np.round(np.median(scores, axis=0)) + + @dataclass(frozen=True, kw_only=True) class ScoringTrials: """ Every verdict from scoring the same responses several times. Attributes: - scores (np.ndarray): Verdicts of shape ``(num_trials, num_responses)``. An undetermined - verdict holds a placeholder (false, or 0.0 for harm scores). + scores (np.ndarray): Values of shape ``(num_trials, num_responses)``, using verdicts by + default. An undetermined value holds a placeholder (false, or 0.0 for harm scores). undetermined (np.ndarray): Booleans of the same shape, true where no verdict was reached. total_scoring_time (float): Seconds spent scoring. total_scored_items (int): Responses scored, summed over trials. @@ -476,9 +528,8 @@ async def evaluate_dataset_async( for response in assistant_responses ] - # Transpose human scores so each row is a complete set of scores across all responses. # Built before scoring, so ragged human scores fail before any scoring call is paid for. - all_human_scores = np.array(human_scores_list).T + all_human_scores = _human_score_matrix(human_scores_list) harm_category = None if labeled_dataset.metrics_type == MetricsType.HARM and labeled_dataset.entries: @@ -513,6 +564,7 @@ async def _run_scoring_trials_async( harm_category: str | None, num_scorer_trials: int, max_concurrency: int, + read_value: Callable[[Score], float | None] | None = None, ) -> ScoringTrials: """ Score every response ``num_scorer_trials`` times and keep each verdict. @@ -526,6 +578,8 @@ async def _run_scoring_trials_async( harm_category (str | None): The labeled harm category, for harm datasets. num_scorer_trials (int): The number of trials. max_concurrency (int): Maximum number of concurrent scoring requests. + read_value (Callable[[Score], float | None] | None): Read another value from a determined + score, or return None to mark it undetermined. Defaults to the verdict. Returns: ScoringTrials: Every verdict, which were undetermined, and the scoring time. @@ -544,9 +598,10 @@ async def _run_scoring_trials_async( total_scored_items += len(score_groups) score_values: list[bool | float] = [] for index, scores in enumerate(score_groups): - value = self._determined_value( - self._select_evaluation_score(scores=scores, harm_category=harm_category) - ) + score = self._select_evaluation_score(scores=scores, harm_category=harm_category) + value = self._determined_value(score) + if value is not None and read_value is not None and score is not None: + value = read_value(score) if value is None: undetermined[trial, index] = True value = placeholder @@ -727,6 +782,23 @@ def _select_evaluation_score(*, scores: list[Score], harm_category: str | None) f"but received {len(scores)} scores and found {len(category_matches)} category matches." ) + async def _add_conversation_to_memory_async(self, conversation: Sequence[Message]) -> None: + """ + Store a dataset conversation in memory, skipping messages that are already stored. + + Dataset entries keep fixed piece IDs, so scoring the same dataset object again + must not insert its messages a second time. + + Args: + conversation (Sequence[Message]): The messages of one dataset entry. + """ + memory = self.scorer._memory + piece_ids = [piece.id for message in conversation for piece in message.message_pieces] + stored = {str(piece.id) for piece in await memory.get_message_pieces_async(prompt_ids=piece_ids)} + for message in conversation: + if not any(str(piece.id) in stored for piece in message.message_pieces): + await memory.add_message_to_memory_async(request=message) + @abc.abstractmethod async def _validate_and_extract_data_async( self, @@ -840,11 +912,8 @@ async def _validate_and_extract_data_async( for entry in labeled_dataset.entries: harm_entry = cast("HarmHumanLabeledEntry", entry) - assistant_messages: list[Message] = [] - for message in harm_entry.conversation: - (await self.scorer._memory.add_message_to_memory_async(request=message)) - if message.api_role == "assistant": - assistant_messages.append(message) + await self._add_conversation_to_memory_async(harm_entry.conversation) + assistant_messages = [message for message in harm_entry.conversation if message.api_role == "assistant"] if len(assistant_messages) != 1: raise ValueError( "Each HarmHumanLabeledEntry must contain exactly one assistant message, " @@ -1032,11 +1101,10 @@ async def _validate_and_extract_data_async( for entry in labeled_dataset.entries: objective_entry = cast("ObjectiveHumanLabeledEntry", entry) - assistant_messages: list[Message] = [] - for message in objective_entry.conversation: - await self.scorer._memory.add_message_to_memory_async(request=message) - if message.api_role == "assistant": - assistant_messages.append(message) + await self._add_conversation_to_memory_async(objective_entry.conversation) + assistant_messages = [ + message for message in objective_entry.conversation if message.api_role == "assistant" + ] if len(assistant_messages) != 1: raise ValueError( "Each ObjectiveHumanLabeledEntry must contain exactly one assistant message, " @@ -1062,20 +1130,20 @@ def _compute_metrics( ) -> ObjectiveScorerMetrics: # Calculate the majority vote of human scores for each response, which is considered the gold label. # If the vote is split, the resulting gold score will be 0 (i.e. False). Same logic is applied to model trials. - gold_scores = np.round(np.median(all_human_scores, axis=0)) - majority_model_scores = np.round(np.median(all_model_scores, axis=0)) + gold_scores = _majority_vote(all_human_scores) + majority_model_scores = _majority_vote(all_model_scores) true_positive = int(np.sum((gold_scores == 1) & (majority_model_scores == 1))) false_positive = int(np.sum((gold_scores == 0) & (majority_model_scores == 1))) true_negative = int(np.sum((gold_scores == 0) & (majority_model_scores == 0))) false_negative = int(np.sum((gold_scores == 1) & (majority_model_scores == 0))) accuracy = (true_positive + true_negative) / gold_scores.size - precision = true_positive / (true_positive + false_positive) if (true_positive + false_positive) > 0 else 0.0 - recall = true_positive / (true_positive + false_negative) if (true_positive + false_negative) > 0 else 0.0 - specificity = ( - float(true_negative / (true_negative + false_positive)) if (true_negative + false_positive) > 0 else None + precision, recall, f1_score, specificity = _classification_rates( + true_positive=true_positive, + false_positive=false_positive, + true_negative=true_negative, + false_negative=false_negative, ) - f1_score = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0 num_responses = all_human_scores.shape[1] num_human_raters = all_human_scores.shape[0] diff --git a/pyrit/score/scorer_evaluation/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py new file mode 100644 index 0000000000..38ec101fe6 --- /dev/null +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -0,0 +1,416 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Suggest a ``FloatScaleThresholdScorer`` threshold from human-labeled data. + +The helpers here only suggest a value. They never change a scorer: the caller reads the +suggestion, checks the held-out result, and sets the threshold themselves. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING + +import numpy as np + +from pyrit.models import FloatFeedback, ScoringExpectation +from pyrit.score.scorer_evaluation.scorer_evaluator import ( + ObjectiveScorerEvaluator, + _classification_rates, + _human_score_matrix, + _majority_vote, + _validate_num_scorer_trials, +) +from pyrit.score.true_false.float_scale_threshold_scorer import FloatScaleThresholdScorer + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pyrit.models import Score + from pyrit.score.scorer_evaluation.human_labeled_dataset import HumanLabeledDataset + + +@dataclass(frozen=True) +class ThresholdOperatingPoint: + """ + How a threshold classifies a set of labeled float scores. + + A score at or above ``threshold`` counts as true, which is how ``FloatScaleThresholdScorer`` + applies its threshold. With several scoring trials, every trial of every response is + counted, so the counts describe single scoring runs rather than responses. + + Attributes: + threshold (float): The threshold that was applied. + true_positive (int): Gold-true scores at or above the threshold. + false_positive (int): Gold-false scores at or above the threshold. + true_negative (int): Gold-false scores below the threshold. + false_negative (int): Gold-true scores below the threshold. + precision (float): ``TP / (TP + FP)``, or 0.0 when nothing is at or above the threshold. + recall (float): ``TP / (TP + FN)``, or 0.0 when there are no gold-true scores. + f1_score (float): The harmonic mean of precision and recall, or 0.0 when both are 0.0. + specificity (float | None): ``TN / (TN + FP)``, or None when there are no gold-false scores. + """ + + threshold: float + true_positive: int + false_positive: int + true_negative: int + false_negative: int + precision: float + recall: float + f1_score: float + specificity: float | None + + +@dataclass(frozen=True) +class ThresholdSuggestion: + """ + A suggested threshold, how it was chosen, and how it does on held-out data. + + The threshold is chosen on the tuning split only. ``holdout_point`` then applies that frozen + threshold to responses the choice never saw, which is the estimate to trust. The tuning + numbers are optimistic, because the threshold was picked to look good on them. + + Attributes: + threshold (float): The suggested threshold, one of the observed tuning scores. Use the exact + value: a threshold rounded up past an observed score turns that score's verdicts false. + criterion (str): ``"max_f1"``, or ``"max_recall_at_min_precision"`` when ``min_precision`` was set. + min_precision (float | None): The precision floor the threshold had to meet on the tuning split. + tuning_point (ThresholdOperatingPoint): The suggested threshold on the tuning split. + holdout_point (ThresholdOperatingPoint | None): The suggested threshold on the holdout split, + or None when ``holdout_fraction`` was 0. + operating_points (tuple[ThresholdOperatingPoint, ...]): Every candidate threshold on the + tuning split, in ascending order of threshold. Left out of ``repr``. + current_threshold (float | None): The threshold the suggestion is compared with, if any. + current_tuning_point (ThresholdOperatingPoint | None): ``current_threshold`` on the tuning split. + current_holdout_point (ThresholdOperatingPoint | None): ``current_threshold`` on the holdout split. + num_tuning_responses (int): Responses in the tuning split. + num_holdout_responses (int): Responses in the holdout split. + num_scorer_trials (int): Scoring trials per response. + num_excluded_responses (int): Responses left out because a trial returned no float score. + scores (np.ndarray): The float scores tuned on, shaped ``(num_trials, num_responses)``, without + excluded responses. Pass them back to ``suggest_threshold`` with ``labels`` to try other + options without scoring again. Left out of ``repr`` and comparisons. + labels (np.ndarray): The gold label of each response in ``scores``. Left out of ``repr`` and + comparisons. + """ + + threshold: float + criterion: str + min_precision: float | None + tuning_point: ThresholdOperatingPoint + holdout_point: ThresholdOperatingPoint | None + operating_points: tuple[ThresholdOperatingPoint, ...] = field(repr=False) + current_threshold: float | None + current_tuning_point: ThresholdOperatingPoint | None + current_holdout_point: ThresholdOperatingPoint | None + num_tuning_responses: int + num_holdout_responses: int + num_scorer_trials: int + scores: np.ndarray = field(repr=False, compare=False) + labels: np.ndarray = field(repr=False, compare=False) + num_excluded_responses: int = 0 + + +def suggest_threshold( + *, + scores: Sequence[float] | np.ndarray, + labels: Sequence[bool] | np.ndarray, + min_precision: float | None = None, + holdout_fraction: float = 0.5, + seed: int | None = 0, + current_threshold: float | None = None, +) -> ThresholdSuggestion: + """ + Suggest a ``FloatScaleThresholdScorer`` threshold from human-labeled float scores. + + The responses are split at random, keeping the share of gold-true labels the same in both + parts. On the tuning part, every nonzero observed score is a candidate, because a threshold between + two observed scores classifies them the same way as the higher one. Without + ``min_precision``, the candidate with the highest F1 score is suggested. With it, the + candidate with the highest recall among those whose precision reaches ``min_precision`` is + suggested. Ties go to the higher threshold. The suggested threshold is then applied, unchanged, + to the holdout part. + + Args: + scores (Sequence[float] | np.ndarray): Float scores in ``[0, 1]``, either one per response + or shaped ``(num_trials, num_responses)``. Several trials of a response stay in the + same split. + labels (Sequence[bool] | np.ndarray): The gold (human) label of each response. + min_precision (float | None): If set, a precision in ``(0, 1]`` the suggested threshold must + reach on the tuning split. Defaults to None, which maximizes F1. + holdout_fraction (float): The share of responses held out to check the suggestion, in + ``[0, 1)``. 0 tunes on every response and reports no held-out result. Defaults to 0.5. + seed (int | None): Seed for the random split. Defaults to 0, so repeated calls agree. + current_threshold (float | None): A threshold to report next to the suggestion on both + splits, such as the one a scorer uses today. Defaults to None. + + Returns: + ThresholdSuggestion: The suggested threshold with its tuning and held-out results. + + Raises: + ValueError: If the inputs are malformed, a split has no gold-true response (including an + empty holdout split when ``holdout_fraction`` is above 0), every tuning score or every + gold-true tuning score is 0.0, or no candidate reaches ``min_precision``. + """ + score_matrix, gold = _validate_scores_and_labels(scores=scores, labels=labels) + _validate_suggestion_options(min_precision=min_precision, holdout_fraction=holdout_fraction) + if current_threshold is not None: + _validate_threshold(threshold=current_threshold, name="current_threshold") + + tuning_index, holdout_index = _stratified_split(gold=gold, holdout_fraction=holdout_fraction, seed=seed) + tuning_scores, tuning_gold = score_matrix[:, tuning_index], gold[tuning_index] + if not tuning_gold.any(): + raise ValueError("The tuning split has no gold-true response, so recall is undefined.") + if holdout_fraction > 0 and not gold[holdout_index].any(): + raise ValueError( + "The holdout split has no gold-true response; add labeled data, or set holdout_fraction=0 " + "to tune on every response without a held-out check." + ) + + # A threshold must be in (0, 1], so a score of 0.0 can never count as true. + candidates = np.unique(tuning_scores[tuning_scores > 0]) + if candidates.size == 0: + raise ValueError("Every tuning score is 0.0, so no threshold in (0, 1] separates the responses.") + if not (tuning_scores[:, tuning_gold] > 0).any(): + raise ValueError( + "Every gold-true tuning score is 0.0, so no threshold in (0, 1] counts a gold-true response as true." + ) + operating_points = tuple( + _operating_point(score_matrix=tuning_scores, gold=tuning_gold, threshold=float(candidate)) + for candidate in candidates + ) + + if min_precision is None: + criterion = "max_f1" + eligible = list(operating_points) + ranking_key = "f1_score" + else: + criterion = "max_recall_at_min_precision" + eligible = [point for point in operating_points if point.precision >= min_precision] + ranking_key = "recall" + if not eligible: + best_precision = max(point.precision for point in operating_points) + raise ValueError( + f"No threshold reaches a precision of {min_precision} on the tuning split; " + f"the highest is {best_precision:.3f}." + ) + # operating_points ascend by threshold, so max() over the reversed list breaks ties upward. + chosen = max(reversed(eligible), key=lambda point: getattr(point, ranking_key)) + + def at(*, threshold: float | None, index: np.ndarray) -> ThresholdOperatingPoint | None: + if threshold is None or index.size == 0: + return None + return _operating_point(score_matrix=score_matrix[:, index], gold=gold[index], threshold=threshold) + + return ThresholdSuggestion( + threshold=chosen.threshold, + criterion=criterion, + min_precision=min_precision, + tuning_point=chosen, + holdout_point=at(threshold=chosen.threshold, index=holdout_index), + operating_points=operating_points, + current_threshold=current_threshold, + current_tuning_point=at(threshold=current_threshold, index=tuning_index), + current_holdout_point=at(threshold=current_threshold, index=holdout_index), + num_tuning_responses=int(tuning_index.size), + num_holdout_responses=int(holdout_index.size), + num_scorer_trials=int(score_matrix.shape[0]), + scores=score_matrix.copy(), + labels=gold.copy(), + ) + + +async def suggest_threshold_async( + *, + scorer: FloatScaleThresholdScorer, + labeled_dataset: HumanLabeledDataset, + num_scorer_trials: int = 1, + max_concurrency: int = 10, + min_precision: float | None = None, + holdout_fraction: float = 0.5, + seed: int | None = 0, +) -> ThresholdSuggestion: + """ + Score an OBJECTIVE dataset with a threshold scorer and suggest a threshold for it. + + Each response is scored the way ``ObjectiveScorerEvaluator`` scores it, but the float value + the threshold was applied to is kept instead of the true/false verdict. The gold label of a + response is the majority vote of its human labels; a split vote counts as false, as in the + evaluator. Responses with a trial that returned no float score are left out and counted in + ``num_excluded_responses``. The scorer's own threshold is reported as ``current_threshold``. + + The scorer is not changed. To use the suggestion, create a new ``FloatScaleThresholdScorer`` + with ``threshold=suggestion.threshold``. + + Args: + scorer (FloatScaleThresholdScorer): The threshold scorer whose threshold to tune. + labeled_dataset (HumanLabeledDataset): An OBJECTIVE dataset with one assistant response per entry. + num_scorer_trials (int): Scoring runs per response. Must be at least 1. Defaults to 1. + max_concurrency (int): Maximum number of concurrent scoring requests. Defaults to 10. + min_precision (float | None): See ``suggest_threshold``. Defaults to None. + holdout_fraction (float): See ``suggest_threshold``. Defaults to 0.5. + seed (int | None): See ``suggest_threshold``. Defaults to 0. + + Returns: + ThresholdSuggestion: The suggested threshold with its tuning and held-out results. + + Raises: + ValueError: If ``num_scorer_trials`` is less than 1, the scorer is not a + ``FloatScaleThresholdScorer``, the dataset is not a valid OBJECTIVE dataset (including + entries with different numbers of human scores), no response has a float score, or + ``suggest_threshold`` rejects the scores. + """ + _validate_num_scorer_trials(num_scorer_trials) + _validate_suggestion_options(min_precision=min_precision, holdout_fraction=holdout_fraction) + if not isinstance(scorer, FloatScaleThresholdScorer): + raise ValueError(f"suggest_threshold_async tunes a FloatScaleThresholdScorer, got {type(scorer).__name__}.") + current_threshold = scorer.threshold + + evaluator = ObjectiveScorerEvaluator(scorer=scorer) + responses, human_scores, objectives = await evaluator._validate_and_extract_data_async(labeled_dataset) + gold = _majority_vote(_human_score_matrix(human_scores)) == 1 + + trials = await evaluator._run_scoring_trials_async( + responses=responses, + expectations=[ScoringExpectation(objective=objective) for objective in objectives or []], + harm_category=None, + num_scorer_trials=num_scorer_trials, + max_concurrency=max_concurrency, + read_value=_kept_float, + ) + determined = trials.determined_responses + if not determined.any(): + raise ValueError("The scorer returned no float score for any response, so there is nothing to tune on.") + + suggestion = suggest_threshold( + scores=trials.scores[:, determined], + labels=gold[determined], + min_precision=min_precision, + holdout_fraction=holdout_fraction, + seed=seed, + current_threshold=current_threshold, + ) + return replace(suggestion, num_excluded_responses=int((~determined).sum())) + + +def _kept_float(score: Score) -> float | None: + """ + Read the float value retained by a threshold scorer. + + Returns: + float | None: The retained value, or None when no float feedback was recorded. + """ + feedback = FloatFeedback.read(score) + return feedback.value if feedback is not None else None + + +def _validate_suggestion_options(*, min_precision: float | None, holdout_fraction: float) -> None: + """ + Validate tuning options before any scoring work. + + Raises: + ValueError: If a precision floor or holdout fraction is outside its supported range. + """ + if min_precision is not None and not 0 < min_precision <= 1: + raise ValueError("min_precision must be in (0, 1].") + if not 0 <= holdout_fraction < 1: + raise ValueError("holdout_fraction must be in [0, 1).") + + +def _validate_scores_and_labels( + *, + scores: Sequence[float] | np.ndarray, + labels: Sequence[bool] | np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """ + Check the inputs and return scores shaped ``(num_trials, num_responses)`` with boolean labels. + + Returns: + tuple[np.ndarray, np.ndarray]: The score matrix and the gold labels. + + Raises: + ValueError: If the shapes disagree, a score is outside ``[0, 1]``, or a label is not boolean. + """ + score_matrix = np.asarray(scores, dtype=np.float64) + if score_matrix.ndim == 1: + score_matrix = score_matrix[np.newaxis, :] + if score_matrix.ndim != 2 or score_matrix.size == 0: + raise ValueError("scores must be a non-empty 1-D or (num_trials, num_responses) array.") + if not np.isfinite(score_matrix).all() or (score_matrix < 0).any() or (score_matrix > 1).any(): + raise ValueError("Every score must be a finite number in [0, 1].") + + label_array = np.asarray(labels) + if label_array.ndim != 1 or label_array.shape[0] != score_matrix.shape[1]: + raise ValueError( + f"labels must have one entry per response ({score_matrix.shape[1]}), but has shape {label_array.shape}." + ) + if label_array.dtype != np.bool_: + if not np.isin(label_array, [0, 1]).all(): + raise ValueError("Every label must be a boolean (or 0/1).") + label_array = label_array.astype(bool) + return score_matrix, label_array + + +def _validate_threshold(*, threshold: float, name: str) -> None: + """ + Check that a threshold is one ``FloatScaleThresholdScorer`` accepts. + + Raises: + ValueError: If the threshold is not a finite number in ``(0, 1]``. + """ + if not np.isfinite(threshold) or not 0 < threshold <= 1: + raise ValueError(f"{name} must be a finite number in (0, 1].") + + +def _stratified_split(*, gold: np.ndarray, holdout_fraction: float, seed: int | None) -> tuple[np.ndarray, np.ndarray]: + """ + Split response indices into tuning and holdout parts with the same share of gold-true labels. + + Returns: + tuple[np.ndarray, np.ndarray]: The sorted tuning and holdout indices. + """ + if holdout_fraction == 0: + return np.arange(gold.size), np.array([], dtype=np.int64) + rng = np.random.default_rng(seed) + holdout_parts = [] + for label in (True, False): + members = np.flatnonzero(gold == label) + holdout_parts.append(rng.permutation(members)[: round(members.size * holdout_fraction)]) + holdout_index = np.sort(np.concatenate(holdout_parts)) + tuning_index = np.setdiff1d(np.arange(gold.size), holdout_index) + return tuning_index, holdout_index + + +def _operating_point(*, score_matrix: np.ndarray, gold: np.ndarray, threshold: float) -> ThresholdOperatingPoint: + """ + Count every trial's verdict at ``threshold`` against the gold labels. + + Returns: + ThresholdOperatingPoint: The confusion counts and rates. + """ + predicted = score_matrix >= threshold + actual = np.broadcast_to(gold, score_matrix.shape) + true_positive = int(np.sum(predicted & actual)) + false_positive = int(np.sum(predicted & ~actual)) + true_negative = int(np.sum(~predicted & ~actual)) + false_negative = int(np.sum(~predicted & actual)) + precision, recall, f1_score, specificity = _classification_rates( + true_positive=true_positive, + false_positive=false_positive, + true_negative=true_negative, + false_negative=false_negative, + ) + return ThresholdOperatingPoint( + threshold=threshold, + true_positive=true_positive, + false_positive=false_positive, + true_negative=true_negative, + false_negative=false_negative, + precision=precision, + recall=recall, + f1_score=f1_score, + specificity=specificity, + ) diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py new file mode 100644 index 0000000000..432ec128bf --- /dev/null +++ b/tests/unit/score/test_threshold_suggestion.py @@ -0,0 +1,425 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from unittest.mock import AsyncMock, MagicMock + +import numpy as np +import pytest + +from pyrit.memory import MemoryInterface +from pyrit.models import FloatFeedback, Message, MessagePiece, Score, ScoreStatus +from pyrit.score import ( + FloatScaleThresholdScorer, + HumanLabeledDataset, + MetricsType, + ObjectiveHumanLabeledEntry, + TrueFalseFallbackScorer, + suggest_threshold, + suggest_threshold_async, +) + +# Gold-true responses score high, gold-false ones low, with some overlap in the middle. +SCORES = [0.9, 0.8, 0.7, 0.6, 0.4, 0.2, 0.6, 0.3, 0.2, 0.1, 0.0, 0.0] +LABELS = [True, True, True, True, True, True, False, False, False, False, False, False] + + +def test_suggest_threshold_current_point_counts_scores_at_threshold_as_true() -> None: + point = suggest_threshold( + scores=SCORES, labels=LABELS, holdout_fraction=0, current_threshold=0.6 + ).current_tuning_point + + assert point is not None + assert (point.true_positive, point.false_positive, point.true_negative, point.false_negative) == (4, 1, 5, 2) + assert point.precision == pytest.approx(0.8) + assert point.recall == pytest.approx(4 / 6) + assert point.f1_score == pytest.approx(2 * 0.8 * (4 / 6) / (0.8 + 4 / 6)) + assert point.specificity == pytest.approx(5 / 6) + + +def test_suggest_threshold_current_point_undefined_rates() -> None: + point = suggest_threshold( + scores=[0.1, 0.2], labels=[True, True], holdout_fraction=0, current_threshold=0.5 + ).current_tuning_point + + assert point is not None + assert point.precision == 0.0 + assert point.recall == 0.0 + assert point.f1_score == 0.0 + assert point.specificity is None + + +def test_suggest_threshold_without_holdout_maximizes_f1() -> None: + suggestion = suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0) + + assert suggestion.criterion == "max_f1" + best_f1 = max(point.f1_score for point in suggestion.operating_points) + assert suggestion.tuning_point.f1_score == best_f1 + assert suggestion.threshold == 0.4 + assert suggestion.holdout_point is None + assert suggestion.num_tuning_responses == 12 + assert suggestion.num_holdout_responses == 0 + + +def test_suggest_threshold_candidates_are_observed_positive_scores() -> None: + suggestion = suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0) + + assert [point.threshold for point in suggestion.operating_points] == [0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9] + + +def test_suggest_threshold_keeps_inputs_out_of_repr() -> None: + suggestion = suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0) + + np.testing.assert_array_equal(suggestion.scores, [SCORES]) + np.testing.assert_array_equal(suggestion.labels, LABELS) + assert "operating_points" not in repr(suggestion) + assert "scores=" not in repr(suggestion) + assert suggestion == suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0) + + +def test_suggest_threshold_copies_caller_arrays() -> None: + scores, labels = np.array(SCORES), np.array(LABELS) + suggestion = suggest_threshold(scores=scores, labels=labels, holdout_fraction=0) + + scores[:] = 0.0 + labels[:] = False + + np.testing.assert_array_equal(suggestion.scores, [SCORES]) + np.testing.assert_array_equal(suggestion.labels, LABELS) + + +def test_suggest_threshold_min_precision_maximizes_recall_subject_to_floor() -> None: + suggestion = suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0, min_precision=1.0) + + assert suggestion.criterion == "max_recall_at_min_precision" + assert suggestion.threshold == 0.7 + assert suggestion.tuning_point.precision == 1.0 + assert suggestion.tuning_point.recall == pytest.approx(0.5) + + +def test_suggest_threshold_breaks_ties_toward_higher_threshold() -> None: + # 0.9 (TP=1, FP=0, FN=1) and 0.3 (TP=2, FP=2, FN=0) both have an F1 score of 2/3. + suggestion = suggest_threshold(scores=[0.9, 0.5, 0.4, 0.3], labels=[True, False, False, True], holdout_fraction=0) + + f1_by_threshold = {point.threshold: point.f1_score for point in suggestion.operating_points} + assert f1_by_threshold[0.9] == pytest.approx(f1_by_threshold[0.3]) + assert suggestion.threshold == 0.9 + + +def test_suggest_threshold_f1_ties_survive_floating_point() -> None: + # 0.9 gives TP=1, FP=3, FN=1 and 0.2 gives TP=2, FP=8, FN=0: both have an F1 score of exactly 1/3. + suggestion = suggest_threshold( + scores=[0.9, 0.2, 0.9, 0.9, 0.9, 0.5, 0.5, 0.5, 0.5, 0.5], + labels=[True, True] + [False] * 8, + holdout_fraction=0, + ) + + f1_by_threshold = {point.threshold: point.f1_score for point in suggestion.operating_points} + assert f1_by_threshold[0.9] == f1_by_threshold[0.2] + assert suggestion.threshold == 0.9 + + +def test_suggest_threshold_rejects_empty_holdout_when_requested() -> None: + # Half of one response per class rounds to zero, so nothing would be held out. + with pytest.raises(ValueError, match="holdout split has no gold-true"): + suggest_threshold(scores=[0.9, 0.1], labels=[True, False]) + + +def test_suggest_threshold_reports_current_threshold() -> None: + suggestion = suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0, current_threshold=0.9) + + assert suggestion.current_threshold == 0.9 + assert suggestion.current_tuning_point.recall == pytest.approx(1 / 6) + assert suggestion.current_holdout_point is None + + +def test_suggest_threshold_holdout_is_stratified_and_disjoint() -> None: + rng = np.random.default_rng(1) + labels = np.array([True] * 40 + [False] * 60) + scores = np.clip(np.where(labels, 0.6, 0.3) + rng.normal(0, 0.15, labels.size), 0, 1) + + suggestion = suggest_threshold(scores=scores, labels=labels, holdout_fraction=0.25, current_threshold=0.9) + + assert suggestion.num_holdout_responses == 25 + assert suggestion.num_tuning_responses == 75 + holdout = suggestion.holdout_point + assert holdout.true_positive + holdout.false_negative == 10 + assert holdout.false_positive + holdout.true_negative == 15 + assert suggestion.current_holdout_point is not None + assert suggestion.current_holdout_point.threshold == 0.9 + + +def test_suggest_threshold_tunes_only_on_the_tuning_split() -> None: + # With seed 0 the tuning split is (0.2, True) and (0.8, False). Tuning on all four responses + # would tie 0.2 with 0.9 and pick 0.9, so 0.2 shows the held-out pair stayed out of tuning. + suggestion = suggest_threshold( + scores=[0.9, 0.2, 0.8, 0.3], labels=[True, True, False, False], holdout_fraction=0.5, seed=0 + ) + + assert suggestion.threshold == 0.2 + tuning, holdout = suggestion.tuning_point, suggestion.holdout_point + assert (tuning.true_positive, tuning.false_positive, tuning.true_negative, tuning.false_negative) == (1, 1, 0, 0) + assert holdout is not None + assert (holdout.true_positive, holdout.false_positive, holdout.true_negative, holdout.false_negative) == ( + 1, + 1, + 0, + 0, + ) + assert ( + suggest_threshold(scores=[0.9, 0.2, 0.8, 0.3], labels=[True, True, False, False], holdout_fraction=0).threshold + == 0.9 + ) + + +def test_suggest_threshold_is_reproducible_with_seed() -> None: + rng = np.random.default_rng(2) + labels = rng.random(60) < 0.5 + scores = np.clip(np.where(labels, 0.7, 0.3) + rng.normal(0, 0.2, labels.size), 0, 1) + + first = suggest_threshold(scores=scores, labels=labels, seed=7) + second = suggest_threshold(scores=scores, labels=labels, seed=7) + + assert first == second + + +def test_suggest_threshold_counts_every_trial() -> None: + trials = np.array([[0.9, 0.1], [0.8, 0.7]]) + + suggestion = suggest_threshold(scores=trials, labels=[True, False], holdout_fraction=0) + + assert suggestion.num_scorer_trials == 2 + assert suggestion.num_tuning_responses == 2 + point = suggestion.tuning_point + assert point.true_positive + point.false_positive + point.true_negative + point.false_negative == 4 + + +def test_suggest_threshold_accepts_zero_one_labels() -> None: + suggestion = suggest_threshold(scores=[0.9, 0.1], labels=[1, 0], holdout_fraction=0) + + assert suggestion.threshold == 0.9 + + +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"scores": [], "labels": []}, "non-empty"), + ({"scores": [0.5, 1.5], "labels": [True, False]}, r"\[0, 1\]"), + ({"scores": [0.5, float("nan")], "labels": [True, False]}, r"\[0, 1\]"), + ({"scores": [0.5, 0.2], "labels": [True]}, "one entry per response"), + ({"scores": [0.5, 0.2], "labels": [True, 2]}, "boolean"), + ({"scores": [0.5, 0.2], "labels": [True, False], "min_precision": 0}, "min_precision"), + ({"scores": [0.5, 0.2], "labels": [True, False], "holdout_fraction": 1}, "holdout_fraction"), + ({"scores": [0.5, 0.2], "labels": [True, False], "current_threshold": 0}, "current_threshold"), + ({"scores": [0.5, 0.2], "labels": [False, False], "holdout_fraction": 0}, "no gold-true"), + ({"scores": [0.0, 0.0], "labels": [True, False], "holdout_fraction": 0}, "Every tuning score is 0.0"), + ( + {"scores": [0.0, 0.0, 0.5], "labels": [True, True, False], "holdout_fraction": 0}, + "Every gold-true tuning score is 0.0", + ), + ( + {"scores": [0.9, 0.9], "labels": [True, False], "holdout_fraction": 0, "min_precision": 0.9}, + "No threshold reaches a precision of 0.9", + ), + ], +) +def test_suggest_threshold_rejects_bad_input(kwargs: dict, match: str) -> None: + with pytest.raises(ValueError, match=match): + suggest_threshold(**kwargs) + + +def test_suggest_threshold_rejects_holdout_without_positive() -> None: + # One gold-true response cannot be in both splits. + with pytest.raises(ValueError, match="holdout split has no gold-true"): + suggest_threshold(scores=[0.9, 0.1, 0.2], labels=[True, False, False], holdout_fraction=0.4) + + +def _entry(objective: str, human_scores: list[bool]) -> ObjectiveHumanLabeledEntry: + assistant = Message( + message_pieces=[ + MessagePiece( + role="assistant", + original_value=f"response to {objective}", + original_value_data_type="text", + conversation_id=objective, + ) + ] + ) + return ObjectiveHumanLabeledEntry([assistant], human_scores, objective) + + +def _threshold_score(value: float | None, *, threshold: float = 0.9) -> Score: + if value is None: + return Score(score_type="true_false", status=ScoreStatus.UNDETERMINED) + return Score( + score_type="true_false", + score_value=str(value >= threshold).lower(), + score_metadata=FloatFeedback(value=value).to_metadata(), + ) + + +@pytest.fixture +def mock_threshold_scorer() -> MagicMock: + scorer = MagicMock(spec=FloatScaleThresholdScorer) + scorer.threshold = 0.9 + scorer._memory = MagicMock(spec=MemoryInterface) + scorer._memory.add_message_to_memory_async = AsyncMock() + scorer._memory.get_message_pieces_async = AsyncMock(return_value=[]) + scorer.get_chat_target.return_value = None + return scorer + + +async def test_suggest_threshold_async_uses_kept_float_values(mock_threshold_scorer: MagicMock) -> None: + values = {"a": 0.95, "b": 0.6, "c": 0.5, "d": 0.4, "e": 0.1, "f": None} + dataset = HumanLabeledDataset( + name="threshold_test", + metrics_type=MetricsType.OBJECTIVE, + version="1.0", + entries=[ + _entry("a", [True, True]), + _entry("b", [True, True]), + _entry("c", [True, True]), + _entry("d", [False, False]), + _entry("e", [True, False]), # A split vote counts as false. + _entry("f", [True, True]), + ], + ) + + async def score_async(**kwargs): + return [_threshold_score(values[kwargs["expectation"].objective])] + + mock_threshold_scorer.score_async = AsyncMock(side_effect=score_async) + + suggestion = await suggest_threshold_async( + scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0 + ) + + assert suggestion.num_excluded_responses == 1 + assert suggestion.num_tuning_responses == 5 + assert suggestion.threshold == 0.5 + assert suggestion.tuning_point.recall == 1.0 + assert suggestion.tuning_point.false_positive == 0 + assert suggestion.current_threshold == 0.9 + assert suggestion.current_tuning_point.recall == pytest.approx(1 / 3) + # The kept scores leave out the excluded response, so they can be tuned again offline. + np.testing.assert_array_equal(suggestion.scores, [[0.95, 0.6, 0.5, 0.4, 0.1]]) + np.testing.assert_array_equal(suggestion.labels, [True, True, True, False, False]) + assert suggest_threshold(scores=suggestion.scores, labels=suggestion.labels, holdout_fraction=0).threshold == 0.5 + + +async def test_suggest_threshold_async_runs_each_trial(mock_threshold_scorer: MagicMock) -> None: + dataset = HumanLabeledDataset( + name="threshold_test", + metrics_type=MetricsType.OBJECTIVE, + version="1.0", + entries=[_entry("a", [True]), _entry("b", [False])], + ) + mock_threshold_scorer.score_async = AsyncMock( + side_effect=[[_threshold_score(0.8)], [_threshold_score(0.2)], [_threshold_score(0.7)], [_threshold_score(0.3)]] + ) + + suggestion = await suggest_threshold_async( + scorer=mock_threshold_scorer, labeled_dataset=dataset, num_scorer_trials=2, holdout_fraction=0 + ) + + assert mock_threshold_scorer.score_async.await_count == 4 + assert suggestion.num_scorer_trials == 2 + assert suggestion.threshold == 0.7 + np.testing.assert_array_equal(suggestion.scores, [[0.8, 0.2], [0.7, 0.3]]) + + +@pytest.mark.parametrize("undetermined", [True, False]) +async def test_suggest_threshold_async_requires_a_float_score( + mock_threshold_scorer: MagicMock, undetermined: bool +) -> None: + dataset = HumanLabeledDataset( + name="threshold_test", metrics_type=MetricsType.OBJECTIVE, version="1.0", entries=[_entry("a", [True])] + ) + score = _threshold_score(None) if undetermined else Score(score_type="true_false", score_value="false") + mock_threshold_scorer.score_async = AsyncMock(return_value=[score]) + + with pytest.raises(ValueError, match="no float score"): + await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0) + + +async def test_suggest_threshold_async_rejects_zero_trials(mock_threshold_scorer: MagicMock) -> None: + dataset = HumanLabeledDataset( + name="threshold_test", metrics_type=MetricsType.OBJECTIVE, version="1.0", entries=[_entry("a", [True])] + ) + + with pytest.raises(ValueError, match="num_scorer_trials"): + await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, num_scorer_trials=0) + + +@pytest.mark.parametrize(("min_precision", "holdout_fraction"), [(95, 0.5), (None, 1.0)]) +async def test_suggest_threshold_async_rejects_options_before_scoring( + mock_threshold_scorer: MagicMock, min_precision: float | None, holdout_fraction: float +) -> None: + dataset = HumanLabeledDataset( + name="threshold_test", metrics_type=MetricsType.OBJECTIVE, version="1.0", entries=[_entry("a", [True])] + ) + mock_threshold_scorer.score_async = AsyncMock(return_value=[_threshold_score(0.95)]) + + with pytest.raises(ValueError): + await suggest_threshold_async( + scorer=mock_threshold_scorer, + labeled_dataset=dataset, + min_precision=min_precision, + holdout_fraction=holdout_fraction, + ) + + mock_threshold_scorer._memory.add_message_to_memory_async.assert_not_awaited() + mock_threshold_scorer.score_async.assert_not_awaited() + + +async def test_suggest_threshold_async_reuses_the_same_dataset( + mock_threshold_scorer: MagicMock, sqlite_instance: MemoryInterface +) -> None: + mock_threshold_scorer._memory = sqlite_instance + dataset = HumanLabeledDataset( + name="threshold_test", + metrics_type=MetricsType.OBJECTIVE, + version="1.0", + entries=[_entry("a", [True]), _entry("b", [False])], + ) + mock_threshold_scorer.score_async = AsyncMock( + side_effect=lambda **kwargs: [_threshold_score(0.8 if kwargs["expectation"].objective == "a" else 0.2)] + ) + + first = await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0) + second = await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0) + + assert first.threshold == second.threshold == 0.8 + assert len(await sqlite_instance.get_message_pieces_async()) == 2 + + +async def test_suggest_threshold_async_rejects_ragged_human_scores_before_scoring( + mock_threshold_scorer: MagicMock, +) -> None: + dataset = HumanLabeledDataset( + name="threshold_test", + metrics_type=MetricsType.OBJECTIVE, + version="1.0", + entries=[_entry("a", [True, True]), _entry("b", [False])], + ) + mock_threshold_scorer.score_async = AsyncMock(return_value=[_threshold_score(0.95)]) + + with pytest.raises(ValueError, match="inhomogeneous"): + await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0) + + mock_threshold_scorer.score_async.assert_not_awaited() + + +async def test_suggest_threshold_async_rejects_scorer_that_is_not_a_threshold_scorer_before_scoring() -> None: + dataset = HumanLabeledDataset( + name="threshold_test", metrics_type=MetricsType.OBJECTIVE, version="1.0", entries=[_entry("a", [True])] + ) + fallback = MagicMock(spec=TrueFalseFallbackScorer) + fallback._memory = MagicMock(spec=MemoryInterface) + fallback._memory.add_message_to_memory_async = AsyncMock() + fallback.score_async = AsyncMock(return_value=[_threshold_score(0.95)]) + + with pytest.raises(ValueError, match="tunes a FloatScaleThresholdScorer"): + await suggest_threshold_async(scorer=fallback, labeled_dataset=dataset, holdout_fraction=0) + + fallback._memory.add_message_to_memory_async.assert_not_awaited() + fallback.score_async.assert_not_awaited()