Skip to content

Transformers for forecasting: PatchTST and the Temporal Fusion Transformer

Two attention-based forecasters, PatchTST (patches, every step at once) and the Temporal Fusion Transformer (covariates, quantiles), plus adaptive conformal intervals for series whose errors change.

Advanced ~16 min9 steps

What runs in CodeSplash

You will be able to

  • Explain patching and per-window normalization, and why PatchTST forecasts every step at once
  • Read the Temporal Fusion Transformer's quantile intervals, variable importance and attention
  • Say what variable importance does and doesn't tell you
  • Choose between split and adaptive conformal intervals in the Uncertainty tab

Read first

01

Attention for time series

Read

A Transformer lets every position of its input look at every other position and decide how much each matters (self-attentionSelf-attentionEach token builds its next value as a weighted mix of all tokens, with weights from how well their keys match its query.). For time series the question is what a "position" is. Two answers:

  • PatchTST cuts the recent past into short patches and treats each patch as one token.
  • The Temporal Fusion Transformer (TFT) keeps one position per time step but first decides, at every step, which inputs matter.

Both are trained on your data, in both engines, from the same starting weights, so Python and R give the same forecasts. Both are Experimental: small networks that need a backtest to earn their place beside the baselines.

02

PatchTST: patches and one forecast for every step

Read
PatchTST forecast (patch Transformer)Recorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

PatchTST (12 patches of 4, stride 2): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 15.4 over 2 origins.

MAE
15.372
RMSE
18.791
MAPE
0.0334

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
0.764111958-12-01
−9.48721958-12-01
23.34631958-12-01
−11.78841958-12-01
−6.44251958-12-01
−29.74961958-12-01
−13.93671958-12-01
−13.28481958-12-01
−29.05491958-12-01
3.538101958-12-01
−2.637111958-12-01
10.830121958-12-01
19.03111959-12-01
1.21321959-12-01
−38.63331959-12-01
7.19241959-12-01
−15.16651959-12-01
−27.26361959-12-01
−4.71371959-12-01
−29.09481959-12-01
−32.46891959-12-01
9.044101959-12-01
−8.853111959-12-01
−21.391121959-12-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.02600.17891
0.17900.17892
0.15530.17893
−0.12190.17894
0.13900.17895
−0.10650.17896
0.04610.17897
−0.15940.17898
0.14410.17899
0.06760.178910
−0.17780.178911
0.23920.178912
−0.19020.178913
0.11960.178914
−0.01520.178915
−0.23730.178916
0.08880.178917
−0.23520.178918
0.04840.178919
−0.13110.178920
0.07080.178921
0.09720.178922
0.06840.178923
0.28050.178924

Backtest accuracy (2 origins, horizon 12)

MetricValue
MAE15.372
RMSE18.791
MAPE0.0334
sMAPE0.0329
MASE0.5187
WAPE0.0340
Coverage of the 80% interval0.6667
Coverage of the 95% interval0.8333

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01438.22422.52453.93414.20462.25
1961-02-01422.97407.69438.24399.60446.33
1961-03-01473.94458.12489.75449.75498.13
1961-04-01501.30482.65519.95472.78529.82
1961-05-01528.25509.36547.13499.36557.13
1961-06-01598.50578.26618.74567.55629.46
1961-07-01680.46661.07699.86650.81710.12
1961-08-01689.68668.68710.68657.56721.79
1961-09-01590.26568.47612.05556.94623.58
1961-10-01500.74479.85521.64468.79532.70
1961-11-01447.37425.28469.47413.58481.16
1961-12-01487.00465.08508.93453.47520.53
The exact R script · R R version 4.5.1 (2025-06-13)
# PatchTST forecast (patch Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.patchtst 1.0.0 · spec 06cf24fba9e3a013
# 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 is codesplashr's cs_ptst_* twin.

# %% 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 <- 2
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(
  window = NULL,
  patch_len = NULL,
  stride = NULL,
  d_model = 16,
  heads = 2,
  layers = 2,
  epochs = 40,
  learning_rate = 0.005,
  batch_size = NULL,
  weight_decay = 0,
  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.patchtst/monthly_defaults_small/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.patchtst/monthly_defaults_small/out-r")
# PatchTST: ONE Transformer trained on the windows of every series (channel independence). Each window is
# instance-normalized, cut into patches that become tokens, and a flatten head forecasts every step at once. The
# driver asks for one series and origin at a time, so the network for each origin (its distance from the end of the
# series) is trained once on all series cut at that origin and reused for every series.
.ptst_global <- new.env()
.ptst_full <- NULL

.ptst_full_series <- function() {
  if (is.null(.ptst_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)
      full[[if (is.null(key)) "_" else key]] <- list(t = reg$t, y = reg$y)
    }
    .ptst_full <<- full
  }
  .ptst_full
}

min_train <- function(m) cs_ptst_window_length(PARAMS$window, H, m) + H + 9L
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 <- .ptst_full_series()
  times <- full[[if (is.null(current_series)) "_" else current_series]]$t
  d <- length(times) - match(t[length(t)], times)  # values after this origin
  name <- as.character(d)
  if (is.null(.ptst_global[[name]])) {
    train <- list()
    for (s in full) {
      o <- length(s$y) - d
      if (o <= 0) next
      start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
      train[[length(train) + 1L]] <- s$y[start:o]
    }
    .ptst_global[[name]] <- cs_ptst_fit_global(
      train, h,
      window = cs_ptst_window_length(PARAMS$window, h, m),
      patch_len = PARAMS$patch_len,
      stride = PARAMS$stride,
      d_model = as.integer(PARAMS$d_model),
      heads = as.integer(PARAMS$heads),
      layers = as.integer(PARAMS$layers),
      epochs = as.integer(PARAMS$epochs),
      lr = PARAMS$learning_rate,
      batch_size = PARAMS$batch_size,
      weight_decay = PARAMS$weight_decay,
      seed = SEED
    )
  }
  cs_ptst_forecast(.ptst_global[[name]], y, h, levels)
}

# %% 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")
  ))
}

# %% 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 = "PatchTST forecast (patch Transformer)",
  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

PatchTST (12 patches of 4, stride 2): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 15.4 over 2 origins.

MAE
15.372
RMSE
18.791
MAPE
0.0334

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

Backtest accuracy (2 origins, horizon 12)

MetricValue
MAE15.372
RMSE18.791
MAPE0.0334
sMAPE0.0329
MASE0.5187
WAPE0.0340
Coverage of the 80% interval0.6667
Coverage of the 95% interval0.8333

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01438.22422.52453.93414.20462.25
1961-02-01422.97407.69438.24399.60446.33
1961-03-01473.94458.12489.75449.75498.13
1961-04-01501.30482.65519.95472.78529.82
1961-05-01528.25509.36547.13499.36557.13
1961-06-01598.50578.26618.74567.55629.46
1961-07-01680.46661.07699.86650.81710.12
1961-08-01689.68668.68710.68657.56721.79
1961-09-01590.26568.47612.05556.94623.58
1961-10-01500.74479.85521.64468.79532.70
1961-11-01447.37425.28469.47413.58481.16
1961-12-01487.00465.08508.93453.47520.53
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# PatchTST forecast (patch Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.patchtst 1.0.0 · spec 06cf24fba9e3a013
# 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 patchtst  # twin of codesplashr::cs_ptst_* (torch, shared initial weights)

# %% 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 = 2
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 = {
    "window": None,
    "patch_len": None,
    "stride": None,
    "d_model": 16,
    "heads": 2,
    "layers": 2,
    "epochs": 40,
    "learning_rate": 0.005,
    "batch_size": None,
    "weight_decay": 0,
    "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.patchtst/monthly_defaults_small/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.patchtst/monthly_defaults_small/out-python",
)
# PatchTST: ONE Transformer trained on the windows of every series (channel independence). Each window is
# instance-normalized, cut into patches that become tokens, and a flatten head forecasts every step at once. The
# driver asks for one series and origin at a time, so the network for each origin (its distance from the end of the
# series) is trained once on all series cut at that origin and reused for every series.
_GLOBAL = {}
_FULL = {}


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)
            _FULL[key] = ([float(v) for v in t], [float(v) for v in y])
    return _FULL


