AI Logic

Architectures

Pyraformer

Updated:

Architecture of Pyraformer. Left: the overall flow, which embeds the lookback window, builds coarser-scale nodes with CSCM, stacks pyramidal attention layers, then gathers features and outputs the forecast window with a linear layer. Right: a four-level pyramid showing how one node attends only to its neighbors on the same level, its children, and its parent

Background and overview

Pyraformer is a forecasting model that arranges a time series into a "pyramid" summarizing it over many levels, from fine to coarse temporal resolution, and handles long sequences with little computation using "pyramidal attention", in which each node attends only to its neighbors on the same level, its children on the level below, and its parent on the level above. It was introduced by Shizhan Liu, Hang Yu, et al. and accepted at ICLR 2022. The official implementation is available on Ant Group's GitHub (ant-research).

Transformer attention connects every pair of time steps, so it can capture distant relations, but its computation grows with the square of the sequence length LL. Models such as Informer reduced computation by connecting fewer pairs. Pyraformer's distinguishing feature is that it uses a hierarchy of temporal resolutions to decide which pairs to keep.

In the official description, if the finest level holds hourly observations, the level above can be viewed as daily features, and the levels above that as weekly and monthly features. On a coarse level, simply connecting neighbors expresses distant relations such as "last month and this month", so long-range relations can be captured with far fewer connections than representing everything on the finest level alone.

Because each node connects to a fixed number of others, the computation is O(L)O(L), proportional to the sequence length (according to the descriptions in the DLinear, Crossformer, and PatchTST papers).

In this article, the past interval used as input for prediction is called the lookback window, and the interval to be predicted is called the forecast window. Pyraformer builds a pyramid from the lookback window and outputs the values of the forecast window all at once.

Architecture

The overall architecture is explained following the official implementation (ant-research/Pyraformer on GitHub) and the figure in its README. In the figure at the top of the article, the left side shows the overall flow and the right side shows how pyramidal attention connects nodes.

The forecasting flow is as follows.

  1. Embed: Embed the observations of the lookback window and the covariates (such as time stamps) separately, and add a positional encoding.
  2. Build coarser-scale nodes (CSCM): Use temporal convolutions to build coarse nodes that summarize the sequence CC steps at a time, then summarize those CC at a time, and so on. The original sequence and the nodes of all the levels built are concatenated into one sequence and passed to the attention that follows.
  3. Apply pyramidal attention (PAM): Each node attends only to a fixed set of others (explained below). NN layers, each consisting of PAM and a feed-forward network (each with a residual connection and normalization), are stacked.
  4. Output the forecast window: The values of the forecast window are produced by one of the two methods below.

How the pyramid is connected

Let SS be the number of levels, CC the number of children, and AA the number of neighbors seen on the same level. The ii-th node ni(s)n^{(s)}_i on level ss attends to three kinds of nodes.

  • Neighbors on the same level: AA nodes centered on itself (intra-scale connections)
  • Children: the CC nodes on the next finer level that it summarizes (inter-scale connections)
  • Parent: the single node on the next coarser level that summarizes it (inter-scale connections)

The connections between levels form a CC-ary tree, in which each node has CC children. The attention itself is ordinary scaled dot-product attention, with weights computed only within the set of neighbors Ni\mathbb{N}_i.

yi=∑l∈Niexp⁡(qikl⊤/dK)∑l′∈Niexp⁡(qikl′⊤/dK)vly_i = \sum_{l \in \mathbb{N}_i} \frac{\exp(q_i k_l^\top / \sqrt{d_K})}{\sum_{l' \in \mathbb{N}_i} \exp(q_i k_{l'}^\top / \sqrt{d_K})} v_l

Why it is O(L)O(L)

Level ss has L/Cs−1L / C^{s-1} nodes, so the total number of nodes over all levels is

L(1+1C+1C2+⋯ )<CC−1LL \left(1 + \frac{1}{C} + \frac{1}{C^2} + \cdots\right) < \frac{C}{C - 1} L

Each node attends to at most A+C+1A + C + 1 others, so if AA and CC are constants, the attention computation is proportional to LL. The defaults in the official implementation are C=4C = 4 (three coarser scales) and A=3A = 3.

