Skip to content

Sets: Deep Sets and the Set Transformer

When a group of rows has no order, the model's answer shouldn't change if you shuffle them. Deep Sets pools shared encodings with a sum; the Set Transformer lets rows attend to each other and pools with learned seed queries.

Advanced ~14 min8 steps

What runs in CodeSplash

You will be able to

  • State the Deep Sets form ρ(Σ φ(x)) and why the sum makes it order-free
  • Choose between sum, mean, max and attention pooling
  • Explain how a seed query pools a set and why inducing points save memory
  • Count sets, not rows, when you judge how much data a set model has

Read first

01

When order means nothing

Read

A shopping basket, a team, the measurements of one patient on one day: each is a set. Shuffling its rows doesn't change what it is, so a model's answer shouldn't change either. That property is permutation invariancePermutation invarianceShuffling the rows inside a set leaves the prediction unchanged; every set model is built to have it..

A model that predicts one value per row of the set has a weaker rule, permutation equivariancePermutation equivarianceReordering the inputs reorders the outputs the same way and changes nothing else. Attention without positions behaves this way.: shuffle the rows and the outputs shuffle the same way.

Ordinary networks fail both tests: feed the rows in a different order and the answer moves. A set modelSet modelA model for groups of rows whose order doesn't matter (a basket's items, a team's players), one set id per group. is built to pass them.

02

Deep Sets: encode, then sum

Read

Deep SetsDeep SetsEncode every row of a set alone, pool the encodings (mean, sum or max), and predict from the pooled vector. runs every element through the same network ϕ\phi, adds the results and maps the total with a second network ρ\rho:

f(X)=ρ(∑x∈Xϕ(x)).f(X) = \rho\Big(\sum_{x \in X} \phi(x)\Big).

Addition doesn't care about order, so ff is invariant by construction. The reference's three-element example gives 0.277 and 0.768 in either order, and checks it.

Sum keeps how many elements there were; mean drops the count; max keeps the most extreme element.

Reference · SPE005 · Runs in CodeSplashDeep SetsDeep Sets models unordered collections through shared element transformations and symmetric aggregation. It is appropriate when predictions should not depend on input order, such as bags of measurements, variable-sized…
Python
import numpy as np
X = np.array([[1., 0.], [.2, .8], [-.3, .5]]); W = np.array([[.5, .2], [-.1, .7]])
f = lambda A: np.tanh(np.tanh(A @ W).sum(axis=0))   # rho(sum phi(x))
print(f(X), np.allclose(f(X), f(X[[2, 0, 1]])))
R
X <- rbind(c(1, 0), c(.2, .8), c(-.3, .5)); W <- rbind(c(.5, .2), c(-.1, .7))
f <- function(A) tanh(colSums(tanh(A %*% W)))      # rho(sum phi(x))
print(c(f(X), isTRUE(all.equal(f(X), f(X[c(3, 1, 2), ])))))
03

The Set Transformer: attend, then pool

Read

Deep Sets encodes each element alone, so interactions must survive the sum. The Set TransformerSet TransformerA set model whose rows attend to each other before pooling; inducing points make large sets affordable. lets elements attend to each other first; with no positional encoding, attention stays equivariant.

It pools with a learned seed query SS that attends over the elements: PMA(Z)=MAB(S,rFF(Z))\text{PMA}(Z) = \text{MAB}(S, \text{rFF}(Z)). The reference's single seed pools a set to 0.316 and 0.453, unchanged when the rows are shuffled.

Full attention costs grow with the square of the set size. Inducing points route attention through a few learned vectors instead.

Reference · SPE006 · Runs in CodeSplashSet TransformerSet Transformer learns interactions among unordered elements using attention while maintaining permutation-compatible processing and invariant pooling.

Without masks or positions, shuffling the inputs only shuffles the outputs.

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
0

How many of the positions are <pad>.

Width d

Heads

Mask

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

.26.11.08.06.44.06.15.31.04.06.23.21.02.08.44.21.03.22.24.64.02.01.03.06.08.08.62.11.06.05.37.48.03.01.09.03thecatsatonthematthecatsatonthemat
  • 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.

