Skip to content

TracIn in Analyze: the training rows behind a network's predictions

TracIn follows a network's training through its checkpoints to find the training rows that pushed a prediction's loss down or up. Read proponents, opponents and self-influence, and spot rankings driven by gradient size.

Advanced ~10 min7 steps

What runs in CodeSplash

You will be able to

  • Explain a TracIn score as a learning rate times a dot product of loss gradients, added over checkpoints
  • Read proponents, opponents and self-influence, and use self-influence to find rows worth checking
  • Recognize when the ranking mostly follows gradient size

Read first

01

What taught the network this?

Read

Most explanations point at features. TracInTracInInfluence of a training row on a prediction: learning rate × the dot product of their loss gradients, summed over saved checkpoints. points at training rows: which of them pushed the network toward this prediction while it trained, and which pushed it away.

02

Tracing gradient descent

Predict

Predict first

One training step of size η on training row i changes the explained row's loss. To first order, by how much?

By its gradient's length aloneBy −η times the dot product of the two rows' loss gradientsBy the distance between the two rows' features
Reveal

−η times the dot product of their loss gradients. If the two gradients point the same way, the step on row i also lowers the explained row's loss. TracIn adds this up over the checkpointsCheckpoint (TracIn)The network's weights saved during training (the last and the best epoch); TracIn adds up one gradient product per checkpoint. the run saved, each weighted by its learning rate. Positive totals are proponents, negative ones opponents.

03

Read the card

Explore

A dense network predicts ozone from weather. TracIn traces 2 predictions to 93 training rows over 2 checkpoints (the best and the last epoch). Training row 101 helped a prediction the most, with a score of 0.464.

TracIn training-row influence for a saved network — learn.torch_mlp/regression_airquality_early_stoppingRecorded · Python and R agreeRecorded 2026-11-25 · 59 values compared
R

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 rowEffectRankTraining rowIts targetTracIn score
31Proponent1126730.3729
31Proponent2143160.2572
31Proponent395160.2372
31Proponent497350.2249
31Opponent1117168−0.6174
31Opponent24837−0.3655
31Opponent362135−0.3642
31Opponent430115−0.2667
88Proponent11011100.4645
88Proponent2124960.4042
88Proponent3100890.3140
88Proponent4123850.3054
88Opponent18720−0.2866
88Opponent29516−0.2532
88Opponent3949−0.2274
88Opponent49735−0.1791

Training rows the network found hardest to fit (TracIn self-influence)

RankTraining rowIts targetSelf-influence
11171686.281
248374.767
3126733.172
4621352.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")
))
Python

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 rowEffectRankTraining rowIts targetTracIn score
31Proponent1126730.3729
31Proponent2143160.2572
31Proponent395160.2372
31Proponent497350.2249
31Opponent1117168−0.6174
31Opponent24837−0.3655
31Opponent362135−0.3642
31Opponent430115−0.2667
88Proponent11011100.4645
88Proponent2124960.4042
88Proponent3100890.3140
88Proponent4123850.3054
88Opponent18720−0.2866
88Opponent29516−0.2532
88Opponent3949−0.2274
88Opponent49735−0.1791

Training rows the network found hardest to fit (TracIn self-influence)

RankTraining rowIts targetSelf-influence
11171686.281
248374.767
3126733.172
4621352.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"),
    )
)

The self-influence table lists rows the network found hardest to fit, starting with row 117. 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. is a row's score with itself; large values often mark unusual or mislabeled rows, which makes it a good place to start a data check.

04

When gradient size takes over

Reflect

A row with a huge gradient gets a large score with almost everything. The card's Rankings reflect more than gradient size row reports the mean Spearman ρ between |TracIn| and self-influence: 0.75 here, and 1.00 for a small CNN on digit images. When it is near 1, the top rows are mostly "rows the network moved a lot for", whatever the prediction. How would you tell a row that really taught this prediction from one that is merely loud?

TracIn training-row influence for a saved network — learn.cnn/binary_odd_full_batchRecorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

