AI Logic

Architectures

Informer

Updated:

Architecture of Informer. The left side shows the overall flow: the encoder reads the past window, and the decoder outputs the future window in one pass from an input made of a start token and zero placeholders. The right side shows the inside of the encoder, which stacks attention blocks and distilling to halve the length step by step, and the four steps of ProbSparse self-attention

Background and Overview

Informer is a model that makes the Transformer usable for long time-series forecasting by adding three ideas: (1) ProbSparse self-attention, which computes attention only for the important queries; (2) "self-attention distilling," which halves the sequence length at each layer; and (3) a decoder that outputs the whole future window in a single pass. Zhou et al. of Beihang University published it in 2020, and it appeared at AAAI 2021. The paper also released ETT, which has since become a standard benchmark for time-series forecasting.

The paper calls the problem of predicting values many days ahead long sequence time-series forecasting (LSTF). An example is forecasting the temperature of a power transformer hourly, 20 days (480 points) ahead. In Figure 1 of the paper, the error of an LSTM jumps once the prediction length exceeds 48 points, and its prediction speed also drops.

Attention passes information between any two time steps in a single step, which suits capturing relationships between distant time steps. Used as is, however, it has three problems.

  1. Computation grows with the square of the length: For a sequence of length LL, each layer needs O(L2)O(L^2) computation and memory.
  2. Stacking layers runs out of memory: Stacking JJ layers raises memory to O(J⋅L2)O(J \cdot L^2).
  3. Predicting long outputs is slow: With "dynamic decoding," where the decoder emits one step at a time, the longer the output, the longer it takes.

Informer adds one idea for each of these three problems.

This article calls the past interval used as input for the forecast the past window and the interval to be forecast the future window. In the paper's notation, the past window has length LxL_x and the future window has length LyL_y. Informer reads the past window with the encoder and outputs all LyL_y values of the future window at once with the decoder.

Architecture

Informer keeps the encoder-decoder form of the Transformer. In the figure at the top of the article, the left side shows the overall flow, and the right side shows the inside of the encoder and the steps of ProbSparse self-attention.

The forecasting flow is as follows.

  1. Build the input representation: The value at each time step is mapped to dmodeld_{\mathrm{model}} dimensions by a 1D convolution of width 3, and a positional embedding (the same sinusoids as the Transformer) and a learned embedding of time stamps (minute, hour, day of week, month, and so on) are added (Appendix B). Time stamps are included to give attention cues about long periods such as weeks and months.
  2. Read the past window with the encoder: ProbSparse self-attention blocks alternate with "distilling," which halves the sequence.
  3. Build the decoder input: The tail of the past window (the start token) is concatenated with zero placeholders as long as the future window (time stamps are still attached).
  4. Output the future window with the decoder: The input passes through masked ProbSparse self-attention, attention over the encoder output, and a fully connected layer, and the outputs at the placeholder positions become the forecast. A single computation produces the entire future window.
  5. Train: The whole model is trained with the MSE between the forecast and the ground truth as the loss.

ProbSparse self-attention

In standard attention, the output for the ii-th query qiq_i is the average of the values vjv_j weighted by their similarity to all keys kjk_j (Eq. 1).

A(qi,K,V)=∑jk(qi,kj)∑lk(qi,kl)vj=Ep(kj∣qi)[vj],k(qi,kj)=exp⁡(qikj⊤d)\mathcal{A}(q_i, K, V) = \sum_j \frac{k(q_i, k_j)}{\sum_l k(q_i, k_l)} v_j = \mathbb{E}_{p(k_j \mid q_i)}[v_j], \qquad k(q_i, k_j) = \exp\left(\frac{q_i k_j^\top}{\sqrt{d}}\right)

The paper observed that learned attention weights follow a long-tail distribution (a few pairs take most of the weight, and the rest have almost no effect). For a query whose weight distribution p(kj∣qi)p(k_j \mid q_i) is close to uniform, the output is almost the same as a plain average of the values. The paper therefore measures a query's "sparsity" by how far it is from the uniform distribution (Kullback-Leibler divergence) (Eq. 2).

