Skip to content

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.

Advanced ~16 min11 steps

What runs in CodeSplash

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

Read first

01

From values to tokens

Read

A 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.

02

PatchTST: patches as tokens

Read

PatchTSTPatchTSTA 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 pp with stride ss, and embeds each with shared weights:

Pc,j=(xc,js,…,xc,js+p−1),tc,j=WPc,j+b+ej.P_{c,j} = (x_{c,js}, \dots, x_{c,js+p-1}), \qquad t_{c,j} = W P_{c,j} + b + e_j .

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;
03

Patches by hand

Explore
Python
import 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])
R
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 1

Longer patches mean fewer tokens and a longer reach, but a short spike can vanish inside one patch.

04

PatchTST on the Nile

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

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

Plots

Forecast of flowWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95yearflow
——actual——1,8711,120
——actual——1,8721,160
——actual——1,873963
——actual——1,8741,210
——actual——1,8751,160
——actual——1,8761,160
——actual——1,877813
——actual——1,8781,230
——actual——1,8791,370
——actual——1,8801,140
——actual——1,881995
——actual——1,882935
——actual——1,8831,110
——actual——1,884994
——actual——1,8851,020
——actual——1,886960
——actual——1,8871,180
——actual——1,888799
——actual——1,889958
——actual——1,8901,140
——actual——1,8911,100
——actual——1,8921,210
——actual——1,8931,150
——actual——1,8941,250
——actual——1,8951,260
——actual——1,8961,220
——actual——1,8971,030
——actual——1,8981,100
——actual——1,899774
——actual——1,900840
——actual——1,901874
——actual——1,902694
——actual——1,903940
——actual——1,904833
——actual——1,905701
——actual——1,906916
——actual——1,907692
——actual——1,9081,020
——actual——1,9091,050
——actual——1,910969
——actual——1,911831
——actual——1,912726
——actual——1,913456
——actual——1,914824
——actual——1,915702
——actual——1,9161,120
——actual——1,9171,100
——actual——1,918832
——actual——1,919764
——actual——1,920821
——actual——1,921768
——actual——1,922845
——actual——1,923864
——actual——1,924862
——actual——1,925698
——actual——1,926845
——actual——1,927744
——actual——1,928796
——actual——1,9291,040
——actual——1,930759

First 60 of 110 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
−69.74811950
−156.6621950
−36.60031950
236.8441950
133.3851950
151.3261950
144.9471950
232.0481950
291.6091950
94.946101950
236.3811960
−53.98021960
190.7631960
329.6441960
147.0751960
−150.5761960
−62.29571960
−215.8581960
−20.58491960
−133.04101960
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.09720.21911
0.07250.21912
−0.13240.21913
−0.12070.21914
−0.11240.21915
−0.24820.21916
−0.01340.21917
0.25980.21918
0.00520.21919
0.19650.219110

Backtest accuracy (2 origins, horizon 10)

MetricValue
MAE154.41
RMSE175.09
MAPE0.1722
sMAPE0.1813
MASE1.160
WAPE0.1761
Coverage of the 80% interval0.2000
Coverage of the 95% interval0.2500

Forecast

yearForecast80% low80% high95% low95% high
1,971779.23716.20842.25682.83875.62
1,9721061.84999.891123.79967.101156.58
1,973966.66900.721032.61865.801067.52
1,974973.35911.661035.04879.001067.70
1,975981.10900.711061.50858.151104.06
1,976773.34693.36853.31651.03895.65
1,977934.31855.491013.12813.771054.85
1,978957.12887.791026.45851.091063.15
1,9791050.28967.991132.58924.421176.14
1,9801047.78972.901122.65933.261162.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
))
Python

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)

MetricValue
MAE154.41
RMSE175.09
MAPE0.1722
sMAPE0.1813
MASE1.160
WAPE0.1761
Coverage of the 80% interval0.2000
Coverage of the 95% interval0.2500

Forecast

yearForecast80% low80% high95% low95% high
1,971779.23716.20842.25682.83875.62
1,9721061.84999.891123.79967.101156.58
1,973966.66900.721032.61865.801067.52
1,974973.35911.661035.04879.001067.70
1,975981.10900.711061.50858.151104.06
1,976773.34693.36853.31651.03895.65
1,977934.31855.491013.12813.771054.85
1,978957.12887.791026.45851.091063.15
1,9791050.28967.991132.58924.421176.14
1,9801047.78972.901122.65933.261162.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.

05

Chronos: values become words

Read

ChronosChronosAmazon'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, ut=xt/su_t = x_t / s, then maps each utu_t to one of a fixed set of bins. The model is trained to predict the next token,

−∑tlog⁡pθ(bt∣b<t),-\sum_t \log p_\theta(b_t \mid b_{<t}),

and forecasts by sampling tokens and mapping them back through bin centers and ss. 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.
06

Bins by hand

Explore

The reference uses six bins of width 1 from −3 to 3. The values −2.4-2.4, −0.3-0.3 and 1.81.8 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.

Python
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 tokens
R
values <- 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]))
07

TimesFM: continuous patches, decoder only

Read

TimesFMTimesFMA 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.
08

A pretrained forecaster on the Nile

Predict

Predict 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?

Clearly better than the naive forecastAbout as good as the naive forecastClearly worse than the naive forecast
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 zero-shot forecastRecorded · one engineRecorded 2026-11-25 · 29 values compared
Python

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

