Skip to content

Diffusion for series: TimeGrad forecasts and CSDI imputations

Diffusion models can sample whole futures or fill gaps. TimeGrad denoises the next values conditioned on a recurrent summary of the past; CSDI denoises only the missing entries, conditioned on the observed ones through a mask.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Write TimeGrad's conditional noise-prediction loss and say what the recurrent state carries
  • Compute CSDI's masked denoising loss and explain why the mask must be explicit
  • Tell retrospective imputation from forecasting by what the condition may see
  • Judge diffusion forecasts and imputations against simple baselines

Read first

01

Sampling a future

Read

TimeGradTimeGradA forecaster that draws each next point of all series by denoising, conditioned on a recurrent network's summary of the past. forecasts several related series jointly. A recurrent network summarizes the history in a state ht−1h_{t-1}. A small denoising diffusionDenoising diffusionAdds noise to data in many small steps and trains a network to undo one step; sampling starts from noise and denoises step by step. model, conditioned on that state, learns to turn noise into the next vector of values:

xt(k)=αˉk xt+1−αˉk ϵ,L=E ∥ϵ−ϵθ(xt(k),k,ht−1)∥2.x_t^{(k)} = \sqrt{\bar\alpha_k}\,x_t + \sqrt{1 - \bar\alpha_k}\,\epsilon, \qquad \mathcal{L} = \mathbb{E}\,\big\lVert \epsilon - \epsilon_\theta(x_t^{(k)}, k, h_{t-1}) \big\rVert^2 .

To forecast, it samples the next vector, feeds it into the recurrent state and repeats. Each run is one joint path for all series, so their co-movements survive, which separate per-series intervals lose.

Reference · SEQ001 · Runs in CodeSplashTimeGradA probabilistic multivariate forecasting model combining an autoregressive temporal state with conditional denoising diffusion. It generates distributions of future observations rather than only point estimates.

The noising and sampling loop on a simple one-dimensional target.

DExplorable · Diffusion: noise schedule, sampler steps, guidance

How does a diffusion model turn noise back into data, and what do the schedule, the steps and guidance change?

With this sampler and number of steps, will the samples match the data?

How sure?

β schedule

250

The forward process at this step: how much signal is left.

Sampler

DDPM adds fresh noise every step; DDIM is deterministic.

50
0.0

0 = unconditional, 1 = plain conditional, above 1 = guided.

Class to guide toward

400
  • Noised samples
  • Exact q(xₜ)
  • Samples
  • Data

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.

02

The noise loss by hand

Explore

The reference noises a two-step, two-series block with αˉ=0.7\bar\alpha = 0.7 and scores a denoiser that predicts 0.9 times the true noise. The noise-prediction error is 0.00075. A perfect denoiser would score 0; the loss says how far each prediction is from the noise that was really added.

Python
import numpy as np
clean = np.array([[1., 2.], [1.3, 1.8]]); noise = np.array([[.2, -.4], [.1, .3]])
alpha_bar = .7
noised = np.sqrt(alpha_bar) * clean + np.sqrt(1 - alpha_bar) * noise   # the denoiser's input
predicted = .9 * noise                                                  # a stand-in denoiser
print(np.mean((predicted - noise) ** 2))
R
clean <- rbind(c(1, 2), c(1.3, 1.8)); noise <- rbind(c(.2, -.4), c(.1, .3))
alpha_bar <- .7
noised <- sqrt(alpha_bar) * clean + sqrt(1 - alpha_bar) * noise        # the denoiser's input
predicted <- .9 * noise                                                 # a stand-in denoiser
print(mean((predicted - noise)^2))
03

TimeGrad at teaching scale

Predict

Predict first

A tiny TimeGrad (8 recurrent units, 12 diffusion steps, 30 epochs) forecasts a year of airline passengers. How do you expect it to do against the seasonal naive forecast?

Close to the seasonal naive forecastFar worse than the seasonal naive forecast
Reveal

Far worse. Its MASE is 6.5 and its 80% intervals cover 8.3% of the actual values. A diffusion forecaster this small, on one trending series, hasn't learned the level or the season. More samples only estimate its wrong distribution more precisely. Compare with baselines before reading anything into the paths.

TimeGrad diffusion forecast (joint sample paths)Recorded · Python and R agreeRecorded 2026-11-25 · 28 values compared
R

TimeGrad (12 diffusion steps): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 199 over 1 origin.

MAE
198.79
RMSE
216.48
MAPE
0.4016

Plots

Forecast of passengersWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95monthpassengers
——actual——−662,688,000,000112
——actual——−660,009,600,000118
——actual——−657,590,400,000132
——actual——−654,912,000,000129
——actual——−652,320,000,000121
——actual——−649,641,600,000135
——actual——−647,049,600,000148
——actual——−644,371,200,000148
——actual——−641,692,800,000136
——actual——−639,100,800,000119
——actual——−636,422,400,000104
——actual——−633,830,400,000118
——actual——−631,152,000,000115
——actual——−628,473,600,000126
——actual——−626,054,400,000141
——actual——−623,376,000,000135
——actual——−620,784,000,000125
——actual——−618,105,600,000149
——actual——−615,513,600,000170
——actual——−612,835,200,000170
——actual——−610,156,800,000158
——actual——−607,564,800,000133
——actual——−604,886,400,000114
——actual——−602,294,400,000140
——actual——−599,616,000,000145
——actual——−596,937,600,000150
——actual——−594,518,400,000178
——actual——−591,840,000,000163
——actual——−589,248,000,000172
——actual——−586,569,600,000178
——actual——−583,977,600,000199
——actual——−581,299,200,000199
——actual——−578,620,800,000184
——actual——−576,028,800,000162
——actual——−573,350,400,000146
——actual——−570,758,400,000166
——actual——−568,080,000,000171
——actual——−565,401,600,000180
——actual——−562,896,000,000193
——actual——−560,217,600,000181
——actual——−557,625,600,000183
——actual——−554,947,200,000218
——actual——−552,355,200,000230
——actual——−549,676,800,000242
——actual——−546,998,400,000209
——actual——−544,406,400,000191
——actual——−541,728,000,000172
——actual——−539,136,000,000194
——actual——−536,457,600,000196
——actual——−533,779,200,000196
——actual——−531,360,000,000236
——actual——−528,681,600,000235
——actual——−526,089,600,000229
——actual——−523,411,200,000243
——actual——−520,819,200,000264
——actual——−518,140,800,000272
——actual——−515,462,400,000237
——actual——−512,870,400,000211
——actual——−510,192,000,000180
——actual——−507,600,000,000201

First 60 of 156 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
95.47711959-12-01
79.87921959-12-01
123.9831959-12-01
173.0241959-12-01
188.4651959-12-01
253.9861959-12-01
357.3371959-12-01
352.1481959-12-01
236.9891959-12-01
202.14101959-12-01
138.89111959-12-01
183.18121959-12-01

Assumptions

  • Series end together — Every series has the same time steps, so the joint model sees them side by side.

Backtest accuracy (1 origin, horizon 12)

MetricValue
MAE198.79
RMSE216.48
MAPE0.4016
sMAPE0.5153
MASE6.528
WAPE0.4175
Coverage of the 80% interval0.0833
Coverage of the 95% interval0.2500

Backtest CRPS of the sample paths by horizon

HorizonCRPSForecasts
160.4651
246.7311
387.6491
4137.621
5149.751
6206.481
7318.431
8310.831
9190.841
10159.541
11100.981
12142.621

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01349.73216.18436.75204.19455.90
1961-02-01337.95248.20426.78165.56452.14
1961-03-01319.71233.04419.69197.21471.32
1961-04-01311.59219.67389.17154.46422.06
1961-05-01306.33227.19407.38160.32428.22
1961-06-01302.97193.91427.22108.03479.55
1961-07-01284.48197.94382.78145.48434.63
1961-08-01271.96171.61372.64154.17425.70
1961-09-01290.66189.88412.85114.71439.62
1961-10-01276.82179.07393.23131.63410.60
1961-11-01268.06174.29387.73136.30409.73
1961-12-01265.18165.57368.28130.12407.24
The exact R script · R R version 4.5.1 (2025-06-13)
# TimeGrad diffusion forecast (joint sample paths)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.timegrad 1.0.0 · spec 491c8a00f0aa4a7f
# Dataset: ml_airpassengers (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 and sampler are codesplashr's cs_tg_* twins.