def min_train(m):
    return patchtst.window_length(PARAMS["window"], H, m) + H + 9


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()
    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 t_k, y_k in full.values():
            o = len(y_k) - d
            if o <= 0:
                continue
            start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
            train.append(y_k[start:o])
        _GLOBAL[d] = patchtst.fit_global(
            train, h,
            window=patchtst.window_length(PARAMS["window"], h, m),
            patch_len=PARAMS["patch_len"],
            stride=PARAMS["stride"],
            d_model=int(PARAMS["d_model"]),
            heads=int(PARAMS["heads"]),
            layers=int(PARAMS["layers"]),
            epochs=int(PARAMS["epochs"]),
            lr=PARAMS["learning_rate"],
            batch_size=PARAMS["batch_size"],
            weight_decay=PARAMS["weight_decay"],
            seed=SEED,
        )
    return patchtst.forecast(_GLOBAL[d], list(y), h, levels)


# %% 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"),
            },
        )
    )

# %% 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": "PatchTST forecast (patch Transformer)",
        "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,
    }
)

PatchTSTPatchTSTA Transformer that reads the recent past as short patches (tokens) and forecasts every step ahead at once. takes the last 24 months, centers them on their own mean and divides by their own spread (reversible instance normalizationReversible instance normalizationEach input window is centered on its own mean and scaled by its own spread; forecasts are mapped back the same way.). It then cuts them into 12 overlapping patches of 4 values. Attention runs over the patches, and one linear layer forecasts all 12 months at once. No prediction is fed back as an input, so an early error can't snowball.

The backtest MASE is 0.52. Compare it with the seasonal naive baseline in a forecast experiment before trusting it.

03

One network for many series

Read
PatchTST forecast (patch Transformer)Recorded · Python and R agreeRecorded 2026-11-25 · 40 values compared
R

2 series, one model each: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 61.4 over 2 origins.

MAE
61.440
RMSE
83.568
MAPE
0.0746

Plots

Forecast of deathsWhere is the series heading, and how uncertain is the forecast?
View data
kindsexmonthdeaths
actualfemale126,230,400,000901
actualfemale128,908,800,000689
actualfemale131,328,000,000827
actualfemale134,006,400,000677
actualfemale136,598,400,000522
actualfemale139,276,800,000406
actualfemale141,868,800,000441
actualfemale144,547,200,000393
actualfemale147,225,600,000387
actualfemale149,817,600,000582
actualfemale152,496,000,000578
actualfemale155,088,000,000666
actualfemale157,766,400,000830
actualfemale160,444,800,000752
actualfemale162,864,000,000785
actualfemale165,542,400,000664
actualfemale168,134,400,000467
actualfemale170,812,800,000438
actualfemale173,404,800,000421
actualfemale176,083,200,000412
actualfemale178,761,600,000343
actualfemale181,353,600,000440
actualfemale184,032,000,000531
actualfemale186,624,000,000771
actualfemale189,302,400,000767
actualfemale191,980,800,0001,141
actualfemale194,486,400,000896
actualfemale197,164,800,000532
actualfemale199,756,800,000447
actualfemale202,435,200,000420
actualfemale205,027,200,000376
actualfemale207,705,600,000330
actualfemale210,384,000,000357
actualfemale212,976,000,000445
actualfemale215,654,400,000546
actualfemale218,246,400,000764
actualfemale220,924,800,000862
actualfemale223,603,200,000660
actualfemale226,022,400,000663
actualfemale228,700,800,000643
actualfemale231,292,800,000502
actualfemale233,971,200,000392
actualfemale236,563,200,000411
actualfemale239,241,600,000348
actualfemale241,920,000,000387
actualfemale244,512,000,000385
actualfemale247,190,400,000411
actualfemale249,782,400,000638
actualfemale252,460,800,000796
actualfemale255,139,200,000853
actualfemale257,558,400,000737
actualfemale260,236,800,000546
actualfemale262,828,800,000530
actualfemale265,507,200,000446
actualfemale268,099,200,000431
actualfemale270,777,600,000362
actualfemale273,456,000,000387
actualfemale276,048,000,000430
actualfemale278,726,400,000425
actualfemale281,318,400,000679

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
−6.65911979-06-01
42.53921979-06-01
32.23431979-06-01
32.34041979-06-01
29.26951979-06-01
−28.92661979-06-01
−55.58711979-06-01
99.81321979-06-01
41.96131979-06-01
112.7941979-06-01
32.49351979-06-01
−222.6761979-06-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.09130.28291
−0.18870.28292
0.07370.28293
−0.03440.28294
0.01240.28295
−0.00730.28296
−0.05790.28297
0.08380.28298
0.15070.28299
0.09490.282910
−0.13880.282911
−0.19290.282912
−0.12780.282913
0.04400.282914
−0.00050.282915
−0.09610.282916
−0.08250.282917
−0.05980.282918
0.07880.282919
−0.00060.282920
−0.17180.282921
−0.06300.282922
−0.13240.282923
−0.01480.282924

Backtest accuracy (2 origins, horizon 6)

MetricValue
MAE61.440
RMSE83.568
MAPE0.0746
sMAPE0.0756
MASE0.4656
WAPE0.0790
Coverage of the 90% interval0.9167

Forecast

SeriesmonthForecast90% low90% high
female1980-01-01743.88527.32960.44
female1980-02-01817.25621.411013.10
female1980-03-01712.58541.22883.94
female1980-04-01590.79466.85714.72
female1980-05-01504.82349.20660.44
female1980-06-01447.02328.25565.78
male1980-01-011831.411614.852047.97
male1980-02-012091.741895.892287.58
male1980-03-011812.471641.111983.83
male1980-04-011539.161415.221663.09
male1980-05-011322.651167.021478.27
male1980-06-011110.35991.581229.12
The exact R script · R R version 4.5.1 (2025-06-13)
# PatchTST forecast (patch Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.patchtst 1.0.0 · spec a29f91589e548639
# Dataset: ml_deaths (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 codesplashr's cs_ptst_* twin.

# %% Data
TIME <- "month"
VALUE <- "deaths"
SERIES <- "sex"
H <- 6
LEVELS <- as.numeric(c(90))
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(
  window = 24,
  patch_len = 6,
  stride = 3,
  d_model = 8,
  heads = 2,
  layers = 1,
  epochs = 30,
  learning_rate = 0.005,
  batch_size = 32,
  weight_decay = 0,
  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_deaths.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.patchtst/panel_patches_batches/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.patchtst/panel_patches_batches/out-r")
# PatchTST: ONE Transformer trained on the windows of every series (channel independence). Each window is
# instance-normalized, cut into patches that become tokens, and a flatten head forecasts every step at once. The
# driver asks for one series and origin at a time, so the network for each origin (its distance from the end of the
# series) is trained once on all series cut at that origin and reused for every series.
.ptst_global <- new.env()
.ptst_full <- NULL

.ptst_full_series <- function() {
  if (is.null(.ptst_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)
      full[[if (is.null(key)) "_" else key]] <- list(t = reg$t, y = reg$y)
    }
    .ptst_full <<- full
  }
  .ptst_full
}

