How It Works
hprobes implements the H-Neuron discovery pipeline from arXiv:2512.01797. This page explains the core concepts.
The CETT Metric
CETT (Contribution to rEsidual sTream norm of Token t) measures how much each individual FFN neuron contributes to the model's hidden state at a given token position.
For neuron j at token position t:
Where:
z_{j,t}— SwiGLU activation of neuronjat tokent(input toW_down)W_down[:, j]— thej-th column of the down-projection weight matrixh_t = W_down * z_t— FFN output vector at tokent
The column norms ||W_down[:, j]||_2 are precomputed once and reused across all samples.
Model Support
hprobes reads each layer's FFN down-projection (down_proj, c_proj, fc2). Two architecture variations are handled explicitly:
- Heterogeneous FFN dims — models whose intermediate size differs per layer (e.g. Gemma 4 E-series double-wide MLPs) are supported: dims are tracked per layer and flat CETT indices map through per-layer offsets.
- MoE layers — two capture paths exist. Dense extraction reads the layer's FFN down-projection, which for MoE models with a dense shared expert (e.g. Qwen2MoE / Qwen3.5 MoE) is
shared_expert.down_proj; flattened 2D(tokens, dim)activations from the shared expert are handled by the hooks. Routed experts are covered by the MoE pipeline (fit_moe), which replays the experts loop and captures active-only per-expert CETT. When a shared expert is present,fit_moealso captures it read-only and fuses it into the same probe design (L{layer}:S:N{neuron}features, gate-weighted bysigmoid(shared_expert_gate)when available).
H-Neuron Discovery
The discovery pipeline has four steps:
1. Feature Extraction
For each MCQ sample, the model predicts an answer letter by reading logits at the last token of the prompt (the answer cue, when used, is part of the prompt). CETT is extracted and the prediction is compared against the ground truth.
2. Labeling
Contrastive mode (default, contrastive=True):
- Appends the predicted answer token to the prompt and captures CETT at that position
- If the model is wrong: label = 1 (hallucination)
- If the model is correct: label = 0
- Also captures CETT at the last prompt token and always labels it 0 (negative example)
- This 3-vs-1 scheme gives the classifier both "where the model decides" and "where it hallucinates"
Non-contrastive mode (contrastive=False):
- Captures CETT at the last prompt token only
- Incorrect answers → label 1, correct → label 0
3. Sparse Selection
- Variance pre-selection: Top 5,000 features by variance (Welford's online algorithm)
- Standardization: Zero-mean, unit-variance normalization
- L1 logistic regression:
LogisticRegression(solver="liblinear", l1_ratio=1, C=l1_C, class_weight="balanced") - H-Neuron extraction: Neurons with positive coefficients in the trained classifier
The l1_C parameter controls sparsity — lower values yield fewer, more confident H-Neurons.
Large-matrix solver fallback (#47)
liblinear casts element counts to 32-bit integers, so matrices with more than
2**31 - 1 nonzero units raise OverflowError at fit time (this bites 27B+
models at all-features covering ~1M+ features). With solver="auto" (the
default), the probe pre-checks the exact quantity liblinear checks and routes
to saga — the only other L1-capable solver — only when the ceiling would be
exceeded; below it, behavior stays byte-identical (liblinear). A residual
OverflowError under auto triggers one logged retry with saga. Explicit
solver="saga" is also available, e.g. to run a whole grid single-solver.
Sparsity/result caveats (measured on GPT-2 + MedQA and ESM-2 650M masked
residues): at equal C, saga recovers ~99% of liblinear's selected neurons but
yields a ~5× denser set; probe AUROC is statistically indistinguishable
(paired bootstrap CI spans zero). Matching liblinear's set density needs a
C retune (~half, dataset-dependent), and even then the exact sets differ at
the margins. Fit time is ~5× slower at realistic matrix sizes. Never mix
solvers within one comparison (grid/table/claim) — use solver="saga" for
all cells or liblinear for all cells; the effective solver is recorded in
saved metadata (config.solver_used). At the default tolerance (tol=1e-4),
saga may exhaust max_iter=1000 and emit a ConvergenceWarning while still
returning an approximately-equal solution — a budget limit of the optimizer,
not a failure (no int32 ceiling exists on saga's path); budget tuning is
deferred until real above-ceiling (2³¹ units) runs provide evidence.
4. Causal Validation
To confirm that H-Neurons causally influence hallucination (not just correlate with it), causal_validate() scales their activations during inference:
| Alpha | Effect |
|---|---|
| 0.0 | Full suppression (zero out H-Neurons) |
| 0.5 | Partial suppression |
| 1.0 | Baseline (no intervention) |
| 1.5 | Mild amplification |
| 2.0 | Strong amplification |
If H-Neurons are truly causal, suppressing them should change accuracy on the validation set.
Contrastive vs Non-Contrastive
| Contrastive (default) | Non-Contrastive | |
|---|---|---|
| CETT position | Predicted answer token | Last prompt token |
| Forward passes | 2 per sample | 1 per sample |
| Labeling | 3-vs-1 (answer + prompt rows) | Binary (correct/incorrect) |
| Captures | Where hallucination manifests | Where the model makes the decision |
Contrastive mode is recommended for most use cases. It produces more discriminative features because it captures the model's representation specifically at the point of answer generation.
Extract Once, Refit Many
fit() couples the expensive forward phase (CETT extraction) with the cheap
selection+fitting phase. For sweeps over multiple variants on the same samples
(different top_k, control labels, bootstraps), split the two:
rows = probe.extract_features(samples) # forwards run once
probe.fit_on_features(rows) # variant 1: defaults
probe.fit_on_features(rows, top_k=1000) # variant 2: reselect only
extract_features_from_responses() / fit_on_response_features() are the
same split for pre-generated responses. Artifacts persist with
save_rows() / load_rows() (arrays + JSON sidecar); rows_key() binds
cached rows to exact weights, samples and extraction config, so stale rows
can never be silently reused. Selection always stays downstream of the cache.
Consistency Filtering
When n_consistency > 1, the probe draws n samples from the restricted letter distribution (softmax over A–J logits) before committing to a prediction. If the draws disagree, the sample is skipped entirely.
This matches the paper's methodology of filtering out ambiguous samples where the model is uncertain between multiple letters.
Threshold Calibration
After score(), the probe computes an optimal decision threshold using Youden's J statistic:
This is stored as probe.threshold_ and persisted through save()/load(). The threshold is used in production when you need a binary hallucination/not-hallucination decision rather than a continuous score.
Performance Optimizations and Numerical Equivalence
hprobes batches the deterministic CETT extraction loops (fit_from_responses, score_on_responses, causal_validate) when batch_size > 1, and uses torch.inference_mode() (numerically identical to no_grad, just faster). The batched paths are verified equivalent to the single-sample paths by tests/test_equivalence.py and tests/test_attn_equivalence.py.
Attention implementations are approximately-equal, not bit-identical
eager attention is the reference used for published results. sdpa and flash_attention_2 (opt-in via --attn-implementation) are faster but only approximately numerically equal — fused kernels reorder floating-point accumulation. On MPS we measured eager-vs-sdpa logits differing by up to ~0.5 (argmax stable on test samples); activations at down_proj shift by ~1e-2–1e-1 relative. This can flip borderline predictions. Do not use sdpa/flash to produce or reproduce published paper numbers unless you run and record an equivalence check (the harness in tests/test_attn_equivalence.py).
Why the hooked probing paths do not use torch.compile
CETT extraction and α-scaling read/modify activations through forward hooks that write to Python dicts. torch.compile with fullgraph=True is incompatible with this pattern: the hook logic gets baked into the compiled graph at trace time and never executes during the forward pass, so no activations are captured (see pytorch/pytorch#173452, open as of 2026). The fullgraph=False workaround loses ~30–50% of the CUDA-graph speedup. Consequently the probing paths intentionally stay eager. torch.compile is only safe for hook-free, fixed-shape forward passes (e.g. plain generation).