# %% Data
TIME <- "month"
VALUE <- "passengers"
SERIES <- NULL
H <- 12
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL  # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL  # NULL = the horizon
OFFSETS <- NULL  # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL  # NULL = train on all values before each origin
TRAIN_START <- NULL  # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
  hidden_size = 8,
  denoiser_layers = c(16),
  diffusion_steps = 12,
  step_embedding = 8,
  window = NULL,
  samples = 50,
  epochs = 30,
  learning_rate = 0.005,
  batch_size = NULL,
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
  cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
  early <- !is.na(times_all) & times_all < cut
  n_early <- sum(early)
  if (n_early > 0) {
    warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
    times_all[early] <- NA
  }
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.timegrad/single_series/out-r")
extra_tables <- list()  # model blocks may add result tables (assign with <<-)
extra_assumptions <- list()  # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()

# %% 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,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/forecast.timegrad/single_series/out-r")
# TimeGrad: a GRU reads every series together (one vector per time step) and a denoising diffusion model draws the
# next vector given the GRU's state, so the sample paths are joint across series. The driver asks for one series
# and origin at a time, so the model for each origin (its distance from the end of the series) is trained once on
# all series cut at that origin, its paths are drawn once, and each series reads its own column.
.tg_global <- new.env()  # origin offset -> list(model, joint paths S x h x D)
.tg_full <- NULL
.tg_origin <- new.env()  # "series|origin label" -> origin offset, for the sample scores below
.tg_key <- function(key) if (is.null(key) || is.na(key)) "_" else key

.tg_full_series <- function() {
  if (is.null(.tg_full)) {
    full <- list()
    for (key in series_keys) {
      sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
      t_raw <- times_all[sel]; y_raw <- values_all[sel]
      if (sum(!is.na(y_raw)) < 3) next  # too short to use; the driver stops on it with CS_E_TOO_FEW_ROWS
      freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
      reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
      m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
      full[[.tg_key(key)]] <- list(t = reg$t, y = reg$y, m = m)
    }
    .tg_full <<- full
  }
  .tg_full
}

context_length <- function(m) if (!is.null(PARAMS$window)) max(2L, as.integer(PARAMS$window)) else if (m > 1) 2L * as.integer(m) else 8L
min_train <- function(m) context_length(m) + H + 2
prepare_series <- function(y, t, m, freq) {
  cs_check_finite(y, VALUE)  # CS_E_NOT_FINITE, like the Python twin
  NULL
}

fit_forecast <- function(y, t, h, m, levels, spec) {
  full <- .tg_full_series()
  keys <- names(full)
  me <- .tg_key(current_series)
  times <- full[[me]]$t
  d <- length(times) - match(t[length(t)], times)  # values after this origin
  name <- as.character(d)
  if (is.null(.tg_global[[name]])) {
    train <- list()
    for (s in full) {
      o <- length(s$y) - d
      if (o <= 0) stop("a series has no values before this origin")
      start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
      train[[length(train) + 1L]] <- s$y[start:o]
    }
    C <- context_length(m)
    model <- cs_tg_fit(
      train, h,
      context = C,
      hidden = as.integer(PARAMS$hidden_size),
      denoiser = as.integer(unlist(PARAMS$denoiser_layers)),
      diffusion_steps = as.integer(PARAMS$diffusion_steps),
      emb_dim = as.integer(PARAMS$step_embedding),
      epochs = as.integer(PARAMS$epochs),
      lr = PARAMS$learning_rate,
      batch_size = PARAMS$batch_size,
      seed = SEED
    )
    recent <- do.call(cbind, lapply(seq_along(train), function(j) {
      s <- train[[j]]
      (s[(length(s) - C + 1L):length(s)] - model$mu[j]) / model$sd[j]
    }))
    .tg_global[[name]] <- list(model = model, paths = cs_tg_sample(model, recent, h, n_samples = as.integer(PARAMS$samples), seed = SEED))
  }
  g <- .tg_global[[name]]
  model <- g$model
  .tg_origin[[paste0(me, "|", cs_ml_fc_format_time(t[length(t)], TEMPORAL))]] <- d
  P <- matrix(g$paths[, , match(me, keys)], nrow = dim(g$paths)[1])
  mean_ <- vapply(seq_len(h), function(s) sum(P[, s]) / nrow(P), numeric(1))
  lower <- list(); upper <- list()
  for (level in levels) {
    a <- (1 - level / 100) / 2
    lower[[as.character(level)]] <- vapply(seq_len(h), function(s) cs_tg_quantile7(P[, s], a), numeric(1))
    upper[[as.character(level)]] <- vapply(seq_len(h), function(s) cs_tg_quantile7(P[, s], 1 - a), numeric(1))
  }
  list(mean = mean_, lower = lower, upper = upper, fitted = NULL,
       label = sprintf("TimeGrad (%d diffusion steps)", as.integer(PARAMS$diffusion_steps)),
       facts = list(context = as.numeric(model$context), epochs_run = as.numeric(model$epochs_run), final_loss = model$final_loss,
                    series_joint = as.numeric(model$D), windows = as.numeric(model$windows)))
}

# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
  current_series <- key  # model blocks may read it (e.g. table titles)
  sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
  t_raw <- times_all[sel]; y_raw <- values_all[sel]
  if (sum(!is.na(y_raw)) < 3) {  # too few values to read the time step from
    cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
  }
  x_later <- NULL
  if (length(XREG)) {  # rows after the last observed value carry known future regressors
    x_raw <- x_all[sel, , drop = FALSE]
    last_y <- max(t_raw[!is.na(y_raw)])
    later <- t_raw > last_y
    x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
    t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
  }
  freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
  reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
  t <- reg$t; y <- reg$y
  x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
  filled <- filled + reg$filled
  freq_label <- freq$label
  freq_alias <- cs_ml_fc_alias(freq$unit)
  m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
  seasons <- c(seasons, m)
  n <- length(y)
  n_obs <- n_obs + n
  if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
  spec <- prepare_series(y, t, m, freq)
  step <- if (!is.null(STEP)) as.integer(STEP) else H
  if (!is.null(OFFSETS)) {
    origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
    if (length(origins) < length(OFFSETS)) {
      warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
    }
  } else {
    origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
  }
  for (o in origins) {
    start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
    if (length(XREG)) {
      X_TRAIN <- x_grid[start:o, , drop = FALSE]
      X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
    }
    res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
    if (inherits(res, "error")) {
      warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
      next
    }
    n_origins <- n_origins + 1
    scale <- cs_ml_fc_mase_scale(y[1:o], m)
    scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
    lag <- if (m > 1 && o > m) m else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
    for (k in seq_len(H)) {
      row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
                  time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
                  mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
                  snaive = y[o - lag + (k - 1) %% lag + 1])
      for (level in LEVELS) {
        row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
        row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
      }
      bt_rows[[length(bt_rows) + 1]] <- row
    }
  }
  if (length(XREG)) {
    X_TRAIN <- x_grid
    X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
    if (nrow(x_later) < H) {
      warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
    }
  }
  final <- fit_forecast(y, t, H, m, LEVELS, spec)
  labels[[length(labels) + 1]] <- final$label
  for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
  fitted <- final$fitted
  diag <- DIAG[[if (is.null(key)) "_" else key]]
  resid <- diag$resid
  if (is.null(residuals_first) && !is.null(resid)) {
    residuals_first <- as.numeric(resid)
  } else if (is.null(residuals_first) && !is.null(fitted)) {
    ok <- !is.na(fitted)
    residuals_first <- (y - fitted)[ok]
  }
  skey <- if (is.null(key)) NA_character_ else key
  for (i in seq_len(n)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
    if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))]  # the last length(resid) times
    if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
    if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
    fc_rows[[length(fc_rows) + 1]] <- row
    if (!is.null(fitted) && !is.na(fitted[i])) {
      fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
    }
  }
  future <- cs_ml_fc_future_times(t[n], freq, H)
  for (k in seq_len(H)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
    for (level in LEVELS) {
      row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
      row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
    }
    fc_rows[[length(fc_rows) + 1]] <- row
  }
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))

as_frame <- function(rows) {
  cols <- unique(unlist(lapply(rows, names)))
  as.data.frame(stats::setNames(lapply(cols, function(cn) {
    v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
    unlist(v)
  }), cols), stringsAsFactors = FALSE, check.names = FALSE)
}

# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
  n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
  filled = filled, fc_check = wsum(forecasts$mean),
  model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
  freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
  values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
  values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)

nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
  nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
  artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}

# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
  time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
  value = cs_col(VALUE, fan$mean, kind = "numeric"),
  kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
  if (level %in% LEVELS) {
    roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
    roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
  }
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
  charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
    h = cs_col("horizon", bt$h, kind = "numeric"),
    error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
    origin = cs_col("origin", bt$origin, kind = "categorical")
  ))
}
if (length(residuals_first) > 4) {
  lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
  r_acf <- cs_ml_fc_acf(residuals_first, lags)
  bound <- 1.959963984540054 / sqrt(length(residuals_first))
  charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
    lag = cs_col("lag", seq_len(lags), kind = "numeric"),
    acf = cs_col("ACF", r_acf, kind = "numeric"),
    bound = cs_col("bound", rep(bound, lags), kind = "numeric")
  ))
}

# %% Sample scores: the exact CRPS of every backtest forecast's sample, and the energy score of the joint paths
.tg_keys <- names(.tg_full_series())
.tg_ends <- unique(vapply(.tg_full_series(), function(s) sprintf("%d|%.17g", length(s$y), s$t[length(s$t)]), character(1)))
.tg_minlen <- min(vapply(.tg_full_series(), function(s) length(s$y), integer(1)))
extra_assumptions[[length(extra_assumptions) + 1L]] <- list(
  key = "aligned_series", label = "Series end together",
  status = if (length(.tg_ends) <= 1L) "pass" else "warn",
  detail = if (length(.tg_ends) <= 1L) "Every series has the same time steps, so the joint model sees them side by side."
           else sprintf("The series differ in length or end time; they were lined up at their last value and the model used the last %d values they share.", .tg_minlen)
)
.tg_crps <- list()
.tg_joint <- list()
for (r in bt_rows) {
  me <- .tg_key(r$series)
  d <- .tg_origin[[paste0(me, "|", r$origin)]]
  if (is.null(d) || is.null(.tg_global[[as.character(d)]])) next
  paths_d <- .tg_global[[as.character(d)]]$paths
  .tg_crps[[length(.tg_crps) + 1L]] <- c(r$h, cs_tg_crps(paths_d[, r$h, match(me, .tg_keys)], r$actual))
  jk <- sprintf("%08d|%08d", as.integer(d), as.integer(r$h))
  if (is.null(.tg_joint[[jk]])) .tg_joint[[jk]] <- list(d = d, h = r$h, act = list())
  .tg_joint[[jk]]$act[[me]] <- r$actual
}
if (length(.tg_crps)) {
  cm <- do.call(rbind, .tg_crps)
  values$crps_sample <- sum(cm[, 2]) / nrow(cm)
  hs <- sort(unique(cm[, 1]))
  extra_tables[[length(extra_tables) + 1L]] <- list(
    key = "crps_by_horizon",
    title = "Backtest CRPS of the sample paths by horizon",
    columns = list(list(key = "h", label = "Horizon", type = "integer"), list(key = "crps", label = "CRPS", type = "number"),
                   list(key = "n", label = "Forecasts", type = "integer")),
    rows = lapply(hs, function(k) list(h = as.integer(k), crps = sum(cm[cm[, 1] == k, 2]) / sum(cm[, 1] == k), n = sum(cm[, 1] == k)))
  )
}
if (length(.tg_keys) > 1L) {
  es <- numeric(0)
  for (jk in sort(names(.tg_joint))) {
    g <- .tg_joint[[jk]]
    if (length(g$act) != length(.tg_keys)) next
    paths_d <- .tg_global[[as.character(g$d)]]$paths
    es <- c(es, cs_tg_energy(matrix(paths_d[, g$h, ], nrow = dim(paths_d)[1]), vapply(.tg_keys, function(s) g$act[[s]], numeric(1))))
  }
  if (length(es)) values$energy_score <- sum(es) / length(es)
}
if (!is.null(.tg_global[["0"]])) {  # the final forecast's sample paths
  p0 <- .tg_global[["0"]]$paths
  S0 <- dim(p0)[1]
  prow <- list()
  for (j in seq_along(.tg_keys)) for (k in seq_len(H)) {
    prow[[length(prow) + 1L]] <- data.frame(series = if (identical(.tg_keys[j], "_")) NA_character_ else .tg_keys[j], h = k, sample = seq_len(S0), value = p0[, k, j])
  }
  nanoparquet::write_parquet(do.call(rbind, prow), file.path(out, "paths.parquet"))
  artifacts[[length(artifacts) + 1L]] <- list(key = "paths", path = file.path(out, "paths.parquet"), format = "parquet")
}
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
  rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
  for (level in LEVELS) {
    ck <- paste0("coverage_", lv(level))
    if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
  }
  tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
                      columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
             list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
  fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
                             list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
  rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
  title = "TimeGrad diffusion forecast (joint sample paths)",
  engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
  n = n_obs,
  summary = summary,
  statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
  tables = tables,
  values = values,
  assumptions = extra_assumptions,
  warnings = warnings,
  notes = list(),
  charts = charts,
  artifacts = artifacts
))
Python

TimeGrad (12 diffusion steps): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 199 over 1 origin.

MAE
198.79
RMSE
216.48
MAPE
0.4016

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

Assumptions

  • Series end together — Every series has the same time steps, so the joint model sees them side by side.

Backtest accuracy (1 origin, horizon 12)

MetricValue
MAE198.79
RMSE216.48
MAPE0.4016
sMAPE0.5153
MASE6.528
WAPE0.4175
Coverage of the 80% interval0.0833
Coverage of the 95% interval0.2500

Backtest CRPS of the sample paths by horizon

HorizonCRPSForecasts
160.4651
246.7311
387.6491
4137.621
5149.751
6206.481
7318.431
8310.831
9190.841
10159.541
11100.981
12142.621

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01349.73216.18436.75204.19455.90
1961-02-01337.95248.20426.78165.56452.14
1961-03-01319.71233.04419.69197.21471.32
1961-04-01311.59219.67389.17154.46422.06
1961-05-01306.33227.19407.38160.32428.22
1961-06-01302.97193.91427.22108.03479.55
1961-07-01284.48197.94382.78145.48434.63
1961-08-01271.96171.61372.64154.17425.70
1961-09-01290.66189.88412.85114.71439.62
1961-10-01276.82179.07393.23131.63410.60
1961-11-01268.06174.29387.73136.30409.73
1961-12-01265.18165.57368.28130.12407.24
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TimeGrad diffusion forecast (joint sample paths)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.timegrad 1.0.0 · spec 491c8a00f0aa4a7f
# Dataset: ml_airpassengers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.errors import check_finite
from codesplash.deep import timegrad as tg  # twin of codesplashr::cs_tg_* (torch, shared initial weights and draws)

# %% Data
TIME = "month"
VALUE = "passengers"
SERIES = None
H = 12
LEVELS = [float(v) for v in [80, 95]]
SEASON = None  # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None  # None = the horizon
OFFSETS = None  # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None  # None = train on all values before each origin
TRAIN_START = None  # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
    "hidden_size": 8,
    "denoiser_layers": [16],
    "diffusion_steps": 12,
    "step_embedding": 8,
    "window": None,
    "samples": 50,
    "epochs": 30,
    "learning_rate": 0.005,
    "batch_size": None,
    "optimizer": "default",
    "lr_schedule": "none",
    "warmup_epochs": 0,
    "grad_clip": 0,
    "ema_decay": 0,
    "swa_start": 0,
    "history_every_step": False,
    "profile": "parity",
    "checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
    cut = fc.parse_time(TRAIN_START, TEMPORAL)
    early = np.nan_to_num(times_all, nan=np.inf) < cut
    if early.any():
        warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
        times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
    warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None]  # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
    warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
    cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
    cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.timegrad/single_series/out-python")
extra_tables = []  # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = []  # … and assumption rows
current_series = None
X_TRAIN = None  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}


# %% 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,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/forecast.timegrad/single_series/out-python",
)
# TimeGrad: a GRU reads every series together (one vector per time step) and a denoising diffusion model draws the
# next vector given the GRU's state, so the sample paths are joint across series. The driver asks for one series
# and origin at a time, so the model for each origin (its distance from the end of the series) is trained once on
# all series cut at that origin, its paths are drawn once, and each series reads its own column.
_GLOBAL = {}  # origin offset → (model, joint paths S × h × D)
_FULL = {}
_ORIGIN = {}  # (series, origin label) → origin offset, for the sample scores below


def _full_series():
    if not _FULL:
        for key in series_keys:
            sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
            t_raw, y_raw = times_all[sel], values_all[sel]
            if int(np.sum(~np.isnan(y_raw))) < 3:  # too short to use; the driver stops on it with CS_E_TOO_FEW_ROWS
                continue
            freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
            t, y, _ = fc.regularize(t_raw, y_raw, freq)
            m = int(SEASON) if SEASON else int(freq["season"])
            _FULL[key] = ([float(v) for v in t], [float(v) for v in y], m)
    return _FULL