Inside CSCM

In the default of the official implementation (Bottleneck_Construct), a fully connected layer first reduces the feature dimension, and then 1D convolutions with kernel size and stride both equal to CC (with batch normalization and ELU) are stacked, one per level. The output of each level is projected back to the original dimension with a fully connected layer, concatenated with the original sequence, and passed through layer normalization. The implementation also includes versions that summarize with max pooling or average pooling instead of convolutions.

Two forecasting methods

  • Method 1: gather features and apply a linear layer: Concatenate the features of the node for the last time step and of its ancestor nodes on each level, and output all values of the forecast window at once with a single fully connected layer. This is the default for long-term forecasting in the official implementation.
  • Method 2: attention decoder: A standard two-layer attention decoder in which each position of the forecast window attends to the encoder output (and preceding positions), followed by a fully connected layer that outputs the values.

Why it works

Pyraformer's design is explained to work for the following reasons (according to the official README and the papers that cite it).

  • Coarse levels bring distant relations close: Two time steps far apart on the fine level end up in the same or neighboring nodes a few levels up. So relations over long ranges, such as days, weeks, and months, can be traced while keeping the number of connections small.
  • Multi-resolution representation: Each level holds features covering a different time span, so short-period and long-period variations can be represented on different levels.
  • Constant number of connections: Each node attends to at most A+C+1A + C + 1 others, so the computation per node does not grow as the sequence gets longer.

As an analogy, the pyramid is "a company org chart". Employees (fine time steps) talk only with the people at neighboring desks and with their own section manager (parent). Section managers talk with neighboring section managers and with their department head, and department heads talk with each other. Information between employees in distant departments reaches them in few steps via section managers and department heads. Far fewer conversations are needed than in a meeting where everyone talks with everyone (ordinary attention).

Experimental results

The following are numbers from later papers that compared Pyraformer on the same long-term forecasting benchmarks (multivariate, MSE; lower is better).

Excerpt from Table 2 of the DLinear paper (lookback window 96. Pyraformer and DLinear were implemented and measured by the DLinear authors; the others are from the FEDformer paper)

DataForecast lengthPyraformerInformerAutoformerFEDformerDLinear
ETT (ETTh1)960.6640.8650.4490.3760.375
ETT (ETTh1)7200.9631.1810.5140.5060.472
ETT (ETTm2)960.4350.3650.2550.2030.167
ETT (ETTm2)7203.6253.3790.4330.4210.397
Electricity960.3860.2740.2010.1930.140
Traffic962.0850.7190.6130.5870.410

Excerpt from Table 1 of the Crossformer paper (with the lookback window searched as a hyperparameter)

DataForecast lengthPyraformerInformerAutoformerFEDformer
ETTh11680.7810.9310.4930.412
ETTh17200.9931.2150.5390.521
Weather240.3010.3350.3630.357
Traffic1680.6350.6600.6490.607
  • Often better than Informer: On ETTh1, its error is lower than Informer's in both tables.
  • Often behind decomposition-based and linear models: In the same tables, Autoformer, FEDformer, and the simple linear model DLinear do better in many settings. There are also settings, such as short-term forecasting on Weather in the Crossformer table, where Pyraformer is the best of the four models above.

In Table 2 of the TimesNet paper (average over four forecast lengths), Pyraformer's MSE on ETTh1 is 0.827, better than Informer (1.040) and worse than Autoformer (0.496).

Caveats in practice

Keep the following points in mind when using Pyraformer.

  • O(L)O(L) requires a dedicated kernel: To compute only the pyramid connections, the official implementation uses a dedicated kernel compiled with TVM (PAM-TVM). The version without it (PAM-Naive) computes attention for all pairs and then hides them with a mask, so memory is not reduced. The Crossformer paper excludes Pyraformer from its efficiency comparison because it requires TVM.
  • No speedup with short lookback windows: The official README also states that because the lookback windows in the experiments are short, PAM-TVM does not improve speed. The pyramid's advantage pays off when handling very long sequences.
  • CC and the number of levels constrain the lookback window length: Coarse-level nodes are built by grouping CC at a time, so it is easier to use a lookback window length divisible by CC raised to the number of levels (how leftover ends are handled depends on the implementation).
  • Not among the top in later benchmarks: As the tables above show, many settings have been reported where it falls behind Autoformer, FEDformer, and linear models. If accuracy matters, compare against these as well.
  • The official implementation is in PyTorch: It is available at ant-research/Pyraformer on GitHub. It is not built into PyTorch itself.