TracIn traced 2 predictions to 800 training rows over 1 checkpoint; training row 606 helped the most (score 0.0414, for explained row 2), and training row 819 was the hardest to fit (self-influence 6.17).

Largest proponent score (training row 606)
0.0414
Largest self-influence (training row 819)
6.171

Assumptions

  • Checkpoints of this training — 1 distinct checkpoint of the training call that made the model; with one, TracIn is the gradient dot product at the final weights.
  • Rankings reflect more than gradient size — Mean Spearman ρ between |TracIn| and self-influence 1.00; the rankings mostly follow how large each training row's gradient is.
  • Features vary independently — r0c2 and r7c2: |ρ| = 0.94; 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 rowEffectRankTraining rowIts targetTracIn score
425Proponent119false0.0261
425Proponent2379false0.0245
425Proponent3130false0.0236
425Opponent1819true−0.0279
425Opponent2606true−0.0251
425Opponent3492true−0.0229
846Proponent1606true0.0414
846Proponent2819true0.0407
846Proponent3492true0.0352
846Opponent119false−0.0413
846Opponent2379false−0.0392
846Opponent3130false−0.0364

Training rows the network found hardest to fit (TracIn self-influence)

RankTraining rowIts targetSelf-influence
1819true6.171
219false5.826
3606true5.430
  • TracIn adds up, over the 1 saved checkpoint of this training (last (epoch 60)), 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 a674e760f5d956db
# Explains the saved model learn.cnn/binary_odd_full_batch with its own learner code (learn.cnn 1.4.0, driver mode "explain").
# Convolutional neural network (CNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.cnn 1.4.0 · spec 1b2aa32e38c96824
# Dataset: ml_digits (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 is built by codesplashr's cs_deep_fit_cnn twin.

