Hugging Face Transformers 中的 Autoformer:自相关分解 Transformer 的长期时序预测实战指南
【免费下载链接】transformers🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers
Autoformer(Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting)是一种面向长期时序预测(Long-Term Series Forecasting, LTSF)的深度分解架构。本文以 Autoformer 官方文档(及对应的日语版文档)为核心骨架,结合本仓库中 Autoformer 的完整实现源码,系统讲解其两大核心机制(序列分解与自相关注意力)、全部配置参数、模型 API,以及基于AutoformerForPrediction的训练、推理与采样实战流程。读完本文,你将掌握如何在 🤗 Transformers 中加载、配置、微调并部署 Autoformer 完成长期时序预测任务。
一、模型概述:Autoformer 解决了什么问题
Autoformer 由 Haixu Wu、Jiehui Xu、Jianmin Wang 与 Mingsheng Long 在论文Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting中提出,由 elisim 与 kashif 贡献至 Hugging Face Transformers,并于 2023 年 5 月 30 日随本项目合入。
论文的核心论断可以从三个层面理解:
- 长期预测是现实刚需:极端天气早期预警、长期能源消费规划等场景都要求模型具备更长的预测时域,而传统基于 Transformer 的时序模型虽然通过多种自注意力机制寻找长程依赖,但长期未来的复杂时间模式会让模型难以找到可靠依赖。
- 自注意力的信息利用瓶颈:为了在长序列上保持效率,传统 Transformer 必须采用稀疏化的逐点(point-wise)自注意力,导致信息利用出现瓶颈。
- Autoformer 的两大创新:
- 序列分解(Series Decomposition):打破"序列分解只在预处理阶段做一次"的传统惯例,将其革新为深度模型的基础内部模块,赋予模型对复杂时间序列的渐进式分解能力——每一层都会把趋势(trend)与季节性(seasonal)成分逐步分离;
- 自相关机制(Auto-Correlation Mechanism):受随机过程理论启发,基于序列的周期性,在子序列层面进行依赖发现与表示聚合。自相关在效率与精度两方面都优于自注意力。
论文在覆盖能源、交通、经济、气象与疾病五类实际应用的六个基准上取得了当时的 SOTA 精度(相对提升约 38%)。需要说明的是,该数字为论文自述结果,本文仅作论文观点转述,不作为本仓库的实测结论。
在本仓库中,Autoformer 的实现位于 src/transformers/models/autoformer/ 目录,由三个文件构成:
configuration_autoformer.py:AutoformerConfig配置类;modeling_autoformer.py:AutoformerModel、AutoformerForPrediction等模型类;__init__.py:模块惰性加载入口。
官方提供了可直接加载的检查点huggingface/autoformer-tourism-monthly(以月度旅游数据为例训练),并配套了数据集批次文件hf-internal-testing/tourism-monthly-batch,官方文档的代码示例均基于这两者展开。
二、核心机制一:序列分解(Series Decomposition)
Autoformer 将"移动平均分解"从数据预处理步骤升级为网络内部的基础模块。在源码中,这一模块对应AutoformerSeriesDecompositionLayer(modeling_autoformer.py):
# 源码语义:x_trend = AvgPool(Padding(X)),x_seasonal = X - x_trend class AutoformerSeriesDecompositionLayer(nn.Module): def __init__(self, config): super().__init__() self.kernel_size = config.moving_average self.avg = nn.AvgPool1d(kernel_size=self.kernel_size, stride=1, padding=0) def forward(self, x): # 在时间序列两端做填充,再进行平均池化得到趋势项 num_of_pads = (self.kernel_size - 1) // 2 front = x[:, 0:1, :].repeat(1, num_of_pads, 1) end = x[:, -1:, :].repeat(1, num_of_pads, 1) x_padded = torch.cat([front, x, end], dim=1) x_trend = self.avg(x_padded.permute(0, 2, 1)).permute(0, 2, 1) x_seasonal = x - x_trend return x_seasonal, x_trend其数学语义为:x_trend = AvgPool(Padding(X)),x_seasonal = X - x_trend。其中平均池化的窗口大小kernel_size直接由配置项moving_average控制(默认 25)。
渐进式分解如何发生?在AutoformerEncoderLayer(modeling_autoformer.py)中,编码器每一层都包含两个分解模块decomp1、decomp2,分别作用于"自相关注意力 + 残差"之后与"前馈网络 + 残差"之后,把每次残差叠加产生的趋势成分剥离出去;解码器层AutoformerDecoderLayer(modeling_autoformer.py)则进一步在自注意力、交叉注意力与前馈网络三段各放置一个分解模块(decomp1/decomp2/decomp3),并将三处剥离出的趋势残差相加后,经trend_projection(一个 kernel_size=3、circular padding 的 Conv1d)投影回特征空间,逐层累积出完整的趋势分量。
此外,模型还配套实现了一个专为季节性分量设计的AutoformerLayernorm(modeling_autoformer.py):先做标准nn.LayerNorm,再减去沿时间维的均值,即AutoformerLayernorm(x) = nn.LayerNorm(x) - torch.mean(nn.LayerNorm(x)),避免季节性分量携带整体偏移。
三、核心机制二:自相关注意力(Auto-Correlation)
自相关机制替代了传统的点乘自注意力,其实现集中在AutoformerAttention(modeling_autoformer.py),包含两个阶段:
阶段一:基于周期的依赖发现(period-based dependencies discovery)
通过快速傅里叶变换(FFT)计算序列的自相关:
# 源码语义(已简化): query_states_fft = torch.fft.rfft(query_states, n=tgt_len, dim=1) key_states_fft = torch.fft.rfft(key_states, n=tgt_len, dim=1) attn_weights = query_states_fft * torch.conj(key_states_fft) attn_weights = torch.fft.irfft(attn_weights, n=tgt_len, dim=1) # Autocorrelation(Q,K)自相关通过 FFT 域相乘再反变换实现,复杂度为 O(L log L)(L 为序列长度),这正是论文所称"自相关在效率上优于自注意力"的根源——无需稀疏化即可处理长序列。
阶段二:时延聚合(time delay aggregation)
# 源码语义(已简化): top_k = int(self.autocorrelation_factor * math.log(time_length)) _, top_k_delays_index = torch.topk(autocorrelations_mean_on_bsz, top_k) # 对 value_states 按 top-k 时延做 roll 后加权求和 delays_agg += value_states_roll_delay * top_k_autocorrelations_at_delay代码先对自相关分数取 top-k 个显著时延(k 由autocorrelation_factor × ln(time_length)决定),对 top-k 分数做 softmax 归一化,再将value_states按各时延滚动(roll)后加权聚合。训练时滚动使用torch.roll,推理时则通过重复拼接与torch.gather实现等价的周期式索引,保证梯度与数值行为正确。
由于 Autoformer 是编码器-解码器结构,AutoformerAttention同时承担了解码器中的自注意力与交叉注意力两种角色(通过key_value_states是否为None判断),并完整支持 KV Cache(past_key_values参数)以加速自回归解码。
四、AutoformerConfig:完整参数手册
AutoformerConfig(configuration_autoformer.py)继承自PreTrainedConfig,model_type为"autoformer"。它兼容通用 Transformer 命名的属性映射(hidden_size→d_model、num_attention_heads→encoder_attention_heads、num_hidden_layers→encoder_layers)。
4.1 任务与时序相关参数
| 参数 | 默认值 | 说明 |
|---|---|---|
prediction_length | 必填(None) | 解码器预测长度,即模型的预测时域(horizon) |
context_length | 跟随prediction_length | 编码器上下文长度,未设置时默认等于prediction_length |
distribution_output | "student_t" | 分布输出头,可选"student_t"、"normal"、"negative_binomial" |
loss | "nll" | 损失函数,与distribution_output对应;目前仅支持参数化分布的负对数似然(nll) |
input_size | 1 | 目标变量维度,单变量为 1,多变量预测时大于 1 |
lags_sequence | [1,2,3,4,5,6,7] | 输入序列的滞后阶数,常由数据频率决定 |
scaling | True | 是否对输入目标做缩放;True/"mean"用均值缩放,"std"用标准差缩放,False不缩放 |
num_time_features | 0 | 输入中的时间特征数量(如月份、日期等) |
num_dynamic_real_features | 0 | 动态实值特征数量 |
num_static_categorical_features | 0 | 静态类别特征数量 |
num_static_real_features | 0 | 静态实值特征数量 |
cardinality | None | 每个静态类别特征的取值基数列表,长度须等于num_static_categorical_features;后者大于 0 时该参数不能为None |
num_parallel_samples | 100 | 推理时每个时间步并行采样的样本数 |
label_length | 10 | 解码器 start token 长度,用于直接多步预测(非自回归生成) |
4.2 Transformer 架构参数
| 参数 | 默认值 | 说明 |
|---|---|---|
d_model | 64 | 模型隐藏维度 |
encoder_attention_heads/decoder_attention_heads | 2/2 | 编码器/解码器注意力头数 |
encoder_layers/decoder_layers | 2/2 | 编码器/解码器层数 |
encoder_ffn_dim/decoder_ffn_dim | 32/32 | 前馈网络中间维度 |
activation_function | "gelu" | 激活函数 |
dropout | 0.1 | 全连接层 dropout |
encoder_layerdrop/decoder_layerdrop | 0.1/0.1 | 层丢弃(LayerDrop)概率 |
attention_dropout | 0.1 | 注意力 dropout |
activation_dropout | 0.1 | 激活 dropout |
init_std | 0.02 | 初始化标准差 |
use_cache | True | 是否返回 KV Cache |
is_encoder_decoder | True | 编码器-解码器架构标记 |
4.3 Autoformer 特有参数
| 参数 | 默认值 | 说明 |
|---|---|---|
moving_average | 25 | 移动平均窗口大小,实为序列分解层中AvgPool1d的卷积核尺寸 |
autocorrelation_factor | 3 | 自相关机制因子,用于筛选 top-k 个自相关时延;论文建议取值在 1~5 之间 |
4.4 派生属性与校验逻辑
配置类在__post_init__中完成几项关键计算:
context_length为空时回退为prediction_length;lags_sequence统一转换为list;- 未显式给出
cardinality/embedding_dimension且存在静态类别特征时,embedding_dimension自动取min(50, (cat + 1) // 2); - 自动推导
feature_size = input_size * len(lags_sequence) + _number_of_features,其中_number_of_features聚合了类别特征嵌入维度、动态实值特征、时间特征、静态实值特征以及缩放所需的log1p(abs(loc))与log(scale)两个维度(共input_size * 2)。feature_size决定了值嵌入层、季节性投影与趋势投影的输出维度,是整条前向链路的关键桥梁; validate_architecture负责校验cardinality、embedding_dimension与num_static_categorical_features的长度一致性。
# 官方文档示例:初始化配置并随机初始化模型 >>> from transformers import AutoformerConfig, AutoformerModel >>> # 初始化一个默认的 Autoformer 配置 >>> configuration = AutoformerConfig() >>> # 从配置随机初始化模型(随机权重) >>> model = AutoformerModel(configuration) >>> # 访问模型配置 >>> configuration = model.config五、AutoformerModel 与 AutoformerForPrediction
5.1 AutoformerModel:编码器-解码器主干
AutoformerModel(modeling_autoformer.py)是完整的时序 Transformer 主干,结构如下:
- 缩放器(Scaler):依据
config.scaling选择AutoformerMeanScaler(均值缩放)、AutoformerStdScaler(标准差缩放)或AutoformerNOPScaler(不缩放)。缩放器会在上下文窗口上计算loc与scale,训练时用于归一化输入、推理时用于把预测反归一化回原始量纲; - 特征嵌入器(FeatureEmbedder):当
num_static_categorical_features > 0时,用nn.Embedding将静态类别特征映射为稠密向量; - 编码器
AutoformerEncoder:值嵌入 + 正弦位置嵌入 + 若干AutoformerEncoderLayer,支持 LayerDrop 与梯度检查点; - 解码器
AutoformerDecoder:同样的值嵌入与位置嵌入(位置偏移为context_length - label_length),由AutoformerDecoderLayer堆叠,输出经seasonality_projection投影回feature_size维度; - 序列分解层:用于在解码器输入端从上下文序列中切分出季节性与趋势初始化输入。
前向流程的核心步骤在create_network_inputs与forward中体现:
- 依据
_past_length = context_length + max(lags_sequence)从past_values中截取上下文; - 通过
get_lagged_subsequences构建滞后子序列(形状为(batch, seq_len, input_size * num_lags)),并拼入时间特征、静态特征与log1p(abs(loc))、log(scale)缩放特征; - 编码器消费"滞后序列 + 特征"拼接后的输入,输出编码表示;
- 解码器输入由"上下文季节性分量后
label_length段 + 全零预测段"拼接"时间特征"得到,趋势初始值由"上下文趋势后label_length段 + 上下文均值重复"构成——即直接多步(非自回归)预测的初始化策略; - 输出
AutoformerModelOutput,除标准字段外还额外携带trend、loc、scale与static_features。
5.2 AutoformerForPrediction:带分布头的预测模型
AutoformerForPrediction(modeling_autoformer.py)在AutoformerModel之上叠加概率分布头:
- 根据
distribution_output选择StudentTOutput、NormalOutput或NegativeBinomialOutput(实现位于 time_series_utils.py),通过parameter_projection把解码器输出投影为分布参数; - 损失函数为负对数似然
nll = -log_prob(target),并用weighted_average按future_observed_mask对缺失值加权; - 训练阶段提供
future_values与future_time_features,前向返回Seq2SeqTSPredictionOutput(含loss、params、loc、scale等); - 推理阶段调用
generate:仅输入past_values、past_time_features、future_time_features(及可选静态特征),将样本按num_parallel_samples并行复制,复用编码器输出与 KV Cache 进行解码,最后从分布中采样num_parallel_samples条预测轨迹,返回SampleTSPredictionOutput,其sequences形状为(batch_size, num_parallel_samples, prediction_length)(多变量时追加input_size维)。
六、实战:训练与推理完整流程
6.1 训练:前向与反向传播
以下代码直接取自官方文档示例(见AutoformerForPrediction.forward的 docstring 与英文文档),用于从 Hub 下载数据批次与预训练权重并执行一次训练前向:
>>> from huggingface_hub import hf_hub_download >>> import torch >>> from transformers import AutoformerForPrediction >>> file = hf_hub_download( ... repo_id="hf-internal-testing/tourism-monthly-batch", filename="train-batch.pt", repo_type="dataset" ... ) >>> batch = torch.load(file) >>> model = AutoformerForPrediction.from_pretrained("huggingface/autoformer-tourism-monthly") >>> # 训练阶段:同时提供过去与未来值,以及可选的附加特征 >>> outputs = model( ... past_values=batch["past_values"], ... past_time_features=batch["past_time_features"], ... past_observed_mask=batch["past_observed_mask"], ... static_categorical_features=batch["static_categorical_features"], ... future_values=batch["future_values"], ... future_time_features=batch["future_time_features"], ... ) >>> loss = outputs.loss >>> loss.backward()注意past_values的序列长度应为context_length + max(lags_sequence)(默认lags_sequence最大滞后为 7,即比context_length多 7 步),缺失值需以 0 填充并用past_observed_mask标记。
6.2 推理:采样预测
>>> # 推理阶段:仅提供过去值,模型自回归生成未来值 >>> outputs = model.generate( ... past_values=batch["past_values"], ... past_time_features=batch["past_time_features"], ... past_observed_mask=batch["past_observed_mask"], ... static_categorical_features=batch["static_categorical_features"], ... future_time_features=batch["future_time_features"], ... ) >>> mean_prediction = outputs.sequences.mean(dim=1)outputs.sequences形状为(batch_size, num_parallel_samples, prediction_length),对采样维度求均值即可得到逐时间步的点预测,也可以直接对样本分布做分位数统计以输出预测区间。
6.3 进阶:启用静态实值特征
AutoformerForPrediction支持static_real_features。使用前需先根据数据集的静态实值特征数量改写配置,并手动同步feature_size(官方文档特别指出feature_size不会被自动重算):
>>> from huggingface_hub import hf_hub_download >>> import torch >>> from transformers import AutoformerConfig, AutoformerForPrediction >>> file = hf_hub_download( ... repo_id="hf-internal-testing/tourism-monthly-batch", filename="train-batch.pt", repo_type="dataset" ... ) >>> batch = torch.load(file) >>> # 查看静态实值特征数量 >>> num_static_real_features = batch["static_real_features"].shape[-1] >>> # 加载预训练配置并覆盖 num_static_real_features >>> configuration = AutoformerConfig.from_pretrained( ... "huggingface/autoformer-tourism-monthly", ... num_static_real_features=num_static_real_features, ... ) >>> # feature_size 不会被重算,需手动同步 >>> configuration.feature_size += num_static_real_features >>> model = AutoformerForPrediction(configuration) >>> outputs = model( ... past_values=batch["past_values"], ... past_time_features=batch["past_time_features"], ... past_observed_mask=batch["past_observed_mask"], ... static_categorical_features=batch["static_categorical_features"], ... static_real_features=batch["static_real_features"], ... future_values=batch["future_values"], ... future_time_features=batch["future_time_features"], ... )七、输入输出约定与测试验证
7.1 输入张量约定
past_values:(batch_size, sequence_length)或(batch_size, sequence_length, input_size),作为编码器上下文,可含滞后扩展;缺失值以 0 填充;past_time_features:(batch_size, sequence_length, num_features),时间特征充当"位置编码"角色——与 BERT 等模型在内部学习位置编码不同,时序 Transformer 需要外部提供时间特征(月份、日期、年龄特征、节假日等均可);Autoformer 只为static_categorical_features学习额外嵌入;past_observed_mask:布尔掩码,1 表示观测值,0 表示缺失值;static_categorical_features:(batch_size, num_static_categorical_features),典型例子是时间序列 ID;static_real_features:(batch_size, num_static_real_features),典型例子是促销信息;future_values:(batch_size, prediction_length),训练标签;future_time_features:(batch_size, prediction_length, num_features),预测窗口的时间特征,推理时必须提供。
7.2 测试与验证
仓库在 tests/models/autoformer/test_modeling_autoformer.py 中提供了完整的模型测试套件。测试器AutoformerModelTester使用d_model=16、prediction_length=7、context_length=14、label_length=10、lags_sequence=[1,2,3,4,5]、scaling="std"等微型配置构造输入(test_modeling_autoformer.py),并覆盖:
- 编码器/解码器独立保存与加载(
check_encoder_decoder_model_standalone); - 编码器输出形状为
context_length,解码器序列长度为prediction_length + label_length; AutoformerModel与AutoformerForPrediction从huggingface/autoformer-tourism-monthly检查点加载并执行前向、生成与梯度回传(test_modeling_autoformer.py)。
若需在本地运行测试,可在仓库根目录执行:
pytest tests/models/autoformer/test_modeling_autoformer.py八、资源与延伸阅读
- 模型实现:src/transformers/models/autoformer/modeling_autoformer.py
- 配置实现:src/transformers/models/autoformer/configuration_autoformer.py
- 官方英文文档:docs/source/en/model_doc/autoformer.md
- 模型测试:tests/models/autoformer/test_modeling_autoformer.py
- 可加载检查点:
huggingface/autoformer-tourism-monthly;配套数据集批次:hf-internal-testing/tourism-monthly-batch
作为补充说明,Autoformer 的模块设计与时间序列 Transformer 家族的实现存在较多共享(本仓库中多个缩放器、嵌入器与注意力组件均标注为从time_series_transformer模型复制改造而来),读者对照阅读 time_series_transformer 的实现可以更快理解时序模型族的通用设计范式。在实际接入新数据集时,务必根据数据频率设定合理的lags_sequence、根据预测周期设定prediction_length与context_length,并保持autocorrelation_factor处于论文建议的 1~5 区间。
【免费下载链接】transformers🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考