diff --git a/doc/code/scoring/9_choosing_a_threshold.ipynb b/doc/code/scoring/9_choosing_a_threshold.ipynb new file mode 100644 index 0000000000..312a4d0d63 --- /dev/null +++ b/doc/code/scoring/9_choosing_a_threshold.ipynb @@ -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": [ + "
\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_scorefalse_positive
current (0.9)0.0111.000.0220.0
suggested (0.33)0.9020.830.86517.0
\n", + "
" + ], + "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": [ + "
\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": "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 +} diff --git a/doc/code/scoring/9_choosing_a_threshold.py b/doc/code/scoring/9_choosing_a_threshold.py new file mode 100644 index 0000000000..0e676847bf --- /dev/null +++ b/doc/code/scoring/9_choosing_a_threshold.py @@ -0,0 +1,114 @@ +# --- +# jupyter: +# jupytext: +# text_representation: +# extension: .py +# format_name: percent +# format_version: '1.3' +# jupytext_version: 1.19.4 +# --- + +# %% [markdown] +# # Choosing a Threshold for `FloatScaleThresholdScorer` +# +# `FloatScaleThresholdScorer` turns a float score into true/false: a score at or above its +# `threshold` counts as true. The threshold decides how many real successes the scorer catches +# (recall) and how many failures it marks as successes (false positives), and a value picked by +# hand can be far from the best trade-off for a given scorer. +# +# `suggest_threshold` picks a threshold from scores that humans have labeled. It is opt-in and only +# suggests a value; nothing changes until you create a scorer with it. It: +# +# 1. splits the labeled responses into a tuning part and a holdout part, keeping the share of +# successes the same in both, +# 2. tries every observed score on the tuning part and picks the one with the best F1 score, or, +# with `min_precision`, the one with the best recall whose precision is at least `min_precision`, +# 3. applies that threshold, unchanged, to the holdout part. The holdout numbers are the ones to +# trust: the tuning numbers look better than they will in practice, because the threshold was +# picked to fit them. +# +# This example runs offline on made-up scores, so you can see the output without a model. + +# %% +import numpy as np +import pandas as pd + +from pyrit.score import suggest_threshold + +rng = np.random.default_rng(0) +labels = rng.random(400) < 0.5 # True: humans say the objective was achieved +# A judge that is fairly good at ranking responses but rarely gives successes a very high score. +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) + +rows = { + f"current ({suggestion.current_threshold})": suggestion.current_holdout_point, + f"suggested ({suggestion.threshold})": suggestion.holdout_point, +} +pd.DataFrame( + { + name: { + "recall": point.recall, + "precision": point.precision, + "f1_score": point.f1_score, + "false_positive": point.false_positive, + } + for name, point in rows.items() + } +).T.round(3) + +# %% [markdown] +# `operating_points` lists every candidate 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] +# ## With a real scorer +# +# `suggest_threshold_async` scores an OBJECTIVE `HumanLabeledDataset` with your +# `FloatScaleThresholdScorer` and keeps the float value behind each true/false verdict, so you do +# not need to collect the scores yourself. The scorer's own threshold is reported as +# `current_threshold`. With `num_scorer_trials` above 1, every trial is counted, so the numbers +# describe a single scoring run, which is how the scorer is used in an attack. +# +# ```python +# 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, +# ) +# +# judge = SelfAskScaleScorer.from_scale(chat_target=OpenAIChatTarget()) +# scorer = FloatScaleThresholdScorer(scorer=judge, threshold=0.9) +# dataset = HumanLabeledDataset.from_csv( +# csv_path=SCORER_EVALS_PATH / "objective" / "cyber.csv", metrics_type=MetricsType.OBJECTIVE +# ) +# +# suggestion = await suggest_threshold_async(scorer=scorer, labeled_dataset=dataset, num_scorer_trials=3) +# print(suggestion.threshold, suggestion.holdout_point) +# +# tuned_scorer = FloatScaleThresholdScorer(scorer=judge, threshold=suggestion.threshold) +# ``` +# +# A threshold tuned on one dataset fits that dataset's mix of objectives and responses. Check the +# holdout numbers, and tune again when the judge model, rubric, or kind of objective changes. diff --git a/doc/myst.yml b/doc/myst.yml index ef1a8dad9c..ba7a10e8cc 100644 --- a/doc/myst.yml +++ b/doc/myst.yml @@ -181,6 +181,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/9_choosing_a_threshold.ipynb - file: code/scoring/multi_label_true_false.md - file: code/scoring/scorer_stability.md - file: code/memory/0_memory.md diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index 51a6da1247..59c93b24c8 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -113,6 +113,13 @@ ScorerStabilityMetrics, compute_scorer_stability, ) + from pyrit.score.scorer_evaluation.threshold_suggestion import ( + ThresholdOperatingPoint, + ThresholdSuggestion, + evaluate_threshold, + 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 ( @@ -376,6 +383,11 @@ "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", + "evaluate_threshold": "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/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py new file mode 100644 index 0000000000..fc48f23671 --- /dev/null +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -0,0 +1,399 @@ +# 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, replace +from typing import TYPE_CHECKING + +import numpy as np + +from pyrit.models import FloatFeedback +from pyrit.score.scorer_evaluation.scorer_evaluator import ObjectiveScorerEvaluator + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pyrit.score.scorer_evaluation.human_labeled_dataset import HumanLabeledDataset + from pyrit.score.true_false.float_scale_threshold_scorer import FloatScaleThresholdScorer + + +@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. + 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. + 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. + """ + + threshold: float + criterion: str + min_precision: float | None + tuning_point: ThresholdOperatingPoint + holdout_point: ThresholdOperatingPoint | None + operating_points: tuple[ThresholdOperatingPoint, ...] + 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 + num_excluded_responses: int = 0 + + +def evaluate_threshold( + *, + scores: Sequence[float] | np.ndarray, + labels: Sequence[bool] | np.ndarray, + threshold: float, +) -> ThresholdOperatingPoint: + """ + Classify labeled float scores with one threshold. + + Args: + scores (Sequence[float] | np.ndarray): Float scores in ``[0, 1]``, either one per response + or shaped ``(num_trials, num_responses)``. + labels (Sequence[bool] | np.ndarray): The gold label of each response. + threshold (float): The threshold to apply. Scores at or above it count as true. + + Returns: + ThresholdOperatingPoint: The confusion counts and rates at ``threshold``. + """ + score_matrix, gold = _validate_scores_and_labels(scores=scores, labels=labels) + _validate_threshold(threshold=threshold, name="threshold") + return _operating_point(score_matrix=score_matrix, gold=gold, threshold=threshold) + + +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 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 is 0.0, or + no candidate reaches ``min_precision``. + """ + score_matrix, gold = _validate_scores_and_labels(scores=scores, labels=labels) + 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).") + 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.") + 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]), + ) + + +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 dataset is not a valid OBJECTIVE + dataset, no response has a float score, or ``suggest_threshold`` rejects the scores. + """ + if num_scorer_trials < 1: + raise ValueError("num_scorer_trials must be at least 1.") + + evaluator = ObjectiveScorerEvaluator(scorer=scorer) + responses, human_scores, objectives = await evaluator._validate_and_extract_data_async(labeled_dataset) + # Entries may have different numbers of raters, so take each majority vote separately. + gold = np.array([np.round(np.median(entry_scores)) == 1 for entry_scores in human_scores], dtype=bool) + + trial_scores = np.full((num_scorer_trials, len(responses)), np.nan) + for trial in range(num_scorer_trials): + score_groups = await evaluator._score_responses_grouped_async( + responses=responses, + objectives=objectives or [], + max_concurrency=max_concurrency, + ) + for index, scores in enumerate(score_groups): + score = evaluator._select_evaluation_score(scores=scores, harm_category=None) + if score is None or score.is_undetermined: + continue + feedback = FloatFeedback.read(score) + if feedback is not None: + trial_scores[trial, index] = feedback.value + + determined = ~np.isnan(trial_scores).any(axis=0) + 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=trial_scores[:, determined], + labels=gold[determined], + min_precision=min_precision, + holdout_fraction=holdout_fraction, + seed=seed, + current_threshold=scorer.threshold, + ) + return replace(suggestion, num_excluded_responses=int((~determined).sum())) + + +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 = 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 + # From the integer counts, so equal F1 scores compare equal and ties break toward the higher threshold. + 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 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..40f65e3f08 --- /dev/null +++ b/tests/unit/score/test_threshold_suggestion.py @@ -0,0 +1,286 @@ +# 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, + evaluate_threshold, + 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_evaluate_threshold_counts_scores_at_threshold_as_true() -> None: + point = evaluate_threshold(scores=SCORES, labels=LABELS, threshold=0.6) + + 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_evaluate_threshold_undefined_rates() -> None: + point = evaluate_threshold(scores=[0.1, 0.2], labels=[True, True], threshold=0.5) + + 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_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_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.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.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]), + _entry("b", [True, True, False]), + _entry("c", [True]), + _entry("d", [False]), + _entry("e", [True, False]), # A split vote counts as false. + _entry("f", [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) + + +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 + + +async def test_suggest_threshold_async_requires_a_float_score(mock_threshold_scorer: MagicMock) -> 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(None)]) + + 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)