# %% Data and split plan
TARGET <- "odd"
FEATURES <- c("r0c0", "r0c1", "r0c2", "r0c3", "r0c4", "r0c5", "r0c6", "r0c7", "r1c0", "r1c1", "r1c2", "r1c3", "r1c4", "r1c5", "r1c6", "r1c7", "r2c0", "r2c1", "r2c2", "r2c3", "r2c4", "r2c5", "r2c6", "r2c7", "r3c0", "r3c1", "r3c2", "r3c3", "r3c4", "r3c5", "r3c6", "r3c7", "r4c0", "r4c1", "r4c2", "r4c3", "r4c4", "r4c5", "r4c6", "r4c7", "r5c0", "r5c1", "r5c2", "r5c3", "r5c4", "r5c5", "r5c6", "r5c7", "r6c0", "r6c1", "r6c2", "r6c3", "r6c4", "r6c5", "r6c6", "r6c7", "r7c0", "r7c1", "r7c2", "r7c3", "r7c4", "r7c5", "r7c6", "r7c7")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  image_width = 8,
  conv_blocks = 1,
  filters = 4,
  kernel_size = 5,
  dense_units = 0,
  dropout = 0,
  epochs = 60,
  learning_rate = 0.02,
  batch_size = NULL,
  weight_decay = 0.001,
  early_stopping = 0,
  validation_fraction = 0.1,
  semi_supervised = "none",
  fixmatch_threshold = 0.95,
  fixmatch_weight = 1,
  fixmatch_ratio = 2,
  fixmatch_flip = FALSE,
  loss = "cross_entropy",
  focal_gamma = 2,
  focal_alpha = NULL,
  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_digits.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(
    r0c0 = "numeric",
    r0c1 = "numeric",
    r0c2 = "numeric",
    r0c3 = "numeric",
    r0c4 = "numeric",
    r0c5 = "numeric",
    r0c6 = "numeric",
    r0c7 = "numeric",
    r1c0 = "numeric",
    r1c1 = "numeric",
    r1c2 = "numeric",
    r1c3 = "numeric",
    r1c4 = "numeric",
    r1c5 = "numeric",
    r1c6 = "numeric",
    r1c7 = "numeric",
    r2c0 = "numeric",
    r2c1 = "numeric",
    r2c2 = "numeric",
    r2c3 = "numeric",
    r2c4 = "numeric",
    r2c5 = "numeric",
    r2c6 = "numeric",
    r2c7 = "numeric",
    r3c0 = "numeric",
    r3c1 = "numeric",
    r3c2 = "numeric",
    r3c3 = "numeric",
    r3c4 = "numeric",
    r3c5 = "numeric",
    r3c6 = "numeric",
    r3c7 = "numeric",
    r4c0 = "numeric",
    r4c1 = "numeric",
    r4c2 = "numeric",
    r4c3 = "numeric",
    r4c4 = "numeric",
    r4c5 = "numeric",
    r4c6 = "numeric",
    r4c7 = "numeric",
    r5c0 = "numeric",
    r5c1 = "numeric",
    r5c2 = "numeric",
    r5c3 = "numeric",
    r5c4 = "numeric",
    r5c5 = "numeric",
    r5c6 = "numeric",
    r5c7 = "numeric",
    r6c0 = "numeric",
    r6c1 = "numeric",
    r6c2 = "numeric",
    r6c3 = "numeric",
    r6c4 = "numeric",
    r6c5 = "numeric",
    r6c6 = "numeric",
    r6c7 = "numeric",
    r7c0 = "numeric",
    r7c1 = "numeric",
    r7c2 = "numeric",
    r7c3 = "numeric",
    r7c4 = "numeric",
    r7c5 = "numeric",
    r7c6 = "numeric",
    r7c7 = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "none",
  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(
  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 small convolutional network on torch for R (float64, one thread). Each row's design columns are the
# pixels of one grayscale image, row by row; blocks of convolution -> ReLU -> 2 x 2 max pooling feed a dense
# layer and the output layer. Pixels are divided by the training rows' largest value. Initial weights,
# batches, dropout masks and early-stopping rows come from the shared random stream, so Python's torch
# trains the same network.
fit_model <- function(X, y, w) {
  if (TASK == "binary") {
    target <- as.numeric(y); o <- 1L
  } else {
    target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
  }
  cs_deep_fit_cnn(
    unname(X), target, w, TASK, o,
    image_width = if (is.null(PARAMS$image_width)) NULL else as.integer(PARAMS$image_width),
    conv_blocks = as.integer(PARAMS$conv_blocks),
    filters = as.integer(PARAMS$filters),
    kernel_size = as.integer(PARAMS$kernel_size),
    dense_units = as.integer(PARAMS$dense_units),
    dropout = PARAMS$dropout,
    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
  )
}

predict_model <- function(model, X) cs_deep_cnn_predict(model, unname(X), TASK)

feature_importance <- function(model, names) NULL

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)  # plain numeric weights, the architecture and the pixel scale
  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.cnn/binary_odd_full_batch\",\"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\":3}", 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 = "Convolutional neural network (CNN)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet")
))
Python

TracIn traced 2 predictions to 800 training rows over 1 checkpoint; training row 606 helped the most (score 0.0414, for explained row 2), and training row 819 was the hardest to fit (self-influence 6.17).

Largest proponent score (training row 606)
0.0414
Largest self-influence (training row 819)
6.171

Assumptions

  • Checkpoints of this training — 1 distinct checkpoint of the training call that made the model; with one, TracIn is the gradient dot product at the final weights.
  • Rankings reflect more than gradient size — Mean Spearman ρ between |TracIn| and self-influence 1.00; the rankings mostly follow how large each training row's gradient is.
  • Features vary independently — r0c2 and r7c2: |ρ| = 0.94; 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 rowEffectRankTraining rowIts targetTracIn score
425Proponent119false0.0261
425Proponent2379false0.0245
425Proponent3130false0.0236
425Opponent1819true−0.0279
425Opponent2606true−0.0251
425Opponent3492true−0.0229
846Proponent1606true0.0414
846Proponent2819true0.0407
846Proponent3492true0.0352
846Opponent119false−0.0413
846Opponent2379false−0.0392
846Opponent3130false−0.0364

Training rows the network found hardest to fit (TracIn self-influence)

