Skip to content
Merged
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
12 changes: 6 additions & 6 deletions pyrit/executor/promptgen/gcg/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

import json
from dataclasses import asdict, dataclass, field
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Self

if TYPE_CHECKING:
from pathlib import Path
Expand Down Expand Up @@ -125,7 +125,7 @@ def to_json(self) -> str:
return json.dumps(asdict(self), indent=2)

@classmethod
def from_json(cls, payload: str) -> GCGDataConfig:
def from_json(cls, payload: str) -> Self:
"""
Deserialize a config previously produced by ``to_json``.

Expand All @@ -142,7 +142,7 @@ def from_json(cls, payload: str) -> GCGDataConfig:
return cls(**data)

@classmethod
def from_json_file(cls, path: str | Path) -> GCGDataConfig:
def from_json_file(cls, path: str | Path) -> Self:
"""
Load a config from a JSON file.

Expand Down Expand Up @@ -391,7 +391,7 @@ def to_json(self) -> str:
return json.dumps(asdict(self), indent=2)

@classmethod
def from_json(cls, payload: str) -> GCGConfig:
def from_json(cls, payload: str) -> Self:
"""
Deserialize a config previously produced by ``to_json``.

Expand All @@ -413,7 +413,7 @@ def from_json(cls, payload: str) -> GCGConfig:
return cls._from_dict(data)

@classmethod
def from_json_file(cls, path: str | Path) -> GCGConfig:
def from_json_file(cls, path: str | Path) -> Self:
"""
Load a config from a JSON file produced by ``to_json_file``.

Expand All @@ -437,7 +437,7 @@ def to_json_file(self, path: str | Path) -> None:
f.write(self.to_json())

@classmethod
def _from_dict(cls, data: dict[str, Any]) -> GCGConfig:
def _from_dict(cls, data: dict[str, Any]) -> Self:
if "models" not in data or not isinstance(data["models"], list):
raise ValueError("GCGConfig payload must contain a 'models' list.")
return cls(
Expand Down
20 changes: 12 additions & 8 deletions pyrit/scenario/core/technique_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,17 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, NamedTuple
from typing import TYPE_CHECKING, Generic, Literal, NamedTuple, TypeVar

if TYPE_CHECKING:
from collections.abc import Sequence

from pyrit.converter import Converter
from pyrit.scenario.core.scenario_technique import ScenarioTechnique
from pyrit.registry import InstanceRegistry
from pyrit.scenario import ScenarioTechnique


TechniqueT = TypeVar("TechniqueT", bound="ScenarioTechnique")

CONVERTER_MODIFIER_PREFIX = "converter."

Expand Down Expand Up @@ -81,20 +85,20 @@ class TechniqueTokenIssue:


@dataclass(frozen=True)
class TechniqueTokenResolution:
class TechniqueTokenResolution(Generic[TechniqueT]):
"""Everything a set of technique tokens resolved to, plus what did not resolve."""

techniques: list[Any] = field(default_factory=list)
techniques: list[TechniqueT] = field(default_factory=list)
technique_converters: dict[str, list[Converter]] = field(default_factory=dict)
issues: list[TechniqueTokenIssue] = field(default_factory=list)


def resolve_technique_tokens(
*,
tokens: Sequence[str],
technique_class: type[ScenarioTechnique],
technique_class: type[TechniqueT],
scenario_name: str,
) -> TechniqueTokenResolution:
) -> TechniqueTokenResolution[TechniqueT]:
"""
Resolve technique tokens into technique members and their additive converters.

Expand All @@ -111,8 +115,8 @@ def resolve_technique_tokens(
TechniqueTokenResolution: Resolved technique members, converters keyed by
concrete technique name, and the references that did not resolve.
"""
resolution = TechniqueTokenResolution()
converter_instances: Any = None
resolution: TechniqueTokenResolution[TechniqueT] = TechniqueTokenResolution()
converter_instances: InstanceRegistry[Converter] | None = None

for token in tokens:
base_name, modifiers = parse_technique_token(token)
Expand Down
42 changes: 41 additions & 1 deletion tests/unit/executor/promptgen/gcg/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from __future__ import annotations

import json
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, assert_type

import pytest

Expand Down Expand Up @@ -255,6 +255,46 @@ def test_data_config_json_round_trip(tmp_path: Path) -> None:
assert GCGDataConfig.from_json_file(target) == original


class _DerivedGCGDataConfig(GCGDataConfig):
pass


class _DerivedGCGConfig(GCGConfig):
pass


def test_json_factories_preserve_data_config_subclass(tmp_path: Path) -> None:
original = _DerivedGCGDataConfig(train_data="train.csv", n_train_data=2)

from_json = _DerivedGCGDataConfig.from_json(original.to_json())
assert_type(from_json, _DerivedGCGDataConfig)
assert isinstance(from_json, _DerivedGCGDataConfig)
assert from_json == original

target = tmp_path / "data.json"
original.to_json_file(target)
from_file = _DerivedGCGDataConfig.from_json_file(target)
assert_type(from_file, _DerivedGCGDataConfig)
assert isinstance(from_file, _DerivedGCGDataConfig)
assert from_file == original


def test_json_factories_preserve_config_subclass(tmp_path: Path) -> None:
original = _DerivedGCGConfig(models=[GCGModelConfig(name=_LLAMA_2)])

from_json = _DerivedGCGConfig.from_json(original.to_json())
assert_type(from_json, _DerivedGCGConfig)
assert isinstance(from_json, _DerivedGCGConfig)
assert from_json.models == original.models

target = tmp_path / "config.json"
original.to_json_file(target)
from_file = _DerivedGCGConfig.from_json_file(target)
assert_type(from_file, _DerivedGCGConfig)
assert isinstance(from_file, _DerivedGCGConfig)
assert from_file.models == original.models


def test_to_json_is_pretty_printed() -> None:
payload = _minimal_config().to_json()
assert "\n" in payload
Expand Down
47 changes: 47 additions & 0 deletions tests/unit/scenario/core/test_technique_tokens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from typing import assert_type

from pyrit.scenario import ScenarioTechnique
from pyrit.scenario.core import TechniqueTokenResolution, parse_technique_token, resolve_technique_tokens


class _TypedTechnique(ScenarioTechnique):
ALL = ("all", {"all"})
First = ("first", set())
Second = ("second", set())


def test_parse_technique_token_preserves_ordered_modifiers() -> None:
parsed = parse_technique_token("first:converter.one:converter.two")

assert parsed.base_name == "first"
assert parsed.modifiers == ("converter.one", "converter.two")


def test_resolve_technique_tokens_preserves_concrete_technique_type() -> None:
resolution = resolve_technique_tokens(
tokens=["first", "second"],
technique_class=_TypedTechnique,
scenario_name="typed-test",
)

assert_type(resolution, TechniqueTokenResolution[_TypedTechnique])
assert_type(resolution.techniques, list[_TypedTechnique])
assert resolution.techniques == [_TypedTechnique.First, _TypedTechnique.Second]
assert resolution.technique_converters == {}
assert resolution.issues == []


def test_resolve_technique_tokens_reports_invalid_techniques_without_changing_types() -> None:
resolution = resolve_technique_tokens(
tokens=["missing", "first"],
technique_class=_TypedTechnique,
scenario_name="typed-test",
)

assert_type(resolution.techniques, list[_TypedTechnique])
assert resolution.techniques == [_TypedTechnique.First]
assert [issue.kind for issue in resolution.issues] == ["unknown_technique"]
assert resolution.issues[0].name == "missing"
Loading