Skip to content

Feature tokens and row attention: FT-Transformer and SAINT

FT-Transformer turns every column into its own token and lets attention mix them. SAINT adds attention across rows, which makes a prediction depend on its batch. Build both by hand and read FT-Transformer's attention on Pima.

Advanced ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Tokenize a numeric column with its own weight and bias, and say why column identity survives
  • Explain what one attention layer over feature tokens computes
  • Show with a worked example that row attention makes a row's output depend on its companions
  • Say what a fair comparison with trees needs

Read first

01

A token per column

Read

A Transformer reads a sequence of vectors. A table row has no such sequence, so FT-Transformer makes one. Its feature tokenizerFeature tokenizerTurning each feature into a learned vector (b + x·W), so a Transformer can treat the columns of a table like the words of a sentence. turns numeric column jj into a vector with that column's own weight and bias:

tj=bj+xj wj,t_j = b_j + x_j\,w_j ,

and a categorical column into a learned embedding plus a bias. A class token joins the column tokens, Transformer blocks mix them, and the class token's final vector feeds the prediction head.

Because each column has its own wjw_j and bjb_j, the network knows which column a token came from without any order.

Reference · SPE002 · Runs in CodeSplashFeature Tokenizer Transformer (FT-Transformer)FT-Transformer converts individual tabular features into tokens and models their interactions through transformer blocks.
02

One attention pass by hand

Read

The reference tokenizes a row with three numbers into 2-wide tokens. The second column, x2=1.2x_2 = 1.2, becomes the token (0.84, 0.08). One attention pass then mixes all three tokens; the first token comes out as (0.374, 0.064), a weighted blend of every column.

Python
import numpy as np
def sm(a): e = np.exp(a - a.max(axis=-1, keepdims=True)); return e / e.sum(axis=-1, keepdims=True)
x = np.array([.4, 1.2, -.5])
W = np.array([[.2, .5], [.7, -.1], [.3, .4]]); b = np.array([[.1, 0], [0, .2], [.2, .1]])
tokens = x[:, None] * W + b                       # one token per column
mixed = sm(tokens @ tokens.T / np.sqrt(2)) @ tokens
print(tokens, mixed)
R
sm <- function(a) { e <- exp(a - apply(a, 1, max)); e / rowSums(e) }
x <- c(.4, 1.2, -.5)
W <- rbind(c(.2, .5), c(.7, -.1), c(.3, .4)); b <- rbind(c(.1, 0), c(0, .2), c(.2, .1))
tokens <- x * W + b                               # one token per column
mixed <- sm(tokens %*% t(tokens) / sqrt(2)) %*% tokens
print(list(tokens = tokens, mixed = mixed))
03

FT-Transformer on Pima

Explore
FT-TransformerRecorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

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

Plots

Training curves (final model)Is the network still learning, and when did it start to overfit?
View data
NetworkEpochTraining lossValidation loss
FT-Transformer10.61320.6554
FT-Transformer20.57010.5701
FT-Transformer30.53730.5449
FT-Transformer40.51220.5476
FT-Transformer50.50180.5258
FT-Transformer60.48110.5262
FT-Transformer70.48380.4890
FT-Transformer80.46620.4974
FT-Transformer90.46730.5543
FT-Transformer100.45920.4895
FT-Transformer110.44900.4613
FT-Transformer120.45730.5025
FT-Transformer130.42520.4801
FT-Transformer140.43040.5195
FT-Transformer150.42250.5162
FT-Transformer160.43290.5181
FT-Transformer170.41260.5510
FT-Transformer180.41180.5151
FT-Transformer190.44100.4905
Attention from [CLS] to each featureWhich features does the model rely on most?
View data
FeatureMean attention
npreg0.1453
glu0.1356
bmi0.1352
bp0.1238
ped0.1186
age0.1153
skin0.1127

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.89380.45050.78870.7292
211420.79310.53070.74650.7245
311420.88050.43800.81690.8005

Attention to features

FeatureMean [CLS] attention
npreg0.1453
glu0.1356
bmi0.1352
bp0.1238
ped0.1186
age0.1153
skin0.1127

Training curves

NetworkEpochTraining lossValidation loss
FT-Transformer10.61320.6554
FT-Transformer20.57010.5701
FT-Transformer30.53730.5449
FT-Transformer40.51220.5476
FT-Transformer50.50180.5258
FT-Transformer60.48110.5262
FT-Transformer70.48380.4890
FT-Transformer80.46620.4974
FT-Transformer90.46730.5543
FT-Transformer100.45920.4895
FT-Transformer110.44900.4613
FT-Transformer120.45730.5025
FT-Transformer130.42520.4801
FT-Transformer140.43040.5195
FT-Transformer150.42250.5162
FT-Transformer160.43290.5181
FT-Transformer170.41260.5510
FT-Transformer180.41180.5151
FT-Transformer190.44100.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_))
Python

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

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111420.89380.45050.78870.7292
211420.79310.53070.74650.7245
311420.88050.43800.81690.8005

Attention to features

