Search

Search papers and lessons

Temporal Fusion Transformers for Interpretable Multi-horizon Forecasting

Bryan Lim, Sercan O. Arik, Nicolas Loeff et al. · 2019

The Temporal Fusion Transformer forecasts many future steps at once, handles static, known and observed inputs separately, and shows which inputs and past times mattered.

On this page

  • Colour = topic mix
  • Probability
  • Neural network basics
  • Calculus
  • Discrete math
  • Linear algebra
  • Architectures
  • ReadReady to readNot yet

TL;DR

The Temporal Fusion Transformer (TFT) is a neural network that predicts several future values of a series at once, with a prediction range for each. It treats three kinds of input differently: fixed facts about each entity (a store's location), things known in advance (a holiday next week), and things only seen so far (yesterday's foot traffic). It uses gates to switch off unneeded parts, and an attention layer whose weights can be read back as "which past times mattered." On four real datasets it beat the benchmarks the authors compared against, by 7 percent on median-forecast loss and 9 percent on the 90th-percentile loss, on average.

Builds on: Time Series Forecasting, Long Short-Term Memory, Multi-Head Attention, Quantile Regression · Leads to: Transformer (the attention design it modifies for readability)

Why it mattered

Many real forecasting problems mix inputs of different kinds, and most deep models of the time handled only some of them. The paper's introduction gives examples: a retailer planning stock for a whole season, or a clinician planning treatment over several steps. In retail, the inputs include product and store metadata, promotions scheduled in advance, and sales that are only observed as they happen.

Earlier multi-horizon models often assumed that all other inputs were also known in the future, which fails for things like foot traffic. Attention models for time series could show which time steps mattered, but not which input variable mattered at a given time. Post-hoc explanation methods such as LIME and SHAP ignore the time order of inputs. TFT was built to do both jobs: forecast accurately and show its reasoning in terms a user can check.

The problem

Each entity i (a store, a patient, a stock index) has three kinds of data. Static covariates s are fixed over time. Observed inputs z are measured only up to the forecast time. Known inputs x are predetermined, such as the day of the week, and are available for future steps too. The target is y.

Given a lookback window of k past steps, the model must output a forecast for each of the next τ steps, up to τ_max, and for each quantile q. A quantile is a point on the distribution of outcomes: the 0.5 quantile is the median, and 0.9 is a value the outcome should stay under 90 percent of the time. Outputting several quantiles gives a range, which matters for inventory and risk decisions.

The paper treats the problem as direct multi-horizon forecasting: all horizons are predicted at once from the same encoding, instead of feeding predictions back in one step at a time as autoregressive models do.

How it works

Here is the flow of one forecast, with the pieces named in the order the data meets them.

  1. Inputs enter as three groups: static metadata, past observed values, and known future values. Each variable is turned into a vector of the same size, using a learned embedding for categories and a linear map for numbers.
  2. Variable selection decides how much each variable counts at each time step. It produces one weight per variable and adds the weighted features together. Here is a tiny instance with two variables, a sales lag and a holiday flag. Suppose the selection network outputs the scores (2, 0) for the two variables.
  3. Turn the scores into weights with softmax. Softmax of (2, 0) is about (0.88, 0.12). Check: the two weights sum to 1, and the first variable gets most of the weight.
  4. Combine the processed features with those weights. If the processed sales feature is [1, 0] and the processed holiday feature is [0, 1], the combined vector is 0.88 × [1, 0] + 0.12 × [0, 1] = [0.88, 0.12]. Check: the output is dominated by the sales feature, and a reader can see why.
  5. Static encoders turn the static metadata into four context vectors. These are passed to the variable selection, the local processing, and the static enrichment steps, so that the same store or product shapes how the time steps are read.
  6. A sequence-to-sequence LSTM processes the past inputs and the known future inputs locally, so that each time step is read in its recent context.
  7. A static enrichment step adds the static context to each time step.
  8. A multi-head attention layer lets each forecast step look at all earlier steps. The paper changes it so that all heads share one value matrix and their attention maps are averaged, so the attention weights can be read as one set of weights over time.
  9. A position-wise feed-forward block, with gating and a residual connection, refines the result. Each forecast step then gets a linear output for each quantile.
flowchart TD
  S["static metadata"] --> SE["static encoders: four context vectors"]
  P["past observed inputs"] --> VS1["variable selection"]
  K["known future inputs"] --> VS2["variable selection"]
  SE --> VS1
  SE --> VS2
  VS1 --> LSTM["LSTM encoder and decoder"]
  VS2 --> LSTM
  LSTM --> ENR["static enrichment"]
  SE --> ENR
  ENR --> ATT["interpretable multi-head attention"]
  ATT --> FF["gated feed-forward and norm"]
  FF --> Q["linear output per quantile and horizon"]

