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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion doc/code/analytics/0_attack_results.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,55 @@ identity, score type, or scoring expectation is absent, compatibility cannot be
fully verified. Different matched seed groups may use different scoring contexts
if each individual baseline/attack pair has the same expectation.
Older runs without a saved run plan and separately executed runs are not
supported. The reported difference is descriptive and does not establish that
supported; to compare reruns, use `compute_outcome_repeatability` (below). The reported difference is descriptive and does not establish that
the attack caused an outcome to change. No confidence interval is provided,
because small and constant paired samples need careful uncertainty treatment.

### Compare reruns of the same scenario

Targets and scorers are stochastic, so one run is one sample per objective: two
runs with the same success rate can still disagree on which objectives
succeeded. `compute_outcome_repeatability` compares two or more **separately
executed** runs of the same scenario configuration and reports, for each
objective planned in all of them, whether the attack always succeeded, always
failed, or changed between runs.

```python
from pyrit.analytics import compute_outcome_repeatability

# run_a, run_b and run_c are loaded ScenarioResults of the same configuration,
# each containing hydrated AttackResults.
report = compute_outcome_repeatability([run_a, run_b, run_c])
counts = report.overall
print(counts.always_success, counts.always_failure, counts.mixed)
print(counts.agreement_rate, counts.run_success_rates, counts.rate_range)
print(counts.shared_units, counts.decided_units)
for technique, technique_counts in report.by_technique.items():
print(technique, technique_counts.agreement_rate)
```

Units are matched across runs by their planned
`(atomic_group_id, seed_group_id)`, which are deterministic, and each run
contributes its latest top-level result per unit, selected as
`compute_scenario_statistics` does. `shared_units` counts units planned in every
run, and `decided_units` the shared units whose outcome is success or failure in
every run. `agreement_rate` is `(always_success + always_failure) / decided_units`.
`run_success_counts` and `run_success_rates` follow the order the runs were
passed in, and the rates use `decided_units` as their denominator, so
`rate_range` (highest rate minus lowest) compares the same objectives. All three
are `None` when no unit is decided in every run.

Errored, undetermined and missing outcomes stay out of the denominator and are
counted instead: `error_units`, `undetermined_units` and `missing_units` count
shared units with that outcome in at least one run, so they may overlap.
`partially_planned_units` counts units planned in only some runs. `by_technique`
gives the same counts per technique label; the baseline is labelled `baseline`.

Every run needs a valid saved run plan, and all runs must share one scenario
evaluation hash, the check resume uses to refuse a changed scenario, technique
or dataset selection, target, or scorer; otherwise `ValueError` is raised. The
counts describe agreement and do not include confidence intervals.

### ASSERT policy metrics

