class HProbes:
"""Discover and causally validate hallucination-associated FFN neurons in a transformer LLM.
Implements the CETT metric to identify a sparse set of neurons whose activations
predict whether the model will hallucinate, then validates them causally via
activation scaling.
Parameters
----------
model : transformers CausalLM
Any HuggingFace causal language model. Must already be loaded and on the
correct device.
tokenizer : transformers tokenizer
Matching tokenizer for the model.
l1_C : float
Inverse L1 regularisation strength (C=1/λ). Higher = less sparsity.
Default 1.0.
contrastive : bool
If True (default), uses 3-vs-1 labeling: CETT captured at the generated answer token,
hallucinatory answers labeled 1, everything else 0.
If False, binary correct/incorrect labels at last prompt token.
layer_stride : int
Sample every Nth layer. 1 = all layers, 2 = even layers only (faster).
validation_split : float
Fraction of samples held out for scoring and causal validation.
seed : int
max_tokens : int
Max input tokens before truncation.
Attributes (set after fit)
--------------------------
h_neurons_ : list of (layer_idx, neuron_idx) tuples
n_neurons_ : int
neuron_ratio_ : float — ratio in ‰ relative to total features
layer_distribution_ : dict[int, int]
accuracy_ : float — model accuracy on the fit dataset
is_fitted_ : bool
"""
def __init__(
self,
model: torch.nn.Module,
tokenizer,
l1_C: float = 1.0,
layer_stride: int = 1,
validation_split: float = 0.2,
seed: int = 42,
max_tokens: int = 1024,
batch_size: int = 1,
n_consistency: int = 1,
top_k: Union[int, str] = 0,
auto_safety: float = _DEFAULT_AUTO_SAFETY,
save_predictions: bool = True,
readout: str = "both",
readout_max_new_tokens: int = 16,
check_l2: bool = False,
stability: bool = False,
correlation: bool = False,
cluster: bool = False,
strict_memory: bool = False,
solver: str = "auto",
stability_n_jobs: Union[int, str, None] = None,
):
if stability_n_jobs is not None and not (
isinstance(stability_n_jobs, int) or stability_n_jobs == "auto"
):
raise ValueError(
f"stability_n_jobs must be an int, 'auto' or None, got {stability_n_jobs!r}"
)
self.model = model
self.tokenizer = tokenizer
self.l1_C = l1_C
self.check_l2 = check_l2
self.stability = stability
self.correlation = correlation
self.cluster = cluster
self.strict_memory = strict_memory
if solver not in ("auto", "liblinear", "saga"):
raise ValueError(f"solver must be 'auto', 'liblinear' or 'saga', got {solver!r}")
self.solver = solver
self.solver_: Optional[str] = None
self.stability_n_jobs = stability_n_jobs
self._top_k_auto = isinstance(top_k, str) and top_k.strip().lower() in ("auto", "-1")
self.top_k = 0 if self._top_k_auto else int(top_k)
self.auto_safety = auto_safety
self.save_predictions = save_predictions
if readout not in ("logits", "generate", "both"):
raise ValueError(f"readout must be 'logits', 'generate' or 'both', got {readout!r}")
self.readout = readout
self.readout_max_new_tokens = readout_max_new_tokens
self._top_k_reason: Optional[Dict[str, Any]] = None
self._predictions_: List[Dict[str, Any]] = []
self._val_samples: List[Dict] = []
self._options_key: str = "options"
self._n_fits = (
1
+ (_STABILITY_N_RUNS if stability else 0)
+ int(bool(check_l2))
+ int(bool(correlation))
)
self.batch_size = batch_size
self.layer_stride = layer_stride
self.validation_split = validation_split
self.seed = seed
self.max_tokens = max_tokens
self.n_consistency = n_consistency
# Set after fit()
self.h_neurons_: List[Tuple[int, int]] = []
self.n_neurons_: int = 0
self.neuron_ratio_: float = 0.0
self.layer_distribution_: Dict[int, int] = {}
self.accuracy_: float = 0.0
self.threshold_: float = 0.5
self.is_fitted_: bool = False
self._l2_results_: Optional[Dict] = None
self._stability_results_: Optional[Dict] = None
self._correlation_results_: Optional[Dict] = None
self._cluster_info_: Optional[Dict] = None
# Internal state
self._layers: List[int] = []
self._col_norms: Dict[int, torch.Tensor] = {}
self._layer_dims: Dict[int, int] = {}
self._layer_offsets: Dict[int, int] = {}
self._intermediate_dim: int = 0
self._n_features: int = 0
self._top_k_idx: Optional[np.ndarray] = None
self._col_mean: Optional[np.ndarray] = None
self._col_std: Optional[np.ndarray] = None
self._clf: Optional[LogisticRegression] = None
self._letter_ids: Dict[str, int] = {}
self._answer_cue: str = ""
# Validation split cache
self._val_prompts: List[str] = []
self._val_gt: List[str] = []
self._X_val: Optional[np.ndarray] = None
if self.batch_size > 1:
self._ensure_pad_token()
self._y_val: Optional[np.ndarray] = None
self._val_is_answer: Optional[np.ndarray] = None
self._X_train_cache: Optional[np.ndarray] = None
self._y_train_cache: Optional[np.ndarray] = None
# Results storage (set after score() / causal_validate())
self.score_results_: Optional[Dict] = None
self.cv_results_: Optional[Dict[float, float]] = None
def _set_feature_layout(self) -> None:
"""Compute per-layer dims and flat offsets from ``_col_norms``.
Supports models whose FFN intermediate dims differ per layer
(e.g. Gemma 4 E-series double-wide MLPs).
"""
self._layer_dims = {layer: int(self._col_norms[layer].shape[0]) for layer in self._layers}
self._n_features = sum(self._layer_dims.values())
self._intermediate_dim = self._layer_dims[self._layers[0]]
self._layer_offsets = {}
offset = 0
for layer in self._layers:
self._layer_offsets[layer] = offset
offset += self._layer_dims[layer]
def _ensure_layout_from_artifact(self, artifact: "CETTRows") -> None:
"""Restore the feature layout from artifact meta on setup-less probes (#26).
A fresh probe refitting cached rows never ran extraction setup, so
``_n_features`` is 0 and flat-index mapping has no offsets. The
layout is fully determined by the artifact (layers + per-layer dims
recorded at extraction); restore it and verify the row width matches.
"""
if self._n_features:
return
try:
layers = list(artifact.meta["layers"])
layer_dims = {int(k): int(v) for k, v in artifact.meta["layer_dims"].items()}
except KeyError as e:
raise ValueError(f"artifact lacks layout meta ({e}); re-extract rows") from e
if artifact.rows.shape[1] != sum(layer_dims.values()):
raise ValueError("artifact row width disagrees with recorded layout")
self._layers = layers
self._layer_dims = layer_dims
self._n_features = sum(layer_dims.values())
self._intermediate_dim = layer_dims[layers[0]]
self._layer_offsets = {}
offset = 0
for layer in layers:
self._layer_offsets[layer] = offset
offset += layer_dims[layer]
def _flat_to_layer_neuron(self, flat_idx: int) -> Optional[Tuple[int, int]]:
"""Map a flat CETT index to ``(layer, neuron)`` using per-layer offsets."""
for layer in self._layers:
offset = self._layer_offsets[layer]
dim = self._layer_dims[layer]
if offset <= flat_idx < offset + dim:
return layer, int(flat_idx - offset)
return None
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def extract_features(
self,
samples: List[Dict],
question_key: str = "question",
options_key: str = "options",
answer_key: str = "answer",
prompt_fn: Optional[Callable[[Dict], str]] = None,
answer_cue: str = "\n\nAnswer:",
label_fn: Optional[Callable[[str, str, Dict], int]] = None,
) -> CETTRows:
"""Run the expensive forward phase once; return reusable rows (#26).
Selection (variance top-k, priors, clustering) and fitting all happen
downstream in :meth:`fit_on_features`, so one artifact serves any
number of refit variants. Labels are computed with ``label_fn`` at
extraction time, exactly as in the inline path.
"""
self._answer_cue = answer_cue
self._layers = available_layers(self.model)[:: self.layer_stride]
self._col_norms = precompute_col_norms(self.model, self._layers)
self._set_feature_layout()
self._letter_ids = self._get_letter_ids()
print(f"[hprobes] Layers: {len(self._layers)} | Features: {self._n_features:,}")
(
cett_raw,
train_labels,
row_to_sample,
valid_prompts,
valid_gt,
per_sample,
valid_samples,
) = self._extract_features(
samples,
question_key,
options_key,
answer_key,
prompt_fn,
answer_cue,
self._n_features,
label_fn,
)
if not cett_raw:
raise ValueError("no valid samples — extraction produced zero rows")
artifact = CETTRows(
rows=np.stack(cett_raw, axis=0),
labels=np.array(train_labels),
row_to_sample=list(row_to_sample),
prompts=list(valid_prompts),
ground_truth=list(valid_gt),
per_sample=list(per_sample),
samples=list(valid_samples),
welford_n=int(self._welford_n),
welford_mean=np.array(self._welford_mean),
welford_M2=np.array(self._welford_M2),
meta={
"mode": "live",
"layers": list(self._layers),
"layer_dims": {str(k): int(v) for k, v in self._layer_dims.items()},
"n_features": self._n_features,
"model_fp": fingerprint_model(self.model, self._layers),
"config": {
"question_key": question_key,
"options_key": options_key,
"answer_key": answer_key,
"answer_cue": answer_cue,
"batch_size": self.batch_size,
"max_tokens": self.max_tokens,
"readout": self.readout,
"label_fn": getattr(label_fn, "__name__", None)
if label_fn is not None
else "default",
},
},
)
artifact.validate()
return artifact
def fit_on_features(
self,
artifact: CETTRows,
options_key: str = "options",
top_k: Optional[int] = None,
) -> "HProbes":
"""Variance selection + split + L1 probe on cached rows (#26).
Bit-identical to the tail of :meth:`fit` for the same inputs.
``top_k`` overrides the constructor setting for this refit only, so
variant sweeps share one artifact.
"""
artifact.validate()
if artifact.meta.get("mode", "live") != "live":
raise ValueError("fit_on_features requires live-path rows")
self._ensure_layout_from_artifact(artifact)
valid_prompts = artifact.prompts
valid_gt = artifact.ground_truth
per_sample = artifact.per_sample
valid_samples = artifact.samples
row_to_sample = artifact.row_to_sample
override = self.top_k if top_k is None else top_k
resolved_top_k = min(override, self._n_features) if override > 0 else self._n_features
n_valid = len(valid_prompts)
self.accuracy_ = sum(p["is_correct"] for p in per_sample) / n_valid if n_valid > 0 else 0.0
self._predictions_ = [
{"index": i, "prompt": valid_prompts[i], **per_sample[i]} for i in range(n_valid)
]
print(f"[hprobes] Valid: {n_valid} | Accuracy: {self.accuracy_:.3f}")
if n_valid < 20:
print(f" WARNING: only {n_valid} valid samples — probe may be unreliable.")
if self._top_k_auto:
resolved, self._top_k_reason = _resolve_auto_top_k(
n_valid=n_valid,
n_rows=max(1, int(n_valid * (1 - self.validation_split))),
n_features=self._n_features,
n_fits=self._n_fits,
cett_bytes=4 * n_valid * self._n_features,
cett_bytes_per_sample=4 * self._n_features,
safety=self.auto_safety,
)
print(
f"[hprobes] auto top_k: {resolved or self._n_features:,}/{self._n_features:,} "
f"(avail {self._top_k_reason['available_bytes'] / 1e9:.1f} GB, "
f"CETT {self._top_k_reason['cett_bytes'] / 1e9:.1f} GB, "
f"safety {self.auto_safety})"
)
if 0 < resolved < 1000:
print(
f" WARNING: resolved top_k={resolved} is aggressive — fewer samples raise it."
)
resolved_top_k = min(resolved, self._n_features) if resolved > 0 else self._n_features
# --- Variance pre-selection ---
feature_var = artifact.variance()
self._top_k_idx = np.argsort(feature_var)[-resolved_top_k:]
X = artifact.rows[:, self._top_k_idx]
y = np.array(artifact.labels)
# --- Train/val split at sample level ---
# Ground-truth correctness labels per sample (for stratification)
sample_correct = np.array([int(p["is_correct"]) for p in per_sample])
sample_arr = np.arange(n_valid)
can_strat = sample_correct.sum() > 1 and (n_valid - sample_correct.sum()) > 1
train_s, val_s = train_test_split(
sample_arr,
test_size=self.validation_split,
random_state=self.seed,
stratify=sample_correct if can_strat else None,
)
train_set, val_set = set(train_s.tolist()), set(val_s.tolist())
train_rows = np.array([i for i, si in enumerate(row_to_sample) if si in train_set])
val_rows = np.array([i for i, si in enumerate(row_to_sample) if si in val_set])
X_train, X_val = X[train_rows], X[val_rows]
y_train, y_val = y[train_rows], y[val_rows]
self._X_train_cache = X_train
self._y_train_cache = y_train
self._X_val = X_val
self._y_val = y_val
# Store val prompts + ground truth for causal_validate()
self._val_prompts = [valid_prompts[i] for i in val_s]
self._val_gt = [valid_gt[i] for i in val_s]
self._val_samples = [valid_samples[i] for i in val_s]
self._options_key = options_key
# --- Phase 2: Cluster-based feature selection (optional) ---
if self.cluster:
cluster_reps, self._cluster_info_ = _select_cluster_representatives(X_train)
X_train = X_train[:, cluster_reps]
X_val = X_val[:, cluster_reps]
self._X_train_cache = X_train
self._y_train_cache = y_train
self._X_val = X_val
self._y_val = y_val
self._top_k_cluster_reps = self._top_k_idx[cluster_reps]
self._top_k_idx_original = self._top_k_idx.copy()
self._top_k_idx = self._top_k_cluster_reps
# --- Phase 3: L1 probe ---
_warn_if_memory_heavy(
X_train.shape[0],
X_train.shape[1],
stability=self.stability,
check_l2=self.check_l2,
correlation=self.correlation,
strict=self.strict_memory,
)
solver_used = _resolve_solver(self.solver, _liblinear_units(X_train))
if self.solver == "auto" and solver_used != "liblinear":
print(
f"[hprobes] solver auto->{solver_used}: "
f"{_liblinear_units(X_train):,} element units exceed liblinear's "
f"int32 ceiling ({_LIBLINEAR_INT32_CEILING:,})"
)
n_classes = len(np.unique(y_train))
if n_classes < 2:
self.h_neurons_, self.n_neurons_, self.neuron_ratio_ = [], 0, 0.0
self.layer_distribution_ = {}
self.is_fitted_ = True
self._clf = None
self._X_val, self._y_val = np.array([]), np.array([])
print("[hprobes] Single-class training data — no H-Neurons found.")
return self
self._clf, solver_used = _fit_logistic(
X_train,
y_train,
solver_used,
l1_ratio=1,
C=self.l1_C,
max_iter=1000,
random_state=self.seed,
)
self.solver_ = solver_used
coef = self._clf.coef_[0]
selected = np.where(coef > 0)[0]
self.h_neurons_ = []
for sel_idx in selected:
flat_idx = int(self._top_k_idx[sel_idx])
mapped = self._flat_to_layer_neuron(flat_idx)
if mapped is not None:
self.h_neurons_.append(mapped)
self.n_neurons_ = len(self.h_neurons_)
self.neuron_ratio_ = self.n_neurons_ / self._n_features * 1000
self.layer_distribution_ = {}
for li, _ in self.h_neurons_:
self.layer_distribution_[li] = self.layer_distribution_.get(li, 0) + 1
self.is_fitted_ = True
if self.check_l2 and self.n_neurons_ > 0:
self._l2_results_ = _run_l2_check(
selected, X_train, y_train, self.l1_C, self.seed, solver=self.solver_ or "liblinear"
)
if self.stability and self.n_neurons_ > 0:
self._stability_results_ = _run_stability_check(
X_train,
y_train,
self.l1_C,
n_runs=5,
base_seed=self.seed,
solver=self.solver_ or "liblinear",
n_jobs=self.stability_n_jobs,
)
if self.correlation and self.n_neurons_ > 0:
self._correlation_results_ = _run_correlation_check(selected, X_train)
print(f"[hprobes] H-Neurons: {self.n_neurons_} | Ratio: {self.neuron_ratio_:.3f}‰")
if self.layer_distribution_:
top = sorted(self.layer_distribution_.items(), key=lambda x: x[1], reverse=True)[:5]
print(f"[hprobes] Top layers: {top}")
return self
def fit(
self,
samples: List[Dict],
question_key: str = "question",
options_key: str = "options",
answer_key: str = "answer",
prompt_fn: Optional[Callable[[Dict], str]] = None,
answer_cue: str = "\n\nAnswer:",
label_fn: Optional[Callable[[str, str, Dict], int]] = None,
) -> "HProbes":
"""Discover H-Neurons from MCQ samples.
Parameters
----------
samples : list of dict
Each dict should contain at minimum a question and a ground-truth answer.
For MCQ: {"question": "...", "options": {"A": "...", ...}, "answer": "A"}
question_key : str
Key for the question text in each sample dict. Default "question".
options_key : str
Key for the options dict in each sample dict. Default "options".
answer_key : str
Key for the ground-truth answer letter in each sample dict. Default "answer".
prompt_fn : callable, optional
Custom function that takes a sample dict and returns a formatted string.
If None, uses tokenizer.apply_chat_template() with MCQ formatting.
answer_cue : str
String appended to every prompt to elicit a single-letter answer.
Default "\\n\\nAnswer:".
label_fn : callable, optional
Custom labeling function (predicted, ground_truth, sample) -> int (0 or 1).
If None, uses default hallucination labeling: 1 if incorrect, 0 if correct.
For control probes, pass a custom function, e.g.:
- Answer letter control: lambda pred, gt, s: 1 if pred == "A" else 0
- Domain control: lambda pred, gt, s: 1 if s.get("subject") == "Anatomy" else 0
Returns
-------
self
"""
artifact = self.extract_features(
samples,
question_key=question_key,
options_key=options_key,
answer_key=answer_key,
prompt_fn=prompt_fn,
answer_cue=answer_cue,
label_fn=label_fn,
)
return self.fit_on_features(artifact, options_key=options_key)
def extract_features_from_responses(
self,
samples: List[Dict],
question_key: str = "question",
response_key: str = "response",
answer_tokens_key: str = "answer_tokens",
label_key: str = "judge",
aggregation: str = "mean",
) -> CETTRows:
"""Forward phase over pre-generated responses; return reusable rows (#26).
Dual-span rows (answer + other per sample) are stacked answer-block
first; ``meta["n_answer_rows"]`` records the split. Selection and
fitting happen downstream in :meth:`fit_on_response_features`.
"""
self._layers = available_layers(self.model)[:: self.layer_stride]
self._col_norms = precompute_col_norms(self.model, self._layers)
self._set_feature_layout()
self._letter_ids = self._get_letter_ids()
print(
f"[hprobes] Layers: {len(self._layers)} | Features: {self._n_features:,} | Mode: H-Neuron (dual-span)"
)
self._welford_n = 0
self._welford_mean = np.zeros(self._n_features, dtype=np.float64)
self._welford_M2 = np.zeros(self._n_features, dtype=np.float64)
cett_ans, cett_other, labels_ans, labels_other = [], [], [], []
valid_prompts, valid_gt = [], []
per_sample, skipped = [], 0
def _record_features(full_text, is_correct, vec_ans, vec_other):
valid_prompts.append(full_text)
valid_gt.append("correct" if is_correct else "incorrect")
per_sample.append({"is_correct": is_correct})
ans = np.nan_to_num(vec_ans.numpy().astype(np.float32))
cett_ans.append(ans)
labels_ans.append(0 if is_correct else 1) # 1 = hallucinatory
self._welford_update(ans)
oth = np.nan_to_num(vec_other.numpy().astype(np.float32))
cett_other.append(oth)
labels_other.append(0) # always negative (non-answer tokens)
self._welford_update(oth)
device = next(self.model.parameters()).device
if self.batch_size > 1:
orig_padding_side = self.tokenizer.padding_side
self.tokenizer.padding_side = "right"
pending = [] # (full_text, (span_start, span_end), is_correct)
for sample in tqdm(samples, desc="CETT extraction (responses)"):
raw_label = sample.get(label_key)
if raw_label is None:
skipped += 1
continue
is_correct = str(raw_label).lower() in ("true", "1", "t")
question = sample.get(question_key, "")
response = sample.get(response_key, "")
ans_tokens = sample.get(answer_tokens_key, [])
# Build full Q+A prompt via chat template
if (
hasattr(self.tokenizer, "apply_chat_template")
and self.tokenizer.chat_template is not None
):
msgs = [
{"role": "user", "content": question},
{"role": "assistant", "content": response},
]
full_text = self.tokenizer.apply_chat_template(
msgs, tokenize=False, add_generation_prompt=False
)
else:
full_text = f"{question}\n{response}"
tokens = self._tokenize(full_text)
seq_len = tokens["input_ids"].shape[1]
# Compute answer span:
# 1. When answer_tokens are provided → find exact factual span in response
# 2. When chat template is used → compute response start position, use as fallback
# 3. Otherwise → use _find_answer_span on full sequence
if ans_tokens:
span = self._find_answer_span(tokens["input_ids"][0], ans_tokens)
else:
span = None
if span is not None:
span_start, span_end = span
elif (
hasattr(self.tokenizer, "apply_chat_template")
and self.tokenizer.chat_template is not None
):
user_only = self.tokenizer.apply_chat_template(
[{"role": "user", "content": question}],
tokenize=False,
add_generation_prompt=False,
)
user_tokens = self._tokenize(user_only)
input_len = user_tokens["input_ids"].shape[1] - 1
span_start = input_len + 1
span_end = seq_len
else:
skipped += 1
continue
pending.append((full_text, (span_start, span_end), is_correct))
if self.batch_size > 1 and len(pending) >= self.batch_size:
batch = pending
pending = []
prompts = [b[0] for b in batch]
enc = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
spans = [b[1] for b in batch]
try:
vec_ans_m, vec_oth_m = forward_cett_dual_span_batch(
self.model, enc, spans, self._layers, self._col_norms, aggregation
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += len(batch)
continue
for i, (full_text, _span, is_correct) in enumerate(batch):
_record_features(full_text, is_correct, vec_ans_m[i], vec_oth_m[i])
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Flush the final partial batch (batch_size > 1) or each single sample
# (batch_size == 1, preserving the original per-sample forward path).
if self.batch_size > 1:
if pending:
prompts = [b[0] for b in pending]
enc = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
spans = [b[1] for b in pending]
try:
vec_ans_m, vec_oth_m = forward_cett_dual_span_batch(
self.model, enc, spans, self._layers, self._col_norms, aggregation
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += len(pending)
else:
for i, (full_text, _span, is_correct) in enumerate(pending):
_record_features(full_text, is_correct, vec_ans_m[i], vec_oth_m[i])
if torch.cuda.is_available():
torch.cuda.empty_cache()
else:
for full_text, span, is_correct in pending:
span_start, span_end = span
try:
vec_ans, vec_other = forward_cett_dual_span(
self.model,
self._tokenize(full_text),
span_start,
span_end,
self._layers,
self._col_norms,
aggregation,
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += 1
continue
_record_features(full_text, is_correct, vec_ans, vec_other)
if torch.cuda.is_available():
torch.cuda.empty_cache()
if self.batch_size > 1:
self.tokenizer.padding_side = orig_padding_side
if skipped:
print(f"[hprobes] Skipped: {skipped}")
if not cett_ans:
raise ValueError("no valid samples — extraction produced zero rows")
rows = np.stack(cett_ans + cett_other, axis=0)
n_answer = len(cett_ans)
artifact = CETTRows(
rows=rows,
labels=np.array(labels_ans + labels_other),
row_to_sample=list(range(n_answer)) + list(range(n_answer)),
prompts=list(valid_prompts),
ground_truth=list(valid_gt),
per_sample=list(per_sample),
samples=[
{"prompt": p, "label": g, **s}
for p, g, s in zip(valid_prompts, valid_gt, per_sample)
],
welford_n=int(self._welford_n),
welford_mean=np.array(self._welford_mean),
welford_M2=np.array(self._welford_M2),
meta={
"mode": "dual-span",
"aggregation": aggregation,
"n_answer_rows": n_answer,
"layers": list(self._layers),
"layer_dims": {str(k): int(v) for k, v in self._layer_dims.items()},
"n_features": self._n_features,
"model_fp": fingerprint_model(self.model, self._layers),
"config": {
"question_key": question_key,
"response_key": response_key,
"answer_tokens_key": answer_tokens_key,
"label_key": label_key,
"batch_size": self.batch_size,
"max_tokens": self.max_tokens,
},
},
)
artifact.validate()
return artifact
def fit_on_response_features(
self,
artifact: CETTRows,
top_k: Optional[int] = None,
) -> "HProbes":
"""Selection + fitting on cached dual-span rows (#26).
Bit-identical to the tail of :meth:`fit_from_responses` for the same
inputs. ``top_k`` overrides the constructor setting for this refit.
"""
artifact.validate()
if artifact.meta.get("mode") != "dual-span":
raise ValueError("fit_on_response_features requires dual-span rows")
self._ensure_layout_from_artifact(artifact)
valid_prompts = artifact.prompts
valid_gt = artifact.ground_truth
per_sample = artifact.per_sample
row_to_sample = artifact.row_to_sample
override = self.top_k if top_k is None else top_k
resolved_top_k = min(override, self._n_features) if override > 0 else self._n_features
n_valid = len(valid_prompts)
self.accuracy_ = sum(p["is_correct"] for p in per_sample) / n_valid if n_valid > 0 else 0.0
self._predictions_ = [
{"index": i, "prompt": valid_prompts[i], "is_correct": per_sample[i]["is_correct"]}
for i in range(n_valid)
]
print(f"[hprobes] Valid: {n_valid} | Accuracy: {self.accuracy_:.3f}")
if self._top_k_auto:
resolved, self._top_k_reason = _resolve_auto_top_k(
n_valid=n_valid,
n_rows=max(1, 2 * int(n_valid * (1 - self.validation_split))),
n_features=self._n_features,
n_fits=self._n_fits,
cett_bytes=8 * n_valid * self._n_features,
cett_bytes_per_sample=8 * self._n_features,
safety=self.auto_safety,
)
print(
f"[hprobes] auto top_k: {resolved or self._n_features:,}/{self._n_features:,} "
f"(avail {self._top_k_reason['available_bytes'] / 1e9:.1f} GB, "
f"CETT {self._top_k_reason['cett_bytes'] / 1e9:.1f} GB, "
f"safety {self.auto_safety})"
)
if 0 < resolved < 1000:
print(
f" WARNING: resolved top_k={resolved} is aggressive — fewer samples raise it."
)
resolved_top_k = min(resolved, self._n_features) if resolved > 0 else self._n_features
# Variance pre-selection
feature_var = self._welford_M2 / max(self._welford_n - 1, 1)
self._top_k_idx = np.argsort(feature_var)[-resolved_top_k:]
X = artifact.rows[:, self._top_k_idx]
y = np.array(artifact.labels)
# Sample-level train/val split
sample_correct = np.array([int(p["is_correct"]) for p in per_sample])
sample_arr = np.arange(n_valid)
can_strat = sample_correct.sum() > 1 and (n_valid - sample_correct.sum()) > 1
train_s, val_s = train_test_split(
sample_arr,
test_size=self.validation_split,
random_state=self.seed,
stratify=sample_correct if can_strat else None,
)
train_set, val_set = set(train_s.tolist()), set(val_s.tolist())
train_rows = np.array([i for i, si in enumerate(row_to_sample) if si in train_set])
val_rows = np.array([i for i, si in enumerate(row_to_sample) if si in val_set])
X_train, X_val = X[train_rows], X[val_rows]
y_train, y_val = y[train_rows], y[val_rows]
self._X_train_cache, self._y_train_cache = X_train, y_train
self._X_val, self._y_val = X_val, y_val
self._val_prompts = [valid_prompts[i] for i in val_s]
self._val_gt = [valid_gt[i] for i in val_s]
# Evaluation protocol: answer-token rows only (strip non-answer controls)
ans_count = int(artifact.meta["n_answer_rows"])
self._val_is_answer = np.array([idx < ans_count for idx in val_rows])
# --- Cluster-based feature selection (optional) ---
if self.cluster:
cluster_reps, self._cluster_info_ = _select_cluster_representatives(X_train)
X_train = X_train[:, cluster_reps]
X_val = X_val[:, cluster_reps]
self._X_val = X_val
self._y_val = y_val
self._X_train_cache = X_train
self._y_train_cache = y_train
self._top_k_cluster_reps = self._top_k_idx[cluster_reps]
self._top_k_idx_original = self._top_k_idx.copy()
self._top_k_idx = self._top_k_cluster_reps
_warn_if_memory_heavy(
X_train.shape[0],
X_train.shape[1],
stability=self.stability,
check_l2=self.check_l2,
correlation=self.correlation,
strict=self.strict_memory,
)
solver_used = _resolve_solver(self.solver, _liblinear_units(X_train))
if self.solver == "auto" and solver_used != "liblinear":
print(
f"[hprobes] solver auto->{solver_used}: "
f"{_liblinear_units(X_train):,} element units exceed liblinear's "
f"int32 ceiling ({_LIBLINEAR_INT32_CEILING:,})"
)
n_classes = len(np.unique(y_train))
if n_classes < 2:
self.h_neurons_, self.n_neurons_, self.neuron_ratio_ = [], 0, 0.0
self.layer_distribution_ = {}
self.is_fitted_ = True
self._clf = None
self._X_val, self._y_val = np.array([]), np.array([])
print("[hprobes] Single-class training data — no H-Neurons found.")
return self
self._clf, solver_used = _fit_logistic(
X_train,
y_train,
solver_used,
l1_ratio=1,
C=self.l1_C,
max_iter=1000,
random_state=self.seed,
)
self.solver_ = solver_used
coef = self._clf.coef_[0]
selected = np.where(coef > 0)[0]
self.h_neurons_ = []
for sel_idx in selected:
flat_idx = int(self._top_k_idx[sel_idx])
mapped = self._flat_to_layer_neuron(flat_idx)
if mapped is not None:
self.h_neurons_.append(mapped)
self.n_neurons_ = len(self.h_neurons_)
self.neuron_ratio_ = self.n_neurons_ / self._n_features * 1000
self.layer_distribution_ = {}
for li, _ in self.h_neurons_:
self.layer_distribution_[li] = self.layer_distribution_.get(li, 0) + 1
self.is_fitted_ = True
if self.check_l2 and self.n_neurons_ > 0:
self._l2_results_ = _run_l2_check(
selected, X_train, y_train, self.l1_C, self.seed, solver=self.solver_ or "liblinear"
)
if self.stability and self.n_neurons_ > 0:
self._stability_results_ = _run_stability_check(
X_train,
y_train,
self.l1_C,
n_runs=5,
base_seed=self.seed,
solver=self.solver_ or "liblinear",
n_jobs=self.stability_n_jobs,
)
if self.correlation and self.n_neurons_ > 0:
self._correlation_results_ = _run_correlation_check(selected, X_train)
print(f"[hprobes] H-Neurons: {self.n_neurons_} | Ratio: {self.neuron_ratio_:.3f}‰")
if self.layer_distribution_:
top = sorted(self.layer_distribution_.items(), key=lambda x: x[1], reverse=True)[:5]
print(f"[hprobes] Top layers: {top}")
return self
def fit_moe(
self,
samples: List[Dict],
question_key: str = "question",
options_key: str = "options",
answer_key: str = "answer",
layers: Optional[List[int]] = None,
score: str = "mean_abs",
per_expert_top_n: int = 64,
top_k: int = 2000,
min_active: int = 2,
routing_baseline: bool = True,
fusion: str = "concat",
normalize_write: bool = False,
stability: Optional[bool] = None,
stability_runs: int = 5,
) -> "HProbes":
"""Discover H-Neurons on MoE models via active-only per-expert CETT (#41).
Forwards run once per sample with :class:`hprobes.moe.MoECapture`
attached to every selected layer's experts module; prediction and
label come from the same forward's logits (dense-equivalent protocol).
Features are then selected two-stage and assembled sparse.
``score`` selects the per-expert neuron ranking: ``mean_abs``
(default; ``sum|act|/n_samples`` with structural zeros), ``conditional``
(active-row mean), ``expected`` (gate-weighted expected contribution),
or ``variance`` (active-row variance).
``normalize_write`` divides feature values by each layer's total FFN
write norm at the decision token, mirroring dense CETT (#41.2). Off by
default so previously reported numbers stay comparable.
``routing_baseline`` fits the routing-only control probe on the same
samples (features = per-token expert indicators at the decision
token); ``fusion="concat"`` also fits the fused neuron+routing probe.
Results land in ``self.moe_``.
``stability`` enables the full-pipeline bootstrap (#72); ``None`` uses
the probe's constructor setting. ``stability_runs`` defaults to 5.
"""
from .moe import (
_MOE_SCORES,
MoECapture,
SharedExpertCapture,
_MoEFeatures,
fit_moe_probe,
)
if score not in _MOE_SCORES:
raise ValueError(f"score must be one of {_MOE_SCORES}, got {score!r}")
if top_k < 0:
raise ValueError("top_k must be non-negative (0 = all features)")
if stability_runs < 1:
raise ValueError(f"stability_runs must be >= 1, got {stability_runs}")
do_stability = self.stability if stability is None else bool(stability)
from .cett import _get_transformer_layers
blocks = _get_transformer_layers(self.model)
if layers is None:
layers = list(range(len(blocks)))
self._layers = list(layers)
self._letter_ids = self._get_letter_ids(space_prefixed=True)
self._answer_cue = "\n\nAnswer:"
# MoE layout: intermediate dim from the stacked expert weights.
self._layer_dims = {
li: int(blocks[li].mlp.experts.down_proj.shape[2]) for li in self._layers
}
self._intermediate_dim = self._layer_dims[self._layers[0]]
device = next(self.model.parameters()).device
captures: List[MoECapture] = []
handles = []
num_experts = None
for li in self._layers:
experts_mod = blocks[li].mlp.experts
num_experts = int(experts_mod.down_proj.shape[0])
cap = MoECapture(num_experts=num_experts, layer=li)
handles.append(cap.attach(experts_mod))
captures.append(cap)
# Always-on shared experts (Qwen2Moe / Qwen3.5-style) are captured
# read-only alongside the routed experts: same decision-token protocol.
shared_captures: List[SharedExpertCapture] = []
for li in self._layers:
cap_s = SharedExpertCapture(blocks[li].mlp, li)
if cap_s.available:
cap_s.attach()
shared_captures.append(cap_s)
# Layer total-FFN-write norms (#41.2): hook each block's output so the
# probe can normalise like dense CETT (|z| * col_norms / ||h||). Only
# registered when requested -- no overhead for the default path.
write_norm_cache: Dict[int, torch.Tensor] = {}
write_handles = []
if normalize_write:
for li in self._layers:
def make_write_hook(idx: int):
def hook(module, inputs, output):
write_norm_cache[idx] = _mlp_write_norms(output)
return hook
write_handles.append(blocks[li].mlp.register_forward_hook(make_write_hook(li)))
# Per-sample forward; capture stays active only during the forward.
feats: List[Dict[Tuple[int, int], Tuple[List[int], torch.Tensor, torch.Tensor]]] = []
routings: List[torch.Tensor] = []
labels: List[int] = []
prompts: List[str] = []
per_sample: List[Dict] = []
write_norms: List[Dict[int, float]] = []
try:
for sample in samples:
if self.readout in ("generate", "both"):
raise NotImplementedError(
"fit_moe supports readout='logits'; generation readout not wired yet"
)
prompt = self._format_moe_prompt(sample, question_key, options_key)
full, decision_pos = self._moe_full_encoding(prompt)
# Per-forward records only: clear so sample k's features can
# never include sample j<k rows at a coincident position.
for cap in captures:
cap.clear_records()
for cap_s in shared_captures:
cap_s.clear()
with torch.no_grad():
out = self.model(full["input_ids"].to(device))
logits = out.logits[0, decision_pos, :]
pred = self._predict_letter(
logits, letters=self._option_letters(sample, options_key)
)
gt = self._moe_gt_letter(sample, options_key, answer_key)
if pred is None or gt is None:
continue
is_correct = self._moe_letter_match(pred, gt)
labels.append(0 if is_correct else 1)
prompts.append(prompt)
per_sample.append({"is_correct": is_correct, "pred": pred, "gt": gt})
feats_sample = self._moe_decision_features(captures, decision_pos)
for cap_s in shared_captures:
shared = cap_s.decision_feature(decision_pos)
if shared is not None:
feats_sample[(cap_s.layer, "shared")] = shared
feats.append(feats_sample)
if normalize_write:
missing = [li for li in self._layers if li not in write_norm_cache]
if missing:
raise RuntimeError(
"normalize_write=True but no FFN write norm was captured for "
f"layer(s) {missing}; the block's mlp forward was not invoked. "
"Disable normalize_write for this model."
)
write_norms.append(
{li: float(write_norm_cache[li][decision_pos]) for li in self._layers}
)
else:
write_norms.append({})
routings.append(
torch.stack([cap.routing_table()[decision_pos] for cap in captures])
)
finally:
for h in handles:
h.remove()
for cap_s in shared_captures:
cap_s.remove()
for h in write_handles:
h.remove()
if not feats:
raise ValueError("no valid samples — MoE extraction produced zero rows")
artifact = _MoEFeatures(
feats=feats,
routings=routings,
labels=np.array(labels),
prompts=prompts,
per_sample=per_sample,
write_norms=write_norms,
capture_meta={
"layers": self._layers,
"num_experts": num_experts,
"shared_layers": [cap_s.layer for cap_s in shared_captures],
"model_fp": fingerprint_model(self.model, self._layers),
"score": score,
"per_expert_top_n": per_expert_top_n,
"top_k": top_k,
"min_active": min_active,
"normalize_write": normalize_write,
},
)
self.moe_ = fit_moe_probe(
artifact,
l1_C=self.l1_C,
validation_split=self.validation_split,
seed=self.seed,
fusion=fusion,
stability=do_stability,
stability_runs=stability_runs,
stability_n_jobs=self.stability_n_jobs,
)
if routing_baseline:
self.moe_["routing_baseline"] = fit_moe_probe(
artifact,
l1_C=self.l1_C,
validation_split=self.validation_split,
seed=self.seed,
routing_only=True,
)
self.is_fitted_ = True
return self
def counterfactual_routing(
self,
samples: List[Dict],
question_key: str = "question",
options_key: str = "options",
answer_key: str = "answer",
layers: Optional[List[int]] = None,
doses: Optional[List[int]] = None,
seed: int = 0,
) -> Dict[str, Any]:
"""Counterfactual routing: rescue/corruption + controls (#42 standard 4).
Baseline pass records per-sample routing at the decision token; each
sample gets a matched opposite-label donor (nearest by length, then
entropy -- a documented difficulty proxy). Then, per dose (expert
slots replaced, capped at k):
- ``rescue``: incorrect samples take the donor's first ``dose`` slots
- ``corruption``: correct samples take the donor's first ``dose`` slots
- ``random``: frequency-matched random experts (both directions), the
non-donor control
- ``self_swap``: own routing re-imposed -- bit-exact no-op gate
Interventions apply at the decision token only (v1, documented);
``seed`` controls the random control's draws.
"""
from .cett import _get_transformer_layers
from .moe import MoECapture
from .routing import dose_rows, frequency_sampled_experts, match_donors
import torch as _t
blocks = _get_transformer_layers(self.model)
if layers is None:
layers = list(range(len(blocks)))
self._layers = list(layers)
self._letter_ids = self._get_letter_ids(space_prefixed=True)
self._answer_cue = "\n\nAnswer:"
device = next(self.model.parameters()).device
captures = {}
handles = []
for li in self._layers:
experts_mod = blocks[li].mlp.experts
cap = MoECapture(num_experts=int(experts_mod.down_proj.shape[0]), layer=li)
handles.append(cap.attach(experts_mod))
captures[li] = cap
def _forward(sample: Dict) -> Dict:
prompt = self._format_moe_prompt(sample, question_key, options_key)
full, decision_pos = self._moe_full_encoding(prompt)
for cap in captures.values():
cap.clear_records()
with _t.no_grad():
out = self.model(full["input_ids"].to(device))
logits = out.logits[0, decision_pos, :]
logp = _t.log_softmax(logits.float(), dim=-1)
return {
"decision_pos": decision_pos,
"pred": self._predict_letter(
logits, letters=self._option_letters(sample, options_key)
),
"entropy": float(-(logp.exp() * logp).sum()),
"routing": {
li: [int(x) for x in captures[li].routing_table()[decision_pos].tolist()]
for li in self._layers
},
"weights": {
li: [float(x) for x in captures[li].gate_table()[decision_pos].tolist()]
for li in self._layers
},
"prompt_len": int(self._tokenize(prompt)["input_ids"].shape[1]),
}
try:
base: List[Dict] = []
for sample in samples:
gt = self._moe_gt_letter(sample, options_key, answer_key)
rec = _forward(sample)
if rec["pred"] is None or gt is None:
continue
rec["gt"] = gt
rec["is_correct"] = self._moe_letter_match(rec["pred"], gt)
rec["sample"] = sample
base.append(rec)
labels = [0 if r["is_correct"] else 1 for r in base]
donors = match_donors(
labels, [r["prompt_len"] for r in base], [r["entropy"] for r in base]
)
usage: Dict[int, Dict[int, float]] = {li: {} for li in self._layers}
for r in base:
for li in self._layers:
for e in r["routing"][li]:
usage[li][e] = usage[li].get(e, 0.0) + 1.0
k = len(base[0]["routing"][self._layers[0]]) if base else 0
if doses is None:
doses = [1, 2, 5]
eff_doses = sorted({min(d, k) for d in doses if d >= 1})
def _intervened_forward(idx: int, mode: str, dose: int) -> Dict:
rec = base[idx]
donor_idx = donors.get(idx, idx)
for li in self._layers:
if mode == "donor":
e, w = dose_rows(
rec["routing"][li],
rec["weights"][li],
base[donor_idx]["routing"][li],
base[donor_idx]["weights"][li],
dose,
)
elif mode == "random":
picks = frequency_sampled_experts(
usage[li], dose=dose, k=k, seed=seed + idx * 1000 + li
)
e = list(picks) + list(rec["routing"][li][len(picks) :])
w = list(rec["weights"][li])
else: # self
e, w = list(rec["routing"][li]), list(rec["weights"][li])
captures[li].set_routing_override(
[rec["decision_pos"]],
_t.tensor([e], dtype=_t.long),
_t.tensor([w], dtype=_t.float),
)
post = _forward(rec["sample"])
for li in self._layers:
captures[li].clear_routing_override()
return post
def _group(idxs: List[int], mode: str, dose: int, direction: str) -> Dict:
flips = 0
acc_after = 0.0
ent_delta = 0.0
for idx in idxs:
post = _intervened_forward(idx, mode, dose)
flips += int(post["pred"] != base[idx]["pred"])
acc_after += (
1.0 if self._moe_letter_match(post["pred"], base[idx]["gt"]) else 0.0
)
ent_delta += post["entropy"] - base[idx]["entropy"]
n = len(idxs)
return {
"direction": direction,
"dose": dose,
"n_targets": n,
"flip_rate": flips / n if n else 0.0,
"accuracy_after": acc_after / n if n else 0.0,
"mean_entropy_delta": ent_delta / n if n else 0.0,
}
self_swap = {"n": len(base), "flips": 0, "max_abs_entropy_delta": 0.0}
for idx in range(len(base)):
post = _intervened_forward(idx, "self", k)
self_swap["flips"] += int(post["pred"] != base[idx]["pred"])
self_swap["max_abs_entropy_delta"] = max(
self_swap["max_abs_entropy_delta"],
abs(post["entropy"] - base[idx]["entropy"]),
)
incorrect = [i for i, r in enumerate(base) if not r["is_correct"]]
correct = [i for i, r in enumerate(base) if r["is_correct"]]
rescue: List[Dict] = []
corruption: List[Dict] = []
random_rows: List[Dict] = []
for dose in eff_doses:
if incorrect:
rescue.append(_group(incorrect, "donor", dose, "rescue"))
random_rows.append(_group(incorrect, "random", dose, "rescue"))
if correct:
corruption.append(_group(correct, "donor", dose, "corruption"))
random_rows.append(_group(correct, "random", dose, "corruption"))
finally:
for h in handles:
h.remove()
result = {
"n_samples": len(base),
"k": k,
"doses": eff_doses,
"layers": self._layers,
"donor_matches": {"n_targets": len(donors), "donors": donors},
"self_swap": self_swap,
"rescue": rescue,
"corruption": corruption,
"random": random_rows,
}
self._counterfactual_routing = result
return result
def moe_routing_analysis(
self,
samples: List[Dict],
question_key: str = "question",
options_key: str = "options",
answer_key: str = "answer",
layers: Optional[List[int]] = None,
n_perm: int = 200,
seed: int = 0,
) -> Dict[str, Any]:
"""Routing vs correctness statistics (+ CETT cross-check if fitted).
One baseline forward per sample; records decision-token routing and
gate weights; compares correct vs incorrect via
:func:`hprobes.routing.routing_stats`. When ``fit_moe`` was run
first, appends ``cett_cross_check``: overlap between routing-flagged
experts and the experts hosting CETT-selected neurons (#42 vs #41).
"""
from .cett import _get_transformer_layers
from .moe import MoECapture
from .routing import cett_routing_overlap, routing_stats
import torch as _t
blocks = _get_transformer_layers(self.model)
if layers is None:
layers = list(range(len(blocks)))
self._layers = list(layers)
self._letter_ids = self._get_letter_ids(space_prefixed=True)
self._answer_cue = "\n\nAnswer:"
device = next(self.model.parameters()).device
captures = {}
handles = []
for li in self._layers:
experts_mod = blocks[li].mlp.experts
cap = MoECapture(num_experts=int(experts_mod.down_proj.shape[0]), layer=li)
handles.append(cap.attach(experts_mod))
captures[li] = cap
routings: List[Any] = []
gates: List[Any] = []
labels: List[int] = []
try:
for sample in samples:
prompt = self._format_moe_prompt(sample, question_key, options_key)
full, decision_pos = self._moe_full_encoding(prompt)
for cap in captures.values():
cap.clear_records()
with _t.no_grad():
out = self.model(full["input_ids"].to(device))
pred = self._predict_letter(
out.logits[0, decision_pos, :],
letters=self._option_letters(sample, options_key),
)
gt = self._moe_gt_letter(sample, options_key, answer_key)
if pred is None or gt is None:
continue
labels.append(0 if self._moe_letter_match(pred, gt) else 1)
routings.append(
_t.stack([captures[li].routing_table()[decision_pos] for li in self._layers])
)
gates.append(
_t.stack([captures[li].gate_table()[decision_pos] for li in self._layers])
)
finally:
for h in handles:
h.remove()
if not routings:
raise ValueError("no valid samples — routing analysis produced zero rows")
n_experts = max(int(r.max()) for r in routings) + 1
stats = routing_stats(
routings, np.array(labels), gates=gates, n_experts=n_experts, n_perm=n_perm, seed=seed
)
moe = getattr(self, "moe_", None)
if moe and moe.get("feature_names"):
names = [moe["feature_names"][j] for j in moe.get("selected", [])]
stats["cett_cross_check"] = cett_routing_overlap(names, stats)
self._moe_routing_analysis = stats
return stats
@staticmethod
def _moe_decision_features(
captures, decision_pos: int
) -> Dict[Tuple[int, int], Tuple[List[int], torch.Tensor, torch.Tensor]]:
"""Decision-token activations keyed by (layer, expert) (issue #41).
Returns ``{(layer, expert): (tokens, acts, gates)}`` using each
capture's own routing table to mask the token dimension; the decision
row is looked up by position.
"""
out: Dict[Tuple[int, int], Tuple[List[int], torch.Tensor, torch.Tensor]] = {}
for cap in captures:
for rec in cap.records:
sel = (rec["tokens"] == decision_pos).nonzero(as_tuple=False).flatten()
if sel.numel() == 0:
continue
key = (cap.layer, int(rec["expert"]))
out[key] = (
[decision_pos] * sel.numel(),
rec["acts"][sel],
rec["gates"][sel],
)
return out
def _format_moe_prompt(self, sample: Dict, question_key: str, options_key: str) -> str:
options = sample.get(options_key, {})
question = sample.get(question_key, "")
if isinstance(options, dict):
opt_txt = "\n".join(f"{k}. {v}" for k, v in options.items())
else:
opt_txt = "\n".join(f"{chr(65 + i)}. {v}" for i, v in enumerate(options))
return f"{question}\n{opt_txt}"
def _moe_full_encoding(self, prompt: str):
"""Tokenize ``prompt + answer cue`` and return (encoding, last-token index).
The MoE readout must use the last token the model actually sees; the
answer cue is part of the input, so the decision position is the final
token of the combined encoding.
"""
full = self._tokenize(prompt + self._answer_cue)
return full, int(full["input_ids"].shape[1]) - 1
@staticmethod
def _option_letters(sample: Dict, options_key: str) -> Optional[List[str]]:
"""MCQ letter keys for a sample (dict keys or positional letters)."""
options = sample.get(options_key, {})
if isinstance(options, dict):
letters = [str(k) for k in options]
elif isinstance(options, (list, tuple)):
letters = [chr(65 + i) for i in range(len(options))]
else:
return None
return letters or None
@staticmethod
def _moe_gt_letter(sample: Dict, options_key: str, answer_key: str) -> Optional[str]:
ans = sample.get(answer_key)
if ans is None:
return None
options = sample.get(options_key, {})
if isinstance(options, dict):
keys = list(options.keys())
else:
keys = [chr(65 + i) for i in range(len(options))]
if isinstance(ans, int) and 0 <= ans < len(keys):
return keys[ans]
if isinstance(ans, str) and ans in keys:
return ans
if isinstance(ans, str) and ans and ans[0].upper() in keys:
return ans[0].upper()
return None
@staticmethod
def _moe_letter_match(pred: Optional[str], gt: Optional[str]) -> bool:
return bool(pred and gt and pred.upper() == gt.upper())
def fit_from_responses(
self,
samples: List[Dict],
question_key: str = "question",
response_key: str = "response",
answer_tokens_key: str = "answer_tokens",
label_key: str = "judge",
aggregation: str = "mean",
) -> "HProbes":
"""Discover H-Neurons from pre-generated responses.
Methodology:
1. Tokenize full Q+A sequence
2. Compute per-token CETT: |z| * ||W_down|| / (||h|| + 1e-8)
3. Aggregate: mean over answer span, mean over non-answer span
4. Create 2 rows per sample: answer (label=correctness), other (label=0)
5. Train L1 logistic regression → positive-weight neurons = H-Neurons
Parameters
----------
samples : list of dict
Each dict must contain question, response, answer_tokens (list of token
strings marking the factual span), and a correctness label.
question_key : str
Key for the question string. Default "question".
response_key : str
Key for the generated response string. Default "response".
answer_tokens_key : str
Key for list of answer token strings (the factual span). Default "answer_tokens".
label_key : str
Key for the correctness label. Accepts "true"/"false" strings or 1/0 ints.
Default "judge".
aggregation : "mean" | "max"
How to aggregate CETT over token spans. Default "mean".
Returns
-------
self
"""
artifact = self.extract_features_from_responses(
samples,
question_key=question_key,
response_key=response_key,
answer_tokens_key=answer_tokens_key,
label_key=label_key,
aggregation=aggregation,
)
return self.fit_on_response_features(artifact)
def score(self) -> Dict:
"""Evaluate probe AUROC and random neuron baseline on the held-out val split.
Returns
-------
dict with keys:
auroc, balanced_accuracy,
random_baseline_auroc, random_baseline_balanced_accuracy,
auroc_gap, n_h_neurons, neuron_ratio_permille, threshold
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
if self._clf is None:
return {
"auroc": None,
"balanced_accuracy": None,
"random_baseline_auroc": None,
"random_baseline_balanced_accuracy": None,
"auroc_gap": None,
"n_h_neurons": 0,
"neuron_ratio_permille": 0.0,
"threshold": None,
}
X_val, y_val = self._X_val, self._y_val
# Evaluation protocol: answer-token rows only
if self._val_is_answer is not None:
X_val = X_val[self._val_is_answer]
y_val = y_val[self._val_is_answer]
try:
scores = self._clf.predict_proba(X_val)[:, 1]
auroc = roc_auc_score(y_val, scores)
fpr, tpr, thresholds = roc_curve(y_val, scores)
J = tpr - fpr
if np.isfinite(thresholds).any() and J.max() > J.min():
self.threshold_ = float(thresholds[int(J.argmax())])
else:
self.threshold_ = 0.5
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
auroc = None
preds = self._clf.predict(X_val)
bal_acc = balanced_accuracy_score(y_val, preds)
# Random neuron baseline — same N neurons, same probe, same hyperparams
rand_auroc, rand_bal_acc = None, None
if self.n_neurons_ > 0:
rng = np.random.RandomState(self.seed + 1)
top_k = len(self._top_k_idx)
rand_idx = rng.choice(top_k, size=min(self.n_neurons_, top_k), replace=False)
clf_rand = LogisticRegression(
solver=self.solver_ or "liblinear",
l1_ratio=1,
C=self.l1_C,
max_iter=1000,
random_state=self.seed,
)
clf_rand.fit(self._X_train_cache[:, rand_idx], self._y_train_cache)
try:
rand_scores = clf_rand.predict_proba(X_val[:, rand_idx])[:, 1]
rand_auroc = roc_auc_score(y_val, rand_scores)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
pass
rand_preds = clf_rand.predict(X_val[:, rand_idx])
rand_bal_acc = balanced_accuracy_score(y_val, rand_preds)
gap = (auroc - rand_auroc) if (auroc is not None and rand_auroc is not None) else None
if gap is not None:
print(f"[hprobes] AUROC: {auroc:.3f} | Random: {rand_auroc:.3f} | Gap: {gap:+.3f}")
self.score_results_ = {
"auroc": auroc,
"balanced_accuracy": bal_acc,
"random_baseline_auroc": rand_auroc,
"random_baseline_balanced_accuracy": rand_bal_acc,
"auroc_gap": gap,
"n_h_neurons": self.n_neurons_,
"neuron_ratio_permille": self.neuron_ratio_,
"threshold": self.threshold_,
}
return self.score_results_
def causal_validate(
self,
alphas: List[float] = None,
) -> Dict[float, float]:
"""Scale H-Neuron activations by each alpha and measure accuracy on val split.
Uses the same readout as the fit labels: ``logits`` (top letter token) or, for
``generate``/``both``, greedy generation with the letter parsed from the text
(unparseable generations count as incorrect so the denominator stays fixed).
Labeling convention (Incorrect=1):
suppression (alpha<1) should INCREASE accuracy,
amplification (alpha>1) should DECREASE accuracy.
Returns
-------
dict mapping alpha → accuracy
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
if not self.h_neurons_:
print("[hprobes] No H-Neurons found — skipping causal validation.")
return {}
alphas = alphas or [0.0, 0.5, 1.0, 1.5, 2.0]
results = {}
device = next(self.model.parameters()).device
if self.batch_size > 1 and self._val_prompts:
orig_padding_side = self.tokenizer.padding_side
self.tokenizer.padding_side = "right"
use_generation = self.readout in ("generate", "both") and bool(self._val_samples)
for alpha in alphas:
correct, total = 0, 0
if use_generation:
self._ensure_pad_token()
for sample, prompt, gt in zip(self._val_samples, self._val_prompts, self._val_gt):
tokens = self._tokenize(prompt)
input_len = tokens["input_ids"].shape[1]
try:
with scaled_h_neurons(self.model, self.h_neurons_, alpha, self._layers):
with torch.inference_mode():
out = self.model.generate(
**tokens,
max_new_tokens=self.readout_max_new_tokens,
do_sample=False,
pad_token_id=self.tokenizer.pad_token_id,
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
continue
text = self.tokenizer.decode(out[0, input_len:], skip_special_tokens=True)
pred = self._extract_generated_letter(text, sample, self._options_key)
# Unparseable generation counts as incorrect: fixed denominator across alphas.
correct += int(pred == gt)
total += 1
elif self.batch_size > 1 and self._val_prompts:
for start in range(0, len(self._val_prompts), self.batch_size):
chunk_prompts = self._val_prompts[start : start + self.batch_size]
chunk_gt = self._val_gt[start : start + self.batch_size]
enc = self.tokenizer(
chunk_prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
try:
logits_matrix = scale_h_neurons_batch(
self.model, enc, self.h_neurons_, alpha, self._layers
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
continue
for i, gt in enumerate(chunk_gt):
pred = self._predict_letter(logits_matrix[i])
correct += int(pred == gt)
total += 1
if torch.cuda.is_available():
torch.cuda.empty_cache()
else:
for prompt, gt in zip(self._val_prompts, self._val_gt):
tokens = self._tokenize(prompt)
try:
logits = scale_h_neurons(
self.model, tokens, self.h_neurons_, alpha, self._layers
)
pred = self._predict_letter(logits)
correct += int(pred == gt)
total += 1
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
continue
if torch.cuda.is_available():
torch.cuda.empty_cache()
results[alpha] = correct / total if total > 0 else 0.0
if self.batch_size > 1 and self._val_prompts:
self.tokenizer.padding_side = orig_padding_side
self.cv_results_ = results
return results
def compare_with(self, other: "HProbes") -> Dict[str, Any]:
"""Compare H-Neurons with another fitted probe.
Computes Jaccard similarity and overlap statistics between the H-Neuron
sets identified by this probe and another probe. Useful for:
- Testing stability across different C values (AP-6)
- Comparing base vs fine-tuned models (AP-4)
- Cross-model comparisons (AP-12)
Parameters
----------
other : HProbes
Another fitted probe to compare against.
Returns
-------
dict with keys:
jaccard_similarity : float
Jaccard index (intersection / union), range [0, 1]
n_shared : int
Number of neurons in both sets
n_union : int
Total unique neurons across both sets
n_only_self : int
Neurons only in this probe
n_only_other : int
Neurons only in the other probe
shared_neurons : list of [layer, neuron] pairs
The actual shared neurons, sorted by layer then neuron index
Examples
--------
>>> probe1 = HProbes(model, tok, l1_C=0.1).fit(samples)
>>> probe2 = HProbes(model, tok, l1_C=1.0).fit(samples)
>>> comparison = probe1.compare_with(probe2)
>>> print(f"Jaccard: {comparison['jaccard_similarity']:.3f}")
>>> print(f"Shared: {comparison['n_shared']} neurons")
"""
if not self.is_fitted_:
raise RuntimeError("This probe must be fitted before comparison")
if not other.is_fitted_:
raise RuntimeError("Other probe must be fitted before comparison")
set_self = set(self.h_neurons_)
set_other = set(other.h_neurons_)
intersection = set_self & set_other
union = set_self | set_other
return {
"jaccard_similarity": len(intersection) / len(union) if union else 0.0,
"n_shared": len(intersection),
"n_union": len(union),
"n_only_self": len(set_self - set_other),
"n_only_other": len(set_other - set_self),
"shared_neurons": sorted([list(n) for n in intersection]),
}
def save(self, path: str) -> Path:
"""Save probe results and classifier to disk.
Writes:
- ``<path>.json`` — human-readable results (neurons, scores, cv)
- ``<path>.pkl`` — serialized classifier for transfer experiments
- ``<path>.predictions.jsonl`` — per-sample predictions (unless ``save_predictions=False``)
Parameters
----------
path : str
Base path (e.g. "results/gemma_medqa"). Extensions are added automatically.
Returns
-------
Path to the JSON file.
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
# Ensure .json extension
json_path = p.with_suffix(".json")
# Extract model metadata for comparison
model_name = None
if hasattr(self.model, "config"):
model_name = getattr(self.model.config, "_name_or_path", None)
if model_name is None:
model_name = getattr(self.model.config, "model_type", None)
out = {
"saved_at": datetime.now(timezone.utc).isoformat(),
"model": model_name or getattr(self, "model_id", None),
"dataset": getattr(self, "dataset_name", None),
"n_samples": getattr(self, "n_samples_used", None),
"fit": {
"n_h_neurons": self.n_neurons_,
"neuron_ratio_permille": self.neuron_ratio_,
"accuracy": self.accuracy_,
"layer_distribution": {str(k): v for k, v in self.layer_distribution_.items()},
"h_neurons": [list(n) for n in self.h_neurons_],
},
"metadata": {
"model_name": model_name,
"n_layers": len(self._layers),
"intermediate_dim": self._intermediate_dim,
"layer_dims": {str(k): v for k, v in self._layer_dims.items()},
"total_features": self._n_features,
},
}
if self.score_results_ is not None:
out["score"] = self.score_results_
if self.cv_results_ is not None:
out["causal_validation"] = {str(k): v for k, v in self.cv_results_.items()}
if self._l2_results_ is not None:
out["l2_check"] = self._l2_results_
if self._stability_results_ is not None:
out["stability"] = self._stability_results_
if self._correlation_results_ is not None:
out["correlation"] = self._correlation_results_
if self._cluster_info_ is not None:
out["cluster"] = self._cluster_info_
out["config"] = {
"h_neurons": self.h_neurons_,
"layers": self._layers,
"intermediate_dim": self._intermediate_dim,
"layer_dims": {str(k): v for k, v in self._layer_dims.items()},
"n_features": self._n_features,
"l1_C": self.l1_C,
"top_k": self._top_k_reason["top_k_resolved"] if self._top_k_reason else self.top_k,
"top_k_auto": self._top_k_auto,
"top_k_reason": self._top_k_reason,
"layer_stride": self.layer_stride,
"seed": self.seed,
"max_tokens": self.max_tokens,
"answer_cue": self._answer_cue,
"threshold": self.threshold_,
"n_consistency": self.n_consistency,
"readout": self.readout,
"solver": self.solver,
"solver_used": self.solver_,
"clf_classes": self._clf.classes_.tolist() if hasattr(self._clf, "classes_") else [],
}
if self.save_predictions and self._predictions_:
out["predictions_file"] = p.with_suffix(".predictions.jsonl").name
class _NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (np.integer,)):
return int(obj)
if isinstance(obj, (np.floating,)):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.bool_):
return bool(obj)
return super().default(obj)
json_path.write_text(json.dumps(out, indent=2, cls=_NumpyEncoder))
if self.save_predictions and self._predictions_:
predictions_path = json_path.with_suffix(".predictions.jsonl")
with open(predictions_path, "w") as fh:
for record in self._predictions_:
fh.write(json.dumps(record, cls=_NumpyEncoder) + "\n")
# Save classifier state for transfer experiments
tensors = {}
if hasattr(self._clf, "coef_"):
tensors["clf_coef"] = torch.tensor(self._clf.coef_)
if hasattr(self._clf, "intercept_"):
tensors["clf_intercept"] = torch.tensor(self._clf.intercept_)
if self._top_k_idx is not None:
tensors["top_k_idx"] = torch.tensor(self._top_k_idx)
if self._col_mean is not None:
tensors["col_mean"] = torch.tensor(self._col_mean)
if self._col_std is not None:
tensors["col_std"] = torch.tensor(self._col_std)
if self._X_train_cache is not None:
tensors["X_train"] = torch.tensor(self._X_train_cache)
if self._y_train_cache is not None:
tensors["y_train"] = torch.tensor(self._y_train_cache)
if self._X_val is not None and len(self._X_val) > 0:
tensors["X_val"] = torch.tensor(self._X_val)
if self._y_val is not None and len(self._y_val) > 0:
tensors["y_val"] = torch.tensor(self._y_val)
sf_path = p.with_suffix(".safetensors")
save_file(tensors, sf_path)
return json_path
@classmethod
def load(cls, path: str, model: torch.nn.Module, tokenizer) -> "HProbes":
"""Load a saved probe classifier and attach it to a (possibly different) model.
Use this to run transfer experiments: fit on an IT model, then load onto the
corresponding PT base model to test whether H-Neurons transfer.
Parameters
----------
path : str
Base path used when saving (e.g. "results/gemma_medqa"). Will look for
``<path>.pkl``.
model : transformers CausalLM
Model to attach the loaded probe to (can differ from the original).
tokenizer :
Matching tokenizer for the model.
Returns
-------
HProbes instance ready for score_on() or causal_validate().
"""
sf_path = Path(path).with_suffix(".safetensors")
json_path = Path(path).with_suffix(".json")
if not sf_path.exists() or not json_path.exists():
raise FileNotFoundError(f"Saved probe missing .safetensors or .json at {path}")
with open(json_path, "r") as f:
metadata = json.load(f)
if "config" not in metadata:
raise ValueError(
f"Invalid format: missing 'config' in {json_path}. Please re-fit the probe."
)
config = metadata["config"]
tensors = load_file(sf_path)
probe = cls(
model=model,
tokenizer=tokenizer,
l1_C=config["l1_C"],
layer_stride=config["layer_stride"],
seed=config["seed"],
max_tokens=config["max_tokens"],
solver=config.get("solver", "auto"),
)
# Reconstruct the LogisticRegression model (solver only matters for refits)
probe._clf = LogisticRegression(
solver=config.get("solver_used") or "liblinear",
l1_ratio=1,
C=config["l1_C"],
max_iter=1000,
)
probe.solver_ = config.get("solver_used")
if "clf_coef" in tensors:
probe._clf.coef_ = tensors["clf_coef"].numpy()
if "clf_intercept" in tensors:
probe._clf.intercept_ = tensors["clf_intercept"].numpy()
if config.get("clf_classes"):
probe._clf.classes_ = np.array(config["clf_classes"])
probe._top_k_idx = tensors["top_k_idx"].numpy() if "top_k_idx" in tensors else None
probe._col_mean = tensors["col_mean"].numpy() if "col_mean" in tensors else None
probe._col_std = tensors["col_std"].numpy() if "col_std" in tensors else None
probe._X_train_cache = tensors["X_train"].numpy() if "X_train" in tensors else None
probe._y_train_cache = tensors["y_train"].numpy() if "y_train" in tensors else None
probe._X_val = tensors["X_val"].numpy() if "X_val" in tensors else np.array([])
probe._y_val = tensors["y_val"].numpy() if "y_val" in tensors else np.array([])
probe.h_neurons_ = [(layer, neuron) for layer, neuron in config["h_neurons"]]
probe._layers = config["layers"]
probe._intermediate_dim = config["intermediate_dim"]
probe._n_features = config["n_features"]
probe._answer_cue = config["answer_cue"]
probe.threshold_ = config.get("threshold", 0.5)
probe.n_consistency = config.get("n_consistency", 1)
probe.n_neurons_ = len(probe.h_neurons_)
probe.layer_distribution_ = {}
for layer, _ in probe.h_neurons_:
probe.layer_distribution_[layer] = probe.layer_distribution_.get(layer, 0) + 1
probe._col_norms = precompute_col_norms(model, probe._layers)
probe._set_feature_layout()
total = probe._n_features if probe._n_features > 0 else 1
probe.neuron_ratio_ = (probe.n_neurons_ / total) * 1000
probe._letter_ids = probe._get_letter_ids()
probe.is_fitted_ = True
return probe
def score_on(
self,
samples: List[Dict],
question_key: str = "question",
options_key: str = "options",
answer_key: str = "answer",
prompt_fn: Optional[Callable[[Dict], str]] = None,
) -> Dict:
"""Extract activations from the attached model and score with the loaded classifier.
Used for transfer experiments: the classifier was fitted on a different model,
and we test whether the same H-Neurons predict hallucination on this model.
Parameters
----------
samples : list of dict
MCQ samples in the same format used during fit().
question_key, options_key, answer_key, prompt_fn :
Same as fit().
Returns
-------
dict with auroc, balanced_accuracy, random_baseline_auroc, auroc_gap
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
if self._clf is None:
return {
"auroc": None,
"balanced_accuracy": None,
"random_baseline_auroc": None,
"random_baseline_balanced_accuracy": None,
"auroc_gap": None,
"n_h_neurons": 0,
"neuron_ratio_permille": 0.0,
"threshold": None,
}
X, y = [], []
skipped = 0
device = next(self.model.parameters()).device
if self.batch_size > 1:
orig_padding_side = self.tokenizer.padding_side
self.tokenizer.padding_side = "right"
batch_buf: list = [] # list of (prompt, gt)
def _flush(buf):
nonlocal skipped
if not buf:
return
prompts = [b[0] for b in buf]
enc = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
if "attention_mask" in enc:
last_positions = (enc["attention_mask"].sum(dim=1) - 1).tolist()
else:
last_positions = [enc["input_ids"].shape[1] - 1] * len(buf)
try:
cett_matrix, logits_matrix = forward_cett_batch(
self.model,
enc,
self._layers,
self._col_norms,
[int(p) for p in last_positions],
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += len(buf)
return
for i, (prompt, gt) in enumerate(buf):
try:
cett_vec = cett_matrix[i].numpy()
pred = self._predict_letter(logits_matrix[i])
label = 1 if pred != gt else 0
X.append(cett_vec)
y.append(label)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += 1
if torch.cuda.is_available():
torch.cuda.empty_cache()
for sample in tqdm(samples, desc="CETT extraction (transfer)"):
gt = self._parse_ground_truth(sample, answer_key)
if gt is None:
continue
prompt = self._build_prompt(
sample, question_key, options_key, prompt_fn, self._answer_cue
)
batch_buf.append((prompt, gt))
if self.batch_size > 1 and len(batch_buf) >= self.batch_size:
_flush(batch_buf)
batch_buf = []
if self.batch_size <= 1 and len(batch_buf) >= 1:
_flush(batch_buf)
batch_buf = []
if batch_buf:
_flush(batch_buf)
if self.batch_size > 1:
self.tokenizer.padding_side = orig_padding_side
if skipped:
print(f"[hprobes] Skipped transfer samples: {skipped}")
if not X:
return {
"auroc": None,
"balanced_accuracy": None,
"random_baseline_auroc": None,
"auroc_gap": None,
}
X_arr = np.array(X)
y_arr = np.array(y)
# Normalise with the original training statistics
if self._col_mean is not None and self._col_std is not None:
X_norm = (X_arr[:, self._top_k_idx] - self._col_mean) / (self._col_std + 1e-8)
else:
X_norm = X_arr[:, self._top_k_idx]
try:
scores = self._clf.predict_proba(X_norm)[:, 1]
auroc = roc_auc_score(y_arr, scores)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
auroc = None
preds = self._clf.predict(X_norm)
bal_acc = balanced_accuracy_score(y_arr, preds)
rand_auroc = None
if self.n_neurons_ > 0:
rng = np.random.RandomState(self.seed + 1)
rand_idx = rng.choice(
self._top_k_idx.shape[0],
size=min(self.n_neurons_, self._top_k_idx.shape[0]),
replace=False,
)
clf_rand = LogisticRegression(
solver=self.solver_ or "liblinear",
l1_ratio=1,
C=self.l1_C,
max_iter=1000,
random_state=self.seed,
)
try:
clf_rand.fit(X_norm[: len(X_norm) // 2, rand_idx], y_arr[: len(y_arr) // 2])
rand_scores = clf_rand.predict_proba(X_norm[len(X_norm) // 2 :, rand_idx])[:, 1]
rand_auroc = roc_auc_score(y_arr[len(y_arr) // 2 :], rand_scores)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
pass
gap = (auroc - rand_auroc) if (auroc is not None and rand_auroc is not None) else None
rand_str = f"{rand_auroc:.3f}" if rand_auroc is not None else "n/a"
gap_str = f"{gap:+.3f}" if gap is not None else "n/a"
print(f"[hprobes transfer] AUROC: {auroc:.3f} | Random: {rand_str} | Gap: {gap_str}")
result = {
"auroc": auroc,
"balanced_accuracy": bal_acc,
"random_baseline_auroc": rand_auroc,
"auroc_gap": gap,
"n_samples": len(X),
}
self.score_results_ = result
return result
def score_on_responses(
self,
samples: List[Dict],
question_key: str = "question",
response_key: str = "response",
label_key: str = "judge",
aggregation: str = "mean",
) -> Dict:
"""Score a fitted probe on pre-generated open-ended responses.
Used for cross-dataset transfer: the classifier was fitted on one dataset
and we evaluate it on another dataset's pre-generated Q+A pairs.
Parameters
----------
samples : list of dict
Each dict must contain question, response, and a correctness label.
question_key : str
Key for the question string.
response_key : str
Key for the generated response string.
label_key : str
Key for the correctness label.
aggregation : str
How to aggregate CETT over token spans ("mean" or "max").
Returns
-------
dict with auroc, balanced_accuracy, random_baseline_auroc, auroc_gap
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
if self._clf is None:
return {
"auroc": None,
"balanced_accuracy": None,
"random_baseline_auroc": None,
"random_baseline_balanced_accuracy": None,
"auroc_gap": None,
"n_h_neurons": 0,
"neuron_ratio_permille": 0.0,
"threshold": None,
}
X, y = [], []
skipped = 0
def _make_span(sample, question, response):
"""Build (full_text, (span_start, span_end)) for a sample, or None."""
if (
hasattr(self.tokenizer, "apply_chat_template")
and self.tokenizer.chat_template is not None
):
msgs = [
{"role": "user", "content": question},
{"role": "assistant", "content": response},
]
full_text = self.tokenizer.apply_chat_template(
msgs, tokenize=False, add_generation_prompt=False
)
user_only = self.tokenizer.apply_chat_template(
[{"role": "user", "content": question}],
tokenize=False,
add_generation_prompt=False,
)
user_tokens = self._tokenize(user_only)
input_len = user_tokens["input_ids"].shape[1] - 1
span_start = input_len + 1
else:
full_text = f"{question}\n{response}"
span_start = -1
tokens = self._tokenize(full_text)
seq_len = tokens["input_ids"].shape[1]
if span_start < 0:
span_start, span_end = 0, seq_len
else:
span_end = seq_len
return full_text, (span_start, span_end)
device = next(self.model.parameters()).device
if self.batch_size > 1:
orig_padding_side = self.tokenizer.padding_side
self.tokenizer.padding_side = "right"
pending = [] # (sample, is_correct, full_text, span)
for sample in tqdm(samples, desc="CETT extraction (transfer)"):
raw_label = sample.get(label_key)
if raw_label is None:
skipped += 1
continue
is_correct = str(raw_label).lower() in ("true", "1", "t")
question = sample.get(question_key, "")
response = sample.get(response_key, "")
made = _make_span(sample, question, response)
if made is None:
skipped += 1
continue
full_text, span = made
pending.append((sample, is_correct, full_text, span))
if self.batch_size > 1 and len(pending) >= self.batch_size:
batch = pending
pending = []
prompts = [b[2] for b in batch]
enc = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
spans = [b[3] for b in batch]
try:
vec_ans_m, _vec_oth_m = forward_cett_dual_span_batch(
self.model, enc, spans, self._layers, self._col_norms, aggregation
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError):
skipped += len(batch)
continue
for i, (_sample, is_correct, _ft, _span) in enumerate(batch):
ans = np.nan_to_num(vec_ans_m[i].numpy().astype(np.float32))
X.append(ans)
y.append(0 if is_correct else 1)
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Final partial batch (batch_size > 1) or the batch_size==1 single-forward path
if self.batch_size > 1:
if pending:
prompts = [b[2] for b in pending]
enc = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
spans = [b[3] for b in pending]
try:
vec_ans_m, _vec_oth_m = forward_cett_dual_span_batch(
self.model, enc, spans, self._layers, self._col_norms, aggregation
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError):
skipped += len(pending)
else:
for i, (_sample, is_correct, _ft, _span) in enumerate(pending):
ans = np.nan_to_num(vec_ans_m[i].numpy().astype(np.float32))
X.append(ans)
y.append(0 if is_correct else 1)
if torch.cuda.is_available():
torch.cuda.empty_cache()
else:
for _sample, is_correct, full_text, span in pending:
span_start, span_end = span
try:
vec_ans, _vec_other = forward_cett_dual_span(
self.model,
self._tokenize(full_text),
span_start,
span_end,
self._layers,
self._col_norms,
aggregation,
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError):
skipped += 1
continue
ans = np.nan_to_num(vec_ans.numpy().astype(np.float32))
X.append(ans)
y.append(0 if is_correct else 1)
if torch.cuda.is_available():
torch.cuda.empty_cache()
if self.batch_size > 1:
self.tokenizer.padding_side = orig_padding_side
if skipped:
print(f"[hprobes] Skipped transfer samples: {skipped}")
if not X:
return {
"auroc": None,
"balanced_accuracy": None,
"random_baseline_auroc": None,
"random_baseline_balanced_accuracy": None,
"auroc_gap": None,
"n_samples": 0,
}
X_arr = np.array(X)
y_arr = np.array(y)
if self._col_mean is not None and self._col_std is not None:
X_norm = (X_arr[:, self._top_k_idx] - self._col_mean) / (self._col_std + 1e-8)
else:
X_norm = X_arr[:, self._top_k_idx]
try:
scores = self._clf.predict_proba(X_norm)[:, 1]
auroc = roc_auc_score(y_arr, scores)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error computing AUROC: {e}")
auroc = None
try:
preds = self._clf.predict(X_norm)
bal_acc = balanced_accuracy_score(y_arr, preds)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error computing balanced accuracy: {e}")
bal_acc = None
rand_auroc = None
if self.n_neurons_ > 0:
rng = np.random.RandomState(self.seed + 1)
rand_idx = rng.choice(
self._top_k_idx.shape[0],
size=min(self.n_neurons_, self._top_k_idx.shape[0]),
replace=False,
)
clf_rand = LogisticRegression(
solver=self.solver_ or "liblinear",
l1_ratio=1,
C=self.l1_C,
max_iter=1000,
random_state=self.seed,
)
try:
n_half = len(X_norm) // 2
if n_half >= 2 and len(set(y_arr[:n_half])) >= 2:
clf_rand.fit(X_norm[:n_half, rand_idx], y_arr[:n_half])
rand_scores = clf_rand.predict_proba(X_norm[n_half:, rand_idx])[:, 1]
rand_auroc = roc_auc_score(y_arr[n_half:], rand_scores)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError):
pass
gap = (auroc - rand_auroc) if (auroc is not None and rand_auroc is not None) else None
rand_str = f"{rand_auroc:.3f}" if rand_auroc is not None else "n/a"
gap_str = f"{gap:+.3f}" if gap is not None else "n/a"
print(f"[hprobes transfer] AUROC: {auroc:.3f} | Random: {rand_str} | Gap: {gap_str}")
result = {
"auroc": auroc,
"balanced_accuracy": bal_acc,
"random_baseline_auroc": rand_auroc,
"auroc_gap": gap,
"n_samples": len(X),
"y_true": y_arr.tolist(),
"y_score": scores.tolist() if auroc is not None else None,
}
self.score_results_ = result
return result
def detect(
self,
prompt: str,
answer_letter: Optional[str] = None,
) -> float:
"""Estimate hallucination risk for a single prompt (production inference).
Runs one or two forward passes on ``prompt`` and returns a risk score
using the fitted probe — no ground truth required.
Parameters
----------
prompt : str
Fully formatted prompt string, including the answer cue
(e.g. the output of ``tokenizer.apply_chat_template(...)`` + ``"\\n\\nAnswer:"``).
answer_letter : str, optional
The letter the model already predicted (e.g. ``"A"``).
If provided, skips the first forward pass (faster — piggybacks on your
existing generation call). If None, the probe runs its own forward pass
to predict the letter.
Returns
-------
float
Hallucination risk score in ``[0, 1]``.
Higher → model more likely to be wrong / hallucinating.
Raises
------
RuntimeError
If called before ``fit()``.
ValueError
If ``answer_letter`` is not a recognised MCQ letter (A–J).
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
if self._clf is None:
return 0.5
tokens = self._tokenize(prompt)
# Always use 3-vs-1 approach: CETT at answer token
if answer_letter is None:
_, logits = forward_cett(self.model, tokens, self._layers, self._col_norms)
answer_letter = self._predict_letter(logits)
else:
answer_letter = answer_letter.strip().upper()
letter_token_id = self._letter_ids.get(answer_letter)
if letter_token_id is None:
raise ValueError(
f"Unknown answer letter {answer_letter!r}. Expected one of {list(self._letter_ids)}"
)
cett_vec = forward_cett_at_token(
self.model, tokens, letter_token_id, self._layers, self._col_norms
)
x = np.nan_to_num(cett_vec.numpy().astype(np.float32))
x_sel = x[self._top_k_idx]
if self._col_mean is not None and self._col_std is not None:
x_norm = (x_sel - self._col_mean) / (self._col_std + 1e-8)
else:
x_norm = x_sel
return float(self._clf.predict_proba(x_norm.reshape(1, -1))[0, 1])
def detect_batch(
self,
prompts: List[str],
answer_letters: Optional[List[str]] = None,
batch_size: Optional[int] = None,
) -> List[float]:
"""Estimate hallucination risk for a batch of prompts.
Batched version of :meth:`detect` — uses the same GPU-vectorized CETT
extraction as ``fit()``, so throughput scales with batch size.
Parameters
----------
prompts : list of str
Fully formatted prompt strings including the answer cue.
answer_letters : list of str, optional
Predicted answer letter per prompt (e.g. ``["A", "C", "B"]``).
If provided, skips the first forward pass for the whole batch.
If None, the probe runs a batched forward pass to predict all letters.
batch_size : int, optional
Number of prompts per forward pass. Defaults to ``self.batch_size``.
Returns
-------
list of float
Hallucination risk score in ``[0, 1]`` for each prompt, in the same
order as ``prompts``.
"""
if not self.is_fitted_:
raise RuntimeError(_NOT_FITTED_MSG)
bs = batch_size or self.batch_size
device = next(self.model.parameters()).device
orig_padding_side = self.tokenizer.padding_side
self.tokenizer.padding_side = "right"
all_scores: List[float] = []
try:
for start in range(0, len(prompts), bs):
batch_prompts = prompts[start : start + bs]
batch_letters = (
answer_letters[start : start + bs] if answer_letters is not None else None
)
enc = self.tokenizer(
batch_prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
if "attention_mask" in enc:
last_positions = (enc["attention_mask"].sum(dim=1) - 1).tolist()
else:
last_positions = [enc["input_ids"].shape[1] - 1] * len(batch_prompts)
# Get answer letters if not provided
if batch_letters is None:
_, logits_matrix = forward_cett_batch(
self.model,
enc,
self._layers,
self._col_norms,
[int(p) for p in last_positions],
)
batch_letters = [
self._predict_letter(logits_matrix[i]) for i in range(len(batch_prompts))
]
else:
batch_letters = [lt.strip().upper() for lt in batch_letters]
# Get letter token IDs
letter_ids = [self._letter_ids.get(lt) for lt in batch_letters]
valid_idx = [i for i, lid in enumerate(letter_ids) if lid is not None]
if not valid_idx:
# No valid letters, return 0.0 for all
all_scores.extend([0.0] * len(batch_prompts))
continue
# Extract CETT at answer tokens
valid_enc: Dict[str, torch.Tensor] = {"input_ids": enc["input_ids"][valid_idx]}
if "attention_mask" in enc:
valid_enc["attention_mask"] = enc["attention_mask"][valid_idx]
cett_matrix = forward_cett_at_token_batch(
self.model,
valid_enc,
[letter_ids[i] for i in valid_idx],
self._layers,
self._col_norms,
)
# Map valid results back to original batch positions
scores_batch = [0.0] * len(batch_prompts)
for j, i in enumerate(valid_idx):
x = np.nan_to_num(cett_matrix[j].numpy().astype(np.float32))
x_sel = x[self._top_k_idx]
if self._col_mean is not None and self._col_std is not None:
x_norm = (x_sel - self._col_mean) / (self._col_std + 1e-8)
else:
x_norm = x_sel
scores_batch[i] = float(self._clf.predict_proba(x_norm.reshape(1, -1))[0, 1])
all_scores.extend(scores_batch)
if torch.cuda.is_available():
torch.cuda.empty_cache()
finally:
self.tokenizer.padding_side = orig_padding_side
return all_scores
# ------------------------------------------------------------------
# Prompt building
# ------------------------------------------------------------------
def _letter_logits_for(
self, logits: torch.Tensor, sample: Dict, options_key: str
) -> Dict[str, float]:
"""Raw letter logits at the readout position, restricted to the sample's options."""
options = sample.get(options_key, {}) or {}
if isinstance(options, list):
letters = [_MCQ_LETTERS[i] for i in range(len(options))]
elif isinstance(options, dict):
letters = list(options.keys())
else:
letters = []
return {
letter: round(float(logits[self._letter_ids[letter]].item()), 4)
for letter in letters
if letter in self._letter_ids
}
def _extract_generated_letter(self, text: str, sample: Dict, options_key: str) -> Optional[str]:
"""Parse the answer letter from generated text for a sample."""
options = sample.get(options_key, {}) or {}
if isinstance(options, list):
letters = [_MCQ_LETTERS[i] for i in range(len(options)) if i < len(_MCQ_LETTERS)]
texts = {letter: str(t) for letter, t in zip(letters, options)}
elif isinstance(options, dict):
letters = [letter for letter in options if letter in self._letter_ids]
texts = {letter: str(options[letter]) for letter in letters}
else:
return None
return _extract_letter_from_text(text, letters, texts)
def _generate_letter(
self, prompt: str, sample: Dict, options_key: str
) -> Tuple[Optional[str], str]:
"""Greedy generation for the MCQ readout. Returns ``(letter, generated_text)``."""
self._ensure_pad_token()
tokens = self._tokenize(prompt)
input_len = tokens["input_ids"].shape[1]
with torch.inference_mode():
out = self.model.generate(
**tokens,
max_new_tokens=self.readout_max_new_tokens,
do_sample=False,
pad_token_id=self.tokenizer.pad_token_id,
)
text = self.tokenizer.decode(out[0, input_len:], skip_special_tokens=True)
return self._extract_generated_letter(text, sample, options_key), text
def _build_prompt(
self,
sample: Dict,
question_key: str,
options_key: str,
prompt_fn: Optional[Callable],
answer_cue: str,
) -> str:
"""Build a formatted prompt string from a sample dict.
If prompt_fn is provided, uses it directly.
Otherwise, uses tokenizer.apply_chat_template() with MCQ formatting.
"""
if prompt_fn is not None:
content = prompt_fn(sample)
else:
q = sample.get(question_key, "")
opts = sample.get(options_key, {})
if isinstance(opts, str):
import ast
try:
opts = ast.literal_eval(opts)
except (
ValueError,
KeyError,
RuntimeError,
IndexError,
TypeError,
SyntaxError,
) as e:
logging.warning(f"Error evaluating ast literal: {e}")
opts = {}
if isinstance(opts, list):
# HuggingFace datasets like MMLU use a list of choice texts
opts = {_MCQ_LETTERS[i]: v for i, v in enumerate(opts)}
if opts:
choices = "\n".join(f"{k}. {v}" for k, v in opts.items())
content = f"{q}\n{choices}"
else:
content = q
# Use model's own chat template if available, else plain text
if (
hasattr(self.tokenizer, "apply_chat_template")
and self.tokenizer.chat_template is not None
):
messages = [{"role": "user", "content": content}]
prompt = self.tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
else:
prompt = content
return prompt + answer_cue
def _parse_ground_truth(self, sample: Dict, answer_key: str) -> Optional[str]:
"""Extract ground-truth answer letter from sample dict.
Handles:
- Single letter: "A", "B", ...
- Numeric index: 0→A, 1→B, ... (common in HuggingFace MCQ datasets)
- List wrapping: ["A"] or ["Ans. The key is B. ..."] (e.g. PLAB)
- Free-text: "Ans. The key is B. ..." → extracts first A-J letter after
common answer cue phrases
"""
import re
raw = sample.get(answer_key)
if raw is None:
return None
# Unwrap single-element lists
if isinstance(raw, list):
raw = raw[0] if raw else None
if raw is None:
return None
raw = str(raw).strip()
if raw.upper() in _MCQ_LETTERS:
return raw.upper()
if raw.isdigit() and int(raw) < len(_MCQ_LETTERS):
return _MCQ_LETTERS[int(raw)]
# Free-text fallback: "The key is B", "answer is C", "key: D", etc.
m = re.search(r"(?:key\s+is|answer\s+is|key\s*:)\s*([A-J])\b", raw, re.IGNORECASE)
if m:
return m.group(1).upper()
return None
# ------------------------------------------------------------------
# Tokenizer / logit helpers
# ------------------------------------------------------------------
def _get_letter_ids(self, space_prefixed: bool = False) -> Dict[str, int]:
"""Map MCQ letters → single token id each.
``space_prefixed`` targets the tokens models emit in text (``" A"``
rather than ``"A"``); the last id is used so a split prefix cannot
shadow the letter token.
"""
letter_ids = {}
for letter in _MCQ_LETTERS:
text = f" {letter}" if space_prefixed else letter
ids = self.tokenizer.encode(text, add_special_tokens=False)
if ids:
letter_ids[letter] = ids[-1] if space_prefixed else ids[0]
return letter_ids
def _predict_letter(self, logits: torch.Tensor, letters: Optional[List[str]] = None) -> str:
"""Pick the MCQ letter with the highest logit.
``letters`` optionally restricts the argmax to the sample's option
keys (e.g. A-D for four-option questions).
"""
candidates = {k: v for k, v in self._letter_ids.items() if letters is None or k in letters}
if not candidates:
candidates = self._letter_ids
return max(candidates.items(), key=lambda kv: logits[kv[1]].item())[0]
def _consistency_predict(self, tokens: Dict[str, torch.Tensor], n: int) -> Optional[str]:
"""Sample n predictions from the letter distribution and return the agreed letter.
Runs a single forward pass, restricts logits to MCQ letter tokens, then
draws n samples with temperature=1.0. Returns the agreed letter if all n
samples match, else None (inconsistent → skip the sample).
"""
letters = list(self._letter_ids.keys())
token_ids = torch.tensor(list(self._letter_ids.values()))
with torch.inference_mode():
out = self.model(**tokens)
logits = out.logits[0, -1, :].float().cpu()
letter_logits = logits[token_ids] # (n_letters,) — temperature=1.0 (no scaling)
probs = torch.softmax(letter_logits, dim=0)
indices = torch.multinomial(probs, num_samples=n, replacement=True).tolist()
preds = [letters[i] for i in indices]
return preds[0] if len(set(preds)) == 1 else None
def _ensure_pad_token(self):
"""Ensure the tokenizer has a pad token so batched padding works.
Falls back to the EOS token when the tokenizer defines none. Modifies
the tokenizer in place; safe to call repeatedly.
"""
if self.tokenizer.pad_token_id is not None:
return
if self.tokenizer.eos_token_id is not None:
self.tokenizer.pad_token = self.tokenizer.eos_token
return
self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
self.model.resize_token_embeddings(len(self.tokenizer))
def _tokenize(self, prompt: str) -> Dict[str, torch.Tensor]:
device = next(self.model.parameters()).device
tokens = self.tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=self.max_tokens,
)
return {k: v.to(device) for k, v in tokens.items()}
# ------------------------------------------------------------------
# Feature extraction
# ------------------------------------------------------------------
def _extract_features(
self,
samples: List[Dict],
question_key: str,
options_key: str,
answer_key: str,
prompt_fn: Optional[Callable],
answer_cue: str,
top_k: int,
label_fn: Optional[Callable[[str, str, Dict], int]],
):
"""Extract CETT feature vectors for all samples.
Runs inference internally to:
1. Predict the model's answer letter
2. Compare to ground truth → correctness label
3. Extract CETT in the same forward pass
Returns
-------
cett_raw, train_labels, row_to_sample, valid_prompts, valid_gt, per_sample
"""
# Default labeling: hallucination (incorrect=1, correct=0)
if label_fn is None:
def label_fn(pred, gt, sample):
return 1 if pred != gt else 0
self._welford_n = 0
self._welford_mean = np.zeros(self._n_features, dtype=np.float64)
self._welford_M2 = np.zeros(self._n_features, dtype=np.float64)
cett_raw, train_labels, row_to_sample = [], [], []
valid_prompts, valid_gt = [], []
valid_samples: List[Dict] = []
per_sample = []
skipped = 0
device = next(self.model.parameters()).device
if self.batch_size > 1:
orig_padding_side = self.tokenizer.padding_side
self.tokenizer.padding_side = "right"
batch_buf: list = [] # list of (sample, gt, prompt) waiting to be processed
def _flush_batch(buf):
nonlocal skipped
if not buf:
return
prompts = [b[2] for b in buf]
enc = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=self.max_tokens,
).to(device)
# last real token position per sample (for logits)
if "attention_mask" in enc:
last_positions = (enc["attention_mask"].sum(dim=1) - 1).tolist()
else:
last_positions = [enc["input_ids"].shape[1] - 1] * len(buf)
try:
cett_matrix, logits_matrix = forward_cett_batch(
self.model,
enc,
self._layers,
self._col_norms,
[int(p) for p in last_positions],
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += len(buf)
return
for i, (sample, gt, prompt) in enumerate(buf):
logits_letter = self._predict_letter(logits_matrix[i])
generated, generated_letter = None, None
if self.readout in ("generate", "both"):
generated_letter, generated = self._generate_letter(prompt, sample, options_key)
if generated_letter is None:
skipped += 1
continue
pred = generated_letter
else:
pred = logits_letter
is_correct = pred == gt
sample_pos = len(valid_prompts)
valid_prompts.append(prompt)
valid_gt.append(gt)
valid_samples.append(sample)
record = {
"predicted": pred,
"ground_truth": gt,
"is_correct": is_correct,
"letter_logits": self._letter_logits_for(logits_matrix[i], sample, options_key),
"logits_letter": logits_letter,
"logits_is_correct": logits_letter == gt,
}
if generated is not None:
record["generated"] = generated
record["generated_letter"] = generated_letter
record["generated_is_correct"] = generated_letter == gt
per_sample.append(record)
# Decision feature: last prompt token CETT (the model's pre-decision state)
try:
last_prompt_vec = np.nan_to_num(cett_matrix[i].numpy().astype(np.float32))
cett_raw.append(last_prompt_vec)
train_labels.append(label_fn(pred, gt, sample))
row_to_sample.append(sample_pos)
self._welford_update(last_prompt_vec)
except Exception as e:
logging.warning(f"Error extracting prompt CETT in batch: {e}")
if torch.cuda.is_available():
torch.cuda.empty_cache()
for sample in tqdm(samples, desc="CETT extraction"):
gt = self._parse_ground_truth(sample, answer_key)
if gt is None:
skipped += 1
continue
prompt = self._build_prompt(sample, question_key, options_key, prompt_fn, answer_cue)
if self.batch_size > 1 and self.n_consistency <= 1:
batch_buf.append((sample, gt, prompt))
if len(batch_buf) >= self.batch_size:
_flush_batch(batch_buf)
batch_buf = []
continue
# --- single-sample path ---
tokens = self._tokenize(prompt)
letter_logits = None
logits_letter = None
generated, generated_letter = None, None
if self.n_consistency > 1:
pred = self._consistency_predict(tokens, self.n_consistency)
if pred is None:
skipped += 1
continue
logits_letter = pred
try:
cett_vec, _ = forward_cett(self.model, tokens, self._layers, self._col_norms)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += 1
continue
else:
try:
cett_vec, logits = forward_cett(
self.model, tokens, self._layers, self._col_norms
)
except (ValueError, KeyError, RuntimeError, IndexError, TypeError) as e:
logging.warning(f"Error: {e}")
skipped += 1
continue
logits_letter = self._predict_letter(logits)
letter_logits = self._letter_logits_for(logits, sample, options_key)
pred = logits_letter
if self.readout in ("generate", "both") and self.n_consistency <= 1:
generated_letter, generated = self._generate_letter(prompt, sample, options_key)
if generated_letter is None:
skipped += 1
continue
pred = generated_letter
is_correct = pred == gt
sample_pos = len(valid_prompts)
valid_prompts.append(prompt)
valid_gt.append(gt)
valid_samples.append(sample)
record = {
"predicted": pred,
"ground_truth": gt,
"is_correct": is_correct,
"letter_logits": letter_logits,
"logits_letter": logits_letter,
"logits_is_correct": logits_letter == gt,
}
if generated is not None:
record["generated"] = generated
record["generated_letter"] = generated_letter
record["generated_is_correct"] = generated_letter == gt
per_sample.append(record)
# Decision feature: last prompt token CETT (the model's pre-decision state)
try:
cett_vec_np = np.nan_to_num(cett_vec.numpy().astype(np.float32))
cett_raw.append(cett_vec_np)
train_labels.append(label_fn(pred, gt, sample))
row_to_sample.append(sample_pos)
self._welford_update(cett_vec_np)
except Exception as e:
logging.warning(f"Error extracting decision CETT: {e}")
if torch.cuda.is_available():
torch.cuda.empty_cache()
# flush remaining batch
if batch_buf:
_flush_batch(batch_buf)
if self.batch_size > 1:
self.tokenizer.padding_side = orig_padding_side
if skipped:
print(f"[hprobes] Skipped: {skipped}")
return (
cett_raw,
train_labels,
row_to_sample,
valid_prompts,
valid_gt,
per_sample,
valid_samples,
)
def _find_answer_span(
self, input_ids: torch.Tensor, answer_tokens: List[str]
) -> Optional[Tuple[int, int]]:
"""Find the contiguous span of answer tokens in the tokenized sequence.
Normalizes ▁ (SentencePiece) and Ġ (BPE) word boundary markers before
matching.
Returns (start, end) indices (end exclusive), or None if not found.
"""
if not answer_tokens:
return None
full_tokens = [self.tokenizer.decode([tid]) for tid in input_ids]
ans_norm = [t.replace("▁", " ").replace("Ġ", " ") for t in answer_tokens]
m = len(ans_norm)
for i in range(len(full_tokens) - m + 1):
window = [full_tokens[j].replace("▁", " ").replace("Ġ", " ") for j in range(i, i + m)]
if window == ans_norm:
return i, i + m
return None
def _welford_update(self, vec: np.ndarray):
self._welford_n += 1
delta = vec.astype(np.float64) - self._welford_mean
self._welford_mean += delta / self._welford_n
self._welford_M2 += delta * (vec.astype(np.float64) - self._welford_mean)