AI Logic

Architectures

Crossformer

Updated:

Structure of Crossformer. The left side shows the overall flow: an encoder that embeds the lookback window into per-variable segments and stacks two-stage attention layers while merging segments, and a decoder that predicts at each scale and sums the results. The right side shows the inside of a two-stage attention layer (attention along the time direction, and attention along the variable direction through routers)

Background and overview

Crossformer is a long-horizon forecasting model that embeds a multivariate time series into a 2D array of "short per-variable intervals (segments)" and captures both the relations between time steps and the relations between variables with a two-stage attention split into a time direction and a variable direction. It was introduced in 2023 by Zhang and Yan of Shanghai Jiao Tong University in "Crossformer: Transformer Utilizing Cross-Dimension Dependency for Multivariate Time Series Forecasting" and published at ICLR 2023.

In image recognition there is a different model with a very similar name, CrossFormer, introduced by Wang et al. in 2021 ("CrossFormer: A Versatile Vision Transformer Hinging on Cross-scale Attention", arXiv:2108.00154). It is a vision Transformer that embeds image patches at multiple sizes and has nothing to do with the time series forecasting Crossformer covered in this article. When you see the name in a paper or library, check which one is meant.

Earlier Transformer-based time series forecasting models (Informer, Autoformer, FEDformer, and others) focused mainly on capturing relations between time steps efficiently. The values of all variables at a time step were simply embedded into one vector, and relations between variables (for example, electricity usage rising when the temperature rises) were not handled explicitly.

To use these "relations between variables" explicitly, Crossformer combines three components.

  1. Dimension-segment-wise embedding (DSW embedding): cuts the series of each variable into intervals of length LsegL_{\mathrm{seg}} and turns each interval into one vector.
  2. Two-stage attention layer (TSA layer): applies attention first along the time direction and then along the variable direction. The variable direction goes through a small number of "routers" to keep the cost down.
  3. Hierarchical encoder-decoder (HED): merges adjacent segments to build coarser time scales, predicts at each scale, and sums the predictions.

In this article, the past interval used as input for the forecast is called the lookback window, and the interval to be predicted is called the forecast window. In the paper's notation, the lookback window length is TT, the forecast window length is τ\tau, and the number of variables is DD (note that these symbols differ from LL and TT in other articles).

Architecture

The input is the lookback window x1:T∈RT×Dx_{1:T} \in \mathbb{R}^{T \times D}. The output is the forecast window xT+1:T+τ∈Rτ×Dx_{T+1:T+\tau} \in \mathbb{R}^{\tau \times D}. In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of a two-stage attention layer.

1. Dimension-segment-wise embedding (DSW embedding)

The series of each variable dd is cut into segments xi,d(s)∈RLsegx^{(s)}_{i,d} \in \mathbb{R}^{L_{\mathrm{seg}}} of length LsegL_{\mathrm{seg}} (1≤i≤T/Lseg1 \le i \le T/L_{\mathrm{seg}}). Each segment is mapped to dmodeld_{\mathrm{model}} dimensions with a learned matrix EE, and a learned position embedding for each (time position ii, variable dd) is added.

hi,d=E xi,d(s)+Ei,d(pos)h_{i,d} = E\, x^{(s)}_{i,d} + E^{(\mathrm{pos})}_{i,d}

The result is a 2D (time × variable) array of vectors HH. The paper argues that using intervals rather than single time steps as the unit is more natural, based on the observation that the attention weights of the original Transformer form interval-shaped clusters in which nearby time steps get similar values.

2. Two-stage attention layer (TSA layer)

Two stages are applied in order to the input Z∈RL×D×dmodelZ \in \mathbb{R}^{L \times D \times d_{\mathrm{model}}} (LL is the number of segments).

  1. Cross-time stage: for each variable, applies multi-head attention between segments, followed by a residual connection, layer normalization, and a 2-layer MLP. The weights are shared across all variables. The cost is O(DL2)O(DL^2).
  2. Cross-dimension stage: for each time step (segment position), captures the relations between variables. Direct attention among DD variables costs O(D2)O(D^2), so a small number of learned routers Ri,:R_{i,:} (cc of them; the paper uses c=10c = 10) are used.
    • With the routers as queries, information is gathered from all variables (Bi,:B_{i,:}).
    • With each variable as the query, the gathered information is received from the routers.

