AI Logic

Architectures

PatchTST

Updated:

Structure of PatchTST. The left shows the overall flow: the lookback window is split into per-variable series, which pass through normalization, patching, embedding, a Transformer encoder, and flattening with a linear head to produce the forecast window. The right shows the inside of an encoder layer (multi-head attention and feed-forward, with residual connections and batch normalization) and an example of how patches are cut.

Background and overview

PatchTST is a model that splits a multivariate time series into single series per variable (channel independence), cuts each into short segments (patches), feeds them to a Transformer encoder, and forecasts the whole forecast window at once. It was published in 2022 by Nie, Nguyen, Sinthong, and Kalagnanam of Princeton University and IBM Research in "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers," and appeared at ICLR 2023. The name stands for patch time series Transformer.

The starting point of the paper was the result, shown by the paper that proposed DLinear (Zeng et al.), that "a simple linear model can forecast more accurately than Transformer-based models such as Informer, Autoformer, and FEDformer." Without changing the attention mechanism, PatchTST showed that a Transformer can beat this linear model by rethinking what becomes a single token.

There are two key ideas.

  1. Patching: A value at a single time step, like a single character in a sentence, carries little meaning on its own. So PP consecutive time steps (for example, 16) are grouped into one token. The number of tokens drops to roughly 1/S1/S (SS is the stride between patches), so a longer lookback window can be read with the same compute.
  2. Channel independence: The MM variables are not mixed; each one passes through the same Transformer separately. The embedding and encoder weights are shared across all variables.

It applies to 1D time series the same idea as ViT, which cut images into 16×16 patches to make tokens.

In this article, the past interval used as input for the forecast is called the lookback window (length LL), and the interval to be predicted is called the forecast window (length TT). PatchTST turns the lookback window into a sequence of patches, reads it with the encoder, and outputs all TT values of the forecast window at once with a final linear layer.

Architecture

The input is the lookback window of MM variables (x1,…,xL)(x_1, \dots, x_L), xt∈RMx_t \in \mathbb{R}^M. The output is the forecast window (x^L+1,…,x^L+T)(\hat{x}_{L+1}, \dots, \hat{x}_{L+T}). In the figure at the top of the article, the left shows the overall flow and the right shows the inside of the Transformer encoder.

The forecasting flow is as follows.

  1. Split by variable: Split the input into MM univariate series x(i)∈R1×Lx^{(i)} \in \mathbb{R}^{1 \times L} (i=1,…,Mi = 1, \dots, M). All subsequent processing is done independently for each variable, with the same weights.
  2. Apply instance normalization: For each series, subtract the mean and divide by the standard deviation (instance normalization; the same idea as RevIN). This mitigates the shift in value levels between training and prediction. The mean and standard deviation are restored at the output.
  3. Cut into patches: Append SS copies of the last value to the end of the series, then cut out patches of length PP shifted by SS. The number of patches is N=⌊(L−P)/S⌋+2N = \lfloor (L - P)/S \rfloor + 2. The paper's default setting is P=16P = 16, S=8S = 8, which gives N=42N = 42 patches for L=336L = 336.
  4. Embed: Map each patch to DD dimensions with a linear layer Wp∈RD×PW_p \in \mathbb{R}^{D \times P}, and add a learned position embedding Wpos∈RD×NW_{\mathrm{pos}} \in \mathbb{R}^{D \times N}.
  5. Pass through a Transformer encoder: Stack standard encoder layers that connect multi-head attention and a feed-forward layer with residual connections. Batch normalization is used for normalization.
  6. Output the forecast window: Flatten the encoder output z(i)∈RD×Nz^{(i)} \in \mathbb{R}^{D \times N} into a single vector, and map it with a linear layer to a forecast x^(i)\hat{x}^{(i)} of length TT. Rearranging the MM forecasts gives the multivariate forecast.

The embedding and attention can be written as follows (hh is the head index).

xd(i)=Wp xp(i)+Wpos,Oh(i)⊤=Softmax ⁣(Qh(i)Kh(i)⊤dk)Vh(i)x_d^{(i)} = W_p\, x_p^{(i)} + W_{\mathrm{pos}}, \qquad O_h^{(i)\top} = \mathrm{Softmax}\!\left(\frac{Q_h^{(i)} K_h^{(i)\top}}{\sqrt{d_k}}\right) V_h^{(i)}

The loss is the mean squared error over the forecast window, with per-variable errors averaged over the MM series.

