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 L. 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), 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.
Embed: Embed the observations of the lookback window and the covariates (such as time stamps) separately, and add a positional encoding.
Build coarser-scale nodes (CSCM): Use temporal convolutions to build coarse nodes that summarize the sequence C steps at a time, then summarize those C 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.
Apply pyramidal attention (PAM): Each node attends only to a fixed set of others (explained below). N layers, each consisting of PAM and a feed-forward network (each with a residual connection and normalization), are stacked.
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 S be the number of levels, C the number of children, and A the number of neighbors seen on the same level. The i-th node ni(s) on level s attends to three kinds of nodes.
Neighbors on the same level: A nodes centered on itself (intra-scale connections)
Children: the C 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 C-ary tree, in which each node has C children. The attention itself is ordinary scaled dot-product attention, with weights computed only within the set of neighbors Ni.
Level s has L/Cs−1 nodes, so the total number of nodes over all levels is
L(1+C1+C21+⋯)<C−1CL
Each node attends to at most A+C+1 others, so if A and C are constants, the attention computation is proportional to L. The defaults in the official implementation are C=4 (three coarser scales) and A=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 C (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+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)
Excerpt from Table 1 of the Crossformer paper (with the lookback window searched as a hyperparameter)
Data
Forecast length
Pyraformer
Informer
Autoformer
FEDformer
ETTh1
168
0.781
0.931
0.493
0.412
ETTh1
720
0.993
1.215
0.539
0.521
Weather
24
0.301
0.335
0.363
0.357
Traffic
168
0.635
0.660
0.649
0.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) 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.
C and the number of levels constrain the lookback window length: Coarse-level nodes are built by grouping C at a time, so it is easier to use a lookback window length divisible by C 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). 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. L is the length of the lookback window.
Turns values into tokens and reads them with a language model
Autoregressive one token at a time
Probability distribution (sample paths)
O(L2) (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) 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 C steps each (equivalent to daily if C=24); the level above that summarizes C 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.