AI Logic

Architectures

DLinear

Updated:

DLinear architecture. Left: the overall flow, which splits the look-back window into a trend and a remainder (seasonal) with a moving average, applies a linear layer to each, adds them, and outputs the whole forecast window at once. Right: inside one linear layer (each future value is a weighted sum of the L past values)

Background and overview

DLinear is a model that splits the look-back window into a "trend" and a "remainder (seasonal)" with a moving average, applies one linear layer along the time axis to each, and adds them to predict the whole forecast window at once. It was introduced in 2022 by Zeng, Chen, Zhang, and Xu of The Chinese University of Hong Kong and IDEA in "Are Transformers Effective for Time Series Forecasting?", and published at AAAI 2023. The name stands for Decomposition + Linear.

The real focus of the paper is less the DLinear model itself than the question "Do Transformers actually help long-term forecasting?" At the time, Transformer-based models such as Informer, Autoformer, and FEDformer were being proposed one after another, but the non-Transformer methods they were compared against all predicted one step at a time and stacked the predictions, which lets errors accumulate. The paper suspected that much of the Transformers' improvement came from outputting the whole forecast window at once (direct multi-step forecasting).

To test this, the authors built three models that output the whole forecast window with a single linear layer (collectively called LTSF-Linear).

  • Linear: applies a single linear layer to the look-back window.
  • DLinear: splits the input into trend and remainder, then applies a linear layer to each. It is strongest when the data has a clear trend (such as a steady upward climb).
  • NLinear: subtracts the last value of the look-back window, applies a linear layer, and adds the value back to the output. It is strongest when the level of the values shifts between training and prediction.

In multivariate forecasting on nine benchmarks, these simple models beat most Transformer-based models of the time by 20–50%. Following this result, many later forecasting models, such as PatchTST, TSMixer (Google), and iTransformer, use DLinear as a baseline.

In this article, the past interval used as input is called the look-back window (length LL), and the interval to be predicted is called the forecast window (length TT). DLinear computes the TT values of the forecast window directly as weighted sums of the LL values of the look-back window.

Architecture

The input is the look-back window of CC variables, X∈RL×CX \in \mathbb{R}^{L \times C}. The output is the forecast window X^∈RT×C\hat{X} \in \mathbb{R}^{T \times C}. In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of one linear layer.

Linear (the base linear model)

For each variable ii, a linear layer along the time axis, W∈RT×LW \in \mathbb{R}^{T \times L}, is applied to the look-back series Xi∈RLX_i \in \mathbb{R}^{L}.

X^i=WXi\hat{X}_i = W X_i

Each future value is a weighted sum of the LL past values. The weights WW are shared across all variables, and relationships between variables are not used.

DLinear's forecasting flow

  1. Extract the trend: pad both ends of the look-back window by repeating the edge values (k−1)/2(k-1)/2 times, then apply a moving average of width k=25k = 25. The result is the trend XtX_t (its length stays LL).
  2. Compute the remainder: subtract the trend from the original series to get the remainder (seasonal) Xs=X−XtX_s = X - X_t.
  3. Apply a linear layer to each: apply Wt∈RT×LW_t \in \mathbb{R}^{T \times L} to the trend and Ws∈RT×LW_s \in \mathbb{R}^{T \times L} to the remainder.
  4. Add: the sum of the two outputs is the forecast.
Xt=AvgPool(Padding(X)),Xs=X−Xt,X^=WsXs+WtXtX_t = \mathrm{AvgPool}(\mathrm{Padding}(X)), \qquad X_s = X - X_t, \qquad \hat{X} = W_s X_s + W_t X_t

This decomposition, which extracts the trend with a moving average and treats the difference from the original series as the seasonal component, is the same series decomposition used in Autoformer and FEDformer (the moving-average width of 25 also matches Autoformer). DLinear keeps only that decomposition and replaces the attention parts with linear layers.

NLinear

NLinear subtracts the last value of the look-back window, xLx_L, from the whole window, applies the linear layer, and then adds xLx_L back. It is a simple normalization that aligns the level of the values with the last value.