L=Ex1M∑i=1M∥x^L+1:L+T(i)−xL+1:L+T(i)∥22\mathcal{L} = \mathbb{E}_x \frac{1}{M} \sum_{i=1}^{M} \bigl\| \hat{x}^{(i)}_{L+1:L+T} - x^{(i)}_{L+1:L+T} \bigr\|_2^2

The paper's default encoder has 3 layers, 16 heads, D=128D = 128, and a feed-forward width of 256 (with GELU activation), with a dropout rate of 0.2. For the small datasets ILI, ETTh1, and ETTh2, it is shrunk to 4 heads, D=16D = 16, and width 128.

Self-supervised pretraining

PatchTST can also pretrain the encoder on unlabeled series. Like MAE and BERT, it has the model reconstruct masked parts.

  1. Cut non-overlapping patches: This ensures the visible patches do not contain values of the masked patches.
  2. Set some patches to 0: In the paper, 40% of the patches are chosen at random and set to 0 (42 patches with an input length of 512 and a patch length of 12).
  3. Reconstruct with the same encoder: A D×PD \times P linear layer replaces the forecasting head, and the model reconstructs the values of the masked patches with MSE.

After pretraining, the model is used for forecasting either by linear probing, which trains only the forecasting head, or by training the head for 10 epochs and then fine-tuning the whole model for 20 epochs.

Why it works

The paper explains that the two ideas work for different reasons.

Patching: putting local shapes into tokens and enabling long windows

  • Each token carries meaning: A single time step's value cannot tell whether the series "is on the way up or at a peak." A 16-step patch puts the local slope and shape inside the token, making it easier for attention to compare tokens with each other.
  • Less computation: The cost of attention grows with the square of the number of tokens NN. Patching makes N≈L/SN \approx L/S, so computation and memory drop to roughly 1/S21/S^2. On the Traffic data, training time fell to 1/22 (Table 1 of the paper).
  • Long lookback windows can be read: The freed compute can be used to lengthen the lookback window. Whereas many Transformer-based models did not become more accurate with longer lookback windows, PatchTST's MSE kept falling as the window grew (Figure 2 of the paper).

Channel independence: a different attention per variable, and less overfitting

Appendix A.7 of the paper gives three reasons why the design that does not mix variables is advantageous.

  • Each variable can be viewed differently: Each series has its own attention weights, so variables that behave differently are not forced to share the same view.
  • It can learn from less data: Models that mix variables must learn along the variable axis and the time axis at once, so they need more data. In experiments that shrink the training data, the channel-independent model gained accuracy faster.
  • It overfits less: Models that mix variables began to see their test error rise after a few epochs, while the channel-independent model's error kept falling.

As an analogy, channel independence is like "one analyst who has learned a single way of reading goes through the records of power, temperature, and humidity one at a time, separately." The reading method (weights) is shared, so the number of learned parameters does not grow, yet each record can be read according to its own circumstances.

Experimental results

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

PatchTST/64 uses a lookback window of L=512L = 512 (64 patches), and PatchTST/42 uses L=336L = 336 (42 patches). DLinear uses L=336L = 336, and the other Transformer-based models use the best value with LL varied from 24 to 720. Eight datasets were used for evaluation: ETT (ETTh1, ETTh2, ETTm1, ETTm2), Weather, Traffic, Electricity, and ILI.

DataTTPatchTST/64PatchTST/42DLinearFEDformerAutoformerInformer
Weather960.1490.1520.1760.2380.2490.354
Weather7200.3140.3200.3230.3890.4150.916
Traffic960.3600.3670.4100.5760.5970.733
Traffic7200.4320.4340.4660.6210.6390.827
Electricity960.1290.1300.1400.1860.1960.304
ETTh1960.3700.3750.3750.3760.4350.941
ETTh17200.4470.4490.4720.4690.5151.144
ETTm27200.3620.3670.3970.4100.4143.001

Compared with the best Transformer-based models, PatchTST/64 lowered MSE by 21.0% overall and PatchTST/42 by 20.2%. It also beat DLinear, especially on the large datasets Weather, Traffic, and Electricity, and on ILI. On the other hand, for some horizons of ETTh1 and ETTm1, DLinear was equal or slightly better.

Effect of patching and channel independence (Weather and Traffic, PatchTST/42 settings; MSE; Table 7 of the paper)

DataTTBoth (PatchTST)Channel independence onlyPatching onlyNeither
Weather960.1520.1640.1680.177
Weather7200.3200.3270.3510.340
Traffic960.3670.3970.595Out of memory