min_train <- function(m) cs_ptst_window_length(PARAMS$window, H, m) + H + 9L
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 <- .ptst_full_series()
  times <- full[[if (is.null(current_series)) "_" else current_series]]$t
  d <- length(times) - match(t[length(t)], times)  # values after this origin
  name <- as.character(d)
  if (is.null(.ptst_global[[name]])) {
    train <- list()
    for (s in full) {
      o <- length(s$y) - d
      if (o <= 0) next
      start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
      train[[length(train) + 1L]] <- s$y[start:o]
    }
    .ptst_global[[name]] <- cs_ptst_fit_global(
      train, h,
      window = cs_ptst_window_length(PARAMS$window, h, m),
      patch_len = PARAMS$patch_len,
      stride = PARAMS$stride,
      d_model = as.integer(PARAMS$d_model),
      heads = as.integer(PARAMS$heads),
      layers = as.integer(PARAMS$layers),
      epochs = as.integer(PARAMS$epochs),
      lr = PARAMS$learning_rate,
      batch_size = PARAMS$batch_size,
      weight_decay = PARAMS$weight_decay,
      seed = SEED
    )
  }
  cs_ptst_forecast(.ptst_global[[name]], y, h, levels)
}

# %% 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")
  ))
}

# %% 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 = "PatchTST forecast (patch Transformer)",
  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

2 series, one model each: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 61.4 over 2 origins.

MAE
61.440
RMSE
83.568
MAPE
0.0746

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

Backtest accuracy (2 origins, horizon 6)

MetricValue
MAE61.440
RMSE83.568
MAPE0.0746
sMAPE0.0756
MASE0.4656
WAPE0.0790
Coverage of the 90% interval0.9167

Forecast

SeriesmonthForecast90% low90% high
female1980-01-01743.88527.32960.44
female1980-02-01817.25621.411013.10
female1980-03-01712.58541.22883.94
female1980-04-01590.79466.85714.72
female1980-05-01504.82349.20660.44
female1980-06-01447.02328.25565.78
male1980-01-011831.411614.852047.97
male1980-02-012091.741895.892287.58
male1980-03-011812.471641.111983.83
male1980-04-011539.161415.221663.09
male1980-05-011322.651167.021478.27
male1980-06-011110.35991.581229.12
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# PatchTST forecast (patch Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.patchtst 1.0.0 · spec a29f91589e548639
# Dataset: ml_deaths (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 patchtst  # twin of codesplashr::cs_ptst_* (torch, shared initial weights)

# %% Data
TIME = "month"
VALUE = "deaths"
SERIES = "sex"
H = 6
LEVELS = [float(v) for v in [90]]
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 = {
    "window": 24,
    "patch_len": 6,
    "stride": 3,
    "d_model": 8,
    "heads": 2,
    "layers": 1,
    "epochs": 30,
    "learning_rate": 0.005,
    "batch_size": 32,
    "weight_decay": 0,
    "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_deaths.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.patchtst/panel_patches_batches/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.patchtst/panel_patches_batches/out-python",
)
# PatchTST: ONE Transformer trained on the windows of every series (channel independence). Each window is
# instance-normalized, cut into patches that become tokens, and a flatten head forecasts every step at once. The
# driver asks for one series and origin at a time, so the network for each origin (its distance from the end of the
# series) is trained once on all series cut at that origin and reused for every series.
_GLOBAL = {}
_FULL = {}


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)
            _FULL[key] = ([float(v) for v in t], [float(v) for v in y])
    return _FULL


def min_train(m):
    return patchtst.window_length(PARAMS["window"], H, m) + H + 9


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()
    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 t_k, y_k in full.values():
            o = len(y_k) - d
            if o <= 0:
                continue
            start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
            train.append(y_k[start:o])
        _GLOBAL[d] = patchtst.fit_global(
            train, h,
            window=patchtst.window_length(PARAMS["window"], h, m),
            patch_len=PARAMS["patch_len"],
            stride=PARAMS["stride"],
            d_model=int(PARAMS["d_model"]),
            heads=int(PARAMS["heads"]),
            layers=int(PARAMS["layers"]),
            epochs=int(PARAMS["epochs"]),
            lr=PARAMS["learning_rate"],
            batch_size=PARAMS["batch_size"],
            weight_decay=PARAMS["weight_decay"],
            seed=SEED,
        )
    return patchtst.forecast(_GLOBAL[d], list(y), h, levels)


# %% 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"),
            },
        )
    )

# %% 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": "PatchTST forecast (patch Transformer)",
        "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,
    }
)

With a Series column, every series' windows train the same network, but each window only ever reads its own series (channel independenceChannel independenceEvery series is fed through the same network on its own; series share the weights but never mix inside a window.). Because each window is normalized on its own, a large series and a small one can share the weights.

04

Which normalization?

Predict

Predict first

You multiply a series by 10 and add 1,000, then train PatchTST again with the same settings. What happens to the forecasts?

Exactly ten times larger, plus 1,000Different: the network sees new numbers
Reveal

Exactly ten times larger, plus 1,000. Each window is normalized before the network reads it, so the network sees the same numbers and its forecasts are mapped back to the new scale.

05

TFT: covariates, quantiles and what the model used

Read
Temporal Fusion Transformer forecast (TFT)Recorded · Python and R agreeRecorded 2026-11-25 · 30 values compared
R

Temporal Fusion Transformer (3 quantiles): 6-step forecasts of drivers (monthly data, 192 observations). Backtest MAE 21.8 over 2 origins.

MAE
21.778
RMSE
24.234
MAPE
0.2111

Plots

Forecast of driversWhere is the series heading, and how uncertain is the forecast?
View data
hi_80kindlo_80monthdrivers
—actual—−31,536,000,000107
—actual—−28,857,600,00097
—actual—−26,438,400,000102
—actual—−23,760,000,00087
—actual—−21,168,000,000119
—actual—−18,489,600,000106
—actual—−15,897,600,000110
—actual—−13,219,200,000106
—actual—−10,540,800,000107
—actual—−7,948,800,000134
—actual—−5,270,400,000147
—actual—−2,678,400,000180
—actual—0125
—actual—2,678,400,000134
—actual—5,097,600,000110
—actual—7,776,000,000102
—actual—10,368,000,000103
—actual—13,046,400,000111
—actual—15,638,400,000120
—actual—18,316,800,000129
—actual—20,995,200,000122
—actual—23,587,200,000183
—actual—26,265,600,000169
—actual—28,857,600,000190
—actual—31,536,000,000134
—actual—34,214,400,000108
—actual—36,633,600,000104
—actual—39,312,000,000117
—actual—41,904,000,000157
—actual—44,582,400,000148
—actual—47,174,400,000130
—actual—49,852,800,000140
—actual—52,531,200,000136
—actual—55,123,200,000140
—actual—57,801,600,000187
—actual—60,393,600,000150
—actual—63,072,000,000159
—actual—65,750,400,000143
—actual—68,256,000,000114
—actual—70,934,400,000127
—actual—73,526,400,000159
—actual—76,204,800,000156
—actual—78,796,800,000138
—actual—81,475,200,000120
—actual—84,153,600,000117
—actual—86,745,600,000170
—actual—89,424,000,000168
—actual—92,016,000,000198
—actual—94,694,400,000144
—actual—97,372,800,000146
—actual—99,792,000,000109
—actual—102,470,400,000131
—actual—105,062,400,000151
—actual—107,740,800,000140
—actual—110,332,800,000153
—actual—113,011,200,000140
—actual—115,689,600,000161
—actual—118,281,600,000168
—actual—120,960,000,000152
—actual—123,552,000,000136

First 60 of 198 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
−13.98211983-12-01
−22.12321983-12-01
−28.16131983-12-01
−20.57941983-12-01
−19.02751983-12-01
−16.49661983-12-01
−17.01111984-06-01
−3.17021984-06-01
21.43031984-06-01
18.58741984-06-01
31.83251984-06-01
48.93461984-06-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.46700.15351
0.05900.15352
−0.08220.15353
−0.09410.15354
−0.03260.15355
−0.01710.15356
−0.10020.15357
−0.08220.15358
−0.09400.15359
−0.05640.153510
0.25480.153511
0.46180.153512
0.29100.153513
−0.00940.153514
−0.12390.153515
−0.10830.153516
−0.02160.153517
−0.09520.153518
−0.13180.153519
−0.17960.153520
−0.21720.153521
−0.09520.153522
0.15700.153523
0.25590.153524
Variable importance: past inputsWhich features does the model rely on most?
View data
inputselection weight
drivers0.0644
petrol0.3560
law0.0577
season (sin)0.0988
season (cos)0.0678
time index0.3554
Variable importance: future inputsWhich features does the model rely on most?
View data
inputselection weight
law0.3459
season (sin)0.1339
season (cos)0.3670
time index0.1532
Attention of the first forecast step over the lookbackHow does the series move over time, and where is an estimated break?
View data
steps before the forecastattention weight
−240.0427
−230.0418
−220.0410
−210.0402
−200.0396
−190.0392
−180.0390
−170.0392
−160.0394
−150.0398
−140.0403
−130.0407
−120.0409
−110.0408
−100.0406
−90.0403
−80.0400
−70.0396
−60.0394
−50.0393
−40.0392
−30.0393
−20.0399
−10.0405
00.0373