X^i=W(Xi−xL,i)+xL,i\hat{X}_i = W (X_i - x_{L,i}) + x_{L,i}

Number of parameters

Linear and NLinear have T⋅LT \cdot L parameters (the number of weights), and DLinear has 2T⋅L2 T \cdot L. The official implementation lets the weights be either shared across all variables or separate for each variable (individual).

Why it works

The paper runs several experiments to investigate why simple models like DLinear are strong, and why Transformer-based models are less effective than expected.

A linear layer uses the temporal order directly

The linear-layer weight WijW_{ij} represents "how much the jj-th past time step affects the ii-th future time step." Because the weight is tied to the position of each value, the temporal order is used directly in the forecast. Self-attention, by contrast, produces the same computation even when the order of its inputs is shuffled, and relies on positional embeddings for order information.

The paper ran an experiment that randomly shuffles the order of the look-back window (Table 5 of the paper). On Exchange-Rate (currency exchange rates), Linear's error worsened by 27% on average, while FEDformer, Autoformer, and Informer barely changed. The fact that breaking the order does not change the results shows that Transformer-based models make little use of temporal order.

Long-term forecasts depend on trend and periodicity

The paper argues that forecasts far into the future depend less on fine movements in the look-back window than on whether the model can capture trend and periodicity. Trend and periodicity can be expressed with few parameters, so large models are actually more prone to overfitting the noise. In the Electricity setting DLinear has 140K parameters, less than one hundredth of the 13M–20M of the Transformer-based models (Table 8 of the paper).

Lengthening the look-back window helps only the linear models

When the look-back length LL was varied from 24 to 720, the errors of the Transformer-based models stayed flat or got worse, while the errors of Linear, NLinear, and DLinear dropped as the window grew (Figure 4 of the paper). The paper explains that Transformer-based models tend to overfit the noise in long windows.

Decomposition handles the trend separately

A single linear layer has to handle both a trend, such as a steep upward climb, and daily cycles at once. DLinear first extracts the trend and splits the work between two linear layers, one for the trend and one for the seasonal part. The paper explains that this decomposition improves on Linear's accuracy when the data has a clear trend.

Because the linear-layer weights directly show "which time steps were used and how much," arranging the trained weights as an image reveals what the model relied on. In Appendix D.3 of the paper, on Traffic (hourly), large weights appear on the most recent time steps of the look-back window at intervals of 24 steps (one day) and 168 steps (one week) across the future steps, showing that the model uses daily and weekly cycles.

Experimental results

Long-term forecasting benchmarks (multivariate; MSE, lower is better; excerpt from Table 2 of the paper)

LTSF-Linear uses a look-back window of L=336L = 336, and the Transformer-based models use L=96L = 96 (Transformer-based models tend to get worse with longer windows, so each is compared at a length favorable to it). Nine datasets were used for evaluation: ETT (ETTh1, ETTh2, ETTm1, ETTm2), Electricity, Exchange-Rate, Traffic, Weather, and ILI.

DataTTLinearNLinearDLinearFEDformerAutoformerInformerRepeat last value
Electricity960.1400.1410.1400.1930.2010.2741.588
Exchange7200.9641.0330.6431.1951.4472.4780.823
Traffic960.4100.4100.4100.5870.6130.7192.723
Weather960.1760.1820.1760.2170.2660.3000.259
ETTh1960.3750.3740.3750.3760.4490.8651.295
ETTh27200.6980.3940.6050.4630.5153.6470.588
ETTm1960.3080.3060.2990.3790.5050.6721.214
ILI241.9471.6832.2153.2283.4835.7646.587

In many settings, the best of the three linear models was 20–50% lower than the best Transformer-based model. Which model does best depends on the data: DLinear is strongest on Exchange-Rate, which has a clear trend, while NLinear is strongest on ETTh2 and ILI, where the level shifts a lot. On the other hand, for short-horizon forecasting on ETTh1 (T=96T = 96), the gap to FEDformer was under 1%.

Computational cost (Electricity, L=96L = 96, T=720T = 720; Table 8 of the paper)

