Source code for rhscope.integrations.dpo

"""Offline monitor scoring for DPO-style preference datasets.

DPO (and its siblings IPO, KTO, ORPO, SimPO) optimize a policy against
preference pairs - chosen / rejected completions for a shared prompt - with
no online rollouts. There is no reward signal to penalize mid-training, so
the natural integration point is *before* training: score both halves of
each pair with the monitor and let the caller filter or re-weight
preferences that reward hacking behaviors.

:func:`score_dpo_pairs` is the single entry point. Its return value carries
both score vectors plus per-pair metadata that downstream code can turn into
filter masks.
"""

from __future__ import annotations

import logging
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any

import numpy as np
import torch

from rhscope.activations import extract_activations
from rhscope.monitor import HackMonitor

logger = logging.getLogger(__name__)


[docs] @dataclass(frozen=True) class DPOPairScores: """Monitor scores for a batch of DPO preference pairs. Attributes: chosen_scores: ``(N,)`` scores for the preferred completion of each pair. rejected_scores: ``(N,)`` scores for the dispreferred completion. threshold: The monitor's binary-decision threshold at scoring time. preference_flips_to_hacker: Boolean mask; ``True`` where the chosen completion scores higher than the rejected - i.e. the preference data rewards *more* hacking. Prime candidates for filtering. """ chosen_scores: np.ndarray rejected_scores: np.ndarray threshold: float preference_flips_to_hacker: np.ndarray def __len__(self) -> int: return int(self.chosen_scores.shape[0]) @property def mean_chosen(self) -> float: """Mean monitor score across chosen completions (``0.0`` if empty).""" return float(self.chosen_scores.mean()) if len(self) else 0.0 @property def mean_rejected(self) -> float: """Mean monitor score across rejected completions (``0.0`` if empty).""" return float(self.rejected_scores.mean()) if len(self) else 0.0 @property def hacking_rate_chosen(self) -> float: """Fraction of chosen completions whose score is at or above threshold.""" if len(self) == 0: return 0.0 return float((self.chosen_scores >= self.threshold).mean()) @property def hacking_rate_rejected(self) -> float: """Fraction of rejected completions at or above threshold.""" if len(self) == 0: return 0.0 return float((self.rejected_scores >= self.threshold).mean())
[docs] def filter_mask(self, *, drop_preference_flips: bool = True) -> np.ndarray: """Return a boolean mask over pairs the caller may want to keep. Args: drop_preference_flips: If True, excludes pairs where the chosen completion is more hack-like than the rejected (i.e. the preference data is actively pushing the policy toward hacking). Returns: ``(N,)`` boolean array; ``True`` means "keep this pair". """ keep = np.ones(len(self), dtype=bool) if drop_preference_flips: keep &= ~self.preference_flips_to_hacker return keep
[docs] def score_dpo_pairs( monitor: HackMonitor, model: Any, tokenizer: Any, prompts: Sequence[str], chosen: Sequence[str], rejected: Sequence[str], *, batch_size: int = 8, max_length: int = 1024, ) -> DPOPairScores: """Score both halves of every preference pair with ``monitor``. The chosen and rejected completions are scored independently against the policy model that ``monitor`` was trained for - the caller is responsible for aligning the ``model`` argument with ``monitor.base_model``. Args: monitor: Loaded :class:`HackMonitor`. model: Policy model whose activations the probe reads. Should match ``monitor.base_model``. tokenizer: Matching tokenizer. prompts: Shared prompts, one per preference pair. chosen: Preferred completions, aligned with ``prompts``. rejected: Dispreferred completions, aligned with ``prompts``. batch_size: Forward-pass batch size. max_length: Token truncation length. Returns: :class:`DPOPairScores` carrying both score vectors. Raises: ValueError: If input lengths differ. """ n = len(prompts) if not (len(chosen) == n == len(rejected)): raise ValueError( f"Lengths must match: prompts={n}, chosen={len(chosen)}, rejected={len(rejected)}." ) if n == 0: empty = np.asarray([], dtype=np.float64) return DPOPairScores( chosen_scores=empty, rejected_scores=empty, threshold=monitor.threshold, preference_flips_to_hacker=np.asarray([], dtype=bool), ) prompt_list = [str(p) for p in prompts] chosen_list = [str(c) for c in chosen] rejected_list = [str(r) for r in rejected] with torch.no_grad(): chosen_acts = extract_activations( model, tokenizer, prompt_list, chosen_list, layers=monitor.layer, pooling=monitor.pooling, batch_size=batch_size, max_length=max_length, )[monitor.layer] rejected_acts = extract_activations( model, tokenizer, prompt_list, rejected_list, layers=monitor.layer, pooling=monitor.pooling, batch_size=batch_size, max_length=max_length, )[monitor.layer] chosen_scores = monitor.score(chosen_acts).detach().cpu().float().numpy() rejected_scores = monitor.score(rejected_acts).detach().cpu().float().numpy() flips = chosen_scores > rejected_scores return DPOPairScores( chosen_scores=chosen_scores, rejected_scores=rejected_scores, threshold=monitor.threshold, preference_flips_to_hacker=flips, )