04

Diet from a chick's growth record

Explore
Set model (Deep Sets, Set Transformer)Recorded · Python and R agreeRecorded 2026-11-25 · 36 values compared
R

Set model (Deep Sets, Set Transformer): cross-validated log loss 1.424 ± 0.349 over 3 folds; log loss on the locked test set 1.374 (n = 122).

CV log loss
1.424
SD across folds
0.3487
Test log loss
1.374

Plots

Training curves (final model)Is the network still learning, and when did it start to overfit?
View data
NetworkEpochTraining lossValidation loss
Set model11.3921.383
Set model21.3741.383
Set model31.3631.392
Set model41.3471.404
Set model51.3161.445
Set model61.2821.500
Set model71.2301.474
Set model81.1551.345
Set model91.1301.401
Set model101.0821.642
Set model111.0961.632
Set model121.0521.814
Set model131.0851.759
Set model141.1281.366
Set model151.0641.767
Set model161.1312.074
Set model171.0731.444
Set model181.0441.361
Set model191.0501.503
Set model201.0441.694
Set model211.0221.592
Set model221.0241.498
Set model231.0201.446

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
111521.4220.07890.25000.0366
211511.0760.52320.58330.4167
311531.7730.46410.41940.4294

Training curves

NetworkEpochTraining lossValidation loss
Set model11.3921.383
Set model21.3741.383
Set model31.3631.392
Set model41.3471.404
Set model51.3161.445
Set model61.2821.500
Set model71.2301.474
Set model81.1551.345
Set model91.1301.401
Set model101.0821.642
Set model111.0961.632
Set model121.0521.814
Set model131.0851.759
Set model141.1281.366
Set model151.0641.767
Set model161.1312.074
Set model171.0731.444
Set model181.0441.361
Set model191.0501.503
Set model201.0441.694
Set model211.0221.592
Set model221.0241.498
Set model231.0201.446
The exact R script · R R version 4.5.1 (2025-06-13)
# Set model (Deep Sets, Set Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.set_model 1.1.1 · spec 9af67aeaa1263c2d
# Dataset: ml_chickweight (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_set_model twin.

# %% Data and split plan
TARGET <- "Diet"
FEATURES <- c("weight", "Time")
TASK <- "multiclass"
CLASSES <- c("1", "2", "3", "4")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
  level = "set",
  set_scores = FALSE,
  encoder = "mlp",
  pooling = "mean",
  width = 16,
  enc_layers = 2,
  n_blocks = 1,
  n_heads = 4,
  inducing_points = 0,
  dec_layers = 1,
  dropout = 0,
  epochs = 80,
  learning_rate = 0.01,
  batch_size = 8,
  weight_decay = 0,
  early_stopping = 15,
  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_chickweight.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.set_model/multiclass_chicks_deepsets/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    weight = "numeric",
    Time = "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.set_model/multiclass_chicks_deepsets/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.set_model/multiclass_chicks_deepsets/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 set model on torch for R (float64, one thread): rows that share a set id form a set; an encoder reads
# every row, a permutation-invariant pooling summarizes the set, and a decoder predicts for the set (or for
# each row next to its set's summary). Initial weights, batches of sets, dropout masks and early-stopping
# sets come from the shared random stream, so Python's torch trains the same network.
SET_ID <- "Chick"  # the Set id role (rows of one set also stay in one fold)

# Each input row's set id, or NULL when the input has no set column (e.g. scoring data without it).
read_set_ids <- function() {
  if (is.null(SET_ID)) return(NULL)
  values <- tryCatch(nanoparquet::read_parquet("tests/parity/fixtures/ml_chickweight.parquet", col_select = SET_ID)[[SET_ID]], error = function(e) NULL)
  if (is.null(values)) return(NULL)
  missing <- sum(is.na(values))
  if (missing > 0L) cs_error("CS_E_INVALID_VALUES", column = SET_ID, requirement = "present on every row (it names each row's set)", count = missing)
  if (is.factor(values)) as.character(values) else values
}