RankTraining rowIts targetSelf-influence
1819true6.171
219false5.826
3606true5.430
  • TracIn adds up, over the 1 saved checkpoint of this training (last (epoch 60)), 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 a674e760f5d956db
# Explains the saved model learn.cnn/binary_odd_full_batch with its own learner code (learn.cnn 1.4.0, driver mode "explain").
# Convolutional neural network (CNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.cnn 1.4.0 · spec 1b2aa32e38c96824
# Dataset: ml_digits (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
from codesplash.deep import cnn as deepcnn  # twin of codesplashr::cs_deep_fit_cnn (shared weights, AdamW written out)

# %% Data and split plan
TARGET = "odd"
FEATURES = ["r0c0", "r0c1", "r0c2", "r0c3", "r0c4", "r0c5", "r0c6", "r0c7", "r1c0", "r1c1", "r1c2", "r1c3", "r1c4", "r1c5", "r1c6", "r1c7", "r2c0", "r2c1", "r2c2", "r2c3", "r2c4", "r2c5", "r2c6", "r2c7", "r3c0", "r3c1", "r3c2", "r3c3", "r3c4", "r3c5", "r3c6", "r3c7", "r4c0", "r4c1", "r4c2", "r4c3", "r4c4", "r4c5", "r4c6", "r4c7", "r5c0", "r5c1", "r5c2", "r5c3", "r5c4", "r5c5", "r5c6", "r5c7", "r6c0", "r6c1", "r6c2", "r6c3", "r6c4", "r6c5", "r6c6", "r6c7", "r7c0", "r7c1", "r7c2", "r7c3", "r7c4", "r7c5", "r7c6", "r7c7"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "image_width": 8,
    "conv_blocks": 1,
    "filters": 4,
    "kernel_size": 5,
    "dense_units": 0,
    "dropout": 0,
    "epochs": 60,
    "learning_rate": 0.02,
    "batch_size": None,
    "weight_decay": 0.001,
    "early_stopping": 0,
    "validation_fraction": 0.1,
    "semi_supervised": "none",
    "fixmatch_threshold": 0.95,
    "fixmatch_weight": 1,
    "fixmatch_ratio": 2,
    "fixmatch_flip": False,
    "loss": "cross_entropy",
    "focal_gamma": 2,
    "focal_alpha": None,
    "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_digits.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={
        "r0c0": "numeric",
        "r0c1": "numeric",
        "r0c2": "numeric",
        "r0c3": "numeric",
        "r0c4": "numeric",
        "r0c5": "numeric",
        "r0c6": "numeric",
        "r0c7": "numeric",
        "r1c0": "numeric",
        "r1c1": "numeric",
        "r1c2": "numeric",
        "r1c3": "numeric",
        "r1c4": "numeric",
        "r1c5": "numeric",
        "r1c6": "numeric",
        "r1c7": "numeric",
        "r2c0": "numeric",
        "r2c1": "numeric",
        "r2c2": "numeric",
        "r2c3": "numeric",
        "r2c4": "numeric",
        "r2c5": "numeric",
        "r2c6": "numeric",
        "r2c7": "numeric",
        "r3c0": "numeric",
        "r3c1": "numeric",
        "r3c2": "numeric",
        "r3c3": "numeric",
        "r3c4": "numeric",
        "r3c5": "numeric",
        "r3c6": "numeric",
        "r3c7": "numeric",
        "r4c0": "numeric",
        "r4c1": "numeric",
        "r4c2": "numeric",
        "r4c3": "numeric",
        "r4c4": "numeric",
        "r4c5": "numeric",
        "r4c6": "numeric",
        "r4c7": "numeric",
        "r5c0": "numeric",
        "r5c1": "numeric",
        "r5c2": "numeric",
        "r5c3": "numeric",
        "r5c4": "numeric",
        "r5c5": "numeric",
        "r5c6": "numeric",
        "r5c7": "numeric",
        "r6c0": "numeric",
        "r6c1": "numeric",
        "r6c2": "numeric",
        "r6c3": "numeric",
        "r6c4": "numeric",
        "r6c5": "numeric",
        "r6c6": "numeric",
        "r6c7": "numeric",
        "r7c0": "numeric",
        "r7c1": "numeric",
        "r7c2": "numeric",
        "r7c3": "numeric",
        "r7c4": "numeric",
        "r7c5": "numeric",
        "r7c6": "numeric",
        "r7c7": "numeric",
    },
    levels={
    },
    impute="median",
    scale="none",
    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(
    {
        "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 small convolutional network on PyTorch (float64, one thread). Each row's design columns are the pixels
# of one grayscale image, row by row; blocks of convolution -> ReLU -> 2 x 2 max pooling feed a dense layer
# and the output layer. Pixels are divided by the training rows' largest value. Initial weights, batches,
# dropout masks and early-stopping rows come from the shared random stream, so R's torch trains the same
# network.
def fit_model(X, y, w):
    if TASK == "binary":
        target, o = np.asarray(y, dtype=np.float64), 1
    else:
        target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
    return deepcnn.fit_cnn(
        X, target, w, TASK, o,
        image_width=None if PARAMS["image_width"] is None else int(PARAMS["image_width"]),
        conv_blocks=int(PARAMS["conv_blocks"]),
        filters=int(PARAMS["filters"]),
        kernel_size=int(PARAMS["kernel_size"]),
        dense_units=int(PARAMS["dense_units"]),
        dropout=PARAMS["dropout"],
        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,
    )


def predict_model(model, X):
    return deepcnn.cnn_predict(model, X, TASK)


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 architecture and the pixel scale
    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.cnn/binary_odd_full_batch\",\"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\":3}") 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="Convolutional neural network (CNN)",
        engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
    )
)
05

