AI Logic

Architectures

Autoformer

Updated:

Autoformer architecture. Left: the overall flow, in which the encoder reads the look-back window and the decoder outputs the forecast window at once from seasonal and trend inputs obtained by decomposing the latter half of the look-back window. Right: inside a decoder layer, auto-correlation and series decomposition repeat while the extracted trends are accumulated, along with the four steps of auto-correlation

Background and overview

Autoformer is a Transformer-family model for long-term forecasting that builds series decomposition, which splits a time series into "trend" and "seasonal" (periodic fluctuation) parts, into the network many times over, and replaces attention with "Auto-Correlation," which aggregates copies of the series shifted by a period. Wu, Xu, Wang, and Long of Tsinghua University published it in 2021, and it was accepted at NeurIPS 2021.

The paper identified two problems with earlier Transformer-based long-term forecasting.

  1. Relationships are hard to find in complex, distant changes: Long series intertwine trends, multiple periods, and irregular changes, making it hard for attention to find reliable relationships.
  2. Sparse attention misses information: To reduce computation, Informer and similar models restrict attention to a subset of time-step pairs. Because they reduce computation while still linking time steps point by point, the usable information shrinks as well.

In response, Autoformer introduced two ideas.

  • Make decomposition a component of the network: Series decomposition is usually preprocessing applied to the look-back window before forecasting. Autoformer places decomposition blocks inside every encoder and decoder layer, and forecasts while gradually extracting the trend from intermediate representations.
  • Link sub-series instead of points: Using the property that sub-series at the same phase of a period (such as the same time of day each day) behave similarly, it shifts the series by the period and aggregates the shifted copies.

The paper reports that on six benchmarks (energy, traffic, economics, weather, and disease), it reduced MSE by 38% on average relative to the previous best results.

In this article, the past interval used as input for forecasting is called the look-back window, and the interval to be predicted is called the forecast window. In the paper's notation, the look-back window has length II and the forecast window has length OO, written "input-II-predict-OO." Autoformer outputs the OO values of the forecast window all at once.

Architecture

Autoformer has the same encoder-decoder form as the Transformer, with attention replaced by auto-correlation and the in-layer normalization positions replaced by series decomposition. The left side of the header figure shows the overall flow; the right side shows the contents of one decoder layer and the steps of auto-correlation.

Series decomposition block

A moving average is applied to a series X∈RLΓ—d\mathcal{X} \in \mathbb{R}^{L \times d} of length LL to extract the trend, and the remainder is taken as the seasonal component (Equation 1). The moving average is computed by average pooling after padding the ends so that the length does not change.

Xt=AvgPool(Padding(X)),Xs=Xβˆ’Xt\mathcal{X}_t = \mathrm{AvgPool}(\mathrm{Padding}(\mathcal{X})), \qquad \mathcal{X}_s = \mathcal{X} - \mathcal{X}_t

These two lines are written together as Xs,Xt=SeriesDecomp(X)\mathcal{X}_s, \mathcal{X}_t = \mathrm{SeriesDecomp}(\mathcal{X}).

Forecasting flow

  1. Build the decoder inputs: Decompose the latter half of the look-back window (length I/2I/2), then append zeros after the seasonal component and the mean of the look-back window after the trend component, each for the forecast window length OO (Equation 2). This yields two inputs, seasonal and trend.
  2. Read the seasonal part with the encoder: Each layer computes auto-correlation with a residual, series decomposition, feed-forward with a residual, and series decomposition, in that order (Equation 3). The trend extracted by decomposition is discarded, and only the seasonal component is passed to the next layer.
  3. Refine the seasonal part and accumulate the trend in the decoder: Each layer applies auto-correlation, auto-correlation over the encoder output, and feed-forward to the seasonal component, with series decomposition after each (Equation 4). The three extracted trends Tl,1,Tl,2,Tl,3\mathcal{T}^{l,1}, \mathcal{T}^{l,2}, \mathcal{T}^{l,3} are linearly projected and added to the trend stream.
  4. Add the two to form the forecast: The projected seasonal component of the last layer is added to the accumulated trend to give the forecast for the forecast window.
  5. Train: Minimize the squared error (L2 loss) between the forecast and the ground truth.

