AI Logic

Architectures

iTransformer

Updated:

Architecture of iTransformer. The left side shows the overall flow: each variable of the past window is embedded into its own variate token, encoder layers are stacked, and a projection outputs the future window. The right side shows how tokens are formed in the original Transformer (time steps as tokens) versus iTransformer (variables as tokens), and the inside of an encoder layer

Background and Overview

iTransformer is a long-term forecasting model that keeps every component of the Transformer encoder unchanged and only inverts the direction of the tokens, from "time steps" to "variables". It turns the entire past window of one variable into one token, learns the relationships between variables with attention, and learns each variable's change over time with the feed-forward layer. Liu, Hu, Zhang, Wu, Wang, Ma, and Long of Tsinghua University and Ant Group published it in 2023, and it appeared at ICLR 2024.

Earlier Transformer-based models (Informer, Autoformer, and others) made the values of all variables at one time step into one token. The paper points out the following problems with this design.

  • Values with different meanings get mixed into one: Values with different units and distributions, such as temperature (°C) and power (kW), are embedded into a single vector.
  • The same time step does not necessarily reflect the same event: Variables can be offset in time (a change in one variable may show up in another several hours later).
  • A single time step carries little information: Each token sees too narrow a range, so attention weights struggle to mean anything.

On top of that, the simple linear model DLinear had been shown to beat Transformer-based models, prompting debate over whether Transformers are unsuited to time-series forecasting. The paper's position is that "the Transformer is not unsuitable; the way it was used (which axis becomes the token) was wrong."

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 TT, the future window has length SS, and there are NN variables (note that these symbols differ from LL and TT in other articles).

Architecture

The input is the past-window table X∈RT×NX \in \mathbb{R}^{T \times N} (rows are time steps, columns are variables). The output is the future-window table Y^∈RS×N\hat{Y} \in \mathbb{R}^{S \times N}. In the figure at the top of the article, the left side shows the overall flow, and the right side shows the inside of an encoder layer.

The forecasting flow is as follows.

  1. Normalize: For each variable, subtract the mean of the past window and divide by the standard deviation (the default in the official implementation; the inverse transform is applied to the output).
  2. Make one token per variable: The entire past window of variable nn, X:,n∈RTX_{:,n} \in \mathbb{R}^{T}, is embedded into a DD-dimensional vector hnh_n. This is called a variate token. NN variables yield NN tokens.
  3. Stack encoder layers: In each layer, attention mixes the variate tokens with one another, and the feed-forward layer transforms each token separately (explained in detail below).
  4. Output the future window: Each token hnh_n from the last layer is projected into a forecast Y^:,n\hat{Y}_{:,n} of length SS.

Equation (1) of the paper writes this as follows (ll is the layer index and LL is the number of layers).

hn0=Embedding(X:,n),Hl+1=TrmBlock(Hl)  (l=0,…,L−1),Y^:,n=Projection(hnL)h_n^0 = \mathrm{Embedding}(X_{:,n}), \qquad H^{l+1} = \mathrm{TrmBlock}(H^l)\ \ (l = 0, \dots, L-1), \qquad \hat{Y}_{:,n} = \mathrm{Projection}(h_n^L)

Embedding:RT→RD\mathrm{Embedding}: \mathbb{R}^T \to \mathbb{R}^D and Projection:RD→RS\mathrm{Projection}: \mathbb{R}^D \to \mathbb{R}^S are MLPs in the paper and a single linear layer in the official implementation. The order of time steps is contained in the arrangement of the embedding weights, so the Transformer's positional encoding is not used.

Inside an encoder layer (swapped roles)

