Overview
Informer is a Transformer-based model specifically designed for long-term time series forecasting (LSTF). While standard Transformer models excel in sequence modeling, their quadratic computational complexity with respect to input length makes them inefficient for very long time series. Informer addresses this bottleneck by introducing several innovations to significantly improve efficiency and reduce memory usage, making it suitable for applications like electricity consumption planning and traffic trend forecasting.
Architecture & Components
Informer's architecture is built upon the encoder-decoder structure of the Transformer but incorporates three distinctive characteristics to handle long sequences efficiently:
- ProbSparse Self-Attention Mechanism: This is Informer's primary innovation for efficiency. Instead of computing attention scores for every query-key pair (which leads to quadratic complexity), ProbSparse attention intelligently selects only a subset of "active" queries that are most likely to contribute significantly to the attention mechanism. This reduces the computational overhead from $O(L^2)$ to $O(L \log L)$ in both time complexity and memory usage, where $L$ is the sequence length.
- Self-Attention Distillation: This technique further enhances efficiency and memory management. It progressively halves the sequence length at each cascading layer by applying a convolutional downsampling operation. This process distills the most salient temporal information while discarding redundant parts, allowing the model to handle extremely long input sequences effectively.
- Generative Style Decoder: Unlike traditional decoders that predict one step at a time in an autoregressive manner (which is slow for long sequences), Informer's decoder predicts the entire long time-series sequence in a single forward operation. This drastically improves the inference speed for long-sequence predictions. The decoder takes the start token of the target sequence and the output of the encoder to generate the full forecast.
- Input Embeddings and Positional Encoding: Informer encodes time series data using input embeddings and positional encoding (often external time features like 'month of year', 'day of month') to capture temporal and sequential information, allowing the model to perceive the order of time and local/global temporal dependencies.
Conceptual diagram of Informer's architecture with ProbSparse Self-Attention and Self-Attention Distillation.
When to Use Informer
Informer is well-suited for:
- Long-sequence time series forecasting (LSTF) problems where computational efficiency is a major concern.
- Datasets with repeating patterns and large volumes of historical data.
- Real-time forecasting applications due to its single-pass generative decoder.
- As a baseline for Transformer-based time series models, especially when comparing efficiency.
Pros and Cons
Pros
- High Efficiency for Long Sequences: ProbSparse Self-Attention and Self-Attention Distillation significantly reduce computational complexity and memory usage to $O(L \log L)$.
- Fast Inference: The generative style decoder allows for predicting the entire long sequence in one forward pass, drastically improving speed.
- Captures Long-Range Dependencies: Despite sparsity, it aims to maintain the Transformer's ability to model long-term relationships.
- Parallelizable: Like other Transformers, it benefits from parallel computation during training.
Cons
- Sensitive to Noise: Informer variants have shown higher error rates and instability, particularly under noisy conditions and at longer forecast horizons. ProbSparse attention may struggle to capture precise long-term dependencies when signals are corrupted.
- Potential Information Loss: Self-attention distillation, while efficient, can lead to the loss or weakening of long-term dependencies in temporal sequences.
- Less Consistent Performance: May perform less consistently than other Transformer variants (e.g., Autoformer, PatchTST) on structured low-noise or high-variance time series.
- Implicit Trend/Seasonality Handling: Does not explicitly decompose trend and seasonality like Autoformer, relying on the attention mechanism to implicitly learn these patterns.
Example Implementation
Informer is primarily implemented in PyTorch, often as part of larger time series Transformer libraries. Here's a conceptual example using the HuggingFace Transformers library, which provides a convenient API for Informer.
PyTorch Example (using HuggingFace Transformers)
import torch
import pandas as pd
import numpy as np
from transformers import InformerForPrediction
from huggingface_hub import hf_hub_download
import matplotlib.pyplot as plt
# 1. Load a sample dataset (conceptual - replace with your own data)
# For demonstration, we'll simulate a batch structure similar to HuggingFace datasets
# In a real scenario, you'd load your time series data and preprocess it
# to create 'past_values', 'past_time_features', etc.
# Example: Create synthetic data
n_samples = 200
context_length = 96 # Length of input sequence for encoder
prediction_length = 24 # Length of sequence to predict
num_input_channels = 1 # Univariate time series
# Simulate past_values (e.g., a sine wave with noise and trend)
past_values_np = (np.sin(np.arange(context_length + prediction_length) / 10) * 10 +
np.arange(context_length + prediction_length) * 0.1 +
np.random.randn(context_length + prediction_length) * 2)
past_values_np = past_values_np.reshape(1, -1, num_input_channels) # (batch_size, seq_len, num_channels)
past_values = torch.tensor(past_values_np[:, :context_length, :], dtype=torch.float32)
# Simulate future_values (for training/evaluation, not needed for inference)
future_values = torch.tensor(past_values_np[:, context_length:, :], dtype=torch.float32)
# Simulate past_time_features (e.g., simple linear time index)
past_time_features = torch.tensor(np.arange(context_length).reshape(1, -1, 1), dtype=torch.float32)
future_time_features = torch.tensor(np.arange(context_length, context_length + prediction_length).reshape(1, -1, 1), dtype=torch.float32)
# 2. Load a pre-trained Informer model (or initialize from scratch)
# For a real application, you might fine-tune on your data or train from scratch
# model = InformerForPrediction.from_pretrained("huggingface/informer-tourism-monthly") # Example pre-trained model
# Or initialize from config:
from transformers import InformerConfig
config = InformerConfig(
context_length=context_length,
prediction_length=prediction_length,
num_input_channels=num_input_channels,
lags_sequence=[1, 2, 3, 4, 5, 6, 7], # Default lags
num_encoder_layers=2,
num_decoder_layers=1,
d_model=128,
num_attention_heads=4,
activation_function="gelu",
dropout=0.1,
attention_dropout=0.0,
ffn_dim=512,
scaling="mean", # or "std", "none"
loss="mse", # or "nll" for probabilistic
num_time_features=1, # For the time feature we created
)
model = InformerForPrediction(config)
# 3. Perform a forward pass (inference example)
# For inference, you only need past_values and future_time_features
# (future_values and past_observed_mask are typically for training/evaluation)
model.eval() # Set model to evaluation mode
with torch.no_grad():
outputs = model(
past_values=past_values,
past_time_features=past_time_features,
future_time_features=future_time_features,
# If you have missing values in past_values, provide past_observed_mask
# past_observed_mask=torch.ones_like(past_values, dtype=torch.bool)
)
forecast = outputs.predictions.squeeze().numpy() # Remove batch and channel dimensions
# 4. Display the forecast (conceptual)
print("Informer PyTorch (HuggingFace) model inference complete.")
print(f"Forecast shape: {forecast.shape}")
print(f"First 5 forecasted values: {forecast[:5]}")
# Plotting (conceptual)
# plt.figure(figsize=(14, 7))
# plt.plot(np.arange(context_length), past_values.squeeze().numpy(), label='Past Values')
# plt.plot(np.arange(context_length, context_length + prediction_length), future_values.squeeze().numpy(), label='Actual Future Values', color='orange')
# plt.plot(np.arange(context_length, context_length + prediction_length), forecast, label='Informer Forecast', linestyle='--', color='green')
# plt.title('Informer Time Series Forecast (PyTorch)')
# plt.xlabel('Time Step')
# plt.ylabel('Value')
# plt.legend()
# plt.grid(True)
# plt.show()