ModelMACsParametersInference timeMemory
DLinear0.04G140K0.4 ms687 MiB
Transformer4.03G13.61M26.8 ms6,091 MiB
Informer3.93G14.39M49.3 ms3,869 MiB
Autoformer4.41G14.91M164.1 ms7,607 MiB
FEDformer4.41G20.68M40.5 ms4,143 MiB

Gradually turning Informer into a linear model (MSE, L=96L = 96; Table 4 of the paper)

DataTTInformerAttention → linear layerEmbedding + linear layerLinear layer only
Exchange960.8471.0030.1730.084
ETTh1960.8650.6130.4540.400

The more components were removed and the simpler the model became, the lower the error. The paper concludes that, at least on these benchmarks, self-attention and the complex components around it were not needed.

Practical considerations

Keep the following points in mind when using DLinear.

  • Nonlinear relationships and abrupt changes are hard to capture: a single linear layer has limited expressive power. The paper also notes that movements caused by change points (where behavior shifts at a certain time) are hard to capture.
  • Relationships between variables are not used: each variable is forecast independently. For data where other variables are informative, compare against models such as TSMixer (Google) and iTransformer.
  • Use a fairly long look-back window: with short inputs, linear models lack expressive power (the paper uses L=336L = 336 as the default).
  • Compare Linear, DLinear, and NLinear before choosing: which is best depends on the data. DLinear suits data with a clear trend, and NLinear suits data whose level changes greatly over time.
  • The forecast length is built into the model: the weights have shape T×LT \times L, so changing LL or TT requires retraining.

DLinear was proposed as a baseline for checking "whether complex models actually beat this simple reference on long-term forecasting benchmarks." The paper itself describes DLinear as merely a simple baseline with limited expressive power. Always include it as a baseline when evaluating new models, and when using it for real forecasting, compare it against more expressive models as well.

Comparison with other models

The table below lines up models commonly used for long-term forecasting from the same perspectives. LL is the length of the look-back window.

ModelTemporal modelingRelationships between variablesHow the forecast window is producedComplexity in input length LL
InformerProbSparse self-attention and distillationMixed in the embeddingAll at once (generative decoder)O(Llog⁡L)O(L \log L)
AutoformerSeries decomposition and auto-correlationMixed in the embeddingAll at onceO(Llog⁡L)O(L \log L)
DLinearSeries decomposition and per-time-step linear weightsNot used (each variable independent)All at once (linear layer)O(L)O(L)
PatchTSTSelf-attention over patchesNot used (each variable independent)All at once (flatten + linear layer)O((L/S)2)O((L/S)^2)
TSMixer (Google)MLP across time stepsMixed by an MLP across variablesAll at once (linear projection)O(L)O(L)
N-BEATSStacked fully connected layers and basis expansionNot used (univariate)All at onceO(L)O(L)

DLinear and Autoformer both split the series into trend and seasonal parts with a moving average. Autoformer repeats the decomposition in every layer of the network and handles the seasonal component with auto-correlation, whereas DLinear decomposes the input only once and forecasts each part with a single linear layer.

Rough guidelines for choosing:

  • To measure the effect of a new model or feature: include DLinear and NLinear as baselines. Training finishes in seconds and needs almost no tuning.
  • To forecast series with clear periodicity and trend on limited compute: DLinear is practical as is.
  • To read finer patterns from a long look-back window: PatchTST outperformed DLinear on the larger benchmarks.
  • When relationships between variables or auxiliary features matter: TSMixer (Google) and iTransformer are candidates.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
