AI Logic

Architectures

FEDformer

Updated:

FEDformer architecture. Left: the overall flow, in which the encoder reads the look-back window and the decoder, fed with the decomposed second half of the look-back window, outputs the whole forecast window at once. Top right: inside FEB-f, which applies a Fourier transform and multiplies weights only on randomly selected modes. Bottom right: inside the MOE decomposition, which mixes average pooling of different widths with weights

Background and overview

FEDformer is a long-term forecasting model that keeps the same "forecast while splitting into trend and seasonal parts" design as Autoformer, and adds components that apply a Fourier (or wavelet) transform to the time series and work only on a randomly selected subset of frequency components. The name stands for Frequency Enhanced Decomposed Transformer. It was introduced in 2022 by Zhou (Tian), Ma, and colleagues at Alibaba, and accepted at ICML 2022.

The paper starts from the observation that Transformer-based forecasts sometimes fail to preserve the global properties of a series (its overall trend and value distribution). In Figure 1 of the paper, on ETTm1, a standard Transformer's forecast had a different distribution from the ground truth. The paper explains that attention, which predicts the value at each time step point by point, tends to break the properties of the series as a whole.

In response, FEDformer combines two ideas.

  1. Build series decomposition into the model: as in Autoformer, every encoder and decoder layer splits the series into trend and seasonal parts. This is further improved into a "mixture-of-experts decomposition" (MOE decomposition) that mixes moving averages of different widths.
  2. Compute in the frequency domain: instead of attention, the series is Fourier-transformed, and learned weights are applied to only some of its frequency components (modes). Because the whole series is transformed at once, global properties are easier to capture.

Because the number of selected modes is fixed, the complexity is O(L)O(L), linear in sequence length. The paper reports that on six benchmarks, it reduced error (MSE) relative to Autoformer, the previous state of the art, by 14.8% in multivariate and 22.6% in univariate forecasting.

In this article, the past interval used as input 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. FEDformer outputs the OO values of the forecast window all at once.

Architecture

FEDformer's overall architecture is the same as Autoformer's; only the components differ (Figure 2 of the paper). 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 frequency enhanced block (FEB-f) and the MOE decomposition.

ComponentAutoformerFEDformer
Replacement for self-attentionAuto-correlationFrequency Enhanced Block (FEB)
Replacement for encoder-decoder attentionAuto-correlationFrequency Enhanced Attention (FEA)
Series decompositionMoving average of a single widthMOE decomposition mixing moving averages of different widths

The forecasting flow is as follows.

  1. Build the decoder input: as in Autoformer, the second half of the look-back window (length I/2I/2) is split into seasonal and trend parts, and placeholders for the forecast window of length OO are appended, giving two inputs of length I/2+OI/2 + O.
  2. Read the seasonal part with the encoder: each layer applies FEB with a residual, MOE decomposition, feed-forward with a residual, and MOE decomposition, in that order (Eq. 1). The trend is discarded, and only the seasonal part is passed on.
  3. Refine the seasonal part and accumulate the trend with the decoder: each layer applies FEB, FEA over the encoder output, and feed-forward in turn, with a residual and MOE decomposition after each (Eq. 2). The three extracted trends are projected and added to the trend stream.
  4. Add the two to form the forecast: the projection of the last layer's seasonal part, WS⋅XdeMW_S \cdot \mathcal{X}^M_{\mathrm{de}}, is added to the accumulated trend TdeM\mathcal{T}^M_{\mathrm{de}}.

Frequency Enhanced Block (FEB-f)