Backtest accuracy (2 origins, horizon 6)

MetricValue
MAE21.778
RMSE24.234
MAPE0.2111
sMAPE0.2064
MASE1.281
WAPE0.2128
Coverage of the 80% interval0.6667

Variable importance (average selection weight; past and future inputs each add up to 1)

InputRead forWeight
driversPast0.0644
petrolPast0.3560
lawPast0.0577
season (sin)Past0.0988
season (cos)Past0.0678
time indexPast0.3554
lawFuture0.3459
season (sin)Future0.1339
season (cos)Future0.3670
time indexFuture0.1532

Forecast

monthForecast80% low80% high
1985-01-0194.02172.080144.41
1985-02-0196.34076.246130.43
1985-03-0198.32779.400127.41
1985-04-0193.96264.941126.83
1985-05-0194.44374.054115.48
1985-06-0195.02577.232111.49
  • Future values of law, petrol are known for 0 of 6 steps; the last known values are held for the rest.
The exact R script · R R version 4.5.1 (2025-06-13)
# Temporal Fusion Transformer forecast (TFT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.tft 1.1.0 · spec 91c176bed41c1b14
# Dataset: f7_seatbelts (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 codesplashr's cs_tft_* twin.

# %% Data
TIME <- "month"
VALUE <- "drivers"
SERIES <- NULL
H <- 6
LEVELS <- as.numeric(c(80))
SEASON <- NULL  # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 2
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
FUTURE_COV <- c("law")  # known-future covariates: values given for the forecast steps
PAST_COV <- c("petrol")  # past-only covariates: observed up to now, not ahead
PAST_ONLY <- setdiff(PAST_COV, FUTURE_COV)
XREG <- c(FUTURE_COV, PAST_ONLY)

PARAMS <- list(
  window = NULL,
  d_model = 8,
  heads = 2,
  epochs = 12,
  learning_rate = 0.005,
  batch_size = NULL,
  weight_decay = 0,
  quantile_grid = "intervals",
  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/f7_seatbelts.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.tft/known_and_past_covariates/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.tft/known_and_past_covariates/out-r")
# Temporal Fusion Transformer: ONE network trained on the windows of every series, with variable selection over the
# target, the covariates, the season position and a time index; an LSTM encoder-decoder; interpretable attention and
# quantile outputs. The driver asks for one series and origin at a time, so the network for each origin (its distance
# from the end of the series) is trained once on all series cut at that origin and reused for every series.
.tft_global <- new.env()
.tft_full <- NULL
KIDX <- match(FUTURE_COV, XREG)
PIDX <- match(PAST_ONLY, XREG)

.tft_cols <- function(x, idx) if (is.null(x) || !length(idx)) NULL else as.matrix(x)[, idx, drop = FALSE]

.tft_full_series <- function() {
  if (is.null(.tft_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
      x_raw <- NULL
      if (length(XREG)) {  # rows after the last observed value carry known future covariates
        x_raw <- x_all[sel, , drop = FALSE]
        last_y <- max(t_raw[!is.na(y_raw)])
        later <- t_raw > last_y
        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)
      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
      m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
      full[[if (is.null(key)) "_" else key]] <- list(t = reg$t, y = reg$y, m = m, x = x_grid)
    }
    .tft_full <<- full
  }
  .tft_full
}

min_train <- function(m) cs_tft_window_length(PARAMS$window, H, m) + H + 9L
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 <- .tft_full_series()
  keys <- names(full)
  cur <- if (is.null(current_series)) "_" else current_series
  times <- full[[cur]]$t
  d <- length(times) - match(t[length(t)], times)  # values after this origin
  name <- as.character(d)
  if (is.null(.tft_global[[name]])) {
    items <- list()
    for (sidx in seq_along(keys)) {
      s <- full[[keys[sidx]]]
      o <- length(s$y) - d
      if (o <= 0) next
      start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
      xs <- if (is.null(s$x)) NULL else s$x[start:o, , drop = FALSE]
      items[[length(items) + 1L]] <- cs_tft_prepare_item(s$y[start:o], .tft_cols(xs, KIDX), .tft_cols(xs, PIDX), s$m,
                                                          start - 1L, sidx - 1L)
    }
    .tft_global[[name]] <- cs_tft_fit_global(
      items, h, cs_tft_window_length(PARAMS$window, h, m), levels, length(keys),
      any(vapply(full, function(s) s$m > 1, logical(1))),
      d_model = as.integer(PARAMS$d_model),
      heads = as.integer(PARAMS$heads),
      epochs = as.integer(PARAMS$epochs),
      lr = PARAMS$learning_rate,
      batch_size = PARAMS$batch_size,
      weight_decay = PARAMS$weight_decay,
      seed = SEED,
      extra_quantiles = if (identical(PARAMS$quantile_grid, "deciles")) cs_tft_deciles else NULL  # more quantiles to learn (Wave 8)
    )
  }
  item <- cs_tft_prepare_item(y, .tft_cols(X_TRAIN, KIDX), .tft_cols(X_TRAIN, PIDX), m, match(t[1], times) - 1L,
                              match(cur, keys) - 1L, known_future = .tft_cols(X_FUTURE, KIDX))
  cs_tft_forecast(.tft_global[[name]], item, h, levels)
}

# %% 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]
      }
      # The network's own quantiles as q_<100 tau> columns (q_10, q_2_5 ...), which the host's backtest scores read.
      for (j in seq_along(res$quantiles$tau)) row[[paste0("q_", lv(round(100 * res$quantiles$tau[j], 6)))]] <- res$quantiles$values[k, j]
      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")
  ))
}

# %% Variable importance and attention (the final model)
if (!is.null(.tft_global[["0"]])) {
  g <- .tft_global[["0"]]
  nm <- cs_tft_variable_names(VALUE, PAST_ONLY, FUTURE_COV, g$use_season)
  imp_rows <- c(
    lapply(seq_along(nm$past), function(j) list(input = nm$past[j], where = "Past", weight = g$w_past[j])),
    lapply(seq_along(nm$future), function(j) list(input = nm$future[j], where = "Future", weight = g$w_future[j]))
  )
  extra_tables[[length(extra_tables) + 1]] <- list(
    key = "importance",
    title = "Variable importance (average selection weight; past and future inputs each add up to 1)",
    columns = list(list(key = "input", label = "Input"), list(key = "where", label = "Read for"), list(key = "weight", label = "Weight", type = "number")),
    rows = imp_rows
  )
  charts[[length(charts) + 1]] <- cs_chart("importance_past", "importance-bar", "Variable importance: past inputs", list(
    feature = cs_col("input", nm$past, kind = "categorical"),
    importance = cs_col("selection weight", g$w_past, kind = "numeric")
  ))
  if (length(nm$future) > 1) {
    charts[[length(charts) + 1]] <- cs_chart("importance_future", "importance-bar", "Variable importance: future inputs", list(
      feature = cs_col("input", nm$future, kind = "categorical"),
      importance = cs_col("selection weight", g$w_future, kind = "numeric")
    ))
  }
  L0 <- as.integer(g$window)
  charts[[length(charts) + 1]] <- cs_chart("attention", "series-line", "Attention of the first forecast step over the lookback", list(
    x = cs_col("steps before the forecast", as.numeric(seq(0L, L0) - L0), kind = "numeric"),
    y = cs_col("attention weight", g$attention, kind = "numeric")
  ))
  values$importance_check <- sum(seq_along(nm$past) * g$w_past)
  values$attention_check <- sum(seq_len(L0 + 1L) * g$attention)
}
if (identical(PARAMS$quantile_grid, "deciles") && length(bt_rows)) {
  # A weighted sum of every native quantile the backtests wrote (q_<100 tau> columns), so both engines agree.
  qkeys <- grep("^q_", names(bt_rows[[1]]), value = TRUE)
  wq <- as.numeric(outer(seq_along(qkeys), seq_along(bt_rows), function(j, i) i * j))
  qv <- unlist(lapply(bt_rows, function(r) unlist(r[qkeys])), use.names = FALSE)
  values$q_check <- sum(wq * qv) / sum(wq)
}
# %% 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 = "Temporal Fusion Transformer forecast (TFT)",
  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