DLinear implementation (follows Section 4, Figure 2, and Appendix B.2 of the paper arXiv:2205.13504,
and models/DLinear.py in the official implementation cure-lab/LTSF-Linear)
Input x: [batch, look-back window L, variables C] -> output: [batch, forecast window T, variables C]
"""


class MovingAvg(nn.Module):
  """Extract the trend with a moving average. Pad both ends by repeating the edge values to keep the length L"""

  def __init__(self, kernel_size=25):
    super().__init__()
    self.k = kernel_size
    self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=1, padding=0)

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


class DLinear(nn.Module):
  def __init__(self, seq_len=336, pred_len=96, n_vars=7, kernel_size=25, individual=False):
    super().__init__()
    self.decomp = MovingAvg(kernel_size)
    self.individual = individual
    if individual:  # separate weights for each variable
      self.linear_seasonal = nn.ModuleList([nn.Linear(seq_len, pred_len) for _ in range(n_vars)])
      self.linear_trend = nn.ModuleList([nn.Linear(seq_len, pred_len) for _ in range(n_vars)])
    else:           # weights shared across all variables (W_s, W_t ∈ R^{T×L})
      self.linear_seasonal = nn.Linear(seq_len, pred_len)
      self.linear_trend = nn.Linear(seq_len, pred_len)

  def forward(self, x):                                   # x: [B, L, C]
    trend = self.decomp(x)                                # trend X_t
    seasonal = x - trend                                  # remainder (seasonal) X_s = X − X_t
    trend, seasonal = trend.permute(0, 2, 1), seasonal.permute(0, 2, 1)  # [B, C, L]
    if self.individual:
      s = torch.stack([f(seasonal[:, i]) for i, f in enumerate(self.linear_seasonal)], dim=1)
      t = torch.stack([f(trend[:, i]) for i, f in enumerate(self.linear_trend)], dim=1)
    else:
      s, t = self.linear_seasonal(seasonal), self.linear_trend(trend)    # linear layers along the time axis
    return (s + t).permute(0, 2, 1)                       # [B, T, C]


class NLinear(nn.Module):
  """Subtract the last value, apply a linear layer, then add it back"""

  def __init__(self, seq_len=336, pred_len=96):
    super().__init__()
    self.linear = nn.Linear(seq_len, pred_len)

  def forward(self, x):                                   # x: [B, L, C]
    last = x[:, -1:, :].detach()
    y = self.linear((x - last).permute(0, 2, 1)).permute(0, 2, 1)
    return y + last


# Usage (7 variables as in ETTh1; predict the next 96 steps from the past 336 steps)
model = DLinear(seq_len=336, pred_len=96, n_vars=7)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.MSELoss()

x = torch.randn(32, 336, 7)                               # look-back window
y = torch.randn(32, 96, 7)                                # ground truth for the forecast window

model.train()                                             # no dropout or normalization, so train and eval compute the same thing
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
optimizer.step()

model.eval()
with torch.no_grad():
  pred = model(x)                                         # [32, 96, 7]

# The learned weights (future time steps × past time steps) show which time steps the model relied on
w_seasonal = model.linear_seasonal.weight                 # [T, L] = [96, 336]

FAQ

Q. If DLinear beats Transformers, does that mean Transformers are unsuited to time series forecasting?
A.

The paper's conclusion is that "at least on the benchmarks of the time, the design choices of the Transformer-based models of the time were not paying off." Later, PatchTST, which uses patches as tokens, and iTransformer, which uses variables as tokens, outperformed DLinear on the same benchmarks. This shows that Transformers can perform well in time series forecasting once the way tokens are formed is rethought.

Q. How should I choose among Linear, DLinear, and NLinear?
A.

In the paper's results, DLinear tended to do better on data with a clear trend (such as Exchange-Rate), and NLinear on data whose level shifts between training and prediction (such as ETTh2 and ILI). On strongly periodic data such as Electricity and Traffic, the three were nearly identical. All three are cheap to train, so the reliable approach is to try all of them and pick one on validation data.

Q. How should the moving-average width of 25 be chosen?
A.

The paper uses 25, the same as Autoformer. A wider window gives a smoother trend and leaves more short cycles in the seasonal component. You can tune it using the period of the data as a guide (for example, 24 for a daily cycle in hourly data), but the paper does not compare different widths.

References

  1. Zeng, A., Chen, M., Zhang, L., & Xu, Q. (2023). Are Transformers Effective for Time Series Forecasting? AAAI 2023.
  2. cure-lab/LTSF-Linear (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. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.