FEB-f is the component used instead of self-attention (Section 3.2, Figure 3).

  1. Linear transform: multiply the input x∈RN×Dx \in \mathbb{R}^{N \times D} by weights w∈RD×Dw \in \mathbb{R}^{D \times D} to get q=x⋅wq = x \cdot w.
  2. Fourier transform: move qq to the frequency domain to get Q=F(q)∈CN×DQ = \mathcal{F}(q) \in \mathbb{C}^{N \times D}.
  3. Select modes: keep only MM randomly selected modes (frequency components), giving Q~∈CM×D\tilde{Q} \in \mathbb{C}^{M \times D} (M≪NM \ll N; the paper's default is M=64M = 64).
  4. Apply weights per mode: multiply by learned complex weights R∈CD×D×MR \in \mathbb{C}^{D \times D \times M}, mode by mode.
  5. Return to the time domain: fill the remaining modes with 0 to restore length NN, and apply the inverse Fourier transform.
Q~=Select(F(q)),FEB-f(q)=F−1(Padding(Q~⊙R))\tilde{Q} = \mathrm{Select}(\mathcal{F}(q)), \qquad \mathrm{FEB\text{-}f}(q) = \mathcal{F}^{-1}\bigl(\mathrm{Padding}(\tilde{Q} \odot R)\bigr)

⊙\odot is the operation that, for each mode mm, takes the weighted sum from input channel did_i to output channel dod_o: Ym,do=∑diQ~m,di⋅Rdi,do,mY_{m,d_o} = \sum_{d_i} \tilde{Q}_{m,d_i} \cdot R_{d_i,d_o,m}.

Frequency Enhanced Attention (FEA-f)

FEA-f replaces encoder-decoder attention (Figure 4). The query qq (from the decoder) and the key kk and value vv (from the encoder) are each Fourier-transformed and reduced to MM selected modes, an attention-style computation is performed in the frequency domain, and the result is transformed back (Eqs. 6 and 7).

FEA-f(q,k,v)=F−1(Padding(σ(Q~⋅K~⊤)⋅V~))\mathrm{FEA\text{-}f}(q, k, v) = \mathcal{F}^{-1}\bigl(\mathrm{Padding}(\sigma(\tilde{Q} \cdot \tilde{K}^\top) \cdot \tilde{V})\bigr)

σ\sigma is an activation function; softmax or tanh is used, since convergence behavior differs by dataset.

Wavelet version (FEB-w, FEA-w)

There is also a version that uses a multiwavelet transform based on Legendre polynomials instead of the Fourier transform (Section 3.3). It recursively splits the input into high-frequency, low-frequency, and remaining parts (3 levels by default in the paper), processes each with FEB-f, and reassembles them. Whereas the Fourier transform looks at the frequencies of the whole series, the wavelet transform can also capture local structure in time. The two versions are called FEDformer-f and FEDformer-w.

MOE decomposition

Extracting the trend with a moving average of a single width can fail to separate the trend well on data with complex periodic variation. MOE decomposition lines up several average-pooling filters of different widths to produce multiple trends, and mixes them with weights computed from the input (Eq. 10).

Xtrend=Softmax(L(x))∗F(x)\mathbf{X}_{\mathrm{trend}} = \mathrm{Softmax}(L(x)) * F(x)

F(⋅)F(\cdot) is the set of average-pooling filters, and Softmax(L(x))\mathrm{Softmax}(L(x)) gives the weights that mix them. The seasonal part is what remains after subtracting the trend from the input.

Why it works

The paper explains why using only some of the frequencies still works, as follows (Section 2).

  • Time series tend to be sparse in frequency: many time series, when expressed in a fixed basis such as the Fourier basis, can be mostly represented by a few components. Keeping all components risks memorizing even high-frequency changes caused by noise, fitting the past too closely (overfitting) and worsening forecasts.
  • Random selection loses almost no information: the paper proves that if the matrix AA of Fourier transforms of mm series is low-rank (its components are similar to one another), then selecting just s=O(k2/ϵ2)s = O(k^2 / \epsilon^2) components at random represents the original information with almost the same accuracy as the best approximation from the top kk singular values (Theorem 1).
  • Low frequencies alone are not enough: a common approach is to keep only low frequencies, but sudden changes in the trend can reflect important events, and discarding all high frequencies loses that information. Random selection includes both low and high frequencies.

In experiments too, random selection gave better results than selecting from the lowest frequencies upward. It was also confirmed that accuracy plateaus as the number of modes keeps increasing, so a moderate number rather than all modes is best (Figure 6).

The decomposition structure also helps bring the forecast distribution closer to the ground truth. In a test of whether the forecast and the look-back window come from the same distribution (the Kolmogorov-Smirnov test), the forecasts of Transformer and Informer were judged "different distributions" in many settings, while Autoformer and FEDformer rarely were, and only FEDformer had p-values above 0.01 in every setting on ETTm1 and ETTm2 (Table 5).

As an analogy, FEDformer treats a time series like "sound" and learns to adjust only some of the knobs on an equalizer. It splits the whole sound (series) into components by frequency, adjusts the strength of a few dozen selected knobs, and turns it back into sound. Since the number of knobs is fixed, the effort of adjustment barely grows even when the song (series) gets longer.

Experimental results

The paper evaluated on the same six datasets as Autoformer (ETT's ETTm2, Electricity, Exchange, Traffic, Weather, ILI) with the same settings as Autoformer (look-back window of 96, or 36 for ILI only).

Multivariate forecasting (MSE, lower is better; excerpt from Table 2 of the paper)

DataForecast lengthFEDformer-fFEDformer-wAutoformerInformerLogTransReformer
ETTm2960.2030.2040.2550.3650.7680.658
ETTm27200.4210.4330.4223.3793.0482.631
Electricity3360.2140.2120.2310.3000.2800.350
Exchange3360.4600.4260.5091.6721.6591.357
Traffic3360.6210.5700.6220.7770.73370.742
Weather3360.3390.3810.3590.5780.7970.639
ILI602.8572.5452.7705.2645.2784.882

The LogTrans value of 0.7337 for Traffic at 336 is reproduced as printed in the paper's table (the other values have three decimal places).

  • Multivariate: FEDformer (either f or w) was best on every dataset and forecast length, reducing MSE by 14.8% overall relative to Autoformer. On Exchange and ILI the improvement exceeded 20%. It improved even on Exchange, which has no clear periodicity.
  • Univariate: MSE was 22.6% lower overall than Autoformer, with improvements of more than 30% on Traffic and Weather (Table 3).
  • f and w excel on different data: the Fourier and wavelet versions were better on different datasets, and the paper presents them as complementary options.

Effect of each component (ETTm1 and ETTm2, multivariate; Table 4 of the paper)

A version that replaces Autoformer's auto-correlation with FEB-f only in the self-attention position (V1) beat Autoformer in 10 of 16 settings, and a version that replaces it with FEA-f only between the encoder and decoder (V2) beat it in 12. FEDformer-f, which replaces both, beat it in all 16. MOE decomposition was also 2.96% better on average than single-width decomposition (ETT and Weather).

Complexity (Table 1 of the paper)

ModelTraining time and memoryForecasting steps
FEDformerO(L)O(L)1
AutoformerO(Llog⁡L)O(L \log L)1
InformerO(Llog⁡L)O(L \log L)1
TransformerO(L2)O(L^2)LL

The Fourier transform itself is O(Llog⁡L)O(L \log L), but the paper explains that fixing the number of selected modes MM and computing only the selected modes makes it O(L)O(L).

Practical considerations

Keep the following points in mind when using FEDformer.

  • Try both the Fourier and wavelet versions: which one is better depended on the data. The wavelet version is stronger on local structure, but the recursive decomposition makes it heavier to implement and compute.
  • Choose the number of modes: the default is M=64M = 64. In the paper's experiments, adding too many modes did not improve accuracy, which plateaued.
  • Fix the randomly selected modes: the mode selection is described as "a set of Fourier bases chosen in advance," decided before training. Reselecting modes at every forecast would break the correspondence with the learned weights RR.
  • Comparisons focus on short look-back windows: the paper's main results use a look-back window of 96 to match Autoformer. With longer look-back windows, the ranking against other models may change.
  • The official implementation is in PyTorch: it is published on GitHub as MAZiqing/FEDformer. PyTorch itself has no built-in version, but FEB-f can be written briefly with torch.fft.

FEB-f keeps only the MM selected frequency components in its output. Changes at unselected frequencies cannot be represented in that layer and must be handled by the residual connections or the trend side of the decomposition. For data where very fine changes matter for forecasting, consider the number of modes, how they are selected, or the wavelet version.

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)

FEDformer inherits Autoformer's decomposition structure and moves the component that handles the seasonal part from the time domain (auto-correlation) to the frequency domain (FEB and FEA). The paper describes the difference as: "Autoformer splits the series into sub-series in the time domain and selects the top kk, whereas FEDformer computes frequency components from the whole series, so it captures global properties more easily."

Rough guidelines for choosing:

  • To forecast periodic multivariate series far ahead with little compute: FEDformer is a good fit.
  • To use the model while checking the learned periods (lags): Autoformer lets you read off periods from the selected lags.
  • To use multiple resolutions with O(L)O(L) complexity: Pyraformer is also a candidate.
  • To quickly build a strong baseline first: also try the MLP-only TSMixer (Google).

PyTorch example

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

"""
A small implementation of FEDformer's components (following Eqs. 3 and 4 (FEB-f) and Eq. 10 (MOE decomposition) of the paper arXiv:2201.12740)
"""


class FEBf(nn.Module):
  """Frequency enhanced block (Fourier version): apply learned complex weights only to M selected modes"""

  def __init__(self, d_model=512, seq_len=96, modes=64, seed=0):
    super().__init__()
    self.proj = nn.Linear(d_model, d_model)                     # q = x · w
    n_freq = seq_len // 2 + 1                                   # number of modes from rfft of a real series
    g = torch.Generator().manual_seed(seed)
    idx = torch.randperm(n_freq, generator=g)[:min(modes, n_freq)].sort().values
    self.register_buffer("index", idx)                          # randomly selected modes, decided before training and fixed
    scale = 1.0 / (d_model * d_model)
    # R ∈ C^{D × D × M}: complex weights from input channels to output channels for each mode
    self.weight = nn.Parameter(scale * torch.randn(len(idx), d_model, d_model, dtype=torch.cfloat))

  def forward(self, x):                                         # x: [B, N, D]
    q = self.proj(x)
    Q = torch.fft.rfft(q, dim=1)                                # time → frequency [B, N/2+1, D]
    Qs = Q[:, self.index]                                       # Select: keep only M modes [B, M, D]
    Y = torch.einsum("bmi,mio->bmo", Qs, self.weight)           # Y_{m,o} = Σ_i Q_{m,i} R_{i,o,m}
    out = torch.zeros_like(Q)
    out[:, self.index] = Y                                      # Padding: unselected modes are 0
    return torch.fft.irfft(out, n=x.size(1), dim=1)             # frequency → time [B, N, D]


class MOEDecomp(nn.Module):
  """Mixture-of-experts series decomposition (Eq. 10): mix moving-average trends of different widths with weights computed from the input"""

  def __init__(self, d_model=512, kernel_sizes=(7, 12, 14, 24, 48)):
    super().__init__()
    self.kernel_sizes = kernel_sizes                            # the set of widths is a hyperparameter (an example here)
    self.gate = nn.Linear(d_model, len(kernel_sizes))           # L(x): outputs the mixing weights

  def moving_avg(self, x, k):
    front = x[:, :1].repeat(1, (k - 1) // 2, 1)
    end = x[:, -1:].repeat(1, k // 2, 1)
    xp = torch.cat([front, x, end], dim=1).transpose(1, 2)
    return F.avg_pool1d(xp, kernel_size=k, stride=1).transpose(1, 2)

  def forward(self, x):                                         # x: [B, L, D]
    trends = torch.stack([self.moving_avg(x, k) for k in self.kernel_sizes], dim=-1)  # [B, L, D, K]
    w = torch.softmax(self.gate(x), dim=-1).unsqueeze(2)        # [B, L, 1, K]
    trend = (trends * w).sum(dim=-1)
    return x - trend, trend                                     # seasonal, trend


class EncoderLayer(nn.Module):
  """Encoder layer (Eq. 1): FEB + residual → MOE decomposition → FF + residual → MOE decomposition. The trend is discarded"""

  def __init__(self, d_model=512, seq_len=96, d_ff=2048, dropout=0.05):
    super().__init__()
    self.feb = FEBf(d_model, seq_len)
    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 = MOEDecomp(d_model), MOEDecomp(d_model)
    self.drop = nn.Dropout(dropout)

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


layer = EncoderLayer(d_model=512, seq_len=96)
x = torch.randn(32, 96, 512)                                    # embedded look-back window [B, I, D]
layer.train()                                                   # dropout is active only during training
y = layer(x)                                                    # [32, 96, 512]
layer.eval()
with torch.no_grad():
  y = layer(x)

FAQ

Q. What is a "mode"?
A.

It is each individual frequency component obtained when a Fourier transform splits a series into components by frequency. They range from slow waves to fine ones, such as a change that repeats once a day and a change that repeats twice a day. FEDformer keeps only MM of them (64 by default), selected at random, and applies learned weights to each.

Q. Wouldn't it be more natural to keep only the low frequencies?
A.

Keeping only low frequencies is common for removing noise, but the paper points out that important events, such as sudden changes in the trend, can show up at high frequencies, and discarding them all loses that information. Both theory (Theorem 1) and experiments (Figure 6) show that random selection gives better results than selecting from the lowest frequencies upward.

Q. What changed from Autoformer?
A.

The overall structure (splitting into trend and seasonal parts in every encoder and decoder layer and accumulating the trend) stays the same. Three components changed: the auto-correlation used in place of self-attention became FEB, the auto-correlation between the encoder and decoder became FEA, and the single-width moving average became MOE decomposition. The complexity also dropped from O(Llog⁡L)O(L \log L) to O(L)O(L).

References

  1. Zhou, T., Ma, Z., Wen, Q., Wang, X., Sun, L., & Jin, R. (2022). FEDformer: Frequency Enhanced Decomposed Transformer for Long-term Series Forecasting. Proceedings of the 39th International Conference on Machine Learning, PMLR 162.
  2. MAZiqing/FEDformer (official implementation, PyTorch)
  3. Wu, H., Xu, J., Wang, J., & Long, M. (2021). Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting. NeurIPS 2021.
  4. 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.