`compute_assert_policy_metrics_async(result)` reports **impermissible behavior
Expand Down
8 changes: 8 additions & 0 deletions pyrit/analytics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
from pyrit.analytics.assert_policy_metrics import NotAssertPolicyRunError, compute_assert_policy_metrics_async
from pyrit.analytics.attack_result_analytics import AttackResultAnalytics
from pyrit.analytics.conversation_analytics import ConversationAnalytics
from pyrit.analytics.outcome_repeatability import (
OutcomeRepeatability,
OutcomeRepeatabilityCounts,
compute_outcome_repeatability,
)
from pyrit.analytics.outcome_statistics import combine_outcome_statistics, compute_outcome_statistics
from pyrit.analytics.paired_outcome_statistics import (
PairedOutcomeChildConversation,
Expand Down Expand Up @@ -45,6 +50,7 @@
"combine_outcome_statistics": "pyrit.analytics.outcome_statistics",
"compute_assert_policy_metrics_async": "pyrit.analytics.assert_policy_metrics",
"NotAssertPolicyRunError": "pyrit.analytics.assert_policy_metrics",
"compute_outcome_repeatability": "pyrit.analytics.outcome_repeatability",
"compute_outcome_statistics": "pyrit.analytics.outcome_statistics",
"compute_paired_outcome_statistics": "pyrit.analytics.paired_outcome_statistics",
"get_paired_outcome_details": "pyrit.analytics.paired_outcome_statistics",
Expand All @@ -53,6 +59,8 @@
"compute_technique_stats_async": "pyrit.analytics.technique_analysis",
"count_execution_units": "pyrit.analytics.scenario_statistics",
"ConversationAnalytics": "pyrit.analytics.conversation_analytics",
"OutcomeRepeatability": "pyrit.analytics.outcome_repeatability",
"OutcomeRepeatabilityCounts": "pyrit.analytics.outcome_repeatability",
"PairedOutcomeStatistics": "pyrit.analytics.paired_outcome_statistics",
"PairedOutcomeChildConversation": "pyrit.analytics.paired_outcome_statistics",
"PairedOutcomeDetail": "pyrit.analytics.paired_outcome_statistics",
Expand Down
40 changes: 7 additions & 33 deletions pyrit/analytics/assert_policy_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,14 @@
from dataclasses import dataclass, field
from typing import TYPE_CHECKING

from pyrit.analytics.scenario_statistics import (
ScenarioPlanLookup,
load_scenario_run_plan,
resolve_attack_result_attempt,
)
from pyrit.analytics.scenario_statistics import load_scenario_run_plan, select_effective_attack_results
from pyrit.memory import CentralMemory
from pyrit.models import (
AssertBinaryRate,
AssertCategoryJudgment,
AssertDimensionResult,
AssertPolicyMetrics,
AttackOutcome,
ScenarioExecutionUnit,
ScenarioRunPlanGroupKind,
ScoreStatus,
ViolatesAssertPolicy,
Expand All @@ -49,7 +44,6 @@
from collections.abc import Iterable, Sequence
from datetime import datetime

from pyrit.analytics.scenario_statistics import ScenarioAttempt
from pyrit.memory import MemoryInterface
from pyrit.models import (
AssertNodeJudgment,
Expand Down Expand Up @@ -232,34 +226,14 @@ def _select_effective_results(scenario_result: ScenarioResult) -> list[_Effectiv
list[_EffectiveResult]: The effective results.
"""
plan = load_scenario_run_plan(scenario_result)
lookup = ScenarioPlanLookup.from_plan(plan=plan)
groups = {group.id: group for group in plan.atomic_groups} if plan is not None else {}
planned = (
{
ScenarioExecutionUnit(atomic_group_id=group.id, seed_group_id=seed)
for group in plan.atomic_groups
for seed in group.seed_group_ids
}
if plan is not None
else None
)
attempts: dict[ScenarioExecutionUnit, list[tuple[ScenarioAttempt, AttackResult]]] = {}
for name, results in scenario_result.attack_results.items():
for result in results:
attempt = resolve_attack_result_attempt(atomic_attack_name=name, attack_result=result, plan_lookup=lookup)
if planned is None or attempt.unit in planned:
attempts.setdefault(attempt.unit, []).append((attempt, result))
effective = []
for unit, entries in attempts.items():
completions = sorted(
(entry for entry in entries if entry[0].attempt_index is None),
key=lambda entry: (entry[0].timestamp, entry[0].attempt_id),
return [
_EffectiveResult(
technique=_technique(attempt.atomic_attack_name, group=groups.get(unit.atomic_group_id)),
result=result,
)
if completions:
attempt, result = completions[-1]
technique = _technique(attempt.atomic_attack_name, group=groups.get(unit.atomic_group_id))
effective.append(_EffectiveResult(technique=technique, result=result))
return effective
for unit, (attempt, result) in select_effective_attack_results(scenario_result, plan=plan).items()
]


def _technique(atomic_attack_name: str, *, group: ScenarioRunPlanAtomicGroup | None) -> str:
Expand Down
169 changes: 169 additions & 0 deletions pyrit/analytics/outcome_repeatability.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""
Outcome agreement across separately executed runs of the same scenario configuration.

Ports the logic of ``compute_repeatability`` in ASSERT's ``assert_ai/analysis/stability.py``
(https://github.com/responsibleai/ASSERT, MIT license). Unlike upstream, errored and
undetermined outcomes are counted and kept out of the agreement denominator, per-run rates
cover only the units decided in every run, and the runs must share one configuration.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

from pyrit.analytics.scenario_statistics import load_scenario_run_plan, select_effective_attack_results
from pyrit.models import AttackOutcome, ScenarioEvaluationIdentifier, ScenarioExecutionUnit

if TYPE_CHECKING:
from collections.abc import Sequence

from pyrit.models import ScenarioResult

_DECIDED = (AttackOutcome.SUCCESS, AttackOutcome.FAILURE)


@dataclass(frozen=True, slots=True)
class OutcomeRepeatabilityCounts:
"""
Outcome agreement for one set of execution units across the compared runs.

``shared_units`` counts units planned in every run, and ``decided_units`` the shared units
whose latest top-level outcome is success or failure in every run. ``agreement_rate`` and
each run's success rate use ``decided_units`` as the denominator, so ``rate_range`` compares
the same objectives; they are None when no unit is decided. ``missing_units``,
``error_units`` and ``undetermined_units`` count shared units with that outcome in at least
one run, so they may overlap. ``partially_planned_units`` counts units planned in some runs
only; they are not shared.
"""

shared_units: int
decided_units: int
always_success: int
always_failure: int
mixed: int
agreement_rate: float | None
run_success_counts: tuple[int, ...]
run_success_rates: tuple[float | None, ...]
rate_range: float | None
missing_units: int
error_units: int
undetermined_units: int
partially_planned_units: int


@dataclass(frozen=True, slots=True)
class OutcomeRepeatability:
"""
Outcome agreement across runs, overall and per technique label.

``run_count`` is the number of compared runs; ``run_success_counts`` and
``run_success_rates`` follow the order the runs were passed in. ``by_technique`` is keyed by
each planned group's technique label, which names the baseline ``baseline``.
"""

run_count: int
overall: OutcomeRepeatabilityCounts
by_technique: dict[str, OutcomeRepeatabilityCounts]


def compute_outcome_repeatability(scenario_results: Sequence[ScenarioResult]) -> OutcomeRepeatability:
"""
Compare the outcomes of two or more separately executed runs of one scenario configuration.

Units are matched across runs by their planned ``(atomic_group_id, seed_group_id)``, which
are deterministic, and each run contributes the latest top-level outcome per unit, selected
as ``compute_scenario_statistics`` does. A unit decided in every run counts as
``always_success``, ``always_failure`` or ``mixed``.

Args:
scenario_results (Sequence[ScenarioResult]): The runs to compare, each with its hydrated
attack results.

Returns:
OutcomeRepeatability: Agreement counts and per-run rates, overall and per technique.

Raises:
ValueError: If fewer than two runs are given, a run is given twice, a run has no valid
saved plan, or the runs do not share one scenario configuration.
"""
if len(scenario_results) < 2:
raise ValueError("Outcome repeatability needs at least two scenario runs.")
run_ids = [str(result.id) for result in scenario_results]
if len(set(run_ids)) != len(run_ids):
raise ValueError("Each scenario run can be compared only once.")

plans = []
for result in scenario_results:
plan = load_scenario_run_plan(result)
if plan is None:
raise ValueError(f"Scenario result {result.id} has no valid saved run plan to match units across runs.")
plans.append(plan)
eval_hashes = {ScenarioEvaluationIdentifier(result.scenario_identifier).eval_hash for result in scenario_results}
if len(eval_hashes) > 1:
raise ValueError(
"Outcome repeatability compares runs of the same scenario configuration, but these runs "
"differ in scenario, technique or dataset selection, target, or scorer."
)

planned_by_run: list[set[ScenarioExecutionUnit]] = []
techniques: dict[ScenarioExecutionUnit, str] = {}
for plan in plans:
planned: set[ScenarioExecutionUnit] = set()
for group in plan.atomic_groups:
for seed in group.seed_group_ids:
unit = ScenarioExecutionUnit(atomic_group_id=group.id, seed_group_id=seed)
planned.add(unit)
techniques.setdefault(unit, group.technique_label)
planned_by_run.append(planned)
outcomes_by_run = [
{unit: result.outcome for unit, (_, result) in select_effective_attack_results(scenario, plan=plan).items()}
for scenario, plan in zip(scenario_results, plans, strict=True)
]

shared = set.intersection(*planned_by_run)
partially_planned = set.union(*planned_by_run) - shared
overall = _counts(units=shared, partially_planned=partially_planned, outcomes_by_run=outcomes_by_run)
by_technique = {
technique: _counts(
units={unit for unit in shared if techniques[unit] == technique},
partially_planned={unit for unit in partially_planned if techniques[unit] == technique},
outcomes_by_run=outcomes_by_run,
)
for technique in sorted(set(techniques.values()))
}
return OutcomeRepeatability(run_count=len(scenario_results), overall=overall, by_technique=by_technique)


def _counts(
*,
units: set[ScenarioExecutionUnit],
partially_planned: set[ScenarioExecutionUnit],
outcomes_by_run: list[dict[ScenarioExecutionUnit, AttackOutcome]],
) -> OutcomeRepeatabilityCounts:
decided = [unit for unit in units if all(run.get(unit) in _DECIDED for run in outcomes_by_run)]
successes = [sum(run[unit] == AttackOutcome.SUCCESS for run in outcomes_by_run) for unit in decided]
always_success = sum(count == len(outcomes_by_run) for count in successes)
always_failure = sum(count == 0 for count in successes)
run_success_counts = tuple(sum(run[unit] == AttackOutcome.SUCCESS for unit in decided) for run in outcomes_by_run)
run_success_rates = tuple(count / len(decided) if decided else None for count in run_success_counts)
return OutcomeRepeatabilityCounts(
shared_units=len(units),
decided_units=len(decided),
always_success=always_success,
always_failure=always_failure,
mixed=len(decided) - always_success - always_failure,
agreement_rate=(always_success + always_failure) / len(decided) if decided else None,
run_success_counts=run_success_counts,
run_success_rates=run_success_rates,
rate_range=(max(run_success_counts) - min(run_success_counts)) / len(decided) if decided else None,
missing_units=sum(any(unit not in run for run in outcomes_by_run) for unit in units),
error_units=sum(any(run.get(unit) == AttackOutcome.ERROR for run in outcomes_by_run) for unit in units),
undetermined_units=sum(
any(run.get(unit) == AttackOutcome.UNDETERMINED for run in outcomes_by_run) for unit in units
),
partially_planned_units=len(partially_planned),
)
47 changes: 47 additions & 0 deletions pyrit/analytics/scenario_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,53 @@ def select_execution_attack_result_ids(
}


def select_effective_attack_results(
scenario_result: ScenarioResult,
*,
plan: ScenarioRunPlan | None,
) -> dict[ScenarioExecutionUnit, tuple[ScenarioAttempt, AttackResult]]:
"""
Select the latest top-level attempt for each counted execution unit.

Counted units are the planned units of ``plan``, or every resolved unit when ``plan`` is None,
matching ``compute_scenario_statistics``. Attempts are ordered by timestamp, then attempt ID.
A unit without a top-level completion has no entry.

Args:
scenario_result (ScenarioResult): The scenario result with its hydrated attack results.
plan (ScenarioRunPlan | None): The run plan to resolve units against, or None for a legacy run.

Returns:
dict[ScenarioExecutionUnit, tuple[ScenarioAttempt, AttackResult]]: The selected attempt and
its attack result for each unit that has one.
"""
lookup = ScenarioPlanLookup.from_plan(plan=plan)
planned = (
{
ScenarioExecutionUnit(atomic_group_id=group.id, seed_group_id=seed)
for group in plan.atomic_groups
for seed in group.seed_group_ids
}
if plan is not None
else None
)
attempts: dict[ScenarioExecutionUnit, list[tuple[ScenarioAttempt, AttackResult]]] = {}
for name, results in scenario_result.attack_results.items():
for result in results:
attempt = resolve_attack_result_attempt(atomic_attack_name=name, attack_result=result, plan_lookup=lookup)
if planned is None or attempt.unit in planned:
attempts.setdefault(attempt.unit, []).append((attempt, result))
effective: dict[ScenarioExecutionUnit, tuple[ScenarioAttempt, AttackResult]] = {}
for unit, entries in attempts.items():
completions = sorted(
(entry for entry in entries if entry[0].attempt_index is None),
key=lambda entry: (entry[0].timestamp, entry[0].attempt_id),
)
if completions:
effective[unit] = completions[-1]
return effective


def retry_pressure(*, attempts_per_unit: Iterable[int], persisted_retries: Iterable[int]) -> int:
"""
Combine per-attempt retries with re-attempts of the same execution unit.
Expand Down
Loading