SET_VALUES <- read_set_ids()

# Each design matrix the driver makes knows its rows' set ids (attribute cs_sets; rows come from the input's
# row names).
.cs_set_design_apply <- cs_ml_design_apply
cs_ml_design_apply <- function(prep, frame) {
  X <- .cs_set_design_apply(prep, frame)
  if (!is.null(SET_VALUES)) attr(X, "cs_sets") <- SET_VALUES[as.integer(rownames(frame))]
  X
}

sets_of <- function(X, fallback = NULL) {
  s <- attr(X, "cs_sets")
  if (!is.null(s) && length(s) == nrow(X)) return(s)
  if (!is.null(fallback) && length(fallback) == nrow(X)) return(fallback)
  NULL
}

fit_model <- function(X, y, w) {
  sets <- sets_of(X)
  if (is.null(sets)) cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none for set models (rows belong to sets)", 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)
  }
  fit <- cs_deep_fit_set_model(
    unname(as.matrix(X)), sets, target, w, TASK, o,
    target_name = TARGET,
    width = as.integer(PARAMS$width),
    encoder = PARAMS$encoder,
    enc_layers = as.integer(PARAMS$enc_layers),
    n_blocks = as.integer(PARAMS$n_blocks),
    n_heads = as.integer(PARAMS$n_heads),
    inducing_points = as.integer(PARAMS$inducing_points),
    pooling = PARAMS$pooling,
    level = PARAMS$level,
    dec_layers = as.integer(PARAMS$dec_layers),
    dropout = PARAMS$dropout,
    epochs = as.integer(PARAMS$epochs),
    lr = PARAMS$learning_rate,
    batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
    weight_decay = PARAMS$weight_decay,
    early_stopping = as.integer(PARAMS$early_stopping) > 0,
    validation_fraction = PARAMS$validation_fraction,
    patience = max(1L, as.integer(PARAMS$early_stopping)),
    seed = SEED
  )
  fit$mu <- mu
  fit$sd <- sd
  # A set model must not depend on the order of a set's rows: predictions with each set reversed.
  fit$invariance_gap <- cs_deep_set_invariance_gap(fit, unname(as.matrix(X)), sets, TASK)
  fit
}

