Skip to content

Tabular, time-series, scientific, and geometric deep learning · Time-series forecasting and representation · SPE017 · Architecture

Temporal Fusion Transformer (TFT)

TFT combines static context, known future covariates and observed historical inputs for multi-horizon forecasting.

Runs in CodeSplash (Experimental) Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page. The methods that run it are Experimental.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Availability
Runs in CodeSplash (Experimental)
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through forecast.tft. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

TFT combines static context, known future covariates and observed historical inputs for multi-horizon forecasting. Variable-selection and gating components allow inspection of model behavior while attention models longer-range temporal relationships.

Question / hypotheses

The operative question is whether the specified representation, symmetry, likelihood or physical constraint improves held-out behavior for this data domain. This is a learning framework, not a null-hypothesis test; losses, attention weights and predictive confidence are not statistical p-values.

Architecture / computational structure

Static encoders and variable-selection networks feed recurrent local processing, gated residual components, static enrichment and temporal attention. Output heads predict quantiles across forecast horizons.

Assumptions

Known future features must be truly available at forecast time. Attention and variable-selection weights are descriptive, not causal. Quantile crossing, leakage from scaling and series/seasonality shift can undermine interpretation.

Formula / computational definition

L=∑t,h,qρq(yt+h−y^t,h,q)L=\sum_{t,h,q}\rho_q(y_{t+h}-\hat y_{t,h,q}), where ρq(e)=max⁡(qe,(q−1)e)\rho_q(e)=\max(qe,(q-1)e) is pinball loss. Feature weights arise from variable-selection networks; time attention must respect the allowed historical/future information design.

Parameters and notation

Learned or estimated: Variable-selection/gating networks, static embeddings, recurrent and attention weights, enrichment projections and quantile heads.

Hyperparameters and effects: Lookback/horizon, quantiles, hidden widths, heads, dropout, covariate partition, optimizer and batch construction. Quantile coverage and tail accuracy depend on loss choices and data, not simply on attention size.

Fitting, fine-tuning, and adaptation

Fit quantile loss with rolling-origin validation and explicit static/known/observed feature roles. For transfer, fit target embeddings/heads while freezing shared temporal blocks, then unfreeze at a smaller rate. Recalibrate target quantiles and monitor source horizons for forgetting. Architecture changes to available covariates require retraining compatible selection layers.

How to use and calibrate

Define the independent evaluation unit before preprocessing: row/entity, whole set/object, molecule/trajectory, input function or chronological forecasting origin. Keep target construction and normalization within permitted training data. Evaluate pinball loss, interval coverage/width, point metrics, horizon-specific errors and sensitivity to covariate availability. Compare against recurrent, linear and seasonal baselines; audit attention stability across seeds.

Example application

Forecast several future horizons using historical measurements and a legitimately known operating schedule. This is a proposed use case, not a claim of validated performance on supplied real data.

Interpretation / pitfalls

Watch out

Assess model error against domain baselines and the stated assumptions. Component-level mathematical correctness does not establish paper reproduction or scientific validity. Use an independent validation design for model selection and a final held-out evaluation for claims; uncertainty and calibration require separate assessment.

Python and R code examples

Scope: TFT-style multi-horizon quantile loss and quantile-crossing diagnostic. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.

Full-model route: Python: an audited TFT implementation. R: custom native torch or Python bridge. The snippets compute multi-quantile pinball loss and a crossing diagnostic, not a full TFT forward pass.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — TFT-style multi-horizon quantile loss and quantile-crossing diagnostic. Use the shared setup.

Shared setup for this chapter
import numpy as np
def sm(x):
    x=np.asarray(x); e=np.exp(x-x.max(axis=-1,keepdims=True)); return e/e.sum(axis=-1,keepdims=True)
truth=np.array([1.,2.]); quantiles=np.array([.1,.5,.9])
prediction=np.array([[.7,1.1,1.4],[1.5,1.9,2.5]])
error=truth[:,None]-prediction
loss=np.maximum(quantiles*error,(quantiles-1)*error).mean()
crossing=np.any(np.diff(prediction,axis=1)<0)
print(loss,'crossing',crossing)
R

Component demo, not a trained model — TFT-style multi-horizon quantile loss and quantile-crossing diagnostic. Use the shared setup.

Shared setup for this chapter
sm <- function(x) {
  if(is.null(dim(x))) { e<-exp(x-max(x)); return(e/sum(e)) }
  t(apply(x,1,function(v) { e<-exp(v-max(v)); e/sum(e) }))
}
truth<-c(1,2); quantiles<-c(.1,.5,.9)
prediction<-matrix(c(.7,1.1,1.4,1.5,1.9,2.5),2,byrow=TRUE)
error<-truth-prediction; q<-matrix(quantiles,2,3,byrow=TRUE)
loss<-mean(pmax(q*error,(q-1)*error))
crossing<-any(apply(prediction,1,diff)<0); print(list(loss=loss,crossing=crossing))

Sources

From the CodeSplash reference, entry SPE017.