M(qi,K)=ln⁡∑j=1LKeqikj⊤d−1LK∑j=1LKqikj⊤dM(q_i, K) = \ln \sum_{j=1}^{L_K} e^{\frac{q_i k_j^\top}{\sqrt{d}}} - \frac{1}{L_K} \sum_{j=1}^{L_K} \frac{q_i k_j^\top}{\sqrt{d}}

Computing this for every query still costs O(L2)O(L^2), so in practice an approximation that replaces the first term with a maximum is used (Eq. 4).

Mˉ(qi,K)=max⁡j{qikj⊤d}−1LK∑j=1LKqikj⊤d\bar{M}(q_i, K) = \max_j \left\{\frac{q_i k_j^\top}{\sqrt{d}}\right\} - \frac{1}{L_K} \sum_{j=1}^{L_K} \frac{q_i k_j^\top}{\sqrt{d}}

The procedure is as follows (Algorithm 1 in Appendix E).

  1. Measure sparsity on a subset of pairs: Randomly select only LKln⁡LQL_K \ln L_Q query-key pairs, compute their dot products, and obtain Mˉ\bar{M} for each query.
  2. Select the top queries: Select the top u=c⋅ln⁡LQu = c \cdot \ln L_Q queries with the largest Mˉ\bar{M} (cc is a constant; the paper uses c=5c = 5).
  3. Compute standard attention only for the selected queries: The selected queries compute scaled dot-product attention against all keys.
  4. Use the mean for the remaining queries: The output of each unselected query is the mean of the values VV.
A(Q,K,V)=Softmax(QˉK⊤d)V\mathcal{A}(Q, K, V) = \mathrm{Softmax}\left(\frac{\bar{Q} K^\top}{\sqrt{d}}\right) V

Qˉ\bar{Q} is a sparse matrix that keeps only the top uu queries. When queries and keys have the same length LL, both computation and memory become O(Llog⁡L)O(L \log L). The paper explains that in multi-head attention, each head selects different queries, which limits information loss.

Self-attention distilling

In the encoder, the following "distilling" step sits between attention blocks (Eq. 5).

Xj+1=MaxPool(ELU(Conv1d([Xj]AB)))X_{j+1} = \mathrm{MaxPool}\bigl(\mathrm{ELU}(\mathrm{Conv1d}([X_j]_{\mathrm{AB}}))\bigr)

[⋅]AB[\cdot]_{\mathrm{AB}} is the attention block, Conv1d is a convolution of width 3 along the time axis, ELU is the activation function, and MaxPool is max pooling with stride 2. Each layer halves the sequence length, so the total memory stays within O((2−ϵ)Llog⁡L)O((2 - \epsilon) L \log L). In addition, replica stacks that take the input at successively halved lengths are built, and the outputs of all stacks are concatenated to form the encoder output. The experimental setting combines a 3-layer stack with a 1-layer stack that receives 1/4 of the input.

Generative decoder

The decoder receives the following input (Eq. 6).

Xde=Concat(Xtoken,X0)∈R(Ltoken+Ly)×dmodelX_{\mathrm{de}} = \mathrm{Concat}(X_{\mathrm{token}}, X_0) \in \mathbb{R}^{(L_{\mathrm{token}} + L_y) \times d_{\mathrm{model}}}

XtokenX_{\mathrm{token}} is a segment of length LtokenL_{\mathrm{token}} cut from the past window, and X0X_0 is the placeholder for the future window, with values set to 0 and only time stamps included. For example, to forecast 168 points (7 days) ahead, the preceding 5 days are used as the start token. Self-attention is masked so that it does not look at later positions.

Why It Works

Each of Informer's three ideas works for the following reason.

  • ProbSparse: skipping computation that has no effect: If attention weights are long-tailed, the output of a query with near-uniform weights is almost the same as the mean of the values. Replacing the computation for such queries with the mean changes the result little. As evidence for this assumption, the paper notes that compared with a version using standard attention (Informer†), Informer won 32 to 12 in the univariate experiments.
  • Distilling: fitting long inputs into memory: Halving the length at each layer allows a long past window. The version without distilling ran out of memory once the input exceeded 720 (Table 5).
  • Generative decoder: no error accumulation: Step-by-step decoding feeds the model's own predictions back as the next input, so errors pile up. Outputting all placeholder positions at once speeds up prediction and avoids error accumulation. Accuracy barely changed when the forecast start was shifted, whereas the step-by-step version produced unusable results (Table 6).

