Source code for rhscope.bench.detectors

"""Detector interface and baseline implementations.

A ``Detector`` scores ``(prompt, response)`` pairs on a hacking-vs-clean axis.
Baselines (random, token-count) provide floor comparisons; ``ProbeDetector``
wraps a trained ``Probe`` with the activation-extraction glue required to
score free-form text.
"""

from __future__ import annotations

from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import Any, Literal

import numpy as np

from rhscope.activations import extract_activations
from rhscope.probes.base import Probe


[docs] class Detector(ABC): """Abstract base class for reward-hacking detectors. Concrete detectors implement ``score_batch``. ``name`` is used for bookkeeping in benchmark results. """ name: str = "detector"
[docs] @abstractmethod def score_batch( self, prompts: Sequence[str], responses: Sequence[str], ) -> np.ndarray: """Return a 1-D numpy array of scores (higher = more hack-like)."""
[docs] class RandomDetector(Detector): """Baseline that emits uniform random scores. AUROC should be ~0.5.""" name = "random" def __init__(self, seed: int = 0) -> None: self._rng = np.random.default_rng(seed)
[docs] def score_batch( self, prompts: Sequence[str], responses: Sequence[str], ) -> np.ndarray: """Return i.i.d. uniform ``[0, 1)`` scores, one per example.""" if len(prompts) != len(responses): raise ValueError("prompts and responses must have the same length.") return self._rng.random(len(prompts))
[docs] class TokenCountDetector(Detector): """Baseline that uses response length as the hacking score. Longer responses often correlate with verbosity-type hacking; this baseline exists mostly to confirm that any serious probe clearly beats "count tokens". """ name = "token_count"
[docs] def score_batch( self, prompts: Sequence[str], responses: Sequence[str], ) -> np.ndarray: """Return the whitespace-token count of each response as its score.""" if len(prompts) != len(responses): raise ValueError("prompts and responses must have the same length.") return np.asarray([float(len(r.split())) for r in responses], dtype=np.float64)
[docs] class ProbeDetector(Detector): """Wrap a trained ``Probe`` with activation extraction. Attributes: probe: Trained ``Probe`` whose ``metadata.layer`` and ``metadata.pooling`` drive activation extraction. model: Loaded Hugging Face causal LM that the probe was trained against. tokenizer: Matching tokenizer. batch_size: Mini-batch size for forward passes. max_length: Token truncation length. """ def __init__( self, probe: Probe, model: Any, tokenizer: Any, *, batch_size: int = 8, max_length: int = 1024, ) -> None: self.probe = probe self.model = model self.tokenizer = tokenizer self.batch_size = batch_size self.max_length = max_length self.name = f"probe[{probe.metadata.probe_type}@L{probe.metadata.layer}]"
[docs] def score_batch( self, prompts: Sequence[str], responses: Sequence[str], ) -> np.ndarray: """Run the wrapped probe against activations of ``(prompt, response)``.""" if len(prompts) != len(responses): raise ValueError("prompts and responses must have the same length.") if len(prompts) == 0: return np.asarray([], dtype=np.float64) acts = extract_activations( self.model, self.tokenizer, list(prompts), list(responses), layers=self.probe.metadata.layer, pooling=self.probe.metadata.pooling, batch_size=self.batch_size, max_length=self.max_length, ) tensor = acts[self.probe.metadata.layer] scores = self.probe.score(tensor).detach().cpu().float().numpy() return np.asarray(scores, dtype=np.float64)
Reducer = Literal["mean", "max", "min", "sum", "weighted_mean"] """Supported reducers for :class:`CompositeDetector`. - ``"mean"``: equal-weight average. - ``"max"`` / ``"min"``: element-wise max / min (strict aggregator / veto). - ``"sum"``: raw sum; useful when each sub-detector's scale is already calibrated. - ``"weighted_mean"``: ``sum(w_i * s_i) / sum(w_i)`` - requires ``weights``. """
[docs] class CompositeDetector(Detector): """Ensemble multiple :class:`Detector` instances into one. All sub-detectors are called on the same ``(prompts, responses)`` batch and their outputs are reduced element-wise into a single score vector. Common use cases: - Probe + LLM-judge fusion: ``CompositeDetector([probe_det, judge_det], "mean")``. - Veto ensemble: ``CompositeDetector([probe, rule], "max")`` - any sub-detector firing flags the response. - Weighted combination: pass ``weights=[1.0, 0.3]`` with ``reducer="weighted_mean"``. The composite does **not** rescale its inputs. Sub-detectors with wildly different output scales should be normalized (e.g. sigmoid) before being composed - otherwise one detector dominates the reduction. Attributes: detectors: Sub-detectors, scored in order. reducer: Reduction strategy. weights: Per-detector weights for ``reducer="weighted_mean"``; otherwise unused. """ def __init__( self, detectors: Sequence[Detector], reducer: Reducer = "mean", *, weights: Sequence[float] | None = None, name: str | None = None, ) -> None: if not detectors: raise ValueError("CompositeDetector requires at least one sub-detector.") self._detectors = list(detectors) self._reducer = reducer self._weights = self._validate_weights(weights, len(self._detectors), reducer) self.name = name if name is not None else self._auto_name() @staticmethod def _validate_weights( weights: Sequence[float] | None, n_detectors: int, reducer: Reducer, ) -> np.ndarray | None: if reducer != "weighted_mean": if weights is not None: raise ValueError( f"weights are only used for reducer='weighted_mean'; " f"got {len(weights)} weights with reducer={reducer!r}." ) return None if weights is None: raise ValueError("reducer='weighted_mean' requires explicit weights.") arr = np.asarray(weights, dtype=np.float64) if arr.ndim != 1 or arr.shape[0] != n_detectors: raise ValueError( f"weights length must equal detector count; got {arr.shape[0]} " f"weights for {n_detectors} detectors." ) if (arr < 0).any(): raise ValueError("weights must be non-negative.") if arr.sum() == 0: raise ValueError("weights must sum to a positive value.") return arr def _auto_name(self) -> str: parts = ",".join(d.name for d in self._detectors) return f"composite[{self._reducer}]({parts})" @property def detectors(self) -> list[Detector]: """Sub-detectors, in the order they are scored and reduced.""" return list(self._detectors) @property def reducer(self) -> Reducer: """Reduction strategy used across sub-detector scores.""" return self._reducer
[docs] def score_batch( self, prompts: Sequence[str], responses: Sequence[str], ) -> np.ndarray: """Score ``(prompts, responses)`` with every sub-detector and reduce.""" if len(prompts) != len(responses): raise ValueError("prompts and responses must have the same length.") if not prompts: return np.asarray([], dtype=np.float64) per_detector = np.stack( [ np.asarray(d.score_batch(prompts, responses), dtype=np.float64) for d in self._detectors ] ) # shape: (n_detectors, n_examples) if self._reducer == "mean": return np.asarray(per_detector.mean(axis=0), dtype=np.float64) if self._reducer == "max": return np.asarray(per_detector.max(axis=0), dtype=np.float64) if self._reducer == "min": return np.asarray(per_detector.min(axis=0), dtype=np.float64) if self._reducer == "sum": return np.asarray(per_detector.sum(axis=0), dtype=np.float64) if self._reducer == "weighted_mean": assert self._weights is not None weighted = (per_detector.T * self._weights).T return np.asarray(weighted.sum(axis=0) / self._weights.sum(), dtype=np.float64) raise ValueError(f"Unknown reducer {self._reducer!r}.") # pragma: no cover
[docs] class CallableDetector(Detector): """Adapter wrapping a plain callable as a ``Detector``. Useful for ad-hoc experiments or for scoring with external services during an evaluation sweep. """ def __init__( self, fn: Any, *, name: str = "callable", ) -> None: self._fn = fn self.name = name
[docs] def score_batch( self, prompts: Sequence[str], responses: Sequence[str], ) -> np.ndarray: """Forward to the wrapped callable and validate its output shape.""" out = self._fn(list(prompts), list(responses)) arr = np.asarray(out, dtype=np.float64) if arr.ndim != 1: raise ValueError(f"Callable detector must return 1-D scores; got shape {arr.shape}.") if arr.shape[0] != len(prompts): raise ValueError( f"Callable detector returned {arr.shape[0]} scores for {len(prompts)} inputs." ) return arr