Module contents
Lesson 14 of 39Core 100 min

Probing: what information representations contain

Study interpretability of internal representations through layer-wise linear probes, control tasks and MDL, distinguishing decodable information from information used. Explore evidence for linear representations, TCAV concept vectors and concept erasure as a causal test.

After this lesson you can

  • Train layer-wise linear probes on transformer activations and plot decodability curves.
  • Design control tasks and calculate probe selectivity.
  • Calculate and interpret the online code length of MDL probing.
  • Apply TCAV with tests against random concepts.
  • Erase a concept with INLP or LEACE and test whether model behavior changes.

Before you start

What is in a representation?

A model receives a sequence of Othello moves and predicts the next one. Even without explicitly receiving the board, its internal states may contain enough information to reconstruct it. A probe tries to read a known property from a frozen activation. Its success provides evidence that the property is decodable under the chosen protocol; it does not itself prove that the model uses that property to produce its output.

In a layer-wise linear probe, extract a representation hi∈Rdh_i\in\mathbb R^d and fit p(yi∣hi)=softmax⁡(Whi+b)p(y_i\mid h_i)=\operatorname{softmax}(Wh_i+b). Train W,bW,b on one split and measure accuracy and loss on another; the model producing hih_i remains frozen. Repeat for each layer with the same task, budget and splits, selecting regularization on validation. A curve by layer answers where a label becomes easy to read with that probe family, not where it was first computed or which single layer uses it. Sample size, duplicates and entity grouping matter as much as the classifier.

Before fitting, define the evaluation unit. If several sentences describe the same entity, randomly splitting sentences can place that entity in training and test; the probe can recognize it without generalizing to new entities. An entity split answers a different question and is usually harder. For pairs such as a statement and its negation, keep members of each pair together to avoid test wording revealing a template seen during fitting. Also check a majority-class baseline and, when classes are imbalanced, accompany accuracy with per-class metrics.

Layer comparisons must extract activations at the same sequence position: first token, last token and mean are not equivalent. Normalization, dimension and regularization affect ease of fitting. Fit transformations using training only and freeze them before evaluation. Selecting the best test layer and reporting that same value as final performance selects on the test set; choose using validation and measure on a separate final split. A single curve does not identify the mechanism that generated the information.

A probe that learns the task

If the representation retains word identity, an expressive probe can memorize an arbitrary label per type and score well even if the linguistic property is not simply organized. Hewitt and Liang assign fixed random labels to types and define selectivity as task accuracy minus control accuracy. The control must share the same protocol, classes and access to identity: an independent random assignment per occurrence does not measure that memorization.

InteractiveA probe that is too clever
  • Task
  • Control
0
ProbeLinear
Task accuracy0.938
Control accuracy0.588
Selectivity0.350
Results of probes actually fitted on synthetic representations of 120 types. Each type appears in training and test, with different noise per occurrence; the control has a fixed random label per type.

The figure uses six occurrences of each type for training and two for evaluation. The real task depends linearly on two coordinates and the control is randomly assigned. A drop in selectivity warns about capacity in this experiment; it is not a law that every large probe memorizes or a universal measure of causality. Evaluating unseen types changes the question and the control task no longer measures the same memorization capacity. The downloadable generator preserves seed, classes and fitting; review MLP convergence warnings before interpreting a new result.

The cost of communicating labels

Minimum description length for probing also addresses the effort needed to learn the readout. The online code fixes an order and blocks B0,…,BKB_0,\ldots,B_K. The first block is transmitted with a uniform code of log⁡2C\log_2 C bits per label; for each subsequent block, train a probe on previous blocks and encode its labels using probabilities predicted before seeing them:

Lonline=∣B0∣log⁡2C−∑k=1K∑i∈Bklog⁡2pk−1(yi∣hi).L_{\rm online}=|B_0|\log_2 C-\sum_{k=1}^{K}\sum_{i\in B_k}\log_2 p_{k-1}(y_i\mid h_i).

More compression means that probe family learned to predict labels earlier under that order and schedule. It is not exact mutual information or a property independent of optimizer, discretization, order or distribution. Probabilities must be valid and fitting for each block may use only earlier labels; training on the encoded block leaks the future. Voita and Titov compare this method with another code based on model cost.

