Skip to content

Mixup, CutMix and label smoothing

Three ways to train on softened targets — blended rows, pasted image patches and smoothed labels — what each does to the loss and to confidence, and which CodeSplash runs.

Applied ~13 min7 steps

What runs in CodeSplash

You will be able to

  • Blend two rows and their targets with mixup, by hand
  • Explain how CutMix mixes labels by the share of area each image keeps
  • Compute a label-smoothed target and its cross-entropy
  • Say why softened targets change confidence, and check it on held-out data

Read first

01

Mixup: blend rows and targets

Read

MixupMixupTrains on blends of two rows and their targets, with a random mixing weight, a simple guard against overfitting. trains on weighted blends of two rows, and blends their targets with the same weight λ, drawn from a Beta(α, α) distribution for every pair:

x~=λxi+(1−λ)xj,y~=λyi+(1−λ)yj\tilde x = \lambda x_i + (1-\lambda) x_j, \qquad \tilde y = \lambda y_i + (1-\lambda) y_j

With λ = 0.7, rows (1, 0) and (0, 2) blend to (0.70, 0.60), and one-hot targets for class 1 and class 2 blend to (0.70, 0.30). The network learns to change its answer smoothly between examples instead of jumping.

02

CutMix: paste a patch

Read

Blending two photos pixel by pixel gives a ghostly double image. CutMixCutMixPastes a random box from one training image into another and mixes the labels by the share of area each image keeps. pastes a random box from one image into another instead, and mixes the labels by area.

In the program below, a 2 × 2 box of a black 4 × 4 image replaces the center of a white one. Twelve of the sixteen pixels stay white, so the white image's label gets weight 0.75. If the box is clipped at the border, the weight must be recomputed from the area actually pasted.

Python
import numpy as np

x1, x2 = np.array([1., 0.]), np.array([0., 2.])
y1, y2 = np.array([1., 0.]), np.array([0., 1.]); lam = .7
print(lam * x1 + (1 - lam) * x2, lam * y1 + (1 - lam) * y2)       # mixup

a, b = np.ones((4, 4)), np.zeros((4, 4))
mask = np.ones((4, 4)); mask[1:3, 1:3] = 0                        # the pasted box
print(mask * a + (1 - mask) * b); print("original-label weight", mask.mean())   # CutMix
R
x1 <- c(1, 0); x2 <- c(0, 2); y1 <- c(1, 0); y2 <- c(0, 1); lam <- .7
print(lam * x1 + (1 - lam) * x2); print(lam * y1 + (1 - lam) * y2)   # mixup

a <- matrix(1, 4, 4); b <- matrix(0, 4, 4)
mask <- matrix(1, 4, 4); mask[2:3, 2:3] <- 0                         # the pasted box
print(mask * a + (1 - mask) * b); print(mean(mask))                  # CutMix
03

Label smoothing: never aim for certainty

Read

Cross-entropy on one-hot targets rewards pushing the true class's probability all the way to 1. Label smoothingLabel smoothingTrains a classifier toward slightly softened targets, such as 0.95 instead of 1, so it is less overconfident. moves a share ε of the target evenly across all C classes:

qc=(1−ε) [c=y]+ε/Cq_c = (1-\varepsilon)\,[c = y] + \varepsilon / C

With C = 3 and ε = 0.1, the target for class 2 becomes (0.033, 0.933, 0.033). A prediction of (0.1, 0.8, 0.1) then has cross-entropy 0.362. The lowest loss is now reached short of certainty, so the network stays less extreme. Only the training loss uses smoothed targets.

04

Both in a torch learner

Read
Deep neural network (torch MLP)Recorded · Python and R agreeRecorded 2026-11-25 · 30 values compared
R

Deep neural network (torch MLP): cross-validated log loss 0.056 ± 0.023 over 3 folds; log loss on the locked test set 0.048 (n = 69).

CV log loss
0.0558
SD across folds
0.0234
Test log loss
0.0479

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11920.07550.98910.98990.9909
21920.0299111
31910.06210.98900.99170.9868
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec ebda99c717f9d350
# 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 = "relu",
  epochs = 40,
  learning_rate = 0.02,
  batch_size = 32,
  weight_decay = 0.0001,
  early_stopping = 10,
  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.9,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0.3,
  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("target/academy-parity/run-8142/learn.torch_mlp/multiclass_train_mixup_ema/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("target/academy-parity/run-8142/learn.torch_mlp/multiclass_train_mixup_ema/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]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
  warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL  # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
  yy <- y[rows + 1L]
  ww <- sample_weights(rows)
  if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
  r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
                      seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
  if (fold_id == 0) resampled <<- r$info
  r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)

