"""Token-level probe scoring - localise reward hacking inside a response.
:func:`rhscope.activations.extract_activations` returns one pooled
activation per example, which is right for the primary scoring flow
(one monitor score per rollout). This module adds the orthogonal
capability: *per-token* scoring, so a trained probe can tell you
*which tokens* in a response look hack-like.
Use cases:
- **Attribution.** Show the user which fragment of a response the
monitor is reacting to (hardcoded return, test-deletion comment,
fake assertion, etc).
- **Mid-generation early stop.** During RL rollout generation, score
the partial response every N tokens and abort if the maximum-so-far
crosses a threshold - cheaper than letting the full rollout finish
and penalising afterwards.
- **Span-level benchmarks.** Compute the probe's response-span max and
report it as the detector output when the probe was trained with
response-level labels.
The scoring path reuses the probe's `` score(activations)`` method
without modification. Probes are linear in hidden state, so per-token
and per-example scores are two different reductions of the same
underlying forward pass.
"""
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.metadata import PoolingStrategy
from rhscope.probes.base import Probe
logger = logging.getLogger(__name__)
[docs]
@dataclass(frozen=True)
class TokenScoreResult:
"""Per-response token-level probe scoring.
Attributes:
response_tokens: Decoded token strings for each example, aligned
with ``per_token_scores``. Prompt tokens are excluded.
per_token_scores: Per-token probe scores, one 1-D numpy array
per example. Higher means more hack-like.
max_score: ``(N,)`` per-example maximum score over response
tokens. Suitable as a drop-in scalar in place of the usual
pooled probe score.
argmax_token: ``(N,)`` per-example index of the peak-scoring
response token; ``response_tokens[i][argmax_token[i]]`` is
the single token the probe reacted to most strongly.
"""
response_tokens: list[list[str]]
per_token_scores: list[np.ndarray]
max_score: np.ndarray
argmax_token: np.ndarray
def _ensure_pad_token(tokenizer: Any) -> str | None:
"""Temporarily pad with eos if no pad token; return the original value."""
saved: str | None = tokenizer.pad_token
if tokenizer.pad_token is None and tokenizer.eos_token is not None:
tokenizer.pad_token = tokenizer.eos_token
return saved
def _decode_response_tokens(
tokenizer: Any, prompt: str, response: str, max_length: int
) -> list[str]:
"""Decode the per-token strings for the response portion only.
Tokenises prompt and response separately (matching
:func:`extract_token_activations`) so the returned list aligns with
the hidden-state slice the probe will score.
"""
prompt_ids = tokenizer(
prompt,
return_tensors=None,
padding=False,
truncation=True,
max_length=max_length,
)["input_ids"]
response_ids = tokenizer(
response,
return_tensors=None,
padding=False,
truncation=True,
max_length=max_length,
)["input_ids"]
budget = max(0, max_length - len(prompt_ids))
response_ids = response_ids[:budget]
return [tokenizer.decode([tid], skip_special_tokens=False) for tid in response_ids]
[docs]
def score_tokens(
probe: Probe,
model: Any,
tokenizer: Any,
prompts: Sequence[str],
responses: Sequence[str],
*,
layer: int | None = None,
batch_size: int = 4,
max_length: int = 1024,
device: str | torch.device | None = None,
) -> TokenScoreResult:
"""Score every response token with a trained probe.
Args:
probe: A fitted probe. The probe must expose a
:meth:`~rhscope.probes.base.Probe.score` method that accepts
activations of shape ``(T, hidden_dim)``.
model: Hugging Face causal LM the probe was trained on.
tokenizer: Matching tokenizer.
prompts: One prompt per example.
responses: Response text aligned with ``prompts``.
layer: Hidden-state layer. Defaults to ``probe.metadata.layer``.
batch_size: Examples per forward pass.
max_length: Truncation length for ``prompt + response``.
device: Target device; defaults to the model's device.
Returns:
:class:`TokenScoreResult` with per-token scores, per-example
max, and the index of the peak-scoring response token.
"""
resolved_layer = layer if layer is not None else int(probe.metadata.layer)
token_acts = extract_token_activations(
model,
tokenizer,
prompts,
responses,
layer=resolved_layer,
batch_size=batch_size,
max_length=max_length,
device=device,
)
per_token_scores: list[np.ndarray] = []
max_scores: list[float] = []
argmaxes: list[int] = []
tokens_per_example: list[list[str]] = []
for prompt, response, acts in zip(prompts, responses, token_acts, strict=True):
tokens = _decode_response_tokens(tokenizer, prompt, response, max_length)
# Align: slice tokens to the activation length (truncation may differ).
tokens = tokens[: acts.shape[0]]
tokens_per_example.append(tokens)
if acts.shape[0] == 0:
per_token_scores.append(np.asarray([], dtype=np.float64))
max_scores.append(float("-inf"))
argmaxes.append(-1)
continue
scores = probe.score(acts).detach().cpu().float().numpy()
scores = scores.reshape(-1).astype(np.float64)
per_token_scores.append(scores)
max_scores.append(float(scores.max()))
argmaxes.append(int(scores.argmax()))
return TokenScoreResult(
response_tokens=tokens_per_example,
per_token_scores=per_token_scores,
max_score=np.asarray(max_scores, dtype=np.float64),
argmax_token=np.asarray(argmaxes, dtype=np.int64),
)
# Pooling-strategy type is imported for the type-signature docs in tests;
# re-exported so callers can reference it without a deep import path.
__all__ = [
"PoolingStrategy",
"TokenScoreResult",
"extract_token_activations",
"score_tokens",
]