def context_length(m):
    """The option, else two seasons (8 without a season)."""
    return max(2, int(PARAMS["window"])) if PARAMS["window"] else (2 * int(m) if m > 1 else 8)


def min_train(m):
    return context_length(m) + H + 2


def prepare_series(y, t, m, freq):
    check_finite(y, VALUE)  # CS_E_NOT_FINITE, like the R twin
    return None


def fit_forecast(y, t, h, m, levels, spec):
    full = _full_series()
    keys = list(full.keys())
    times = full[current_series][0]
    d = len(times) - (times.index(float(t[-1])) + 1)  # values after this origin
    if d not in _GLOBAL:
        train = []
        for key in keys:
            y_k = full[key][1]
            o = len(y_k) - d
            if o <= 0:
                raise ValueError(f"series {key} has no values before this origin")
            start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
            train.append(y_k[start:o])
        C = context_length(m)
        model = tg.fit_timegrad(
            train, h,
            context=C,
            hidden=int(PARAMS["hidden_size"]),
            denoiser=[int(u) for u in PARAMS["denoiser_layers"]],
            diffusion_steps=int(PARAMS["diffusion_steps"]),
            emb_dim=int(PARAMS["step_embedding"]),
            epochs=int(PARAMS["epochs"]),
            lr=PARAMS["learning_rate"],
            batch_size=PARAMS["batch_size"],
            seed=SEED,
        )
        recent = np.column_stack([[(v - model["mu"][j]) / model["sd"][j] for v in s[len(s) - C :]] for j, s in enumerate(train)])
        _GLOBAL[d] = (model, tg.sample_paths(model, recent, h, n_samples=int(PARAMS["samples"]), seed=SEED))
    model, paths = _GLOBAL[d]
    _ORIGIN[(current_series, fc.format_time(t[-1], TEMPORAL))] = d
    P = paths[:, :, keys.index(current_series)]
    mean = [fc._mean(P[:, s].tolist()) for s in range(h)]
    lower, upper = {}, {}
    for level in levels:
        a = (1.0 - float(level) / 100.0) / 2.0
        lower[level] = [tg.quantile7(P[:, s], a) for s in range(h)]
        upper[level] = [tg.quantile7(P[:, s], 1.0 - a) for s in range(h)]
    return {
        "mean": mean,
        "lower": lower,
        "upper": upper,
        "fitted": None,
        "label": f"TimeGrad ({int(PARAMS['diffusion_steps'])} diffusion steps)",
        "facts": {
            "context": float(model["context"]),
            "epochs_run": float(model["epochs_run"]),
            "final_loss": model["final_loss"],
            "series_joint": float(model["D"]),
            "windows": float(model["windows"]),
        },
    }


# %% Backtests and forecasts
def lv(level):
    return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")


bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
    current_series = key  # model blocks may read it (e.g. table titles)
    sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
    t_raw, y_raw = times_all[sel], values_all[sel]
    if int(np.sum(~np.isnan(y_raw))) < 3:  # too few values to read the time step from
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
    x_later = None
    if XREG:  # rows after the last observed value carry known future regressors
        x_raw = x_all[sel]
        last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
        later = t_raw > last_y
        order_later = np.argsort(t_raw[later], kind="stable")
        x_later = x_raw[later][order_later]
        t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
    freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
    t, y, nfill = fc.regularize(t_raw, y_raw, freq)
    x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
    filled += nfill
    freq_label = freq["label"]
    freq_alias = fc.ALIASES.get(freq["unit"], "")
    m = int(SEASON) if SEASON else int(freq["season"])
    seasons.append(m)
    y = [float(v) for v in y]
    n = len(y)
    n_obs += n
    if n < min_train(m) + 1:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
    spec = prepare_series(y, t, m, freq)
    step = int(STEP) if STEP else H
    if OFFSETS is not None:
        origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
        if len(origins) < len(OFFSETS):
            warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
    else:
        origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
    for o in origins:
        start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
        if XREG:
            X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
        try:
            res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
        except Exception as e:  # a failed origin is skipped, not fatal
            warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
            continue
        n_origins += 1
        scale = fc.mase_scale(y[:o], m)
        scale2 = fc.rmsse_scale(y[:o], m)
        lag = m if (m > 1 and o > m) else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
        for k in range(H):
            row = {
                "series": key,
                "origin": fc.format_time(t[o - 1], TEMPORAL),
                "time": fc.format_time(t[o + k], TEMPORAL),
                "h": k + 1,
                "actual": y[o + k],
                "mean": float(res["mean"][k]),
                "scale": scale,
                "scale2": scale2,
                "last": y[o - 1],
                "snaive": y[o - lag + k % lag],
            }
            for level in LEVELS:
                row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
                row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
            bt_rows.append(row)
    if XREG:
        X_TRAIN = x_grid
        X_FUTURE = fc.future_regressors(x_grid, x_later, H)
        if len(x_later) < H:
            warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
    final = fit_forecast(y, t, H, m, LEVELS, spec)
    labels[key] = final["label"]
    for name, value in final["facts"].items():
        facts[name if not SERIES else f"{name}[{key}]"] = value
    fitted = final.get("fitted")
    diag = DIAG.get(key) or {}
    resid = diag.get("resid")
    if residuals_first is None and resid is not None:
        residuals_first = [float(v) for v in resid]
    elif residuals_first is None and fitted is not None:
        residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
    for i in range(n):
        row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
        if resid is not None and i >= n - len(resid):  # the last len(resid) times (differencing drops early ones)
            row["resid"] = float(resid[i - (n - len(resid))])
        if "fitdf" in diag:
            row["lb_fitdf"] = float(diag["fitdf"])
        if "lags" in diag:
            row["lb_lags"] = float(diag["lags"])
        fc_rows.append(row)
        if fitted is not None and not math.isnan(fitted[i]):
            fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
    future = fc.future_times(t[-1], freq, H)
    for k in range(H):
        row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
        for level in LEVELS:
            row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
            row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
        fc_rows.append(row)
if filled:
    warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")

# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None


def wsum(xs):
    return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)


values = {
    "n_series": len(series_keys),
    "n_obs": n_obs,
    "horizon": H,
    "season": seasons[0],
    "n_origins": n_origins,
    "filled": filled,
    "fc_check": wsum([r["mean"] for r in forecasts]),
    "model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
    "freq_label": freq_label,
    "frequency": freq_alias,
}
if top:
    values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
    values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
    values[f"bt[{k}]"] = v
values.update(facts)

pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
    pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
    artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})

# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
    "time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
    "value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
    "kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
    if level in LEVELS:
        roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
        roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
    roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
    charts.append(
        cs.chart(
            "backtest",
            "backtest-errors",
            "Backtest errors by horizon",
            {
                "h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
                "error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
                "origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
            },
        )
    )
if residuals_first and len(residuals_first) > 4:
    lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
    r_acf = fc.acf(residuals_first, lags)
    bound = 1.959963984540054 / math.sqrt(len(residuals_first))
    charts.append(
        cs.chart(
            "acf",
            "acf-plot",
            "Residual autocorrelation",
            {
                "lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
                "acf": cs.col("ACF", r_acf, kind="numeric"),
                "bound": cs.col("bound", [bound] * lags, kind="numeric"),
            },
        )
    )

# %% Sample scores: the exact CRPS of every backtest forecast's sample, and the energy score of the joint paths
_KEYS = list(_full_series().keys())
_ends = {(len(v[1]), v[0][-1]) for v in _full_series().values()}
extra_assumptions.append({
    "key": "aligned_series",
    "label": "Series end together",
    "status": "pass" if len(_ends) <= 1 else "warn",
    "detail": "Every series has the same time steps, so the joint model sees them side by side." if len(_ends) <= 1
    else f"The series differ in length or end time; they were lined up at their last value and the model used the last {min(n for n, _ in _ends)} values they share.",
})
_crps = []
_joint = {}
for r in bt_rows:
    d = _ORIGIN.get((r["series"], r["origin"]))
    if d is None or d not in _GLOBAL:
        continue
    paths_d = _GLOBAL[d][1]
    _crps.append((r["h"], tg.crps_sample(paths_d[:, r["h"] - 1, _KEYS.index(r["series"])], r["actual"])))
    _joint.setdefault((d, r["h"]), {})[r["series"]] = r["actual"]