Temporal Fusion Transformer (3 quantiles): 6-step forecasts of drivers (monthly data, 192 observations). Backtest MAE 21.8 over 2 origins.

MAE
21.778
RMSE
24.234
MAPE
0.2111

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

Backtest accuracy (2 origins, horizon 6)

MetricValue
MAE21.778
RMSE24.234
MAPE0.2111
sMAPE0.2064
MASE1.281
WAPE0.2128
Coverage of the 80% interval0.6667

Variable importance (average selection weight; past and future inputs each add up to 1)

InputRead forWeight
driversPast0.0644
petrolPast0.3560
lawPast0.0577
season (sin)Past0.0988
season (cos)Past0.0678
time indexPast0.3554
lawFuture0.3459
season (sin)Future0.1339
season (cos)Future0.3670
time indexFuture0.1532

Forecast

monthForecast80% low80% high
1985-01-0194.02172.080144.41
1985-02-0196.34076.246130.43
1985-03-0198.32779.400127.41
1985-04-0193.96264.941126.83
1985-05-0194.44374.054115.48
1985-06-0195.02577.232111.49
  • Future values of law, petrol are known for 0 of 6 steps; the last known values are held for the rest.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Temporal Fusion Transformer forecast (TFT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.tft 1.1.0 · spec 91c176bed41c1b14
# Dataset: f7_seatbelts (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 tft  # twin of codesplashr::cs_tft_* (torch, shared initial weights)

# %% Data
TIME = "month"
VALUE = "drivers"
SERIES = None
H = 6
LEVELS = [float(v) for v in [80]]
SEASON = None  # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 2
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
FUTURE_COV = ["law"]  # known-future covariates: values given for the forecast steps
PAST_COV = ["petrol"]  # past-only covariates: observed up to now, not ahead
PAST_ONLY = [c for c in PAST_COV if c not in FUTURE_COV]
XREG = FUTURE_COV + PAST_ONLY

PARAMS = {
    "window": None,
    "d_model": 8,
    "heads": 2,
    "epochs": 12,
    "learning_rate": 0.005,
    "batch_size": None,
    "weight_decay": 0,
    "quantile_grid": "intervals",
    "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/f7_seatbelts.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.tft/known_and_past_covariates/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.tft/known_and_past_covariates/out-python",
)
# Temporal Fusion Transformer: ONE network trained on the windows of every series, with variable selection over the
# target, the covariates, the season position and a time index; an LSTM encoder-decoder; interpretable attention and
# quantile outputs. The driver asks for one series and origin at a time, so the network for each origin (its distance
# from the end of the series) is trained once on all series cut at that origin and reused for every series.
_GLOBAL = {}
_FULL = {}
KIDX = [XREG.index(c) for c in FUTURE_COV]
PIDX = [XREG.index(c) for c in PAST_ONLY]


def _cols(x, idx):
    return None if x is None or not idx else np.asarray(x, dtype=np.float64)[:, idx]


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
            x_raw = None
            if XREG:  # rows after the last observed value carry known future covariates
                x_raw = x_all[sel]
                last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
                later = t_raw > last_y
                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, _ = 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
            m = int(SEASON) if SEASON else int(freq["season"])
            _FULL[key] = ([float(v) for v in t], [float(v) for v in y], m, x_grid)
    return _FULL


def min_train(m):
    return tft.window_length(PARAMS["window"], H, m) + H + 9


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:
        items = []
        for sidx, key in enumerate(keys):
            t_k, y_k, m_k, x_k = full[key]
            o = len(y_k) - d
            if o <= 0:
                continue
            start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
            xs = None if x_k is None else x_k[start:o]
            items.append(tft.prepare_item(y_k[start:o], _cols(xs, KIDX), _cols(xs, PIDX), m_k, start, sidx))
        _GLOBAL[d] = tft.fit_global(
            items, h, tft.window_length(PARAMS["window"], h, m), levels, len(keys), any(v[2] > 1 for v in full.values()),
            d_model=int(PARAMS["d_model"]),
            heads=int(PARAMS["heads"]),
            epochs=int(PARAMS["epochs"]),
            lr=PARAMS["learning_rate"],
            batch_size=PARAMS["batch_size"],
            weight_decay=PARAMS["weight_decay"],
            seed=SEED,
            extra_quantiles=tft.DECILES if PARAMS["quantile_grid"] == "deciles" else (),  # more quantiles to learn (Wave 8)
        )
    item = tft.prepare_item(
        list(y), _cols(X_TRAIN, KIDX), _cols(X_TRAIN, PIDX), m, times.index(float(t[0])), keys.index(current_series),
        known_future=_cols(X_FUTURE, KIDX),
    )
    return tft.forecast(_GLOBAL[d], item, h, levels)


# %% 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])
            # The network's own quantiles as q_<100·τ> columns (q_10, q_2_5 …), which the host's backtest scores read.
            for tau, qv in res["quantiles"].items():
                row[f"q_{lv(round(100.0 * tau, 6))}"] = float(qv[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"),
            },
        )
    )

# %% Variable importance and attention (the final model)
if 0 in _GLOBAL:
    g = _GLOBAL[0]
    names_p, names_f = tft.variable_names(VALUE, PAST_ONLY, FUTURE_COV, g["use_season"])
    imp_rows = [{"input": names_p[j], "where": "Past", "weight": g["w_past"][j]} for j in range(len(names_p))]
    imp_rows += [{"input": names_f[j], "where": "Future", "weight": g["w_future"][j]} for j in range(len(names_f))]
    extra_tables.append({
        "key": "importance",
        "title": "Variable importance (average selection weight; past and future inputs each add up to 1)",
        "columns": [{"key": "input", "label": "Input"}, {"key": "where", "label": "Read for"}, {"key": "weight", "label": "Weight", "type": "number"}],
        "rows": imp_rows,
    })
    charts.append(cs.chart("importance_past", "importance-bar", "Variable importance: past inputs", {
        "feature": cs.col("input", names_p, kind="categorical"),
        "importance": cs.col("selection weight", g["w_past"], kind="numeric"),
    }))
    if len(names_f) > 1:
        charts.append(cs.chart("importance_future", "importance-bar", "Variable importance: future inputs", {
            "feature": cs.col("input", names_f, kind="categorical"),
            "importance": cs.col("selection weight", g["w_future"], kind="numeric"),
        }))
    L0 = int(g["window"])
    charts.append(cs.chart("attention", "series-line", "Attention of the first forecast step over the lookback", {
        "x": cs.col("steps before the forecast", [float(j - L0) for j in range(L0 + 1)], kind="numeric"),
        "y": cs.col("attention weight", g["attention"], kind="numeric"),
    }))
    values["importance_check"] = fc._sum([(j + 1) * g["w_past"][j] for j in range(len(names_p))])
    values["attention_check"] = fc._sum([(j + 1) * g["attention"][j] for j in range(L0 + 1)])