As an analogy, ProbSparse self-attention is like "listening carefully in a meeting only to people whose remarks stand out, and substituting the overall average for those with nothing in particular to say." Because the number of people heard is limited to about ln⁡L\ln L, the meeting barely gets longer as participants (time steps) increase.

Experimental Results

The paper evaluated four datasets: ETT (ETTh1, ETTh2, ETTm1), electricity consumption of 321 households (ECL), and weather at about 1,600 US locations (Weather). Values are standardized to mean 0 and standard deviation 1, and lower is better.

Univariate forecasting (forecasting only the oil temperature of ETTh1; MSE; excerpt from Table 1 of the paper; the leftmost column is the prediction length)

Prediction lengthInformerInformer† (standard attention)LogTransReformerLSTMaDeepARARIMAProphet
240.0980.0920.1030.2220.1140.1070.1080.115
1680.1830.1870.2071.5220.2360.2390.3961.224
7200.2690.2570.2732.1120.6830.6580.6592.735

Multivariate forecasting (forecasting all 7 columns of ETTh1; MSE; excerpt from Table 2 of the paper)

Prediction lengthInformerInformer†LogTransReformerLSTMaLSTnet
240.5770.6200.6860.9910.6501.293
1680.9310.9471.0021.8241.2121.997
7201.2151.2411.3972.4151.9602.143
  • Error grows slowly over long horizons: In univariate forecasting, MSE was lower than LSTMa by 26.8% at 168 points, 52.4% at 336 points, and 60.1% at 720 points.
  • Stronger than statistical methods and DeepAR: Compared with DeepAR, ARIMA, and Prophet, MSE was lower on average by 49.3% at 168 points, 61.1% at 336 points, and 65.1% at 720 points. On ECL, however, DeepAR did better for shorter forecasts of 336 points or less.
  • Win counts: In the univariate table, Informer was best 32 times, Informer† 12 times, and DeepAR 6 times. In the multivariate table, the counts were 33, 14, 1 (LogTrans), and 2 (LSTnet).

Complexity (Table 4 of the paper; per layer)

ModelTraining timeTraining memoryPrediction steps
InformerO(Llog⁡L)O(L \log L)O(Llog⁡L)O(L \log L)1
TransformerO(L2)O(L^2)O(L2)O(L^2)LL
LSTMO(L)O(L)O(L)O(L)LL

Standing in later papers

Informer became a common baseline for later long-term forecasting models. In Table 1 of the Autoformer paper (ETTm2, past window 96, multivariate, MSE), Informer scored 0.365, 0.533, 1.363, and 3.379 at prediction lengths 96, 192, 336, and 720, with error growing sharply as the horizon lengthens, and fell far behind Autoformer (0.255, 0.281, 0.339, 0.422).

Practical Considerations

Keep the following points in mind when using Informer.

  • Today it mostly serves as a baseline: In later papers, Autoformer, FEDformer, simple linear models, TSMixer (Google), and others clearly outperform it on the same ETT benchmark. When building a new forecasting system, compare against these as well.
  • Check the fit with your data: Even in the paper, DeepAR did better on shorter ECL forecasts. The paper also notes that the margin in multivariate forecasting was not as large as in univariate forecasting.
  • Many hyperparameters: The number of encoder layers (2 to 6), the lengths of the past window and start token, the sampling constant cc, and so on must be tuned per dataset. The paper states that the start token must be shorter than the past window.
  • Prepare time stamps: The input representation uses time stamps such as minute, hour, day of week, and month, which are also placed in the future-window placeholders. For data without time stamps, this part has no effect.
  • The official implementation is in PyTorch: It is available on GitHub at zhouhaoyi/Informer2020. PyTorch itself has no built-in version.

ProbSparse self-attention measures sparsity on randomly selected query-key pairs, so the selected queries change during training even for the same input. Also, in the comparison in the Autoformer paper (Table 4), replacing Autoformer's internal component with ProbSparse increased the error in every setting compared with not replacing it. It is an approximation to save computation and does not improve accuracy on every dataset.

Comparison with Other Models