The trend accumulation in the decoder is given by the following equation.

Tdel=Tdelβˆ’1+Wl,1βˆ—Tdel,1+Wl,2βˆ—Tdel,2+Wl,3βˆ—Tdel,3\mathcal{T}^{l}_{\mathrm{de}} = \mathcal{T}^{l-1}_{\mathrm{de}} + \mathcal{W}_{l,1} * \mathcal{T}^{l,1}_{\mathrm{de}} + \mathcal{W}_{l,2} * \mathcal{T}^{l,2}_{\mathrm{de}} + \mathcal{W}_{l,3} * \mathcal{T}^{l,3}_{\mathrm{de}}

The Auto-Correlation mechanism

Auto-correlation measures how similar a series is to a copy of itself shifted by Ο„\tau (Equation 5).

RXX(Ο„)=lim⁑Lβ†’βˆž1Lβˆ‘t=1LXtXtβˆ’Ο„\mathcal{R}_{\mathcal{X}\mathcal{X}}(\tau) = \lim_{L \to \infty} \frac{1}{L} \sum_{t=1}^{L} \mathcal{X}_t \mathcal{X}_{t-\tau}

A Ο„\tau with large R(Ο„)\mathcal{R}(\tau) is a strong candidate for the period length. The Auto-Correlation mechanism takes the same query Q\mathcal{Q}, key K\mathcal{K}, and value V\mathcal{V} as attention and computes the following (Equation 6).

  1. Find period candidates: Compute the auto-correlation RQ,K(Ο„)\mathcal{R}_{\mathcal{Q},\mathcal{K}}(\tau) of Q\mathcal{Q} and K\mathcal{K} for every lag Ο„βˆˆ{1,…,L}\tau \in \{1, \ldots, L\}, and choose the k=⌊cΓ—log⁑LβŒ‹k = \lfloor c \times \log L \rfloor largest lags Ο„1,…,Ο„k\tau_1, \ldots, \tau_k (cc is a hyperparameter, 1–3 in the paper).
  2. Turn them into weights: Normalize the kk selected auto-correlations with softmax.
  3. Shift and aggregate: Rotate the value V\mathcal{V} by each Ο„i\tau_i (Roll: elements pushed off the front wrap around to the end), multiply by the weights, and sum. This is called "time delay aggregation."
AutoCorrelation(Q,K,V)=βˆ‘i=1kRoll(V,Ο„i) R^Q,K(Ο„i)\mathrm{AutoCorrelation}(\mathcal{Q}, \mathcal{K}, \mathcal{V}) = \sum_{i=1}^{k} \mathrm{Roll}(\mathcal{V}, \tau_i)\, \widehat{\mathcal{R}}_{\mathcal{Q},\mathcal{K}}(\tau_i)

The auto-correlation for all lags can be computed at once with the fast Fourier transform (FFT), using the Wiener–Khinchin theorem (Equation 8).

SXX(f)=F(Xt) Fβˆ—(Xt),RXX(Ο„)=Fβˆ’1(SXX(f))\mathcal{S}_{\mathcal{X}\mathcal{X}}(f) = \mathcal{F}(\mathcal{X}_t)\, \mathcal{F}^*(\mathcal{X}_t), \qquad \mathcal{R}_{\mathcal{X}\mathcal{X}}(\tau) = \mathcal{F}^{-1}(\mathcal{S}_{\mathcal{X}\mathcal{X}}(f))

The FFT costs O(Llog⁑L)O(L \log L) and O(log⁑L)O(\log L) series are aggregated, so the overall complexity is O(Llog⁑L)O(L \log L). As in multi-head attention, it is computed per head and the results are concatenated (Equation 7). For auto-correlation over the encoder output, K\mathcal{K} and V\mathcal{V} are taken from the encoder output and their length is aligned to OO.

Why it works