FeatureMean [CLS] attention
npreg0.1453
glu0.1356
bmi0.1352
bp0.1238
ped0.1186
age0.1153
skin0.1127

Training curves

NetworkEpochTraining lossValidation loss
FT-Transformer10.61320.6554
FT-Transformer20.57010.5701
FT-Transformer30.53730.5449
FT-Transformer40.51220.5476
FT-Transformer50.50180.5258
FT-Transformer60.48110.5262
FT-Transformer70.48380.4890
FT-Transformer80.46620.4974
FT-Transformer90.46730.5543
FT-Transformer100.45920.4895
FT-Transformer110.44900.4613
FT-Transformer120.45730.5025
FT-Transformer130.42520.4801
FT-Transformer140.43040.5195
FT-Transformer150.42250.5162
FT-Transformer160.43290.5181
FT-Transformer170.41260.5510
FT-Transformer180.41180.5151
FT-Transformer190.44100.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)
)

Two blocks with 16-wide tokens reach a cross-validated AUC of 0.856 and a test AUC of 0.799.

The class token's average attention is spread almost evenly: glucose gets 0.136 and skin fold 0.113. Attention says where one layer pooled information, not which column drives diabetes; later layers and the head can reweigh everything.

04

SAINT: attention across rows too

Read

SAINTSAINTA table network that attends across the columns of a row and across the rows of a batch, often pretrained with contrastive views. keeps attention over a row's columns and adds intersample attentionIntersample attentionAttention in which each row reads the other rows of its batch, so a row's prediction depends on which rows came with it.: each row's representation attends to the other rows in its batch. It is often pretrained on unlabeled rows with contrastive and denoising objectives before the supervised head is fitted.

Row attention can borrow strength from similar rows. It also means a prediction depends on which rows came with it, so the context batch becomes part of the model.

Reference · SPE003 · Partly runs in CodeSplashSAINTSAINT uses both feature attention and attention across rows, with a contrastive pretraining option for tabular data.

Attention weights, masks and heads on a handful of tokens.

DExplorable · Attention: scores, masks and heads

Where does each word look, and what do the scaling and the masks change?

With this mask, how much of each word's attention lands on <pad>?

How sure?
6
2

How many of the positions are <pad>.

Width d

Heads

Mask

Without masks or positions the output rows shuffle the same way.

.51.22.16.11.00.00.27.55.07.10.00.00.02.10.59.28.00.00.26.71.02.01.00.00.09.09.69.13.00.00.42.54.03.01.00.00thecatsaton<pad><pad>thecatsaton<pad><pad>
  • Little weight
  • Most weight
  • Masked: score set to −∞

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

05

A companion row changes the answer

Predict

Predict first

Three rows pass through one row-attention layer. Then only row 3 is changed. What happens to row 1's output?

Row 1's output stays the sameRow 1's output changes
Reveal

It changes. In the reference's example row 1 comes out as (0.615, 0.385) first and (2.379, −0.646) after row 3 moves. So evaluate SAINT on the same test rows with several valid context batches, and never let test labels into a batch.

06

What runs here

Read
07

Check: tokens and rows

Checkpoint

Check yourself

FT-Transformer has no positional encoding over columns. How does it know which column a token came from?

Show the answer

Answer: a

tj=bj+xjwjt_j = b_j + x_j w_j with column-specific wj,bjw_j, b_j (an embedding table for categories) keeps column identity without imposing an order.

Check yourself

With x2=1.2x_2 = 1.2, weight w2=(0.7,−0.1)w_2 = (0.7, -0.1) and bias b2=(0,0.2)b_2 = (0, 0.2), what is the first value of the token t2=b2+x2w2t_2 = b_2 + x_2 w_2?

Show the answer

Answer: 0.84

0+1.2×0.70 + 1.2 \times 0.7. The second value is 0.2+1.2×(−0.1)0.2 + 1.2 \times (-0.1).

Check yourself

FT-Transformer beats boosted trees by a hair on one random split. What would make the comparison fair?

Show the answer

Answer: b

The reference calls for matched tuning and leakage-safe splits. A gap smaller than the fold-to-fold spread is not a win.

Check yourself

Why must you report how SAINT's context batches were built at prediction time?

Show the answer

Answer: b

Row attention makes the companions part of the input. Different valid batches can give different predictions for the same row.

Check yourself

Which practice leaks information when evaluating SAINT?

Show the answer

Answer: a

Test labels must never enter context. Pretraining on permitted unlabeled rows and trying several batches are both fine.

Check yourself

SAINT beats FT-Transformer on your table. Which follow-up tells you why?

Show the answer

Answer: b

The reference asks to separate the gains: pretraining, row attention and compute can each explain the difference.

08

Recap

Recap
  • FT-Transformer gives each column its own tokenizer, then mixes tokens with attention.
  • Attention weights describe pooling, not causes.
  • SAINT adds attention across rows: predictions depend on the batch, so report and vary it.
  • FT-Transformer runs in CodeSplash; SAINT's row attention is explained here.

Concepts in this lesson