Module contents
Lesson 13 of 39Advanced 105 min

Data attribution: influence functions, TracIn and TRAK

Attribute a prediction to training examples using influence functions, Hessian-vector products and their limitations in deep networks. Study TracIn, datamodels, TRAK and data Shapley, evaluate with LDS, and examine applications in label debugging, poisoning detection and LLMs.

After this lesson you can

  • Derive the influence of reweighting an example on test loss.
  • Calculate inverse Hessian-vector products using damped conjugate gradient and LiSSA.
  • Implement TracIn with checkpoints and TRAK with projected per-example gradients.
  • Evaluate attribution methods with the linear datamodeling score against retraining.
  • Use self-influence to identify mislabeled and poisoned examples.

Before you start

Which training example changed the prediction?

A network fails on an image. Was there a wrong label, duplicate example, rare point or manipulated sample in training? Data attribution assigns scores to training examples for a particular question and algorithm. It does not automatically prove that an example historically caused a prediction or resolve authorship or rights by itself.

Debugging and provenance questions require different checks. To debug a label, a score can prioritize human review, followed by correction and reevaluation on independent data. To detect poisoning, measure recall among known manipulated examples and false positives among legitimate data; ranking only the most suspicious cases hides the latter cost. For text provenance, similarity and influence can be complementary signals, but neither establishes literal copying, authorization or ownership alone. Retain identifiers and the selection procedure so someone else can audit the conclusion.

The most direct conceptual reference is retraining without one example, leave-one-out (LOO), using the same remaining data and a defined training protocol. With nn examples it requires nn additional fits. Influence approximates a small weight change around an optimum; TracIn follows gradients along the trajectory; a datamodel tries to predict outputs of retraining on subsets. Their costs, assumptions and targets differ.

Reweighting a point

Let zi=(xi,yi)z_i=(x_i,y_i), loss ℓ(zi,θ)\ell(z_i,\theta) and regularized risk R(θ)=n−1∑iℓ(zi,θ)+r(θ)R(\theta)=n^{-1}\sum_i\ell(z_i,\theta)+r(\theta). Assume an interior minimum θ^\hat\theta with zero gradient and invertible Hessian H=∇θ2R(θ^)H=\nabla_\theta^2R(\hat\theta). The influence function reweights a point by Rϵ(θ)=R(θ)+ϵℓ(z,θ)R_\epsilon(\theta)=R(\theta)+\epsilon\ell(z,\theta).

By the implicit function theorem, differentiating ∇Rϵ(θ^ϵ)=0\nabla R_\epsilon(\hat\theta_\epsilon)=0 at ϵ=0\epsilon=0,

H ⁣dθ^ϵ ⁣dϵ∣0+∇ℓ(z,θ^)=0, ⁣dℓ(ztest,θ^ϵ) ⁣dϵ∣0=−∇ℓ(ztest,θ^)⊤H−1∇ℓ(z,θ^).H\left.\frac{\dd\hat\theta_\epsilon}{\dd\epsilon}\right|_0+\nabla\ell(z,\hat\theta)=0, \qquad \frac{\dd\ell(z_{\rm test},\hat\theta_\epsilon)}{\dd\epsilon}\Big|_0 =-\nabla\ell(z_{\rm test},\hat\theta)\T H^{-1}\nabla\ell(z,\hat\theta).

The sign above corresponds to increasing the weight infinitesimally. A negative value indicates upweighting reduces test loss to first order. Removing an observation changes its weight in the opposite direction and, if the average is renormalized, also changes the other weights. For r(θ)=λ∥θ∥2/2r(\theta)=\lambda\|\theta\|^2/2, the LOO objective gradient at θ^\hat\theta is −[gi+λθ^]/(n−1)-[g_i+\lambda\hat\theta]/(n-1), with gi=∇ℓi(θ^)g_i=\nabla\ell_i(\hat\theta). The first approximation of the parameter change is H−1(gi+λθ^)/(n−1)H^{-1}(g_i+\lambda\hat\theta)/(n-1). This correction matters when comparing with a fit using the mean of the remaining n−1n-1 and the same regularization.