For example, for a binary task with four initial labels and a uniform distribution, the first block costs four bits. If the next has two labels and the probe assigns 0.8 to each correct answer, it adds −2log⁡2(0.8)≈0.644-2\log_2(0.8)\approx0.644 bits. A highly confident wrong prediction costs much more than an uncertain prediction; thus MDL depends on calibration, not only accuracy. Repeat orders and report their variability. When comparing representations, keep the same labels, blocks, hyperparameter search and probe family; an isolated bit count has no interpretation without that protocol.

From a concept direction to an intervention

For TCAV, construct concept and reference examples, extract their activations at a layer and fit a linear separator. The normal vector oriented toward the concept is a CAV vCv_C. For class output fkf_k and activation hh, local sensitivity is ∇hfk(h)⊤vC\nabla_h f_k(h)\T v_C; a collection’s TCAV counts the fraction with positive derivative. Normalization, chosen logit, point and vector orientation change the interpretation. A positive derivative describes an infinitesimal activation displacement; it does not prove there is a natural input edit that changes only the concept.

Repeat construction with random reference groups and compare score variability before declaring an effect, as in Kim et al.. Concept images may share texture or context: the separator can learn those factors. Separate examples used to form the CAV from those used to measure sensitivity, retain controls and report how many comparisons were made.

A result close to one means many derivatives have positive sign, not that the concept explains one hundred percent of the decision. Magnitudes can be nearly zero while signs remain positive; showing the derivative distribution adds context. Comparison with random concepts assesses whether the chosen direction stands out from that reference procedure, not whether all confounders are ruled out. If many concepts or layers are tested, account for multiplicity; the interpretation must also say how concept examples were chosen.

Board, truth and geometry

The linear representation hypothesis proposes that certain factors are encoded as activation directions or subspaces. It does not mean every property is linear or that a direction found in one model is universal. In Othello-GPT, Li et al. investigated board states from moves; Nanda et al. found a clearer linear representation distinguishing own and opponent pieces rather than black and white. Intervening on the representation changed move predictions. The correct basis depends on the turn: comparing probes with different labels without explaining that change can produce opposite conclusions.

InteractiveThe board inside the model
Actual board (dots mark legal moves)
Board decoded by the probe

● black piece, ● white piece. Sequence: d3. The edit adds a probe direction to the internal state. The model's highest-logit move may be illegal.

5
Probe
Intervention
Correctly decoded squares100.0 %
Mean accuracy across 200 games99.9 %
Square with the highest logite3
Edited squared3
Precomputed openings and readouts from MetaOthello Classic. Play up to three moves, change layer and probe, and compare an activation edit at the last square with the original prediction.

The figure uses MetaOthello, an eight-layer transformer trained to predict moves, and its published probes for the piece of the player who just moved, the opponent and an empty square. For comparison, the generator fits black/white/empty linear probes by regularized regression on 1,000 synthetic games and evaluates them on another 200 games generated from the same distribution. In that evaluation, the absolute probe classified 0.811–0.830 of squares correctly depending on layer; the relative probe achieved 0.954–1.000. The prevalence of empty squares affects both figures and the comparison uses different training procedures; it does not itself identify the cause of the difference.

The board lets you play a precomputed opening; it does not query a model in the browser. At each layer the intervention adds six units of a normalized direction separating probe categories at the last square, and both its readout and model logits are recalculated. The edit does not change the real board and can produce an out-of-distribution activation. The largest logit is chosen among all 64 squares without enforcing legality: its change measures that intervention, not a guarantee that the model simulates a complete alternative board. Downloadable generator and original architecture; the original repository and weights are MIT licensed and their revision is pinned in the generator.

On simple sentences, Marks and Tegmark study directions associated with truth, transfer between sets and internal interventions. Gurnee and Tegmark find linear structures related to space and time in particular tasks and models; an observed structure does not guarantee factual truth on a new question. CCS by Burns et al. seeks a direction without truth labels using statement-negation pairs and consistency constraints. Without external orientation, a solution can invert the classes; logical consistency does not generally identify truth and can exploit spurious regularities.

Erasing information and observing behavior

INLP repeatedly fits a linear concept probe and projects onto the null space of its weight vector. Each projection removes that direction from the representation; enough iterations can remove dimensions useful for other concepts. A subsequent probe must be trained and evaluated separately. LEACE computes a minimum-distortion affine transformation under a family of norms that removes linear covariance with the concept in the distribution used. For binary labels this equalizes conditional means; it is a population guarantee under its assumptions, while for finite samples it is checked in training and generalization measured in test.

InteractiveErasing a concept
  • Class 1
  • Class 0
