Module contents
Lesson 5 of 23Core 100 min

Mathematical formulation of research problems

Move from an informal question to a mathematical object for reasoning and experimentation: identify data distribution, hypothesis class, loss, intervention, and quantity of interest; choose simplifying assumptions; and design minimal toy models such as the Elhage et al. superposition model. Practice limiting cases and invariances as formulation checks.

After this lesson you can

  • Translate an informal question into a formulation with objects, assumptions, a quantity of interest, and a response criterion.
  • Design a minimal toy model reproducing a large-scale phenomenon and justify what it omits.
  • Use limiting cases, invariances, and scaling analysis to rule out incorrect formulations or candidate formulas.
  • Formalize label noise with a transition matrix and derive the loss correction.
  • Choose between a theoretical and an empirical question according to the resulting formulation.

Before you start

A question needs objects

“Why does a detector work in one repository and fail in another?” is a useful question, but still admits many explanations. The code distribution, label definition, class proportions, or evaluation process may change. Formulating a problem turns intuition into objects and decisions: data distribution, model class, loss, intervention, quantity of interest, and response criterion. It need not be perfect initially, but should make choices visible.

Let Ps(X,Y)P_s(X,Y) be the source distribution and Pt(X,Y)P_t(X,Y) the target distribution, h∈Hh\in\mathcal H a predictor, and ℓ\ell a loss. Target risk is Rt(h)=EPt[ℓ(h(X),Y)]R_t(h)=\mathbb E_{P_t}[\ell(h(X),Y)]. One concrete question is whether Rt(h)−Rs(h)R_t(h)-R_s(h) exceeds a meaningful magnitude under a fixed training procedure. A sample of repositories estimates an average for the population it actually comes from; it does not guarantee performance on every new repository. Define whether the split is by file, project, or date, because sharing code between training and test can change the question.

InteractiveFormalization ladder

Formal question: under the distribution of same repository, measure target risk for a linear classifier, using 0-1 error and no adaptation.

Population risk requires a distribution; the benchmark estimates a quantity under a sample and protocol. A theoretical bound requires additional assumptions about distribution shift and class. If you choose a difference, specify the comparator, budget and evaluation unit.

Answer typesource risk
Choose distribution, model, loss, intervention, and quantity. The visible formulation still needs data and assumptions to support an answer.

An empirical protocol might hold out whole projects, tune hyperparameters only on validation, and compare source and target error with intervals across projects. A theoretical question might assume a relationship between PsP_s and PtP_t and seek a target-risk bound. The two answers are not interchangeable: a valid bound under strong assumptions may be uninformative on real data; a finite benchmark does not prove a guarantee for every distribution. Decide which result would change your decision before running the experiment.

Assumptions as part of the result

Simplifying assumptions make the problem manageable but may remove the phenomenon you wanted to study. Independent examples simplify a variance calculation; in code, files from the same project share author, dependencies, and style, so independence across files may be false. Assuming labels have the same meaning across repositories simplifies comparison but hides changes in annotation criteria. Record each assumption, what it lets you calculate, and how you might test it.

Do not confuse an assumption with an observed property. A balanced sample can be constructed artificially without the population being balanced. A linear model can isolate a mechanism while failing to capture interactions required by the real problem. Begin with a small question, derive consequences, and find a case where the assumption matters; then expand the model or test sensitivity. A well-bounded conditional result is more useful than an unconditional general claim.

A good formulation also preserves objects it does not measure. If comparing two detectors, specify the cost of false positives and false negatives, selection procedure, and which target data were permitted. If adaptation uses test-project labels, the setting differs from deployment without labels. A mean difference can hide one method improving large projects and worsening small ones; the aggregation unit is part of the quantity of interest.

The ladder is not a single recipe

To move from question to experiment, first list observable objects: projects, files, snippets, predictions, and labels. Decide which unit is sampled and which receives the loss. If each file counts equally, a large project dominates the average; if each project counts equally, small projects carry more weight per file. Neither aggregation is universally correct. Choose according to the decision to inform, and present another aggregation as a sensitivity analysis when relevant.

The quantity of interest can be a risk difference, worst risk across a family of domains, or expected cost under a decision threshold. A difference needs an explicit comparator: the same detector evaluated on source and target answers a different question from two separately trained detectors. If data, architecture, and threshold all change, a result can describe the whole system but cannot attribute the change to one component. Also specify how to handle unlabeled files and projects that cannot be processed.

A distribution abstracts a sampling process; it is not a dataset that magically represents the future. In a temporal benchmark, available projects may not represent future ones and a date split does not remove every dependency. External evaluation on projects from another organization provides evidence of transport, though it remains finite. Describe selection, date, population, and limitations so another person knows when to apply the conclusion.

