Source code for rhscope.probes.tokens

"""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
[docs] def extract_token_activations( model: Any, tokenizer: Any, prompts: Sequence[str], responses: Sequence[str], *, layer: int, batch_size: int = 4, max_length: int = 1024, device: str | torch.device | None = None, ) -> list[torch.Tensor]: """Return per-response-token hidden states at the given layer. The returned list has one tensor per example of shape ``(T_response_i, hidden_dim)`` on CPU in float32. Prompt tokens are excluded because they are not what the probe is supposed to score. Args: model: Loaded Hugging Face causal LM. tokenizer: Matching tokenizer. prompts: One prompt per example. responses: Response text aligned with ``prompts``. layer: Hidden-state layer index. ``0`` is the embedding layer; ``1..num_hidden_layers`` are transformer block outputs. batch_size: Examples per forward pass. max_length: Truncation length for ``prompt + response``. device: Target device; defaults to the model's device. Returns: One ``(T, hidden_dim)`` float32 tensor per example on CPU. """ if len(prompts) != len(responses): raise ValueError("prompts and responses must have the same length.") model_device = device if device is not None else next(model.parameters()).device saved_pad = _ensure_pad_token(tokenizer) pad_id = int(getattr(tokenizer, "pad_token_id", None) or 0) # Tokenize prompt and response separately, then concatenate token ids. # This avoids subword-boundary drift from tokenizing ``p + r`` as one # string (which also matters for a whitespace-based test tokenizer). prompt_tokens = tokenizer( list(prompts), return_tensors=None, padding=False, truncation=True, max_length=max_length, )["input_ids"] response_tokens = tokenizer( list(responses), return_tensors=None, padding=False, truncation=True, max_length=max_length, )["input_ids"] combined_ids: list[list[int]] = [] response_spans: list[tuple[int, int]] = [] # (start, end) inclusive-exclusive for p_ids, r_ids in zip(prompt_tokens, response_tokens, strict=True): budget = max_length - len(p_ids) if budget < 0: p_ids = p_ids[:max_length] budget = 0 r_ids = r_ids[:budget] if budget > 0 else [] joined = list(p_ids) + list(r_ids) combined_ids.append(joined) response_spans.append((len(p_ids), len(joined))) result: list[torch.Tensor | None] = [None] * len(prompts) try: model.eval() for start in range(0, len(prompts), batch_size): batch_indices = range(start, min(start + batch_size, len(prompts))) batch_id_lists = [combined_ids[i] for i in batch_indices] max_seq = max((len(row) for row in batch_id_lists), default=1) if max_seq == 0: continue padded = [row + [pad_id] * (max_seq - len(row)) for row in batch_id_lists] mask = [[1] * len(row) + [0] * (max_seq - len(row)) for row in batch_id_lists] input_ids = torch.tensor(padded, dtype=torch.long, device=model_device) attention_mask = torch.tensor(mask, dtype=torch.long, device=model_device) with torch.no_grad(): outputs = model( input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True, use_cache=False, ) hidden = outputs.hidden_states[layer] # (B, S, H) hidden_cpu = hidden.detach().cpu().float() for batch_pos, global_idx in enumerate(batch_indices): r_start, r_end = response_spans[global_idx] if r_start >= r_end: result[global_idx] = hidden_cpu[batch_pos, :0] else: result[global_idx] = hidden_cpu[batch_pos, r_start:r_end] finally: if saved_pad is None and tokenizer.pad_token == tokenizer.eos_token: # Leaving pad=eos is safer than reverting to None mid-pipeline. pass out: list[torch.Tensor] = [] for r in result: if r is None: # pragma: no cover - would indicate internal bug raise RuntimeError("Internal error: unfilled token activation slot.") out.append(r) return out
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", ]