# %% 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.9,
  swa_start = 0,
  label_smoothing = 0,
  mixup_alpha = 0.3,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.torch_mlp/multiclass_train_mixup_ema/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
  cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
  .deep_training_set(X, rows, fold_id, repeat_)
}
# 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"
if (PASSES > 0 && DROPOUT == 0 && !VARIATIONAL) {
  cs_error("CS_E_INVALID_OPTION", option = "Prediction passes", allowed = "0 unless dropout or variational weights are on", value = PASSES)
}
if (VARIATIONAL && DROPOUT > 0) {
  cs_error("CS_E_INVALID_OPTION", option = "Dropout", allowed = "0 with variational weights (their noise replaces it)", value = DROPOUT)
}
SUBGROUPS <- NULL
if (ROBUST == "group_dro" && is.null(SUBGROUPS)) {
  cs_error("CS_E_INVALID_OPTION", option = "Robust training", allowed = "Group DRO only with a Subgroups column", value = "group_dro")
}
if (ROBUST == "group_dro" && RESAMPLE != "none" && TASK != "regression") {
  cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none with Group DRO", value = RESAMPLE)
}
# Differential privacy (DP-SGD): with an epsilon or a noise multiplier set, every fit clips each row's
# gradient and adds noise (cs_deep_dp_*, turned on by the trainer's dp plugin above; the guarantee goes to
# dp.json). Off by default. These options can't be combined with it:
DP <- cs_deep_dp_settings(PARAMS)
if (!is.null(DP)) {
  if (VARIATIONAL || ROBUST != "none") {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with variational weights or robust training", value = "on")
  }
  if (RESAMPLE != "none") {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with resampling (copies of a row would each count)", value = "on")
  }
}

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"))

# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
  fold <- folds[[i]]
  prep <- cs_ml_design_fit(design, rows_of(fold$train))
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
  cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
            predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
  cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")

# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
  if (!is.null(resampled)) {
    warnings <- c(warnings, as.list(resampled$notes))
    notes <- c(notes, list(cs_ml_resample_describe(resampled)))
  }
  if (length(plan$test)) {
    cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
              predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
  }
  importance <- feature_importance(model, names_)
  artifacts[[length(artifacts) + 1L]] <- list(
    key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
  )
  artifacts <- c(artifacts, save_model(model, out))
  cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)

# %% Result
cs_publish(cs_ml_result(
  run,
  title = "Deep neural network (torch MLP)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
  n_features = length(names_),
  n_train = length(plan$train),
  n_test = length(plan$test),
  params = PARAMS,
  features = names_,
  importance = importance,
  artifacts = artifacts,
  warnings = warnings,
  notes = notes
))
Python

Deep neural network (torch MLP): cross-validated log loss 0.056 ± 0.023 over 3 folds; log loss on the locked test set 0.048 (n = 69).

