Skip to content

DeepLIFT and Grad-CAM: reference differences and coarse maps

DeepLIFT propagates differences from a reference through a network in one backward pass; Grad-CAM weights a convolutional layer's maps by their gradients. Learn the rule behind each and what each picture can and can't show.

Advanced ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Describe DeepLIFT's multipliers and its summation-to-delta property
  • Compute a Grad-CAM map from feature maps and their averaged gradients
  • Explain what Grad-CAM's final ReLU and upsampling hide
  • Run a randomization check on a saliency map

Read first

01

DeepLIFT: differences, not derivatives

Read

DeepLIFTDeepLIFTPasses each unit's change against a baseline row back through a network, scaled by its input's change, so contributions add up exactly. compares the row with a reference row and propagates differences in activations backward. Each unit gets a multiplier m=Δy/Δxm=\Delta y/\Delta x, a finite-difference slope rather than a local derivative, and the contributions satisfy

∑iCΔxi→Δt=Δt,mΔz→ΔyRescale=ΔyΔz.\sum_i C_{\Delta x_i\to\Delta t}=\Delta t,\qquad m^{\text{Rescale}}_{\Delta z\to\Delta y}=\frac{\Delta y}{\Delta z}.

The Rescale rule handles a nonlinearity by its average slope between reference and row, so a saturated ReLU still passes credit. One backward pass gives attributions that add up exactly to the output's change. In the reference's one-ReLU example the contributions are 1.333 and −0.333.

Reference · EXP005 · Runs in CodeSplashDeepLIFTPropagate activation differences relative to a reference through a neural computation, assigning input contributions to the difference in a chosen output.
02

DeepLIFT's caveats

Read
  • Rules per operation. Rescale and RevealCancel are rules, not derivatives; a transformer's attention and normalization need their own, and libraries differ. Record which rule you used.
  • Graph dependence. Two networks computing the same function can get different DeepLIFT attributions, a property IG doesn't share.
  • The reference carries the same burden as IG's baseline: summing to the change from a meaningless reference explains a meaningless change.

On simple networks, compare DeepLIFT with IG: large disagreements point at the rules.

03

DeepLIFT in CodeSplash

Read

Gradient attributions for a saved model runs DeepLIFT (Rescale) for torch MLPs with ReLU, tanh or sigmoid layers.

Gradient attributions for a saved model — learn.torch_mlp/multiclass_penguins_tanh_batchesRecorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

Across 20 rows, bill_dep moves the model's P(Gentoo) the most (DeepLIFT, mean |attribution| 0.19).

Mean |attribution|, bill_dep
0.1902
Baseline P(Gentoo)
0.6267
Completeness gap
1.037e-6

Plots

Mean |attribution| (DeepLIFT, probability scale)Which features does the model rely on most?
View data
FeatureMean |attribution|
bill_dep0.1902
island0.1560
bill_len0.1263
body_mass0.0951
flipper_len0.0633
sex0.0401
DeepLIFT attributions per rowHow does each feature push individual predictions up or down, and for which values?
View data
FeatureAttribution (probability)Feature value (scaled)
bill_dep−0.24060.7468
bill_dep−0.41341
bill_dep−0.49480.7848
bill_dep−0.07310.5316
bill_dep−0.18810.7722
bill_dep−0.19920.6709
bill_dep−0.22050.7089
bill_dep−0.17010.6329
bill_dep0.20430.0127
bill_dep0.15300
bill_dep0.11770.1392
bill_dep0.09620.2278
bill_dep0.09560.2405
bill_dep0.13080.1266
bill_dep−0.25030.7975
bill_dep−0.21240.8481
bill_dep−0.04490.5696
bill_dep−0.15650.6203
bill_dep−0.15640.7342
bill_dep−0.18490.7215
island0.09180
island−0.03150.5000
island0.16440
island0.13300
island−0.11711
island0.09270
island0.09440
island−0.22071
island0.10370
island0.07600
island0.08960
island0.07280
island0.12940
island0.09860
island−0.28110.5000
island−0.17560.5000
island−0.19750.5000
island−0.44800.5000
island−0.21650.5000
island−0.28530.5000
bill_len−0.37330.0349
bill_len−0.06360.3144
bill_len−0.15340.3013
bill_len−0.43410.1703
bill_len−0.24720
bill_len−0.33800.1223
bill_len−0.20710.2009
bill_len−0.13190.2795
bill_len−0.00290.3581
bill_len0.00350.4279
bill_len0.00530.4847
bill_len0.03180.5677
bill_len−0.04950.6725
bill_len0.00030.5109
bill_len−0.07350.6725
bill_len−0.01080.6638
bill_len−0.09901
bill_len−0.13610.6157
bill_len−0.06240.6900
bill_len−0.10250.7118