The components are the same as in a standard Transformer encoder, but the axes they work on are swapped.

  • Self-attention: learning relationships between variables: Queries, keys, and values Q,K,V∈RN×dkQ, K, V \in \mathbb{R}^{N \times d_k} are built from the NN variate tokens. Each entry of the score matrix A=QK⊤/dk∈RN×NA = QK^\top / \sqrt{d_k} \in \mathbb{R}^{N \times N} represents the strength of the relationship between two variables. The more strongly two variables are related, the more they mix into each other's representations.
  • Feed-forward layer: learning each variable's change over time: A fully connected layer with shared weights is applied to every variate token. Its role is to extract features common to all series, such as amplitude, period, and trend in the past window.
  • Layer normalization: aligning the scale of each variable: The mean and variance are taken over the DD features of each variate token hnh_n. This brings variables with different units onto the same scale and helps with series whose mean and variance shift over time (non-stationary series).
LayerNorm(H)={hn−Mean(hn)Var(hn) | n=1,…,N}\mathrm{LayerNorm}(H) = \left\{ \frac{h_n - \mathrm{Mean}(h_n)}{\sqrt{\mathrm{Var}(h_n)}} \ \middle|\ n = 1, \dots, N \right\}

The paper's experimental setup uses L∈{2,3,4}L \in \{2, 3, 4\} layers, token dimension D∈{256,512}D \in \{256, 512\}, mean squared error as the loss, Adam, batch size 32, and 10 epochs. In the official implementation, when time stamps (hour, day of week, and so on) are provided, they are also fed into the encoder as additional tokens.

Why It Works

The paper explains that inverting the token direction lets each Transformer component do what it is good at.

Attention weights come to mean "relationships between variables"

When time steps are tokens, attention compares "which time step resembles which." But the value at a single time step carries almost no meaning, unlike a word, and attention computes the same result even if the order is shuffled, so information about the order of time steps also tends to be lost. When variables are tokens, the attention scores come to represent "which variable is related to which." In Figure 7 of the paper, the score matrices of shallow layers resembled the correlations between variables in the past window, and those of deep layers resembled the correlations in the future window.

Change over time is handled in the same form as a linear model

The feed-forward layer applies a fully connected layer with shared weights to the representation of each variable's entire past window. This combines the form of linear models like DLinear, which forecast with "fixed weights per time step," with the form of PatchTST, which "shares weights across all variables." As a result, like linear models, it has the property that accuracy improves as the past window gets longer (Figure 6 of the paper). The original Transformer did not improve with a longer window, but the inverted version did.

It works even when the number of variables changes

Since variables are tokens, the model runs even when the number of tokens (variables) differs between training and prediction. A model trained on only 20% of the variables kept the increase in error small when forecasting all variables (Figure 5 of the paper).

As an analogy, the original Transformer compares "daily reports that bundle every item for one day" one sheet at a time, while iTransformer lines up "a month-long chart for each item" and compares them. On a single daily report, items are mixed and hard to read, but with charts side by side it is easy to see that "these two move in the same shape."

Experimental Results

Long-term forecasting benchmarks (multivariate; past window T=96T = 96; MSE averaged over four future-window lengths, lower is better; excerpt from Table 1 of the paper)

The future-window lengths are four short ones for PEMS (S∈{12,24,36,48}S \in \{12, 24, 36, 48\} according to the note on Table 1) and S∈{96,192,336,720}S \in \{96, 192, 336, 720\} for the others. ETT and PEMS are averages over four subsets.

Dataset (variables)iTransformerPatchTSTCrossformerTimesNetDLinearFEDformer
ECL (321)0.1780.2050.2440.1920.2120.214
ETT (7)0.3830.3810.6850.3910.4420.408
Exchange (8)0.3600.3670.9400.4160.3540.519
Traffic (862)0.4280.4810.5500.6200.6250.610
Weather (21)0.2580.2590.2590.2590.2650.309
Solar-Energy (137)0.2330.2700.6410.3010.3300.291
PEMS (170–883)0.1190.2170.2200.1480.3200.224

The gap was especially large on ECL, Traffic, Solar-Energy, and PEMS, which have many variables. On ETT (7 variables) and Exchange (8 variables), which have few, it was roughly on par with PatchTST and DLinear or slightly behind. The paper explains that on highly volatile data such as PEMS, PatchTST, which looks at the data patch by patch, has trouble capturing fine fluctuations.