What TracIn needs

Read

TracIn reads a torch network (dense network, CNN or FT-Transformer) and the checkpoints saved while it trained. A registered model version points back to its training run's folder, which keeps them; for any other model the card says what is missing:

TracIn training-row influence for a saved network — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 12 values compared
R

TracIn was not computed: the method needs a torch network (dense network, CNN or FT-Transformer).

Assumptions

  • Checkpoints of this training — TracIn needs a torch network (dense network, CNN or FT-Transformer).
  • Features vary independently — skin and bmi: |ρ| = 0.69; 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-data influence (TracIn) was not computed: the method needs a torch network (dense network, CNN or FT-Transformer).
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 b849b69a868bc348
# Explains the saved model learn.tree/binary_pima with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 2c9409d7e5211ff1
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  max_depth = 6,
  min_samples_split = 10,
  min_samples_leaf = 5,
  criterion = "gini",
  min_impurity_decrease = 0,
  ccp_alpha = 0
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.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(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "none",
  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
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in R and Python (rpart differs: surrogates, cp scaling,
# internal cross-validation).
fit_model <- function(X, y, w) {
  k <- if (TASK == "regression") 0L else if (TASK == "binary") 2L else length(CLASSES)
  cs_ml_cart_fit(X, y, TASK, k, criterion = PARAMS$criterion, max_depth = PARAMS$max_depth,
                 min_samples_split = as.integer(PARAMS$min_samples_split),
                 min_samples_leaf = as.integer(PARAMS$min_samples_leaf),
                 min_impurity_decrease = PARAMS$min_impurity_decrease, ccp_alpha = PARAMS$ccp_alpha, w = w)
}

predict_model <- function(model, X) {
  p <- cs_ml_cart_predict(model, X)
  if (TASK == "binary") p[, 2] else p
}

feature_importance <- function(model, names) cs_ml_cart_importances(model, names)

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  classes <- if (TASK == "binary") c(setdiff(CLASSES, POSITIVE)[1], POSITIVE) else if (length(CLASSES)) CLASSES else NULL
  list(list(key = "model", path = path, format = "rds"), cs_ml_tree_json(directory, model, names_, classes))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"tracin\",\"method\":\"explain.tracin\",\"model\":\"learn.tree/binary_pima\",\"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\":5}", 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("stats")) {
  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 = "Decision tree (CART)",
  engine = cs_engine_info("stats", "nanoparquet")
))
Python

