"""Grid trainer for the pre-trained probe matrix.
A *probe grid* is the Cartesian product of (models) x (categories).
Nothing in this module is specific to any particular model or category
count; a single call trains the full matrix end-to-end.
The driver, :func:`train_probe_grid`, takes:
- A list of :class:`ModelConfig` (any Hugging Face causal LMs).
- A list of category names to train probes for.
- A :class:`RHDetectBench` to curate training data from.
and produces, for each (model, category) cell:
- A trained probe artifact on disk.
- A model card alongside it.
- An entry in a :class:`ProbeGridResult` with the per-cell metrics.
Pushing to the Hub is optional and controlled by ``push_to_hub``. Nothing in
this module requires a specific model vendor.
"""
from __future__ import annotations
import json
import logging
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from rhscope.bench.curation import curate_general_subset, curate_subset
from rhscope.bench.rhdetect import RHDetectBench
from rhscope.hub import push_probe_to_hub
from rhscope.model_card import ModelCardExtras, save_model_card
from rhscope.recipes.config import ModelConfig
from rhscope.recipes.grpo import _load_base_model, set_global_seed
from rhscope.training.data import HackExample
from rhscope.training.trainer import ProbeType, TrainProbeResult, train_probe
logger = logging.getLogger(__name__)
GENERAL_KEY = "general"
"""Canonical name for the across-categories balanced probe."""
[docs]
@dataclass(frozen=True)
class ProbeGridCellResult:
"""Outcome of training a single (model, category) cell.
Attributes:
model_name_or_path: HF model ID or local path.
category: Category trained on (``"general"`` for the balanced subset).
probe_stem: Local probe stem on disk.
model_card_path: Model-card markdown file alongside the artifact.
val_auroc: Validation AUROC of the winning layer.
best_layer: Winning transformer-block index.
train_examples: Count of examples in the final (train + val) fit.
hub_url: Hub URL if ``push_to_hub=True``; ``None`` otherwise.
weak: True iff ``val_auroc < weak_threshold`` - surfaces
under-performing cells without silently filtering them.
"""
model_name_or_path: str
category: str
probe_stem: Path
model_card_path: Path
val_auroc: float
best_layer: int
train_examples: int
hub_url: str | None
weak: bool
[docs]
@dataclass
class ProbeGridResult:
"""Aggregate result of a full grid run.
Attributes:
cells: One :class:`ProbeGridCellResult` per cell, in the order the
grid was walked.
output_dir: Root directory for all per-cell artifacts.
"""
cells: list[ProbeGridCellResult] = field(default_factory=list)
output_dir: Path | None = None
def __len__(self) -> int:
return len(self.cells)
[docs]
def weak_cells(self) -> list[ProbeGridCellResult]:
"""Return cells whose validation AUROC fell below the weak threshold."""
return [c for c in self.cells if c.weak]
[docs]
def summary(self) -> str:
"""Markdown summary table across the grid."""
lines = [
"| Model | Category | Val AUROC | Best layer | Examples | Weak? |",
"|---|---|---|---|---|---|",
]
for cell in self.cells:
flag = "yes" if cell.weak else "no"
lines.append(
f"| `{cell.model_name_or_path}` | `{cell.category}` | "
f"{cell.val_auroc:.4f} | {cell.best_layer} | "
f"{cell.train_examples} | {flag} |"
)
return "\n".join(lines) + "\n"
[docs]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serializable dict representation of the grid result."""
return {
"output_dir": str(self.output_dir) if self.output_dir else None,
"cells": [
{
"model_name_or_path": c.model_name_or_path,
"category": c.category,
"probe_stem": str(c.probe_stem),
"model_card_path": str(c.model_card_path),
"val_auroc": c.val_auroc,
"best_layer": c.best_layer,
"train_examples": c.train_examples,
"hub_url": c.hub_url,
"weak": c.weak,
}
for c in self.cells
],
}
[docs]
def save_json(self, path: str | Path, *, indent: int | None = 2) -> Path:
"""Write ``to_dict()`` as JSON to ``path`` and return the resolved Path."""
out = Path(path)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(self.to_dict(), indent=indent, sort_keys=True), encoding="utf-8")
return out
def _model_slug(name_or_path: str) -> str:
"""Produce a filesystem-safe slug for a model name or path."""
return name_or_path.replace("/", "--").replace("\\", "--").strip("-")
def _cell_stem(output_dir: Path, model_name_or_path: str, category: str) -> Path:
return output_dir / _model_slug(model_name_or_path) / category / "probe"
def _default_repo_id(model_name_or_path: str, category: str, hub_namespace: str) -> str:
if not hub_namespace:
raise ValueError(
"hub_namespace is required to build a Hub repo ID. Pass it explicitly "
"when push_to_hub=True; do not assume a default org/user."
)
return f"{hub_namespace}/{_model_slug(model_name_or_path)}-{category}"
def _trial_entries(result: TrainProbeResult) -> list[dict[str, Any]]:
return [
{
"layer": trial.layer,
"probe_type": trial.probe_type,
"train_auroc": trial.train_auroc,
"val_auroc": trial.val_auroc,
}
for trial in result.trials
]
[docs]
def train_probe_grid(
models: Iterable[ModelConfig],
categories: Iterable[str],
bench: RHDetectBench,
*,
output_dir: str | Path,
per_category_examples: int = 2000,
general_examples: int = 5000,
include_general: bool = True,
probe_type: ProbeType = "dom",
val_fraction: float = 0.2,
batch_size: int = 8,
max_length: int = 1024,
weak_threshold: float = 0.7,
seed: int = 0,
push_to_hub: bool = False,
hub_namespace: str | None = None,
hub_private: bool = False,
hub_token: str | None = None,
model_loader: Callable[[ModelConfig], tuple[Any, Any]] = _load_base_model,
probe_kwargs: Mapping[str, Any] | None = None,
) -> ProbeGridResult:
"""Train a Cartesian grid of probes across models x categories.
Each cell loads the model once, extracts activations for a
category-specific (or balanced "general") subset of ``bench``, fits a
probe via :func:`rhscope.training.train_probe`, writes the artifact and
a Hugging Face model card next to it, and optionally pushes both to
the Hub.
Args:
models: Each :class:`ModelConfig` names an HF causal LM. The models
are loaded one at a time.
categories: Category names to train category-specific probes for.
``"general"`` is reserved and appended automatically if
``include_general=True`` and not already listed.
bench: Source :class:`RHDetectBench` for curation.
output_dir: Root directory for all per-cell artifacts.
per_category_examples: Target subset size per category.
general_examples: Target subset size for the balanced general probe.
include_general: Whether to also train a ``general`` probe per model.
probe_type: ``"dom"`` or ``"logistic"``.
val_fraction: Fraction held out for layer selection.
batch_size: Activation forward-pass batch size.
max_length: Token truncation length.
weak_threshold: Val-AUROC below which a cell is flagged ``weak=True``.
seed: Base RNG seed. Each cell derives its own seed deterministically.
push_to_hub: Upload each probe to the Hub after training.
hub_namespace: Hub org/user name used for auto-generated repo IDs.
hub_private: Create Hub repos as private.
hub_token: Explicit Hub auth token; defaults to the env / cached login.
model_loader: Callable ``(ModelConfig) -> (model, tokenizer)``. Lets
tests inject a mock without touching real HF repos.
probe_kwargs: Forwarded to :func:`train_probe`.
Returns:
:class:`ProbeGridResult` with one entry per cell.
Raises:
ValueError: If any requested category is absent from ``bench``.
"""
output_root = Path(output_dir)
output_root.mkdir(parents=True, exist_ok=True)
if push_to_hub and not hub_namespace:
raise ValueError(
"push_to_hub=True requires an explicit hub_namespace. "
"No default is assumed; pass your own Hub org/user."
)
categories = list(categories)
if include_general and GENERAL_KEY not in categories:
work = [GENERAL_KEY, *categories]
else:
work = categories
bench_categories = sorted({e.category for e in bench.examples})
for cat in work:
if cat == GENERAL_KEY:
continue
if cat not in bench_categories:
raise ValueError(
f"Category {cat!r} not present in bench; available: {bench_categories}."
)
result = ProbeGridResult(output_dir=output_root)
for model_cfg in models:
logger.info("Loading base model %s", model_cfg.name_or_path)
set_global_seed(seed)
model, tokenizer = model_loader(model_cfg)
for cat_idx, category in enumerate(work):
cell_seed = seed + 1 + cat_idx * 7
examples = _curate_examples(
bench=bench,
category=category,
per_category_examples=per_category_examples,
general_examples=general_examples,
include_general=include_general,
seed=cell_seed,
)
if not examples:
logger.warning(
"Skipping cell (%s, %s): no examples after curation.",
model_cfg.name_or_path,
category,
)
continue
stem = _cell_stem(output_root, model_cfg.name_or_path, category)
stem.parent.mkdir(parents=True, exist_ok=True)
logger.info(
"Training probe cell: model=%s category=%s n=%d",
model_cfg.name_or_path,
category,
len(examples),
)
train_result = train_probe(
model=model,
tokenizer=tokenizer,
examples=examples,
probe_type=probe_type,
pooling="last_token",
category=category,
base_model_name=model_cfg.name_or_path,
val_fraction=val_fraction,
batch_size=batch_size,
max_length=max_length,
seed=cell_seed,
probe_kwargs=dict(probe_kwargs) if probe_kwargs else None,
)
train_result.probe.save(stem)
repo_id: str | None = None
if hub_namespace:
repo_id = _default_repo_id(model_cfg.name_or_path, category, hub_namespace)
card_path = stem.parent / "README.md"
save_model_card(
train_result.probe.metadata,
card_path,
repo_id=repo_id if push_to_hub else None,
extras=ModelCardExtras(
trials=_trial_entries(train_result),
datasets=[bench.dataset_name] if bench.dataset_name else [],
notes=f"Training data hash: `{train_result.training_data_hash}`.",
),
)
hub_url: str | None = None
if push_to_hub:
if repo_id is None: # pragma: no cover - guarded at launch
raise RuntimeError(
"push_to_hub is True but no repo_id was derived; this is a bug."
)
logger.info(
"Pushing cell (%s, %s) to Hub as %s", model_cfg.name_or_path, category, repo_id
)
hub_url = push_probe_to_hub(
stem=stem,
repo_id=repo_id,
private=hub_private,
token=hub_token,
)
val = float(train_result.best_trial.val_auroc)
result.cells.append(
ProbeGridCellResult(
model_name_or_path=model_cfg.name_or_path,
category=category,
probe_stem=stem,
model_card_path=card_path,
val_auroc=val,
best_layer=train_result.best_trial.layer,
train_examples=len(examples),
hub_url=hub_url,
weak=val < weak_threshold,
)
)
logger.info(
"Probe grid complete: %d cells (%d weak).",
len(result.cells),
len(result.weak_cells()),
)
return result
def _curate_examples(
*,
bench: RHDetectBench,
category: str,
per_category_examples: int,
general_examples: int,
include_general: bool,
seed: int,
) -> list[HackExample]:
if category == GENERAL_KEY and include_general:
return curate_general_subset(bench, n=general_examples, seed=seed)
return curate_subset(bench, category=category, n=per_category_examples, seed=seed)