predict_model <- function(model, X) {
  sets <- sets_of(X, SET_VALUES)
  if (is.null(sets)) {
    cs_error("CS_E_INVALID_VALUES", column = if (is.null(SET_ID)) "Set id" else SET_ID,
             requirement = "in the data (a set model predicts whole sets)", count = nrow(X))
  }
  p <- cs_deep_set_predict(model, unname(as.matrix(X)), sets, 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_set_model(cs_ml_result(
  run,
  title = "Set model (Deep Sets, Set 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

Set model (Deep Sets, Set Transformer): cross-validated log loss 1.424 ± 0.349 over 3 folds; log loss on the locked test set 1.374 (n = 122).

CV log loss
1.424
SD across folds
0.3487
Test log loss
1.374

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

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
111521.4220.07890.25000.0366
211511.0760.52320.58330.4167
311531.7730.46410.41940.4294

Training curves

NetworkEpochTraining lossValidation loss
Set model11.3921.383
Set model21.3741.383
Set model31.3631.392
Set model41.3471.404
Set model51.3161.445
Set model61.2821.500
Set model71.2301.474
Set model81.1551.345
Set model91.1301.401
Set model101.0821.642
Set model111.0961.632
Set model121.0521.814
Set model131.0851.759
Set model141.1281.366
Set model151.0641.767
Set model161.1312.074
Set model171.0731.444
Set model181.0441.361
Set model191.0501.503
Set model201.0441.694
Set model211.0221.592
Set model221.0241.498
Set model231.0201.446
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Set model (Deep Sets, Set Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.set_model 1.1.1 · spec 9af67aeaa1263c2d
# Dataset: ml_chickweight (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 sets as deepsets  # twin of codesplashr::cs_deep_fit_set_model (shared weights, Adam written out)

# %% Data and split plan
TARGET = "Diet"
FEATURES = ["weight", "Time"]
TASK = "multiclass"
CLASSES = ["1", "2", "3", "4"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
    "level": "set",
    "set_scores": False,
    "encoder": "mlp",
    "pooling": "mean",
    "width": 16,
    "enc_layers": 2,
    "n_blocks": 1,
    "n_heads": 4,
    "inducing_points": 0,
    "dec_layers": 1,
    "dropout": 0,
    "epochs": 80,
    "learning_rate": 0.01,
    "batch_size": 8,
    "weight_decay": 0,
    "early_stopping": 15,
    "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_chickweight.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.set_model/multiclass_chicks_deepsets/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "weight": "numeric",
        "Time": "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.set_model/multiclass_chicks_deepsets/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.set_model/multiclass_chicks_deepsets/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 set model on PyTorch (float64, one thread): rows that share a set id form a set; an encoder reads every
# row, a permutation-invariant pooling summarizes the set, and a decoder predicts for the set (or for each
# row next to its set's summary). Initial weights, batches of sets, dropout masks and early-stopping sets
# come from the shared random stream, so R's torch trains the same network.
SET_ID = "Chick"  # the Set id role (rows of one set also stay in one fold)


def read_set_ids():
    """Each input row's set id, or None when the input has no set column (e.g. scoring data without it)."""
    if SET_ID is None:
        return None
    try:
        values = pd.read_parquet("tests/parity/fixtures/ml_chickweight.parquet", columns=[SET_ID])[SET_ID]
    except Exception:  # noqa: BLE001 — the column is not in this input
        return None
    missing = int(values.isna().sum())
    if missing:
        cs.cs_error("CS_E_INVALID_VALUES", column=SET_ID, requirement="present on every row (it names each row's set)", count=missing)
    return values.to_numpy(dtype=object)


SET_VALUES = read_set_ids()


class SetDesign:
    """The driver's design; each design matrix it makes knows its rows' set ids (codesplash.deep.sets.SetRows)."""

    def __init__(self, inner):
        self._inner = inner

    def fit(self, frame):
        return SetPrep(self._inner.fit(frame))

    def __getattr__(self, name):
        return getattr(self._inner, name)


class SetPrep:
    def __init__(self, inner):
        self._inner = inner

    def transform(self, frame):
        return deepsets.with_sets(self._inner.transform(frame), SET_VALUES[frame.index.to_numpy()])

    def __getattr__(self, name):
        return getattr(self._inner, name)


design = SetDesign(design)


def fit_model(X, y, w):
    sets = deepsets.sets_of(X)
    if sets is None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none for set models (rows belong to sets)", 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)
    fit = deepsets.fit_set_model(
        np.asarray(X), sets, target, w, TASK, o,
        target_name=TARGET,
        width=int(PARAMS["width"]),
        encoder=PARAMS["encoder"],
        enc_layers=int(PARAMS["enc_layers"]),
        n_blocks=int(PARAMS["n_blocks"]),
        n_heads=int(PARAMS["n_heads"]),
        inducing_points=int(PARAMS["inducing_points"]),
        pooling=PARAMS["pooling"],
        level=PARAMS["level"],
        dec_layers=int(PARAMS["dec_layers"]),
        dropout=PARAMS["dropout"],
        epochs=int(PARAMS["epochs"]),
        lr=PARAMS["learning_rate"],
        batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
        weight_decay=PARAMS["weight_decay"],
        early_stopping=int(PARAMS["early_stopping"]) > 0,
        validation_fraction=PARAMS["validation_fraction"],
        patience=max(1, int(PARAMS["early_stopping"])),
        seed=SEED,
    )
    fit.update({"mu": mu, "sd": sd})
    # A set model must not depend on the order of a set's rows: predictions with each set reversed.
    fit["invariance_gap"] = deepsets.invariance_gap(fit, np.asarray(X), sets, TASK)
    return fit


def predict_model(model, X):
    sets = deepsets.sets_of(X, SET_VALUES)
    if sets is None:
        cs.cs_error("CS_E_INVALID_VALUES", column=SET_ID or "Set id", requirement="in the data (a set model predicts whole sets)", count=int(np.asarray(X).shape[0]))
    p = deepsets.set_predict(model, np.asarray(X), sets, 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(
    deepsets.extend_set_model(run.result(
        title="Set model (Deep Sets, Set 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)
)

Each chick's weighings form one set, and the target is its diet. Deep Sets with mean pooling names the right diet for 35.5% of held-out chicks. The Invariance gap, the largest change when every set is reversed, is 0 up to rounding.

There are only 39 chicks. Each set is one example, so this is a very small dataset even though it has hundreds of rows.

05

Does attention help here?

Predict

Predict first

The same chicks go through a Set Transformer with attention pooling and four inducing points. What do you expect?

Clearly better than Deep SetsNo clear gain; with so few sets both are noisy
Reveal

No clear gain. Its cross-validated accuracy is 53.1%, with a fold-to-fold SD of 13.1%, but on the locked test chicks it is right for 21.3%, against 50.8% for Deep Sets. With so few sets the scores point both ways. A richer encoder needs more sets, not more rows per set, before its interactions pay off.

Set model (Deep Sets, Set Transformer)Recorded · Python and R agreeRecorded 2026-11-25 · 36 values compared
R

Set model (Deep Sets, Set Transformer): cross-validated log loss 1.378 ± 0.412 over 3 folds; log loss on the locked test set 2.409 (n = 122).

CV log loss
1.378
SD across folds
0.4120
Test log loss
2.409

Plots

Training curves (final model)Is the network still learning, and when did it start to overfit?
View data
NetworkEpochTraining loss
Set model11.385
Set model21.353
Set model31.314
Set model41.272
Set model51.228
Set model61.215
Set model71.159
Set model81.116
Set model91.184
Set model101.153
Set model111.150
Set model121.143
Set model131.099
Set model141.093
Set model151.087
Set model161.086
Set model171.093
Set model181.077
Set model191.069
Set model201.062
Set model211.059
Set model221.049
Set model231.042
Set model241.063
Set model251.037
Set model261.064
Set model271.046
Set model281.018
Set model290.9810
Set model300.9609
Set model310.9624
Set model320.9326
Set model330.9247
Set model340.9360
Set model350.9211
Set model360.8426
Set model370.8861
Set model380.8251
Set model390.9200
Set model400.8225

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
111521.5390.44740.41180.2729
211510.91020.68210.57050.5361
311531.6860.46410.38180.3067

Training curves

NetworkEpochTraining lossValidation loss
Set model11.385—
Set model21.353—
Set model31.314—
Set model41.272—
Set model51.228—
Set model61.215—
Set model71.159—
Set model81.116—
Set model91.184—
Set model101.153—
Set model111.150—
Set model121.143—
Set model131.099—
Set model141.093—
Set model151.087—
Set model161.086—
Set model171.093—
Set model181.077—
Set model191.069—
Set model201.062—
Set model211.059—
Set model221.049—
Set model231.042—
Set model241.063—
Set model251.037—
Set model261.064—
Set model271.046—
Set model281.018—
Set model290.9810—
Set model300.9609—
Set model310.9624—
Set model320.9326—
Set model330.9247—
Set model340.9360—
Set model350.9211—
Set model360.8426—
Set model370.8861—
Set model380.8251—
Set model390.9200—
Set model400.8225—
The exact R script · R R version 4.5.1 (2025-06-13)
# Set model (Deep Sets, Set Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.set_model 1.1.1 · spec e37d59f1c957a003
# Dataset: ml_chickweight (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_set_model twin.

# %% Data and split plan
TARGET <- "Diet"
FEATURES <- c("weight", "Time")
TASK <- "multiclass"
CLASSES <- c("1", "2", "3", "4")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
  level = "set",
  set_scores = FALSE,
  encoder = "attention",
  pooling = "attention",
  width = 8,
  enc_layers = 2,
  n_blocks = 1,
  n_heads = 2,
  inducing_points = 4,
  dec_layers = 1,
  dropout = 0,
  epochs = 40,
  learning_rate = 0.005,
  batch_size = 10,
  weight_decay = 0,
  early_stopping = 0,
  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_chickweight.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.set_model/multiclass_chicks_set_transformer/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    weight = "numeric",
    Time = "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.set_model/multiclass_chicks_set_transformer/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.set_model/multiclass_chicks_set_transformer/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 set model on torch for R (float64, one thread): rows that share a set id form a set; an encoder reads
# every row, a permutation-invariant pooling summarizes the set, and a decoder predicts for the set (or for
# each row next to its set's summary). Initial weights, batches of sets, dropout masks and early-stopping
# sets come from the shared random stream, so Python's torch trains the same network.
SET_ID <- "Chick"  # the Set id role (rows of one set also stay in one fold)

# Each input row's set id, or NULL when the input has no set column (e.g. scoring data without it).
read_set_ids <- function() {
  if (is.null(SET_ID)) return(NULL)
  values <- tryCatch(nanoparquet::read_parquet("tests/parity/fixtures/ml_chickweight.parquet", col_select = SET_ID)[[SET_ID]], error = function(e) NULL)
  if (is.null(values)) return(NULL)
  missing <- sum(is.na(values))
  if (missing > 0L) cs_error("CS_E_INVALID_VALUES", column = SET_ID, requirement = "present on every row (it names each row's set)", count = missing)
  if (is.factor(values)) as.character(values) else values
}

SET_VALUES <- read_set_ids()

# Each design matrix the driver makes knows its rows' set ids (attribute cs_sets; rows come from the input's
# row names).
.cs_set_design_apply <- cs_ml_design_apply
cs_ml_design_apply <- function(prep, frame) {
  X <- .cs_set_design_apply(prep, frame)
  if (!is.null(SET_VALUES)) attr(X, "cs_sets") <- SET_VALUES[as.integer(rownames(frame))]
  X
}

sets_of <- function(X, fallback = NULL) {
  s <- attr(X, "cs_sets")
  if (!is.null(s) && length(s) == nrow(X)) return(s)
  if (!is.null(fallback) && length(fallback) == nrow(X)) return(fallback)
  NULL
}

fit_model <- function(X, y, w) {
  sets <- sets_of(X)
  if (is.null(sets)) cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none for set models (rows belong to sets)", 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)
  }
  fit <- cs_deep_fit_set_model(
    unname(as.matrix(X)), sets, target, w, TASK, o,
    target_name = TARGET,
    width = as.integer(PARAMS$width),
    encoder = PARAMS$encoder,
    enc_layers = as.integer(PARAMS$enc_layers),
    n_blocks = as.integer(PARAMS$n_blocks),
    n_heads = as.integer(PARAMS$n_heads),
    inducing_points = as.integer(PARAMS$inducing_points),
    pooling = PARAMS$pooling,
    level = PARAMS$level,
    dec_layers = as.integer(PARAMS$dec_layers),
    dropout = PARAMS$dropout,
    epochs = as.integer(PARAMS$epochs),
    lr = PARAMS$learning_rate,
    batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
    weight_decay = PARAMS$weight_decay,
    early_stopping = as.integer(PARAMS$early_stopping) > 0,
    validation_fraction = PARAMS$validation_fraction,
    patience = max(1L, as.integer(PARAMS$early_stopping)),
    seed = SEED
  )
  fit$mu <- mu
  fit$sd <- sd
  # A set model must not depend on the order of a set's rows: predictions with each set reversed.
  fit$invariance_gap <- cs_deep_set_invariance_gap(fit, unname(as.matrix(X)), sets, TASK)
  fit
}

predict_model <- function(model, X) {
  sets <- sets_of(X, SET_VALUES)
  if (is.null(sets)) {
    cs_error("CS_E_INVALID_VALUES", column = if (is.null(SET_ID)) "Set id" else SET_ID,
             requirement = "in the data (a set model predicts whole sets)", count = nrow(X))
  }
  p <- cs_deep_set_predict(model, unname(as.matrix(X)), sets, 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_set_model(cs_ml_result(
  run,
  title = "Set model (Deep Sets, Set 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

Set model (Deep Sets, Set Transformer): cross-validated log loss 1.378 ± 0.412 over 3 folds; log loss on the locked test set 2.409 (n = 122).

CV log loss
1.378
SD across folds
0.4120
Test log loss
2.409

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

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
111521.5390.44740.41180.2729
211510.91020.68210.57050.5361
311531.6860.46410.38180.3067

Training curves

NetworkEpochTraining lossValidation loss
Set model11.385—
Set model21.353—
Set model31.314—
Set model41.272—
Set model51.228—
Set model61.215—
Set model71.159—
Set model81.116—
Set model91.184—
Set model101.153—
Set model111.150—
Set model121.143—
Set model131.099—
Set model141.093—
Set model151.087—
Set model161.086—
Set model171.093—
Set model181.077—
Set model191.069—
Set model201.062—
Set model211.059—
Set model221.049—
Set model231.042—
Set model241.063—
Set model251.037—
Set model261.064—
Set model271.046—
Set model281.018—
Set model290.9810—
Set model300.9609—
Set model310.9624—
Set model320.9326—
Set model330.9247—
Set model340.9360—
Set model350.9211—
Set model360.8426—
Set model370.8861—
Set model380.8251—
Set model390.9200—
Set model400.8225—
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Set model (Deep Sets, Set Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.set_model 1.1.1 · spec e37d59f1c957a003
# Dataset: ml_chickweight (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 sets as deepsets  # twin of codesplashr::cs_deep_fit_set_model (shared weights, Adam written out)

# %% Data and split plan
TARGET = "Diet"
FEATURES = ["weight", "Time"]
TASK = "multiclass"
CLASSES = ["1", "2", "3", "4"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
    "level": "set",
    "set_scores": False,
    "encoder": "attention",
    "pooling": "attention",
    "width": 8,
    "enc_layers": 2,
    "n_blocks": 1,
    "n_heads": 2,
    "inducing_points": 4,
    "dec_layers": 1,
    "dropout": 0,
    "epochs": 40,
    "learning_rate": 0.005,
    "batch_size": 10,
    "weight_decay": 0,
    "early_stopping": 0,
    "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_chickweight.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.set_model/multiclass_chicks_set_transformer/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "weight": "numeric",
        "Time": "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.set_model/multiclass_chicks_set_transformer/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.set_model/multiclass_chicks_set_transformer/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 set model on PyTorch (float64, one thread): rows that share a set id form a set; an encoder reads every
# row, a permutation-invariant pooling summarizes the set, and a decoder predicts for the set (or for each
# row next to its set's summary). Initial weights, batches of sets, dropout masks and early-stopping sets
# come from the shared random stream, so R's torch trains the same network.
SET_ID = "Chick"  # the Set id role (rows of one set also stay in one fold)


def read_set_ids():
    """Each input row's set id, or None when the input has no set column (e.g. scoring data without it)."""
    if SET_ID is None:
        return None
    try:
        values = pd.read_parquet("tests/parity/fixtures/ml_chickweight.parquet", columns=[SET_ID])[SET_ID]
    except Exception:  # noqa: BLE001 — the column is not in this input
        return None
    missing = int(values.isna().sum())
    if missing:
        cs.cs_error("CS_E_INVALID_VALUES", column=SET_ID, requirement="present on every row (it names each row's set)", count=missing)
    return values.to_numpy(dtype=object)


SET_VALUES = read_set_ids()


class SetDesign:
    """The driver's design; each design matrix it makes knows its rows' set ids (codesplash.deep.sets.SetRows)."""

    def __init__(self, inner):
        self._inner = inner

    def fit(self, frame):
        return SetPrep(self._inner.fit(frame))

    def __getattr__(self, name):
        return getattr(self._inner, name)


class SetPrep:
    def __init__(self, inner):
        self._inner = inner

    def transform(self, frame):
        return deepsets.with_sets(self._inner.transform(frame), SET_VALUES[frame.index.to_numpy()])

    def __getattr__(self, name):
        return getattr(self._inner, name)


design = SetDesign(design)


def fit_model(X, y, w):
    sets = deepsets.sets_of(X)
    if sets is None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none for set models (rows belong to sets)", 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)
    fit = deepsets.fit_set_model(
        np.asarray(X), sets, target, w, TASK, o,
        target_name=TARGET,
        width=int(PARAMS["width"]),
        encoder=PARAMS["encoder"],
        enc_layers=int(PARAMS["enc_layers"]),
        n_blocks=int(PARAMS["n_blocks"]),
        n_heads=int(PARAMS["n_heads"]),
        inducing_points=int(PARAMS["inducing_points"]),
        pooling=PARAMS["pooling"],
        level=PARAMS["level"],
        dec_layers=int(PARAMS["dec_layers"]),
        dropout=PARAMS["dropout"],
        epochs=int(PARAMS["epochs"]),
        lr=PARAMS["learning_rate"],
        batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
        weight_decay=PARAMS["weight_decay"],
        early_stopping=int(PARAMS["early_stopping"]) > 0,
        validation_fraction=PARAMS["validation_fraction"],
        patience=max(1, int(PARAMS["early_stopping"])),
        seed=SEED,
    )
    fit.update({"mu": mu, "sd": sd})
    # A set model must not depend on the order of a set's rows: predictions with each set reversed.
    fit["invariance_gap"] = deepsets.invariance_gap(fit, np.asarray(X), sets, TASK)
    return fit


def predict_model(model, X):
    sets = deepsets.sets_of(X, SET_VALUES)
    if sets is None:
        cs.cs_error("CS_E_INVALID_VALUES", column=SET_ID or "Set id", requirement="in the data (a set model predicts whole sets)", count=int(np.asarray(X).shape[0]))
    p = deepsets.set_predict(model, np.asarray(X), sets, 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(
    deepsets.extend_set_model(run.result(
        title="Set model (Deep Sets, Set 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)
)
06

What runs here

Read
07

Check: set models

Checkpoint

Check yourself

Why is f(X)=ρ(∑x∈Xϕ(x))f(X) = \rho(\sum_{x \in X} \phi(x)) unchanged when the elements of XX are reordered?

Show the answer

Answer: a

Shared ϕ\phi plus a symmetric sum gives exact invariance, up to floating-point rounding.

Check yourself

The number of items in a basket matters for your prediction. Which pooling keeps that information?

Show the answer

Answer: b

A sum grows with the number of elements. Mean divides it out; max keeps only the largest value of each unit.

Check yourself

A set model is trained on 40 sets with about 12 rows each. How much data does it have?

Show the answer

Answer: b

For set-level targets, the set is the unit. Folds keep each set together, and the effective sample size is the number of sets.

Check yourself

How does pooling by multihead attention (PMA) produce a fixed-size summary of a set of any size?

Show the answer

Answer: a

With k seeds you get k outputs whatever the set size, and reordering the elements doesn't change them.

Check yourself

Why use inducing points in a Set Transformer?

Show the answer

Answer: b

Inducing-point attention (ISAB) trades some interaction capacity for memory and speed on large sets.

Check yourself

A colleague adds positional embeddings to a Set Transformer's inputs. What breaks?

Show the answer

Answer: a

Positions tell the network about an order the data doesn't have. The model is no longer a set model.

08

Recap

Recap
  • Set models give the same answer for any order of a set's elements.
  • Deep Sets: shared encoder, symmetric pooling. Sum keeps counts, mean doesn't, max keeps extremes.
  • The Set Transformer adds attention between elements and pools with learned seeds; inducing points save memory.
  • Count sets, not rows. Both run in CodeSplash as learn.set_model.

Concepts in this lesson