First 60 of 120 rows.

Why row 23 got its score (DeepLIFT, probability scale)Which features pushed this one prediction up, and which pulled it down?
View data
Attribution (probability)FeatureValue
−0.2406bill_dep19.2
0.0918islandBiscoe
−0.3733bill_len35.9
−0.0566body_mass3800
−0.0958flipper_len189
0.0479sexfemale

Assumptions

  • Attributions add up — Largest gap 1e-06 of the biggest change from the baseline.
  • A meaningful baseline — Attributions compare each row with the training rows' mean design row.
  • Features vary independently — flipper_len and body_mass: |ρ| = 0.85; changing one alone creates unlikely rows, so read their shares as joint.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.

DeepLIFT: mean |attribution| per feature

FeatureMean |attribution|
bill_dep0.1902
island0.1560
bill_len0.1263
body_mass0.0951
flipper_len0.0633
sex0.0401
  • DeepLIFT (Rescale rule): each unit passes back its change against the baseline (the training rows' mean) divided by its input's change, so each row's contributions add up to its P(Gentoo) minus the baseline's (gap 1e-06).
The exact R script · R R version 4.5.1 (2025-06-13)
# Gradient attributions for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.gradients 1.1.0 · spec abdb212379a0402c
# Explains the saved model learn.torch_mlp/multiclass_penguins_tanh_batches 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 ae5076502a5bb0d4
# Dataset: ml_penguins (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 <- "species"
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
TASK <- "multiclass"
CLASSES <- c("Adelie", "Chinstrap", "Gentoo")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
  hidden_layers = c(12),
  activation = "tanh",
  epochs = 60,
  learning_rate = 0.02,
  batch_size = 32,
  weight_decay = 0.0001,
  early_stopping = 0,
  validation_fraction = 0.1,
  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_penguins.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(
    island = "categorical",
    bill_len = "numeric",
    bill_dep = "numeric",
    flipper_len = "numeric",
    body_mass = "numeric",
    sex = "categorical"
  ),
  levels = list(
    island = c("Biscoe", "Dream", "Torgersen"),
    sex = c("female", "male")
  ),
  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\":\"gradients\",\"method\":\"explain.gradients\",\"model\":\"learn.torch_mlp/multiclass_penguins_tanh_batches\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"class\":\"Gentoo\",\"gradRows\":20,\"igBaseline\":\"mean\",\"igSteps\":32,\"maxRows\":20,\"methods\":[\"deeplift\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\"}", 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

Across 20 rows, bill_dep moves the model's P(Gentoo) the most (DeepLIFT, mean |attribution| 0.19).

Mean |attribution|, bill_dep
0.1902
Baseline P(Gentoo)
0.6267
Completeness gap
1.037e-6

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Attributions add up — Largest gap 1e-06 of the biggest change from the baseline.
  • A meaningful baseline — Attributions compare each row with the training rows' mean design row.
  • Features vary independently — flipper_len and body_mass: |ρ| = 0.85; changing one alone creates unlikely rows, so read their shares as joint.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.

DeepLIFT: mean |attribution| per feature

FeatureMean |attribution|
bill_dep0.1902
island0.1560
bill_len0.1263
body_mass0.0951
flipper_len0.0633
sex0.0401
  • DeepLIFT (Rescale rule): each unit passes back its change against the baseline (the training rows' mean) divided by its input's change, so each row's contributions add up to its P(Gentoo) minus the baseline's (gap 1e-06).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Gradient attributions for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.gradients 1.1.0 · spec abdb212379a0402c
# Explains the saved model learn.torch_mlp/multiclass_penguins_tanh_batches 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 ae5076502a5bb0d4
# Dataset: ml_penguins (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 = "species"
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
TASK = "multiclass"
CLASSES = ["Adelie", "Chinstrap", "Gentoo"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
    "hidden_layers": [12],
    "activation": "tanh",
    "epochs": 60,
    "learning_rate": 0.02,
    "batch_size": 32,
    "weight_decay": 0.0001,
    "early_stopping": 0,
    "validation_fraction": 0.1,
    "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_penguins.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={
        "island": "categorical",
        "bill_len": "numeric",
        "bill_dep": "numeric",
        "flipper_len": "numeric",
        "body_mass": "numeric",
        "sex": "categorical",
    },
    levels={
        "island": ["Biscoe", "Dream", "Torgersen"],
        "sex": ["female", "male"],
    },
    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\":\"gradients\",\"method\":\"explain.gradients\",\"model\":\"learn.torch_mlp/multiclass_penguins_tanh_batches\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"class\":\"Gentoo\",\"gradRows\":20,\"igBaseline\":\"mean\",\"igSteps\":32,\"maxRows\":20,\"methods\":[\"deeplift\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\"}") 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 P(Gentoo), the summation gap is 0.000001, essentially zero, and the top feature is bill_dep.

04

Grad-CAM: where in the image

Read

For images, Grad-CAMGrad-CAMA heat map of where a CNN looks for a class: the last convolution block's maps, weighted by how much they raise the class score. asks which spatial regions of a convolutional layer support a class score ycy^c. Average the score's gradient over each feature map AkA^k to get a channel weight, weight the maps, sum and keep the positive part:

αkc=1Z∑i,j∂yc∂Aijk,LGrad-CAMc=ReLU(∑kαkc Ak).\alpha_k^c=\frac1Z\sum_{i,j}\frac{\partial y^c}{\partial A^k_{ij}},\qquad L^c_{\text{Grad-CAM}}=\mathrm{ReLU}\Big(\sum_k\alpha_k^c\,A^k\Big).

In the reference's two-channel example the channel weights are 0.2 and −0.1; after the ReLU, one cell of the map is positive, 0.4, and the rest are zero.

Reference · EXP006 · Partly runs in CodeSplashGrad-CAMProduce a coarse class-targeted spatial map by weighting convolutional feature maps with averaged gradients of a selected score.
05

What the heat map hides

Read
  • Coarse. The map has the layer's resolution (often 7×7); upsampling to the image size smooths it, it doesn't add detail.
  • Positive only. The ReLU discards evidence against the class.
  • Choices. The layer, the class score and the preprocessing all change the map.
  • Persuasive isn't faithful. A map that outlines the object can still come from a background shortcut elsewhere, and agreement with what a person expects proves nothing.
06

Predict: scramble the weights

Predict

Predict first

You replace a trained CNN's weights with random ones and recompute a saliency mapSaliency mapA picture of an attribution over input positions (pixels, tokens, time steps). It shows sensitivity, not proof of what the model uses.. What happens for some popular methods?

The map should change completelyThe map might barely change
Reveal

It might barely change. Some saliency methods mostly reflect the input's edges, so the map looks similar for a random model. That is the point of a model randomization checkModel randomization checkRecompute an explanation after scrambling the model's learned weights; an explanation that stays the same can't be explaining the model.: an explanation that doesn't depend on what the model learned can't be explaining it. Repeat with several seeds and randomize layers one at a time.

07

Where they stand in CodeSplash

Read
EntryIn CodeSplash
DeepLIFT (EXP005)Runs in CodeSplash: Gradient attributions for a saved model (Rescale rule) and the Explain tab, for torch MLPs with ReLU, tanh or sigmoid layers; Python ≡ R
Grad-CAM (EXP006)Partly runs in CodeSplash: an explainer on the Predict Explain tab for Convolutional neural network (CNN) and Image classifier (pretrained ResNet-50 or DINOv2) runs; no Analyze method
08

Check your understanding

Checkpoint

Check yourself

What do DeepLIFT's contributions add up to?

Show the answer

Answer: b

Summation-to-delta is DeepLIFT's completeness. It says nothing about whether the reference represents absence.

Check yourself

A ReLU unit is saturated at the row, so its local gradient is zero. Why can DeepLIFT still give its input credit?

Show the answer

Answer: b

Finite-difference multipliers see the whole move from reference to row, like IG's path integral, in one backward pass.

Check yourself

A Grad-CAM map for "dog" is blank over a cat in the same image. Does the cat region not matter for the dog score?

Show the answer

Answer: b

Grad-CAM shows positive support only. Use a signed attribution or an occlusion test to see evidence against a class.

Check yourself

A Grad-CAM overlay looks detailed at full image size. Where did the detail come from?

Show the answer

Answer: b

Inspect the raw low-resolution map before the color overlay, and don't read pixel-level precision into it.

09

Recap

Recap
  • DeepLIFT propagates differences from a reference with multipliers; contributions add up to the output's change.
  • Its rules depend on the operations and the graph; record them and compare with IG.
  • Grad-CAM weights a conv layer's maps by averaged gradients; it is coarse and positive-only.
  • Run a model randomization check before trusting any saliency map.

Concepts in this lesson