Batch, layer and RMS normalization
Three layers that standardize activations along different axes. See which numbers each one averages over, why batch norm behaves differently in training and prediction, and where CodeSplash's learners use each.
What runs in CodeSplash
- TRN007Batch normalization Partly runs in CodeSplash (Experimental)
- TRN008Layer normalization Runs in CodeSplash (Experimental)
- TRN009RMS normalization Explained here
- FT-Transformer Experimental
- TabNet (attentive feature selection) Experimental
You will be able to
- Say which axis batch, layer and RMS normalization each average over
- Explain why batch norm depends on the batch and has a separate prediction mode
- Pick layer or RMS normalization for sequences, small batches and Transformers
- Say which CodeSplash learners use which normalization
Read first
Same idea, different axis
ReadAll three keep activations on a steady scale between layers, then let the network rescale them with a learned γ (and shift β).
| Layer | Standardizes | Uses the batch? |
|---|---|---|
| Batch normalizationBatch normalizationStandardizes each feature over the rows of a batch during training, then rescales it with a learned scale and shift. | each feature, over the rows of the batch | yes, in training |
| Layer normalizationLayer normalizationStandardizes each row across its own features, then applies a learned scale and shift; same in training and prediction. | each row, over its own features | no |
| RMS normalizationRMS normalizationDivides each row by the root mean square of its features and rescales, without subtracting the mean: a cheaper layer norm. | each row, divided by its root mean square, no centering | no |
Batch norm keeps running averages of the batch means and variances during training and uses those at prediction time, so one row's output never depends on its neighbors once the model is saved.
Switch the layer and the mode to see which numbers each one averages over.
DExplorable · Batch, layer and RMS norm
Which numbers does each normalization layer average over, and when does that bite?
With this layer in training, does example 1's output change when the rest of the batch changes?
Layer
Mode
Batch norm uses the batch's statistics in training and running averages in evaluation.
Added to every value in evaluation: data that drifted.
Batches that built the running averages.
- Above zero
- Below zero
- Example 1
Commit your prediction above to see the result
Make your prediction to see the result.
Normalize three small arrays
ReadBatch norm on three rows turns the first column 1, 3, 5 into −1.225, 0.000 and 1.225. Layer norm turns the row 1, 2, 4 into −1.069, −0.267 and 1.336. RMS norm on the same row gives 0.378, 0.756 and 1.512: no centering, so every value stays positive. A tiny ε under the square root guards against dividing by zero.
import numpy as np
X = np.array([[1., 2.], [3., 4.], [5., 8.]])
print((X - X.mean(0)) / np.sqrt(X.var(0) + 1e-5)) # batch norm: per column, over rows
R = np.array([[1., 2., 4.], [2., 3., 8.]])
print((R - R.mean(1, keepdims=True)) / np.sqrt(R.var(1, keepdims=True) + 1e-5)) # layer norm: per row
x = np.array([1., 2., 4.])
print(x / np.sqrt(np.mean(x * x) + 1e-6)) # RMS norm: per row, no centeringX <- rbind(c(1, 2), c(3, 4), c(5, 8))
C <- sweep(X, 2, colMeans(X))
print(sweep(C, 2, sqrt(colMeans(C^2) + 1e-5), "/")) # batch norm (population variance)
R <- rbind(c(1, 2, 4), c(2, 3, 8))
D <- R - rowMeans(R)
print(D / sqrt(rowMeans(D^2) + 1e-5)) # layer norm
x <- c(1, 2, 4)
print(x / sqrt(mean(x * x) + 1e-6)) # RMS normA batch of one
PredictPredict first
A batch-norm layer in training mode receives a batch holding a single row. What does it output before γ and β are applied?
Reveal
All zeros. Each feature's batch mean is the row's own value, so x − mean is 0 everywhere. Tiny batches give noisy statistics in the same way, only less extreme. Layer norm has no such problem: it never looks at other rows.
Which one where
ReadBatch norm suits convolutional networks with sizable batches. Sequences of different lengths, tiny batches and Transformers use layer norm; many recent language models use RMS norm because it's cheaper and works as well.
Layer norm at work
ReadFT-Transformer: cross-validated ROC AUC 0.856 ± 0.055 over 3 folds; ROC AUC on the locked test set 0.799 (n = 106).
- CV ROC AUC
- 0.8558
- SD across folds
- 0.0548
- Test ROC AUC
- 0.7988
Plots
View data
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| FT-Transformer | 1 | 0.6132 | 0.6554 |
| FT-Transformer | 2 | 0.5701 | 0.5701 |
| FT-Transformer | 3 | 0.5373 | 0.5449 |
| FT-Transformer | 4 | 0.5122 | 0.5476 |
| FT-Transformer | 5 | 0.5018 | 0.5258 |
| FT-Transformer | 6 | 0.4811 | 0.5262 |
| FT-Transformer | 7 | 0.4838 | 0.4890 |
| FT-Transformer | 8 | 0.4662 | 0.4974 |
| FT-Transformer | 9 | 0.4673 | 0.5543 |
| FT-Transformer | 10 | 0.4592 | 0.4895 |
| FT-Transformer | 11 | 0.4490 | 0.4613 |
| FT-Transformer | 12 | 0.4573 | 0.5025 |
| FT-Transformer | 13 | 0.4252 | 0.4801 |
| FT-Transformer | 14 | 0.4304 | 0.5195 |
| FT-Transformer | 15 | 0.4225 | 0.5162 |
| FT-Transformer | 16 | 0.4329 | 0.5181 |
| FT-Transformer | 17 | 0.4126 | 0.5510 |
| FT-Transformer | 18 | 0.4118 | 0.5151 |
| FT-Transformer | 19 | 0.4410 | 0.4905 |
View data
| Feature | Mean attention |
|---|---|
| npreg | 0.1453 |
| glu | 0.1356 |
| bmi | 0.1352 |
| bp | 0.1238 |
| ped | 0.1186 |
| age | 0.1153 |
| skin | 0.1127 |
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 142 | 0.8938 | 0.4505 | 0.7887 | 0.7292 |
| 2 | 1 | 142 | 0.7931 | 0.5307 | 0.7465 | 0.7245 |
| 3 | 1 | 142 | 0.8805 | 0.4380 | 0.8169 | 0.8005 |
Attention to features
| Feature | Mean [CLS] attention |
|---|---|
| npreg | 0.1453 |
| glu | 0.1356 |
| bmi | 0.1352 |
| bp | 0.1238 |
| ped | 0.1186 |
| age | 0.1153 |
| skin | 0.1127 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| FT-Transformer | 1 | 0.6132 | 0.6554 |
| FT-Transformer | 2 | 0.5701 | 0.5701 |
| FT-Transformer | 3 | 0.5373 | 0.5449 |
| FT-Transformer | 4 | 0.5122 | 0.5476 |
| FT-Transformer | 5 | 0.5018 | 0.5258 |
| FT-Transformer | 6 | 0.4811 | 0.5262 |
| FT-Transformer | 7 | 0.4838 | 0.4890 |
| FT-Transformer | 8 | 0.4662 | 0.4974 |
| FT-Transformer | 9 | 0.4673 | 0.5543 |
| FT-Transformer | 10 | 0.4592 | 0.4895 |
| FT-Transformer | 11 | 0.4490 | 0.4613 |
| FT-Transformer | 12 | 0.4573 | 0.5025 |
| FT-Transformer | 13 | 0.4252 | 0.4801 |
| FT-Transformer | 14 | 0.4304 | 0.5195 |
| FT-Transformer | 15 | 0.4225 | 0.5162 |
| FT-Transformer | 16 | 0.4329 | 0.5181 |
| FT-Transformer | 17 | 0.4126 | 0.5510 |
| FT-Transformer | 18 | 0.4118 | 0.5151 |
| FT-Transformer | 19 | 0.4410 | 0.4905 |
The exact R script · R R version 4.5.1 (2025-06-13)
# FT-Transformer
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.ft_transformer 1.1.2 · spec a41e7646c53429be
# 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 is built by codesplashr's cs_deep_fit_ft twin.
# %% 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(
d_token = 16,
n_blocks = 2,
n_heads = 4,
ffn_factor = 1.3333333333333333,
attention_dropout = 0.2,
ffn_dropout = 0.1,
residual_dropout = 0,
epochs = 30,
learning_rate = 0.001,
batch_size = 64,
weight_decay = 1e-5,
early_stopping = 8,
validation_fraction = 0.1,
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_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.ft_transformer/binary_pima/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 = "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.ft_transformer/binary_pima/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(
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 = "target/academy-parity/run-8142/learn.ft_transformer/binary_pima/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_)
}
# FT-Transformer on torch for R (float64, one thread): every design column becomes a token, a [CLS] token
# is appended, and pre-norm Transformer blocks mix them; the head reads [CLS]. 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 == "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)
}
fit <- cs_deep_fit_ft(
unname(X), target, w, TASK, o,
d_token = as.integer(PARAMS$d_token),
n_blocks = as.integer(PARAMS$n_blocks),
n_heads = as.integer(PARAMS$n_heads),
ffn_factor = PARAMS$ffn_factor,
attention_dropout = PARAMS$attention_dropout,
ffn_dropout = PARAMS$ffn_dropout,
residual_dropout = PARAMS$residual_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
)
fit$mu <- mu
fit$sd <- sd
fit
}
predict_model <- function(model, X) {
p <- cs_deep_ft_predict(model, unname(X), TASK)
if (TASK == "regression") model$mu + model$sd * p else p
}
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 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_deep_extend_ft(cs_ml_result(
run,
title = "FT-Transformer",
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
), model, names_))
FT-Transformer: cross-validated ROC AUC 0.856 ± 0.055 over 3 folds; ROC AUC on the locked test set 0.799 (n = 106).
- CV ROC AUC
- 0.8558
- SD across folds
- 0.0548
- Test ROC AUC
- 0.7988
To keep this page light, the plots are shown once, under the R tab.
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 142 | 0.8938 | 0.4505 | 0.7887 | 0.7292 |
| 2 | 1 | 142 | 0.7931 | 0.5307 | 0.7465 | 0.7245 |
| 3 | 1 | 142 | 0.8805 | 0.4380 | 0.8169 | 0.8005 |
Attention to features
| Feature | Mean [CLS] attention |
|---|---|
| npreg | 0.1453 |
| glu | 0.1356 |
| bmi | 0.1352 |
| bp | 0.1238 |
| ped | 0.1186 |
| age | 0.1153 |
| skin | 0.1127 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| FT-Transformer | 1 | 0.6132 | 0.6554 |
| FT-Transformer | 2 | 0.5701 | 0.5701 |
| FT-Transformer | 3 | 0.5373 | 0.5449 |
| FT-Transformer | 4 | 0.5122 | 0.5476 |
| FT-Transformer | 5 | 0.5018 | 0.5258 |
| FT-Transformer | 6 | 0.4811 | 0.5262 |
| FT-Transformer | 7 | 0.4838 | 0.4890 |
| FT-Transformer | 8 | 0.4662 | 0.4974 |
| FT-Transformer | 9 | 0.4673 | 0.5543 |
| FT-Transformer | 10 | 0.4592 | 0.4895 |
| FT-Transformer | 11 | 0.4490 | 0.4613 |
| FT-Transformer | 12 | 0.4573 | 0.5025 |
| FT-Transformer | 13 | 0.4252 | 0.4801 |
| FT-Transformer | 14 | 0.4304 | 0.5195 |
| FT-Transformer | 15 | 0.4225 | 0.5162 |
| FT-Transformer | 16 | 0.4329 | 0.5181 |
| FT-Transformer | 17 | 0.4126 | 0.5510 |
| FT-Transformer | 18 | 0.4118 | 0.5151 |
| FT-Transformer | 19 | 0.4410 | 0.4905 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# FT-Transformer
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.ft_transformer 1.1.2 · spec a41e7646c53429be
# 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
from codesplash.deep import tabular as deeptab # twin of codesplashr::cs_deep_fit_ft (shared weights, AdamW written out)
# %% 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 = {
"d_token": 16,
"n_blocks": 2,
"n_heads": 4,
"ffn_factor": 1.3333333333333333,
"attention_dropout": 0.2,
"ffn_dropout": 0.1,
"residual_dropout": 0,
"epochs": 30,
"learning_rate": 0.001,
"batch_size": 64,
"weight_decay": 1e-5,
"early_stopping": 8,
"validation_fraction": 0.1,
"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_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.ft_transformer/binary_pima/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="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.ft_transformer/binary_pima/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(
{
"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="target/academy-parity/run-8142/learn.ft_transformer/binary_pima/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)
# FT-Transformer on PyTorch (float64, one thread): every design column becomes a token, a [CLS] token is
# appended, and pre-norm Transformer blocks mix them; the head reads [CLS]. 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 == "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)
fit = deeptab.fit_ft_transformer(
X, target, w, TASK, o,
d_token=int(PARAMS["d_token"]),
n_blocks=int(PARAMS["n_blocks"]),
n_heads=int(PARAMS["n_heads"]),
ffn_factor=PARAMS["ffn_factor"],
attention_dropout=PARAMS["attention_dropout"],
ffn_dropout=PARAMS["ffn_dropout"],
residual_dropout=PARAMS["residual_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,
)
fit.update({"mu": mu, "sd": sd})
return fit
def predict_model(model, X):
p = deeptab.ft_predict(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
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 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(
deeptab.extend_ft(run.result(
title="FT-Transformer",
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,
), model, names)
)
This FT-Transformer normalizes every token of every row on its own, so a row scores the same alone as in a batch. It stopped at epoch 11 of 19, with cross-validated AUC 0.856.
Method guide · learn.tabnetTabNet (attentive feature selection)Predict with a network that picks a few columns at each step and shows which ones it used (PyTorch / R torch).What runs here
Read| Entry | In CodeSplash |
|---|---|
| Batch normalization (TRN007) | Partly runs in CodeSplash: ghost batch norm in TabNet; the image classifier keeps ResNet-50's pretrained statistics fixed. The CNN and torch MLP have no batch-norm layer |
| Layer normalization (TRN008) | Runs in CodeSplash: inside the FT-Transformer, written out so Python and R agree |
| RMS normalization (TRN009) | Explained here: no learner offers it |
Check: normalization layers
CheckpointCheck yourself
A batch has 64 rows and 10 features. Over which numbers does batch norm compute the mean it subtracts from feature 3?
Show the answer
Answer: a
Batch norm standardizes each feature across the batch's rows. The running average over many batches is only used at prediction time.
Check yourself
A model with batch norm scores the same row differently depending on which other rows are in the batch. What went wrong?
Show the answer
Answer: a
At prediction time batch norm must use the stored running mean and variance. Then each row's output depends only on that row.
Check yourself
You fine-tune a pretrained CNN on photos from a different camera. What should you decide about its batch-norm statistics?
Show the answer
Answer: b
The running averages describe the old images. Keeping them is stable with small batches; re-estimating adapts to the new camera. Either way, choose deliberately and check on held-out data.
Check yourself
Why does layer norm behave the same in training and prediction?
Show the answer
Answer: a
Each row's mean and variance come from that row. Nothing about the batch enters, so there's no separate prediction mode.
Check yourself
Where does the FT-Transformer learner apply layer norm?
Show the answer
Answer: a
It normalizes every token on its own before the block's sublayers (pre-norm, the usual Transformer choice; the first block skips it before attention), and the [CLS] token again before the head.
Check yourself
How does RMS norm differ from layer norm?
Show the answer
Answer: a
Dropping the centering saves work. The row's overall scale is still removed, and the learned γ restores the size the next layer needs.
Check yourself
Can you train a network with RMS norm in CodeSplash today?
Show the answer
Answer: c
No learner offers RMS norm yet. The FT-Transformer uses layer norm and TabNet uses ghost batch norm.
Recap
Recap- Batch norm: per feature over the batch, with running averages for prediction; sensitive to batch size and distribution shift.
- Layer norm: per row over its features; same in training and prediction; the Transformer default.
- RMS norm: layer norm without centering.
- In CodeSplash: layer norm in the FT-Transformer, ghost batch norm in TabNet, frozen batch-norm statistics in the image classifier; RMS norm is explained here.
Concepts in this lesson