Improvement from inverting other Transformers (MSE averaged over four future-window lengths; excerpt from Table 2 of the paper)

DatasetVersionTransformerInformerTransformer with FlashAttention
TrafficOriginal0.6650.7640.658
TrafficInverted0.4280.6620.492
WeatherOriginal0.6570.6340.659
WeatherInverted0.2580.2710.262

The inversion idea worked regardless of the type of attention. The average MSE improvement was 38.9% for the Transformer and 28.5% for Informer.

Swapping component roles (MSE; excerpt from Table 3 of the paper)

Variable axisTime axisECLTraffic
AttentionFeed-forward (iTransformer)0.1780.428
AttentionAttention0.1930.913
Feed-forwardAttention (original Transformer form)0.2020.863
Feed-forwardFeed-forward0.1820.599

Placing attention on the variable axis and the feed-forward layer on the time axis gave the best results.

Practical Considerations

Keep the following points in mind when using iTransformer.

  • The advantage is small on data with few variables: On ETT (7 variables) and Exchange (8 variables), it was roughly on par with PatchTST and DLinear. Because the mechanism learns relationships between variables, it suits data with many variables and clear relationships among them.
  • Fine shapes within the window are compressed into one vector: The entire past window is embedded into DD dimensions in a single step, so which shape appeared where in the window must be learned by the embedding and the feed-forward layer. For data where local shapes within the window matter, also compare PatchTST, which works with patches.
  • The forecast length is built into the model: The final projection has D→SD \to S weights, so changing the future-window length requires retraining. The past-window length TT is also built into the shape of the embedding weights.
  • The paper's evaluation centers on a past window of 96: The main comparison (Table 1) uses results aligned at T=96T = 96. A longer window also improves iTransformer, but some competing models improve with a longer window as well.

The computation and memory of attention grow with the square of the number of variables NN. When handling more than several thousand variables, combine it with the method proposed in the paper of "training on only a subset of variables per batch," or with efficient attention (such as FlashAttention). In the paper, training on only a subset of variables left accuracy nearly unchanged while greatly reducing memory (Figure 8).

Comparison with Other Models

Placing models commonly used for long-term forecasting side by side from the same angles gives the following. LL is the past-window length and MM is the number of variables (this table uses the same symbols as other articles).

ModelOne tokenRelationships between variablesHow it outputs the future windowMain driver of complexity
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)
PatchTSTOne patch of one variableNot used (each variable independent)All at once (flatten + linear layer)Square of the number of patches
CrossformerOne segment of one variableAttention along the variable axis (via routers)All at once (hierarchical decoder)Variables × square of the number of segments
iTransformerEntire past window of one variableAttention along the variable axisAll at once (linear projection)O(M2)O(M^2)
TSMixer (Google)(No tokens; MLP)Mixed by an MLP along the variable axisAll at once (linear projection)O(L+M)O(L + M) parameters
DLinear(No tokens; linear layer)Not used (each variable independent)All at once (linear layer)O(L)O(L)

iTransformer and Crossformer both handle relationships between variables with attention. Crossformer splits time into segments and applies attention in two stages, along the time axis and the variable axis, whereas iTransformer leaves the time axis to the feed-forward layer and uses attention only along the variable axis. The paper argues that Crossformer's mixing of segments that are not aligned in time actually adds noise.