The cross-time stage is written as Eq. (3) in the paper (Z:,dZ_{:,d} is all segments of variable dd).

Z^:,dtime=LayerNorm(Z:,d+MSAtime(Z:,d,Z:,d,Z:,d)),Ztime=LayerNorm(Z^time+MLP(Z^time))\hat{Z}^{\mathrm{time}}_{:,d} = \mathrm{LayerNorm}\bigl(Z_{:,d} + \mathrm{MSA}^{\mathrm{time}}(Z_{:,d}, Z_{:,d}, Z_{:,d})\bigr), \qquad Z^{\mathrm{time}} = \mathrm{LayerNorm}\bigl(\hat{Z}^{\mathrm{time}} + \mathrm{MLP}(\hat{Z}^{\mathrm{time}})\bigr)

The cross-dimension stage is Eq. (4) (Zi,:Z_{i,:} is all variables at position ii).

Bi,:=MSA1dim(Ri,:,Zi,:time,Zi,:time),Zˉi,:dim=MSA2dim(Zi,:time,Bi,:,Bi,:)B_{i,:} = \mathrm{MSA}^{\mathrm{dim}}_1(R_{i,:}, Z^{\mathrm{time}}_{i,:}, Z^{\mathrm{time}}_{i,:}), \qquad \bar{Z}^{\mathrm{dim}}_{i,:} = \mathrm{MSA}^{\mathrm{dim}}_2(Z^{\mathrm{time}}_{i,:}, B_{i,:}, B_{i,:}) Z^dim=LayerNorm(Ztime+Zˉdim),Zdim=LayerNorm(Z^dim+MLP(Z^dim))\hat{Z}^{\mathrm{dim}} = \mathrm{LayerNorm}(Z^{\mathrm{time}} + \bar{Z}^{\mathrm{dim}}), \qquad Z^{\mathrm{dim}} = \mathrm{LayerNorm}\bigl(\hat{Z}^{\mathrm{dim}} + \mathrm{MLP}(\hat{Z}^{\mathrm{dim}})\bigr)

Going through the routers lowers the cost of the variable direction from O(D2L)O(D^2 L) to O(DL)O(DL), so the whole TSA layer costs O(DL2)O(DL^2). After the two stages, there is a path for information between any two segments (even when both the time step and the variable differ).

3. Hierarchical encoder-decoder (HED)

  • Encoder: from the second layer on, the vectors of two segments adjacent in time are concatenated and combined into one with a learned matrix M∈Rdmodel×2dmodelM \in \mathbb{R}^{d_{\mathrm{model}} \times 2d_{\mathrm{model}}} (segment merging), and then a TSA layer is applied. The higher the layer, the longer the time span one vector represents. Including the output of the DSW embedding, NN layers produce representations at N+1N+1 scales.
  • Decoder: starts from a learned embedding E(dec)E^{(\mathrm{dec})} that represents the positions of the forecast window. In each layer, after a TSA layer, it attends per variable to the encoder output of the same scale and passes the result through an MLP.
  • Prediction: the output of each decoder layer is mapped back to segments of length LsegL_{\mathrm{seg}} with a linear layer WlW^l and rearranged into the forecast window. The final prediction is the sum of the predictions at the N+1N+1 scales.
xT+1:T+τpred=∑l=0NxT+1:T+τpred,lx^{\mathrm{pred}}_{T+1:T+\tau} = \sum_{l=0}^{N} x^{\mathrm{pred},l}_{T+1:T+\tau}

Why it works

The paper explains that each of the three components plays a separate role.

Intervals as the unit, keeping the shape of each variable

When all variables at one time step are put into one vector, values with different units and meanings get mixed, and each vector holds only one time step of temporal information. With DSW embedding, one vector represents "the shape of one variable over one interval", so comparisons along both the time direction and the variable direction happen in meaningful units.

Handling time and variables separately

For an image, height and width mean the same thing even if swapped, but "time" and "variable" in a time series mean different things. Also, flattening the 2D array into one sequence and applying ordinary attention costs O(D2T2/Lseg2)O(D^2 T^2 / L_{\mathrm{seg}}^2), which is infeasible for data with many variables. By handling time and variables in turn, the TSA layer keeps their different meanings while keeping the cost down.