Training is simple to state: the network minimises a quantile loss over the 0.1, 0.5 and 0.9 quantiles at every horizon, and the weights are chosen by random search over settings such as the state size, dropout rate and learning rate.

The math

The math below follows the walkthrough: gates, variable selection, attention, and the quantile output.

The gated residual network, used in steps 2 and 9

The basic block takes a main input a and an optional context vector c. It returns LayerNorm(a + GLU(η₁)), where η₁ is a linear map of η₂ and η₂ = ELU(W₂a + W₃c + b₂). ELU is an activation that is close to the identity for large positive inputs and flat for large negative ones. The gated linear unit is

GLU(γ)=σ(W4γ+b4)⊙(W5γ+b5)\mathrm{GLU}(\boldsymbol{\gamma}) = \sigma(\mathbf{W}_4\boldsymbol{\gamma}+\mathbf{b}_4)\odot(\mathbf{W}_5\boldsymbol{\gamma}+\mathbf{b}_5)

where σ is the sigmoid and ⊙ is element-wise multiplication. When the sigmoid part is near 0, the GLU output is near 0 and the block passes its input through unchanged, so the network can skip any non-linear step it does not need.

Step 3 in symbols: variable selection weights

For past inputs, let Ξₜ be the stacked processed inputs at time t and cₛ a static context vector. The selection weights are

vχt=Softmax(GRNvχ(Ξt,cs))\mathbf{v}_{\chi_t}=\mathrm{Softmax}\big(\mathrm{GRN}_{v_\chi}(\boldsymbol{\Xi}_t,\mathbf{c}_s)\big)

and the combined feature is ξ̃ₜ = Σⱼ vⱼ ξ̃ₜ⁽ʲ⁾, a weighted sum of each variable's own processed feature. Here j indexes the variables.

Step 8 in symbols: interpretable attention

Standard multi-head attention uses a different value matrix for each head. The paper's version shares the values:

MH~(Q,K,V)=1H∑h=1mHAttention(QWQ(h),KWK(h),VWV)\widetilde{\mathrm{MH}}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \frac{1}{H}\sum_{h=1}^{m_H}\mathrm{Attention}\big(\mathbf{Q}\mathbf{W}_Q^{(h)},\mathbf{K}\mathbf{W}_K^{(h)},\mathbf{V}\mathbf{W}_V\big)

Because the values are shared, the averaged attention weights act as one set of weights over time steps. Each head can still pick out a different temporal pattern.

Step 9 in symbols: quantile output and loss

Each quantile forecast is a linear map of the decoder output, ŷ(q, t, τ) = W_q ψ̃(t, τ) + b_q. The quantile loss for one quantile q is

QL(y,y^,q)=q (y−y^)++(1−q) (y^−y)+,(a)+=max⁡(0,a)QL(y,\hat{y},q) = q\,(y-\hat{y})_{+} + (1-q)\,(\hat{y}-y)_{+}, \qquad (a)_{+}=\max(0,a)

Under-forecasts are weighted by q and over-forecasts by 1 − q. At q = 0.9, an under-forecast costs nine times as much as an equal over-forecast, which pushes the output toward the 90th percentile.

Worked example 1: one variable selection

Example
Tiny: softmax over two variables

Two variables get scores (2, 0).

  1. Compute e² ≈ 7.389 and e⁰ = 1.
  2. Sum: 7.389 + 1 = 8.389.
  3. Weights: 7.389 / 8.389 ≈ 0.881 and 1 / 8.389 ≈ 0.119.
  4. Check: 0.881 + 0.119 = 1.000.
  5. Interpretation: the first variable carries about 88 percent of the combined feature.

Worked example 2: the quantile loss is asymmetric

Example
Standard: pricing a miss at q = 0.9

The actual value is y = 10 and the quantile q is 0.9.

  1. Forecast ŷ = 8, an under-forecast of 2. Then (y − ŷ)₊ = 2 and (ŷ − y)₊ = 0.
  2. QL = 0.9 × 2 + 0.1 × 0 = 1.8.
  3. Forecast ŷ = 12, an over-forecast of 2. Then (y − ŷ)₊ = 0 and (ŷ − y)₊ = 2.
  4. QL = 0.9 × 0 + 0.1 × 2 = 0.2.
  5. Interpretation: at q = 0.9, missing low costs nine times as much as missing high by the same amount, so the trained output tends to sit above the median.

Worked example 3: the output size of the Electricity setting

Example
Realistic: how many numbers one forecast produces

The Electricity dataset uses 168 past hours to forecast the next 24 hours, and the model outputs three quantiles (0.1, 0.5, 0.9) for each hour.

  1. Count the horizons: 24.
  2. Count the quantiles: 3.
  3. Multiply: 24 × 3 = 72 numbers for each series at each forecast point.
  4. Interpretation: the model's output is a band of plausible values for each hour, not a single line.

