API overview¶
Everything exported from the top-level rhscope package is stable from v0.1
onward. Deeper imports (anything under a submodule beyond what is listed
below) may be refactored without notice until v1.0.
from rhscope import (
Probe,
ProbeMetadata,
DoMProbe,
LogisticProbe,
HackMonitor,
HackExample,
train_probe,
load_hack_examples,
candidate_layers,
LayerTrialResult,
TrainProbeResult,
)
from rhscope.io import save_probe, load_probe
Probes¶
Probe (abstract)¶
Base class for all activation probes. Concrete probes self-register with a
module-level dispatch table so that Probe.load(stem) returns the correct
subclass based on the stored metadata.probe_type.
Key methods:
fit(hack_activations, clean_activations)- subclass-specific training.score(activations)- returns raw scores (higher = more hack-like).save(stem)/Probe.load(stem)- SafeTensors + JSON sidecar.
DoMProbe (probe_type="dom")¶
Difference-of-means probe:
direction = normalize(mean(hack) - mean(clean))
bias = -midpoint of projected class means
score(x) = x @ direction + bias
Optional ZCA whitening via DoMProbe(metadata, whiten=True).
LogisticProbe (probe_type="logistic")¶
L2-regularized logistic regression fit with torch-native L-BFGS. score
returns logits; probabilities(...) applies the sigmoid.
ProbeMetadata¶
Pydantic v2 model carrying every field needed to safely dispatch, score, and attribute a probe. Fields:
Field |
Type |
Notes |
|---|---|---|
|
|
HF model ID. Probes do not generalize across bases. |
|
|
HuggingFace |
|
|
Sequence pooling strategy. |
|
|
Registry discriminator. |
|
|
Hacking behavior. 7 canonical values; free-form accepted. |
|
|
Expected activation dim at scoring time. |
|
|
Validation AUROC at training time. |
|
|
Count used for the final fit. |
|
|
SHA-256 of the training JSONL. |
|
|
Version that produced the artifact. |
|
|
Set at construction time. |
|
|
Opaque, preserved across round-trips. |
Probe loading¶
Two equivalent entry points, both accepting a local stem or a Hugging Face Hub repo ID:
from rhscope import HackMonitor, Probe
probe = Probe.from_pretrained("rhscope/qwen3-1.5b-code_shortcut")
monitor = HackMonitor.from_pretrained("rhscope/qwen3-1.5b-code_shortcut")
Probe.registered_types() returns the probe-type discriminators
currently registered in the dispatch table - useful for CLI help and for
plug-in probe discovery.
HackMonitor¶
A trained probe plus its base model, with the integration surface the TRL / verl / DPO adapters consume:
monitor = HackMonitor.from_probe(probe, model=model, tokenizer=tokenizer)
monitor = HackMonitor.from_pretrained("my-org/my-probe") # Hub id or local stem
monitor = HackMonitor(custom_detector, threshold=0.0) # any Detector works
scores = monitor.score_batch(prompts, responses) # one call per rollout batch
scores = monitor.score(activations) # probe-backed monitors only
preds = monitor.predict_batch(prompts, responses) # score >= threshold
HackMonitor.require_base_model("...") fails loudly on a probe/policy
mismatch. Probe-specific accessors (base_model, layer, pooling,
category, hidden_dim, metadata, probe, score(activations))
are only valid for probe-backed monitors; they raise AttributeError
when the wrapped detector is something else (a composite you built, a
CallableDetector wrapping a custom scorer, etc).
Activations¶
from rhscope.activations import extract_activations
acts = extract_activations(
model,
tokenizer,
prompts=[...],
responses=[...],
layers=5, # int or list[int]
pooling="last_token", # or "mean" / "max"
batch_size=8,
max_length=1024,
)
# acts: {5: tensor of shape (N, hidden_dim), float32, on CPU}
Uses output_hidden_states=True so all requested layers come out of a single
forward pass. Any Hugging Face causal LM supported by
AutoModelForCausalLM.from_pretrained works.
Training pipeline¶
from rhscope import train_probe, load_hack_examples
examples = load_hack_examples("subsets/code_shortcut.jsonl")
result = train_probe(
model, tokenizer, examples,
probe_type="dom",
category="code_shortcut",
val_fraction=0.2,
seed=0,
)
result.probe.save("checkpoints/qwen3-code-shortcut")
print(f"val_auroc={result.best_trial.val_auroc:.4f}")
Behind the scenes train_probe extracts activations at every candidate
layer in one pass, fits a probe per layer, selects by val AUROC, then re-fits
the winner on train + val for the final artifact.
Hacking environments¶
rhscope ships CodeShortcutEnv as a built-in
source of ground-truth-labelled hacking behaviour: an MBPP-backed
coding env whose reward uses a deliberately weak subset of tests while
a held-out strong suite acts as the hacking oracle. The env is used
for (a) generating probe training data, (b) driving the GRPO recipe,
and (c) the rhscope env-eval CLI subcommand.
from rhscope.envs import CodeShortcutEnv, load_mbpp_tasks
env = CodeShortcutEnv(tasks=load_mbpp_tasks(max_tasks=500))
reward = env.reward_fn(task, response) # weak-tests pass rate
is_hack = env.hacking_signature(task, response) # oracle: weak AND NOT strong
evaluation = env.score_response(task, response) # full TestRunReport
Code execution goes through rhscope.sandbox; see
limitations for the subprocess
vs Docker trade-offs. New envs subclass
BaseEnv and auto-register under their name
class attribute.
Metrics¶
Pure numpy, no sklearn required:
from rhscope.metrics import (
auroc, average_precision, brier_score, confusion_matrix,
expected_calibration_error, precision_recall_curve, sigmoid,
youden_j_threshold,
)
a = auroc(scores, labels) # pooled AUROC
ap = average_precision(scores, labels) # PR-AUC
fit = youden_j_threshold(scores, labels) # optimal decision threshold
cm = confusion_matrix(scores, labels, threshold=0.0) # cm.precision/recall/f1/accuracy
precision, recall, thresholds = precision_recall_curve(scores, labels)
ece = expected_calibration_error(sigmoid(scores), labels)
brier = brier_score(sigmoid(scores), labels)
Benchmark¶
from rhscope.bench import RHDetectBench, ProbeDetector
bench = RHDetectBench.load_jsonl("rh-detect-test.jsonl")
detector = ProbeDetector(probe, model, tokenizer)
result = bench.evaluate(detector, limit=None)
print(result.summary()) # markdown table
result.save_json("results.json")
Baselines¶
RandomDetector(seed)- AUROC ~ 0.5 chance-line baseline.TokenCountDetector()- response length as score; a length-only floor for benchmarks.CallableDetector(fn, name="foo")- wrap any(prompts, responses) -> np.ndarraycallable as aDetector. Use this to compose with your own LLM-as-judge, custom rule, or external scoring function alongside the probe.
Head-to-head detector comparison¶
from rhscope.bench import compare_detectors
cmp = compare_detectors(
{"probe[dom]": probe_dom, "probe[mlp]": probe_mlp, "random": random_baseline},
bench,
max_disagreements=20,
)
print(cmp.summary()) # agreement + correlation
cmp.save_json("detector-comparison.json")
Returns a DetectorComparison with per-detector AUROCs, pairwise
threshold-agreement matrix, Pearson correlation, and the top-K
DisagreementCases for review.
Composite detectors¶
Ensemble multiple detectors with a single reducer:
from rhscope.bench import CallableDetector, CompositeDetector
def my_judge(prompts, responses):
# call your external judge here (OpenAI SDK, Anthropic SDK, Ollama, ...)
return scores
fused = CompositeDetector(
[probe_detector, CallableDetector(my_judge, name="judge")],
reducer="mean", # or "max" / "min" / "sum" / "weighted_mean"
)
For "weighted_mean", pass weights=[...] with one entry per
sub-detector. Composite does not rescale inputs - if sub-detectors
have wildly different output scales, normalize (e.g. sigmoid) before
composing.
Multi-probe leaderboard¶
from rhscope.bench import ProbeHandle, run_probe_leaderboard
board = run_probe_leaderboard(
probes=[ProbeHandle(name="A", probe=..., source="local/A"), ...],
bench=bench,
model_loader=load_model_for_probing,
)
print(board.sorted_by("pooled_auroc").summary())
Groups probes by base_model and loads each model only once.
Trainer integrations¶
Backend-agnostic primitive¶
All framework integrations compose over MonitorPenaltyAdapter:
from rhscope.integrations.base import MonitorPenaltyAdapter
adapter = MonitorPenaltyAdapter(
monitor=monitor,
model=policy_model,
tokenizer=tokenizer,
penalty_coef=0.1,
sink=make_sink("tensorboard", log_dir="runs/monitor"),
)
result = adapter.score_batch(prompts, completions)
# result.rewards : shape (N,) - -penalty_coef * score per entry
# result.raw_scores : shape (N,) - raw monitor scores
# result.metrics : dict - the per-batch metric summary just recorded
Writing an integration for a new RL framework is a thin adapter: call
adapter.score_batch(...) wherever the framework provides a per-rollout
hook, and read from adapter.stats on log ticks.
Activation cache¶
Content-addressed disk cache for pooled activations:
from rhscope.activations import ActivationCache, extract_activations
cache = ActivationCache("~/.cache/rhscope/activations")
acts = extract_activations(
model, tokenizer, prompts, responses,
layers=[5, 10],
cache=cache,
cache_model_id="Qwen/Qwen3-1.5B", # keys namespaced per model
)
Hits are served in a single mmap read. Misses fall through to the
extractor and populate the cache. Keys include model id + prompt +
response + layer + pooling + max_length, so changing any of them is a
clean miss.
GRPO / PPO (rollout-based)¶
from rhscope.integrations.trl import make_monitor_reward_fn, MonitorStatsCallback
monitor_reward = make_monitor_reward_fn(
monitor=monitor,
model=policy_model,
tokenizer=tokenizer,
penalty_coef=0.1,
sink=make_sink("tensorboard", log_dir="runs/monitor"),
)
trainer = GRPOTrainer(
model=policy_model,
reward_funcs=[env_reward, monitor_reward.fn],
callbacks=[MonitorStatsCallback(monitor_reward)],
...
)
DPO / IPO / KTO (preference-based)¶
No rollouts, so monitor shaping happens offline on the preference data:
from rhscope.integrations.dpo import score_dpo_pairs
scores = score_dpo_pairs(monitor, model, tokenizer, prompts, chosen, rejected)
keep_mask = scores.filter_mask(drop_preference_flips=True)
filtered_prefs = [row for row, keep in zip(preferences, keep_mask) if keep]
scores.preference_flips_to_hacker is a boolean mask over pairs where
chosen_scores > rejected_scores - the preference data is actively pushing
the policy toward hacking.
Metric sinks¶
from rhscope.integrations.sinks import make_sink
sink = make_sink("tensorboard", log_dir="runs/monitor")
# or make_sink("stdout"), make_sink("wandb"), make_sink("none")
Recipes¶
from rhscope.recipes import load_recipe
from rhscope.recipes.grpo import run_grpo_recipe
config = load_recipe("recipes/grpo_default.yaml")
result = run_grpo_recipe(config)
print(result.monitor_summary) # per-step monitor metrics
Every field is strict-Pydantic validated. CLI equivalent:
rhscope run-recipe recipes/grpo_default.yaml --override grpo.max_steps=100
Probe grid¶
from rhscope.recipes import train_probe_grid, ModelConfig
from rhscope.bench import RHDetectBench
result = train_probe_grid(
models=[
ModelConfig(name_or_path="Qwen/Qwen3-1.5B"),
ModelConfig(name_or_path="meta-llama/Llama-3.2-3B"),
],
categories=["code_shortcut", "format_gaming", "verbosity"],
bench=RHDetectBench.load_jsonl("rh-detect-train.jsonl"),
output_dir="checkpoints/probe-grid",
push_to_hub=True,
hub_namespace="your-org",
)
print(result.summary())
CLI equivalent: rhscope train-grid.
Research - probe-subspace drift / evasion detection¶
from rhscope.research import EvasionDetector
detector = EvasionDetector.from_baseline(
baseline_probe=baseline, # trained at step 0
baseline_hack_activations=hack_0,
baseline_clean_activations=clean_0,
)
for step in eval_steps:
hack_acts, clean_acts = collect_fresh_activations_at(step)
detector.record(step, hack_acts, clean_acts)
verdict = detector.verdict() # obfuscating / reforming / stable / undecided
print(verdict.reasoning)
detector.save("evasion-report.json")
Addresses a specific research problem: when a policy is trained against a probe-based reward penalty, it can either reform (genuinely stop hacking) or evade (continue hacking but rotate its activation signature out of the probe’s subspace). Scalar monitor curves alone cannot distinguish the two.
EvasionDetector anchors a baseline direction at step 0 and tracks:
Subspace angle between baseline and a fresh DoM direction fit on each step’s labeled activations (sign-folded,
[0, π/2]). Public primitive:rhscope.research.subspace_angle(a, b).Classifier drift - baseline and current directions scored on a held-out val half of each step’s data (fit/val split added so random data does not inflate in-sample AUROC into a false “obfuscation” verdict).
High subspace angle together with high current-probe AUROC on fresh data is the canonical obfuscation fingerprint.
Sandbox backends¶
rhscope.sandbox.run_python(code, backend="subprocess" | "docker", ...):
subprocess(default): fast, dependency-free; POSIXrlimitCPU + memory caps. Not a hard security boundary - use for code of known provenance.docker(opt-in): container with--network=none,--read-only,--cap-drop=ALL,--security-opt=no-new-privileges,--pids-limit=128,--user 65534:65534, memory + CPU caps. Requires Docker; feature-detect withis_docker_available(). Substantially stronger isolation for untrusted model output.
Full CLI surface¶
Command |
Purpose |
|---|---|
|
Train one probe from a JSONL dataset. |
|
Score a probe or baseline on an RH-Detect JSONL. |
|
Build one balanced subset from an RH-Detect JSONL. |
|
Inspect a probe’s metadata (local or Hub) without loading weights. |
|
Train a Cartesian grid of probes end-to-end. |
|
Benchmark many probes and emit a leaderboard. |
|
Render a Hugging Face model card for a probe. |
|
Execute a GRPO recipe YAML. |
|
Measure a base model’s hacking rate on an env (no training). |
Every command supports --help for full flag reference.
Optional dependencies¶
rhscope keeps its core install minimal and defers heavy / framework-
specific packages to extras:
[trl]pulls intrl,peft, andaccelerate- required for GRPO recipes and the TRL integration.[bench]pulls inscikit-learn- only needed for the metrics cross-check tests.[tensorboard]pulls intensorboard- for the local-first metrics sink.[wandb]pulls inwandb- for the W&B sink.
When an optional feature is used without its extras installed, rhscope
raises rhscope.MissingDependencyError with a precise install
command. MissingDependencyError is a subclass of
RuntimeError so existing except RuntimeError blocks continue
to catch it.