CV log loss
0.0558
SD across folds
0.0234
Test log loss
0.0479

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11920.07550.98910.98990.9909
21920.0299111
31910.06210.98900.99170.9868
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec ebda99c717f9d350
# 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": "relu",
    "epochs": 40,
    "learning_rate": 0.02,
    "batch_size": 32,
    "weight_decay": 0.0001,
    "early_stopping": 10,
    "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.9,
    "swa_start": 0,
    "label_smoothing": 0,
    "mixup_alpha": 0.3,
    "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("target/academy-parity/run-8142/learn.torch_mlp/multiclass_train_mixup_ema/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("target/academy-parity/run-8142/learn.torch_mlp/multiclass_train_mixup_ema/out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
    warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None  # the final model's resampling summary
notes = []


def training_set(X, rows, fold_id, repeat):
    """A fit's design matrix, targets and weights: training rows only, resampled when asked
    (codesplash.ml.resample — the same rows in R, from the shared random stream)."""
    yy, ww = y[rows], sample_weights(rows)
    if RESAMPLE == "none" or TASK == "regression":
        return X, yy, ww
    from codesplash.ml import resample as csres

    X2, y2, w2, info = csres.resample(
        X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
    )
    if fold_id == 0:
        global resampled
        resampled = info
    return X2, y2, w2


# %% 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.9,
        "swa_start": 0,
        "label_smoothing": 0,
        "mixup_alpha": 0.3,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/learn.torch_mlp/multiclass_train_mixup_ema/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set


def training_set(X, rows, fold_id, repeat):
    """Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
    the training set as _ml_learn does."""
    deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
    return _deep_training_set(X, rows, fold_id, repeat)


# 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"
if PASSES > 0 and DROPOUT == 0 and not VARIATIONAL:
    cs.cs_error("CS_E_INVALID_OPTION", option="Prediction passes", allowed="0 unless dropout or variational weights are on", value=PASSES)
if VARIATIONAL and DROPOUT > 0:
    cs.cs_error("CS_E_INVALID_OPTION", option="Dropout", allowed="0 with variational weights (their noise replaces it)", value=DROPOUT)
SUBGROUPS = None
if ROBUST == "group_dro" and SUBGROUPS is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Robust training", allowed="Group DRO only with a Subgroups column", value="group_dro")
if ROBUST == "group_dro" and RESAMPLE != "none" and TASK != "regression":
    cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none with Group DRO", value=RESAMPLE)
# Differential privacy (DP-SGD): with an ε or a noise multiplier set, every fit clips each row's gradient
# and adds noise (codesplash.deep.dp, turned on by the trainer's dp plugin above; the guarantee goes to dp.json).
# Off by default. These options can't be combined with it:
DP = deep_dp.settings(PARAMS)
if DP is not None:
    if VARIATIONAL or ROBUST != "none":
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with variational weights or robust training", value="on")
    if RESAMPLE != "none":
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with resampling (copies of a row would each count)", value="on")


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"))


# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
    prep = design.fit(df.iloc[fold.train])
    model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
    run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
    progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")

# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
    model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
    if resampled is not None:
        from codesplash.ml import resample as csres

        warnings.extend(resampled["notes"])
        notes.append(csres.describe(resampled))
    if len(plan.test):
        run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
    importance = feature_importance(model, names)
    artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
    artifacts.extend(save_model(model, out))
    run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()

# %% Result
cs.publish(
    run.result(
        title="Deep neural network (torch MLP)",
        engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
        n_features=len(names),
        n_train=len(plan.train),
        n_test=len(plan.test),
        params=PARAMS,
        features=names,
        importance=importance,
        artifacts=artifacts,
        warnings=warnings,
        notes=notes,
    )
)

Mixup (α) and Label smoothing sit in the training settings of every torch learner. This penguin run uses mixup α = 0.3 with a moving average of the weights and still classifies 99.3% of held-out birds correctly. Mixup can't be combined with dropout or robust training.

Deep neural network (torch MLP)Recorded · Python and R agreeRecorded 2026-11-25 · 33 values compared
R

Deep neural network (torch MLP): cross-validated ROC AUC 0.852 ± 0.039 over 3 folds; ROC AUC on the locked test set 0.815 (n = 106).

CV ROC AUC
0.8521
SD across folds
0.0393
Test ROC AUC
0.8149

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.88420.42630.78870.7131
211420.80830.51400.77460.7563
311420.86370.44720.78870.7742
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec c324e3e8cdbde0a6
# 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)
# torch for R (LibTorch); the network itself is built by codesplashr's cs_deep_* twins.

# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("glu", "bmi", "age", "ped")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  hidden_layers = c(8),
  activation = "relu",
  epochs = 40,
  learning_rate = 0.01,
  batch_size = 64,
  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 = "onecycle",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0.1,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_train_onecycle_label_smoothing/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    glu = "numeric",
    bmi = "numeric",
    age = "numeric",
    ped = "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("target/academy-parity/run-8142/learn.torch_mlp/binary_train_onecycle_label_smoothing/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]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
  warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL  # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
  yy <- y[rows + 1L]
  ww <- sample_weights(rows)
  if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
  r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
                      seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
  if (fold_id == 0) resampled <<- r$info
  r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)