Routers as "coordinators"

In a meeting analogy, the router mechanism replaces everyone talking one-on-one with everyone else (D2D^2 conversations) with a few coordinators (routers) who first collect everyone's opinions and then distribute them to everyone (2cD2cD conversations). This makes it possible to handle relations between variables even for data such as Traffic, which has 862 variables.

Summing predictions over multiple time scales

Fine scales help with near-term predictions, and coarse scales help with far-ahead predictions. Predicting at each scale and summing makes use of both. In the paper's experiments, the hierarchical structure actually lowered accuracy for short horizons but raised it for long horizons.

The segment length LsegL_{\mathrm{seg}} plays the same role as the patch length in PatchTST. The difference is that PatchTST handles each variable separately without mixing them, whereas Crossformer mixes variables in the cross-dimension stage.

Experimental results

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

The evaluation used six datasets: ETT (ETTh1 and ETTm1), WTH (weather), ECL (electricity), ILI, and Traffic. The lookback window length TT was searched as a hyperparameter for each forecast length τ\tau.

Dataτ\tauCrossformerFEDformerAutoformerInformerTransformerMTGNN
ETTh1240.3050.3180.4390.5770.6200.336
ETTh17200.5190.5210.5391.2151.2410.916
ETTm1240.2110.2900.4100.3230.3060.260
ETTm16720.5690.4550.6071.1921.2310.620
ECL480.1560.2290.2410.3440.3340.173
ECL9600.4330.3930.3660.4600.4920.471
Traffic240.4910.5620.5500.6080.5970.506
Traffic7200.5730.6230.6740.7920.6850.557
ILI243.0412.6873.1014.5883.9544.265

Crossformer was best in 36 of the 58 settings (MSE and MAE) and in the top two in 51. On the other hand, on the small ILI dataset, FEDformer and Autoformer, which build in series decomposition, came out ahead. The paper suggests that when data is scarce, models with the prior knowledge of decomposition have an advantage. It also takes the fact that MTGNN, which handles relations between variables with a graph, beat many Transformer-based models as evidence of the importance of relations between variables.

Note that Crossformer uses only past values as input, while the other models also use timestamp features (such as the hour of day).

Effect of each component (ETTh1, MSE; Table 2 of the paper)

τ\tauTransformerDSWDSW + TSADSW + HEDDSW + TSA + HED
240.6200.3730.3220.4060.305
1680.9470.9470.4730.6140.410
7201.2411.0860.6360.8410.519

DSW embedding alone improved on the Transformer, and adding the TSA layer improved every horizon. The combination of all three was best at every horizon.

Effect of hyperparameters (ETTh1; Figure 4 of the paper)

  • Segment length LsegL_{\mathrm{seg}}: for short horizons (τ=24,48\tau = 24, 48), shorter segments were slightly better; for long horizons (τ≥168\tau \ge 168), extending from 4 to 24 lowered the error. Extending to 48 was slightly worse than 24. The paper attributes this to 24 hours matching the daily cycle of this data.
  • Number of routers cc: for τ≤336\tau \le 336, results were stable as cc changed; for τ=720\tau = 720, the error was large with c=3c = 3 and stable with c≥5c \ge 5.

Practical notes

Keep the following points in mind when using Crossformer.

  • Match the segment length to the period of the data: on ETTh1, 24, which matches the daily cycle, gave the best results for long horizons. For data with an unknown period, try several lengths.
  • A long lookback window raises the cost: the cost of an encoder layer is O(DT2/Lseg2)O(D T^2 / L_{\mathrm{seg}}^2), proportional to the square of the lookback window length TT. For long windows, use longer segments to reduce LL.
  • On small data, it can lose to models with built-in decomposition: in data-scarce settings such as ILI, Autoformer and FEDformer came out ahead.
  • The hierarchical structure can hurt short horizons: in the component ablation, adding only HED to DSW lowered accuracy for short horizons (combined with TSA, it improved).
  • Comparisons in later work: in the iTransformer paper (a comparison with the lookback window fixed at 96), Crossformer was far behind PatchTST and DLinear on ETT and Exchange. The iTransformer paper suggests that mixing segments that are not aligned in time introduces noise.