"Neither" is the original time series Transformer (TST), which uses point-wise tokens and mixes variables. On Traffic, without patching, it could not run even with a batch size of 1 on a 48GB GPU.

Self-supervised pretraining (Traffic, MSE; Table 4 of the paper)

TTPretraining + fine-tuningPretraining + linear probingSupervised only
960.3520.3990.367
7200.4250.4600.434

On the large datasets Weather, Traffic, and Electricity, pretraining followed by fine-tuning did better than supervised training from scratch. A model pretrained on Electricity and transferred to Weather and Traffic also did better than the other Transformer-based models (Table 5 of the paper).

Practical considerations

Keep the following points in mind when using PatchTST.

  • It does not use relationships between variables: Because of channel independence, cross-variable relationships such as "power demand rises when temperature rises" cannot be learned inside the encoder. The paper itself lists handling relationships between variables properly as future work. For data where such relationships matter, also compare iTransformer, Crossformer, and TSMixer (Google).
  • The forecasting head tends to be large: The final linear layer maps D⋅ND \cdot N inputs to TT outputs, so its parameter count is proportional to D⋅N⋅TD \cdot N \cdot T. With D=128D = 128, N=42N = 42, and T=720T = 720, the head alone has about 3.9 million parameters.
  • The forecast horizon is built into the model: The head outputs TT values directly, so changing TT requires retraining the head.
  • Use a small model for small datasets: On ILI, ETTh1, and ETTh2, the paper shrinks the model down to D=16D = 16 to curb overfitting.
  • Tune the patch length together with the lookback window: In the paper's additional experiments, fixing the lookback window at 336 and varying the patch length PP from 2 to 40 did not change MSE much, and the paper considers 8 to 16 to be generally good values. The length of the lookback window LL affects accuracy more than the patch length (Figure 2 of the paper).

When the number of variables MM is large, the number of series in a batch grows to B×MB \times M. On Traffic (862 variables), even a batch size of 32 means passing more than 20,000 series through the encoder at once, which uses a lot of GPU memory. For data with many variables, reduce the batch size.

Comparison with other models

The following table compares models commonly used for long-term forecasting from the same viewpoints. LL is the lookback length.

ModelOne tokenRelationships between variablesHow it outputs the forecast windowCost with respect to input length LL
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)
DLinear(No tokens; linear layers)Not used (independent per variable)All at once (linear layer)O(L)O(L)
PatchTSTA patch of one variable (PP time steps)Not used (independent per variable)All at once (flatten + linear layer)O((L/S)2)O((L/S)^2)
CrossformerA segment of one variableAttention along the variable axisAll at once (hierarchical decoder)O(M(L/Lseg)2)O(M (L/L_{\mathrm{seg}})^2)
iTransformerThe whole lookback window of one variableAttention along the variable axisAll at once (linear layer)Square of the number of variables MM
TSMixer (Google)(No tokens; MLPs)Mixed by MLPs along the variable axisAll at once (linear projection)O(L)O(L)

Rough guidelines for choosing:

  • Reading long lookback windows with a Transformer: PatchTST is the basic choice. Patching keeps computation down, and accuracy tends to improve as the window grows.
  • Building a strong baseline quickly: DLinear is easy to use. PatchTST outperformed it on the large benchmarks.
  • Relationships between variables matter for the forecast: iTransformer and Crossformer, which apply attention along the variable axis, are candidates.
  • Plenty of unlabeled series, and pretraining should be exploited: PatchTST's masked pretraining can be used. To use models pretrained on large amounts of data, TimesFM and Chronos are also candidates.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of PatchTST (supervised) (follows Section 3.1, Figure 1, and Appendices A.1.4-A.1.5 of arXiv:2211.14730)