if PARAMS["quantile_grid"] == "deciles" and bt_rows:
    # A weighted sum of every native quantile the backtests wrote (q_<100·τ> columns), so both engines agree.
    qkeys = [c for c in bt_rows[0] if c.startswith("q_")]
    wq = [(i + 1.0) * (j + 1.0) for i in range(len(bt_rows)) for j in range(len(qkeys))]
    values["q_check"] = fc._sum([wq[i * len(qkeys) + j] * bt_rows[i][qkeys[j]] for i in range(len(bt_rows)) for j in range(len(qkeys))]) / fc._sum(wq)
# %% 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": "Temporal Fusion Transformer forecast (TFT)",
        "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,
    }
)

The Temporal Fusion TransformerTemporal Fusion TransformerA forecaster that weighs its inputs with gated variable selection, reads past and future with an LSTM, and outputs quantiles. reads the series together with covariates. Here the 1983 seat-belt law is a known-future covariate, given for the forecast months, and the petrol price is past-only. A small gated network (variable selectionVariable selection networkA small gated network that gives each input a softmax weight at every step; the weights add up to 1.) gives every input a weight at every step. An LSTM reads the past and the future inputs, and attention looks back over the past.

It forecasts quantilesQuantile forecastA forecast that predicts several quantiles directly (the median and each interval's bounds), trained with the pinball loss. directly: the line is the median, and each interval runs between two predicted quantiles. Check their coverage on the backtest; the 80% interval held 66.7% of the actual values.

06

Reading variable importance and attention

Read

The Variable importance charts average the selection weights over the training windows; each set (past inputs, future inputs) adds up to 1. The Attention chart shows how the first forecast step weighs each step of the lookback. A peak 12 months back means the network leans on the same month last year.

These describe this network, not the world. A covariate with a large weight helped this model fit; it isn't proof that the covariate causes anything. A tiny weight can also mean another input carries the same information.

07

Many series and a static input

Read
Temporal Fusion Transformer forecast (TFT)Recorded · Python and R agreeRecorded 2026-11-25 · 40 values compared
R

2 series, one model each: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 77.1 over 2 origins.

MAE
77.069
RMSE
139.99
MAPE
0.0843

Plots

Forecast of deathsWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95sexmonthdeaths
——actual——female126,230,400,000901
——actual——female128,908,800,000689
——actual——female131,328,000,000827
——actual——female134,006,400,000677
——actual——female136,598,400,000522
——actual——female139,276,800,000406
——actual——female141,868,800,000441
——actual——female144,547,200,000393
——actual——female147,225,600,000387
——actual——female149,817,600,000582
——actual——female152,496,000,000578
——actual——female155,088,000,000666
——actual——female157,766,400,000830
——actual——female160,444,800,000752
——actual——female162,864,000,000785
——actual——female165,542,400,000664
——actual——female168,134,400,000467
——actual——female170,812,800,000438
——actual——female173,404,800,000421
——actual——female176,083,200,000412
——actual——female178,761,600,000343
——actual——female181,353,600,000440
——actual——female184,032,000,000531
——actual——female186,624,000,000771
——actual——female189,302,400,000767
——actual——female191,980,800,0001,141
——actual——female194,486,400,000896
——actual——female197,164,800,000532
——actual——female199,756,800,000447
——actual——female202,435,200,000420
——actual——female205,027,200,000376
——actual——female207,705,600,000330
——actual——female210,384,000,000357
——actual——female212,976,000,000445
——actual——female215,654,400,000546
——actual——female218,246,400,000764
——actual——female220,924,800,000862
——actual——female223,603,200,000660
——actual——female226,022,400,000663
——actual——female228,700,800,000643
——actual——female231,292,800,000502
——actual——female233,971,200,000392
——actual——female236,563,200,000411
——actual——female239,241,600,000348
——actual——female241,920,000,000387
——actual——female244,512,000,000385
——actual——female247,190,400,000411
——actual——female249,782,400,000638
——actual——female252,460,800,000796
——actual——female255,139,200,000853
——actual——female257,558,400,000737
——actual——female260,236,800,000546
——actual——female262,828,800,000530
——actual——female265,507,200,000446
——actual——female268,099,200,000431
——actual——female270,777,600,000362
——actual——female273,456,000,000387
——actual——female276,048,000,000430
——actual——female278,726,400,000425
——actual——female281,318,400,000679

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
14.32511979-06-01
8.86821979-06-01
20.98331979-06-01
16.23841979-06-01
55.87351979-06-01
−110.1361979-06-01
19.02611979-06-01
−10.94721979-06-01
−51.43031979-06-01
30.86041979-06-01
146.3351979-06-01
−439.8161979-06-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.22050.29891
−0.19790.29892
−0.12820.29893
−0.09100.29894
−0.16350.29895
−0.09990.29896
−0.08330.29897
0.15700.29898
0.21650.29899
0.18480.298910
0.03770.298911
−0.24930.298912
−0.19620.298913
0.02510.298914
0.01590.298915
−0.03210.298916
−0.02940.298917
0.00980.298918
0.01290.298919
0.00970.298920
−0.06600.298921
−0.21390.298922
−0.03730.298923
0.08450.298924
Variable importance: past inputsWhich features does the model rely on most?
View data
inputselection weight
deaths0.1553
season (sin)0.3350
season (cos)0.0817
time index0.4279
Variable importance: future inputsWhich features does the model rely on most?
View data
inputselection weight
season (sin)0.3664
season (cos)0.4606
time index0.1730
Attention of the first forecast step over the lookbackHow does the series move over time, and where is an estimated break?
View data
steps before the forecastattention weight
−240.0398
−230.0400
−220.0400
−210.0400
−200.0401
−190.0403
−180.0404
−170.0401
−160.0398
−150.0397
−140.0397
−130.0399
−120.0401
−110.0402
−100.0402
−90.0401
−80.0400
−70.0401
−60.0401
−50.0398
−40.0395
−30.0395
−20.0397
−10.0402
00.0405

Backtest accuracy (2 origins, horizon 6)

MetricValue
MAE77.069
RMSE139.99
MAPE0.0843
sMAPE0.0804
MASE0.5916
WAPE0.0991
Coverage of the 80% interval0.9167
Coverage of the 95% interval1

Variable importance (average selection weight; past and future inputs each add up to 1)

InputRead forWeight
deathsPast0.1553
season (sin)Past0.3350
season (cos)Past0.0817
time indexPast0.4279
season (sin)Future0.3664
season (cos)Future0.4606
time indexFuture0.1730

Forecast

SeriesmonthForecast80% low80% high95% low95% high
female1980-01-01702.31581.53803.98455.36845.33
female1980-02-01706.05578.32802.34458.71844.07
female1980-03-01698.20560.92806.51451.30843.60
female1980-04-01620.01427.03794.52393.23807.68
female1980-05-01461.16372.69547.20266.25634.72
female1980-06-01427.68406.51461.52271.21556.81
male1980-01-011811.031494.262080.581152.892192.20
male1980-02-011821.941487.842076.351162.542189.67
male1980-03-011799.721438.482087.361140.852187.70
male1980-04-011562.401054.102033.01968.822076.31
male1980-05-011153.65960.781359.35671.321597.69
male1980-06-011077.141059.091148.24703.281402.15
The exact R script · R R version 4.5.1 (2025-06-13)
# Temporal Fusion Transformer forecast (TFT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.tft 1.1.0 · spec 2298914eec1dcf63
# Dataset: ml_deaths (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 codesplashr's cs_tft_* twin.

# %% Data
TIME <- "month"
VALUE <- "deaths"
SERIES <- "sex"
H <- 6
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
FUTURE_COV <- c()  # known-future covariates: values given for the forecast steps
PAST_COV <- c()  # past-only covariates: observed up to now, not ahead
PAST_ONLY <- setdiff(PAST_COV, FUTURE_COV)
XREG <- c(FUTURE_COV, PAST_ONLY)

PARAMS <- list(
  window = NULL,
  d_model = 8,
  heads = 2,
  epochs = 12,
  learning_rate = 0.005,
  batch_size = 32,
  weight_decay = 0.001,
  quantile_grid = "intervals",
  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_deaths.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.tft/panel_static_batches/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.tft/panel_static_batches/out-r")
# Temporal Fusion Transformer: ONE network trained on the windows of every series, with variable selection over the
# target, the covariates, the season position and a time index; an LSTM encoder-decoder; interpretable attention and
# quantile outputs. The driver asks for one series and origin at a time, so the network for each origin (its distance
# from the end of the series) is trained once on all series cut at that origin and reused for every series.
.tft_global <- new.env()
.tft_full <- NULL
KIDX <- match(FUTURE_COV, XREG)
PIDX <- match(PAST_ONLY, XREG)

.tft_cols <- function(x, idx) if (is.null(x) || !length(idx)) NULL else as.matrix(x)[, idx, drop = FALSE]

.tft_full_series <- function() {
  if (is.null(.tft_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
      x_raw <- NULL
      if (length(XREG)) {  # rows after the last observed value carry known future covariates
        x_raw <- x_all[sel, , drop = FALSE]
        last_y <- max(t_raw[!is.na(y_raw)])
        later <- t_raw > last_y
        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)
      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
      m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
      full[[if (is.null(key)) "_" else key]] <- list(t = reg$t, y = reg$y, m = m, x = x_grid)
    }
    .tft_full <<- full
  }
  .tft_full
}

min_train <- function(m) cs_tft_window_length(PARAMS$window, H, m) + H + 9L
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 <- .tft_full_series()
  keys <- names(full)
  cur <- if (is.null(current_series)) "_" else current_series
  times <- full[[cur]]$t
  d <- length(times) - match(t[length(t)], times)  # values after this origin
  name <- as.character(d)
  if (is.null(.tft_global[[name]])) {
    items <- list()
    for (sidx in seq_along(keys)) {
      s <- full[[keys[sidx]]]
      o <- length(s$y) - d
      if (o <= 0) next
      start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
      xs <- if (is.null(s$x)) NULL else s$x[start:o, , drop = FALSE]
      items[[length(items) + 1L]] <- cs_tft_prepare_item(s$y[start:o], .tft_cols(xs, KIDX), .tft_cols(xs, PIDX), s$m,
                                                          start - 1L, sidx - 1L)
    }
    .tft_global[[name]] <- cs_tft_fit_global(
      items, h, cs_tft_window_length(PARAMS$window, h, m), levels, length(keys),
      any(vapply(full, function(s) s$m > 1, logical(1))),
      d_model = as.integer(PARAMS$d_model),
      heads = as.integer(PARAMS$heads),
      epochs = as.integer(PARAMS$epochs),
      lr = PARAMS$learning_rate,
      batch_size = PARAMS$batch_size,
      weight_decay = PARAMS$weight_decay,
      seed = SEED,
      extra_quantiles = if (identical(PARAMS$quantile_grid, "deciles")) cs_tft_deciles else NULL  # more quantiles to learn (Wave 8)
    )
  }
  item <- cs_tft_prepare_item(y, .tft_cols(X_TRAIN, KIDX), .tft_cols(X_TRAIN, PIDX), m, match(t[1], times) - 1L,
                              match(cur, keys) - 1L, known_future = .tft_cols(X_FUTURE, KIDX))
  cs_tft_forecast(.tft_global[[name]], item, h, levels)
}

# %% 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]
      }
      # The network's own quantiles as q_<100 tau> columns (q_10, q_2_5 ...), which the host's backtest scores read.
      for (j in seq_along(res$quantiles$tau)) row[[paste0("q_", lv(round(100 * res$quantiles$tau[j], 6)))]] <- res$quantiles$values[k, j]
      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")
  ))
}