TracIn was not computed: the method needs a torch network (dense network, CNN or FT-Transformer).

Assumptions

  • Checkpoints of this training — TracIn needs a torch network (dense network, CNN or FT-Transformer).
  • Features vary independently — skin and bmi: |ρ| = 0.69; 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-data influence (TracIn) was not computed: the method needs a torch network (dense network, CNN or FT-Transformer).
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 b849b69a868bc348
# Explains the saved model learn.tree/binary_pima with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 2c9409d7e5211ff1
# Dataset: ml_pima (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.ml.tree import CART, tree_json

# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "max_depth": 6,
    "min_samples_split": 10,
    "min_samples_leaf": 5,
    "criterion": "gini",
    "min_impurity_decrease": 0,
    "ccp_alpha": 0,
}

df = pd.read_parquet("tests/parity/fixtures/ml_pima.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={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute="median",
    scale="none",
    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
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in Python and R.


def fit_model(X, y, w):
    k = 0 if TASK == "regression" else (2 if TASK == "binary" else len(CLASSES))
    model = CART(
        TASK,
        k,
        criterion=PARAMS["criterion"],
        max_depth=PARAMS["max_depth"],
        min_samples_split=int(PARAMS["min_samples_split"]),
        min_samples_leaf=int(PARAMS["min_samples_leaf"]),
        min_impurity_decrease=PARAMS["min_impurity_decrease"],
        ccp_alpha=PARAMS["ccp_alpha"],
    )
    return model.fit(X, y, w)


def predict_model(model, X):
    p = model.predict(X)
    return p[:, 1] if TASK == "binary" else p


def feature_importance(model, names):
    return model.importances(names)


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    if TASK == "binary":
        classes = [[c for c in CLASSES if c != POSITIVE][0], POSITIVE]  # probabilities: [other, positive]
    else:
        classes = CLASSES or None
    return [{"key": "model", "path": path, "format": "joblib"}, tree_json(directory, model, names, classes)]


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.tree/binary_pima\",\"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\":5}") 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="Decision tree (CART)",
        engine=cs.engine_info("numpy", "numpy", "pandas"),
    )
)
06

The code behind it

Read
Python
import numpy as np

# TracIn over checkpoints: grads[k] holds one loss-gradient row per example at checkpoint k.
def tracin(grads_train, grads_test, rates):
    scores = sum(lr * g_test @ g_train.T for g_train, g_test, lr in zip(grads_train, grads_test, rates))
    self_influence = sum(lr * np.sum(g_train**2, axis=1) for g_train, lr in zip(grads_train, rates))
    return scores, self_influence
R
# TracIn over checkpoints: grads[[k]] holds one loss-gradient row per example at checkpoint k.
tracin <- function(grads_train, grads_test, rates) {
  scores <- Reduce(`+`, Map(function(gtr, gte, lr) lr * gte %*% t(gtr), grads_train, grads_test, rates))
  self_influence <- Reduce(`+`, Map(function(gtr, lr) lr * rowSums(gtr^2), grads_train, rates))
  list(scores = scores, self_influence = self_influence)
}
07

Check your understanding

Checkpoint

Check yourself

Training row 57 has a TracIn score of −0.4 for an explained row. What does that mean?

Show the answer

Answer: a

An opponent. A negative score means row 57's gradient steps pointed against the explained row's, so training on it raised that row's loss. It says nothing yet about whether row 57 is wrong.

Check yourself

The card warns that the rankings mostly follow gradient size (ρ = 0.95). What follows?

Show the answer

Answer: a

Big gradients dominate. The numbers are right, but a row with a large gradient scores high with many predictions. Rows that rank high for this prediction and low on self-influence are the more specific evidence.

Check yourself

Why can't TracIn explain a gradient-boosted tree model?

Show the answer

Answer: a

No gradients, no checkpoints. TracIn follows gradient descent. For linear and logistic models, "Training rows behind it" (influence functions) answers the same question in the Explain tab.

Concepts in this lesson