Input x: [batch B, lookback L, variables M] -> output: [B, forecast T, M]
"""


class EncoderLayer(nn.Module):
  """A standard Transformer encoder layer. Normalization is batch normalization (footnote 1 of the paper)"""

  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.BatchNorm1d(d_model)          # Normalize per feature dimension across batch and patches
    self.norm2 = nn.BatchNorm1d(d_model)
    self.drop = nn.Dropout(dropout)

  def bn(self, norm, x):                          # x: [B*M, N, D] -> BatchNorm1d expects [*, D, N]
    return norm(x.transpose(1, 2)).transpose(1, 2)

  def forward(self, x):
    a, _ = self.attn(x, x, x, need_weights=False)
    x = self.bn(self.norm1, x + self.drop(a))     # Residual connection -> normalization
    x = self.bn(self.norm2, x + self.drop(self.ff(x)))
    return x


class PatchTST(nn.Module):
  def __init__(self, seq_len=336, pred_len=96, patch_len=16, stride=8,
               d_model=128, n_heads=16, d_ff=256, n_layers=3, dropout=0.2):
    super().__init__()
    self.patch_len, self.stride = patch_len, stride
    n_patches = (seq_len - patch_len) // stride + 2          # Append S values to the end before cutting
    self.pad = nn.ReplicationPad1d((0, stride))              # Pad by repeating the last value
    self.proj = nn.Linear(patch_len, d_model)                # W_p: patch -> D dims
    self.pos = nn.Parameter(torch.randn(1, n_patches, d_model) * 0.02)  # Learned position embedding W_pos
    self.drop = nn.Dropout(dropout)
    self.layers = nn.ModuleList([EncoderLayer(d_model, n_heads, d_ff, dropout) for _ in range(n_layers)])
    self.head = nn.Linear(d_model * n_patches, pred_len)     # Flatten + linear head (shared by all variables)

  def forward(self, x):                                      # x: [B, L, M]
    B, L, M = x.shape
    # Instance normalization: normalize each series by its mean and std, restore at the end
    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
    # Channel independence: move variables into the batch axis and process each with the same weights
    x = x.permute(0, 2, 1)                                   # [B, M, L]
    x = self.pad(x)                                          # [B, M, L + S]
    x = x.unfold(-1, self.patch_len, self.stride)            # Cut into patches [B, M, N, P]
    N = x.shape[2]
    x = x.reshape(B * M, N, self.patch_len)                  # [B*M, N, P]
    z = self.drop(self.proj(x) + self.pos)                   # [B*M, N, D]
    for layer in self.layers:
      z = layer(z)
    y = self.head(z.flatten(start_dim=1))                    # [B*M, T]
    y = y.reshape(B, M, -1).permute(0, 2, 1)                 # [B, T, M]
    return y * std + mean                                    # Denormalize


# Usage (7 variables as in ETTm1; forecast 96 steps ahead from the past 336 steps)
model = PatchTST(seq_len=336, pred_len=96)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
criterion = nn.MSELoss()                                     # The paper's loss is MSE

x = torch.randn(32, 336, 7)                                  # Lookback window
y = torch.randn(32, 96, 7)                                   # Ground truth for the forecast window

model.train()                                                # Training: dropout is active, batch norm uses batch statistics
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
optimizer.step()

model.eval()                                                 # Inference: dropout off, uses statistics accumulated during training
with torch.no_grad():
  pred = model(x)                                            # [32, 96, 7]

FAQ

Q. How were the patch length of 16 and stride of 8 chosen?
A.

They are the paper's default settings. In the experiments of Appendix A.4.1, fixing the lookback window at 336 and varying the patch length PP from 2 to 40 made little difference in MSE, and the paper considers 8 to 16 to be generally good values. Cutting overlapping patches (S<PS < P) means that shapes at patch boundaries also fall entirely within one token or the other. Self-supervised pretraining uses non-overlapping patches (P=S=12P = S = 12) so that the values of masked patches do not leak.

Q. If each variable is handled separately, why is it called multivariate forecasting?
A.

Because the input and output are tables of MM variables, and the forecast windows of all variables are predicted at once. However, no information is mixed between variables inside the encoder. The weights are shared across all variables, so the model can be used even when the number of variables differs between training and prediction. To handle cross-variable relationships, consider iTransformer or Crossformer.

Q. Can the ideas of PatchTST be used in other models?
A.

Yes. In Appendix A.7.2 of the paper, adding channel independence to Informer, Autoformer, and FEDformer improved accuracy in many settings. The idea of cutting series into patches to make tokens has also been adopted by IBM's TSMixer (IBM) and the pretrained TimesFM.

References

  1. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.
  2. yuqinie98/PatchTST (official implementation, PyTorch)
  3. Zeng, A., Chen, M., Zhang, L., & Xu, Q. (2023). Are Transformers Effective for Time Series Forecasting? AAAI 2023.
  4. Dosovitskiy, A., Beyer, L., Kolesnikov, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021.
  5. Kim, T., Kim, J., Tae, Y., Park, C., Choi, J.-H., & Choo, J. (2022). Reversible Instance Normalization for Accurate Time-Series Forecasting against Distribution Shift. ICLR 2022 (official implementation).