The response criterion must express precision and direction. To detect an error difference of two percentage points, design for enough independent units and an analysis that can distinguish it with useful uncertainty. A wide interval including improvement and harm does not confirm equality. Simulation can measure power under assumed distributions; its conclusions depend on their suitability. Keep planning assumptions separate from final evidence.

A small model for a big question

A toy model retains a chosen mechanism and removes details. Elhage and colleagues study whether more sparse features can be represented in fewer dimensions through superposition. Their ReLU-output model takes x∈Rnx\in\mathbb R^n, compresses h=Wxh=Wx with W∈Rm×nW\in\mathbb R^{m\times n}, and reconstructs x^=ReLU⁡(W⊤Wx+b)\hat x=\operatorname{ReLU}(W^\top Wx+b). The loss is importance-weighted squared error. Features are zero with high probability and, when active, sampled between zero and one.

With m=2m=2 and n=5n=5, columns of WW are vectors in a plane. Only two can be nonzero and mutually orthogonal; even so, if features rarely appear together, several nonorthogonal directions can share dimensions with acceptable interference. Bias and ReLU can remove some negative interference. The study reports geometries such as antipodal pairs and pentagons in certain regimes; the optimization problem can have local minima, and the authors tune multiple initializations to reveal clean structures.

InteractiveTrained superposition in two dimensions
12345

Norms per feature: 1: 1.128 · 2: 1.120 · 3: 1.156 · 4: 1.153 · 5: 1.137.

Columns are numbered without aligning their rotation. Each color represents a feature. A large norm suggests representation but does not prove perfect recovery; loss depends on the distribution and is not directly comparable across densities.

Activation probability
Importance
Loss on new sample0.00903
Columns with norm > 0.15 / 5
Select one of six real runs. Density 0.05 means each feature activates with probability 0.05; decreasing importance is 0.7 raised to the feature index.

The figure uses one seed and 3500 steps per configuration, evaluated on 50,000 new synthetic vectors. At density 0.05 and equal importance, all five norms exceed 0.1 and an approximately pentagonal arrangement appears; with decreasing importance one column is nearly zero in this run. This does not prove a universal transition or perfect recovery of every feature. Losses across densities refer to different distributions and cannot be compared directly as the same task.

The model is not an LLM: there is no text, attention, autoregressive training, or guarantee that real features are independent. It shows that compression and sparsity can make a shared representation reasonable. Claims about a large model require additional measurements and controls; the small model generates hypotheses and isolates a mechanism, but does not automatically transfer its result.

What the geometry shows

Each column WiW_i determines how an isolated feature is encoded. Input feature ii influences reconstruction jj through the inner product Wj⊤WiW_j^\top W_i. When i=ji=j, a norm near one favors recovery of the feature; when i≠ji\ne j, the product measures linear interference before adding bias and applying ReLU. Orthogonal vectors have zero such interference. Opposite vectors have negative product and can share a dimension, but their coexistence in one input requires analyzing activation and bias.

With dense inputs, several features often appear together and interference may be costly. With sparse inputs, single-feature cases may dominate and shared geometry may be advantageous. This comparison depends on the loss, importances, and amplitude distribution. Column norm is not a complete quality measure: bias, cross-products, and reconstruction error conditioned on each activation pattern also matter.

The plane’s global rotation is arbitrary, but angles between columns remain invariant under an orthogonal rotation. In the run with density 0.05 and equal importance, consecutive angular gaps are approximately 73, 72, 73, 71, and 72 degrees. This supports describing an approximate pentagon in that run. Repeating with other seeds and quantifying variation is necessary to discuss stability; a pretty image does not replace an experiment.

Lab: train from scratch

The gradient of WW has two contributions because the same matrix encodes and decodes. The cell sums them and compares a directional derivative with a centered difference. It trains six combinations using Adam implemented in NumPy and a fixed seed; synthetic evaluation data use another seed. The displayed loss is the per-example mean of the sum of weighted errors. Change the seed to see different minima; one run does not identify the global optimum.

[ ]Superposition with equal importanceBrowser
import numpy as np

def sample(rng, batch, n, density):
    return (rng.random((batch,n))<density)*rng.random((batch,n))

def loss_grad(W,b,x,importance):
    hidden=x@W.T; z=hidden@W+b; pred=np.maximum(z,0)
    loss=np.mean(np.sum((pred-x)**2*importance,axis=1))
    dz=2*(pred-x)*importance*(z>0)/len(x)
    gradW=hidden.T@dz+(dz@W.T).T@x
    return loss, gradW, dz.sum(axis=0)