if _crps:
    values["crps_sample"] = fc._mean([c for _, c in _crps])
    extra_tables.append({
        "key": "crps_by_horizon",
        "title": "Backtest CRPS of the sample paths by horizon",
        "columns": [{"key": "h", "label": "Horizon", "type": "integer"}, {"key": "crps", "label": "CRPS", "type": "number"}, {"key": "n", "label": "Forecasts", "type": "integer"}],
        "rows": [{"h": k, "crps": fc._mean([c for hh, c in _crps if hh == k]), "n": sum(1 for hh, _ in _crps if hh == k)} for k in range(1, H + 1) if any(hh == k for hh, _ in _crps)],
    })
if len(_KEYS) > 1:
    _es = [tg.energy_score(_GLOBAL[d][1][:, k - 1, :], np.array([act[s] for s in _KEYS])) for (d, k), act in sorted(_joint.items()) if len(act) == len(_KEYS)]
    if _es:
        values["energy_score"] = fc._mean(_es)
if 0 in _GLOBAL:  # the final forecast's sample paths
    _paths0 = _GLOBAL[0][1]
    _rows = []
    for j, key in enumerate(_KEYS):
        for k in range(H):
            for s in range(_paths0.shape[0]):
                _rows.append({"series": key, "h": k + 1, "sample": s + 1, "value": float(_paths0[s, k, j])})
    pd.DataFrame(_rows).to_parquet(os.path.join(out, "paths.parquet"), index=False)
    artifacts.append({"key": "paths", "path": os.path.join(out, "paths.parquet"), "format": "parquet"})
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
    tables.append(
        {
            "key": "accuracy",
            "title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
            "columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
            "rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
            + [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
        }
    )
tables.extend(extra_tables)
tables.append(
    {
        "key": "forecast",
        "title": "Forecast",
        "columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
        + [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
        + [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
        "rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
    }
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
    summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
    {
        "title": "TimeGrad diffusion forecast (joint sample paths)",
        "engine": cs.engine_info("torch", "codesplash", "numpy", "pandas"),
        "n": n_obs,
        "summary": summary,
        "statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
        "tables": tables,
        "values": values,
        "assumptions": extra_assumptions,
        "warnings": warnings,
        "notes": [],
        "charts": charts,
        "artifacts": artifacts,
    }
)

Its sample CRPS, 159.3, is a proper score for the whole forecast distribution; compare it across models on the same backtest.

04

CSDI: diffusion that fills gaps

Read

CSDICSDI (conditional score-based diffusion imputation)Imputes series by denoising each gap from random noise, conditioned on every observed value, several times over. imputes missing values in multivariate series. During training it hides some observed entries on purpose and splits the rest into an observed set MobsM_{obs}, which conditions the model, and a target set MtargetM_{target}, which it learns to denoise. The loss counts only target entries:

L=E[∑i∈Mtarget(ϵi−ϵθ(xt,t,xobs,Mobs)i)2/∣Mtarget∣].\mathcal{L} = \mathbb{E}\Big[\sum_{i \in M_{target}} \big(\epsilon_i - \epsilon_\theta(x_t, t, x_{obs}, M_{obs})_i\big)^2 \big/ |M_{target}|\Big].

Running the reverse process several times gives several plausible fills for each gap. The mask is an input: writing missing values as zeros without a mask would confuse a gap with a real zero.

Reference · SEQ002 · Runs in CodeSplashCSDI: conditional score-based diffusion imputationA conditional diffusion approach producing distributions for missing values in multivariate time series. It trains using observed/context masks and target masks, allowing several plausible imputations instead of one…
05

A masked loss by hand

Explore

The reference scores a denoiser that predicts 0.8 times the noise, but only on the two target entries of a 2×2 block. The masked error is 0.0034; the observed entries don't count.

Python
import numpy as np
noise = np.array([[.2, -.4], [.1, .3]]); predicted = .8 * noise
target = np.array([[False, True], [True, False]])          # entries the model must fill
print(np.mean((predicted[target] - noise[target]) ** 2))
R
noise <- rbind(c(.2, -.4), c(.1, .3)); predicted <- .8 * noise
target <- rbind(c(FALSE, TRUE), c(TRUE, FALSE))            # entries the model must fill
print(mean((predicted[target] - noise[target])^2))
06

Does CSDI beat a straight line?

Explore
Diffusion imputation for multivariate series (CSDI)Recorded · Python and R agreeRecorded 2026-11-25 · 21 values compared
R

0 missing values in 2 variables were imputed 5 times by conditional diffusion (CSDI). On 95 hidden values the median imputation's MAE was 1.08 (linear interpolation 0.783).

MAE on hidden values
1.079

Plots

Hidden values and their imputationsWhich observations fall outside their prediction intervals, and how wide are the intervals?

95 observed values hidden before training, grouped by variable; bars are 90% intervals of the 5 draws.

View data
ActualHidden valueInterval lowerMedian imputationInterval upper
2.6851−2.057−0.25151.721
2.0612−0.1999−0.12452.979
1.9273−0.21000.33940.9665
−0.09004−3.6740.73371.579
0.59835−0.96440.53432.312
1.2926−4.2620.25694.837
1.0777−1.540−0.50381.556
0.38818−1.598−0.61153.760
−1.3429−1.624−0.12521.227
−2.52910−2.348−1.080−0.0344
−0.285611−1.360−0.66541.456
1.85412−3.201−1.283−0.1464
0.861413−2.388−1.3651.384
1.64414−2.7951.1891.589
−0.240315−2.785−1.8431.929
−0.852116−2.120−0.06141.591
−1.17717−2.153−1.837−1.339
0.796118−1.4960.69044.201
0.056619−2.822−0.00670.4965
−0.444620−4.265−0.39051.216
−0.522421−1.0690.32832.290
−0.613922−2.812−1.361−0.6052
−1.32623−3.5950.86003.602
1.37224−1.102−0.27394.191
−1.31825−3.010−0.24120.5942
0.664226−1.4830.47314.141
0.634127−0.61550.96631.340
−0.341628−2.240−0.8087−0.1309
0.060229−0.8382−0.56741.829
0.823330−2.271−0.89940.6844
−1.46631−1.554−1.0930.7502
−0.446432−3.345−1.4452.529
−1.41033−0.34582.5683.824
0.227634−2.235−0.8200−0.1624
−0.239635−1.1880.21421.714
−1.41336−1.778−0.30361.412
0.993637−0.7709−0.12493.443
0.565338−1.504−0.7204−0.0807
−0.833539−2.960−1.1010.5895
−0.638240−0.95260.89461.471
−1.40541−0.6785−0.46202.091
0.178342−0.41420.34874.962
0.895143−0.08131.0682.744
1.10544−1.545−0.66182.488
−0.085345−1.493−0.85980.9202
−0.274846−1.363−0.53612.487
0.521047−0.4644−0.10424.104
0.684148−2.3611.5393.850
−0.178049−0.54111.5742.602
2.77150−0.85760.02702.080
0.636151−1.278−0.05111.110
0.705352−1.9290.66971.026
−0.857053−0.8664−0.61972.892
−0.800554−2.5720.01230.6071
−1.66055−1.149−0.70340.3651
−0.9770560.14760.26631.769
−0.371357−1.911−1.4010.9401
−0.349558−1.0970.06711.318
1.02159−1.2340.13203.443
2.20960−2.769−0.52453.127

First 60 of 95 rows.

Denoising loss by epochIs the network still learning, and which part of its loss moves?

Mean squared error of the predicted noise on the target cells; lower is better.

View data
PartLoss (mean squared noise error)Epoch
training windows0.96251
training windows1.0422
training windows0.91933
training windows0.94934
training windows0.92065
training windows0.85656
training windows0.84677
training windows0.83848

Assumptions

  • Better than straight-line filling — On 95 hidden values the median imputation's mean absolute error is 1.08 against 0.783 for linear interpolation. A simpler method may serve as well; train longer or use more layers.
  • Missing at random — The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.
  • Enough observed values — The variable with the most gaps is 0% missing.

Imputed variables

VariableMissingObserved meanImputed mean (median draws)Mean 90% interval width
y10−0.0640——
y20−0.0732——

Imputed values (first 0)

RowVariableMedianLowerUpper
  • No values are missing; the completed data sets equal the data.
  • Seed 42; the 5 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact R script · R R version 4.5.1 (2025-06-13)
# Diffusion imputation for multivariate series (CSDI)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.csdi 1.0.0 · spec 07c0f186e36fa3ff
# Dataset: f7_var_panel (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_csdi_* (score network on torch, shared draws), cs_ml_fc_to_days

# 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,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/missing.csdi/panel_two_layers_time/out-r")

# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES <- c("y1", "y2")
TIME <- "month"
SERIES <- "region"
SEED <- 42
M <- as.integer(5)
LEVEL <- 0.9
cols <- unique(c(VARIABLES, TIME, SERIES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_var_panel.parquet", col_select = cols))
n <- nrow(df)
K <- length(VARIABLES)
warnings <- list()
cs_check_finite_columns(df, c(VARIABLES, TIME))  # infinite values stop the run (registry/errors.yaml)
values_raw <- do.call(cbind, lapply(VARIABLES, function(v) suppressWarnings(as.numeric(df[[v]]))))
values_raw <- matrix(values_raw, nrow = n, ncol = K)
for (j in seq_len(K)) if (all(is.na(values_raw[, j]))) cs_error("CS_E_ALL_MISSING", column = VARIABLES[j])
cs_check_rows(n, 4, "CSDI imputation")
times <- NULL
if (!is.null(TIME)) {
  times <- cs_ml_fc_to_days(df[[TIME]])$values
  if (any(is.na(times))) cs_error("CS_E_INVALID_VALUES", column = TIME, requirement = "present on every row (it orders the rows)", count = sum(is.na(times)))
}
series <- NULL
if (!is.null(SERIES)) {
  s <- df[[SERIES]]
  if (sum(is.na(s))) cs_error("CS_E_INVALID_VALUES", column = SERIES, requirement = "present on every row (it names each row's series)", count = sum(is.na(s)))
  series <- as.character(s)
}
if (8 %% 4 != 0) {
  cs_error("CS_E_INVALID_OPTION", option = "Attention heads", allowed = "a divisor of the channels (8)", value = 4)
}
groups <- cs_csdi_grids(values_raw, series, times)
observed <- !is.na(values_raw)
L <- min(as.integer(12), min(vapply(groups, length, integer(1))))
if (L < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Every series", min = 2, n = L)

# Hidden cells for the evaluation (a seeded share of the observed cells, row by row).
SHARE <- 0.2
hidden <- matrix(FALSE, n, K)
if (SHARE > 0) {
  u <- matrix(cs_runif(cs_rng(SEED + 404), n * K), nrow = n, ncol = K, byrow = TRUE)
  hidden <- observed & (u < SHARE)
}
known <- observed & !hidden
st <- cs_csdi_standardize(values_raw, known)
mu <- st$mu; sd <- st$sd
v0 <- values_raw; v0[is.na(v0)] <- 0
std <- sweep(sweep(v0, 2L, mu, "-"), 2L, sd, "/")
Z <- ifelse(known, std, 0)

# %% Train the score network and impute
model <- cs_csdi_fit(
  Z, known, groups, L,
  channels = 8,
  layers = 2,
  heads = 4,
  diffusion_steps = 6,
  online = FALSE,
  epochs = 8,
  lr = 0.005,
  batch_size = 64,
  seed = SEED
)
values <- list(n = n, n_vars = K, m = M, window_length = L, windows = model$windows, epochs_run = model$epochs_run, final_loss = model$final_loss)
assumptions <- list()
charts <- list()
tables <- list()
unstd <- function(d) { for (j in seq_len(K)) d[, , j] <- d[, , j] * sd[j] + mu[j]; d }
if (any(hidden)) {
  ev <- unstd(cs_csdi_impute(model, Z, known, groups, M, SEED + 505))
  sm <- cs_csdi_summarize(ev, LEVEL)
  interp <- cs_csdi_interpolate(values_raw, known, groups)
  idx <- which(t(hidden), arr.ind = TRUE)  # row by row, as in Python
  cells <- cbind(idx[, 2], idx[, 1])
  truth <- values_raw[cells]
  err <- abs(sm$med[cells] - truth)
  values$eval_n <- nrow(cells)
  values$eval_mae <- sum(err) / length(err)
  values$eval_rmse <- sqrt(sum(err * err) / length(err))
  values$eval_crps <- sum(vapply(seq_len(nrow(cells)), function(q) cs_tg_crps(ev[, cells[q, 1], cells[q, 2]], truth[q]), numeric(1))) / nrow(cells)
  values$eval_coverage <- sum(as.numeric(sm$lo[cells] <= truth & truth <= sm$hi[cells])) / nrow(cells)
  ip <- interp[cells]
  ierr <- abs(ip - truth)[!is.na(ip)]
  if (length(ierr)) values$interp_mae <- sum(ierr) / length(ierr)
  for (j in seq_len(K)) {
    e_j <- err[cells[, 2] == j]
    if (length(e_j)) values[[sprintf("eval_mae[%s]", VARIABLES[j])]] <- sum(e_j) / length(e_j)
  }
  better <- !is.null(values$interp_mae) && values$eval_mae <= values$interp_mae
  assumptions[[length(assumptions) + 1L]] <- list(
    key = "beats_interpolation", label = "Better than straight-line filling",
    status = if (better) "pass" else "warn",
    detail = paste0(sprintf("On %d hidden values the median imputation's mean absolute error is %s", nrow(cells), format(signif(values$eval_mae, 3))),
                    if (!is.null(values$interp_mae)) sprintf(" against %s for linear interpolation.", format(signif(values$interp_mae, 3))) else ".",
                    if (better) "" else " A simpler method may serve as well; train longer or use more layers.")
  )
  ord <- order(cells[, 2], cells[, 1])[seq_len(min(400L, nrow(cells)))]
  charts[[length(charts) + 1L]] <- cs_chart("evaluation", "interval-plot", "Hidden values and their imputations", list(
    index = cs_col("Hidden value", seq_along(ord), "numeric"),
    actual = cs_col("Actual", truth[ord], "numeric"),
    pred = cs_col("Median imputation", sm$med[cells[ord, , drop = FALSE]], "numeric"),
    lower = cs_col("Interval lower", sm$lo[cells[ord, , drop = FALSE]], "numeric"),
    upper = cs_col("Interval upper", sm$hi[cells[ord, , drop = FALSE]], "numeric")
  ), note = sprintf("%d observed values hidden before training, grouped by variable; bars are %s intervals of the %d draws.", length(ord), sprintf("%.0f%%", LEVEL * 100), M))
}
Zall <- ifelse(observed, std, 0)  # every observed cell conditions the final draws
draws <- unstd(cs_csdi_impute(model, Zall, observed, groups, M, SEED + 303))
for (s in seq_len(M)) draws[s, , ][observed] <- values_raw[observed]
sm <- cs_csdi_summarize(draws, LEVEL)
missing <- !observed
values$n_missing <- sum(missing)
values$pct_missing <- sum(missing) / (n * K)
imp_rows <- list()
for (j in seq_len(K)) {
  v <- VARIABLES[j]
  mj <- missing[, j]
  values[[sprintf("missing[%s]", v)]] <- sum(mj)
  ob <- values_raw[observed[, j], j]
  values[[sprintf("observed_mean[%s]", v)]] <- sum(ob) / length(ob)
  if (any(mj)) {
    values[[sprintf("imputed_mean[%s]", v)]] <- sum(sm$med[mj, j]) / sum(mj)
    values[[sprintf("interval_width[%s]", v)]] <- sum(sm$hi[mj, j] - sm$lo[mj, j]) / sum(mj)
  }
  imp_rows[[j]] <- list(variable = v, missing = sum(mj), observed = values[[sprintf("observed_mean[%s]", v)]],
                        imputed = values[[sprintf("imputed_mean[%s]", v)]], width = values[[sprintf("interval_width[%s]", v)]])
}
if (!any(missing)) warnings <- c(warnings, "No values are missing; the completed data sets equal the data.")
share_max <- max(colMeans(missing))
assumptions[[length(assumptions) + 1L]] <- list(
  key = "mar", label = "Missing at random", status = "info",
  detail = "The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased."
)
assumptions[[length(assumptions) + 1L]] <- list(
  key = "enough_observed", label = "Enough observed values",
  status = if (share_max > 0.5) "warn" else "pass",
  detail = paste0(sprintf("The variable with the most gaps is %s missing", sprintf("%.0f%%", share_max * 100)),
                  if (share_max > 0.5) " — over half, so its imputations lean on the other variables and the model's guesses." else ".")
)

# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out <- cs_ml_out_dir("target/academy-parity/run-8142/missing.csdi/panel_two_layers_time/out-r")
parts <- lapply(seq_len(M), function(s) {
  part <- data.frame(.imp = rep(s, n), .id = seq_len(n), check.names = FALSE)
  for (j in seq_len(K)) part[[VARIABLES[j]]] <- draws[s, , j]
  part
})
path <- file.path(out, "imputed.parquet")
nanoparquet::write_parquet(do.call(rbind, parts), path)
cidx <- which(missing, arr.ind = TRUE)
cidx <- cidx[order(cidx[, 2], cidx[, 1]), , drop = FALSE][seq_len(min(200L, nrow(cidx))), , drop = FALSE]
hist <- model$history
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Denoising loss by epoch", list(
  x = cs_col("Epoch", vapply(hist, function(h) as.numeric(h$epoch), numeric(1)), "numeric"),
  value = cs_col("Loss (mean squared noise error)", vapply(hist, function(h) h$loss, numeric(1)), "numeric"),
  component = cs_col("Part", rep("training windows", length(hist)), "categorical", levels = c("training windows"))
), note = "Mean squared error of the predicted noise on the target cells; lower is better.")
tables[[length(tables) + 1L]] <- list(key = "imputation", title = "Imputed variables",
  columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "missing", label = "Missing", type = "integer"),
                 list(key = "observed", label = "Observed mean", type = "number"), list(key = "imputed", label = "Imputed mean (median draws)", type = "number"),
                 list(key = "width", label = sprintf("Mean %s interval width", sprintf("%.0f%%", LEVEL * 100)), type = "number")),
  rows = imp_rows)
tables[[length(tables) + 1L]] <- list(key = "cells", title = sprintf("Imputed values (first %d)", nrow(cidx)),
  columns = list(list(key = "row", label = "Row", type = "integer"), list(key = "variable", label = "Variable", type = "string"),
                 list(key = "median", label = "Median", type = "number"), list(key = "low", label = "Lower", type = "number"),
                 list(key = "high", label = "Upper", type = "number")),
  rows = lapply(seq_len(nrow(cidx)), function(q) list(row = cidx[q, 1], variable = VARIABLES[cidx[q, 2]], median = sm$med[cidx[q, , drop = FALSE]],
                                                     low = sm$lo[cidx[q, , drop = FALSE]], high = sm$hi[cidx[q, , drop = FALSE]])))
summary <- sprintf("%d missing values in %d variable%s were imputed %d times by conditional diffusion (CSDI).", values$n_missing, K, if (K != 1) "s" else "", M)
if (!is.null(values$eval_mae)) {
  summary <- paste0(summary, sprintf(" On %d hidden values the median imputation's MAE was %s", values$eval_n, format(signif(values$eval_mae, 3))),
                    if (!is.null(values$interp_mae)) sprintf(" (linear interpolation %s).", format(signif(values$interp_mae, 3))) else ".")
}
cs_publish(list(
  title = "Diffusion imputation for multivariate series (CSDI)",
  engine = cs_engine_info("torch", "nanoparquet", "codesplashr"),
  n = n,
  summary = summary,
  statistics = if (!is.null(values$eval_mae)) list(list(key = "eval_mae", label = "MAE on hidden values", value = values$eval_mae)) else list(),
  tables = tables,
  values = values,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Seed %d; the %d completed data sets are saved as imputed.parquet (long format with .imp and .id).", SEED, M)),
  charts = charts,
  artifacts = list(list(key = "imputed", path = path, format = "parquet", title = sprintf("%d imputed data sets (long format)", M)))
))
Python

0 missing values in 2 variables were imputed 5 times by conditional diffusion (CSDI). On 95 hidden values the median imputation's MAE was 1.08 (linear interpolation 0.783).

MAE on hidden values
1.079

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

Assumptions

  • Better than straight-line filling — On 95 hidden values the median imputation's mean absolute error is 1.08 against 0.783 for linear interpolation. A simpler method may serve as well; train longer or use more layers.
  • Missing at random — The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.
  • Enough observed values — The variable with the most gaps is 0% missing.

Imputed variables

VariableMissingObserved meanImputed mean (median draws)Mean 90% interval width
y10−0.0640——
y20−0.0732——

Imputed values (first 0)

RowVariableMedianLowerUpper
  • No values are missing; the completed data sets equal the data.
  • Seed 42; the 5 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Diffusion imputation for multivariate series (CSDI)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.csdi 1.0.0 · spec 07c0f186e36fa3ff
# Dataset: f7_var_panel (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.deep import csdi  # twin of codesplashr::cs_csdi_* (score network on torch, shared draws)
from codesplash.ml import forecast as fc  # times as days; sequential sums
from codesplash.ml import run as csml  # artifact directory
from codesplash.stats.rng import Rng

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,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/missing.csdi/panel_two_layers_time/out-python",
)

# %% Data (no rows are dropped: the missing values are imputed)
VARIABLES = ["y1", "y2"]
TIME = "month"
SERIES = "region"
SEED = 42
M = 5
LEVEL = 0.9
cols = list(dict.fromkeys(VARIABLES + [c for c in (TIME, SERIES) if c]))
df = pd.read_parquet("tests/parity/fixtures/f7_var_panel.parquet", columns=cols)
n = len(df)
K = len(VARIABLES)
warnings = []
cs.check_finite_columns(df, VARIABLES + ([TIME] if TIME else []))  # infinite values stop the run (registry/errors.yaml)
values_raw = np.column_stack([pd.to_numeric(df[v], errors="coerce").to_numpy(dtype=np.float64) for v in VARIABLES])
for j, v in enumerate(VARIABLES):
    if bool(np.isnan(values_raw[:, j]).all()):
        cs.cs_error("CS_E_ALL_MISSING", column=v)
cs.check_rows(n, 4, "CSDI imputation")
times = None
if TIME:
    times = fc.to_days(df[TIME].to_numpy())[0]
    if bool(np.isnan(times).any()):
        cs.cs_error("CS_E_INVALID_VALUES", column=TIME, requirement="present on every row (it orders the rows)", count=int(np.isnan(times).sum()))
series = None
if SERIES:
    s = df[SERIES]
    if int(s.isna().sum()):
        cs.cs_error("CS_E_INVALID_VALUES", column=SERIES, requirement="present on every row (it names each row's series)", count=int(s.isna().sum()))
    series = s.astype(str).to_numpy(dtype=object)
if 8 % 4 != 0:
    cs.cs_error("CS_E_INVALID_OPTION", option="Attention heads", allowed="a divisor of the channels (8)", value=4)
groups = csdi.grids(values_raw, series, times)
observed = ~np.isnan(values_raw)
L = min(int(12), min(len(g) for g in groups))
if L < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Every series", min=2, n=L)

# Hidden cells for the evaluation (a seeded share of the observed cells, row by row).
SHARE = 0.2
hidden = np.zeros_like(observed)
if SHARE > 0:
    u = Rng(SEED + 404).uniform(n * K).reshape(n, K)
    hidden = observed & (u < SHARE)
known = observed & ~hidden
mu, sd = csdi.standardize(values_raw, known)
Z = np.where(known, (np.nan_to_num(values_raw) - mu) / sd, 0.0)

# %% Train the score network and impute
model = csdi.fit_csdi(
    Z, known, groups, L,
    channels=8,
    layers=2,
    heads=4,
    diffusion_steps=6,
    online=False,
    epochs=8,
    lr=0.005,
    batch_size=64,
    seed=SEED,
)
values = {"n": n, "n_vars": K, "m": M, "window_length": L, "windows": model["windows"], "epochs_run": model["epochs_run"], "final_loss": model["final_loss"]}
assumptions = []
charts = []
tables = []
evaluation = None
if bool(hidden.any()):
    ev = csdi.impute(model, Z, known, groups, M, SEED + 505) * sd + mu
    med, lo, hi = csdi.summarize(ev, LEVEL)
    interp = csdi.interpolate(values_raw, known, groups)
    cells = [(i, j) for i in range(n) for j in range(K) if hidden[i, j]]
    truth = [values_raw[i, j] for i, j in cells]
    err = [abs(med[i, j] - t) for (i, j), t in zip(cells, truth)]
    values["eval_n"] = len(cells)
    values["eval_mae"] = fc._mean(err)
    values["eval_rmse"] = math.sqrt(fc._mean([e * e for e in err]))
    values["eval_crps"] = fc._mean([csdi.crps(ev[:, i, j], t) for (i, j), t in zip(cells, truth)])
    values["eval_coverage"] = fc._mean([1.0 if lo[i, j] <= t <= hi[i, j] else 0.0 for (i, j), t in zip(cells, truth)])
    ierr = [abs(interp[i, j] - t) for (i, j), t in zip(cells, truth) if not math.isnan(interp[i, j])]
    if ierr:
        values["interp_mae"] = fc._mean(ierr)
    for j, v in enumerate(VARIABLES):
        e_j = [e for (i, jj), e in zip(cells, err) if jj == j]
        if e_j:
            values[f"eval_mae[{v}]"] = fc._mean(e_j)
    better = "interp_mae" in values and values["eval_mae"] <= values["interp_mae"]
    assumptions.append({
        "key": "beats_interpolation",
        "label": "Better than straight-line filling",
        "status": "pass" if better else "warn",
        "detail": (f"On {len(cells)} hidden values the median imputation's mean absolute error is {values['eval_mae']:.3g}"
                   + (f" against {values['interp_mae']:.3g} for linear interpolation." if "interp_mae" in values else ".")
                   + ("" if better else " A simpler method may serve as well; train longer or use more layers.")),
    })
    order = sorted(range(len(cells)), key=lambda c: (cells[c][1], cells[c][0]))[:400]
    charts.append(cs.chart("evaluation", "interval-plot", "Hidden values and their imputations", {
        "index": cs.col("Hidden value", list(range(1, len(order) + 1)), "numeric"),
        "actual": cs.col("Actual", [truth[c] for c in order], "numeric"),
        "pred": cs.col("Median imputation", [float(med[cells[c]]) for c in order], "numeric"),
        "lower": cs.col("Interval lower", [float(lo[cells[c]]) for c in order], "numeric"),
        "upper": cs.col("Interval upper", [float(hi[cells[c]]) for c in order], "numeric"),
    }, note=f"{len(order)} observed values hidden before training, grouped by variable; bars are {LEVEL:.0%} intervals of the {M} draws."))
Zall = np.where(observed, (np.nan_to_num(values_raw) - mu) / sd, 0.0)  # every observed cell conditions the final draws
draws = csdi.impute(model, Zall, observed, groups, M, SEED + 303)
draws = np.where(observed[None, :, :], values_raw[None, :, :], draws * sd + mu)
med, lo, hi = csdi.summarize(draws, LEVEL)
missing = ~observed
values["n_missing"] = int(missing.sum())
values["pct_missing"] = float(missing.sum()) / float(n * K)
imp_rows = []
for j, v in enumerate(VARIABLES):
    mj = missing[:, j]
    values[f"missing[{v}]"] = int(mj.sum())
    values[f"observed_mean[{v}]"] = fc._mean(values_raw[observed[:, j], j].tolist())
    if mj.any():
        values[f"imputed_mean[{v}]"] = fc._mean(med[mj, j].tolist())
        values[f"interval_width[{v}]"] = fc._mean((hi[mj, j] - lo[mj, j]).tolist())
    imp_rows.append({"variable": v, "missing": int(mj.sum()), "observed": values[f"observed_mean[{v}]"], "imputed": values.get(f"imputed_mean[{v}]"),
                     "width": values.get(f"interval_width[{v}]")})
if not missing.any():
    warnings.append("No values are missing; the completed data sets equal the data.")
share_max = max(float(missing[:, j].mean()) for j in range(K))
assumptions.append({
    "key": "mar",
    "label": "Missing at random",
    "status": "info",
    "detail": "The imputations are valid when whether a value is missing depends only on observed values (MAR); if values are missing because of what they would have been (MNAR), the imputations are biased.",
})
assumptions.append({
    "key": "enough_observed",
    "label": "Enough observed values",
    "status": "warn" if share_max > 0.5 else "pass",
    "detail": f"The variable with the most gaps is {share_max:.0%} missing" + (" — over half, so its imputations lean on the other variables and the model's guesses." if share_max > 0.5 else "."),
})

# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out = csml.out_dir("target/academy-parity/run-8142/missing.csdi/panel_two_layers_time/out-python")
parts = []
for s in range(M):
    part = {".imp": np.full(n, s + 1), ".id": np.arange(1, n + 1)}
    for j, v in enumerate(VARIABLES):
        part[v] = draws[s, :, j]
    parts.append(pd.DataFrame(part))
path = os.path.join(out, "imputed.parquet")
pd.concat(parts, ignore_index=True).to_parquet(path, index=False)
cells = [(i, j) for j in range(K) for i in range(n) if missing[i, j]][:200]
hist = model["history"]
charts.append(cs.chart("training", "training-components", "Denoising loss by epoch", {
    "x": cs.col("Epoch", [h["epoch"] for h in hist], "numeric"),
    "value": cs.col("Loss (mean squared noise error)", [h["loss"] for h in hist], "numeric"),
    "component": cs.col("Part", ["training windows"] * len(hist), "categorical", levels=["training windows"]),
}, note="Mean squared error of the predicted noise on the target cells; lower is better."))
tables.append({"key": "imputation", "title": "Imputed variables",
               "columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "missing", "label": "Missing", "type": "integer"},
                           {"key": "observed", "label": "Observed mean", "type": "number"}, {"key": "imputed", "label": "Imputed mean (median draws)", "type": "number"},
                           {"key": "width", "label": f"Mean {LEVEL:.0%} interval width", "type": "number"}],
               "rows": imp_rows})