Try it: the Volatility setting forecasts 5 business days with the same three quantiles. How many numbers does one forecast produce? Answer: 5 × 3 = 15.

Results

The paper reports P50 and P90 quantile losses on four datasets. Electricity (370 customers, hourly) and Traffic (440 freeways, hourly) are the simple univariate-with-known-inputs benchmarks used by earlier work. Retail (Favorita grocery sales, daily) is the full-input case: 90 days of history to forecast 30 days ahead for log product sales. Volatility (31 stock indices, daily realised volatility) tests robustness on a small, noisy set, forecasting five business days from a year of history.

The main claims, all as stated in the text:

  • On average across datasets, TFT's P50 loss is 7 percent lower and its P90 loss is 9 percent lower than the next-best model.
  • Against each dataset's next-best method, TFT's improvement falls between 3 and 26 percent.
  • The gating layers matter most for the small, noisy Volatility set, where removing them raises P90 loss by 4.1 percent.
  • The attention and local-processing components have the largest effect: removing them raises P90 loss by more than 6 percent on average.

The interpretability section is qualitative. Variable selection weights show that hour of day dominates in Electricity and that promotions and national holidays matter most for future Retail inputs. Attention patterns show clear daily spikes for Electricity and Traffic, a weaker weekly pattern for Retail, and no strong persistent pattern for Volatility. The regime analysis uses attention-pattern distance on S&P 500 data from 2001 to 2015.

What the results do not show: the comparisons depend on random hyperparameter search with a fixed budget per dataset, and on the authors' choice of benchmarks. The iterative baselines needed future unknown inputs filled in with their last available value. The interpretability claims are demonstrations on a few datasets, not a measured test of whether users trust the output more. Training the best Electricity model took just over 6 hours on one Tesla V100 GPU, which the paper calls practical but is still a real cost.

Common mistakes and tradeoffs

It is tempting to think that a large attention model is automatically a readable one. In fact, standard multi-head attention gives each head its own values, so its weights do not say which input mattered. TFT's shared values are what make the attention map a single reading of time, and removing that change is what would make the output hard to interpret.

It is tempting to think that a point forecast is enough. In fact, many decisions need the spread: a retailer who orders for the 90th percentile of demand orders differently from one who orders for the median. The quantile loss is what gives TFT its range.

It is tempting to think that post-hoc explainers such as SHAP can explain a time series model well. The paper argues they treat time steps as independent, which breaks the dependence between neighbouring steps. TFT builds the explanation into the architecture instead.

When to use it: several inputs of different kinds, multiple horizons, and a need for prediction ranges. When not to use it: a single short series with one input, where a simpler model is faster to train and easier to check. Alternatives include autoregressive recurrent models such as DeepAR, and the simpler statistical methods that the paper's univariate benchmarks compare against.

Reading guide

Read the paper in this order. Each section depends on the lessons named beside it.

Recap: TFT sorts inputs into static, known and observed groups, uses gates to skip unneeded processing, selects variables with softmax weights, runs a local LSTM and a shared-value attention layer over time, and outputs a band of quantiles for every horizon. Its readable parts are the variable selection weights and the attention weights.

Check yourself

QuestionWhy does TFT use a single set of shared value weights in its attention, instead of one value matrix per head?Show answer

If every head had its own values, the attention weights would not directly show how much each time step contributed, since the heads mix different value vectors. Sharing the values lets the averaged attention weights be read as one weighting over time, which is what the paper's interpretability use cases rely on.

QuestionAt q = 0.1, the actual value is 50 and the forecast is 56. What is the quantile loss?Show answer

The forecast is an over-forecast of 6, so (y − ŷ)₊ = 0 and (ŷ − y)₊ = 6. QL = 0.1 × 0 + 0.9 × 6 = 5.4.

QuestionWhy is a gated residual block able to ignore a layer it does not need?Show answer

The GLU multiplies its output by a sigmoid gate. When the gate is near 0, the GLU output is near 0, and the residual connection passes the block's input through unchanged after layer normalization. The network can therefore switch off the non-linear step for a dataset that does not need it.

QuestionApplied scenario: a grocer wants a 30-day forecast of sales for each product in each store, with promotions scheduled in advance and foot traffic known only up to today. Why is TFT a better fit than an autoregressive model that feeds predictions back in one day at a time?Show answer

The promotions are known future inputs, and foot traffic is an observed input that is only known up to today. An autoregressive model assumes all other inputs are known into the future, so it would need to fill in foot traffic. TFT takes the three input types separately and predicts all 30 days directly, and its variable selection and attention weights show whether promotions or past sales drive each forecast.

Sources

Read the full paper

Bryan Lim, Sercan O. Arik, Nicolas Loeff et al., 2019. arXiv:1912.09363