Source code for rhscope.training.data

"""Data types and loaders for probe training.

Training data is a flat JSONL file where each line is a ``HackExample``:

    {"prompt": "...", "response": "...", "is_hacking": true, "category": "..."}

Only ``prompt``, ``response``, and ``is_hacking`` are required. ``category`` is
optional and respected when the probe is category-specific; ``source`` and
``extra`` allow tracking data provenance without changing the schema.
"""

from __future__ import annotations

import hashlib
import json
import random
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any


[docs] @dataclass class HackExample: """A single labeled example for probe training. Attributes: prompt: User-facing prompt (as seen by the model). response: Model continuation to be scored. is_hacking: ``True`` if the response exemplifies reward-hacking behavior, ``False`` otherwise. category: Optional RH-Detect category (e.g. ``"code_shortcut"``). source: Optional provenance tag (dataset name, filename, …). extra: Arbitrary extra fields preserved across load/save. """ prompt: str response: str is_hacking: bool category: str | None = None source: str | None = None extra: dict[str, Any] = field(default_factory=dict)
[docs] def to_dict(self) -> dict[str, Any]: """Return a JSON-serializable dict representation.""" return asdict(self)
[docs] @classmethod def from_dict(cls, data: dict[str, Any]) -> HackExample: """Parse a dict (e.g. from a JSONL line) into a ``HackExample``. Unknown keys land in ``extra`` so forward-compatible fields survive round trips through older code. """ known_keys = {"prompt", "response", "is_hacking", "category", "source", "extra"} payload = {k: data[k] for k in known_keys if k in data} if "prompt" not in payload or "response" not in payload or "is_hacking" not in payload: raise ValueError("HackExample requires 'prompt', 'response', and 'is_hacking' fields.") extra = dict(payload.get("extra", {})) for k, v in data.items(): if k not in known_keys: extra[k] = v payload["extra"] = extra return cls( prompt=str(payload["prompt"]), response=str(payload["response"]), is_hacking=bool(payload["is_hacking"]), category=payload.get("category"), source=payload.get("source"), extra=extra, )
[docs] def load_hack_examples(path: str | Path) -> list[HackExample]: """Load a JSONL file of ``HackExample`` records. Args: path: File to read. One JSON object per line, UTF-8 encoded. Returns: List of parsed examples in file order. Raises: FileNotFoundError: If the path does not exist. ValueError: If any line is not valid JSON or is missing required fields. """ p = Path(path) if not p.is_file(): raise FileNotFoundError(f"HackExample JSONL not found: {p}") out: list[HackExample] = [] with p.open("r", encoding="utf-8") as fh: for lineno, line in enumerate(fh, start=1): line = line.strip() if not line: continue try: data = json.loads(line) except json.JSONDecodeError as e: raise ValueError(f"{p}:{lineno}: invalid JSON: {e}") from e try: out.append(HackExample.from_dict(data)) except ValueError as e: raise ValueError(f"{p}:{lineno}: {e}") from e return out
[docs] def save_hack_examples(path: str | Path, examples: list[HackExample]) -> Path: """Write examples to a JSONL file. Overwrites any existing content.""" p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) with p.open("w", encoding="utf-8") as fh: for ex in examples: fh.write(json.dumps(ex.to_dict(), ensure_ascii=False) + "\n") return p
[docs] def split_hack_clean( examples: list[HackExample], ) -> tuple[list[HackExample], list[HackExample]]: """Partition examples by ``is_hacking``. Returns: ``(hack_examples, clean_examples)``. """ hack = [e for e in examples if e.is_hacking] clean = [e for e in examples if not e.is_hacking] return hack, clean
[docs] def train_val_split( examples: list[HackExample], val_fraction: float, *, seed: int = 0, stratify: bool = True, ) -> tuple[list[HackExample], list[HackExample]]: """Deterministic train/val split, optionally stratified by label. Args: examples: Examples to split. val_fraction: Fraction allocated to the validation set, in ``(0, 1)``. seed: RNG seed for the shuffle. stratify: Preserve the hack/clean ratio in both halves. Default True. Returns: ``(train, val)``. """ if not 0.0 < val_fraction < 1.0: raise ValueError(f"val_fraction must be in (0, 1), got {val_fraction}.") rng = random.Random(seed) if not stratify: shuffled = examples.copy() rng.shuffle(shuffled) cut = round(len(shuffled) * (1.0 - val_fraction)) return shuffled[:cut], shuffled[cut:] hack, clean = split_hack_clean(examples) rng.shuffle(hack) rng.shuffle(clean) hack_cut = round(len(hack) * (1.0 - val_fraction)) clean_cut = round(len(clean) * (1.0 - val_fraction)) train = hack[:hack_cut] + clean[:clean_cut] val = hack[hack_cut:] + clean[clean_cut:] rng.shuffle(train) rng.shuffle(val) return train, val
[docs] def hash_examples(examples: list[HackExample]) -> str: """Return a stable SHA-256 hex digest over the examples' canonical content. Used for training-data provenance metadata so saved probes can be traced back to a specific dataset. """ hasher = hashlib.sha256() for ex in examples: payload = { "prompt": ex.prompt, "response": ex.response, "is_hacking": ex.is_hacking, "category": ex.category, } hasher.update(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8")) hasher.update(b"\n") return hasher.hexdigest()