Placing representative time-series forecasting models side by side from the same angles gives the following. LL is the length of the past window.

ModelHow it handles timeHow it outputs the future windowOutputComplexity in input length LL
DeepARUpdates an LSTM state one step at a timeAutoregressive, one step at a time (samples fed back as the next input)Probability distribution (sample paths)Linear in length (computed in time order)
N-BEATSReads the whole past window with fully connected layers and outputs basis weightsAll at oncePoint forecastLinear in length (input width of the fully connected layers)
InformerProbSparse self-attention and distillingAll at once (generative decoder)Point forecastO(Llog⁡L)O(L \log L)
AutoformerSeries decomposition and Auto-Correlation (aggregation by period lags)All at oncePoint forecastO(Llog⁡L)O(L \log L)
FEDformerSeries decomposition and a subset of frequency-domain modesAll at oncePoint forecastO(L)O(L)
PyraformerPyramidal attention (stacking coarser time resolutions)All at oncePoint forecastO(L)O(L)
TSMixer (Google)MLPs along the time and variable axesAll at once (linear projection)Point forecastLinear in length
ChronosTurns values into tokens and reads them with a language modelAutoregressive, one token at a timeProbability distribution (sample paths)O(L2)O(L^2) (standard attention)

Informer, Autoformer, FEDformer, and Pyraformer all tackle the same problem, "reducing the Transformer's O(L2)O(L^2) computation and outputting the future window all at once," in different ways. All of them are compared on benchmarks such as ETT.