The lengths of the lookback and forecast windows are assumed to be divisible by the segment length LsegL_{\mathrm{seg}}. When they are not, the lookback window is padded at the front by repeating the first value x1x_1, and the forecast window is produced a little longer in segment units, with the first τ\tau values used (Appendix D.1 of the paper). The implementation example below handles only the divisible case.

Comparison with other models

Lining up models commonly used for long-horizon forecasting from the same viewpoints gives the following. LL is the lookback window length and MM is the number of variables (this table uses the same symbols as other articles).

ModelOne tokenRelations between variablesHow the forecast window is producedMain cost factor
InformerAll variables at one time stepMixed in the embeddingAll at once (generative decoder)O(Llog⁡L)O(L \log L)
AutoformerAll variables at one time stepMixed in the embeddingAll at onceO(Llog⁡L)O(L \log L)
PatchTSTA patch of one variableNot used (each variable independent)All at once (flatten + linear layer)Square of the number of patches
CrossformerA segment of one variableAttention along the variable direction (through routers)All at once (sum of per-scale predictions)O(M(L/Lseg)2)O(M (L/L_{\mathrm{seg}})^2)
iTransformerThe whole lookback window of one variableAttention along the variable directionAll at once (linear projection)O(M2)O(M^2)
TSMixer (Google)(No tokens; MLP)Mixed by an MLP along the variable directionAll at once (linear projection)O(L+M)O(L + M) parameters

Rough guidelines for choosing:

  • To capture both relations between variables and fine relations between time steps: Crossformer is one of the few models that applies attention along both the time and variable directions.
  • Many variables, and you want to use their relations easily: also compare iTransformer, which has a simpler structure.
  • Weak relations between variables: PatchTST and DLinear, which treat variables independently, are strong baselines with little computation.
  • Small data with clear periods and trends: Autoformer and FEDformer, which build in series decomposition, can have an advantage.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of Crossformer's components (following Eqs. 1-4 and Eq. 6 of Zhang & Yan, ICLR 2023)