Rough guidelines for choosing are as follows.

  • Many variables, and relationships between them help the forecast (electricity, traffic, solar power, and so on): iTransformer is a good fit.
  • Few variables, or weak relationships between them: PatchTST or DLinear is often enough.
  • The number or kind of variables changes between training and prediction: iTransformer, which makes variables into tokens, handles this as is.
  • You want to use auxiliary features (such as promotion schedules): The extended version of TSMixer (Google) is also a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of iTransformer (following Eqs. 1 and 2 and Figure 4 of arXiv:2310.06625,
and model/iTransformer.py in the official implementation thuml/iTransformer)
Input x: [batch B, past window T, variables N] → output: [B, future window S, N]
"""


class InvertedEncoderLayer(nn.Module):
  """A standard Transformer encoder layer, except that the tokens are 'variables'"""

  def __init__(self, d_model, n_heads, d_ff, dropout):
    super().__init__()
    self.attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout, batch_first=True)
    self.ff = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model))
    self.norm1 = nn.LayerNorm(d_model)          # normalize over the D features of each variate token
    self.norm2 = nn.LayerNorm(d_model)
    self.drop = nn.Dropout(dropout)

  def forward(self, h):                         # h: [B, N, D]
    a, _ = self.attn(h, h, h, need_weights=False)   # attention between variables (scores are N × N)
    h = self.norm1(h + self.drop(a))
    h = self.norm2(h + self.drop(self.ff(h)))      # the same feed-forward layer for every variable
    return h


class ITransformer(nn.Module):
  def __init__(self, seq_len=96, pred_len=96, d_model=512, n_heads=8, d_ff=512, n_layers=3, dropout=0.1):
    super().__init__()
    self.embed = nn.Linear(seq_len, d_model)    # Embedding: entire past window (length T) → D-dim variate token
    self.drop = nn.Dropout(dropout)
    self.layers = nn.ModuleList([InvertedEncoderLayer(d_model, n_heads, d_ff, dropout) for _ in range(n_layers)])
    self.norm = nn.LayerNorm(d_model)
    self.project = nn.Linear(d_model, pred_len) # Projection: D dims → future window (length S)

  def forward(self, x):                         # x: [B, T, N]
    # per-variable normalization (use_norm in the official implementation)
    mean = x.mean(dim=1, keepdim=True).detach()
    std = torch.sqrt(x.var(dim=1, keepdim=True, unbiased=False) + 1e-5).detach()
    x = (x - mean) / std
    h = self.drop(self.embed(x.transpose(1, 2)))     # invert: [B, N, T] → [B, N, D]
    for layer in self.layers:
      h = layer(h)
    y = self.project(self.norm(h)).transpose(1, 2)   # [B, N, S] → [B, S, N]
    return y * std + mean                            # de-normalize


# Usage (862 variables as in Traffic; forecast the next 96 steps from the past 96 steps)
model = ITransformer(seq_len=96, pred_len=96)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.MSELoss()                        # the paper's loss is L2 (MSE)

x = torch.randn(32, 96, 862)                    # past window
y = torch.randn(32, 96, 862)                    # ground truth for the future window

model.train()                                   # training: dropout is active
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
optimizer.step()

model.eval()                                    # inference: dropout is off
with torch.no_grad():
  pred = model(x)                               # [32, 96, 862]
  pred_sub = model(x[:, :, :100])               # works as is with a different number of variables [32, 96, 100]

FAQ

Q. If time steps are not tokens, how is the order of time handled?
A.

The weights of the linear layer (or MLP) that embeds the entire past window into one vector are set separately for each time step, so the order is contained in the arrangement of those weights. This is the same way the linear layer of DLinear handles order with per-time-step weights. For this reason, positional encoding is not used.

Q. How does this differ from PatchTST's "channel independence"?
A.

PatchTST processes each variable separately without mixing them, and uses attention among the patches of a single variable. iTransformer is similar in making one token per variable, but it mixes variables with one another through attention. The paper positions iTransformer's tokens as "the extreme case of a patch widened to the entire past window."

Q. Can it be used on a time series with only one variable?
A.

It runs, but with only one token, attention has no meaning, and the model becomes almost the same as an MLP made of the embedding, feed-forward layer, and projection. For univariate forecasting, PatchTST or DLinear is the more straightforward choice.

References

  1. 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.
  2. thuml/iTransformer (official implementation, PyTorch)
  3. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.
  4. Zeng, A., Chen, M., Zhang, L., & Xu, Q. (2023). Are Transformers Effective for Time Series Forecasting? AAAI 2023.
  5. Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). Attention Is All You Need. NeurIPS 2017.