Patches and pretrained forecasters: PatchTST, Chronos and TimesFM
Transformers read a series in chunks. PatchTST embeds short patches; Chronos scales a series and turns values into tokens for a language model; TimesFM reads continuous patches with a decoder. Build each input step and backtest two of them.
What runs in CodeSplash
- SPE019PatchTST Runs in CodeSplash (Experimental)
- SEQ014Chronos: tokenized probabilistic time-series forecasting Runs in CodeSplash
- SEQ015TimesFM: decoder-only time-series foundation model Explained here
- PatchTST forecast (patch Transformer) Experimental
- Chronos zero-shot forecast Checked in one engine
You will be able to
- Cut a series into patches and say how patch length and stride set the token count
- Turn values into Chronos-style tokens and back, and say what binning loses
- Contrast Chronos's discrete tokens with TimesFM's continuous patches
- Backtest a pretrained forecaster against a naive forecast before trusting it
From values to tokens
ReadA Transformer works on a sequence of tokens. A series of numbers can become tokens in three ways, and the three models here each pick one:
- PatchTST cuts the series into short patches and embeds each patch as a vector.
- Chronos scales the series and maps every value to one of a fixed set of bins, read like words.
- TimesFM cuts continuous patches, like PatchTST, but is pretrained on a huge collection of series and forecasts with a decoder.
The choice decides what detail survives, how long a context fits, and whether the model needs training on your data.
PatchTST: patches as tokens
ReadPatchTSTPatchTSTA Transformer that reads the recent past as short patches (tokens) and forecasts every step ahead at once. splits each series into patchesTime-series patchA short run of consecutive values treated as one token, so a Transformer attends over a few patches, not every step. of length with stride , and embeds each with shared weights:
Fewer, richer tokens than one per time step keep local shape and shorten attention. With channel independenceChannel independenceEvery series is fed through the same network on its own; series share the weights but never mix inside a window., every series goes through the same backbone separately, which shares strength but can't model one series driving another.
In the reference's example two channels of length 12, cut into patches of 4 with stride 2, give a token array of shape 2 × 5 × 3: channels, patches, embedding width.
Reference · SPE019 · Runs in CodeSplashPatchTSTPatchTST uses short temporal patches as transformer tokens and shares a backbone across univariate channels. Patching reduces token count and preserves local temporal structure;Patches by hand
Exploreimport numpy as np
X = np.array([np.sin(np.arange(12.) / 3), np.cos(np.arange(12.) / 3)]) # 2 channels
length, stride = 4, 2
patches = np.stack([X[:, s:s + length] for s in range(0, 12 - length + 1, stride)], axis=1)
tokens = patches @ (np.arange(12.).reshape(4, 3) / 12) # shared embedding
print(tokens.shape, tokens[0, 0])X <- rbind(sin(0:11 / 3), cos(0:11 / 3)) # 2 channels
len <- 4; stride <- 2; starts <- seq(1, 12 - len + 1, by = stride)
W <- matrix(0:11, 4, 3, byrow = TRUE) / 12 # shared embedding
tokens <- aperm(sapply(starts, function(s) X[, s:(s + len - 1)] %*% W, simplify = "array"), c(1, 3, 2))
print(dim(tokens)); print(tokens[1, 1, ]) # channel 1, patch 1Longer patches mean fewer tokens and a longer reach, but a short spike can vanish inside one patch.
PatchTST on the Nile
ExplorePatchTST (19 patches of 3, stride 1): 10-step forecasts of flow (evenly spaced data, 100 observations). Backtest MAE 154 over 2 origins.
- MAE
- 154.41
- RMSE
- 175.09
- MAPE
- 0.1722
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | year | flow |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | 1,871 | 1,120 |
| — | — | actual | — | — | 1,872 | 1,160 |
| — | — | actual | — | — | 1,873 | 963 |
| — | — | actual | — | — | 1,874 | 1,210 |
| — | — | actual | — | — | 1,875 | 1,160 |
| — | — | actual | — | — | 1,876 | 1,160 |
| — | — | actual | — | — | 1,877 | 813 |
| — | — | actual | — | — | 1,878 | 1,230 |
| — | — | actual | — | — | 1,879 | 1,370 |
| — | — | actual | — | — | 1,880 | 1,140 |
| — | — | actual | — | — | 1,881 | 995 |
| — | — | actual | — | — | 1,882 | 935 |
| — | — | actual | — | — | 1,883 | 1,110 |
| — | — | actual | — | — | 1,884 | 994 |
| — | — | actual | — | — | 1,885 | 1,020 |
| — | — | actual | — | — | 1,886 | 960 |
| — | — | actual | — | — | 1,887 | 1,180 |
| — | — | actual | — | — | 1,888 | 799 |
| — | — | actual | — | — | 1,889 | 958 |
| — | — | actual | — | — | 1,890 | 1,140 |
| — | — | actual | — | — | 1,891 | 1,100 |
| — | — | actual | — | — | 1,892 | 1,210 |
| — | — | actual | — | — | 1,893 | 1,150 |
| — | — | actual | — | — | 1,894 | 1,250 |
| — | — | actual | — | — | 1,895 | 1,260 |
| — | — | actual | — | — | 1,896 | 1,220 |
| — | — | actual | — | — | 1,897 | 1,030 |
| — | — | actual | — | — | 1,898 | 1,100 |
| — | — | actual | — | — | 1,899 | 774 |
| — | — | actual | — | — | 1,900 | 840 |
| — | — | actual | — | — | 1,901 | 874 |
| — | — | actual | — | — | 1,902 | 694 |
| — | — | actual | — | — | 1,903 | 940 |
| — | — | actual | — | — | 1,904 | 833 |
| — | — | actual | — | — | 1,905 | 701 |
| — | — | actual | — | — | 1,906 | 916 |
| — | — | actual | — | — | 1,907 | 692 |
| — | — | actual | — | — | 1,908 | 1,020 |
| — | — | actual | — | — | 1,909 | 1,050 |
| — | — | actual | — | — | 1,910 | 969 |
| — | — | actual | — | — | 1,911 | 831 |
| — | — | actual | — | — | 1,912 | 726 |
| — | — | actual | — | — | 1,913 | 456 |
| — | — | actual | — | — | 1,914 | 824 |
| — | — | actual | — | — | 1,915 | 702 |
| — | — | actual | — | — | 1,916 | 1,120 |
| — | — | actual | — | — | 1,917 | 1,100 |
| — | — | actual | — | — | 1,918 | 832 |
| — | — | actual | — | — | 1,919 | 764 |
| — | — | actual | — | — | 1,920 | 821 |
| — | — | actual | — | — | 1,921 | 768 |
| — | — | actual | — | — | 1,922 | 845 |
| — | — | actual | — | — | 1,923 | 864 |
| — | — | actual | — | — | 1,924 | 862 |
| — | — | actual | — | — | 1,925 | 698 |
| — | — | actual | — | — | 1,926 | 845 |
| — | — | actual | — | — | 1,927 | 744 |
| — | — | actual | — | — | 1,928 | 796 |
| — | — | actual | — | — | 1,929 | 1,040 |
| — | — | actual | — | — | 1,930 | 759 |
First 60 of 110 rows.
View data
| error | horizon | origin |
|---|---|---|
| −69.748 | 1 | 1950 |
| −156.66 | 2 | 1950 |
| −36.600 | 3 | 1950 |
| 236.84 | 4 | 1950 |
| 133.38 | 5 | 1950 |
| 151.32 | 6 | 1950 |
| 144.94 | 7 | 1950 |
| 232.04 | 8 | 1950 |
| 291.60 | 9 | 1950 |
| 94.946 | 10 | 1950 |
| 236.38 | 1 | 1960 |
| −53.980 | 2 | 1960 |
| 190.76 | 3 | 1960 |
| 329.64 | 4 | 1960 |
| 147.07 | 5 | 1960 |
| −150.57 | 6 | 1960 |
| −62.295 | 7 | 1960 |
| −215.85 | 8 | 1960 |
| −20.584 | 9 | 1960 |
| −133.04 | 10 | 1960 |
View data
| ACF | bound | lag |
|---|---|---|
| 0.0972 | 0.2191 | 1 |
| 0.0725 | 0.2191 | 2 |
| −0.1324 | 0.2191 | 3 |
| −0.1207 | 0.2191 | 4 |
| −0.1124 | 0.2191 | 5 |
| −0.2482 | 0.2191 | 6 |
| −0.0134 | 0.2191 | 7 |
| 0.2598 | 0.2191 | 8 |
| 0.0052 | 0.2191 | 9 |
| 0.1965 | 0.2191 | 10 |
Backtest accuracy (2 origins, horizon 10)
| Metric | Value |
|---|---|
| MAE | 154.41 |
| RMSE | 175.09 |
| MAPE | 0.1722 |
| sMAPE | 0.1813 |
| MASE | 1.160 |
| WAPE | 0.1761 |
| Coverage of the 80% interval | 0.2000 |
| Coverage of the 95% interval | 0.2500 |
Forecast
| year | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1,971 | 779.23 | 716.20 | 842.25 | 682.83 | 875.62 |
| 1,972 | 1061.84 | 999.89 | 1123.79 | 967.10 | 1156.58 |
| 1,973 | 966.66 | 900.72 | 1032.61 | 865.80 | 1067.52 |
| 1,974 | 973.35 | 911.66 | 1035.04 | 879.00 | 1067.70 |
| 1,975 | 981.10 | 900.71 | 1061.50 | 858.15 | 1104.06 |
| 1,976 | 773.34 | 693.36 | 853.31 | 651.03 | 895.65 |
| 1,977 | 934.31 | 855.49 | 1013.12 | 813.77 | 1054.85 |
| 1,978 | 957.12 | 887.79 | 1026.45 | 851.09 | 1063.15 |
| 1,979 | 1050.28 | 967.99 | 1132.58 | 924.42 | 1176.14 |
| 1,980 | 1047.78 | 972.90 | 1122.65 | 933.26 | 1162.29 |
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 44602a317e46c110
# Dataset: ml_nile (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 <- "year"
VALUE <- "flow"
SERIES <- NULL
H <- 10
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 = 12,
heads = 3,
layers = 1,
epochs = 30,
learning_rate = 0.01,
batch_size = NULL,
weight_decay = 0.001,
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_nile.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/numeric_time_wide/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/numeric_time_wide/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
))
PatchTST (19 patches of 3, stride 1): 10-step forecasts of flow (evenly spaced data, 100 observations). Backtest MAE 154 over 2 origins.
- MAE
- 154.41
- RMSE
- 175.09
- MAPE
- 0.1722
To keep this page light, the plots are shown once, under the R tab.
Backtest accuracy (2 origins, horizon 10)
| Metric | Value |
|---|---|
| MAE | 154.41 |
| RMSE | 175.09 |
| MAPE | 0.1722 |
| sMAPE | 0.1813 |
| MASE | 1.160 |
| WAPE | 0.1761 |
| Coverage of the 80% interval | 0.2000 |
| Coverage of the 95% interval | 0.2500 |
Forecast
| year | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1,971 | 779.23 | 716.20 | 842.25 | 682.83 | 875.62 |
| 1,972 | 1061.84 | 999.89 | 1123.79 | 967.10 | 1156.58 |
| 1,973 | 966.66 | 900.72 | 1032.61 | 865.80 | 1067.52 |
| 1,974 | 973.35 | 911.66 | 1035.04 | 879.00 | 1067.70 |
| 1,975 | 981.10 | 900.71 | 1061.50 | 858.15 | 1104.06 |
| 1,976 | 773.34 | 693.36 | 853.31 | 651.03 | 895.65 |
| 1,977 | 934.31 | 855.49 | 1013.12 | 813.77 | 1054.85 |
| 1,978 | 957.12 | 887.79 | 1026.45 | 851.09 | 1063.15 |
| 1,979 | 1050.28 | 967.99 | 1132.58 | 924.42 | 1176.14 |
| 1,980 | 1047.78 | 972.90 | 1122.65 | 933.26 | 1162.29 |
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 44602a317e46c110
# Dataset: ml_nile (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 = "year"
VALUE = "flow"
SERIES = None
H = 10
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": 12,
"heads": 3,
"layers": 1,
"epochs": 30,
"learning_rate": 0.01,
"batch_size": None,
"weight_decay": 0.001,
"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_nile.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/numeric_time_wide/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/numeric_time_wide/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,
}
)
On a century of Nile flows, the run uses 19 patches of 3 years and forecasts ten years from two origins. Its MASE is 1.16, above 1, so it loses to the naive forecast, and its 80% intervals cover only 20.0% of the actual values. A hundred points is little data to train a Transformer from scratch.
Chronos: values become words
ReadChronosChronosAmazon's family of pretrained forecasting models; Chronos-Bolt reads the history in patches and predicts its 10%–90% quantiles. reuses a language-model architecture. Series tokenizationSeries tokenizationChronos's input step. It scales a series by its mean level, then maps each value to one of a fixed set of bins, read as tokens. divides the context by its mean absolute value, , then maps each to one of a fixed set of bins. The model is trained to predict the next token,
and forecasts by sampling tokens and mapping them back through bin centers and . Sampled paths give quantiles. Binning rounds values, and very large values saturate the outer bins.
Pretrained on many series, it forecasts new ones zero-shot: no training on your data. Later releases (Chronos-Bolt, Chronos-2) changed the architecture and outputs, so record which one you used.
Reference · SEQ014 · Runs in CodeSplashChronos: tokenized probabilistic time-series forecastingThe original Chronos family treats scaled and quantized time-series observations as discrete tokens and trains language-model architectures for probabilistic forecasting.Bins by hand
ExploreThe reference uses six bins of width 1 from −3 to 3. The values , and fall in bins 0, 2 and 4 (counting from 0) and come back as −2.5, −0.5 and 1.5: the bin centers. Real Chronos uses thousands of narrower bins after scaling.
import numpy as np
values = np.array([-2.4, -.3, 1.8]); edges = np.linspace(-3., 3., 7); centers = (edges[:-1] + edges[1:]) / 2
bins = np.clip(np.digitize(values, edges) - 1, 0, len(centers) - 1)
print(bins, centers[bins]) # tokens, values decoded from tokensvalues <- c(-2.4, -.3, 1.8); edges <- seq(-3, 3, length.out = 7); centers <- (head(edges, -1) + tail(edges, -1)) / 2
bins <- pmin(pmax(findInterval(values, edges), 1), length(centers))
print(list(tokens_zero_based = bins - 1, decoded = centers[bins]))TimesFM: continuous patches, decoder only
ReadTimesFMTimesFMA pretrained decoder-only forecaster that reads a series as continuous patches and predicts the next patches; not built in CodeSplash. keeps the values continuous. It cuts the history into patches, embeds each with a small network and runs a decoder-only Transformer: each position sees only earlier patches and predicts the next output patch. The original version was trained with a squared-error loss for point forecasts; later releases added quantile heads.
The reference cuts eight values into two patches of four, with means 2.5 and 3.5. Patching is the whole input step; the learning happens in the pretrained stack.
Reference · SEQ015 · Explained hereTimesFM: decoder-only time-series foundation modelA pretrained time-series model using continuous-valued patches and a decoder-only Transformer to support forecasting across many series.A pretrained forecaster on the Nile
PredictPredict first
Chronos-Bolt Tiny forecasts the same ten Nile years zero-shot, from the last 48 years of context. Its relative MAE compares it with the naive forecast (1 means equal). What do you expect?
Reveal
About as good: 1.02. Better than PatchTST trained from scratch here, but no gain over carrying the last value forward. Pretraining helps most on series like those it was trained on; a long, slowly wandering annual series gives it little to add. Always backtest against a naive forecast.
Chronos-Bolt Tiny (zero-shot): 10-step forecasts of flow (evenly spaced data, 100 observations). Backtest MAE 112 over 2 origins.
- MAE
- 111.85
- RMSE
- 133.64
- MAPE
- 0.1258
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | year | flow |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | 1,871 | 1,120 |
| — | — | actual | — | — | 1,872 | 1,160 |
| — | — | actual | — | — | 1,873 | 963 |
| — | — | actual | — | — | 1,874 | 1,210 |
| — | — | actual | — | — | 1,875 | 1,160 |
| — | — | actual | — | — | 1,876 | 1,160 |
| — | — | actual | — | — | 1,877 | 813 |
| — | — | actual | — | — | 1,878 | 1,230 |
| — | — | actual | — | — | 1,879 | 1,370 |
| — | — | actual | — | — | 1,880 | 1,140 |
| — | — | actual | — | — | 1,881 | 995 |
| — | — | actual | — | — | 1,882 | 935 |
| — | — | actual | — | — | 1,883 | 1,110 |
| — | — | actual | — | — | 1,884 | 994 |
| — | — | actual | — | — | 1,885 | 1,020 |
| — | — | actual | — | — | 1,886 | 960 |
| — | — | actual | — | — | 1,887 | 1,180 |
| — | — | actual | — | — | 1,888 | 799 |
| — | — | actual | — | — | 1,889 | 958 |
| — | — | actual | — | — | 1,890 | 1,140 |
| — | — | actual | — | — | 1,891 | 1,100 |
| — | — | actual | — | — | 1,892 | 1,210 |
| — | — | actual | — | — | 1,893 | 1,150 |
| — | — | actual | — | — | 1,894 | 1,250 |
| — | — | actual | — | — | 1,895 | 1,260 |
| — | — | actual | — | — | 1,896 | 1,220 |
| — | — | actual | — | — | 1,897 | 1,030 |
| — | — | actual | — | — | 1,898 | 1,100 |
| — | — | actual | — | — | 1,899 | 774 |
| — | — | actual | — | — | 1,900 | 840 |
| — | — | actual | — | — | 1,901 | 874 |
| — | — | actual | — | — | 1,902 | 694 |
| — | — | actual | — | — | 1,903 | 940 |
| — | — | actual | — | — | 1,904 | 833 |
| — | — | actual | — | — | 1,905 | 701 |
| — | — | actual | — | — | 1,906 | 916 |
| — | — | actual | — | — | 1,907 | 692 |
| — | — | actual | — | — | 1,908 | 1,020 |
| — | — | actual | — | — | 1,909 | 1,050 |
| — | — | actual | — | — | 1,910 | 969 |
| — | — | actual | — | — | 1,911 | 831 |
| — | — | actual | — | — | 1,912 | 726 |
| — | — | actual | — | — | 1,913 | 456 |
| — | — | actual | — | — | 1,914 | 824 |
| — | — | actual | — | — | 1,915 | 702 |
| — | — | actual | — | — | 1,916 | 1,120 |
| — | — | actual | — | — | 1,917 | 1,100 |
| — | — | actual | — | — | 1,918 | 832 |
| — | — | actual | — | — | 1,919 | 764 |
| — | — | actual | — | — | 1,920 | 821 |
| — | — | actual | — | — | 1,921 | 768 |
| — | — | actual | — | — | 1,922 | 845 |
| — | — | actual | — | — | 1,923 | 864 |
| — | — | actual | — | — | 1,924 | 862 |
| — | — | actual | — | — | 1,925 | 698 |
| — | — | actual | — | — | 1,926 | 845 |
| — | — | actual | — | — | 1,927 | 744 |
| — | — | actual | — | — | 1,928 | 796 |
| — | — | actual | — | — | 1,929 | 1,040 |
| — | — | actual | — | — | 1,930 | 759 |
First 60 of 110 rows.
View data
| error | horizon | origin |
|---|---|---|
| −140.47 | 1 | 1950 |
| −120.50 | 2 | 1950 |
| 0.1300 | 3 | 1950 |
| 240.94 | 4 | 1950 |
| 117.18 | 5 | 1950 |
| 149.06 | 6 | 1950 |
| −83.634 | 7 | 1950 |
| 25.884 | 8 | 1950 |
| 100.84 | 9 | 1950 |
| −25.219 | 10 | 1950 |
| 180.37 | 1 | 1960 |
| 57.683 | 2 | 1960 |
| 52.623 | 3 | 1960 |
| 320.65 | 4 | 1960 |
| 61.529 | 5 | 1960 |
| −109.37 | 6 | 1960 |
| 70.601 | 7 | 1960 |
| −128.04 | 8 | 1960 |
| −132.68 | 9 | 1960 |
| −119.62 | 10 | 1960 |
View data
| quantile | year | flow |
|---|---|---|
| — | 1,941 | 649 |
| — | 1,942 | 846 |
| — | 1,943 | 812 |
| — | 1,944 | 742 |
| — | 1,945 | 801 |
| — | 1,946 | 1,040 |
| — | 1,947 | 860 |
| — | 1,948 | 874 |
| — | 1,949 | 848 |
| — | 1,950 | 890 |
| — | 1,951 | 744 |
| — | 1,952 | 749 |
| — | 1,953 | 838 |
| — | 1,954 | 1,050 |
| — | 1,955 | 918 |
| — | 1,956 | 986 |
| — | 1,957 | 797 |
| — | 1,958 | 923 |
| — | 1,959 | 975 |
| — | 1,960 | 815 |
| — | 1,961 | 1,020 |
| — | 1,962 | 906 |
| — | 1,963 | 901 |
| — | 1,964 | 1,170 |
| — | 1,965 | 912 |
| — | 1,966 | 746 |
| — | 1,967 | 919 |
| — | 1,968 | 718 |
| — | 1,969 | 714 |
| — | 1,970 | 740 |
| 0.1000 | 1,971 | 698.72 |
| 0.1000 | 1,972 | 703.93 |
| 0.1000 | 1,973 | 709.83 |
| 0.1000 | 1,974 | 714.33 |
| 0.1000 | 1,975 | 714.58 |
| 0.1000 | 1,976 | 721.11 |
| 0.1000 | 1,977 | 732.00 |
| 0.1000 | 1,978 | 745.14 |
| 0.1000 | 1,979 | 749.06 |
| 0.1000 | 1,980 | 744.77 |
| 0.2000 | 1,971 | 728.75 |
| 0.2000 | 1,972 | 735.43 |
| 0.2000 | 1,973 | 742.19 |
| 0.2000 | 1,974 | 747.74 |
| 0.2000 | 1,975 | 749.23 |
| 0.2000 | 1,976 | 756.42 |
| 0.2000 | 1,977 | 768.01 |
| 0.2000 | 1,978 | 783.73 |
| 0.2000 | 1,979 | 788.52 |
| 0.2000 | 1,980 | 784.64 |
| 0.3000 | 1,971 | 752.40 |
| 0.3000 | 1,972 | 761.40 |
| 0.3000 | 1,973 | 769.89 |
| 0.3000 | 1,974 | 776.74 |
| 0.3000 | 1,975 | 779.33 |
| 0.3000 | 1,976 | 786.90 |
| 0.3000 | 1,977 | 799.06 |
| 0.3000 | 1,978 | 816.61 |
| 0.3000 | 1,979 | 821.78 |
| 0.3000 | 1,980 | 818.08 |
First 60 of 120 rows.
Assumptions
- Horizon within the model's training — Horizon 10; Chronos-Bolt predicts up to 64 steps at once.
- Enough history for the model — The model read 48 values. Fewer than 64 (four patches of 16) leaves little pattern to recognize.
- Beats the seasonal naive forecast — Backtest MAE is 1.02 times the seasonal naive forecast's from the same origins. Repeating the last season forecast these origins at least as well.
Backtest accuracy (2 origins, horizon 10)
| Metric | Value |
|---|---|
| MAE | 111.85 |
| RMSE | 133.64 |
| MAPE | 0.1258 |
| sMAPE | 0.1278 |
| MASE | 0.8406 |
| WAPE | 0.1275 |
| Coverage of the 50% interval | 0.3500 |
| Coverage of the 80% interval | 0.8000 |
| Coverage of the 95% interval | 0.9500 |
The model's quantiles (the 50% quantile is the forecast)
| year | 10% | 20% | 30% | 40% | 50% | 60% | 70% | 80% | 90% |
|---|---|---|---|---|---|---|---|---|---|
| 1,971 | 698.72 | 728.75 | 752.40 | 775.61 | 799.35 | 824.90 | 854.37 | 892.49 | 953.84 |
| 1,972 | 703.93 | 735.43 | 761.40 | 786.56 | 812.36 | 839.61 | 871.92 | 912.97 | 979.88 |
| 1,973 | 709.83 | 742.19 | 769.89 | 796.74 | 823.57 | 852.33 | 885.82 | 929.32 | 997.39 |
| 1,974 | 714.33 | 747.74 | 776.74 | 805.26 | 833.46 | 863.33 | 898.13 | 942.82 | 1012.43 |
| 1,975 | 714.58 | 749.23 | 779.33 | 808.01 | 837.22 | 868.42 | 904.93 | 950.79 | 1022.50 |
| 1,976 | 721.11 | 756.42 | 786.90 | 816.65 | 846.99 | 879.50 | 917.12 | 964.24 | 1039.05 |
| 1,977 | 732.00 | 768.01 | 799.06 | 830.19 | 862.03 | 896.28 | 935.83 | 985.57 | 1062.82 |
| 1,978 | 745.14 | 783.73 | 816.61 | 848.77 | 882.31 | 918.00 | 959.03 | 1010.59 | 1090.97 |
| 1,979 | 749.06 | 788.52 | 821.78 | 854.33 | 888.23 | 924.69 | 967.19 | 1020.01 | 1101.35 |
| 1,980 | 744.77 | 784.64 | 818.08 | 851.04 | 885.81 | 923.60 | 966.67 | 1020.25 | 1102.83 |
Pretrained weights
| Item | Value |
|---|---|
| Model | Chronos-Bolt Tiny (9M parameters) |
| Source | huggingface.co/amazon/chronos-bolt-tiny |
| Revision | a0e552de83495b5c28c14c71c374f3e33280b340 |
| License | Apache-2.0 |
| Download size | 34.6 MB |
Forecast
| year | Forecast | 50% low | 50% high | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|---|
| 1,971 | 799.35 | 740.57 | 873.43 | 698.72 | 953.84 | 645.44 | 1035.62 |
| 1,972 | 812.36 | 748.42 | 892.44 | 703.93 | 979.88 | 646.53 | 1068.57 |
| 1,973 | 823.57 | 756.04 | 907.57 | 709.83 | 997.39 | 649.62 | 1089.41 |
| 1,974 | 833.46 | 762.24 | 920.47 | 714.33 | 1012.43 | 651.27 | 1107.17 |
| 1,975 | 837.22 | 764.28 | 927.86 | 714.58 | 1022.50 | 649.66 | 1120.59 |
| 1,976 | 846.99 | 771.66 | 940.68 | 721.11 | 1039.05 | 654.47 | 1140.72 |
| 1,977 | 862.03 | 783.53 | 960.70 | 732.00 | 1062.82 | 663.16 | 1169.10 |
| 1,978 | 882.31 | 800.17 | 984.81 | 745.14 | 1090.97 | 672.52 | 1201.43 |
| 1,979 | 888.23 | 805.15 | 993.60 | 749.06 | 1101.35 | 675.39 | 1214.17 |
| 1,980 | 885.81 | 801.36 | 993.46 | 744.77 | 1102.83 | 670.12 | 1217.71 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Chronos zero-shot forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.chronos 1.1.1 · spec b3829008f804dbd6
# Dataset: ml_nile (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.deep import chronos as cbolt # pretrained weights, looked up locally only (never downloaded here)
# %% Data
TIME = "year"
VALUE = "flow"
SERIES = None
H = 10
LEVELS = [float(v) for v in [50, 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 = {
"model": "bolt_tiny",
"context": 48,
}
df = pd.read_parquet("tests/parity/fixtures/ml_nile.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.chronos/tiny_numeric_time_short_context/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
# Chronos-Bolt (Ansari et al. 2024) is pretrained: it reads the recent history and predicts quantiles of the next
# steps without training on this series. Python only — the weights run through the chronos-forecasting package.
# The weights must already be on this computer (the app downloads them only after you confirm the size).
FINAL = {}
WEIGHTS = cbolt.locate(PARAMS["model"]) # stops with CS_WEIGHTS_MISSING and the download size when absent
def min_train(m):
return 8
def prepare_series(y, t, m, freq):
return None
def fit_forecast(y, t, h, m, levels, spec):
res = cbolt.fit_forecast(y, h, m, levels, model=PARAMS["model"], context=PARAMS["context"])
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% 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"),
},
)
)
# %% Quantiles and checks
res0, t0 = FINAL[series_keys[0]]
spec0 = cbolt.MODELS[PARAMS["model"]]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
lq0, q0 = res0["quantile_levels"], res0["quantiles"]
wq = [(j + 1.0) * (k + 1.0) for j in range(len(lq0)) for k in range(H)]
values["q_check"] = fc._sum([wq[j * H + k] * float(q0[j, k]) for j in range(len(lq0)) for k in range(H)]) / fc._sum(wq)
values["weights_label"] = spec0["label"]
suffix0 = f" — {series_keys[0]}" if SERIES else ""
hist0 = min(len(t0), max(3 * H, 24))
y0 = [r["mean"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
th0 = [r["time"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
charts.append(
cs.chart(
"quantiles",
"quantile-fan",
f"Chronos quantiles for {VALUE}" + suffix0,
{
"time": cs.col(TIME, th0 + [times0[k] for j in range(len(lq0)) for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, y0 + [float(q0[j, k]) for j in range(len(lq0)) for k in range(H)], kind="numeric"),
"quantile": cs.col("quantile", [None] * len(y0) + [lq0[j] for j in range(len(lq0)) for k in range(H)], kind="numeric"),
},
)
)
extra_tables.append(
{
"key": "quantiles",
"title": "The model's quantiles (the 50% quantile is the forecast)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"q{int(round(p * 100))}", "label": f"{int(round(p * 100))}%", "type": "number"} for p in lq0],
"rows": [dict({"time": times0[k]}, **{f"q{int(round(p * 100))}": float(q0[j, k]) for j, p in enumerate(lq0)}) for k in range(H)],
}
)
extra_tables.append(
{
"key": "weights",
"title": "Pretrained weights",
"columns": [{"key": "item", "label": "Item"}, {"key": "value", "label": "Value"}],
"rows": [
{"item": "Model", "value": f"{spec0['label']} ({spec0['params']} parameters)"},
{"item": "Source", "value": f"huggingface.co/{spec0['repo']}"},
{"item": "Revision", "value": spec0["revision"]},
{"item": "License", "value": "Apache-2.0"},
{"item": "Download size", "value": cbolt.size_text(spec0["bytes"])},
],
}
)
extra_assumptions.append(
{
"key": "horizon_trained",
"label": "Horizon within the model's training",
"status": "pass" if H <= cbolt.TRAINED_HORIZON else "warn",
"statistic": float(H),
"detail": f"Horizon {H}; Chronos-Bolt predicts up to {cbolt.TRAINED_HORIZON} steps at once." + ("" if H <= cbolt.TRAINED_HORIZON else " Later steps feed the model's own forecasts back, so they can drift."),
}
)
ctx0 = int(res0["facts"]["context"])
extra_assumptions.append(
{
"key": "context_length",
"label": "Enough history for the model",
"status": "pass" if ctx0 >= 64 else "warn",
"statistic": float(ctx0),
"detail": f"The model read {ctx0} values." + ("" if ctx0 >= 64 else " Fewer than 64 (four patches of 16) leaves little pattern to recognize."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
if H > cbolt.TRAINED_HORIZON:
warnings.append(f"Chronos-Bolt was trained for up to {cbolt.TRAINED_HORIZON} steps; steps beyond that are rolled forward from its own forecasts.")
# %% 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": "Chronos zero-shot forecast",
"engine": cs.engine_info("chronos-forecasting", "torch", "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,
}
)
What runs here
ReadCheck: patches and pretrained forecasters
CheckpointCheck yourself
A window of 20 values is cut into patches of length 4 with stride 4. How many tokens does PatchTST see per channel?
Show the answer
Answer: b
With stride equal to the patch length the patches don't overlap: tokens instead of 20.
Check yourself
PatchTST runs each channel through the same backbone separately. What can't it learn that way?
Show the answer
Answer: b
Channel independence shares weights but not information across channels. Cross-series effects need an extension.
Check yourself
PatchTST trained on one 100-point series loses to the naive forecast. What is the most likely reason?
Show the answer
Answer: a
Deep forecasters need many windows, often across many series. On short single series, simple baselines are hard to beat.
Check yourself
How does the original Chronos turn a series into tokens?
Show the answer
Answer: b
Scaling plus binning gives a vocabulary a language model can predict. Decoding maps tokens back through bin centers.
Check yourself
A series suddenly jumps far above anything in its context. What does fixed binning do to it?
Show the answer
Answer: a
Finite bins discretize the support. Extremes saturate, and binning loses precision everywhere.
Check yourself
A zero-shot forecaster's relative MAE on your backtest is about 1. What does that tell you?
Show the answer
Answer: b
Relative MAE compares with the naive (or seasonal naive) forecast. About 1 means no gain.
Check yourself
How does the original TimesFM's input differ from the original Chronos's?
Show the answer
Answer: a
TimesFM keeps values continuous and predicts output patches with a decoder-only stack.
Check yourself
Someone proposes TimesFM because "it was pretrained on billions of points". What should still happen before it's used?
Show the answer
Answer: b
Pretraining coverage helps on similar series. It doesn't remove the need for baselines and honest backtests.
Recap
Recap- PatchTST embeds patches; length and stride set the token count. Channel independence shares weights, not information.
- Chronos scales and bins values into tokens; binning rounds and saturates.
- TimesFM reads continuous patches with a decoder; it is explained here, not built.
- Backtest every pretrained forecaster against a naive forecast. PatchTST runs; Chronos runs in Python only.
Concepts in this lesson