InteractiveApproximate or retrain
  • Removal increases loss
  • Removal reduces loss
  • Test point
Test label
Calculation
Spearman correlation of approximation and LOO1.000
Maximum absolute error0.0006
Move the test case, choose its label and regularization, and compare influence with LOO. All 80 LOO models for each regularization were actually fitted; color and size show loss change when each example is removed.

The figure’s dataset is synthetic, with 80 points and four deliberately flipped labels. The loss is logistic and the penalty also includes the intercept, so HH is positive definite for λ>0\lambda>0. LOO models are refitted with the same average objective and λ\lambda; moving the test input does not require repeating those fits because only the evaluated loss changes. Correlation compares the 80 effects, and maximum error retains the loss scale. Download the generator for the three figures’ data to reproduce the calculations.

In deep networks the assumptions are more delicate: an isolated minimum may not exist, the Hessian can be singular or indefinite, and the stochastic trajectory may reach another point after removing an example. Basu et al. show that architecture and regularization affect accuracy of these approximations. Damping H+γIH+\gamma I changes the approximate problem; if HH has negative eigenvalues, γ\gamma must suffice to make it positive definite before standard conjugate gradient is used. A solver result does not prove LOO is well approximated.

Separate two distinct approximations. First, solving Hs=gHs=g with a small residual ensures ss approximates the given system’s solution, provided the system is well conditioned. Second, using that vector to predict retraining assumes the optimum and loss change approximately linearly. A perfect solver can succeed at the first task and fail at the second. A nearly singular matrix amplifies gradient or numerical errors: compare several damping values and report rank variation, not just a residual.

What stays fixed matters too. Removing a record and retaining the average of the rest differs from reducing its weight without renormalizing. Exclusion can change the number of training steps, minibatches or optimizer parameters; defining LOO requires deciding whether those changes belong to the procedure. To compare two methods, share splits, initializations and budget, and repeat seeds when retraining is random. A difference smaller than variation across seeds needs more evidence before being attributed to one example.

Solving without forming the inverse

A Hessian-vector product can be computed with automatic differentiation without materializing a matrix of size parameters squared. For symmetric positive definite A=H+γIA=H+\gamma I, conjugate gradient constructs conjugate directions and approximates A−1vA^{-1}v using only products AvAv. Residual ∥Ax−v∥\|Ax-v\| checks the damped system, not the accuracy of statistical assumptions.

A LiSSA-like series uses the Neumann identity: if scale ss satisfies ρ(I−A/s)<1\rho(I-A/s)<1,

A−1v=1s∑k=0∞(I−A/s)kv.A^{-1}v=\frac1s\sum_{k=0}^{\infty}(I-A/s)^k v.

Truncation introduces error; stochastic versions estimate products from Hessian samples, introducing variance and additional choices of depth, scale and repetitions. For a positive symmetric matrix s>λmax⁡(A)/2s>\lambda_{\max}(A)/2 suffices, although choosing s≥λmax⁡(A)s\ge\lambda_{\max}(A) avoids negative eigenvalues of the iteration. Large models also use curvature approximations such as EK-FAC: Grosse et al. apply a variant to language models with up to 52 billion parameters; that published result is not a measurement from this laboratory.

Tracing the trajectory

TracIn approximates an example’s contribution to decreasing test loss by summing gradient products at checkpoints:

TracIn⁡(z,zt)≈∑cηc ∇θℓ(z,θc)⊤∇θℓ(zt,θc).\operatorname{TracIn}(z,z_t)\approx\sum_c\eta_c\,\nabla_\theta\ell(z,\theta_c)\T\nabla_\theta\ell(z_t,\theta_c).

A positive sign indicates that a step in the negative direction of the example’s gradient reduces test loss to first order. The actual formula depends on when each example was used and on the optimizer; spaced checkpoints are an approximation, not an exact reconstruction of every minibatch. Pruthi et al. propose this tracing and a scalable checkpoint version.