# %% Variable importance and attention (the final model)
if (!is.null(.tft_global[["0"]])) {
  g <- .tft_global[["0"]]
  nm <- cs_tft_variable_names(VALUE, PAST_ONLY, FUTURE_COV, g$use_season)
  imp_rows <- c(
    lapply(seq_along(nm$past), function(j) list(input = nm$past[j], where = "Past", weight = g$w_past[j])),
    lapply(seq_along(nm$future), function(j) list(input = nm$future[j], where = "Future", weight = g$w_future[j]))
  )
  extra_tables[[length(extra_tables) + 1]] <- list(
    key = "importance",
    title = "Variable importance (average selection weight; past and future inputs each add up to 1)",
    columns = list(list(key = "input", label = "Input"), list(key = "where", label = "Read for"), list(key = "weight", label = "Weight", type = "number")),
    rows = imp_rows
  )
  charts[[length(charts) + 1]] <- cs_chart("importance_past", "importance-bar", "Variable importance: past inputs", list(
    feature = cs_col("input", nm$past, kind = "categorical"),
    importance = cs_col("selection weight", g$w_past, kind = "numeric")
  ))
  if (length(nm$future) > 1) {
    charts[[length(charts) + 1]] <- cs_chart("importance_future", "importance-bar", "Variable importance: future inputs", list(
      feature = cs_col("input", nm$future, kind = "categorical"),
      importance = cs_col("selection weight", g$w_future, kind = "numeric")
    ))
  }
  L0 <- as.integer(g$window)
  charts[[length(charts) + 1]] <- cs_chart("attention", "series-line", "Attention of the first forecast step over the lookback", list(
    x = cs_col("steps before the forecast", as.numeric(seq(0L, L0) - L0), kind = "numeric"),
    y = cs_col("attention weight", g$attention, kind = "numeric")
  ))
  values$importance_check <- sum(seq_along(nm$past) * g$w_past)
  values$attention_check <- sum(seq_len(L0 + 1L) * g$attention)
}
if (identical(PARAMS$quantile_grid, "deciles") && length(bt_rows)) {
  # A weighted sum of every native quantile the backtests wrote (q_<100 tau> columns), so both engines agree.
  qkeys <- grep("^q_", names(bt_rows[[1]]), value = TRUE)
  wq <- as.numeric(outer(seq_along(qkeys), seq_along(bt_rows), function(j, i) i * j))
  qv <- unlist(lapply(bt_rows, function(r) unlist(r[qkeys])), use.names = FALSE)
  values$q_check <- sum(wq * qv) / sum(wq)
}
# %% 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 = "Temporal Fusion Transformer forecast (TFT)",
  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

2 series, one model each: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 77.1 over 2 origins.

MAE
77.069
RMSE
139.99
MAPE
0.0843

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

Backtest accuracy (2 origins, horizon 6)

MetricValue
MAE77.069
RMSE139.99
MAPE0.0843
sMAPE0.0804
MASE0.5916
WAPE0.0991
Coverage of the 80% interval0.9167
Coverage of the 95% interval1

Variable importance (average selection weight; past and future inputs each add up to 1)

InputRead forWeight
deathsPast0.1553
season (sin)Past0.3350
season (cos)Past0.0817
time indexPast0.4279
season (sin)Future0.3664
season (cos)Future0.4606
time indexFuture0.1730

Forecast