The paper explains why each of Autoformer's two ideas works as follows.

  • Repeated decomposition lets trend and seasonal parts be handled separately: If the trend remains mixed in, the mechanism for finding periodic relationships gets pulled along by the trend. Removing the trend layer by layer lets auto-correlation search for periods using only the seasonal component. The removed trend is gradually accumulated in the decoder and returned to the forecast. In the paper's Figure 4, adding more decomposition blocks let the decoder capture both a rising trend and seasonal peaks.
  • Decomposition works better inside the model than as preprocessing: Decomposing inside the model (Ours) gave better results than decomposing the look-back window first and forecasting each component with two separate models (Sep), whether built into Transformer, Informer, LogTrans, or Reformer (Table 3). The paper attributes this to preprocessing decomposition ignoring the interactions between components in the forecast window.
  • Sub-series at the same phase are used as a whole: Attention links time steps point by point, whereas auto-correlation aggregates whole sub-series such as "the same interval one period ago." Even when sparse, it is less likely to miss information, and the cost is only O(Llog⁑L)O(L \log L).

The learned lags corresponded to actual periods (Figure 6). For hourly traffic (Traffic), lags of 24 hours and 168 hours (one week) appeared; for daily exchange rates (Exchange), monthly, quarterly, and yearly periods appeared.

As an analogy, auto-correlation is like pulling out the ledger for "the same week last year" or "the same weekday last week" and laying it over the current one. Whereas attention searches for similar days one day at a time, auto-correlation first decides "how many days of shift makes everything line up best" and then refers to the whole interval shifted by that amount.

Experimental results

The paper evaluated six datasets: ETT, electricity consumption of 321 clients (Electricity), exchange rates of 8 countries (Exchange), road occupancy rates in California (Traffic), 21 weather indicators (Weather), and the ratio of influenza-like illness patients in the US (ILI). The look-back window length is 36 for ILI and 96 for the others.

Multivariate forecasting (MSE; lower is better; excerpt from Table 1 of the paper; ETT is ETTm2)

DataForecast lengthAutoformerInformerLogTransReformerLSTNetLSTMTCN
ETTm2960.2550.3650.7680.6583.1422.0413.041
ETTm27200.4223.3793.0482.6313.1712.7203.135
Electricity3360.2310.3000.2800.3500.8280.4391.000
Exchange3360.5091.6721.6591.3571.5072.1363.113
Traffic3360.6220.7770.7330.7421.2160.8531.479
Weather3360.3590.5780.7970.6390.5970.4550.639
ILI602.7705.2645.2784.8825.5486.8707.127

Autoformer gave the best results on every dataset and every forecast length. At forecast length 336, MSE fell relative to the previous best by 74% on ETT, 18% on Electricity, 61% on Exchange, 15% on Traffic, and 21% on Weather. The paper emphasizes the improvement even on Exchange, which has no clear periodicity. Another characteristic is that the error grows only slowly as the forecast length increases.

Univariate forecasting (a single column of ETTm2; MSE; excerpt from Table 2 of the paper)

Forecast lengthAutoformerN-BEATSInformerDeepARProphetARIMA
960.0650.0820.0880.0990.2870.211
3360.1540.2260.1800.2770.3310.317
7200.1820.1880.3000.3320.5340.366