Forecast of flowWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95yearflow
——actual——1,8711,120
——actual——1,8721,160
——actual——1,873963
——actual——1,8741,210
——actual——1,8751,160
——actual——1,8761,160
——actual——1,877813
——actual——1,8781,230
——actual——1,8791,370
——actual——1,8801,140
——actual——1,881995
——actual——1,882935
——actual——1,8831,110
——actual——1,884994
——actual——1,8851,020
——actual——1,886960
——actual——1,8871,180
——actual——1,888799
——actual——1,889958
——actual——1,8901,140
——actual——1,8911,100
——actual——1,8921,210
——actual——1,8931,150
——actual——1,8941,250
——actual——1,8951,260
——actual——1,8961,220
——actual——1,8971,030
——actual——1,8981,100
——actual——1,899774
——actual——1,900840
——actual——1,901874
——actual——1,902694
——actual——1,903940
——actual——1,904833
——actual——1,905701
——actual——1,906916
——actual——1,907692
——actual——1,9081,020
——actual——1,9091,050
——actual——1,910969
——actual——1,911831
——actual——1,912726
——actual——1,913456
——actual——1,914824
——actual——1,915702
——actual——1,9161,120
——actual——1,9171,100
——actual——1,918832
——actual——1,919764
——actual——1,920821
——actual——1,921768
——actual——1,922845
——actual——1,923864
——actual——1,924862
——actual——1,925698
——actual——1,926845
——actual——1,927744
——actual——1,928796
——actual——1,9291,040
——actual——1,930759

First 60 of 110 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
−140.4711950
−120.5021950
0.130031950
240.9441950
117.1851950
149.0661950
−83.63471950
25.88481950
100.8491950
−25.219101950
180.3711960
57.68321960
52.62331960
320.6541960
61.52951960
−109.3761960
70.60171960
−128.0481960
−132.6891960
−119.62101960
Chronos quantiles for flowWhat range of futures does a probabilistic forecaster expect, step by step?
View data
quantileyearflow
—1,941649
—1,942846
—1,943812
—1,944742
—1,945801
—1,9461,040
—1,947860
—1,948874
—1,949848
—1,950890
—1,951744
—1,952749
—1,953838
—1,9541,050
—1,955918
—1,956986
—1,957797
—1,958923
—1,959975
—1,960815
—1,9611,020
—1,962906
—1,963901
—1,9641,170
—1,965912
—1,966746
—1,967919
—1,968718
—1,969714
—1,970740
0.10001,971698.72
0.10001,972703.93
0.10001,973709.83
0.10001,974714.33
0.10001,975714.58
0.10001,976721.11
0.10001,977732.00
0.10001,978745.14
0.10001,979749.06
0.10001,980744.77
0.20001,971728.75
0.20001,972735.43
0.20001,973742.19
0.20001,974747.74
0.20001,975749.23
0.20001,976756.42
0.20001,977768.01
0.20001,978783.73
0.20001,979788.52
0.20001,980784.64
0.30001,971752.40
0.30001,972761.40
0.30001,973769.89
0.30001,974776.74
0.30001,975779.33
0.30001,976786.90
0.30001,977799.06
0.30001,978816.61
0.30001,979821.78
0.30001,980818.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)

MetricValue
MAE111.85
RMSE133.64
MAPE0.1258
sMAPE0.1278
MASE0.8406
WAPE0.1275
Coverage of the 50% interval0.3500
Coverage of the 80% interval0.8000
Coverage of the 95% interval0.9500

The model's quantiles (the 50% quantile is the forecast)

year10%20%30%40%50%60%70%80%90%
1,971698.72728.75752.40775.61799.35824.90854.37892.49953.84
1,972703.93735.43761.40786.56812.36839.61871.92912.97979.88
1,973709.83742.19769.89796.74823.57852.33885.82929.32997.39
1,974714.33747.74776.74805.26833.46863.33898.13942.821012.43
1,975714.58749.23779.33808.01837.22868.42904.93950.791022.50
1,976721.11756.42786.90816.65846.99879.50917.12964.241039.05
1,977732.00768.01799.06830.19862.03896.28935.83985.571062.82
1,978745.14783.73816.61848.77882.31918.00959.031010.591090.97
1,979749.06788.52821.78854.33888.23924.69967.191020.011101.35
1,980744.77784.64818.08851.04885.81923.60966.671020.251102.83

Pretrained weights

ItemValue
ModelChronos-Bolt Tiny (9M parameters)
Sourcehuggingface.co/amazon/chronos-bolt-tiny
Revisiona0e552de83495b5c28c14c71c374f3e33280b340
LicenseApache-2.0
Download size34.6 MB

Forecast

yearForecast50% low50% high80% low80% high95% low95% high
1,971799.35740.57873.43698.72953.84645.441035.62
1,972812.36748.42892.44703.93979.88646.531068.57
1,973823.57756.04907.57709.83997.39649.621089.41
1,974833.46762.24920.47714.331012.43651.271107.17
1,975837.22764.28927.86714.581022.50649.661120.59
1,976846.99771.66940.68721.111039.05654.471140.72
1,977862.03783.53960.70732.001062.82663.161169.10
1,978882.31800.17984.81745.141090.97672.521201.43
1,979888.23805.15993.60749.061101.35675.391214.17
1,980885.81801.36993.46744.771102.83670.121217.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,
    }
)
09

What runs here

Read
10

Check: patches and pretrained forecasters

Checkpoint

Check 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: 20/4=520 / 4 = 5 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.

11

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