"""Curate :class:`HackExample` subsets from an :class:`RHDetectBench`.
The probe training pipeline (:func:`rhscope.training.train_probe`) consumes
:class:`HackExample` records; the benchmark harness carries
:class:`BenchExample` records. The two schemas differ only in field names -
``label`` vs ``is_hacking``, both carry ``prompt``, ``response``, ``category``.
This module is the glue between the two, plus deterministic subset sampling
for probe-grid training.
Use::
from rhscope.bench import RHDetectBench
from rhscope.bench.curation import curate_subset, curate_grid
bench = RHDetectBench.load_jsonl("rh-detect/test.jsonl")
# One category-specific subset:
code_hack_examples = curate_subset(bench, category="code_shortcut", n=2000)
# Full grid of curated subsets, one per category plus a balanced "general":
subsets = curate_grid(
bench,
category_names=["code_shortcut", "format_gaming", "verbosity"],
per_category=2000,
general=5000,
)
"""
from __future__ import annotations
import logging
import random
from collections.abc import Iterable, Mapping
from rhscope.bench.rhdetect import BenchExample, RHDetectBench
from rhscope.training.data import HackExample
logger = logging.getLogger(__name__)
[docs]
def bench_to_hack_example(example: BenchExample) -> HackExample:
"""Convert a :class:`BenchExample` into a :class:`HackExample`.
All fields are preserved; ``source`` moves into ``extra`` since
:class:`HackExample` has a dedicated ``source`` attribute already.
"""
extra = dict(example.extra) if example.extra else {}
return HackExample(
prompt=example.prompt,
response=example.response,
is_hacking=example.label,
category=example.category,
source=example.source or None,
extra=extra,
)
def _balance_binary(
examples: list[BenchExample],
target: int | None,
rng: random.Random,
) -> list[BenchExample]:
"""Return a shuffled subset with the two labels balanced 50/50.
Args:
examples: Candidate pool.
target: Target total size. If ``None``, uses ``2 * min(positives, negatives)``
- i.e. the maximum balanced size without upsampling.
rng: RNG used to pick which examples make the cut.
Returns:
A list of at most ``target`` examples with equal counts of
``label=True`` and ``label=False``, shuffled.
"""
positives = [e for e in examples if e.label]
negatives = [e for e in examples if not e.label]
max_per_class = min(len(positives), len(negatives))
if max_per_class == 0:
logger.warning(
"Cannot build a balanced subset: pool has %d positives and %d negatives.",
len(positives),
len(negatives),
)
return []
per_class = max_per_class if target is None else min(max_per_class, target // 2)
rng.shuffle(positives)
rng.shuffle(negatives)
chosen = positives[:per_class] + negatives[:per_class]
rng.shuffle(chosen)
return chosen
[docs]
def curate_subset(
bench: RHDetectBench,
*,
category: str,
n: int | None = None,
seed: int = 0,
balance: bool = True,
) -> list[HackExample]:
"""Build a category-specific :class:`HackExample` subset from ``bench``.
Args:
bench: Source benchmark.
category: Which behavior category to pull. Must appear in at least
one of the bench's examples.
n: Target subset size. Clamped to the largest balanced size
available if ``balance=True``. If ``None``, returns the maximum
balanced subset.
seed: RNG seed for the sampling.
balance: If True, hack / clean counts are equalized before sampling.
Returns:
A shuffled list of :class:`HackExample` records.
Raises:
ValueError: If the pool for ``category`` is empty.
"""
pool = [e for e in bench.examples if e.category == category]
if not pool:
available = sorted({e.category for e in bench.examples})
raise ValueError(
f"No examples found for category {category!r}. Available categories: {available}."
)
rng = random.Random(seed)
chosen = (
_balance_binary(pool, target=n, rng=rng)
if balance
else rng.sample(pool, min(len(pool), n or len(pool)))
)
logger.info(
"curate_subset(category=%r): selected %d / %d (requested n=%s, balance=%s).",
category,
len(chosen),
len(pool),
n,
balance,
)
return [bench_to_hack_example(e) for e in chosen]
[docs]
def curate_general_subset(
bench: RHDetectBench,
*,
n: int,
seed: int = 0,
categories: Iterable[str] | None = None,
) -> list[HackExample]:
"""Build a *general* subset - balanced across both hack/clean AND categories.
The result approximates ``n`` total examples split evenly across every
category present in the bench (or the explicit ``categories`` list), with
each per-category slice internally balanced for ``is_hacking``.
Args:
bench: Source benchmark.
n: Target total size.
seed: RNG seed.
categories: Optional explicit category list. Defaults to every
category appearing in the bench.
Returns:
A shuffled list of :class:`HackExample` records.
Raises:
ValueError: If no categories can be used.
"""
if n <= 0:
raise ValueError(f"n must be positive, got {n}.")
all_categories = sorted({e.category for e in bench.examples})
requested = list(categories) if categories is not None else all_categories
missing = sorted(set(requested) - set(all_categories))
if missing:
raise ValueError(
f"Requested categories not present in bench: {missing}. Available: {all_categories}."
)
if not requested:
raise ValueError("No categories available for a general subset.")
per_cat_target = max(2, n // len(requested))
rng = random.Random(seed)
combined: list[HackExample] = []
for cat in requested:
pool = [e for e in bench.examples if e.category == cat]
balanced = _balance_binary(pool, target=per_cat_target, rng=rng)
combined.extend(bench_to_hack_example(e) for e in balanced)
rng.shuffle(combined)
if len(combined) > n:
combined = combined[:n]
logger.info(
"curate_general_subset: %d examples across %d categories (requested n=%d).",
len(combined),
len(requested),
n,
)
return combined
[docs]
def curate_grid(
bench: RHDetectBench,
*,
category_names: Iterable[str],
per_category: int,
general: int | None = None,
seed: int = 0,
include_general: bool = True,
general_key: str = "general",
) -> dict[str, list[HackExample]]:
"""Build a full grid of curated subsets suitable for probe-matrix training.
Args:
bench: Source benchmark.
category_names: Categories to produce one subset per.
per_category: Target size per category-specific subset.
general: Target size for the balanced-across-categories subset.
Defaults to ``per_category * len(category_names)``.
seed: Base RNG seed. Each category uses a derived seed so changing
``category_names`` order does not reshuffle other categories.
include_general: Whether to include the balanced subset at all.
general_key: Dict key under which the balanced subset is stored.
Returns:
``{category_or_key: [HackExample, ...]}``.
Raises:
ValueError: If the category list contains duplicates or
``general_key`` collides with a category name.
"""
categories = list(category_names)
if len(set(categories)) != len(categories):
raise ValueError(f"category_names contains duplicates: {categories}.")
if include_general and general_key in categories:
raise ValueError(
f"general_key {general_key!r} collides with a category name; choose a different key."
)
subsets: dict[str, list[HackExample]] = {}
for idx, cat in enumerate(categories):
subsets[cat] = curate_subset(
bench,
category=cat,
n=per_category,
seed=seed + idx + 1,
balance=True,
)
if include_general:
target = general if general is not None else per_category * len(categories)
subsets[general_key] = curate_general_subset(
bench, n=target, seed=seed, categories=categories
)
return subsets
[docs]
def hack_examples_by_category(
examples: Iterable[HackExample],
) -> Mapping[str, list[HackExample]]:
"""Group a list of :class:`HackExample` by their ``category`` field.
Examples with ``category is None`` are dropped with a warning - probe
training requires a non-empty category label.
"""
grouped: dict[str, list[HackExample]] = {}
orphans = 0
for ex in examples:
if ex.category is None:
orphans += 1
continue
grouped.setdefault(ex.category, []).append(ex)
if orphans:
logger.warning(
"hack_examples_by_category: dropped %d examples with no category.",
orphans,
)
return grouped