Auto-correlation versus attention (results of replacing Autoformer's auto-correlation with other attention mechanisms; ETTm2, multivariate, MSE; excerpt from Table 4 of the paper; "―" means out of memory)

Look-back / forecast lengthAuto-correlationFull attentionLogSparseLSH (Reformer)ProbSparse (Informer)
96 / 3360.3390.3750.3620.3660.481
96 / 14400.5550.6670.5820.6630.715
336 / 14400.574―――1.133

Auto-correlation was best in every setting and fit in memory even in long settings such as a look-back window of 336 and a forecast length of 1440.

Practical considerations

Keep the following points in mind when using Autoformer.

  • Its strength shows on periodic series: Auto-correlation is a mechanism for finding period candidates. Appendix B of the paper also suggests making cc larger for data with clear periods such as ETT and Traffic, and smaller for ILI, which has no clear period.
  • Choose the look-back window length per dataset: In Appendix C of the paper, a look-back window of 96 was enough for ETT, which has clear periods, and lengthening it actually made results worse. For ILI, with weak periodicity, longer windows helped.
  • Set the moving average width: The width of the moving average in series decomposition (the length of the averaging interval) is a hyperparameter. Too short, and seasonal fluctuations remain in the trend; too long, and it cannot keep up with changes in the trend.
  • The series is rotated by the period: Roll is an operation that wraps values pushed off the front around to the end. Because it treats the two ends of the series as connected, periods longer than the look-back window cannot be used for aggregation.
  • The official implementation is in PyTorch: It is available on GitHub at thuml/Autoformer. It is not built into PyTorch itself.

The comparisons in the Autoformer paper are centered on a setting with the look-back window fixed at 96. As Appendix C of the paper shows, changing the look-back window length changes results substantially, and rankings against competing models can even flip. The paper for its successor, FEDformer, reports results that beat Autoformer on the same benchmarks. When comparing benchmark numbers, check whether the look-back window lengths match.

Comparison with other models

The table below lines up representative time series forecasting models from the same perspectives. LL is the length of the look-back window.

ModelTemporal modelingHow the forecast window is producedOutputComplexity in input length LL
DeepARLSTM updates its 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 look-back window with fully connected layers and outputs basis weightsAll at oncePoint forecastLinear in length (width of the fully connected input)
InformerProbSparse self-attention and distillationAll at once (generative decoder)Point forecastO(Llog⁑L)O(L \log L)
AutoformerSeries decomposition and auto-correlation (aggregation by periodic 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 across time and across variablesAll 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)

Autoformer and FEDformer both have a structure that "repeats series decomposition inside the network." FEDformer inherits Autoformer's decomposition structure and replaces auto-correlation with a component that handles only a subset of modes in the frequency domain.

Rough guidelines for choosing:

  • To forecast multivariate series with clear daily, weekly, or yearly periods far ahead: Autoformer is a good fit. The learned lags also show which periods it used.
  • To improve accuracy or computation further while keeping Autoformer's structure: FEDformer is its successor.
  • For series without clear periods: The benefits of auto-correlation are harder to realize, so also compare Informer and the MLP-only TSMixer (Google).
  • For univariate series where the forecast should be explained as trend and seasonal parts: The interpretable configuration of N-BEATS is also a candidate.

PyTorch example

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

"""
A small implementation of Autoformer's components (following Equations 1, 6, and 8 of arXiv:2106.13008)
"""


class SeriesDecomp(nn.Module):
  """Series decomposition (Eq. 1): trend = moving average, seasonal = original βˆ’ trend. Pads with edge values so the length is unchanged"""

  def __init__(self, kernel_size=25):           # the moving average width is a hyperparameter (25 here as an example)
    super().__init__()
    self.k = kernel_size
    self.avg = nn.AvgPool1d(kernel_size, stride=1)

  def forward(self, x):                          # x: [B, L, d]
    front = x[:, :1].repeat(1, (self.k - 1) // 2, 1)
    end = x[:, -1:].repeat(1, self.k // 2, 1)
    trend = self.avg(torch.cat([front, x, end], dim=1).transpose(1, 2)).transpose(1, 2)
    return x - trend, trend                      # seasonal, trend


class AutoCorrelation(nn.Module):
  """Auto-Correlation (Eqs. 6 and 8): compute auto-correlation with FFT, rotate V by the top-k lags, and take the weighted sum"""

  def __init__(self, d_model=512, n_heads=8, c=3):
    super().__init__()
    self.h, self.c = n_heads, c
    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, L, D = xq.shape
    # when attending to the encoder output, align the length of K and V to the query length L (pad with 0 if short)
    xkv = xkv[:, -L:] if xkv.size(1) >= L else F.pad(xkv, (0, 0, 0, L - xkv.size(1)))
    q = self.q(xq).view(B, L, self.h, -1)
    k = self.k(xkv).view(B, L, self.h, -1)
    v = self.v(xkv).view(B, L, self.h, -1)
    # Wiener–Khinchin theorem: R(Ο„) = F^{-1}( F(Q) Β· conj(F(K)) ). Gives all lags at once
    qf = torch.fft.rfft(q, dim=1)
    kf = torch.fft.rfft(k, dim=1)
    corr = torch.fft.irfft(qf * torch.conj(kf), n=L, dim=1)       # [B, L(lag Ο„), h, dk]
    # pick the top k = ⌊cΒ·log LβŒ‹ lags (here chosen by auto-correlation averaged over heads and channels)
    top_k = max(1, int(self.c * math.log(L)))
    mean_corr = corr.mean(dim=(2, 3))                              # [B, L]
    weights, delays = mean_corr.topk(top_k, dim=-1)                # [B, k]
    weights = torch.softmax(weights, dim=-1)
    # time delay aggregation: rotate V by Ο„ (Roll), weight, and sum
    out = torch.zeros_like(v)
    for b in range(B):
      for i in range(top_k):
        out[b] += torch.roll(v[b], shifts=-int(delays[b, i]), dims=0) * weights[b, i]
    return self.out(out.reshape(B, L, D))


class EncoderLayer(nn.Module):
  """Encoder layer (Eq. 3): auto-correlation + residual β†’ decomp β†’ FF + residual β†’ decomp. Drops the trend and returns the seasonal part"""

  def __init__(self, d_model=512, d_ff=2048, dropout=0.05):
    super().__init__()
    self.attn = AutoCorrelation(d_model)
    self.ff = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model))
    self.decomp1, self.decomp2 = SeriesDecomp(), SeriesDecomp()
    self.drop = nn.Dropout(dropout)

  def forward(self, x):
    x, _ = self.decomp1(x + self.drop(self.attn(x, x)))
    x, _ = self.decomp2(x + self.drop(self.ff(x)))
    return x


# Usage: build the decoder inputs (Eq. 2) and pass through an encoder layer
I, O, C, d = 96, 336, 7, 512
past = torch.randn(32, I, C)                                       # look-back window [B, I, variables]
seasonal, trend = SeriesDecomp()(past[:, I // 2:])                 # decompose the latter half of the look-back window
seasonal_init = torch.cat([seasonal, torch.zeros(32, O, C)], dim=1)                  # seasonal: fill with 0
trend_init = torch.cat([trend, past.mean(dim=1, keepdim=True).repeat(1, O, 1)], dim=1)  # trend: fill with the mean

embed = nn.Linear(C, d)                                            # linear embedding for simplicity
layer = EncoderLayer(d)
layer.train()                                                      # dropout only takes effect during training
enc_out = layer(embed(past))                                       # [32, 96, 512]
layer.eval()
with torch.no_grad():
  enc_out = layer(embed(past))

FAQ

Q. How are "seasonal" and "trend" separated?
A.

With a moving average. Applying a moving average to a series smooths out small ups and downs, leaving only slow changes. This is the trend, and what remains after subtracting the trend from the original series (the periodic ups and downs) is the seasonal part. Rather than performing this decomposition once as preprocessing, Autoformer performs it many times inside every encoder and decoder layer.

Q. How does auto-correlation differ from attention?
A.

Attention compares time steps point by point and gathers values from similar time steps. Auto-correlation measures how well the whole series overlaps with itself when shifted by Ο„\tau, and shifts and aggregates the series only at the lags that overlap well (period candidates). The differences are that it gathers "sub-series" rather than "points," and that the computation for all lags can be done together with the FFT in O(Llog⁑L)O(L \log L).

Q. How do Autoformer and FEDformer differ?
A.

FEDformer is a successor model that inherits Autoformer's structure of "repeating series decomposition inside the network." The difference lies in the component that handles the seasonal part: Autoformer uses auto-correlation in the time domain, while FEDformer uses a component that handles only a subset of components in the frequency domain (Fourier or wavelet transforms).

References

  1. Wu, H., Xu, J., Wang, J., & Long, M. (2021). Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting. NeurIPS 2021.
  2. thuml/Autoformer (official implementation, PyTorch)
  3. 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.
  4. Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). Attention Is All You Need. NeurIPS 2017.