Shows the DSW embedding, the two-stage attention (TSA) layer, and segment merging.
Input x: [batch B, lookback window T, variables D] (T is assumed divisible by L_seg)
"""


class DSWEmbedding(nn.Module):
  """Cut each variable into segments of length L_seg and turn them into vectors with a linear layer + position embedding (Eqs. 1, 2)"""

  def __init__(self, seg_len, d_model, n_segs, n_vars):
    super().__init__()
    self.seg_len = seg_len
    self.proj = nn.Linear(seg_len, d_model)                               # E
    self.pos = nn.Parameter(torch.randn(1, n_vars, n_segs, d_model) * 0.02)  # E^(pos)_{i,d}

  def forward(self, x):                                   # x: [B, T, D]
    B, T, D = x.shape
    seg = x.permute(0, 2, 1).reshape(B, D, T // self.seg_len, self.seg_len)  # [B, D, L, L_seg]
    return self.proj(seg) + self.pos                      # [B, D, L, d_model]


def mlp(d_model, d_ff, dropout):
  return nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model))


class TSALayer(nn.Module):
  """Two-stage attention layer (Eqs. 3, 4)"""

  def __init__(self, n_segs, d_model, n_heads=4, d_ff=256, n_routers=10, dropout=0.1):
    super().__init__()
    # Cross-time stage (weights shared across all variables)
    self.time_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout, batch_first=True)
    self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
    self.mlp1 = mlp(d_model, d_ff, dropout)
    # Cross-dimension stage: c learned routers R per position
    self.router = nn.Parameter(torch.randn(n_segs, n_routers, d_model) * 0.02)
    self.sender = nn.MultiheadAttention(d_model, n_heads, dropout=dropout, batch_first=True)    # MSA^dim_1
    self.receiver = nn.MultiheadAttention(d_model, n_heads, dropout=dropout, batch_first=True)  # MSA^dim_2
    self.norm3, self.norm4 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
    self.mlp2 = mlp(d_model, d_ff, dropout)
    self.drop = nn.Dropout(dropout)

  def forward(self, z):                                   # z: [B, D, L, d_model]
    B, D, L, E = z.shape
    # Time direction: attention between segments, per variable
    t = z.reshape(B * D, L, E)
    t = self.norm1(t + self.drop(self.time_attn(t, t, t, need_weights=False)[0]))
    t = self.norm2(t + self.drop(self.mlp1(t)))
    # Variable direction: per position, routers gather from all variables (B_i) and distribute to all variables
    s = t.reshape(B, D, L, E).permute(0, 2, 1, 3).reshape(B * L, D, E)    # [B*L, D, E]
    r = self.router.unsqueeze(0).expand(B, -1, -1, -1).reshape(B * L, -1, E)  # [B*L, c, E]
    buf = self.sender(r, s, s, need_weights=False)[0]                     # gather
    recv = self.receiver(s, buf, buf, need_weights=False)[0]              # distribute
    s = self.norm3(s + self.drop(recv))
    s = self.norm4(s + self.drop(self.mlp2(s)))
    return s.reshape(B, L, D, E).permute(0, 2, 1, 3)      # [B, D, L, d_model]


class SegMerge(nn.Module):
  """Concatenate two adjacent segments and combine them with matrix M (Eq. 6; from the second encoder layer on; normalization follows the official implementation)"""

  def __init__(self, d_model):
    super().__init__()
    self.norm = nn.LayerNorm(2 * d_model)
    self.merge = nn.Linear(2 * d_model, d_model)          # M ∈ R^{d_model × 2 d_model}

  def forward(self, z):                                   # z: [B, D, L, E] (L assumed even)
    B, D, L, E = z.shape
    z = z.reshape(B, D, L // 2, 2 * E)
    return self.merge(self.norm(z))                       # [B, D, L/2, E]


# Usage (like ETTh1: 7 variables, 168 past steps, segment length 24 -> 7 segments)
x = torch.randn(32, 168, 7)
embed = DSWEmbedding(seg_len=24, d_model=64, n_segs=7, n_vars=7)
tsa = TSALayer(n_segs=7, d_model=64)

tsa.train()                                               # training: dropout is active
z = tsa(embed(x))                                         # [32, 7, 7, 64] (variables × segments × features)

tsa.eval()                                                # inference: dropout is off
with torch.no_grad():
  z = tsa(embed(x))

FAQ

Q. Are the image CrossFormer and the time series Crossformer the same thing?
A.

They are different models. The image CrossFormer (Wang et al., 2021, arXiv:2108.00154) is an image recognition Transformer that embeds image patches at multiple sizes and handles relations between nearby and distant patches. The time series Crossformer (Zhang & Yan, ICLR 2023) is a forecasting model that handles both the time and variable relations of a multivariate time series. The capitalization of the names (CrossFormer vs. Crossformer) also differs.

Q. How should the number of routers $c$ be chosen?
A.

The paper uses c=10c = 10. In the ETTh1 experiments, accuracy barely changed for cc from 3 to 20 when the forecast length was 336 or less, and at 720 it was stable for c≥5c \ge 5. Increasing cc widens the path for information between variables but raises the cost O(2cD)O(2cD).

Q. How does it differ from iTransformer?
A.

Both use attention to handle relations between variables. Crossformer splits time into segments, applies attention in two stages along the time and variable directions, and predicts with a hierarchical decoder. iTransformer makes the whole lookback window into one token, uses attention only along the variable direction, and leaves temporal changes to the feed-forward layer. In the comparison in the iTransformer paper (lookback window 96), iTransformer gave better results on most datasets.

References

  1. Zhang, Y., & Yan, J. (2023). Crossformer: Transformer Utilizing Cross-Dimension Dependency for Multivariate Time Series Forecasting. ICLR 2023.
  2. Thinklab-SJTU/Crossformer (official implementation, PyTorch)
  3. Wang, W., Yao, L., Chen, L., et al. (2021). CrossFormer: A Versatile Vision Transformer Hinging on Cross-scale Attention (an image model with a similar name).
  4. Liu, Y., Hu, T., Zhang, H., Wu, H., Wang, S., Ma, L., & Long, M. (2024). iTransformer: Inverted Transformers Are Effective for Time Series Forecasting. ICLR 2024.
  5. 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. AAAI 2021.