SeriesmonthForecast80% low80% high95% low95% high
female1980-01-01702.31581.53803.98455.36845.33
female1980-02-01706.05578.32802.34458.71844.07
female1980-03-01698.20560.92806.51451.30843.60
female1980-04-01620.01427.03794.52393.23807.68
female1980-05-01461.16372.69547.20266.25634.72
female1980-06-01427.68406.51461.52271.21556.81
male1980-01-011811.031494.262080.581152.892192.20
male1980-02-011821.941487.842076.351162.542189.67
male1980-03-011799.721438.482087.361140.852187.70
male1980-04-011562.401054.102033.01968.822076.31
male1980-05-011153.65960.781359.35671.321597.69
male1980-06-011077.141059.091148.24703.281402.15
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Temporal Fusion Transformer forecast (TFT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.tft 1.1.0 · spec 2298914eec1dcf63
# Dataset: ml_deaths (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 tft  # twin of codesplashr::cs_tft_* (torch, shared initial weights)

# %% Data
TIME = "month"
VALUE = "deaths"
SERIES = "sex"
H = 6
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
FUTURE_COV = []  # known-future covariates: values given for the forecast steps
PAST_COV = []  # past-only covariates: observed up to now, not ahead
PAST_ONLY = [c for c in PAST_COV if c not in FUTURE_COV]
XREG = FUTURE_COV + PAST_ONLY

PARAMS = {
    "window": None,
    "d_model": 8,
    "heads": 2,
    "epochs": 12,
    "learning_rate": 0.005,
    "batch_size": 32,
    "weight_decay": 0.001,
    "quantile_grid": "intervals",
    "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_deaths.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.tft/panel_static_batches/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.tft/panel_static_batches/out-python",
)
# Temporal Fusion Transformer: ONE network trained on the windows of every series, with variable selection over the
# target, the covariates, the season position and a time index; an LSTM encoder-decoder; interpretable attention and
# quantile outputs. The driver asks for one series and origin at a time, so the network for each origin (its distance
# from the end of the series) is trained once on all series cut at that origin and reused for every series.
_GLOBAL = {}
_FULL = {}
KIDX = [XREG.index(c) for c in FUTURE_COV]
PIDX = [XREG.index(c) for c in PAST_ONLY]


def _cols(x, idx):
    return None if x is None or not idx else np.asarray(x, dtype=np.float64)[:, idx]


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
            x_raw = None
            if XREG:  # rows after the last observed value carry known future covariates
                x_raw = x_all[sel]
                last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
                later = t_raw > last_y
                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, _ = 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
            m = int(SEASON) if SEASON else int(freq["season"])
            _FULL[key] = ([float(v) for v in t], [float(v) for v in y], m, x_grid)
    return _FULL


def min_train(m):
    return tft.window_length(PARAMS["window"], H, m) + H + 9


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:
        items = []
        for sidx, key in enumerate(keys):
            t_k, y_k, m_k, x_k = full[key]
            o = len(y_k) - d
            if o <= 0:
                continue
            start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
            xs = None if x_k is None else x_k[start:o]
            items.append(tft.prepare_item(y_k[start:o], _cols(xs, KIDX), _cols(xs, PIDX), m_k, start, sidx))
        _GLOBAL[d] = tft.fit_global(
            items, h, tft.window_length(PARAMS["window"], h, m), levels, len(keys), any(v[2] > 1 for v in full.values()),
            d_model=int(PARAMS["d_model"]),
            heads=int(PARAMS["heads"]),
            epochs=int(PARAMS["epochs"]),
            lr=PARAMS["learning_rate"],
            batch_size=PARAMS["batch_size"],
            weight_decay=PARAMS["weight_decay"],
            seed=SEED,
            extra_quantiles=tft.DECILES if PARAMS["quantile_grid"] == "deciles" else (),  # more quantiles to learn (Wave 8)
        )
    item = tft.prepare_item(
        list(y), _cols(X_TRAIN, KIDX), _cols(X_TRAIN, PIDX), m, times.index(float(t[0])), keys.index(current_series),
        known_future=_cols(X_FUTURE, KIDX),
    )
    return tft.forecast(_GLOBAL[d], item, h, levels)


# %% 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])
            # The network's own quantiles as q_<100·τ> columns (q_10, q_2_5 …), which the host's backtest scores read.
            for tau, qv in res["quantiles"].items():
                row[f"q_{lv(round(100.0 * tau, 6))}"] = float(qv[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"),
            },
        )
    )

# %% Variable importance and attention (the final model)
if 0 in _GLOBAL:
    g = _GLOBAL[0]
    names_p, names_f = tft.variable_names(VALUE, PAST_ONLY, FUTURE_COV, g["use_season"])
    imp_rows = [{"input": names_p[j], "where": "Past", "weight": g["w_past"][j]} for j in range(len(names_p))]
    imp_rows += [{"input": names_f[j], "where": "Future", "weight": g["w_future"][j]} for j in range(len(names_f))]
    extra_tables.append({
        "key": "importance",
        "title": "Variable importance (average selection weight; past and future inputs each add up to 1)",
        "columns": [{"key": "input", "label": "Input"}, {"key": "where", "label": "Read for"}, {"key": "weight", "label": "Weight", "type": "number"}],
        "rows": imp_rows,
    })
    charts.append(cs.chart("importance_past", "importance-bar", "Variable importance: past inputs", {
        "feature": cs.col("input", names_p, kind="categorical"),
        "importance": cs.col("selection weight", g["w_past"], kind="numeric"),
    }))
    if len(names_f) > 1:
        charts.append(cs.chart("importance_future", "importance-bar", "Variable importance: future inputs", {
            "feature": cs.col("input", names_f, kind="categorical"),
            "importance": cs.col("selection weight", g["w_future"], kind="numeric"),
        }))
    L0 = int(g["window"])
    charts.append(cs.chart("attention", "series-line", "Attention of the first forecast step over the lookback", {
        "x": cs.col("steps before the forecast", [float(j - L0) for j in range(L0 + 1)], kind="numeric"),
        "y": cs.col("attention weight", g["attention"], kind="numeric"),
    }))
    values["importance_check"] = fc._sum([(j + 1) * g["w_past"][j] for j in range(len(names_p))])
    values["attention_check"] = fc._sum([(j + 1) * g["attention"][j] for j in range(L0 + 1)])
if PARAMS["quantile_grid"] == "deciles" and bt_rows:
    # A weighted sum of every native quantile the backtests wrote (q_<100·τ> columns), so both engines agree.
    qkeys = [c for c in bt_rows[0] if c.startswith("q_")]
    wq = [(i + 1.0) * (j + 1.0) for i in range(len(bt_rows)) for j in range(len(qkeys))]
    values["q_check"] = fc._sum([wq[i * len(qkeys) + j] * bt_rows[i][qkeys[j]] for i in range(len(bt_rows)) for j in range(len(qkeys))]) / fc._sum(wq)
# %% 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": "Temporal Fusion Transformer forecast (TFT)",
        "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,
    }
)

With several series, the TFT also learns an embedding for each series (a static input). It feeds the variable selection and the start of the LSTM, so each series can get its own behavior from shared weights.

08

Adaptive conformal intervals

Read

Every forecaster's run page has an Uncertainty tab with conformal intervals built from the backtest errors. Split per horizon (the default) uses all the backtest errors at each horizon equally. Adaptive (ACI) walks through the backtest origins in time order. After each origin it widens the interval if the actual values fell outside and narrows it if they fell inside (adaptive conformal inferenceAdaptive conformal inferenceConformal intervals whose miss level moves after each origin, wider after misses and narrower after hits, so they follow change.).

When a series becomes more volatile, split intervals keep their old width and start missing. Adaptive intervals catch up. Their long-run miss rate stays near the target whatever the data, but with only a few origins they barely move, so add backtest origins first.

09

Check: transformer forecasters

Checkpoint

Check yourself

How does PatchTST produce a 12-step forecast?

Show the answer

Answer: a

PatchTST forecasts directly: one output per step ahead, so errors don't feed back into later steps.

Check yourself

What is a patch in PatchTST?

Show the answer

Answer: a

Patches of P values start every S steps; attention runs over the patches instead of over every step.

Check yourself

In a TFT run, the petrol price gets the largest past selection weight. What can you conclude?

Show the answer

Answer: a

Selection weights describe what the network used. They aren't causal, and another input may carry the same information.

Check yourself

Where do the TFT's prediction intervals come from?

Show the answer

Answer: a

The TFT predicts the median and the bounds of each interval level; the Uncertainty tab can add conformal intervals beside them.

Check yourself

When do adaptive (ACI) intervals help most compared with split conformal intervals?

Show the answer

Answer: a

ACI adjusts after each origin, so it follows a change in the errors. With very few origins it can hardly move.

Concepts in this lesson