tables.append({"key": "cells", "title": f"Imputed values (first {len(cells)})",
               "columns": [{"key": "row", "label": "Row", "type": "integer"}, {"key": "variable", "label": "Variable", "type": "string"},
                           {"key": "median", "label": "Median", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                           {"key": "high", "label": "Upper", "type": "number"}],
               "rows": [{"row": i + 1, "variable": VARIABLES[j], "median": float(med[i, j]), "low": float(lo[i, j]), "high": float(hi[i, j])} for i, j in cells]})
summary = f"{values['n_missing']} missing values in {K} variable{'s' if K != 1 else ''} were imputed {M} times by conditional diffusion (CSDI)."
if "eval_mae" in values:
    summary += f" On {values['eval_n']} hidden values the median imputation's MAE was {values['eval_mae']:.3g}"
    summary += f" (linear interpolation {values['interp_mae']:.3g})." if "interp_mae" in values else "."
cs.publish({
    "title": "Diffusion imputation for multivariate series (CSDI)",
    "engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [{"key": "eval_mae", "label": "MAE on hidden values", "value": values["eval_mae"]}] if "eval_mae" in values else [],
    "tables": tables,
    "values": values,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Seed {SEED}; the {M} completed data sets are saved as imputed.parquet (long format with .imp and .id)."],
    "charts": charts,
    "artifacts": [{"key": "imputed", "path": path, "format": "parquet", "title": f"{M} imputed data sets (long format)"}],
})

Here CSDI hides 95 observed values before training and scores them afterwards. Its median imputation's MAE is 1.08, against 0.78 for straight-line filling: after a short training run, the simple method wins. Its 90% intervals cover 75.8% of the hidden values.

That built-in check is why Hidden share for checking exists. Keep the simpler fill when the diffusion model doesn't beat it.

07

What the condition may see

Read

Both models condition on context, and the context sets the honest use:

  • Retrospective imputation may use values after the gap. CSDI's default, Conditioning: Past and future, does.
  • Forecasting or online filling may use only the past. A model trained with later values in its condition can't be used live; train with Past only instead.

Imputations are draws from a model, not the missing values. Analyze each of the mm completed datasets and pool the results, as with multiple imputationMultiple imputationFills each gap several plausible ways, analyses every completed dataset and pools the results, so the uncertainty from the gaps stays in., and remember that masking at random in training doesn't make missingness that depends on the missing value harmless.

08

What runs here

Read
09

Check: diffusion for series

Checkpoint

Check yourself

What conditions TimeGrad's denoiser at each forecast step?

Show the answer

Answer: a

The recurrent state carries the past; the denoiser generates the next vector given it.

Check yourself

Why are TimeGrad's sample paths useful for related series?

Show the answer

Answer: b

Separate per-series intervals lose the dependence between series. Joint paths keep it, and multivariate scores test it.

Check yourself

A TimeGrad forecast is badly biased. Will drawing more sample paths fix it?

Show the answer

Answer: b

Sample count controls Monte Carlo precision, not the learned distribution.

Check yourself

Why does CSDI take an explicit mask instead of filling gaps with zeros?

Show the answer

Answer: a

The mask tells the model which entries are observed context and which are targets.

Check yourself

Which entries contribute to CSDI's training loss?

Show the answer

Answer: c

Target entries are observed values hidden during training, so the model has a truth to score against. Truly missing ones have none.

Check yourself

CSDI was trained to impute gaps using values from both sides. Can you use it to fill the latest values in a live dashboard?

Show the answer

Answer: b

Retrospective and online imputation have different information boundaries. Train and evaluate for the one you need.

10

Recap

Recap
  • TimeGrad: a recurrent state conditions a denoiser that samples joint future paths.
  • CSDI: denoise only the masked target entries, conditioned on observed ones.
  • Both can lose to simple baselines; check with backtests and hidden values.
  • Imputations are draws, not data. Both run in CodeSplash.

Concepts in this lesson