Rough guidelines for choosing are as follows.

  • To study or compare the idea of sparse attention itself: Informer is the starting point. It also shows the differences from other sparse attention methods such as Reformer and Longformer.
  • To improve accuracy on series with clear periodicity: Autoformer and FEDformer, which handle a series by splitting it into trend and seasonal parts, are a good fit.
  • To make computation even lighter: FEDformer and Pyraformer, with O(L)O(L) complexity, are candidates.
  • To quickly build a strong baseline first: Also try simple models such as the MLP-only TSMixer (Google).

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A small implementation of Informer's components (following Eqs. 4-6 and Algorithm 1 in Appendix E of arXiv:2012.07436)
"""


class ProbSparseAttention(nn.Module):
  """ProbSparse self-attention. Computes standard attention only for the top u = c·ln L queries"""

  def __init__(self, d_model=512, n_heads=8, factor=5, mask=False):
    super().__init__()
    self.h, self.dk, self.c, self.mask = n_heads, d_model // n_heads, factor, mask
    self.q, self.k, self.v = (nn.Linear(d_model, d_model) for _ in range(3))
    self.out = nn.Linear(d_model, d_model)

  def forward(self, xq, xkv):
    B, Lq, _ = xq.shape
    Lk = xkv.size(1)
    q = self.q(xq).view(B, Lq, self.h, self.dk).transpose(1, 2)      # [B, h, Lq, dk]
    k = self.k(xkv).view(B, Lk, self.h, self.dk).transpose(1, 2)
    v = self.v(xkv).view(B, Lk, self.h, self.dk).transpose(1, 2)
    scale = 1.0 / math.sqrt(self.dk)

    # 1. Randomly sample a subset of keys and compute sparsity M = max − mean (Eq. 4; c·ln L keys per query)
    n_sample = min(Lk, int(self.c * math.ceil(math.log(Lk))))
    idx = torch.randint(Lk, (Lq, n_sample), device=xq.device)
    qk_sample = torch.einsum("bhqd,bhqsd->bhqs", q, k[:, :, idx, :]) * scale
    m = qk_sample.max(-1).values - qk_sample.mean(-1)               # [B, h, Lq]

    # 2. Select the top u queries
    u = min(Lq, int(self.c * math.ceil(math.log(Lq))))
    top = m.topk(u, dim=-1).indices                                 # [B, h, u]

    # 4. The remaining queries output the mean of V (with masking, the cumulative mean up to that position)
    if self.mask:
      steps = torch.arange(1, Lk + 1, device=xq.device).view(1, 1, -1, 1)
      context = v.cumsum(dim=2) / steps
    else:
      context = v.mean(dim=2, keepdim=True).expand(B, self.h, Lq, self.dk).clone()

    # 3. Compute attention against all keys only for the selected queries
    q_top = torch.gather(q, 2, top.unsqueeze(-1).expand(-1, -1, -1, self.dk))
    scores = q_top @ k.transpose(-2, -1) * scale                    # [B, h, u, Lk]
    if self.mask:
      future = torch.arange(Lk, device=xq.device).view(1, 1, 1, -1) > top.unsqueeze(-1)
      scores = scores.masked_fill(future, float("-inf"))
    attn_out = F.softmax(scores, dim=-1) @ v
    context.scatter_(2, top.unsqueeze(-1).expand(-1, -1, -1, self.dk), attn_out)
    return self.out(context.transpose(1, 2).reshape(B, Lq, -1))


class EncoderLayer(nn.Module):
  def __init__(self, d_model=512, n_heads=8, d_ff=2048, dropout=0.1):
    super().__init__()
    self.attn = ProbSparseAttention(d_model, n_heads)
    self.ff = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model))
    self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
    self.drop = nn.Dropout(dropout)

  def forward(self, x):
    x = self.norm1(x + self.drop(self.attn(x, x)))
    return self.norm2(x + self.drop(self.ff(x)))


class Distilling(nn.Module):
  """Self-attention distilling (Eq. 5): Conv1d (width 3) → ELU → max pooling (stride 2) halves the length"""

  def __init__(self, d_model=512):
    super().__init__()
    self.conv = nn.Conv1d(d_model, d_model, kernel_size=3, padding=1)
    self.pool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)

  def forward(self, x):                                             # x: [B, L, d]
    y = F.elu(self.conv(x.transpose(1, 2)))
    return self.pool(y).transpose(1, 2)                            # [B, L/2, d]


# Usage: one encoder stack (attention → distilling → attention → distilling → attention)
d = 512
stack = nn.ModuleList([EncoderLayer(d), Distilling(d), EncoderLayer(d), Distilling(d), EncoderLayer(d)])
x = torch.randn(32, 96, d)                                          # embedded past window [B, L, d]

stack.train()                                                       # dropout is active only in training (use stack.eval() for inference)
for m in stack:
  x = m(x)
print(x.shape)                                                      # [32, 24, 512]: length becomes 1/4

# Decoder input (Eq. 6): start token (last 48 points of the past window) + zero placeholders for the future window (24 points)
past = torch.randn(32, 96, 7)                                       # past window (7 variables)
x_dec = torch.cat([past[:, -48:], torch.zeros(32, 24, 7)], dim=1)   # [32, 72, 7]; time stamps are embedded separately and added

FAQ

Q. Is Informer's "distilling" different from knowledge distillation?
A.

Yes, it is different. Knowledge distillation is a training method in which a small model imitates the outputs of a large model. Informer's "self-attention distilling" is a network component that applies convolution, ELU, and max pooling between encoder layers, halving the sequence length while passing only the prominent features to the next layer.

Q. What goes into the start token?
A.

The part of the past window just before the forecast interval is used as is. It is not a special symbol like the start token of a language model. In the paper's example, to forecast 7 days (168 points) ahead, the preceding 5 days are used as the start token. Zero placeholders as long as the future window follow it, carrying only time stamps, and the decoder outputs the values at the placeholder positions all at once.

Q. Was the ETT benchmark created in the Informer paper?
A.

Yes. ETT (records of oil temperature and load of power transformers) is a dataset collected and released by the authors of the Informer paper. The Informer paper used three subsets, ETTh1, ETTh2, and ETTm1; the Autoformer paper later added ETTm2 and published comparison tables over all four, making it a standard benchmark for long-term forecasting.

References

  1. Zhou, H., Zhang, S., Peng, J., Zhang, S., Li, J., Xiong, H., & Zhang, W. (2021). Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting. Proceedings of the AAAI Conference on Artificial Intelligence, 35(12), 11106–11115.
  2. zhouhaoyi/Informer2020 (official implementation, PyTorch)
  3. zhouhaoyi/ETDataset (ETT dataset)
  4. Wu, H., Xu, J., Wang, J., & Long, M. (2021). Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting. NeurIPS 2021.
  5. Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). Attention Is All You Need. NeurIPS 2017.