To see the sign, consider an SGD step θ′=θ−η∇ℓi(θ)\theta'=\theta-\eta\nabla\ell_i(\theta). Taylor gives ℓt(θ′)−ℓt(θ)≈−η∇ℓt⊤∇ℓi\ell_t(\theta')-\ell_t(\theta)\approx-\eta\nabla\ell_t\T\nabla\ell_i. Aligned gradients anticipate lower test loss, while opposing gradients anticipate an increase. The result is local to that step: it does not itself include momentum carryover, regularization, later changes or example order. Self-influence replaces the test gradient with the example’s own and sums nonnegative terms; it therefore measures gradient intensity under that scheme, not proof that a label is wrong.

To scale, gradient vectors can be saved at checkpoints and neighbors searched by inner products, or restricted to one layer as in the image laboratory. Restriction reduces memory and time but changes the question: two examples with similar head gradients may differ in earlier layers. The checkpoint sum also depends on frequency and assigned weights. With Adam, decay or momentum, replacing the actual step with a gradient product without modeling optimizer state adds another approximation that must be disclosed.

InteractiveAccumulating gradient products
49
10
Intentionally flipped labelYes
Cumulative TracIn−0.7413
Cumulative self-influence3.5633
Choose an example and advance through eleven saved logistic-regression checkpoints. The approximate sum for a test case and self-influence are shown; four labels were deliberately flipped.

Self-influence sums squared gradient norms. A wrong label can produce a large gradient, but so can a rare correctly labeled example. In the generator run, two of four flipped labels appear among the eight largest self-influences of the final inverse-Hessian solution; this is neither a detection guarantee nor a TracIn result on other datasets.

Datamodels, TRAK and a retraining test

A datamodel predicts a trained model’s output from indicators of which examples are present. Ilyas et al. study linear models of that relationship. The linear datamodeling score (LDS) compares, typically using Spearman correlation, additive predictions on subsets with outputs obtained by retraining on those subsets. Specify subset size, output, evaluation sample and how seeds are averaged. Rank correlation does not calibrate prediction magnitude.

InteractivePredicting retraining outputs
LDS (Spearman)0.994
Evaluation retraining runs48
Attribution models1
Each point corresponds to one of 48 subsets actually refitted with logistic regression. Change the attribution and number of models in the projected estimator; the vertical axis is observed logit, the horizontal axis the sum of scores of present examples.

In this small run, correlations are properties of the sample and convex algorithm, not results extrapolatable to a deep network. The generator fits subsets of size 40, evaluates a fixed case and compares influence, TracIn and a simplified TRAK estimator with up to four models. Seeds and subsets are fixed in the downloadable file.

TRAK linearizes an output differentiable in parameters, projects per-example gradients to a smaller space and estimates attributions with a Gram matrix. In the multiclass version of Park et al., the output used is the correct-class log-odds; weight qi=1−piq_i=1-p_i depends on its probability. For matrix Φ\Phi of projected gradients, one model form is ϕt⊤(Φ⊤Φ)−1Φ⊤diag⁡(q)\phi_t\T(\Phi\T\Phi)^{-1}\Phi\T\operatorname{diag}(q). The paper averages components of several models trained on subsets and may apply soft thresholding. The figure adds small Gram regularization and omits that threshold: it is an educational variant, not a replication of the published budget or performance. The Johnson-Lindenstrauss projection gives a probabilistic distance guarantee for a finite set and suitable dimension; it does not guarantee a small projection preserves every attribution ranking.

Shapley data valuation changes the game: players are training examples and a coalition’s value is the utility of a model trained on it. Ghorbani and Zou propose this allocation and sampling approximations. Global accuracy, a test-case loss and a logit define different games. Truncating paths can save fits but introduces bias if utility temporarily approaches that of the full set and then changes.

In a permutation, an example’s marginal contribution is utility with it minus utility immediately before it. Averaging over all orders allocates interactions among players; with few orders the estimator can vary greatly. Small coalitions may lack a class, so the training algorithm and empty-coalition utility must be defined before allocation. The cost differs from an influence function: Shapley values coalitions of varied sizes, while LOO compares the full set with one removal. A redundant example can have LOO near zero and nonzero Shapley value because it helps coalitions where its substitute is not yet present.

