DForecasting · forecast.timegrad
TimeGrad diffusion forecast (joint sample paths)
Can a diffusion model, conditioned on a recurrent network that reads every series together, draw realistic joint futures for related series?
TimeGrad (Rasul et al. 2021) treats the values of all series at one time step as a single point. A recurrent network (GRU) reads the past points; a denoising diffusion model, given the network's state, learns to turn random noise into the next point step by step. Forecasts are sample paths drawn one step at a time and fed back in, so each path is a joint future for every series and keeps their co-movement. The point forecast is the paths' mean, the intervals are their quantiles, and the backtests are scored with the exact CRPS of the sample (and the energy score across series). Both engines train the same networks from the same initial weights and draw the same noise. Experimental: a small network suited to a few related series.
A real result
Example “Panel deaths”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
2 series, one model each: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 285 over 2 origins.
- MAE
- 284.74
- RMSE
- 365.85
- MAPE
- 0.3672
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | sex | month | deaths |
|---|---|---|---|---|---|---|---|
| — | — | actual | — | — | female | 126,230,400,000 | 901 |
| — | — | actual | — | — | female | 128,908,800,000 | 689 |
| — | — | actual | — | — | female | 131,328,000,000 | 827 |
| — | — | actual | — | — | female | 134,006,400,000 | 677 |
| — | — | actual | — | — | female | 136,598,400,000 | 522 |
| — | — | actual | — | — | female | 139,276,800,000 | 406 |
| — | — | actual | — | — | female | 141,868,800,000 | 441 |
| — | — | actual | — | — | female | 144,547,200,000 | 393 |
| — | — | actual | — | — | female | 147,225,600,000 | 387 |
| — | — | actual | — | — | female | 149,817,600,000 | 582 |
| — | — | actual | — | — | female | 152,496,000,000 | 578 |
| — | — | actual | — | — | female | 155,088,000,000 | 666 |
| — | — | actual | — | — | female | 157,766,400,000 | 830 |
| — | — | actual | — | — | female | 160,444,800,000 | 752 |
| — | — | actual | — | — | female | 162,864,000,000 | 785 |
| — | — | actual | — | — | female | 165,542,400,000 | 664 |
| — | — | actual | — | — | female | 168,134,400,000 | 467 |
| — | — | actual | — | — | female | 170,812,800,000 | 438 |
| — | — | actual | — | — | female | 173,404,800,000 | 421 |
| — | — | actual | — | — | female | 176,083,200,000 | 412 |
| — | — | actual | — | — | female | 178,761,600,000 | 343 |
| — | — | actual | — | — | female | 181,353,600,000 | 440 |
| — | — | actual | — | — | female | 184,032,000,000 | 531 |
| — | — | actual | — | — | female | 186,624,000,000 | 771 |
| — | — | actual | — | — | female | 189,302,400,000 | 767 |
| — | — | actual | — | — | female | 191,980,800,000 | 1,141 |
| — | — | actual | — | — | female | 194,486,400,000 | 896 |
| — | — | actual | — | — | female | 197,164,800,000 | 532 |
| — | — | actual | — | — | female | 199,756,800,000 | 447 |
| — | — | actual | — | — | female | 202,435,200,000 | 420 |
| — | — | actual | — | — | female | 205,027,200,000 | 376 |
| — | — | actual | — | — | female | 207,705,600,000 | 330 |
| — | — | actual | — | — | female | 210,384,000,000 | 357 |
| — | — | actual | — | — | female | 212,976,000,000 | 445 |
| — | — | actual | — | — | female | 215,654,400,000 | 546 |
| — | — | actual | — | — | female | 218,246,400,000 | 764 |
| — | — | actual | — | — | female | 220,924,800,000 | 862 |
| — | — | actual | — | — | female | 223,603,200,000 | 660 |
| — | — | actual | — | — | female | 226,022,400,000 | 663 |
| — | — | actual | — | — | female | 228,700,800,000 | 643 |
| — | — | actual | — | — | female | 231,292,800,000 | 502 |
| — | — | actual | — | — | female | 233,971,200,000 | 392 |
| — | — | actual | — | — | female | 236,563,200,000 | 411 |
| — | — | actual | — | — | female | 239,241,600,000 | 348 |
| — | — | actual | — | — | female | 241,920,000,000 | 387 |
| — | — | actual | — | — | female | 244,512,000,000 | 385 |
| — | — | actual | — | — | female | 247,190,400,000 | 411 |
| — | — | actual | — | — | female | 249,782,400,000 | 638 |
| — | — | actual | — | — | female | 252,460,800,000 | 796 |
| — | — | actual | — | — | female | 255,139,200,000 | 853 |
| — | — | actual | — | — | female | 257,558,400,000 | 737 |
| — | — | actual | — | — | female | 260,236,800,000 | 546 |
| — | — | actual | — | — | female | 262,828,800,000 | 530 |
| — | — | actual | — | — | female | 265,507,200,000 | 446 |
| — | — | actual | — | — | female | 268,099,200,000 | 431 |
| — | — | actual | — | — | female | 270,777,600,000 | 362 |
| — | — | actual | — | — | female | 273,456,000,000 | 387 |
| — | — | actual | — | — | female | 276,048,000,000 | 430 |
| — | — | actual | — | — | female | 278,726,400,000 | 425 |
| — | — | actual | — | — | female | 281,318,400,000 | 679 |
First 60 of 156 rows.
View data
| error | horizon | origin |
|---|---|---|
| −116.52 | 1 | 1979-06-01 |
| −176.21 | 2 | 1979-06-01 |
| −212.40 | 3 | 1979-06-01 |
| −139.24 | 4 | 1979-06-01 |
| −52.458 | 5 | 1979-06-01 |
| 42.529 | 6 | 1979-06-01 |
| −549.13 | 1 | 1979-06-01 |
| −547.15 | 2 | 1979-06-01 |
| −705.39 | 3 | 1979-06-01 |
| −589.99 | 4 | 1979-06-01 |
| −92.652 | 5 | 1979-06-01 |
| −193.17 | 6 | 1979-06-01 |
Assumptions
- Series end together — Every series has the same time steps, so the joint model sees them side by side.
Backtest accuracy (2 origins, horizon 6)
| Metric | Value |
|---|---|
| MAE | 284.74 |
| RMSE | 365.85 |
| MAPE | 0.3672 |
| sMAPE | 0.2960 |
| MASE | 2.117 |
| WAPE | 0.3660 |
| Coverage of the 80% interval | 0.8333 |
| Coverage of the 95% interval | 1 |
Backtest CRPS of the sample paths by horizon
| Horizon | CRPS | Forecasts |
|---|---|---|
| 1 | 204.86 | 2 |
| 2 | 224.77 | 2 |
| 3 | 318.37 | 2 |
| 4 | 218.56 | 2 |
| 5 | 80.512 | 2 |
| 6 | 118.12 | 2 |
Forecast
| Series | month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|
| female | 1980-01-01 | 530.12 | 337.46 | 739.90 | 275.97 | 794.93 |
| female | 1980-02-01 | 556.19 | 410.22 | 693.92 | 191.65 | 782.90 |
| female | 1980-03-01 | 600.31 | 405.92 | 785.90 | 322.68 | 854.57 |
| female | 1980-04-01 | 540.96 | 367.24 | 742.03 | 303.74 | 839.17 |
| female | 1980-05-01 | 527.64 | 358.22 | 717.71 | 294.67 | 774.04 |
| female | 1980-06-01 | 518.35 | 326.97 | 728.37 | 282.82 | 853.15 |
| male | 1980-01-01 | 1580.55 | 774.58 | 2286.22 | 449.54 | 2534.56 |
| male | 1980-02-01 | 1496.30 | 820.04 | 2396.40 | −13.842 | 2530.68 |
| male | 1980-03-01 | 1618.83 | 701.85 | 2287.98 | 410.85 | 2596.65 |
| male | 1980-04-01 | 1636.95 | 825.54 | 2379.97 | 206.04 | 2783.93 |
| male | 1980-05-01 | 1349.08 | 853.35 | 1982.06 | 422.76 | 2458.95 |
| male | 1980-06-01 | 1493.61 | 353.68 | 2345.00 | −50.513 | 2667.92 |
2 series, one model each: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 285 over 2 origins.
- MAE
- 284.74
- RMSE
- 365.85
- MAPE
- 0.3672
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Series end together — Every series has the same time steps, so the joint model sees them side by side.
Backtest accuracy (2 origins, horizon 6)
| Metric | Value |
|---|---|
| MAE | 284.74 |
| RMSE | 365.85 |
| MAPE | 0.3672 |
| sMAPE | 0.2960 |
| MASE | 2.117 |
| WAPE | 0.3660 |
| Coverage of the 80% interval | 0.8333 |
| Coverage of the 95% interval | 1 |
Backtest CRPS of the sample paths by horizon
| Horizon | CRPS | Forecasts |
|---|---|---|
| 1 | 204.86 | 2 |
| 2 | 224.77 | 2 |
| 3 | 318.37 | 2 |
| 4 | 218.56 | 2 |
| 5 | 80.512 | 2 |
| 6 | 118.12 | 2 |
Forecast
| Series | month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|
| female | 1980-01-01 | 530.12 | 337.46 | 739.90 | 275.97 | 794.93 |
| female | 1980-02-01 | 556.19 | 410.22 | 693.92 | 191.65 | 782.90 |
| female | 1980-03-01 | 600.31 | 405.92 | 785.90 | 322.68 | 854.57 |
| female | 1980-04-01 | 540.96 | 367.24 | 742.03 | 303.74 | 839.17 |
| female | 1980-05-01 | 527.64 | 358.22 | 717.71 | 294.67 | 774.04 |
| female | 1980-06-01 | 518.35 | 326.97 | 728.37 | 282.82 | 853.15 |
| male | 1980-01-01 | 1580.55 | 774.58 | 2286.22 | 449.54 | 2534.56 |
| male | 1980-02-01 | 1496.30 | 820.04 | 2396.40 | −13.842 | 2530.68 |
| male | 1980-03-01 | 1618.83 | 701.85 | 2287.98 | 410.85 | 2596.65 |
| male | 1980-04-01 | 1636.95 | 825.54 | 2379.97 | 206.04 | 2783.93 |
| male | 1980-05-01 | 1349.08 | 853.35 | 1982.06 | 422.76 | 2458.95 |
| male | 1980-06-01 | 1493.61 | 353.68 | 2345.00 | −50.513 | 2667.92 |
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Panel deathsml_deaths · series: sex · time: month · value: deaths
- Var panel batchesf7_var_panel · series: region · time: month · value: y1
- Single seriesml_airpassengers · time: month · value: passengers
- Numeric timeml_nile · time: year · value: flow
- Degenerate infml_airpassengers · time: month · value: passengers
- Degenerate one group leftml_deaths · series: sex · time: month · value: deaths
- Degenerate all naml_airpassengers · time: month · value: passengers
In the guides
Where it sits in the decision guides
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
- Deep learning (CNN, RNN, Transformer) · DS & ML Decision Guide · Predict — forecast or classify outcomes
- Deep-learning forecasting · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Timetemporal / numeric · 1 column
- Dates or evenly spaced numbers; gaps are filled by linear interpolation.
- Valuenumeric · 1 column
- What to forecast.
- Seriescategorical · 0–1 column
- Optional: related series in long format, modeled together so their paths move jointly.
Choices you make
model
- Recurrent unitsdefault 16
Size of the GRU state that summarizes the past for the diffusion model.
- Denoiser hidden layers (units)default 32,32
Units in each hidden layer of the network that predicts the noise.
- Diffusion stepsdefault 50
Noise levels between data and pure noise; each forecast step runs this many denoising passes, so more steps cost more time.
- Context lengthdefault —
Recent values the network reads before it starts drawing the forecast.
- Sample pathsdefault 100
Joint forecast paths drawn. More paths give steadier means, quantiles and scores.
- Epochsdefault 200
Training passes over all windows.
- Learning ratedefault 0.005
Adam's step size.
Advanced
- Step embedding sizedefault 8
Length of the sine–cosine code that tells the denoiser which noise level it sees.
- Batch sizedefault —
Windows per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).
- Optimizerdefault default
How the weights are updated. The method's own choice is the usual one.
- Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
- Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
- AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
- SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
- Learning-rate scheduledefault none
How the learning rate changes over training.
- Constant(default) — The same learning rate every epoch (the method's default).
- Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
- Step — Divides the learning rate by 10 after each third of the epochs.
- One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
- Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
- Warm-up epochsdefault 0
Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.
- Gradient clippingdefault 0
Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.
- Weight average (EMA)default 0
Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.
- Weight average from epoch (SWA)default 0
Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.
- Record every stepdefault off
Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.
- Compute profiledefault parity
Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.
- Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
- Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
- Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
- Checkpoint every (epochs)default —
Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.
- Train fromdefault —
Leave out rows before this date or number, for example before a structural break. Empty uses every row.
- Training windowdefault —
Train each backtest on only this many values before its origin (a sliding window). Empty uses all of them.
- Backtest plandefault —
Set by forecast experiments: each origin's distance from the end of the series, shared by all their models.
options
- Horizondefault 12
Steps ahead to forecast.
- Interval levels (%)default 80,95
Coverage of the prediction intervals: quantiles of the sample paths, in percent (80% and 95% by default).
- Season lengthdefault —
Observations per seasonal cycle (12 monthly, 4 quarterly, 7 daily …); automatic reads the time steps. It sets the default context length.
validation
- Backtest originsdefault 3
Refit on the data up to each origin and forecast the next horizon (0 = no backtest).
- Origin spacingdefault —
Periods between backtest origins. Leave empty to step by the horizon, so the test windows don't overlap.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Series end together
Series are lined up at their last value and the model uses the stretch they all share, so the shortest series limits the training data.
What it reports
- n_obs
- How many independent units the analysis used; it sets precision and power.
- horizon
- How many periods ahead a forecast predicts; uncertainty grows with the horizon.
- season
- A pattern that repeats at a fixed period — daily, weekly, yearly.
- n_series
- How many series a run forecast. With a series column in long format, each one gets its own model and its own backtest.
- fc_check
- A single weighted average of the whole forecast, later steps counting more, so two runs or engines can be compared with one number.
- n_origins
- How many points in the series a forecaster was refit from and scored against the values that followed.
- filled
- How many missing steps in the regular time grid were filled before fitting, so the series has no holes.
- model_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- freq_label
- The spacing of the time grid the forecaster used (daily, weekly, monthly …), as a code and in words.
- frequency
- The spacing of the time grid the forecaster used (daily, weekly, monthly …), as a code and in words.
Per group, level or term: bt[<metric>], context, epochs_run, final_loss, series_joint, windows, <fact>[<series>], fc_lo_check, fc_hi_check, crps_sample, energy_score, filled, freq_label, frequency, model_label, n_origins
Python and R
Python and R use different algorithms; results agree in substance (relative tolerance 1e-8). Python uses torch, codesplash; R uses torch, codesplashr.
Default traps between the two languages
- Lab tier. Both engines run the codesplash twin (codesplash.deep.timegrad ↔ codesplashr cs_tg_*): the GRU equations, the denoiser and Adam written out on LibTorch in double precision on one thread, from the same initial weights; diffusion steps, training noise and every sampling draw from the shared Wichmann–Hill stream, so the paths match draw for draw. Python's torch and R's torch ship different LibTorch builds, so a kernel can differ by an ulp, which training and the denoising chain can amplify; on the fixtures the values agree to about 1e-12.
- Choices written down: the denoiser is an MLP on [noisy vector, sine–cosine step code, GRU state] (the paper uses a small dilated convolution network); β runs linearly from 1e-4 to 0.1 over the diffusion steps and σ² is the posterior variance β̃; series are aligned at their last value and standardized by their own training mean and population SD; no lag or calendar covariates; the CRPS is the exact score of the paths' empirical distribution (1/(2m²) for the pair term), not the 'fair' variant.
The exact script CodeSplash ran for example “Panel deaths” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TimeGrad diffusion forecast (joint sample paths)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.timegrad 1.0.0 · spec 0959b6a762c61810
# Dataset: ml_deaths (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.errors import check_finite
from codesplash.deep import timegrad as tg # twin of codesplashr::cs_tg_* (torch, shared initial weights and draws)
# %% Data
TIME = "month"
VALUE = "deaths"
SERIES = "sex"
H = 6
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
"hidden_size": 6,
"denoiser_layers": [16],
"diffusion_steps": 10,
"step_embedding": 8,
"window": None,
"samples": 50,
"epochs": 30,
"learning_rate": 0.005,
"batch_size": None,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_deaths.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
cut = fc.parse_time(TRAIN_START, TEMPORAL)
early = np.nan_to_num(times_all, nan=np.inf) < cut
if early.any():
warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None] # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.timegrad/panel_deaths/out-python")
extra_tables = [] # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = [] # … and assumption rows
current_series = None
X_TRAIN = None # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/forecast.timegrad/panel_deaths/out-python",
)
# TimeGrad: a GRU reads every series together (one vector per time step) and a denoising diffusion model draws the
# next vector given the GRU's state, so the sample paths are joint across series. The driver asks for one series
# and origin at a time, so the model for each origin (its distance from the end of the series) is trained once on
# all series cut at that origin, its paths are drawn once, and each series reads its own column.
_GLOBAL = {} # origin offset → (model, joint paths S × h × D)
_FULL = {}
_ORIGIN = {} # (series, origin label) → origin offset, for the sample scores below
def _full_series():
if not _FULL:
for key in series_keys:
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
t_raw, y_raw = times_all[sel], values_all[sel]
if int(np.sum(~np.isnan(y_raw))) < 3: # too short to use; the driver stops on it with CS_E_TOO_FEW_ROWS
continue
freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t, y, _ = fc.regularize(t_raw, y_raw, freq)
m = int(SEASON) if SEASON else int(freq["season"])
_FULL[key] = ([float(v) for v in t], [float(v) for v in y], m)
return _FULL
def context_length(m):
"""The option, else two seasons (8 without a season)."""
return max(2, int(PARAMS["window"])) if PARAMS["window"] else (2 * int(m) if m > 1 else 8)
def min_train(m):
return context_length(m) + H + 2
def prepare_series(y, t, m, freq):
check_finite(y, VALUE) # CS_E_NOT_FINITE, like the R twin
return None
def fit_forecast(y, t, h, m, levels, spec):
full = _full_series()
keys = list(full.keys())
times = full[current_series][0]
d = len(times) - (times.index(float(t[-1])) + 1) # values after this origin
if d not in _GLOBAL:
train = []
for key in keys:
y_k = full[key][1]
o = len(y_k) - d
if o <= 0:
raise ValueError(f"series {key} has no values before this origin")
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
train.append(y_k[start:o])
C = context_length(m)
model = tg.fit_timegrad(
train, h,
context=C,
hidden=int(PARAMS["hidden_size"]),
denoiser=[int(u) for u in PARAMS["denoiser_layers"]],
diffusion_steps=int(PARAMS["diffusion_steps"]),
emb_dim=int(PARAMS["step_embedding"]),
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=PARAMS["batch_size"],
seed=SEED,
)
recent = np.column_stack([[(v - model["mu"][j]) / model["sd"][j] for v in s[len(s) - C :]] for j, s in enumerate(train)])
_GLOBAL[d] = (model, tg.sample_paths(model, recent, h, n_samples=int(PARAMS["samples"]), seed=SEED))
model, paths = _GLOBAL[d]
_ORIGIN[(current_series, fc.format_time(t[-1], TEMPORAL))] = d
P = paths[:, :, keys.index(current_series)]
mean = [fc._mean(P[:, s].tolist()) for s in range(h)]
lower, upper = {}, {}
for level in levels:
a = (1.0 - float(level) / 100.0) / 2.0
lower[level] = [tg.quantile7(P[:, s], a) for s in range(h)]
upper[level] = [tg.quantile7(P[:, s], 1.0 - a) for s in range(h)]
return {
"mean": mean,
"lower": lower,
"upper": upper,
"fitted": None,
"label": f"TimeGrad ({int(PARAMS['diffusion_steps'])} diffusion steps)",
"facts": {
"context": float(model["context"]),
"epochs_run": float(model["epochs_run"]),
"final_loss": model["final_loss"],
"series_joint": float(model["D"]),
"windows": float(model["windows"]),
},
}
# %% Backtests and forecasts
def lv(level):
return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")
bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
current_series = key # model blocks may read it (e.g. table titles)
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
t_raw, y_raw = times_all[sel], values_all[sel]
if int(np.sum(~np.isnan(y_raw))) < 3: # too few values to read the time step from
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
x_later = None
if XREG: # rows after the last observed value carry known future regressors
x_raw = x_all[sel]
last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
later = t_raw > last_y
order_later = np.argsort(t_raw[later], kind="stable")
x_later = x_raw[later][order_later]
t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t, y, nfill = fc.regularize(t_raw, y_raw, freq)
x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
filled += nfill
freq_label = freq["label"]
freq_alias = fc.ALIASES.get(freq["unit"], "")
m = int(SEASON) if SEASON else int(freq["season"])
seasons.append(m)
y = [float(v) for v in y]
n = len(y)
n_obs += n
if n < min_train(m) + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
spec = prepare_series(y, t, m, freq)
step = int(STEP) if STEP else H
if OFFSETS is not None:
origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
if len(origins) < len(OFFSETS):
warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
else:
origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
for o in origins:
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
if XREG:
X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
try:
res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
except Exception as e: # a failed origin is skipped, not fatal
warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
continue
n_origins += 1
scale = fc.mase_scale(y[:o], m)
scale2 = fc.rmsse_scale(y[:o], m)
lag = m if (m > 1 and o > m) else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for k in range(H):
row = {
"series": key,
"origin": fc.format_time(t[o - 1], TEMPORAL),
"time": fc.format_time(t[o + k], TEMPORAL),
"h": k + 1,
"actual": y[o + k],
"mean": float(res["mean"][k]),
"scale": scale,
"scale2": scale2,
"last": y[o - 1],
"snaive": y[o - lag + k % lag],
}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
bt_rows.append(row)
if XREG:
X_TRAIN = x_grid
X_FUTURE = fc.future_regressors(x_grid, x_later, H)
if len(x_later) < H:
warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
final = fit_forecast(y, t, H, m, LEVELS, spec)
labels[key] = final["label"]
for name, value in final["facts"].items():
facts[name if not SERIES else f"{name}[{key}]"] = value
fitted = final.get("fitted")
diag = DIAG.get(key) or {}
resid = diag.get("resid")
if residuals_first is None and resid is not None:
residuals_first = [float(v) for v in resid]
elif residuals_first is None and fitted is not None:
residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
for i in range(n):
row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
if resid is not None and i >= n - len(resid): # the last len(resid) times (differencing drops early ones)
row["resid"] = float(resid[i - (n - len(resid))])
if "fitdf" in diag:
row["lb_fitdf"] = float(diag["fitdf"])
if "lags" in diag:
row["lb_lags"] = float(diag["lags"])
fc_rows.append(row)
if fitted is not None and not math.isnan(fitted[i]):
fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
future = fc.future_times(t[-1], freq, H)
for k in range(H):
row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
fc_rows.append(row)
if filled:
warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")
# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None
def wsum(xs):
return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)
values = {
"n_series": len(series_keys),
"n_obs": n_obs,
"horizon": H,
"season": seasons[0],
"n_origins": n_origins,
"filled": filled,
"fc_check": wsum([r["mean"] for r in forecasts]),
"model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
"freq_label": freq_label,
"frequency": freq_alias,
}
if top:
values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
values[f"bt[{k}]"] = v
values.update(facts)
pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})
# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
"time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
"value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
"kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
if level in LEVELS:
roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
charts.append(
cs.chart(
"backtest",
"backtest-errors",
"Backtest errors by horizon",
{
"h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
"error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
"origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
},
)
)
if residuals_first and len(residuals_first) > 4:
lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
r_acf = fc.acf(residuals_first, lags)
bound = 1.959963984540054 / math.sqrt(len(residuals_first))
charts.append(
cs.chart(
"acf",
"acf-plot",
"Residual autocorrelation",
{
"lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
"acf": cs.col("ACF", r_acf, kind="numeric"),
"bound": cs.col("bound", [bound] * lags, kind="numeric"),
},
)
)
# %% Sample scores: the exact CRPS of every backtest forecast's sample, and the energy score of the joint paths
_KEYS = list(_full_series().keys())
_ends = {(len(v[1]), v[0][-1]) for v in _full_series().values()}
extra_assumptions.append({
"key": "aligned_series",
"label": "Series end together",
"status": "pass" if len(_ends) <= 1 else "warn",
"detail": "Every series has the same time steps, so the joint model sees them side by side." if len(_ends) <= 1
else f"The series differ in length or end time; they were lined up at their last value and the model used the last {min(n for n, _ in _ends)} values they share.",
})
_crps = []
_joint = {}
for r in bt_rows:
d = _ORIGIN.get((r["series"], r["origin"]))
if d is None or d not in _GLOBAL:
continue
paths_d = _GLOBAL[d][1]
_crps.append((r["h"], tg.crps_sample(paths_d[:, r["h"] - 1, _KEYS.index(r["series"])], r["actual"])))
_joint.setdefault((d, r["h"]), {})[r["series"]] = r["actual"]
if _crps:
values["crps_sample"] = fc._mean([c for _, c in _crps])
extra_tables.append({
"key": "crps_by_horizon",
"title": "Backtest CRPS of the sample paths by horizon",
"columns": [{"key": "h", "label": "Horizon", "type": "integer"}, {"key": "crps", "label": "CRPS", "type": "number"}, {"key": "n", "label": "Forecasts", "type": "integer"}],
"rows": [{"h": k, "crps": fc._mean([c for hh, c in _crps if hh == k]), "n": sum(1 for hh, _ in _crps if hh == k)} for k in range(1, H + 1) if any(hh == k for hh, _ in _crps)],
})
if len(_KEYS) > 1:
_es = [tg.energy_score(_GLOBAL[d][1][:, k - 1, :], np.array([act[s] for s in _KEYS])) for (d, k), act in sorted(_joint.items()) if len(act) == len(_KEYS)]
if _es:
values["energy_score"] = fc._mean(_es)
if 0 in _GLOBAL: # the final forecast's sample paths
_paths0 = _GLOBAL[0][1]
_rows = []
for j, key in enumerate(_KEYS):
for k in range(H):
for s in range(_paths0.shape[0]):
_rows.append({"series": key, "h": k + 1, "sample": s + 1, "value": float(_paths0[s, k, j])})
pd.DataFrame(_rows).to_parquet(os.path.join(out, "paths.parquet"), index=False)
artifacts.append({"key": "paths", "path": os.path.join(out, "paths.parquet"), "format": "parquet"})
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
tables.append(
{
"key": "accuracy",
"title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
"columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
+ [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
}
)
tables.extend(extra_tables)
tables.append(
{
"key": "forecast",
"title": "Forecast",
"columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
+ [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
+ [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
"rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
}
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
{
"title": "TimeGrad diffusion forecast (joint sample paths)",
"engine": cs.engine_info("torch", "codesplash", "numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
"tables": tables,
"values": values,
"assumptions": extra_assumptions,
"warnings": warnings,
"notes": [],
"charts": charts,
"artifacts": artifacts,
}
)
The exact script CodeSplash ran for example “Panel deaths” · R version 4.5.1 (2025-06-13)
# TimeGrad diffusion forecast (joint sample paths)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.timegrad 1.0.0 · spec 0959b6a762c61810
# Dataset: ml_deaths (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network and sampler are codesplashr's cs_tg_* twins.
# %% Data
TIME <- "month"
VALUE <- "deaths"
SERIES <- "sex"
H <- 6
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL # NULL = the horizon
OFFSETS <- NULL # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL # NULL = train on all values before each origin
TRAIN_START <- NULL # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
hidden_size = 6,
denoiser_layers = c(16),
diffusion_steps = 10,
step_embedding = 8,
window = NULL,
samples = 50,
epochs = 30,
learning_rate = 0.005,
batch_size = NULL,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_deaths.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
early <- !is.na(times_all) & times_all < cut
n_early <- sum(early)
if (n_early > 0) {
warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
times_all[early] <- NA
}
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.timegrad/panel_deaths/out-r")
extra_tables <- list() # model blocks may add result tables (assign with <<-)
extra_assumptions <- list() # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/forecast.timegrad/panel_deaths/out-r")
# TimeGrad: a GRU reads every series together (one vector per time step) and a denoising diffusion model draws the
# next vector given the GRU's state, so the sample paths are joint across series. The driver asks for one series
# and origin at a time, so the model for each origin (its distance from the end of the series) is trained once on
# all series cut at that origin, its paths are drawn once, and each series reads its own column.
.tg_global <- new.env() # origin offset -> list(model, joint paths S x h x D)
.tg_full <- NULL
.tg_origin <- new.env() # "series|origin label" -> origin offset, for the sample scores below
.tg_key <- function(key) if (is.null(key) || is.na(key)) "_" else key
.tg_full_series <- function() {
if (is.null(.tg_full)) {
full <- list()
for (key in series_keys) {
sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
t_raw <- times_all[sel]; y_raw <- values_all[sel]
if (sum(!is.na(y_raw)) < 3) next # too short to use; the driver stops on it with CS_E_TOO_FEW_ROWS
freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
full[[.tg_key(key)]] <- list(t = reg$t, y = reg$y, m = m)
}
.tg_full <<- full
}
.tg_full
}
context_length <- function(m) if (!is.null(PARAMS$window)) max(2L, as.integer(PARAMS$window)) else if (m > 1) 2L * as.integer(m) else 8L
min_train <- function(m) context_length(m) + H + 2
prepare_series <- function(y, t, m, freq) {
cs_check_finite(y, VALUE) # CS_E_NOT_FINITE, like the Python twin
NULL
}
fit_forecast <- function(y, t, h, m, levels, spec) {
full <- .tg_full_series()
keys <- names(full)
me <- .tg_key(current_series)
times <- full[[me]]$t
d <- length(times) - match(t[length(t)], times) # values after this origin
name <- as.character(d)
if (is.null(.tg_global[[name]])) {
train <- list()
for (s in full) {
o <- length(s$y) - d
if (o <= 0) stop("a series has no values before this origin")
start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
train[[length(train) + 1L]] <- s$y[start:o]
}
C <- context_length(m)
model <- cs_tg_fit(
train, h,
context = C,
hidden = as.integer(PARAMS$hidden_size),
denoiser = as.integer(unlist(PARAMS$denoiser_layers)),
diffusion_steps = as.integer(PARAMS$diffusion_steps),
emb_dim = as.integer(PARAMS$step_embedding),
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = PARAMS$batch_size,
seed = SEED
)
recent <- do.call(cbind, lapply(seq_along(train), function(j) {
s <- train[[j]]
(s[(length(s) - C + 1L):length(s)] - model$mu[j]) / model$sd[j]
}))
.tg_global[[name]] <- list(model = model, paths = cs_tg_sample(model, recent, h, n_samples = as.integer(PARAMS$samples), seed = SEED))
}
g <- .tg_global[[name]]
model <- g$model
.tg_origin[[paste0(me, "|", cs_ml_fc_format_time(t[length(t)], TEMPORAL))]] <- d
P <- matrix(g$paths[, , match(me, keys)], nrow = dim(g$paths)[1])
mean_ <- vapply(seq_len(h), function(s) sum(P[, s]) / nrow(P), numeric(1))
lower <- list(); upper <- list()
for (level in levels) {
a <- (1 - level / 100) / 2
lower[[as.character(level)]] <- vapply(seq_len(h), function(s) cs_tg_quantile7(P[, s], a), numeric(1))
upper[[as.character(level)]] <- vapply(seq_len(h), function(s) cs_tg_quantile7(P[, s], 1 - a), numeric(1))
}
list(mean = mean_, lower = lower, upper = upper, fitted = NULL,
label = sprintf("TimeGrad (%d diffusion steps)", as.integer(PARAMS$diffusion_steps)),
facts = list(context = as.numeric(model$context), epochs_run = as.numeric(model$epochs_run), final_loss = model$final_loss,
series_joint = as.numeric(model$D), windows = as.numeric(model$windows)))
}
# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
current_series <- key # model blocks may read it (e.g. table titles)
sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
t_raw <- times_all[sel]; y_raw <- values_all[sel]
if (sum(!is.na(y_raw)) < 3) { # too few values to read the time step from
cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
}
x_later <- NULL
if (length(XREG)) { # rows after the last observed value carry known future regressors
x_raw <- x_all[sel, , drop = FALSE]
last_y <- max(t_raw[!is.na(y_raw)])
later <- t_raw > last_y
x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
}
freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
t <- reg$t; y <- reg$y
x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
filled <- filled + reg$filled
freq_label <- freq$label
freq_alias <- cs_ml_fc_alias(freq$unit)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
seasons <- c(seasons, m)
n <- length(y)
n_obs <- n_obs + n
if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
spec <- prepare_series(y, t, m, freq)
step <- if (!is.null(STEP)) as.integer(STEP) else H
if (!is.null(OFFSETS)) {
origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
if (length(origins) < length(OFFSETS)) {
warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
}
} else {
origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
}
for (o in origins) {
start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
if (length(XREG)) {
X_TRAIN <- x_grid[start:o, , drop = FALSE]
X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
}
res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
if (inherits(res, "error")) {
warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
next
}
n_origins <- n_origins + 1
scale <- cs_ml_fc_mase_scale(y[1:o], m)
scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
lag <- if (m > 1 && o > m) m else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for (k in seq_len(H)) {
row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
snaive = y[o - lag + (k - 1) %% lag + 1])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
}
bt_rows[[length(bt_rows) + 1]] <- row
}
}
if (length(XREG)) {
X_TRAIN <- x_grid
X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
if (nrow(x_later) < H) {
warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
}
}
final <- fit_forecast(y, t, H, m, LEVELS, spec)
labels[[length(labels) + 1]] <- final$label
for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
fitted <- final$fitted
diag <- DIAG[[if (is.null(key)) "_" else key]]
resid <- diag$resid
if (is.null(residuals_first) && !is.null(resid)) {
residuals_first <- as.numeric(resid)
} else if (is.null(residuals_first) && !is.null(fitted)) {
ok <- !is.na(fitted)
residuals_first <- (y - fitted)[ok]
}
skey <- if (is.null(key)) NA_character_ else key
for (i in seq_len(n)) {
row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))] # the last length(resid) times
if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
fc_rows[[length(fc_rows) + 1]] <- row
if (!is.null(fitted) && !is.na(fitted[i])) {
fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
}
}
future <- cs_ml_fc_future_times(t[n], freq, H)
for (k in seq_len(H)) {
row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
}
fc_rows[[length(fc_rows) + 1]] <- row
}
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))
as_frame <- function(rows) {
cols <- unique(unlist(lapply(rows, names)))
as.data.frame(stats::setNames(lapply(cols, function(cn) {
v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
unlist(v)
}), cols), stringsAsFactors = FALSE, check.names = FALSE)
}
# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
filled = filled, fc_check = wsum(forecasts$mean),
model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)
nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}
# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(VALUE, fan$mean, kind = "numeric"),
kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
if (level %in% LEVELS) {
roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
}
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
h = cs_col("horizon", bt$h, kind = "numeric"),
error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
origin = cs_col("origin", bt$origin, kind = "categorical")
))
}
if (length(residuals_first) > 4) {
lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
r_acf <- cs_ml_fc_acf(residuals_first, lags)
bound <- 1.959963984540054 / sqrt(length(residuals_first))
charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
lag = cs_col("lag", seq_len(lags), kind = "numeric"),
acf = cs_col("ACF", r_acf, kind = "numeric"),
bound = cs_col("bound", rep(bound, lags), kind = "numeric")
))
}
# %% Sample scores: the exact CRPS of every backtest forecast's sample, and the energy score of the joint paths
.tg_keys <- names(.tg_full_series())
.tg_ends <- unique(vapply(.tg_full_series(), function(s) sprintf("%d|%.17g", length(s$y), s$t[length(s$t)]), character(1)))
.tg_minlen <- min(vapply(.tg_full_series(), function(s) length(s$y), integer(1)))
extra_assumptions[[length(extra_assumptions) + 1L]] <- list(
key = "aligned_series", label = "Series end together",
status = if (length(.tg_ends) <= 1L) "pass" else "warn",
detail = if (length(.tg_ends) <= 1L) "Every series has the same time steps, so the joint model sees them side by side."
else sprintf("The series differ in length or end time; they were lined up at their last value and the model used the last %d values they share.", .tg_minlen)
)
.tg_crps <- list()
.tg_joint <- list()
for (r in bt_rows) {
me <- .tg_key(r$series)
d <- .tg_origin[[paste0(me, "|", r$origin)]]
if (is.null(d) || is.null(.tg_global[[as.character(d)]])) next
paths_d <- .tg_global[[as.character(d)]]$paths
.tg_crps[[length(.tg_crps) + 1L]] <- c(r$h, cs_tg_crps(paths_d[, r$h, match(me, .tg_keys)], r$actual))
jk <- sprintf("%08d|%08d", as.integer(d), as.integer(r$h))
if (is.null(.tg_joint[[jk]])) .tg_joint[[jk]] <- list(d = d, h = r$h, act = list())
.tg_joint[[jk]]$act[[me]] <- r$actual
}
if (length(.tg_crps)) {
cm <- do.call(rbind, .tg_crps)
values$crps_sample <- sum(cm[, 2]) / nrow(cm)
hs <- sort(unique(cm[, 1]))
extra_tables[[length(extra_tables) + 1L]] <- list(
key = "crps_by_horizon",
title = "Backtest CRPS of the sample paths by horizon",
columns = list(list(key = "h", label = "Horizon", type = "integer"), list(key = "crps", label = "CRPS", type = "number"),
list(key = "n", label = "Forecasts", type = "integer")),
rows = lapply(hs, function(k) list(h = as.integer(k), crps = sum(cm[cm[, 1] == k, 2]) / sum(cm[, 1] == k), n = sum(cm[, 1] == k)))
)
}
if (length(.tg_keys) > 1L) {
es <- numeric(0)
for (jk in sort(names(.tg_joint))) {
g <- .tg_joint[[jk]]
if (length(g$act) != length(.tg_keys)) next
paths_d <- .tg_global[[as.character(g$d)]]$paths
es <- c(es, cs_tg_energy(matrix(paths_d[, g$h, ], nrow = dim(paths_d)[1]), vapply(.tg_keys, function(s) g$act[[s]], numeric(1))))
}
if (length(es)) values$energy_score <- sum(es) / length(es)
}
if (!is.null(.tg_global[["0"]])) { # the final forecast's sample paths
p0 <- .tg_global[["0"]]$paths
S0 <- dim(p0)[1]
prow <- list()
for (j in seq_along(.tg_keys)) for (k in seq_len(H)) {
prow[[length(prow) + 1L]] <- data.frame(series = if (identical(.tg_keys[j], "_")) NA_character_ else .tg_keys[j], h = k, sample = seq_len(S0), value = p0[, k, j])
}
nanoparquet::write_parquet(do.call(rbind, prow), file.path(out, "paths.parquet"))
artifacts[[length(artifacts) + 1L]] <- list(key = "paths", path = file.path(out, "paths.parquet"), format = "parquet")
}
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
for (level in LEVELS) {
ck <- paste0("coverage_", lv(level))
if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
}
tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
title = "TimeGrad diffusion forecast (joint sample paths)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n = n_obs,
summary = summary,
statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
tables = tables,
values = values,
assumptions = extra_assumptions,
warnings = warnings,
notes = list(),
charts = charts,
artifacts = artifacts
))
Sources
- Rasul K, Seward C, Schuster I, Vollgraf R (2021). Autoregressive denoising diffusion models for multivariate probabilistic time series forecasting. ICML 2021.
- Ho J, Jain A, Abbeel P (2020). Denoising diffusion probabilistic models. NeurIPS 2020.
- Gneiting T, Raftery AE (2007). Strictly proper scoring rules, prediction, and estimation. Journal of the American Statistical Association 102(477):359–378.
- Cho K, van Merriënboer B, Gulcehre C, et al. (2014). Learning phrase representations using RNN encoder–decoder for statistical machine translation. EMNLP 2014 (the GRU).
From the CodeSplash method registry · forecast.timegrad v1.0.0.