def train(density, profile, seed=31, steps=3500):
    rng=np.random.default_rng(seed); W=rng.normal(0,.3,(2,5));b=np.zeros(5)
    importance=np.ones(5) if profile=='equal' else .7**np.arange(5)
    mw=np.zeros_like(W);vw=np.zeros_like(W);mb=np.zeros_like(b);vb=np.zeros_like(b)
    for t in range(1,steps+1):
        x=sample(rng,512,5,density);loss,gw,gb=loss_grad(W,b,x,importance)
        mw=.9*mw+.1*gw;vw=.999*vw+.001*gw*gw;mb=.9*mb+.1*gb;vb=.999*vb+.001*gb*gb
        lr=.01;W-=lr*(mw/(1-.9**t))/(np.sqrt(vw/(1-.999**t))+1e-8);b-=lr*(mb/(1-.9**t))/(np.sqrt(vb/(1-.999**t))+1e-8)
    evalx=sample(np.random.default_rng(seed+1000),50000,5,density)
    loss,_,_=loss_grad(W,b,evalx,importance)
    return W,b,loss

rng=np.random.default_rng(4);W=rng.normal(size=(2,5))*.3;b=rng.normal(size=5)*.1;x=sample(rng,50,5,.5);importance=np.ones(5)
loss,gw,gb=loss_grad(W,b,x,importance);d=rng.normal(size=W.shape);eps=1e-6
fd=(loss_grad(W+eps*d,b,x,importance)[0]-loss_grad(W-eps*d,b,x,importance)[0])/(2*eps)
assert abs(fd-(gw*d).sum()) < 1e-7
print('Gradiente direccional:',fd,(gw*d).sum())
for density in (.05,.2):
    W,b,loss=train(density,'equal')
    print(density,'equal','pérdida',round(loss,6),'normas',np.round(np.linalg.norm(W,axis=0),3))
[ ]Equal importance and dense inputBrowser
W,b,loss=train(1.,'equal')
print(1.,'equal','pérdida',round(loss,6),'normas',np.round(np.linalg.norm(W,axis=0),3))

The following cells reuse the functions defined in the first cell within this session.

[ ]Superposition with decreasing importanceBrowser
for density in (.05,.2):
    W,b,loss=train(density,'weighted')
    print(density,'weighted','pérdida',round(loss,6),'normas',np.round(np.linalg.norm(W,axis=0),3))
[ ]Decreasing importance and dense inputBrowser
W,b,loss=train(1.,'weighted')
print(1.,'weighted','pérdida',round(loss,6),'normas',np.round(np.linalg.norm(W,axis=0),3))

Check the tied-weight gradient

Writing the computation in two stages helps avoid forgetting a dependency: h=Wxh=Wx and z=W⊤h+bz=W^\top h+b. If DD denotes the derivative of loss with respect to zz for a batch, one contribution to the gradient of WW comes from the use of WW in the decoder, and another from the change in hh when modifying the encoder. The code computes both with matrix products. Treating the second copy of WW as constant would produce a different update even with the correct array shape.

The derivative of ReLU is taken as zero at the origin. A centered finite difference can cross that nondifferentiable point, so a discrepancy at exactly zero activation does not necessarily indicate the same error as a discrepancy away from zero. The check uses random data and a fixed direction; record values and tolerance, and repeat with other shapes or directions if changing the implementation. Checking the gradient does not prove the optimizer finds the global minimum.

A good geometry comparison needs training and evaluation conditions. Here each combination has the same initialization seed and step count, but batches and difficulty depend on density. The evaluation sample is independent of training batches. The decreasing-importance model also changes the objective, so losses should not be compared without accounting for those weights. For a robust claim, run several seeds and retain both the best result and the distribution of solutions.

Limiting cases and invariances

Limiting-case analysis checks whether a formula agrees with situations understood without it. For the mean of nn independent observations with variance σ2\sigma^2, variance is σ2/n\sigma^2/n. If n=1n=1 it must be σ2\sigma^2; without noise it must be zero; if data scale is multiplied by cc, variance must be multiplied by c2c^2. A candidate failing one of these checks is discarded. One that passes still needs proof: many errors survive a finite set of checks.

InteractiveCheck limiting cases
σ² / n

Still compatible with the applied tests.

σ / n

Still compatible with the applied tests.

σ² · n

Still compatible with the applied tests.

σ² / (n + 1)

Still compatible with the applied tests.

Passing these cases is necessary for this expression, but insufficient to prove it. Independence, equal variances and the quantity’s definition are essential.