25
Linear probe test accuracy1.000
Nonlinear probe test accuracy1.000
Synthetic 3D points and LEACE transformation calculated on training data; linear and nonlinear readouts evaluated on test data are shown. Colors indicate the known class, not a probe result.

In this example classes also differ in radius. Equalizing means and erasing covariance does not eliminate all information: a nonlinear probe can still exploit variance differences. Thresholded linear-classifier accuracy and the squared-error guarantee are not interchangeable claims for arbitrary distributions. If erasure is inserted into a network and output changes, the intervention evidences behavioral sensitivity to that transformation. It can alter other properties or produce out-of-distribution activations; compare with equal-magnitude controls and check concept recovery in later layers. Elazar et al. use amnesic interventions precisely to move from correlation to a behavioral question.

To distinguish these hypotheses, measure at least three quantities: how much a new probe’s ability to read the concept changes, how much the original output changes and how much a control task that should not depend on the concept is altered. A reduction in the first without change in the second is compatible with the model not using it, nonlinear information being retained or later layers reconstructing it. If both fall, the edit affects behavior, but you must still rule out destruction of correlated information. Applying erasure at several layers can prevent recovery, at the cost of a broader intervention that is harder to interpret.

Laboratory: probes, control and online code

A trained synthetic network approximates a task with two latent variables; we retain its activations and fit logistic probes with NumPy. The control assigns a fixed random class per type. The probe predicts occurrences of seen types; it does not evaluate generalization to new types.

[ ]Data and synthetic networkBrowser
import numpy as np
rng=np.random.default_rng(14);types=120;repeats=8
base=rng.normal(size=(types,8));labels=(base[:,0]+base[:,1]>0).astype(int)
control=rng.integers(0,2,size=types);ids=np.repeat(np.arange(types),repeats)
X=base[ids]+rng.normal(scale=.2,size=(len(ids),8));y=labels[ids]
train=np.tile(np.arange(repeats),types)<6
def sigmoid(z):return 1/(1+np.exp(-np.clip(z,-30,30)))
def fit(A,t,steps=600,rate=.1,reg=.01):
    A=np.c_[A,np.ones(len(A))];w=np.zeros(A.shape[1])
    for _ in range(steps):w-=rate*(A.T@(sigmoid(A@w)-t)/len(A)+reg*w)
    return w
def prob(A,w):return sigmoid(np.c_[A,np.ones(len(A))]@w)
# Una capa no lineal entrenada para la tarea mediante descenso de gradiente.
W=rng.normal(scale=.3,size=(8,12));v=rng.normal(scale=.2,size=12)
for _ in range(500):
    h=np.tanh(X[train]@W);err=sigmoid(h@v)-y[train]
    dv=h.T@err/len(h);dW=X[train].T@((err[:,None]*v)*(1-h*h))/len(h)
    W-=.15*dW;v-=.15*dv
layers=[X,np.tanh(X@W)];print('exactitud red:',round(float(((sigmoid(layers[1][~train]@v)>.5)==y[~train]).mean()),3))
[ ]Layer-wise probes and controlBrowser
for layer,H in enumerate(layers):
    result=[]
    for target in [y,control[ids]]:
        w=fit(H[train],target[train]);result.append(float(((prob(H[~train],w)>.5)==target[~train]).mean()))
    print('capa',layer,'tarea/control/selectividad:',*[round(q,3) for q in [*result,result[0]-result[1]]])
[ ]Blockwise prequential MDLBrowser
def online_code_length(A,t,bounds):
    # bounds son índices crecientes desde 0 hasta n; primer bloque uniforme.
    if bounds[0]!=0 or bounds[-1]!=len(t) or any(b<=a for a,b in zip(bounds,bounds[1:])):
        raise ValueError('límites inválidos')
    bits=float(bounds[1])
    for start,end in zip(bounds[1:-1],bounds[2:]):
        w=fit(A[:start],t[:start]);p=np.clip(prob(A[start:end],w),1e-12,1-1e-12)
        bits-=float(np.sum(t[start:end]*np.log2(p)+(1-t[start:end])*np.log2(1-p)))
    return bits
order=rng.permutation(len(X));H=layers[1][order];target=y[order]
print('bits MDL:',round(online_code_length(H,target,[0,50,150,350,650,len(H)]),2),'uniforme:',len(H))
[ ]INLP on training and test checkBrowser
H=layers[1];P=np.eye(H.shape[1])
for _ in range(5):
    w=fit(H[train]@P,y[train]);direction=P@w[:-1];norm=np.linalg.norm(direction)
    if norm<1e-10:break
    direction/=norm;P=P@(np.eye(len(direction))-np.outer(direction,direction))
