Which training rows taught this? Influence functions, TracIn and TRAK
Trace a prediction back to training rows three ways: a derivative at the optimum (influence functions), gradient alignment during training (TracIn), and projected gradients over many models (TRAK).
What runs in CodeSplash
- EXP008Training-example influence functions Partly runs in CodeSplash
- EXP009TracIn checkpoint gradient attribution Runs in CodeSplash (Experimental)
- EXP010TRAK: tracing with the randomly projected after kernel Explained here
- TracIn training-row influence for a saved network Experimental
- Linear / logistic regression Verified in Python and R
You will be able to
- Write the influence-function formula and say when its assumptions hold
- Write TracIn's checkpoint sum and explain how gradient size can dominate it
- Describe TRAK's projected-gradient kernel and why it averages over models
- Validate training-data attribution with retraining experiments
A different kind of explanation
ReadFeature attributions ask which inputs drove a prediction. Training-data attribution asks which training rows did: which examples pushed the model toward this answer, which pushed against it. It helps find mislabeled rows, duplicates and data the model leans on.
The exact answer is expensive: retrain without each row and compare. The three methods here approximate that, each with a different estimand. None of them is a probability that a row "caused" a prediction.
Influence functions
ReadAt a fitted optimum , upweight training row by a tiny . Linear response gives the change in the parameters, and in the loss on a test point :
On a small ridge regression the reference's program compares this formula with a finite-difference refit: 0.01116 against 0.01116, a near-perfect match. That is the convex case it was built for.
Reference · EXP008 · Partly runs in CodeSplashTraining-example influence functionsApproximate how a fitted model or a selected test loss changes when the weight of a training observation changes infinitesimally.When influence breaks
ReadThe derivative assumes a smooth objective, a converged, isolated optimum and an invertible Hessian . Deep networks break all three: training stops before convergence, the loss surface is nonconvex, and is huge and near-singular. Large models use Hessian-vector products and iterative solvers, often with damping, which changes the approximation.
Two more cautions: removing a whole row is a finite change, not an infinitesimal one, and gradient similarity alone is not the influence function (the matters). Validate on small convex models where exact refits are cheap.
TracIn: follow training
ReadTracInTracInInfluence of a training row on a prediction: learning rate × the dot product of their loss gradients, summed over saved checkpoints. skips the optimum entirely. Gradient descent lowers a test point's loss whenever a training step's gradient aligns with the test gradient. Summing that alignment over saved checkpoints , weighted by their learning rates, gives
Positive scores are proponents (rows that helped), negative are opponents. With two checkpoints, the reference's toy score is 0.05.
Reference · EXP009 · Runs in CodeSplashTracIn checkpoint gradient attributionApproximate the influence of a training example through gradient alignment with a target example across selected training checkpoints.Predict: large gradients win
PredictPredict first
TracIn's top proponents for many different test rows are the same handful of training rows. What are they likely to be?
Reveal
Possibly the large-gradient rows. A dot product grows with gradient size, so outliers, mislabeled rows and hard examples can top every ranking. CodeSplash reports the correlation between |TracIn| and each row's self-influenceSelf-influence (TracIn)A training row's TracIn score with itself; large for rows the network found hard to fit, often unusual or mislabeled ones.; when it is near 1, gradient size, not relevance, drives the ranking.
TracIn in CodeSplash
ReadTracIn training-row influence for a saved network uses the checkpoints a run kept (the last and the best epoch).
TracIn traced 2 predictions to 93 training rows over 2 checkpoints; training row 101 helped the most (score 0.464, for explained row 2), and training row 117 was the hardest to fit (self-influence 6.28).
- Largest proponent score (training row 101)
- 0.4645
- Largest self-influence (training row 117)
- 6.281
Assumptions
- Checkpoints of this training — 2 distinct checkpoints of the training call that made the model.
- Rankings reflect more than gradient size — Mean Spearman ρ between |TracIn| and self-influence 0.75; the rankings mostly follow how large each training row's gradient is.
- Features vary independently — Wind and Temp: |ρ| = 0.57; TracIn changes no feature, so related features don't distort it.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
Training rows that helped and hurt each prediction most (TracIn)
| Explained row | Effect | Rank | Training row | Its target | TracIn score |
|---|---|---|---|---|---|
| 31 | Proponent | 1 | 126 | 73 | 0.3729 |
| 31 | Proponent | 2 | 143 | 16 | 0.2572 |
| 31 | Proponent | 3 | 95 | 16 | 0.2372 |
| 31 | Proponent | 4 | 97 | 35 | 0.2249 |
| 31 | Opponent | 1 | 117 | 168 | −0.6174 |
| 31 | Opponent | 2 | 48 | 37 | −0.3655 |
| 31 | Opponent | 3 | 62 | 135 | −0.3642 |
| 31 | Opponent | 4 | 30 | 115 | −0.2667 |
| 88 | Proponent | 1 | 101 | 110 | 0.4645 |
| 88 | Proponent | 2 | 124 | 96 | 0.4042 |
| 88 | Proponent | 3 | 100 | 89 | 0.3140 |
| 88 | Proponent | 4 | 123 | 85 | 0.3054 |
| 88 | Opponent | 1 | 87 | 20 | −0.2866 |
| 88 | Opponent | 2 | 95 | 16 | −0.2532 |
| 88 | Opponent | 3 | 94 | 9 | −0.2274 |
| 88 | Opponent | 4 | 97 | 35 | −0.1791 |
Training rows the network found hardest to fit (TracIn self-influence)
| Rank | Training row | Its target | Self-influence |
|---|---|---|---|
| 1 | 117 | 168 | 6.281 |
| 2 | 48 | 37 | 4.767 |
| 3 | 126 | 73 | 3.172 |
| 4 | 62 | 135 | 2.244 |
- TracIn adds up, over the 2 saved checkpoints of this training (best (epoch 6), last (epoch 21)), the learning rate times the dot product of each training row's loss gradient with the explained row's. Positive scores mark rows whose training steps lowered this row's loss (proponents); negative ones raised it (opponents). High self-influence often marks unusual or mislabeled rows.
The exact R script · R R version 4.5.1 (2025-06-13)
# TracIn training-row influence for a saved network
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.tracin 1.1.0 · spec 616f70965788752b
# Explains the saved model learn.torch_mlp/regression_airquality_early_stopping with its own learner code (learn.torch_mlp 1.4.2, driver mode "explain").
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec ca540cbc120a5fbd
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network itself is built by codesplashr's cs_deep_* twins.
# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
hidden_layers = c(16, 8),
activation = "relu",
epochs = 400,
learning_rate = 0.01,
batch_size = NULL,
weight_decay = 0.001,
early_stopping = 15,
validation_fraction = 0.2,
dropout = 0,
mc_passes = 0,
variational_weights = FALSE,
prior_scale = 1,
kl_weight = 1,
robust_training = "none",
dro_step = 0.01,
adv_epsilon = 0.1,
adv_steps = 5,
trades_beta = 6,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("model-r/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
`solar radiation` = "numeric",
Wind = "numeric",
Temp = "numeric"
),
levels = list(
),
impute = "median",
scale = "standard",
indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("explain-out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "explain-out-r")
# A dense network on torch for R (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — Python's torch starts from the same weights and takes the same steps.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
ACTIVATION <- PARAMS$activation
DROPOUT <- as.numeric(PARAMS$dropout)
PASSES <- as.integer(PARAMS$mc_passes)
VARIATIONAL <- isTRUE(PARAMS$variational_weights)
ROBUST <- PARAMS$robust_training
# Any of the options on: train with cs_deep_fit_mlp_ext (otherwise the plain network, unchanged).
EXTENDED <- DROPOUT > 0 || PASSES > 0 || VARIATIONAL || ROBUST != "none"
fit_model <- function(X, y, w) {
if (cs_deep_dp_enabled() && !is.null(w) && diff(range(as.numeric(w))) > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with row or class weights", value = "on")
}
if (TASK == "regression") {
# Standardize the target (training mean and population SD); predictions are mapped back.
mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
target <- (as.numeric(y) - mu) / sd; o <- 1L
} else if (TASK == "binary") {
mu <- 0; sd <- 1
target <- as.numeric(y); o <- 1L
} else {
mu <- 0; sd <- 1
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
if (!EXTENDED) {
fit <- cs_deep_fit_mlp(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED
)
return(list(params = fit$params, mu = mu, sd = sd, history = fit$history, best_epoch = fit$best_epoch))
}
fit <- cs_deep_fit_mlp_ext(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED,
dropout = DROPOUT,
variational = VARIATIONAL,
prior_scale = PARAMS$prior_scale,
kl_weight = PARAMS$kl_weight,
robust = ROBUST,
groups = if (ROBUST != "group_dro") NULL else SUBGROUPS[FIT_ROWS + 1L],
dro_step = PARAMS$dro_step,
adv_epsilon = PARAMS$adv_epsilon,
adv_steps = as.integer(PARAMS$adv_steps),
trades_beta = PARAMS$trades_beta,
mc_passes = PASSES
)
fit$mu <- mu; fit$sd <- sd; fit$extended <- TRUE
fit
}
predict_model <- function(model, X) {
p <- if (!isTRUE(model$extended)) cs_deep_mlp_predict(model$params, unname(X), ACTIVATION, TASK) else cs_deep_mlp_predict_ext(model, unname(X), TASK)$mean
if (TASK == "regression") model$mu + model$sd * p else p
}
# Predictive SD (numbers, with prediction passes): sqrt(training residual variance + spread across passes).
predict_sd <- function(model, X) model$sd * sqrt(model$noise_var + cs_deep_mlp_predict_ext(model, unname(X), TASK)$spread)
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights + the target scaling
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"tracin\",\"method\":\"explain.tracin\",\"model\":\"learn.torch_mlp/regression_airquality_early_stopping\",\"title\":\"TracIn training-row influence for a saved network\",\"version\":\"1.1.0\"},\"maxRows\":2,\"methods\":[\"tracin\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\",\"tracinRows\":2,\"tracinTop\":4}", simplifyVector = FALSE)
if (is.null(REQUEST)) REQUEST <- list()
model_dir <- if (is.null(REQUEST$modelDir)) out else REQUEST$modelDir
prep <- cs_ml_design_from_json(paste(readLines(file.path(model_dir, "design.json"), warn = FALSE), collapse = "\n"))
# S3 predict methods (ranger, e1071, …) need their package's namespace loaded.
for (pkg in c("torch", "codesplashr")) {
suppressWarnings(suppressPackageStartupMessages(requireNamespace(pkg, quietly = TRUE)))
}
model <- load_model(model_dir)
explainer <- cs_ml_explainer(predict_model, model, prep, TASK, CLASSES, POSITIVE, METRIC, cls = REQUEST$class)
rows <- cs_ml_explain_rows(plan, if (is.null(REQUEST$rows)) "auto" else REQUEST$rows,
as.integer(if (is.null(REQUEST$maxRows)) 1000 else REQUEST$maxRows), SEED)
cs_publish(cs_ml_explain(
explainer, df, rows, plan$train, y, y_index, REQUEST, SEED, model_dir, out,
warnings = warnings,
title = "Deep neural network (torch MLP)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet")
))
TracIn traced 2 predictions to 93 training rows over 2 checkpoints; training row 101 helped the most (score 0.464, for explained row 2), and training row 117 was the hardest to fit (self-influence 6.28).
- Largest proponent score (training row 101)
- 0.4645
- Largest self-influence (training row 117)
- 6.281
Assumptions
- Checkpoints of this training — 2 distinct checkpoints of the training call that made the model.
- Rankings reflect more than gradient size — Mean Spearman ρ between |TracIn| and self-influence 0.75; the rankings mostly follow how large each training row's gradient is.
- Features vary independently — Wind and Temp: |ρ| = 0.57; TracIn changes no feature, so related features don't distort it.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
Training rows that helped and hurt each prediction most (TracIn)
| Explained row | Effect | Rank | Training row | Its target | TracIn score |
|---|---|---|---|---|---|
| 31 | Proponent | 1 | 126 | 73 | 0.3729 |
| 31 | Proponent | 2 | 143 | 16 | 0.2572 |
| 31 | Proponent | 3 | 95 | 16 | 0.2372 |
| 31 | Proponent | 4 | 97 | 35 | 0.2249 |
| 31 | Opponent | 1 | 117 | 168 | −0.6174 |
| 31 | Opponent | 2 | 48 | 37 | −0.3655 |
| 31 | Opponent | 3 | 62 | 135 | −0.3642 |
| 31 | Opponent | 4 | 30 | 115 | −0.2667 |
| 88 | Proponent | 1 | 101 | 110 | 0.4645 |
| 88 | Proponent | 2 | 124 | 96 | 0.4042 |
| 88 | Proponent | 3 | 100 | 89 | 0.3140 |
| 88 | Proponent | 4 | 123 | 85 | 0.3054 |
| 88 | Opponent | 1 | 87 | 20 | −0.2866 |
| 88 | Opponent | 2 | 95 | 16 | −0.2532 |
| 88 | Opponent | 3 | 94 | 9 | −0.2274 |
| 88 | Opponent | 4 | 97 | 35 | −0.1791 |
Training rows the network found hardest to fit (TracIn self-influence)
| Rank | Training row | Its target | Self-influence |
|---|---|---|---|
| 1 | 117 | 168 | 6.281 |
| 2 | 48 | 37 | 4.767 |
| 3 | 126 | 73 | 3.172 |
| 4 | 62 | 135 | 2.244 |
- TracIn adds up, over the 2 saved checkpoints of this training (best (epoch 6), last (epoch 21)), the learning rate times the dot product of each training row's loss gradient with the explained row's. Positive scores mark rows whose training steps lowered this row's loss (proponents); negative ones raised it (opponents). High self-influence often marks unusual or mislabeled rows.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TracIn training-row influence for a saved network
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.tracin 1.1.0 · spec 616f70965788752b
# Explains the saved model learn.torch_mlp/regression_airquality_early_stopping with its own learner code (learn.torch_mlp 1.4.2, driver mode "explain").
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec ca540cbc120a5fbd
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import core as deep # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.deep import mlp_ext as mlpx # dropout, variational weights, Group DRO, PGD/TRADES (twin: cs_deep_*_ext)
from codesplash.deep import dp as deep_dp # differentially private training, DP-SGD (twin: cs_deep_dp_*)
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"hidden_layers": [16, 8],
"activation": "relu",
"epochs": 400,
"learning_rate": 0.01,
"batch_size": None,
"weight_decay": 0.001,
"early_stopping": 15,
"validation_fraction": 0.2,
"dropout": 0,
"mc_passes": 0,
"variational_weights": False,
"prior_scale": 1,
"kl_weight": 1,
"robust_training": "none",
"dro_step": 0.01,
"adv_epsilon": 0.1,
"adv_steps": 5,
"trades_beta": 6,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airquality.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("model-python/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"solar radiation": "numeric",
"Wind": "numeric",
"Temp": "numeric",
},
levels={
},
impute="median",
scale="standard",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("explain-out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="explain-out-python",
)
# A dense network on PyTorch (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — R's torch starts from the same weights and takes the same steps.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
ACTIVATION = PARAMS["activation"]
DROPOUT = float(PARAMS["dropout"])
PASSES = int(PARAMS["mc_passes"])
VARIATIONAL = bool(PARAMS["variational_weights"])
ROBUST = PARAMS["robust_training"]
# Any of the options on: train with codesplash.deep.mlp_ext (otherwise the plain network, unchanged).
EXTENDED = DROPOUT > 0 or PASSES > 0 or VARIATIONAL or ROBUST != "none"
def fit_model(X, y, w):
if deep_dp.enabled() and w is not None and float(np.ptp(np.asarray(w, dtype=np.float64))) > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with row or class weights", value="on")
if TASK == "regression":
# Standardize the target (training mean and population SD); predictions are mapped back.
mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
elif TASK == "binary":
mu, sd = 0.0, 1.0
target, o = np.asarray(y, dtype=np.float64), 1
else:
mu, sd = 0.0, 1.0
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
common = dict(
activation=ACTIVATION,
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=PARAMS["weight_decay"],
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=PARAMS["validation_fraction"],
patience=max(1, int(PARAMS["early_stopping"])),
seed=SEED,
)
if not EXTENDED:
fit = deep.fit_mlp(X, target, w, TASK, HIDDEN, o, **common)
return {"params": fit["params"], "mu": mu, "sd": sd, "history": fit["history"], "best_epoch": fit["best_epoch"]}
fit = mlpx.fit_mlp_ext(
X, target, w, TASK, HIDDEN, o, **common,
dropout=DROPOUT,
variational=VARIATIONAL,
prior_scale=PARAMS["prior_scale"],
kl_weight=PARAMS["kl_weight"],
robust=ROBUST,
groups=None if ROBUST != "group_dro" else SUBGROUPS[FIT_ROWS],
dro_step=PARAMS["dro_step"],
adv_epsilon=PARAMS["adv_epsilon"],
adv_steps=int(PARAMS["adv_steps"]),
trades_beta=PARAMS["trades_beta"],
mc_passes=PASSES,
)
fit.update({"mu": mu, "sd": sd, "extended": True})
return fit
def predict_model(model, X):
if not model.get("extended"):
p = deep.mlp_predict(model["params"], X, ACTIVATION, TASK)
else:
p, _ = mlpx.mlp_predict_ext(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def predict_sd(model, X):
"""Predictive SD (numbers, with prediction passes): √(training residual variance + spread across passes)."""
_, spread = mlpx.mlp_predict_ext(model, X, TASK)
return model["sd"] * np.sqrt(model["noise_var"] + spread)
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path) # plain numpy weights + the target scaling
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Explain the model
import json
from codesplash.ml import explain as csx
REQUEST = json.loads("{\"analyze\":{\"kind\":\"tracin\",\"method\":\"explain.tracin\",\"model\":\"learn.torch_mlp/regression_airquality_early_stopping\",\"title\":\"TracIn training-row influence for a saved network\",\"version\":\"1.1.0\"},\"maxRows\":2,\"methods\":[\"tracin\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\",\"tracinRows\":2,\"tracinTop\":4}") or {}
model_dir = REQUEST.get("modelDir") or out
with open(os.path.join(model_dir, "design.json"), encoding="utf-8") as fh:
prep = csml.FittedDesign.from_json(fh.read())
model = load_model(model_dir)
explainer = csx.Explainer(predict_model, model, prep, TASK, CLASSES, POSITIVE, METRIC, cls=REQUEST.get("class"))
rows = csx.explain_rows(plan, REQUEST.get("rows") or "auto", int(REQUEST.get("maxRows") or 1000), SEED)
cs.publish(
csx.explain(
explainer,
df,
rows,
plan.train,
y,
y_index,
REQUEST,
SEED,
model_dir,
out,
warnings=warnings,
title="Deep neural network (torch MLP)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
)
)
For a small network on air quality with 2 checkpoints, the gradient-norm checkGradient-size dominance (TracIn)Mean Spearman ρ between |TracIn| and self-influence; near 1, the ranking mostly reflects how large each row's gradient is. is 0.75. For a CNN on digits it is 1.000: there the ranking mostly restates which rows have large gradients. With one or two checkpoints, TracIn is a coarse approximation of the training path.
TRAK: projected gradients, many models
ReadTRAKTRAKTraining-data attribution from randomly projected gradients and a linearized model, averaged over several trained models. targets large models. It projects each example's gradient to a low dimension with a random matrix , treats the model as linear in those features, and solves a regularized kernel problem:
then averages over several independently trained models, because one model's linearization is noisy. The reference's program computes only the kernel step for three training rows, with scores up to 0.194. Validate TRAK by retraining on subsets and checking predicted against actual changes, not by how plausible the top examples look.
Reference · EXP010 · Explained hereTRAK: tracing with the randomly projected after kernelEstimate training-data attribution with projected gradient features, a linearized kernel calculation, task-specific weights, and aggregation over fitted models.Where they stand in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Influence functions (EXP008) | Partly runs in CodeSplash: the Explain tab's "Training rows behind it" for Linear / logistic regression runs (exact leave-one-out for least squares, a one-step approximation for logistic); no Analyze method, no deep-network version |
| TracIn (EXP009) | Runs in CodeSplash: TracIn training-row influence for a saved network and the Explain tab, for dense networks, CNNs and FT-Transformers, with the gradient-norm check; Python ≡ R |
| TRAK (EXP010) | Explained here: the reference's kernel step is a verified component check |
Check your understanding
CheckpointCheck yourself
Why are influence functions most trustworthy for convex models like ridge regression?
Show the answer
Answer: b
In deep networks training stops early, the surface is nonconvex and the Hessian is near-singular, so the linear response is a rough guide at best.
Check yourself
An influence score predicts that deleting a training row barely changes a prediction, but an actual refit without the row changes it a lot. Why could that happen?
Show the answer
Answer: b
Compare the approximation with actual refits on a sample of rows before trusting it on the rest.
Check yourself
A training row has a large negative TracIn score for a test row. What does that mean?
Show the answer
Answer: b
Opponents are often worth a look (conflicting or mislabeled examples), but a score isn't proof of either.
Check yourself
The correlation between |TracIn| and self-influence is close to 1. How should you read the top proponents?
Show the answer
Answer: b
Normalizing gradients, or comparing rankings across test rows, separates relevance from gradient size.
Check yourself
How should you check TRAK's attributions?
Show the answer
Answer: b
Plausible top examples can mislead. Subset retraining measures whether attributions predict what training data actually does.
Check yourself
Why does TRAK average over several independently trained models?
Show the answer
Answer: b
Training randomness changes which rows a single model leans on. The ensemble estimates the expected attribution.
Recap
Recap- Influence functions: at an optimum; reliable for convex models.
- TracIn: gradient alignment summed over checkpoints; watch the gradient-norm check.
- TRAK: projected gradients and a kernel solve, averaged over models.
- Validate any of them with actual refits; a score isn't a causal probability.
Concepts in this lesson