Candidates still compatible4 / 4
Apply necessary properties to four candidates for variance of the mean under independence and equal variance.

An invariance is a transformation that leaves a specific property unchanged. If you rotate all columns of WW by an orthogonal matrix QQ, (QW)⊤(QW)=W⊤W(QW)^\top(QW)=W^\top W: the model and loss do not change. Thus the drawing’s absolute orientation has no meaning in this model. Scaling all features or changing activation frequency, by contrast, changes the problem unless other quantities are transformed consistently. Distinguish invariance from equivariance: in the latter, output changes predictably with input.

Dimensions and extreme cases

A formula for squared error must have units of the quantity squared. If σ\sigma is a standard deviation, σ/n\sigma/n has units of the variable, while σ2/n\sigma^2/n has variance units. That observation rules out a candidate before knowing its constants. For nn independent variables with common variance, their sum has variance nσ2n\sigma^2 and division by n2n^2 gives σ2/n\sigma^2/n. If they are correlated, covariance terms appear and can prevent reduction at that rate.

A limit also helps check an algorithm. In ridge regression, with fixed design and positive penalty on all coefficients, λ→∞\lambda\to\infty sends coefficients to zero; an unpenalized intercept need not. In a noise model, T=IT=I must return the original loss. In a transition matrix, each row must sum to one and probabilities must be nonnegative. Testing these properties with small examples detects transpositions or inconsistent conventions before training a large network.

Noisy labels as a probabilistic model

To formalize label noise, let YY be the clean class and Y~\tilde Y the observed class. Define Tij=P(Y~=j∣Y=i)T_{ij}=P(\tilde Y=j\mid Y=i) with rows summing to one. Under noise conditioned only on class, P(Y~=j∣X=x)=∑iTijP(Y=i∣X=x)P(\tilde Y=j\mid X=x)=\sum_i T_{ij}P(Y=i\mid X=x). If p(x)p(x) is a row vector of clean probabilities, the predicted observed distribution is q(x)=p(x)Tq(x)=p(x)T. Patrini and colleagues’ forward correction applies cross-entropy loss to qq and the observed label.

The matrix must match the corruption mechanism. If it changes with xx, a single TT does not describe the process. If it is not invertible, different clean distributions can produce the same observed distribution; even with a known matrix, unique identification is not guaranteed in general. A poorly estimated matrix, a model unable to represent the clean distribution, or finite fitting can leave bias. Correction does not guarantee exact classifier recovery on every finite dataset.

In binary classification with symmetric noise rate η\eta, p~(x)=η+(1−2η)p(x)\tilde p(x)=\eta+(1-2\eta)p(x), where p=P(Y=1∣X=x)p=P(Y=1\mid X=x). If η<1/2\eta<1/2, the sign of p~−1/2\tilde p-1/2 matches that of p−1/2p-1/2 and the Bayes classifier is the same except for ties. This does not say clean and noisy probabilities coincide. With asymmetric noise, the threshold may shift and a classifier trained on noisy labels may differ.

Lab: forward correction

We generate three classes with known softmax probabilities, apply an asymmetric matrix, and train logistic regression by gradient descent on noisy labels. The true matrix and an incorrect one are compared with the identity. In this run, accuracy against clean test labels is 0.5910 without correction, 0.7608 with true TT, and 0.6470 with incorrect TT; agreement with the known Bayes rule is 0.6472, 0.9829, and 0.7188. One seed and a synthetic problem do not prove universal superiority; clean test labels are used only for evaluation.

[ ]Label noise and correctionBrowser
import numpy as np

def softmax(z):
    a=np.exp(z-z.max(axis=1,keepdims=True));return a/a.sum(axis=1,keepdims=True)

def generate(n,rng,T):
    X=rng.normal(size=(n,2));X=np.column_stack((X,np.ones(n)))
    true=np.array([[2.,-1.3,-.7],[-.7,1.5,-.8],[.3,-.1,-.2]])
    p=softmax(X@true); y=np.array([rng.choice(3,p=row) for row in p]);noisy=np.array([rng.choice(3,p=T[k]) for k in y])
    return X,p,y,noisy

def train(X,y,T,steps=1000,lr=.12):
    W=np.zeros((X.shape[1],3));N=len(y)
    for _ in range(steps):
        p=softmax(X@W); observed=p@T; probability=np.maximum(observed[np.arange(N),y],1e-12)
        dprob=-T[:,y].T/probability[:,None]
        dz=p*(dprob-np.sum(p*dprob,axis=1,keepdims=True))
        W-=lr*(X.T@dz)/N
    return W