before=fit(H[train],y[train]);after=fit(H[train]@P,y[train])
print('sonda antes/después en test:',round(float(((prob(H[~train],before)>.5)==y[~train]).mean()),3),
      round(float(((prob(H[~train]@P,after)>.5)==y[~train]).mean()),3),'rango proyección:',np.linalg.matrix_rank(P))

Five iterations do not guarantee perfect erasure. This procedure removes directions chosen in training and evaluates another probe on test data; it does not intervene on the original network and does not prove the concept is necessary for its decision. The probe bias does not define a direction in activation space and is excluded from the projection.

[ ]TCAV and random conceptsBrowser
# En la capa tanh, el resto de la red es el logit h @ v; su gradiente es v.
# El concepto elegido es signo de la primera coordenada de entrada.
concept=(X[:,0]>0).astype(int);cav=fit(H[train],concept[train])[:-1]
cav/=np.linalg.norm(cav)
score=float((np.full((~train).sum(),v@cav)>0).mean())
random_scores=[]
for _ in range(20):
    random_labels=rng.integers(0,2,size=train.sum())
    random_cav=fit(H[train],random_labels)[:-1]
    random_cav/=np.linalg.norm(random_cav)
    random_scores.append(float((v@random_cav)>0))
print('TCAV concepto:',score,'media 20 controles:',round(float(np.mean(random_scores)),3))

Here the derivative of the logit with respect to the last layer is constant: each TCAV is zero or one. The control distribution is deliberately crude and does not constitute a conclusive statistical test; in a nonlinear downstream network, calculate a different derivative per input and repeat concepts and references independently. The class used for the concept was constructed from synthetic input, not a human semantic property.

Local laboratory: transformer representations

The local laboratory extracts residual representations from GPT-2 small pinned to a revision, fits a probe per layer and evaluates arithmetic sentences with numerical subjects separated between training and test. Run python transformer_probe.py --output resultados.json; it requires PyTorch, Transformers, NumPy and scikit-learn, as well as the downloaded model. True and false sentences are constructed in pairs: labels are defined by a known rule, not human judgment of open text.

The script measures the logit difference for tokens “ true” and “ false” before and after two interventions in the last block: adding a mean-difference direction and applying LEACE computed on training data. It also adds a random orthogonal direction of the same norm as a control. A logit change is an effect of that edit on that output. The numbers and template leave superficial regularities; separating subjects helps control exact memorization but is not semantic generalization or proof that the model represents truth in general. The empirical projection uses a pseudoinverse because there are few examples relative to dimensions, so the guarantee outside training must be measured with another probe rather than assumed.

In a CPU run, probe accuracy on 80 test sentences ranged from 0.45 to 0.90 by layer; the final residual layer, fixed before intervention, reached 0.825. After erasure using empirical covariance, a new probe achieved 0.50 on test and the residual covariance norm on training was 6.7×10−56.7\times10^{-5}, not exactly zero because of the numerical threshold. The decision based on the larger “ true” versus “ false” logit achieved 0.50 before and after erasure. Mean margin change was 0.0083 for the mean direction, −0.0063 for the random direction and 0.0288 for erasure. In this task and output no decision improvement attributable to the intervention appears; a decodable direction did not suffice to demonstrate use.

Exercises

Proof
Prove: Prove the squared-error guarantee for a binary label.
0
Let Z∈{0,1}, X be a representation with finite second moments, and E[X|Z=0]=E[X|Z=1].

Step 1 of 3. What does equality of means imply?

Numeric
One probe achieves 91% on the task and 74% on the control; another achieves 85% and 52%. How many more percentage points of selectivity does the second have?
CodeBinary prequential code
Implement online_code_length(X,y,block_fractions). Increasing fractions end in 1 and define boundaries floor(n*f). The first block uses one uniform bit per label; before each later block fit logistic regression with intercept on ALL previous examples, 200 descent steps, rate 0.1 and no regularization. Use probabilities clipped to [1e-12,1−1e-12] and return bits. Reject empty or invalid boundaries with ValueError.
import numpy as np
def online_code_length(X,y,block_fractions):
  pass
Shift+Enter to run
Quiz
An independent probe predicts a label well from a network activation. Which conclusion is justified?

Summary

Key idea
A probe measures what can be read using a defined procedure. Controls and MDL contextualize ease of reading; interventions and causal controls test whether the representation affects behavior.