Careful evaluation separates retrainings used to build the estimator from subsets used to measure LDS. For each subset train the model, evaluate the same logit or loss and compare its output with the sum of scores for present examples. High correlation does not imply the numerical change is correct; assess error and a scatter plot for calibration. Repeat with different subset sizes and test examples, and retain random controls. Using the same subset to build and evaluate the estimator can make the score optimistic.

Random projection reduces gradient dimension and permits a smaller Gram matrix. However, lower dimension can erase relevant differences; an ill-conditioned Gram amplifies noise, and regularization changes attributions. TRAK combines several approximations: margin choice, projection, linear fitting and averaging across models. To assess which affects the result, change one at a time and keep evaluation subsets fixed. Comparison with an exact method on a convex problem is a useful implementation check, but does not guarantee the same behavior in nonconvex networks.

Laboratory: logistic regression from scratch

We generate 80 observations, flip exactly 4 labels and hold out a test case independent of fitting. Regularized logistic regression is convex and the Hessian is positive definite. The code includes the intercept in the penalty so all coordinates share the guarantee.

[ ]Data, fitting and HessianBrowser
import numpy as np
from scipy.special import expit
from scipy.stats import spearmanr
rng=np.random.default_rng(51);n=80;lam=.15
raw=rng.normal(size=(n,2));X=np.c_[raw,np.ones(n)]
y=(raw[:,0]+.8*raw[:,1]+rng.normal(scale=.5,size=n)>0).astype(float)
flips=rng.choice(n,size=4,replace=False);y[flips]=1-y[flips]
def gradients(theta,A,t):return (expit(A@theta)-t)[:,None]*A
def fit(A,t,reg=lam):
    theta=np.zeros(A.shape[1])
    for _ in range(40):
        p=expit(A@theta);g=A.T@(p-t)/len(A)+reg*theta
        H=(A.T*(p*(1-p)))@A/len(A)+reg*np.eye(A.shape[1])
        step=np.linalg.solve(H,g);theta-=step
        if np.linalg.norm(step)<1e-11:break
    return theta
theta=fit(X,y);p=expit(X@theta);Hdata=(X.T*(p*(1-p)))@X/n
H=Hdata+lam*np.eye(3);grads=gradients(theta,X,y)
test=np.array([1.2,.4,1.]);test_label=1.
gtest=(expit(test@theta)-test_label)*test
print('gradiente de ajuste:',np.round(grads.mean(axis=0)+lam*theta,10))
print('etiquetas volteadas:',flips,'autovalores H:',np.round(np.linalg.eigvalsh(H),4))
[ ]Conjugate gradient and Neumann seriesBrowser
def cg(hvp,v,damping=0.,tol=1e-10,maxiter=100):
    x=np.zeros_like(v);r=v-(hvp(x)+damping*x);p=r.copy();rs=r@r
    if np.sqrt(rs)<tol:return x
    for _ in range(maxiter):
        Ap=hvp(p)+damping*p;den=p@Ap
        if den<=0: raise ValueError('El operador no es definido positivo')
        alpha=rs/den;x=x+alpha*p;r=r-alpha*Ap;new=r@r
        if np.sqrt(new)<tol:return x
        p=r+(new/rs)*p;rs=new
    return x
def neumann(hvp,v,scale,depth):
    term=v.copy();ans=np.zeros_like(v)
    for _ in range(depth):
        ans+=term/scale;term=term-hvp(term)/scale
    return ans
sol=cg(lambda v:Hdata@v,gtest,damping=lam)
scale=float(np.linalg.eigvalsh(H).max()*1.05)
approx=neumann(lambda v:H@v,gtest,scale,100)
print('residuo CG:',float(np.linalg.norm(H@sol-gtest)),
      'diferencia Neumann:',float(np.linalg.norm(approx-sol)))

This series uses the deterministic full Hessian. A stochastic LiSSA implementation would replace products with sample estimates and require checking their scale, depth and variability.

[ ]LOO retraining and self-influenceBrowser
def logloss(t,x,y):
    z=float(x@t);return np.logaddexp(0,z)-y*z