Implementing pyramidal attention with a mask leaves the computation at O(L2)O(L^2). The implementation example below also uses a mask and is meant for checking the connectivity. To truly reduce computation on long sequences, a dedicated implementation that gathers and computes only the neighbor nodes (such as the official PAM-TVM) is needed.

Comparison with other models

Lining up representative time series forecasting models along the same axes gives the following. LL is the length of the lookback window.

ModelHow it captures timeHow it outputs the forecast windowOutputComputation with respect to input length LL
DeepARUpdates the state one step at a time with an LSTMAutoregressive one step at a time (feeds samples back as the next input)Probability distribution (sample paths)Proportional to length (computed in time order)
N-BEATSReads the whole lookback window with fully connected layers and outputs basis weightsAll at oncePoint forecastProportional to length (input width of the fully connected layers)
InformerProbSparse self-attention and distillingAll at once (generative decoder)Point forecastO(Llog⁡L)O(L \log L)
AutoformerSeries decomposition and auto-correlation (aggregating by period 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 temporal resolutions)All at oncePoint forecastO(L)O(L)
TSMixer (Google)MLPs along the time and variable dimensionsAll at once (linear projection)Point forecastProportional to 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) (ordinary attention)

Like Informer, Pyraformer reduces the number of attention pairs, and it uses a hierarchy of temporal resolutions to do so. Autoformer and FEDformer instead rely on series decomposition and periodic and frequency properties rather than reducing attention pairs.

Rough guidelines for choosing a model:

  • To handle very long sequences in O(L)O(L) using a dedicated kernel: Pyraformer is suitable.
  • To handle multiple temporal resolutions such as days, weeks, and months explicitly inside the model: Pyraformer's pyramid is suitable.
  • For series with clear periodicity where accuracy matters: Autoformer and FEDformer are suitable.
  • To build a strong baseline quickly: Also try simple models such as DLinear and TSMixer (Google).

PyTorch example

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

"""
A small implementation of Pyraformer's components (following get_mask and Bottleneck_Construct in Layers.py of the official implementation ant-research/Pyraformer)
A masked version (PAM-Naive) for checking the connectivity. The computation remains O(L^2)
"""


def pyramid_mask(L, C=4, A=3, n_scales=3):
  """Return a matrix that is True where each node may attend (A neighbors on the same level, C children, 1 parent)"""
  sizes = [L]
  for _ in range(n_scales):
    sizes.append(sizes[-1] // C)
  start = [sum(sizes[:s]) for s in range(len(sizes))]
  n = sum(sizes)
  allow = torch.zeros(n, n, dtype=torch.bool)
  half = A // 2
  for s, size in enumerate(sizes):                      # intra-scale: A nodes centered on itself
    for i in range(size):
      a, b = max(i - half, 0), min(i + half + 1, size)
      allow[start[s] + i, start[s] + a:start[s] + b] = True
  for s in range(1, len(sizes)):                        # inter-scale: parent and C children, both directions
    for i in range(sizes[s]):
      parent = start[s] + i
      children = slice(start[s - 1] + i * C, start[s - 1] + (i + 1) * C)
      allow[parent, children] = True
      allow[children, parent] = True
  return allow, sizes


class CSCM(nn.Module):
  """Build coarser-scale nodes (reduce dimension -> stack convolutions with kernel and stride C -> restore dimension and concatenate with the original sequence)"""

  def __init__(self, d_model=512, d_bottleneck=128, C=4, n_scales=3):
    super().__init__()
    self.down = nn.Linear(d_model, d_bottleneck)
    self.convs = nn.ModuleList([
      nn.Sequential(nn.Conv1d(d_bottleneck, d_bottleneck, kernel_size=C, stride=C),
                    nn.BatchNorm1d(d_bottleneck), nn.ELU())
      for _ in range(n_scales)
    ])
    self.up = nn.Linear(d_bottleneck, d_model)
    self.norm = nn.LayerNorm(d_model)

  def forward(self, x):                                 # x: [B, L, d]
    h = self.down(x).transpose(1, 2)
    coarse = []
    for conv in self.convs:
      h = conv(h)                                       # length shrinks by 1/C each time
      coarse.append(h)
    coarse = self.up(torch.cat(coarse, dim=2).transpose(1, 2))
    return self.norm(torch.cat([x, coarse], dim=1))     # [B, number of nodes over all levels, d]


class PyramidalAttentionLayer(nn.Module):
  """Pyramidal attention + feed-forward (each with residual and normalization)"""

  def __init__(self, d_model=512, n_heads=4, d_ff=512, dropout=0.05):
    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, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)

  def forward(self, x, allow):
    # attn_mask of nn.MultiheadAttention means "do not attend where True", so pass the inverted allow matrix
    y, _ = self.attn(x, x, x, attn_mask=~allow)
    x = self.norm1(x + y)
    return self.norm2(x + self.ff(x))


