From f8bbdbb683410ed84997deb663d5209ef7a2351f Mon Sep 17 00:00:00 2001 From: Garyouki Date: Wed, 25 Nov 2026 12:15:54 -0800 Subject: [PATCH 1/9] FEAT: Suggest a FloatScaleThresholdScorer threshold from human-labeled data Add an opt-in helper that sweeps thresholds on human-labeled float scores, picks one on a tuning split (max F1, or max recall at a precision floor), and checks the frozen choice on a stratified holdout split. suggest_threshold_async scores an OBJECTIVE dataset with a FloatScaleThresholdScorer and keeps the float value behind each verdict. Closes #4569. Co-Authored-By: Claude Opus 5.5 --- doc/code/scoring/9_choosing_a_threshold.ipynb | 363 ++++++++++++++++ doc/code/scoring/9_choosing_a_threshold.py | 114 +++++ doc/myst.yml | 1 + pyrit/score/__init__.py | 12 + .../scorer_evaluation/threshold_suggestion.py | 394 ++++++++++++++++++ tests/unit/score/test_threshold_suggestion.py | 267 ++++++++++++ 6 files changed, 1151 insertions(+) create mode 100644 doc/code/scoring/9_choosing_a_threshold.ipynb create mode 100644 doc/code/scoring/9_choosing_a_threshold.py create mode 100644 pyrit/score/scorer_evaluation/threshold_suggestion.py create mode 100644 tests/unit/score/test_threshold_suggestion.py 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..9506c716ca --- /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(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..4d45144fc9 --- /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(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 88d037db90..470682f86f 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/memory/0_memory.md children: diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index dfa9b934ad..b12ee5bbed 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -106,6 +106,13 @@ get_all_harm_metrics, get_all_objective_metrics, ) + 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 ( @@ -364,6 +371,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..66454c150e --- /dev/null +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -0,0 +1,394 @@ +# 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, 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_index.size and not gold[holdout_index].any(): + raise ValueError("The holdout split has no gold-true response; lower holdout_fraction or add labeled data.") + + # 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 + f1_score = 2 * precision * recall / (precision + recall) if precision + recall 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..e4f6441bf6 --- /dev/null +++ b/tests/unit/score/test_threshold_suggestion.py @@ -0,0 +1,267 @@ +# 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_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) From bba64ba0c9983da33e797b9d33943c92f1cb5b46 Mon Sep 17 00:00:00 2001 From: Garyouki Date: Wed, 25 Nov 2026 12:22:35 -0800 Subject: [PATCH 2/9] FIX: Address review on threshold suggestion - Reject an empty holdout split whenever holdout_fraction > 0. - Compute F1 from integer counts so exact ties break toward the higher threshold. - Use SelfAskScaleScorer.from_scale in the docs example. Co-Authored-By: Claude Opus 5.5 --- doc/code/scoring/9_choosing_a_threshold.ipynb | 2 +- doc/code/scoring/9_choosing_a_threshold.py | 2 +- .../scorer_evaluation/threshold_suggestion.py | 15 ++++++++++----- tests/unit/score/test_threshold_suggestion.py | 19 +++++++++++++++++++ 4 files changed, 31 insertions(+), 7 deletions(-) diff --git a/doc/code/scoring/9_choosing_a_threshold.ipynb b/doc/code/scoring/9_choosing_a_threshold.ipynb index 9506c716ca..312a4d0d63 100644 --- a/doc/code/scoring/9_choosing_a_threshold.ipynb +++ b/doc/code/scoring/9_choosing_a_threshold.ipynb @@ -327,7 +327,7 @@ " suggest_threshold_async,\n", ")\n", "\n", - "judge = SelfAskScaleScorer(chat_target=OpenAIChatTarget())\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", diff --git a/doc/code/scoring/9_choosing_a_threshold.py b/doc/code/scoring/9_choosing_a_threshold.py index 4d45144fc9..0e676847bf 100644 --- a/doc/code/scoring/9_choosing_a_threshold.py +++ b/doc/code/scoring/9_choosing_a_threshold.py @@ -98,7 +98,7 @@ # suggest_threshold_async, # ) # -# judge = SelfAskScaleScorer(chat_target=OpenAIChatTarget()) +# 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 diff --git a/pyrit/score/scorer_evaluation/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py index 66454c150e..fc48f23671 100644 --- a/pyrit/score/scorer_evaluation/threshold_suggestion.py +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -159,8 +159,9 @@ def suggest_threshold( 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, every tuning - score is 0.0, or no candidate reaches ``min_precision``. + 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: @@ -174,8 +175,11 @@ def suggest_threshold( 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_index.size and not gold[holdout_index].any(): - raise ValueError("The holdout split has no gold-true response; lower holdout_fraction or add labeled data.") + 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]) @@ -379,7 +383,8 @@ def _operating_point(*, score_matrix: np.ndarray, gold: np.ndarray, threshold: f 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 - f1_score = 2 * precision * recall / (precision + recall) if precision + recall 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, diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py index e4f6441bf6..40f65e3f08 100644 --- a/tests/unit/score/test_threshold_suggestion.py +++ b/tests/unit/score/test_threshold_suggestion.py @@ -78,6 +78,25 @@ def test_suggest_threshold_breaks_ties_toward_higher_threshold() -> None: 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) From f3836f53e3c68c38c96f9d2b858b48ff7fe1d571 Mon Sep 17 00:00:00 2001 From: Garyouki Date: Wed, 25 Nov 2026 14:28:15 -0800 Subject: [PATCH 3/9] MAINT: Re-run CI after a flaky macOS timeout Co-Authored-By: Claude Opus 5.5 From 3f17114278652ec0fd4ba146bc753a47c7ae6601 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Wed, 2 Dec 2026 03:03:37 -0800 Subject: [PATCH 4/9] Fix threshold calibration reuse and example setup Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/code/scoring/9_choosing_a_threshold.ipynb | 4 +- doc/code/scoring/9_choosing_a_threshold.py | 4 +- pyrit/score/__init__.py | 2 - .../scorer_evaluation/scorer_evaluator.py | 48 ++++++-- .../scorer_evaluation/threshold_suggestion.py | 103 +++++++++--------- tests/unit/score/test_threshold_suggestion.py | 44 ++++++-- 6 files changed, 130 insertions(+), 75 deletions(-) diff --git a/doc/code/scoring/9_choosing_a_threshold.ipynb b/doc/code/scoring/9_choosing_a_threshold.ipynb index 312a4d0d63..2432519fcf 100644 --- a/doc/code/scoring/9_choosing_a_threshold.ipynb +++ b/doc/code/scoring/9_choosing_a_threshold.ipynb @@ -326,11 +326,13 @@ " 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)\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", + " csv_path=SCORER_EVALS_PATH / \"objective\" / \"bias.csv\", metrics_type=MetricsType.OBJECTIVE\n", ")\n", "\n", "suggestion = await suggest_threshold_async(scorer=scorer, labeled_dataset=dataset, num_scorer_trials=3)\n", diff --git a/doc/code/scoring/9_choosing_a_threshold.py b/doc/code/scoring/9_choosing_a_threshold.py index 0e676847bf..7faea9037c 100644 --- a/doc/code/scoring/9_choosing_a_threshold.py +++ b/doc/code/scoring/9_choosing_a_threshold.py @@ -97,11 +97,13 @@ # SelfAskScaleScorer, # suggest_threshold_async, # ) +# from pyrit.setup import IN_MEMORY, initialize_pyrit_async # +# await initialize_pyrit_async(memory_db_type=IN_MEMORY) # 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 +# csv_path=SCORER_EVALS_PATH / "objective" / "bias.csv", metrics_type=MetricsType.OBJECTIVE # ) # # suggestion = await suggest_threshold_async(scorer=scorer, labeled_dataset=dataset, num_scorer_trials=3) diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index 0a529fd517..77775e8150 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -116,7 +116,6 @@ from pyrit.score.scorer_evaluation.threshold_suggestion import ( ThresholdOperatingPoint, ThresholdSuggestion, - evaluate_threshold, suggest_threshold, suggest_threshold_async, ) @@ -400,7 +399,6 @@ "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", diff --git a/pyrit/score/scorer_evaluation/scorer_evaluator.py b/pyrit/score/scorer_evaluation/scorer_evaluator.py index 6e60b9ac0c..7d597133f5 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -34,7 +34,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 @@ -61,14 +61,36 @@ 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 + + @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. @@ -519,6 +541,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. @@ -532,6 +555,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. @@ -550,9 +575,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 @@ -1076,12 +1102,12 @@ def _compute_metrics( 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 index fc48f23671..a370f630c6 100644 --- a/pyrit/score/scorer_evaluation/threshold_suggestion.py +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -15,12 +15,17 @@ import numpy as np -from pyrit.models import FloatFeedback -from pyrit.score.scorer_evaluation.scorer_evaluator import ObjectiveScorerEvaluator +from pyrit.models import FloatFeedback, ScoringExpectation +from pyrit.score.scorer_evaluation.scorer_evaluator import ( + ObjectiveScorerEvaluator, + _classification_rates, + _validate_num_scorer_trials, +) if TYPE_CHECKING: from collections.abc import Sequence + from pyrit.models import Score from pyrit.score.scorer_evaluation.human_labeled_dataset import HumanLabeledDataset from pyrit.score.true_false.float_scale_threshold_scorer import FloatScaleThresholdScorer @@ -99,29 +104,6 @@ class ThresholdSuggestion: 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, @@ -164,10 +146,7 @@ def suggest_threshold( 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).") + _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") @@ -266,35 +245,28 @@ async def suggest_threshold_async( 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.") + _validate_num_scorer_trials(num_scorer_trials) + _validate_suggestion_options(min_precision=min_precision, holdout_fraction=holdout_fraction) 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) + 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=trial_scores[:, determined], + scores=trials.scores[:, determined], labels=gold[determined], min_precision=min_precision, holdout_fraction=holdout_fraction, @@ -304,6 +276,30 @@ async def suggest_threshold_async( 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, @@ -381,11 +377,12 @@ def _operating_point(*, score_matrix: np.ndarray, gold: np.ndarray, threshold: f 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 + 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, diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py index 40f65e3f08..63be869780 100644 --- a/tests/unit/score/test_threshold_suggestion.py +++ b/tests/unit/score/test_threshold_suggestion.py @@ -13,7 +13,6 @@ HumanLabeledDataset, MetricsType, ObjectiveHumanLabeledEntry, - evaluate_threshold, suggest_threshold, suggest_threshold_async, ) @@ -23,9 +22,12 @@ 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) +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) @@ -33,9 +35,12 @@ def test_evaluate_threshold_counts_scores_at_threshold_as_true() -> None: 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) +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 @@ -267,11 +272,15 @@ async def test_suggest_threshold_async_runs_each_trial(mock_threshold_scorer: Ma assert suggestion.threshold == 0.7 -async def test_suggest_threshold_async_requires_a_float_score(mock_threshold_scorer: MagicMock) -> None: +@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])] ) - mock_threshold_scorer.score_async = AsyncMock(return_value=[_threshold_score(None)]) + 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) @@ -284,3 +293,24 @@ async def test_suggest_threshold_async_rejects_zero_trials(mock_threshold_scorer 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() From 63e0edc2062066e20970b2b5973894ed2113e7fc Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Thu, 3 Dec 2026 12:03:33 -0800 Subject: [PATCH 5/9] Frame threshold tuning as float-scale scorer metrics and run it live Move the page to a non-numbered name, explain where it fits next to scorer metrics, execute the real-scorer example against bias.csv, add reading guidance, and link it from the scorer metrics page. Co-Authored-By: Claude Opus 5.5 --- doc/code/scoring/4_scorer_metrics.ipynb | 6 +- doc/code/scoring/4_scorer_metrics.py | 4 + doc/code/scoring/9_choosing_a_threshold.ipynb | 365 ------------ doc/code/scoring/9_choosing_a_threshold.py | 116 ---- .../float_scale_threshold_metrics.ipynb | 561 ++++++++++++++++++ .../scoring/float_scale_threshold_metrics.py | 154 +++++ doc/myst.yml | 2 +- 7 files changed, 725 insertions(+), 483 deletions(-) delete mode 100644 doc/code/scoring/9_choosing_a_threshold.ipynb delete mode 100644 doc/code/scoring/9_choosing_a_threshold.py create mode 100644 doc/code/scoring/float_scale_threshold_metrics.ipynb create mode 100644 doc/code/scoring/float_scale_threshold_metrics.py 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/9_choosing_a_threshold.ipynb b/doc/code/scoring/9_choosing_a_threshold.ipynb deleted file mode 100644 index 2432519fcf..0000000000 --- a/doc/code/scoring/9_choosing_a_threshold.ipynb +++ /dev/null @@ -1,365 +0,0 @@ -{ - "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", - "from pyrit.setup import IN_MEMORY, initialize_pyrit_async\n", - "\n", - "await initialize_pyrit_async(memory_db_type=IN_MEMORY)\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", - "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 deleted file mode 100644 index 7faea9037c..0000000000 --- a/doc/code/scoring/9_choosing_a_threshold.py +++ /dev/null @@ -1,116 +0,0 @@ -# --- -# 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, -# ) -# from pyrit.setup import IN_MEMORY, initialize_pyrit_async -# -# await initialize_pyrit_async(memory_db_type=IN_MEMORY) -# 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 -# ) -# -# 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/code/scoring/float_scale_threshold_metrics.ipynb b/doc/code/scoring/float_scale_threshold_metrics.ipynb new file mode 100644 index 0000000000..f40204b913 --- /dev/null +++ b/doc/code/scoring/float_scale_threshold_metrics.ipynb @@ -0,0 +1,561 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "1f416997", + "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 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": "8b6f0d01", + "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": 1, + "id": "efad9daa", + "metadata": { + "execution": { + "iopub.execute_input": "2026-12-03T20:02:21.241371Z", + "iopub.status.busy": "2026-12-03T20:02:21.240975Z", + "iopub.status.idle": "2026-12-03T20:02:28.912751Z", + "shell.execute_reply": "2026-12-03T20:02:28.909444Z" + } + }, + "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": 1, + "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 ({round(suggestion.threshold, 3)})\": 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": "8b472071", + "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": 2, + "id": "d34d9808", + "metadata": { + "execution": { + "iopub.execute_input": "2026-12-03T20:02:28.919851Z", + "iopub.status.busy": "2026-12-03T20:02:28.919004Z", + "iopub.status.idle": "2026-12-03T20:02:28.939069Z", + "shell.execute_reply": "2026-12-03T20:02:28.936577Z" + } + }, + "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": 2, + "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": "eb3cd2a7", + "metadata": {}, + "source": [ + "If false positives matter more than missed successes, set a precision floor instead of maximizing\n", + "F1:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "450b547c", + "metadata": { + "execution": { + "iopub.execute_input": "2026-12-03T20:02:28.945158Z", + "iopub.status.busy": "2026-12-03T20:02:28.944645Z", + "iopub.status.idle": "2026-12-03T20:02:28.958609Z", + "shell.execute_reply": "2026-12-03T20:02:28.955970Z" + } + }, + "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": "1b42af48", + "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": 4, + "id": "d9c93107", + "metadata": { + "execution": { + "iopub.execute_input": "2026-12-03T20:02:28.965497Z", + "iopub.status.busy": "2026-12-03T20:02:28.965079Z", + "iopub.status.idle": "2026-12-03T20:02:43.806610Z", + "shell.execute_reply": "2026-12-03T20:02:43.803485Z" + } + }, + "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", + "candidate thresholds: [0.222, 0.778, 1.0]\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.51.00.66730
suggested (0.778)0.51.00.66730
\n", + "
" + ], + "text/plain": [ + " recall precision f1_score true_positive false_positive\n", + "current (0.9) 0.5 1.0 0.667 3 0\n", + "suggested (0.778) 0.5 1.0 0.667 3 0" + ] + }, + "execution_count": 4, + "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", + "print(\"candidate thresholds:\", [round(point.threshold, 3) for point in judge_suggestion.operating_points])\n", + "holdout_comparison(judge_suggestion)" + ] + }, + { + "cell_type": "markdown", + "id": "ff8d26bd", + "metadata": {}, + "source": [ + "### Reading the result\n", + "\n", + "- **Candidate thresholds** are the distinct scores the judge gave on the tuning split. An LLM judge\n", + " often uses only a few points of its scale, so there may be only a few thresholds to choose from,\n", + " and any value between two neighboring candidates behaves like the higher one.\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", + "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. A threshold fits the dataset it was tuned\n", + "on; tune again when the judge model, 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": 5, + "id": "6223ffcc", + "metadata": { + "execution": { + "iopub.execute_input": "2026-12-03T20:02:43.814823Z", + "iopub.status.busy": "2026-12-03T20:02:43.814312Z", + "iopub.status.idle": "2026-12-03T20:02:43.825023Z", + "shell.execute_reply": "2026-12-03T20:02:43.821187Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.7777777777777778\n" + ] + } + ], + "source": [ + "tuned_scorer = FloatScaleThresholdScorer(scorer=judge, threshold=judge_suggestion.threshold)\n", + "print(tuned_scorer.threshold)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "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..e040c39c4e --- /dev/null +++ b/doc/code/scoring/float_scale_threshold_metrics.py @@ -0,0 +1,154 @@ +# --- +# 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 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 ({round(suggestion.threshold, 3)})": 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" +) +print("candidate thresholds:", [round(point.threshold, 3) for point in judge_suggestion.operating_points]) +holdout_comparison(judge_suggestion) + +# %% [markdown] +# ### Reading the result +# +# - **Candidate thresholds** are the distinct scores the judge gave on the tuning split. An LLM judge +# often uses only a few points of its scale, so there may be only a few thresholds to choose from, +# and any value between two neighboring candidates behaves like the higher one. +# - **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. +# +# 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. 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 ecaab655f6..f0cbab20b9 100644 --- a/doc/myst.yml +++ b/doc/myst.yml @@ -198,7 +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/9_choosing_a_threshold.ipynb + - file: code/scoring/float_scale_threshold_metrics.ipynb - file: code/scoring/multi_label_true_false.md - file: code/scoring/scorer_stability.md - file: code/memory/0_memory.md From 94d74ceabea07cff08f05bf9f13a49843487c4c4 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Thu, 3 Dec 2026 12:30:10 -0800 Subject: [PATCH 6/9] Keep tuned scores and show exact thresholds in threshold docs ThresholdSuggestion now keeps the scores and labels it tuned on, so callers can re-tune without scoring again, and leaves the long fields out of repr. The docs show the exact suggested threshold and warn against rounding it, list the judge's operating points, re-split the kept scores, and are linked from the combining and float-scale scorer pages. The regenerated notebook is stripped like the other docs notebooks. Co-Authored-By: Claude Opus 5.5 --- doc/code/scoring/2_float_scale_scorers.ipynb | 3 +- doc/code/scoring/2_float_scale_scorers.py | 3 +- doc/code/scoring/3_combining_scorers.ipynb | 3 +- doc/code/scoring/3_combining_scorers.py | 3 +- .../float_scale_threshold_metrics.ipynb | 292 +++++++++++++----- .../scoring/float_scale_threshold_metrics.py | 41 ++- .../scorer_evaluation/threshold_suggestion.py | 20 +- tests/unit/score/test_threshold_suggestion.py | 15 + 8 files changed, 285 insertions(+), 95 deletions(-) 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/float_scale_threshold_metrics.ipynb b/doc/code/scoring/float_scale_threshold_metrics.ipynb index f40204b913..ad22c5747f 100644 --- a/doc/code/scoring/float_scale_threshold_metrics.ipynb +++ b/doc/code/scoring/float_scale_threshold_metrics.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "1f416997", + "id": "1dadd38a", "metadata": {}, "source": [ "# Objective Metrics for Float-Scale Scorers: Choosing a Threshold\n", @@ -23,7 +23,7 @@ "\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 observed score as the threshold and pick the one with the best F1,\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", @@ -32,7 +32,7 @@ }, { "cell_type": "markdown", - "id": "8b6f0d01", + "id": "aa643383", "metadata": {}, "source": [ "## How the threshold changes the metrics\n", @@ -45,16 +45,9 @@ }, { "cell_type": "code", - "execution_count": 1, - "id": "efad9daa", - "metadata": { - "execution": { - "iopub.execute_input": "2026-12-03T20:02:21.241371Z", - "iopub.status.busy": "2026-12-03T20:02:21.240975Z", - "iopub.status.idle": "2026-12-03T20:02:28.912751Z", - "shell.execute_reply": "2026-12-03T20:02:28.909444Z" - } - }, + "execution_count": null, + "id": "c40271f6", + "metadata": {}, "outputs": [ { "data": { @@ -111,7 +104,7 @@ "suggested (0.33) 0.902 0.83 0.865 83 17" ] }, - "execution_count": 1, + "execution_count": null, "metadata": {}, "output_type": "execute_result" } @@ -133,7 +126,7 @@ " \"\"\"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 ({round(suggestion.threshold, 3)})\": suggestion.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", @@ -147,7 +140,7 @@ }, { "cell_type": "markdown", - "id": "8b472071", + "id": "7e380d02", "metadata": {}, "source": [ "`operating_points` lists the metrics at every candidate threshold on the tuning split, which shows\n", @@ -156,16 +149,9 @@ }, { "cell_type": "code", - "execution_count": 2, - "id": "d34d9808", - "metadata": { - "execution": { - "iopub.execute_input": "2026-12-03T20:02:28.919851Z", - "iopub.status.busy": "2026-12-03T20:02:28.919004Z", - "iopub.status.idle": "2026-12-03T20:02:28.939069Z", - "shell.execute_reply": "2026-12-03T20:02:28.936577Z" - } - }, + "execution_count": null, + "id": "46419e4f", + "metadata": {}, "outputs": [ { "data": { @@ -294,7 +280,7 @@ "72 0.90 0.055 1.000 0 86" ] }, - "execution_count": 2, + "execution_count": null, "metadata": {}, "output_type": "execute_result" } @@ -307,7 +293,7 @@ }, { "cell_type": "markdown", - "id": "eb3cd2a7", + "id": "59930707", "metadata": {}, "source": [ "If false positives matter more than missed successes, set a precision floor instead of maximizing\n", @@ -316,16 +302,9 @@ }, { "cell_type": "code", - "execution_count": 3, - "id": "450b547c", - "metadata": { - "execution": { - "iopub.execute_input": "2026-12-03T20:02:28.945158Z", - "iopub.status.busy": "2026-12-03T20:02:28.944645Z", - "iopub.status.idle": "2026-12-03T20:02:28.958609Z", - "shell.execute_reply": "2026-12-03T20:02:28.955970Z" - } - }, + "execution_count": null, + "id": "53822f73", + "metadata": {}, "outputs": [ { "name": "stdout", @@ -345,7 +324,7 @@ }, { "cell_type": "markdown", - "id": "1b42af48", + "id": "9bea2a34", "metadata": {}, "source": [ "## Tuning a scorer's threshold\n", @@ -361,16 +340,9 @@ }, { "cell_type": "code", - "execution_count": 4, - "id": "d9c93107", - "metadata": { - "execution": { - "iopub.execute_input": "2026-12-03T20:02:28.965497Z", - "iopub.status.busy": "2026-12-03T20:02:28.965079Z", - "iopub.status.idle": "2026-12-03T20:02:43.806610Z", - "shell.execute_reply": "2026-12-03T20:02:43.803485Z" - } - }, + "execution_count": null, + "id": "e3a1fa11", + "metadata": {}, "outputs": [ { "name": "stdout", @@ -391,8 +363,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "tuned on 16 responses, checked on 14, left out 0 without a score\n", - "candidate thresholds: [0.222, 0.778, 1.0]\n" + "tuned on 16 responses, checked on 14, left out 0 without a score\n" ] }, { @@ -433,7 +404,7 @@ " 0\n", " \n", " \n", - " suggested (0.778)\n", + " suggested (0.7777777777777778)\n", " 0.5\n", " 1.0\n", " 0.667\n", @@ -445,12 +416,16 @@ "" ], "text/plain": [ - " recall precision f1_score true_positive false_positive\n", - "current (0.9) 0.5 1.0 0.667 3 0\n", - "suggested (0.778) 0.5 1.0 0.667 3 0" + " recall precision f1_score true_positive \\\n", + "current (0.9) 0.5 1.0 0.667 3 \n", + "suggested (0.7777777777777778) 0.5 1.0 0.667 3 \n", + "\n", + " false_positive \n", + "current (0.9) 0 \n", + "suggested (0.7777777777777778) 0 " ] }, - "execution_count": 4, + "execution_count": null, "metadata": {}, "output_type": "execute_result" } @@ -482,29 +457,202 @@ " f\"checked on {judge_suggestion.num_holdout_responses}, \"\n", " f\"left out {judge_suggestion.num_excluded_responses} without a score\"\n", ")\n", - "print(\"candidate thresholds:\", [round(point.threshold, 3) for point in judge_suggestion.operating_points])\n", "holdout_comparison(judge_suggestion)" ] }, { "cell_type": "markdown", - "id": "ff8d26bd", + "id": "0c1a15e7", + "metadata": {}, + "source": [ + "The candidate thresholds are the distinct nonzero scores the judge gave on the tuning split:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9b1e3543", + "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", + "
thresholdrecallprecisiontrue_positivefalse_positive
00.7777780.4291.030
11.0000000.2861.020
\n", + "
" + ], + "text/plain": [ + " threshold recall precision true_positive false_positive\n", + "0 0.777778 0.429 1.0 3 0\n", + "1 1.000000 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})" + ] + }, + { + "cell_type": "markdown", + "id": "27a2b39e", "metadata": {}, "source": [ "### Reading the result\n", "\n", - "- **Candidate thresholds** are the distinct scores the judge gave on the tuning split. An LLM judge\n", - " often uses only a few points of its scale, so there may be only a few thresholds to choose from,\n", - " and any value between two neighboring candidates behaves like the higher one.\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": "97af2b36", + "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.6671.00.840
suggested (0.7777777777777778)0.6671.00.840
\n", + "
" + ], + "text/plain": [ + " recall precision f1_score true_positive \\\n", + "current (0.9) 0.667 1.0 0.8 4 \n", + "suggested (0.7777777777777778) 0.667 1.0 0.8 4 \n", + "\n", + " false_positive \n", + "current (0.9) 0 \n", + "suggested (0.7777777777777778) 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": "014fb737", + "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. A threshold fits the dataset it was tuned\n", - "on; tune again when the judge model, rubric, or kind of objective changes.\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):" @@ -512,16 +660,9 @@ }, { "cell_type": "code", - "execution_count": 5, - "id": "6223ffcc", - "metadata": { - "execution": { - "iopub.execute_input": "2026-12-03T20:02:43.814823Z", - "iopub.status.busy": "2026-12-03T20:02:43.814312Z", - "iopub.status.idle": "2026-12-03T20:02:43.825023Z", - "shell.execute_reply": "2026-12-03T20:02:43.821187Z" - } - }, + "execution_count": null, + "id": "bf0903cb", + "metadata": {}, "outputs": [ { "name": "stdout", @@ -538,11 +679,6 @@ } ], "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, "language_info": { "codemirror_mode": { "name": "ipython", diff --git a/doc/code/scoring/float_scale_threshold_metrics.py b/doc/code/scoring/float_scale_threshold_metrics.py index e040c39c4e..4fe81142d8 100644 --- a/doc/code/scoring/float_scale_threshold_metrics.py +++ b/doc/code/scoring/float_scale_threshold_metrics.py @@ -27,7 +27,7 @@ # # 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 observed score as the threshold and pick the one with the best F1, +# 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 @@ -58,7 +58,7 @@ 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 ({round(suggestion.threshold, 3)})": suggestion.holdout_point, + f"suggested ({suggestion.threshold})": suggestion.holdout_point, } columns = ["recall", "precision", "f1_score", "true_positive", "false_positive"] return pd.DataFrame.from_dict( @@ -127,24 +127,49 @@ def holdout_comparison(suggestion: ThresholdSuggestion) -> pd.DataFrame: f"checked on {judge_suggestion.num_holdout_responses}, " f"left out {judge_suggestion.num_excluded_responses} without a score" ) -print("candidate thresholds:", [round(point.threshold, 3) for point in judge_suggestion.operating_points]) 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}) + # %% [markdown] # ### Reading the result # -# - **Candidate thresholds** are the distinct scores the judge gave on the tuning split. An LLM judge -# often uses only a few points of its scale, so there may be only a few thresholds to choose from, -# and any value between two neighboring candidates behaves like the higher one. +# - **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. A threshold fits the dataset it was tuned -# on; tune again when the judge model, rubric, or kind of objective changes. +# 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): diff --git a/pyrit/score/scorer_evaluation/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py index a370f630c6..72719dfaef 100644 --- a/pyrit/score/scorer_evaluation/threshold_suggestion.py +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -10,7 +10,7 @@ from __future__ import annotations -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING import numpy as np @@ -72,14 +72,15 @@ class ThresholdSuggestion: 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. + 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. + 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. @@ -87,6 +88,11 @@ class ThresholdSuggestion: 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 @@ -94,13 +100,15 @@ class ThresholdSuggestion: min_precision: float | None tuning_point: ThresholdOperatingPoint holdout_point: ThresholdOperatingPoint | None - operating_points: tuple[ThresholdOperatingPoint, ...] + 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 @@ -117,7 +125,7 @@ def suggest_threshold( 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 + 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 @@ -204,6 +212,8 @@ def at(*, threshold: float | None, index: np.ndarray) -> ThresholdOperatingPoint 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, + labels=gold, ) diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py index 63be869780..749ce03fcb 100644 --- a/tests/unit/score/test_threshold_suggestion.py +++ b/tests/unit/score/test_threshold_suggestion.py @@ -65,6 +65,16 @@ def test_suggest_threshold_candidates_are_observed_positive_scores() -> None: 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_min_precision_maximizes_recall_subject_to_floor() -> None: suggestion = suggest_threshold(scores=SCORES, labels=LABELS, holdout_fraction=0, min_precision=1.0) @@ -250,6 +260,10 @@ async def score_async(**kwargs): 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: @@ -270,6 +284,7 @@ async def test_suggest_threshold_async_runs_each_trial(mock_threshold_scorer: Ma 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]) From 6dfe8be35c2d93e0b809ae8e79977952e11510fd Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Thu, 3 Dec 2026 12:37:08 -0800 Subject: [PATCH 7/9] Show full-precision thresholds and copy kept arrays The judge operating-points table now shows each threshold exactly, so a copied value matches the scorer's verdicts. ThresholdSuggestion copies the scores and labels it keeps, so later changes to the caller's arrays do not alter it. Co-Authored-By: Claude Opus 5.5 --- .../float_scale_threshold_metrics.ipynb | 87 ++++++++++--------- .../scoring/float_scale_threshold_metrics.py | 2 +- .../scorer_evaluation/threshold_suggestion.py | 4 +- tests/unit/score/test_threshold_suggestion.py | 11 +++ 4 files changed, 62 insertions(+), 42 deletions(-) diff --git a/doc/code/scoring/float_scale_threshold_metrics.ipynb b/doc/code/scoring/float_scale_threshold_metrics.ipynb index ad22c5747f..55ce3ea560 100644 --- a/doc/code/scoring/float_scale_threshold_metrics.ipynb +++ b/doc/code/scoring/float_scale_threshold_metrics.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "1dadd38a", + "id": "c5d27562", "metadata": {}, "source": [ "# Objective Metrics for Float-Scale Scorers: Choosing a Threshold\n", @@ -32,7 +32,7 @@ }, { "cell_type": "markdown", - "id": "aa643383", + "id": "5e825c0e", "metadata": {}, "source": [ "## How the threshold changes the metrics\n", @@ -46,7 +46,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c40271f6", + "id": "06f55e40", "metadata": {}, "outputs": [ { @@ -140,7 +140,7 @@ }, { "cell_type": "markdown", - "id": "7e380d02", + "id": "e0866e44", "metadata": {}, "source": [ "`operating_points` lists the metrics at every candidate threshold on the tuning split, which shows\n", @@ -150,7 +150,7 @@ { "cell_type": "code", "execution_count": null, - "id": "46419e4f", + "id": "e577829d", "metadata": {}, "outputs": [ { @@ -293,7 +293,7 @@ }, { "cell_type": "markdown", - "id": "59930707", + "id": "76bfe2f6", "metadata": {}, "source": [ "If false positives matter more than missed successes, set a precision floor instead of maximizing\n", @@ -303,7 +303,7 @@ { "cell_type": "code", "execution_count": null, - "id": "53822f73", + "id": "905a6077", "metadata": {}, "outputs": [ { @@ -324,7 +324,7 @@ }, { "cell_type": "markdown", - "id": "9bea2a34", + "id": "d8631c63", "metadata": {}, "source": [ "## Tuning a scorer's threshold\n", @@ -341,7 +341,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e3a1fa11", + "id": "418d0bb9", "metadata": {}, "outputs": [ { @@ -397,15 +397,15 @@ " \n", " \n", " current (0.9)\n", - " 0.5\n", + " 0.333\n", " 1.0\n", - " 0.667\n", - " 3\n", + " 0.500\n", + " 2\n", " 0\n", " \n", " \n", - " suggested (0.7777777777777778)\n", - " 0.5\n", + " suggested (0.6666666666666666)\n", + " 0.500\n", " 1.0\n", " 0.667\n", " 3\n", @@ -417,12 +417,12 @@ ], "text/plain": [ " recall precision f1_score true_positive \\\n", - "current (0.9) 0.5 1.0 0.667 3 \n", - "suggested (0.7777777777777778) 0.5 1.0 0.667 3 \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.7777777777777778) 0 " + "suggested (0.6666666666666666) 0 " ] }, "execution_count": null, @@ -462,7 +462,7 @@ }, { "cell_type": "markdown", - "id": "0c1a15e7", + "id": "78b97557", "metadata": {}, "source": [ "The candidate thresholds are the distinct nonzero scores the judge gave on the tuning split:" @@ -471,7 +471,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9b1e3543", + "id": "93c1094a", "metadata": {}, "outputs": [ { @@ -505,15 +505,23 @@ " \n", " \n", " 0\n", - " 0.777778\n", + " 0.6666666666666666\n", + " 0.571\n", + " 1.0\n", + " 4\n", + " 0\n", + " \n", + " \n", + " 1\n", + " 0.7777777777777778\n", " 0.429\n", " 1.0\n", " 3\n", " 0\n", " \n", " \n", - " 1\n", - " 1.000000\n", + " 2\n", + " 1.0\n", " 0.286\n", " 1.0\n", " 2\n", @@ -524,9 +532,10 @@ "" ], "text/plain": [ - " threshold recall precision true_positive false_positive\n", - "0 0.777778 0.429 1.0 3 0\n", - "1 1.000000 0.286 1.0 2 0" + " 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, @@ -537,12 +546,12 @@ "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})" + "].round({\"recall\": 3, \"precision\": 3}).astype({\"threshold\": str})" ] }, { "cell_type": "markdown", - "id": "27a2b39e", + "id": "9b60d5e5", "metadata": {}, "source": [ "### Reading the result\n", @@ -566,7 +575,7 @@ { "cell_type": "code", "execution_count": null, - "id": "97af2b36", + "id": "8472794d", "metadata": {}, "outputs": [ { @@ -600,17 +609,17 @@ " \n", " \n", " current (0.9)\n", - " 0.667\n", + " 0.500\n", " 1.0\n", - " 0.8\n", - " 4\n", + " 0.667\n", + " 3\n", " 0\n", " \n", " \n", - " suggested (0.7777777777777778)\n", + " suggested (0.6666666666666666)\n", " 0.667\n", " 1.0\n", - " 0.8\n", + " 0.800\n", " 4\n", " 0\n", " \n", @@ -620,12 +629,12 @@ ], "text/plain": [ " recall precision f1_score true_positive \\\n", - "current (0.9) 0.667 1.0 0.8 4 \n", - "suggested (0.7777777777777778) 0.667 1.0 0.8 4 \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.7777777777777778) 0 " + "suggested (0.6666666666666666) 0 " ] }, "execution_count": null, @@ -645,7 +654,7 @@ }, { "cell_type": "markdown", - "id": "014fb737", + "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", @@ -661,14 +670,14 @@ { "cell_type": "code", "execution_count": null, - "id": "bf0903cb", + "id": "34570ea0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "0.7777777777777778\n" + "0.6666666666666666\n" ] } ], diff --git a/doc/code/scoring/float_scale_threshold_metrics.py b/doc/code/scoring/float_scale_threshold_metrics.py index 4fe81142d8..41e7698a21 100644 --- a/doc/code/scoring/float_scale_threshold_metrics.py +++ b/doc/code/scoring/float_scale_threshold_metrics.py @@ -135,7 +135,7 @@ def holdout_comparison(suggestion: ThresholdSuggestion) -> pd.DataFrame: # %% pd.DataFrame([vars(point) for point in judge_suggestion.operating_points])[ ["threshold", "recall", "precision", "true_positive", "false_positive"] -].round({"recall": 3, "precision": 3}) +].round({"recall": 3, "precision": 3}).astype({"threshold": str}) # %% [markdown] # ### Reading the result diff --git a/pyrit/score/scorer_evaluation/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py index 72719dfaef..864418635f 100644 --- a/pyrit/score/scorer_evaluation/threshold_suggestion.py +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -212,8 +212,8 @@ def at(*, threshold: float | None, index: np.ndarray) -> ThresholdOperatingPoint 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, - labels=gold, + scores=score_matrix.copy(), + labels=gold.copy(), ) diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py index 749ce03fcb..11a11f40be 100644 --- a/tests/unit/score/test_threshold_suggestion.py +++ b/tests/unit/score/test_threshold_suggestion.py @@ -75,6 +75,17 @@ def test_suggest_threshold_keeps_inputs_out_of_repr() -> None: 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) From 492adb1eefa4e3cc5c6a6d2cf8c6a517487b7f22 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Fri, 4 Dec 2026 15:42:33 -0800 Subject: [PATCH 8/9] FIX: Make threshold suggestion reruns and input checks match the evaluator - Skip dataset messages already in memory, so the same HumanLabeledDataset can be scored again. - Share the human-score matrix and majority vote with the evaluator, so ragged rater counts fail the same way before scoring. - Check the scorer keeps a float on each verdict before any scoring call. - Reject tuning data where every gold-true score is 0.0. - Test that tuning ignores the held-out split. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../scorer_evaluation/scorer_evaluator.py | 70 +++++++++++--- .../scorer_evaluation/threshold_suggestion.py | 31 ++++-- tests/unit/score/test_threshold_suggestion.py | 96 +++++++++++++++++-- 3 files changed, 169 insertions(+), 28 deletions(-) diff --git a/pyrit/score/scorer_evaluation/scorer_evaluator.py b/pyrit/score/scorer_evaluation/scorer_evaluator.py index fc7f3f5605..7b1ad278fa 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -82,6 +82,36 @@ def _classification_rates( 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: """ @@ -498,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: @@ -753,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, @@ -866,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, " @@ -1058,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, " @@ -1088,8 +1130,8 @@ 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))) diff --git a/pyrit/score/scorer_evaluation/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py index 864418635f..a048f33e8b 100644 --- a/pyrit/score/scorer_evaluation/threshold_suggestion.py +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -15,12 +15,15 @@ import numpy as np -from pyrit.models import FloatFeedback, ScoringExpectation +from pyrit.models import FloatFeedback, ScorerCapabilityName, ScoringExpectation from pyrit.score.scorer_evaluation.scorer_evaluator import ( ObjectiveScorerEvaluator, _classification_rates, + _human_score_matrix, + _majority_vote, _validate_num_scorer_trials, ) +from pyrit.score.scorer_selection import ScorerRequirements if TYPE_CHECKING: from collections.abc import Sequence @@ -29,6 +32,11 @@ from pyrit.score.scorer_evaluation.human_labeled_dataset import HumanLabeledDataset from pyrit.score.true_false.float_scale_threshold_scorer import FloatScaleThresholdScorer +# Tuning reads the float value a true/false verdict was decided from. +_THRESHOLD_SCORER_REQUIREMENTS = ScorerRequirements( + required=frozenset({ScorerCapabilityName.TRUE_FALSE, ScorerCapabilityName.PRESERVES_FLOAT_SCALE_VALUE}) +) + @dataclass(frozen=True) class ThresholdOperatingPoint: @@ -150,8 +158,8 @@ def suggest_threshold( 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``. + 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) @@ -172,6 +180,10 @@ def suggest_threshold( 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 @@ -252,16 +264,19 @@ async def suggest_threshold_async( 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. + ValueError: If ``num_scorer_trials`` is less than 1, the scorer does not return a true/false + verdict that keeps its float value, 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) + _THRESHOLD_SCORER_REQUIREMENTS.validate(scorer=scorer) + current_threshold = scorer.threshold 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) + gold = _majority_vote(_human_score_matrix(human_scores)) == 1 trials = await evaluator._run_scoring_trials_async( responses=responses, @@ -281,7 +296,7 @@ async def suggest_threshold_async( min_precision=min_precision, holdout_fraction=holdout_fraction, seed=seed, - current_threshold=scorer.threshold, + current_threshold=current_threshold, ) return replace(suggestion, num_excluded_responses=int((~determined).sum())) diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py index 11a11f40be..a293baa88a 100644 --- a/tests/unit/score/test_threshold_suggestion.py +++ b/tests/unit/score/test_threshold_suggestion.py @@ -7,7 +7,7 @@ import pytest from pyrit.memory import MemoryInterface -from pyrit.models import FloatFeedback, Message, MessagePiece, Score, ScoreStatus +from pyrit.models import FloatFeedback, Message, MessagePiece, Score, ScorerCapabilityName, ScoreStatus from pyrit.score import ( FloatScaleThresholdScorer, HumanLabeledDataset, @@ -147,6 +147,29 @@ def test_suggest_threshold_holdout_is_stratified_and_disjoint() -> 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 @@ -188,6 +211,10 @@ def test_suggest_threshold_accepts_zero_one_labels() -> None: ({"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", @@ -235,6 +262,7 @@ def mock_threshold_scorer() -> MagicMock: 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 @@ -246,12 +274,12 @@ async def test_suggest_threshold_async_uses_kept_float_values(mock_threshold_sco metrics_type=MetricsType.OBJECTIVE, version="1.0", entries=[ - _entry("a", [True]), - _entry("b", [True, True, False]), - _entry("c", [True]), - _entry("d", [False]), + _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]), + _entry("f", [True, True]), ], ) @@ -340,3 +368,59 @@ async def test_suggest_threshold_async_rejects_options_before_scoring( 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_without_kept_float_before_scoring( + mock_threshold_scorer: MagicMock, +) -> None: + dataset = HumanLabeledDataset( + name="threshold_test", metrics_type=MetricsType.OBJECTIVE, version="1.0", entries=[_entry("a", [True])] + ) + mock_threshold_scorer.capabilities.includes.side_effect = lambda *, capability: ( + capability != ScorerCapabilityName.PRESERVES_FLOAT_SCALE_VALUE + ) + mock_threshold_scorer.score_async = AsyncMock(return_value=[_threshold_score(0.95)]) + + with pytest.raises(ValueError, match=ScorerCapabilityName.PRESERVES_FLOAT_SCALE_VALUE.value): + await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0) + + mock_threshold_scorer._memory.add_message_to_memory_async.assert_not_awaited() + mock_threshold_scorer.score_async.assert_not_awaited() From 6ec3af8636a9a5ed9c7184dc74566fee9d5db2c6 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Fri, 4 Dec 2026 16:45:41 -0800 Subject: [PATCH 9/9] Require a FloatScaleThresholdScorer in suggest_threshold_async The capability check accepted a TrueFalseFallbackScorer of two threshold scorers, which then failed on the missing threshold attribute. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../scorer_evaluation/threshold_suggestion.py | 17 +++++--------- tests/unit/score/test_threshold_suggestion.py | 23 +++++++++---------- 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/pyrit/score/scorer_evaluation/threshold_suggestion.py b/pyrit/score/scorer_evaluation/threshold_suggestion.py index a048f33e8b..38ec101fe6 100644 --- a/pyrit/score/scorer_evaluation/threshold_suggestion.py +++ b/pyrit/score/scorer_evaluation/threshold_suggestion.py @@ -15,7 +15,7 @@ import numpy as np -from pyrit.models import FloatFeedback, ScorerCapabilityName, ScoringExpectation +from pyrit.models import FloatFeedback, ScoringExpectation from pyrit.score.scorer_evaluation.scorer_evaluator import ( ObjectiveScorerEvaluator, _classification_rates, @@ -23,19 +23,13 @@ _majority_vote, _validate_num_scorer_trials, ) -from pyrit.score.scorer_selection import ScorerRequirements +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 - from pyrit.score.true_false.float_scale_threshold_scorer import FloatScaleThresholdScorer - -# Tuning reads the float value a true/false verdict was decided from. -_THRESHOLD_SCORER_REQUIREMENTS = ScorerRequirements( - required=frozenset({ScorerCapabilityName.TRUE_FALSE, ScorerCapabilityName.PRESERVES_FLOAT_SCALE_VALUE}) -) @dataclass(frozen=True) @@ -264,14 +258,15 @@ async def suggest_threshold_async( ThresholdSuggestion: The suggested threshold with its tuning and held-out results. Raises: - ValueError: If ``num_scorer_trials`` is less than 1, the scorer does not return a true/false - verdict that keeps its float value, the dataset is not a valid OBJECTIVE dataset (including + 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) - _THRESHOLD_SCORER_REQUIREMENTS.validate(scorer=scorer) + 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) diff --git a/tests/unit/score/test_threshold_suggestion.py b/tests/unit/score/test_threshold_suggestion.py index a293baa88a..432ec128bf 100644 --- a/tests/unit/score/test_threshold_suggestion.py +++ b/tests/unit/score/test_threshold_suggestion.py @@ -7,12 +7,13 @@ import pytest from pyrit.memory import MemoryInterface -from pyrit.models import FloatFeedback, Message, MessagePiece, Score, ScorerCapabilityName, ScoreStatus +from pyrit.models import FloatFeedback, Message, MessagePiece, Score, ScoreStatus from pyrit.score import ( FloatScaleThresholdScorer, HumanLabeledDataset, MetricsType, ObjectiveHumanLabeledEntry, + TrueFalseFallbackScorer, suggest_threshold, suggest_threshold_async, ) @@ -408,19 +409,17 @@ async def test_suggest_threshold_async_rejects_ragged_human_scores_before_scorin mock_threshold_scorer.score_async.assert_not_awaited() -async def test_suggest_threshold_async_rejects_scorer_without_kept_float_before_scoring( - mock_threshold_scorer: MagicMock, -) -> None: +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])] ) - mock_threshold_scorer.capabilities.includes.side_effect = lambda *, capability: ( - capability != ScorerCapabilityName.PRESERVES_FLOAT_SCALE_VALUE - ) - mock_threshold_scorer.score_async = AsyncMock(return_value=[_threshold_score(0.95)]) + 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=ScorerCapabilityName.PRESERVES_FLOAT_SCALE_VALUE.value): - await suggest_threshold_async(scorer=mock_threshold_scorer, labeled_dataset=dataset, holdout_fraction=0) + with pytest.raises(ValueError, match="tunes a FloatScaleThresholdScorer"): + await suggest_threshold_async(scorer=fallback, labeled_dataset=dataset, holdout_fraction=0) - mock_threshold_scorer._memory.add_message_to_memory_async.assert_not_awaited() - mock_threshold_scorer.score_async.assert_not_awaited() + fallback._memory.add_message_to_memory_async.assert_not_awaited() + fallback.score_async.assert_not_awaited()