baseline_loss=logloss(theta,test,test_label)
estimated=(grads+lam*theta)@sol/(n-1)
observed=[]
for i in range(n):
    keep=np.arange(n)!=i;observed.append(logloss(fit(X[keep],y[keep]),test,test_label)-baseline_loss)
observed=np.array(observed)
self_inf=np.einsum('ij,ij->i',grads,np.linalg.solve(H,grads.T).T)
top=np.argsort(-self_inf)[:8]
print('Spearman aproximación vs LOO:',round(float(spearmanr(estimated,observed).statistic),4))
print('error máximo:',round(float(np.max(np.abs(estimated-observed))),6))
print('volteadas entre ocho primeras:',int(np.isin(top,flips).sum()),'de',len(flips))
[ ]Data Shapley with truncated ordersBrowser
# Juego de 20 puntos: utilidad = menos pérdida del caso de prueba.
small=X[:20];labels=y[:20];full=-logloss(fit(small,labels),test,test_label)
def truncated_shapley(seed,orders=4,tolerance=1e-3):
    random=np.random.default_rng(seed);out=np.zeros(len(small))
    for _ in range(orders):
        order=random.permutation(len(small));subset=[];last=-logloss(np.zeros(3),test,test_label)
        for j in order:
            subset.append(int(j));value=-logloss(fit(small[subset],labels[subset]),test,test_label)
            out[j]+=value-last;last=value
            if abs(value-full)<tolerance:break
    return out/orders
sv=truncated_shapley(4)
print('Shapley truncado, primeras cinco:',np.round(sv[:5],5),
      'suma:',round(float(sv.sum()),5),'diferencia total:',round(float(full+logloss(np.zeros(3),test,test_label)),5))

The four permutations and tolerance make the mechanism visible; they do not suffice to estimate a stable ranking. The sum of truncated contributions can differ from total change. For real use, repeat orders, assess uncertainty and compare with an untruncated run.

Images: TracIn and TRAK with torch.func

Download the local image laboratory and run python image_attribution.py --output resultados.json. It uses digits 0 and 1 from the real scikit-learn dataset, 160 training images and 40 test images; it flips eight training labels. It fits a small ResNet-18 for five epochs and saves five checkpoints. With torch.func it calculates head-only gradients per example, implements TracIn and a projected TRAK-like formula with two models, and compares with 32 retrainings on 50% subsets. It records LDS, test accuracy and how many flipped labels appear among the eight largest self-influences.

This scale is a small reproducible experiment, not the paper’s budget or a measurement of influence over all layers. The 32 subsets use one training seed each, so LDS includes initialization variability; the TRAK study averages several seeds per subset. Head gradient, projection dimension 32, damping and log-odds output must accompany any interpretation. A negative result or imperfect detection is a valid result.

In a run with the specified seed, test accuracy was 0.925; TracIn LDS was −0.248 and the projected variant’s was −0.123. Three of the eight flipped labels appeared among the eight largest TracIn self-influences. Here attributions did not rank subset outputs well: do not hide that result or turn it into a general claim about the methods. The dataset, short training, seed variation and head-only use limit the comparison; the number also does not prove the other flagged examples are mislabeled.

Exercises

Proof
Prove: Derive the influence of reweighting a loss on test loss.
0
Let Rε(θ)=R(θ)+εℓ(z,θ), with an interior minimum and invertible Hessian.

Step 1 of 3. Which condition is differentiated?

Numeric
In linear regression without an intercept, five points have x=(1,1,1,1,1) and y=(1,2,3,4,10). How much does the exact slope change when the last point is removed?
Quiz
A local influence correlates poorly with LOO in a deep network. Which interpretation is strongest?
CodeSolving with Hessian-vector products
Implement conjugate_gradient(hvp,v,damping,tol). hvp computes H@p; solve (H+damping I)x=v for a symmetric positive definite operator until the residual is less than tol. Raise ValueError if observed curvature is not positive.
import numpy as np
def conjugate_gradient(hvp,v,damping,tol):
  pass
Shift+Enter to run

Summary

Key idea
Data attribution is a counterfactual prediction about the learning procedure. Define the output, perturbation and training, and check the approximation against separate retrainings.