L, d, C = 96, 512, 4                                    # lookback window 96 -> nodes per level 96, 24, 6, 1
allow, sizes = pyramid_mask(L, C=C, A=3, n_scales=3)
print(sizes, allow.sum(dim=1).max().item())             # [96, 24, 6, 1]; each node attends to at most A + C + 1 = 8 nodes

embed = torch.randn(32, L, d)                            # embedded lookback window (observations + covariates + position)
cscm = CSCM(d, C=C)
layers = nn.ModuleList([PyramidalAttentionLayer(d) for _ in range(4)])
head = nn.Linear(len(sizes) * d, 720 * 7)                # method 1: concatenate features of the last time step and its ancestors, output forecast window 720 × 7 variables at once

cscm.train(); layers.train()                             # training: dropout and batch norm behave in training mode
h = cscm(embed)
for layer in layers:
  h = layer(h, allow)
start = [sum(sizes[:s]) for s in range(len(sizes))]
ancestors = [start[s] + (L - 1) // (C ** s) for s in range(len(sizes))]   # node of the last time step, its parent, grandparent, ...
pred = head(h[:, ancestors].reshape(32, -1)).view(32, 720, 7)

FAQ

Q. What is a "scale"?
A.

A level of temporal resolution. The bottom level is the original series (for example, hourly values); the level above consists of nodes summarizing CC steps each (equivalent to daily if C=24C = 24); the level above that summarizes CC daily nodes each, and so on, getting coarser. Pyraformer computes attention on the pyramid formed by stacking these levels.

Q. How does it differ from Informer's ProbSparse?
A.

Both reduce the number of attention pairs, but in different ways. Informer's ProbSparse selects "queries that seem important" from the data and handles the unselected queries with the mean of the values. Pyraformer determines the pairs by structure: each node attends only to a fixed set of nodes, namely its neighbors on the same level, its children, and its parent. Distant time steps are connected via the coarse levels.

Q. Can it be used on ETT?
A.

Yes. The official implementation includes settings for long-term forecasting on ETT (ETTh1, ETTm1, and others). However, comparisons in later papers such as DLinear and Crossformer report many settings on ETT where Autoformer, FEDformer, and linear models do better.

References

  1. Liu, S., Yu, H., Liao, C., Li, J., Lin, W., Liu, A. X., & Dustdar, S. (2022). Pyraformer: Low-complexity Pyramidal Attention for Long-range Time Series Modeling and Forecasting. ICLR 2022.
  2. ant-research/Pyraformer (official implementation and README, PyTorch)
  3. Zeng, A., Chen, M., Zhang, L., & Xu, Q. (2023). Are Transformers Effective for Time Series Forecasting? AAAI 2023.
  4. Zhang, Y., & Yan, J. (2023). Crossformer: Transformer Utilizing Cross-Dimension Dependency for Multivariate Time Series Forecasting. ICLR 2023.
  5. Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2023). A Time Series is Worth 64 Words: Long-term Forecasting with Transformers. ICLR 2023.
  6. Wu, H., Hu, T., Liu, Y., Zhou, H., Wang, J., & Long, M. (2023). TimesNet: Temporal 2D-Variation Modeling for General Time Series Analysis. ICLR 2023.