# %% 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 = "onecycle",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  label_smoothing = 0.1,
  mixup_alpha = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.torch_mlp/binary_train_onecycle_label_smoothing/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
  cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
  .deep_training_set(X, rows, fold_id, repeat_)
}
# 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"
if (PASSES > 0 && DROPOUT == 0 && !VARIATIONAL) {
  cs_error("CS_E_INVALID_OPTION", option = "Prediction passes", allowed = "0 unless dropout or variational weights are on", value = PASSES)
}
if (VARIATIONAL && DROPOUT > 0) {
  cs_error("CS_E_INVALID_OPTION", option = "Dropout", allowed = "0 with variational weights (their noise replaces it)", value = DROPOUT)
}
SUBGROUPS <- NULL
if (ROBUST == "group_dro" && is.null(SUBGROUPS)) {
  cs_error("CS_E_INVALID_OPTION", option = "Robust training", allowed = "Group DRO only with a Subgroups column", value = "group_dro")
}
if (ROBUST == "group_dro" && RESAMPLE != "none" && TASK != "regression") {
  cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none with Group DRO", value = RESAMPLE)
}
# Differential privacy (DP-SGD): with an epsilon or a noise multiplier set, every fit clips each row's
# gradient and adds noise (cs_deep_dp_*, turned on by the trainer's dp plugin above; the guarantee goes to
# dp.json). Off by default. These options can't be combined with it:
DP <- cs_deep_dp_settings(PARAMS)
if (!is.null(DP)) {
  if (VARIATIONAL || ROBUST != "none") {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with variational weights or robust training", value = "on")
  }
  if (RESAMPLE != "none") {
    cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with resampling (copies of a row would each count)", value = "on")
  }
}

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"))

# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
  fold <- folds[[i]]
  prep <- cs_ml_design_fit(design, rows_of(fold$train))
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
  cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
            predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
  cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")

# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
  if (!is.null(resampled)) {
    warnings <- c(warnings, as.list(resampled$notes))
    notes <- c(notes, list(cs_ml_resample_describe(resampled)))
  }
  if (length(plan$test)) {
    cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
              predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
  }
  importance <- feature_importance(model, names_)
  artifacts[[length(artifacts) + 1L]] <- list(
    key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
  )
  artifacts <- c(artifacts, save_model(model, out))
  cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)

# %% Result
cs_publish(cs_ml_result(
  run,
  title = "Deep neural network (torch MLP)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
  n_features = length(names_),
  n_train = length(plan$train),
  n_test = length(plan$test),
  params = PARAMS,
  features = names_,
  importance = importance,
  artifacts = artifacts,
  warnings = warnings,
  notes = notes
))
Python

Deep neural network (torch MLP): cross-validated ROC AUC 0.852 ± 0.039 over 3 folds; ROC AUC on the locked test set 0.815 (n = 106).

CV ROC AUC
0.8521
SD across folds
0.0393
Test ROC AUC
0.8149

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.88420.42630.78870.7131
211420.80830.51400.77460.7563
311420.86370.44720.78870.7742
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec c324e3e8cdbde0a6
# 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.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 = "diabetic"
FEATURES = ["glu", "bmi", "age", "ped"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "hidden_layers": [8],
    "activation": "relu",
    "epochs": 40,
    "learning_rate": 0.01,
    "batch_size": 64,
    "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": "onecycle",
    "warmup_epochs": 0,
    "grad_clip": 0,
    "ema_decay": 0,
    "swa_start": 0,
    "label_smoothing": 0.1,
    "mixup_alpha": 0,
    "history_every_step": False,
    "profile": "parity",
    "checkpoint_every": None,
}

df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.torch_mlp/binary_train_onecycle_label_smoothing/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "glu": "numeric",
        "bmi": "numeric",
        "age": "numeric",
        "ped": "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("target/academy-parity/run-8142/learn.torch_mlp/binary_train_onecycle_label_smoothing/out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
    warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None  # the final model's resampling summary
notes = []


def training_set(X, rows, fold_id, repeat):
    """A fit's design matrix, targets and weights: training rows only, resampled when asked
    (codesplash.ml.resample — the same rows in R, from the shared random stream)."""
    yy, ww = y[rows], sample_weights(rows)
    if RESAMPLE == "none" or TASK == "regression":
        return X, yy, ww
    from codesplash.ml import resample as csres

    X2, y2, w2, info = csres.resample(
        X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
    )
    if fold_id == 0:
        global resampled
        resampled = info
    return X2, y2, w2


# %% 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": "onecycle",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "label_smoothing": 0.1,
        "mixup_alpha": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/learn.torch_mlp/binary_train_onecycle_label_smoothing/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set


def training_set(X, rows, fold_id, repeat):
    """Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
    the training set as _ml_learn does."""
    deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
    return _deep_training_set(X, rows, fold_id, repeat)


# 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"
if PASSES > 0 and DROPOUT == 0 and not VARIATIONAL:
    cs.cs_error("CS_E_INVALID_OPTION", option="Prediction passes", allowed="0 unless dropout or variational weights are on", value=PASSES)