T=np.array([[.55,.40,.05],[.05,.90,.05],[.05,.10,.85]])
wrong=np.array([[.85,.10,.05],[.05,.90,.05],[.05,.10,.85]])
rng=np.random.default_rng(31);X,p,y,yn=generate(3000,rng,T);Xt,pt,yt,_=generate(8000,np.random.default_rng(32),T)
for name,transition in [('sin corrección',np.eye(3)),('T verdadera',T),('T errónea',wrong)]:
 W=train(X,yn,transition);pred=softmax(Xt@W).argmax(axis=1)
 print(name,'exactitud limpia',round(float(np.mean(pred==yt)),4),'acuerdo con Bayes',round(float(np.mean(pred==pt.argmax(axis=1))),4))
print('Bayes vs etiquetas limpias',round(float(np.mean(pt.argmax(axis=1)==yt)),4))

The true matrix is chosen to illustrate asymmetric corruption and is known because the simulation constructs it. A real application would need to estimate it from additional information and assess estimation uncertainty. Forward correction transforms probabilities before computing loss: it does not replace observed labels with supposedly clean ones. Check that T=IT=I reproduces ordinary cross-entropy and each row is a valid distribution.

Identification, measurement, and evaluation

Forward correction optimizes observed-label probability under model pTpT. If the family contains the clean distribution and TT is known and invertible, the population optimum of cross-entropy identifies the clean distribution under the model conditions. This is a claim about a population optimum, not every gradient run. A small sample, regularization, nonconvexity, or misspecification can prevent reaching it.

The example can calculate two measures because it knows the generating distribution. Accuracy against a random clean label includes irreducible uncertainty; agreement with the distribution’s most probable class compares decisions with Bayes. Two classifiers can have the same sample accuracy and differ in predictions, as happens here by rounding, without being identical. In real data the Bayes class is usually unknown and cannot be directly evaluated this way.

Transition TT uses rows for clean classes and columns for observed classes. Some references use the transposed convention; write dimensions before multiplying. In the cell, pp has shape n×kn\times k and TT shape k×kk\times k, so pTpT has an observed probability per row and class. If you select a label assigned zero probability by the model, its logarithm is nonfinite; the exercise implementation rejects that case. Numerical training uses an explicit minimum to avoid overflow, which also changes loss at extreme values.

Design the next experiment

If correction works in the synthetic model, next try to break it: change sample count, corruption rate, conditioning of TT, and classifier capacity. A nearly singular matrix can make small changes in observed probabilities correspond to large changes in the clean distribution. Measure calibration and stability across seeds as well as accuracy. The comparison should use the same split and tuning budget for each method.

In an applied problem, record how each matrix entry was obtained and whether verified labels were used to estimate it. If that same set is used to choose the matrix and report the final result, evaluation may be optimistic. An independent holdout helps measure performance of the entire procedure, including noise estimation. If label quality varies by group or context, a global matrix may hide systematic errors; compare groups with sufficient information and state uncertainty.

Theory and experiment are iterative. Identification theory explains what would be possible with unlimited data and an exact matrix; simulation shows how an implementation behaves under controlled conditions; a benchmark provides evidence on a specific population. If they differ, first check which assumption or unit changed. That comparison can suggest a new question, such as whether corruption depends on content or the logistic model is misspecified.

Exercises

ProofThe boundary with symmetric noise
Prove: Show that the binary Bayes classifier is preserved under symmetric noise independent of X with rate eta < 1/2, except for ties.
0
Write p = P(Y=1|X=x) and calculate the probability of observing label 1.

Step 1 of 2. What is the observed probability?

Numeric
With independent symmetric noise of rate 0.2 and clean accuracy 0.9, what accuracy do you expect to measure against noisy labels?
Code
Implement forward_corrected_loss(logits, noisy_labels, T): logits is an n by k NumPy matrix, noisy_labels contains observed indices, and T is k by k with stochastic rows. Calculate the mean of -log((softmax(logits) @ T)[row, label]), with stable softmax. Reject zero observed probabilities with ValueError.
import numpy as np

def forward_corrected_loss(logits, noisy_labels, T):
  pass
Shift+Enter to run
Quiz
To study a mechanism of in-context learning, which toy model is most informative?
Quiz
In ridge regression, with fixed data and design matrix and penalty λ tending to infinity, what happens to penalized coefficients?

Summary

Formalization requires specifying population, model, loss, intervention, and quantity; assumptions delimit the answer. A small model can isolate superposition, but its result does not automatically transfer to a large model. Limiting cases and invariances detect inconsistencies, and a transition matrix makes explicit what must be known to correct label noise.