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/transformersAutoformerAutoformer: 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.pyAutoformerConfig配置类modeling_autoformer.pyAutoformerModel、AutoformerForPrediction等模型类__init__.py模块惰性加载入口。官方提供了可直接加载的检查点huggingface/autoformer-tourism-monthly以月度旅游数据为例训练并配套了数据集批次文件hf-internal-testing/tourism-monthly-batch官方文档的代码示例均基于这两者展开。二、核心机制一序列分解Series DecompositionAutoformer 将移动平均分解从数据预处理步骤升级为网络内部的基础模块。在源码中这一模块对应AutoformerSeriesDecompositionLayermodeling_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_sizeself.kernel_size, stride1, padding0) 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], dim1) 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。渐进式分解如何发生在AutoformerEncoderLayermodeling_autoformer.py中编码器每一层都包含两个分解模块decomp1、decomp2分别作用于自相关注意力 残差之后与前馈网络 残差之后把每次残差叠加产生的趋势成分剥离出去解码器层AutoformerDecoderLayermodeling_autoformer.py则进一步在自注意力、交叉注意力与前馈网络三段各放置一个分解模块decomp1/decomp2/decomp3并将三处剥离出的趋势残差相加后经trend_projection一个 kernel_size3、circular padding 的 Conv1d投影回特征空间逐层累积出完整的趋势分量。此外模型还配套实现了一个专为季节性分量设计的AutoformerLayernormmodeling_autoformer.py先做标准nn.LayerNorm再减去沿时间维的均值即AutoformerLayernorm(x) nn.LayerNorm(x) - torch.mean(nn.LayerNorm(x))避免季节性分量携带整体偏移。三、核心机制二自相关注意力Auto-Correlation自相关机制替代了传统的点乘自注意力其实现集中在AutoformerAttentionmodeling_autoformer.py包含两个阶段阶段一基于周期的依赖发现period-based dependencies discovery通过快速傅里叶变换FFT计算序列的自相关# 源码语义已简化 query_states_fft torch.fft.rfft(query_states, ntgt_len, dim1) key_states_fft torch.fft.rfft(key_states, ntgt_len, dim1) attn_weights query_states_fft * torch.conj(key_states_fft) attn_weights torch.fft.irfft(attn_weights, ntgt_len, dim1) # 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 Cachepast_key_values参数以加速自回归解码。四、AutoformerConfig完整参数手册AutoformerConfigconfiguration_autoformer.py继承自PreTrainedConfigmodel_type为autoformer。它兼容通用 Transformer 命名的属性映射hidden_size→d_model、num_attention_heads→encoder_attention_heads、num_hidden_layers→encoder_layers。4.1 任务与时序相关参数参数默认值说明prediction_length必填None解码器预测长度即模型的预测时域horizoncontext_length跟随prediction_length编码器上下文长度未设置时默认等于prediction_lengthdistribution_outputstudent_t分布输出头可选student_t、normal、negative_binomiallossnll损失函数与distribution_output对应目前仅支持参数化分布的负对数似然nllinput_size1目标变量维度单变量为 1多变量预测时大于 1lags_sequence[1,2,3,4,5,6,7]输入序列的滞后阶数常由数据频率决定scalingTrue是否对输入目标做缩放True/mean用均值缩放std用标准差缩放False不缩放num_time_features0输入中的时间特征数量如月份、日期等num_dynamic_real_features0动态实值特征数量num_static_categorical_features0静态类别特征数量num_static_real_features0静态实值特征数量cardinalityNone每个静态类别特征的取值基数列表长度须等于num_static_categorical_features后者大于 0 时该参数不能为Nonenum_parallel_samples100推理时每个时间步并行采样的样本数label_length10解码器 start token 长度用于直接多步预测非自回归生成4.2 Transformer 架构参数参数默认值说明d_model64模型隐藏维度encoder_attention_heads/decoder_attention_heads2/2编码器/解码器注意力头数encoder_layers/decoder_layers2/2编码器/解码器层数encoder_ffn_dim/decoder_ffn_dim32/32前馈网络中间维度activation_functiongelu激活函数dropout0.1全连接层 dropoutencoder_layerdrop/decoder_layerdrop0.1/0.1层丢弃LayerDrop概率attention_dropout0.1注意力 dropoutactivation_dropout0.1激活 dropoutinit_std0.02初始化标准差use_cacheTrue是否返回 KV Cacheis_encoder_decoderTrue编码器-解码器架构标记4.3 Autoformer 特有参数参数默认值说明moving_average25移动平均窗口大小实为序列分解层中AvgPool1d的卷积核尺寸autocorrelation_factor3自相关机制因子用于筛选 top-k 个自相关时延论文建议取值在 15 之间4.4 派生属性与校验逻辑配置类在__post_init__中完成几项关键计算context_length为空时回退为prediction_lengthlags_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 与 AutoformerForPrediction5.1 AutoformerModel编码器-解码器主干AutoformerModelmodeling_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带分布头的预测模型AutoformerForPredictionmodeling_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_idhf-internal-testing/tourism-monthly-batch, filenametrain-batch.pt, repo_typedataset ... ) batch torch.load(file) model AutoformerForPrediction.from_pretrained(huggingface/autoformer-tourism-monthly) # 训练阶段同时提供过去与未来值以及可选的附加特征 outputs model( ... past_valuesbatch[past_values], ... past_time_featuresbatch[past_time_features], ... past_observed_maskbatch[past_observed_mask], ... static_categorical_featuresbatch[static_categorical_features], ... future_valuesbatch[future_values], ... future_time_featuresbatch[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_valuesbatch[past_values], ... past_time_featuresbatch[past_time_features], ... past_observed_maskbatch[past_observed_mask], ... static_categorical_featuresbatch[static_categorical_features], ... future_time_featuresbatch[future_time_features], ... ) mean_prediction outputs.sequences.mean(dim1)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_idhf-internal-testing/tourism-monthly-batch, filenametrain-batch.pt, repo_typedataset ... ) 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_featuresnum_static_real_features, ... ) # feature_size 不会被重算需手动同步 configuration.feature_size num_static_real_features model AutoformerForPrediction(configuration) outputs model( ... past_valuesbatch[past_values], ... past_time_featuresbatch[past_time_features], ... past_observed_maskbatch[past_observed_mask], ... static_categorical_featuresbatch[static_categorical_features], ... static_real_featuresbatch[static_real_features], ... future_valuesbatch[future_values], ... future_time_featuresbatch[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)典型例子是时间序列 IDstatic_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_model16、prediction_length7、context_length14、label_length10、lags_sequence[1,2,3,4,5]、scalingstd等微型配置构造输入test_modeling_autoformer.py并覆盖编码器/解码器独立保存与加载check_encoder_decoder_model_standalone编码器输出形状为context_length解码器序列长度为prediction_length label_lengthAutoformerModel与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处于论文建议的 15 区间。【免费下载链接】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),仅供参考