if VARIATIONAL and DROPOUT > 0:
    cs.cs_error("CS_E_INVALID_OPTION", option="Dropout", allowed="0 with variational weights (their noise replaces it)", value=DROPOUT)
SUBGROUPS = None
if ROBUST == "group_dro" and SUBGROUPS is None:
    cs.cs_error("CS_E_INVALID_OPTION", option="Robust training", allowed="Group DRO only with a Subgroups column", value="group_dro")
if ROBUST == "group_dro" and RESAMPLE != "none" and TASK != "regression":
    cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none with Group DRO", value=RESAMPLE)
# Differential privacy (DP-SGD): with an ε or a noise multiplier set, every fit clips each row's gradient
# and adds noise (codesplash.deep.dp, turned on by the trainer's dp plugin above; the guarantee goes to dp.json).
# Off by default. These options can't be combined with it:
DP = deep_dp.settings(PARAMS)
if DP is not None:
    if VARIATIONAL or ROBUST != "none":
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with variational weights or robust training", value="on")
    if RESAMPLE != "none":
        cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with resampling (copies of a row would each count)", value="on")


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"))


# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
    prep = design.fit(df.iloc[fold.train])
    model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
    run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
    progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")

# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
    model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
    if resampled is not None:
        from codesplash.ml import resample as csres

        warnings.extend(resampled["notes"])
        notes.append(csres.describe(resampled))
    if len(plan.test):
        run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
    importance = feature_importance(model, names)
    artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
    artifacts.extend(save_model(model, out))
    run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()

# %% Result
cs.publish(
    run.result(
        title="Deep neural network (torch MLP)",
        engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
        n_features=len(names),
        n_train=len(plan.train),
        n_test=len(plan.test),
        params=PARAMS,
        features=names,
        importance=importance,
        artifacts=artifacts,
        warnings=warnings,
        notes=notes,
    )
)

This Pima run trains toward targets smoothed by 0.1: AUC 0.852, Brier score 0.150. Check the calibration panel before trusting the probabilities.

05

What runs here

Read
EntryIn CodeSplash
mixup (TRN012)Runs in CodeSplash: Mixup (α) in every torch learner's training settings
CutMix (TRN013)Explained here: no learner offers it
Label smoothing (TRN014)Runs in CodeSplash: Label smoothing in every torch learner, for class targets
06

Check: softened targets

Checkpoint

Check yourself

Mixup blends a cat image and a dog image with λ = 0.6. What is the training target?

Show the answer

Answer: a

The target is blended with the same λ as the inputs. That's what teaches the network to move smoothly between classes.

Check yourself

What does mixup's α control?

Show the answer

Answer: a

With small α, λ is usually near 0 or 1, so most blends are mild. As α grows toward 1, λ spreads out and blends get stronger.

Check yourself

In a CodeSplash torch learner you set both Mixup and Dropout. What happens?

Show the answer

Answer: b

The app refuses the combination rather than quietly dropping one. Pick the regularizer you want and compare on held-out data.

Check yourself

CutMix pastes a box covering a quarter of a 32 × 32 image A into image B. What label weights does the mixed image get?

Show the answer

Answer: a

Weights follow area: B keeps three quarters of its pixels.

Check yourself

A CutMix box is drawn near the corner and gets clipped at the image border. What must the code do?

Show the answer

Answer: b

The label weight must match what the network sees. A clipped box covers less of the image than planned.

Check yourself

Can you train with CutMix in CodeSplash today?

Show the answer

Answer: c

CutMix needs image inputs. The torch learners' Mixup works on any table.

Check yourself

A yes/no classifier trains with label smoothing ε = 0.1. Under the uniform convention, what is the target for a "yes" row?

Show the answer

Answer: a

q = (1 − ε)·1 + ε/2 = 0.95, and a "no" row's target is 0.05. CodeSplash uses this convention.

Check yourself

Why can label smoothing change a model's calibration?

Show the answer

Answer: a

Less extreme probabilities can help an overconfident model and hurt a well-calibrated one. Read the calibration on held-out data.

07

Recap

Recap
  • Mixup blends pairs of rows and their targets with λ ~ Beta(α, α).
  • CutMix pastes a box and mixes labels by the area each image keeps.
  • Label smoothing moves ε of the target evenly over the classes; only the training loss sees it.
  • In CodeSplash, every torch learner has Mixup and Label smoothing; CutMix is explained here.

Concepts in this lesson