Skip to content

基础层函数索引:DLinear、Informer、PatchTST

Abstract

这篇先不完整精读每个函数。

它只回答一个问题:DLinear、Informer、PatchTST 这些模型里,哪些 PyTorch 基础层函数和张量操作值得单独写注解文档。

0. 文件索引

项目内容
本文类型基础层函数索引
覆盖模型DLinear / Informer / PatchTST
主要源码目录ts_benchmark/baselines/time_series_library/
已有详细注解../model-order/01-DLinear/01-Autoformer_EncDec-moving_avg-forward-基础语法注解.md
当前目标先分析“有哪些层函数”,再决定后续逐个下钻顺序

本文对应的主源码:

模型/层文件
DLinearts_benchmark/baselines/time_series_library/models/DLinear.py
DLinear 分解层ts_benchmark/baselines/time_series_library/layers/Autoformer_EncDec.py
Informerts_benchmark/baselines/time_series_library/models/Informer.py
Informer / PatchTST 共享 Encoderts_benchmark/baselines/time_series_library/layers/Transformer_EncDec.py
Informer / PatchTST 注意力ts_benchmark/baselines/time_series_library/layers/SelfAttention_Family.py
Informer / PatchTST embeddingts_benchmark/baselines/time_series_library/layers/Embed.py
PatchTSTts_benchmark/baselines/time_series_library/models/PatchTST.py

0.1 本文知识点索引

这些函数分成两类。

第一类是真正的 nn.* 层函数:

类别函数
池化nn.AvgPool1d / nn.MaxPool1d
卷积nn.Conv1d
线性层nn.Linear
归一化nn.LayerNorm / nn.BatchNorm1d
正则化nn.Dropout
paddingnn.ReplicationPad1d
embeddingnn.Embedding / 自定义 PositionalEmbedding / TokenEmbedding
输出头nn.Flatten
容器与参数nn.ModuleList / nn.Parameter

第二类是模型层里必须配套理解的 tensor 操作:

类别函数
换维permute / transpose
改形状reshape / view / flatten
加删维度unsqueeze / squeeze
复制与拼接repeat / torch.cat
patch 切割unfold
注意力计算torch.einsum / torch.matmul / torch.softmax
稀疏选择topk / torch.randint / torch.arange
归一化统计mean / var / sqrt / detach / masked_fill

1. 分析边界

本文先只分析这三个模型的主线:

text
DLinear
Informer
PatchTST

对应源码优先看 time_series_library 版本。

其他 baseline 里也有重复或变体,例如:

text
dtaf/layer/Autoformer_EncDec.py
duet/layers/Autoformer_EncDec.py
timekan/layers/Autoformer_EncDec.py

这些后续可以复用本文的基础函数索引,但不在本文逐个展开。


2. 总览:三类模型各自引入了哪些基础层

2.1 DLinear:分解 + 线性预测

DLinear 的基础层函数最少,适合作为入门顺序的第一站。

函数/层源码位置在 DLinear 里的作用是否建议单独写详细文档
nn.AvgPool1dAutoformer_EncDec.py -> moving_avg.__init__滑动平均,提取 trend必须
permute(0, 2, 1)moving_avg.forward / DLinear.encoder(B,T,C)(B,C,T) 之间切换必须
repeatmoving_avg.forward复制边界时间步做 padding已写一部分
torch.catmoving_avg.forward拼接左 padding、原序列、右 padding已写一部分
nn.LinearDLinear.__init__seq_len 投影到 pred_len必须
nn.ModuleListDLinear.__init__individual=True 时给每个变量单独建 Linear建议
nn.ParameterDLinear.__init__手动初始化 Linear 权重建议
torch.zerosDLinear.encoderindividual=True 时预分配输出可选
F.gelu / nn.Dropoutclassification 分支分类任务输出头可选

DLinear 里最重要的基础层函数是:

text
AvgPool1d
Linear
permute

其中你提到的 03 文档里的 5.2 AvgPool1d,应该单独拆成一篇:

text
Autoformer_EncDec.moving_avg.forward - AvgPool1d 基础层注解

它要接在已经写好的 front / end / torch.cat 注解之后。

2.2 Informer:Embedding + ProbAttention + Encoder/Decoder

Informer 比 DLinear 多出三组东西:

text
Embedding
Attention
Transformer Encoder/Decoder
函数/层源码位置在 Informer 里的作用是否建议单独写详细文档
DataEmbeddingInformer.__init__ / Embed.py数值 embedding + 时间 embedding + 位置 embedding必须
nn.Conv1dTokenEmbedding把原始变量投影到 d_model必须
nn.EmbeddingTemporalEmbedding月/日/星期/小时等离散时间特征 embedding建议
nn.LinearTimeFeatureEmbedding / AttentionLayer / projection时间特征投影、Q/K/V 投影、输出投影必须
PositionalEmbeddingEmbed.py正余弦位置编码必须
nn.LayerNormInformer.__init__ / EncoderLayer / DecoderLayer对最后一维 d_model 归一化必须
nn.Dropoutembedding / attention / FFN训练时随机置零,减轻过拟合建议
ProbAttentionSelfAttention_Family.pyInformer 的稀疏注意力核心必须
torch.matmulProbAttention._prob_QK计算采样 Query-Key 分数必须
topkProbAttention._prob_QK选出稀疏度最高的 Query必须
torch.softmax_update_context把注意力分数转成权重必须
ConvLayerTransformer_EncDec.pydistilling,下采样 encoder 序列建议
nn.Conv1dConvLayer.downConvencoder distill 前的局部卷积建议
nn.BatchNorm1dConvLayer.norm(B,C,L) 归一化建议
nn.ELUConvLayer.activation卷积后的激活可选
nn.MaxPool1dConvLayer.maxPool把序列长度约减半建议
nn.Conv1d(kernel_size=1)EncoderLayer / DecoderLayerTransformer FFN,等价 position-wise MLP必须

Informer 的学习难点不是某个单独层,而是这些层的组合:

text
(B, L, d_model)
  -> Linear Q/K/V
  -> view 成多头
  -> ProbAttention
  -> Linear 输出投影
  -> Conv1d(k=1) FFN

所以 Informer 的基础层函数文档应该优先写:

text
Linear 的最后一维规则
AttentionLayer 里的 view / 多头拆分
ProbAttention 的 matmul / topk / softmax
Conv1d 与 MaxPool1d 的 (B,C,L) 规则

2.3 PatchTST:PatchEmbedding + FullAttention + FlattenHead

PatchTST 的核心是 patch 化。

它比 Informer 更需要理解 ReplicationPad1dunfold

函数/层源码位置在 PatchTST 里的作用是否建议单独写详细文档
nn.ReplicationPad1dPatchEmbedding.__init__在右端复制最后时间步,保证最后 patch 可取必须
unfoldPatchEmbedding.forward沿时间轴滑窗切 patch必须
torch.reshapePatchEmbedding.forward / PatchTST.forecast合并或还原 B*C必须
nn.Linear(patch_len, d_model)PatchEmbedding.value_embedding把 patch 向量投影成 token embedding必须
PositionalEmbeddingPatchEmbedding.position_embedding给 patch token 加位置编码建议
nn.DropoutPatchEmbedding / headembedding 后和 head 后正则化建议
FullAttentionPatchTST.encoderpatch token 之间做标准自注意力必须
torch.einsumFullAttention.forward计算注意力分数和加权 value必须
torch.softmaxFullAttention.forward注意力权重归一化必须
nn.Conv1d(kernel_size=1)EncoderLayerFFN,两层 position-wise 变换必须
nn.LayerNormEncoderLayer / EncoderTransformer 残差后的归一化必须
nn.FlattenFlattenHeadd_model x patch_num 展平成预测头输入必须
nn.Linear(nf, pred_len)FlattenHead每个变量从 token 表示映射到预测窗口必须
mean / var / sqrt / detachPatchTST.forecastNon-stationary 风格标准化建议
unsqueeze / repeatPatchTST.forecast反标准化时扩展均值和方差建议

PatchTST 的优先级最高的基础层函数是:

text
ReplicationPad1d
unfold
reshape(B*C,...)
Flatten
Linear
FullAttention 的 einsum

3. 按函数反查:哪个模型用到了它

3.1 池化类

函数DLinearInformerPatchTST主要语义
nn.AvgPool1dyesnono滑动平均,提取趋势
nn.MaxPool1dnoyesnodistilling,下采样序列

AvgPool1d 是 DLinear / Autoformer 分解系的核心。

MaxPool1d 是 Informer encoder distilling 的核心。

3.2 卷积类

函数DLinearInformerPatchTST主要语义
nn.Conv1d(kernel_size=3)noyesnoTokenEmbedding / distill 局部卷积
nn.Conv1d(kernel_size=1)noyesyesTransformer FFN,等价每个位置上的 Linear

注意:

text
Conv1d 输入格式必须是 (B, C, L)

而时间序列主线经常是:

text
(B, L, C) 或 (B, T, C)

所以它经常和下面两个函数一起出现:

python
permute(0, 2, 1)
transpose(-1, 1)

3.3 线性层

函数DLinearInformerPatchTST主要语义
nn.Linear(seq_len, pred_len)yesnonoDLinear 的预测头
nn.Linear(d_model, d_model)noyesyesQ/K/V 投影与输出投影
nn.Linear(patch_len, d_model)nonoyesPatchEmbedding 的 patch token 投影
nn.Linear(nf, pred_len)nonoyesPatchTST FlattenHead
nn.Linear(d_model, c_out)noyesnoInformer decoder 输出投影

nn.Linear 的核心规则:

只作用在最后一维。

所以:

text
(B, L, d_model) -> Linear(d_model, d_model) -> (B, L, d_model)
(B*C, patch_num, patch_len) -> Linear(patch_len, d_model) -> (B*C, patch_num, d_model)

3.4 归一化和正则化

函数DLinearInformerPatchTST主要语义
nn.LayerNorm间接复用yesyes对最后一维归一化
nn.BatchNorm1dnoyesnoInformer ConvLayer 里对 (B,C,L) 归一化
nn.Dropout分类分支yesyes训练时随机置零

这里最容易混的是:

text
LayerNorm 通常看最后一维
BatchNorm1d 通常看 channel 维

所以二者的输入 shape 语义不一样。

3.5 Padding 和 patch 切割

函数DLinearInformerPatchTST主要语义
手写 repeat + catyesnonomoving_avg 两端复制 padding
nn.ReplicationPad1dnonoyesPatchTST 右端复制 padding
unfoldnonoyes滑窗切 patch

DLinear 和 PatchTST 都用了“复制边界值”的思想,但实现方式不同:

text
DLinear: 手写 x[:,0:1,:].repeat + torch.cat
PatchTST: nn.ReplicationPad1d((0, padding))

3.6 注意力相关

函数DLinearInformerPatchTST主要语义
view(B,L,H,-1)noyesyes拆多头
torch.matmulnoyes部分场景ProbAttention 采样分数
torch.einsumno可用yesFullAttention 点积和加权求和
torch.softmaxnoyesyes注意力权重归一化
topknoyesnoProbAttention 选择重要 Query
torch.randintnoyesnoProbAttention 随机采样 Key

Informer 和 PatchTST 都有 attention,但重点不同:

text
Informer: ProbAttention,重点是采样、topk、近似注意力
PatchTST: FullAttention,重点是标准 QK^T softmax V

4. 当前文档树与阅读顺序

现在采用两层结构:

text
聚合文档:按知识类别读,适合复习和建立地图
下钻文档:按具体源码点读,适合卡在某一行代码时查

4.1 推荐主阅读顺序

先读这两篇聚合文档:

顺序文档覆盖内容用途
A[[10-PyTorch常见层函数-池化卷积线性归一化Embedding]]AvgPool1d / MaxPool1d / Conv1d / Linear / LayerNorm / BatchNorm1d / Dropout / ReplicationPad1d / Embedding / Flatten按“层函数类别”建立总地图
B[[11-PyTorch-Tensor基础操作-切片变形拼接注意力]]切片 / repeat / cat / permute / transpose / reshape / view / unfold / matmul / einsum / softmax / topk / 标准化统计按“Tensor 操作类别”建立总地图
C[[12-SelfAttention_Family/00-SelfAttention_Family总览]]AttentionLayer / FullAttention / DSAttention / ProbAttention / ReformerLayer / TwoStageAttentionLayerSelfAttention_Family.py 的类结构精读 attention 组件

这两篇都遵循同一个结构:

text
基础解释 -> 最小例子 -> 在 DLinear / Informer / PatchTST 的源码位置

4.2 下钻文档顺序

下面这些是具体源码点的详细注解,作为下钻阅读。

顺序文档覆盖函数主要服务
00[[../model-order/01-DLinear/01-Autoformer_EncDec-moving_avg-forward-基础语法注解01-Autoformer_EncDec-moving_avg-forward-基础语法注解]]slice / repeat / torch.cat
01本文总索引建立基础函数地图
02[[../model-order/01-DLinear/02-AvgPool1d与permute-DLinear-moving_avg02-AvgPool1d与permute-DLinear-moving_avg]]nn.AvgPool1d / permute
03[[../model-order/01-DLinear/03-Linear最后一维规则-DLinear-Informer-PatchTST03-Linear最后一维规则-DLinear-Informer-PatchTST]]nn.Linear / nn.Parameter / nn.ModuleList
04[[../model-order/02-PatchTST/03-Conv1d与BCL格式-Informer-PatchTST03-Conv1d与BCL格式-Informer-PatchTST]]nn.Conv1d / permute / transpose
05[[../model-order/02-PatchTST/01-ReplicationPad1d与unfold-PatchTST-PatchEmbedding01-ReplicationPad1d与unfold-PatchTST-PatchEmbedding]]nn.ReplicationPad1d / unfold / reshape
06[[../model-order/02-PatchTST/04-LayerNorm-BatchNorm-Dropout-Transformer基础04-LayerNorm-BatchNorm-Dropout-Transformer基础]]LayerNorm / BatchNorm1d / Dropout
07[[../model-order/02-PatchTST/05-Attention基础操作-view-matmul-einsum-softmax-topk05-Attention基础操作-view-matmul-einsum-softmax-topk]]view / matmul / einsum / softmax / topk
08[[../model-order/03-Informer/01-Embedding与位置编码-Informer-PatchTST01-Embedding与位置编码-Informer-PatchTST]]Embedding / PositionalEmbedding / TokenEmbedding
09[[../model-order/02-PatchTST/02-Flatten与标准化统计-PatchTST输出头02-Flatten与标准化统计-PatchTST输出头]]Flatten / mean / var / sqrt / detach
10[[12-SelfAttention_Family/00-SelfAttention_Family总览]]AttentionLayer / FullAttention / ProbAttention / DSAttention / ReformerLayer / TwoStageAttentionLayerSelfAttention_Family.py 每个类的源码精读

5. 原始建议顺序

按“先能支撑 DLinear 03,再支撑 Informer / PatchTST”的顺序,建议这样写。

优先级文档主题覆盖函数为什么先写
P0AvgPool1d 基础层注解nn.AvgPool1d / permute直接补 DLinear 03 的 5.2
P0nn.Linear 的最后一维规则Linear / Parameter / ModuleListDLinear、Informer、PatchTST 都依赖
P0Conv1d(B,C,L) 规则Conv1d / permute / transposeInformer 和 PatchTST EncoderLayer 都依赖
P1ReplicationPad1d + unfoldReplicationPad1d / unfold / reshapePatchTST patch 化核心
P1LayerNorm / BatchNorm1dLayerNorm / BatchNorm1dTransformer 层里反复出现
P1Attention 基础操作view / matmul / einsum / softmaxInformer、PatchTST 注意力主线
P2Embedding 基础层Embedding / PositionalEmbedding / TemporalEmbeddingInformer 输入层
P2FlattenHeadFlatten / Linear / DropoutPatchTST 输出层
P2标准化统计操作mean / var / sqrt / detachInformer short_forecast、PatchTST forecast

6. 当前已覆盖与缺口

已覆盖

当前已经覆盖 P0、P1 和主要 P2 基础函数:

text
边界切片 / repeat / cat
AvgPool1d / permute
Linear
Conv1d
ReplicationPad1d / unfold
LayerNorm / BatchNorm1d / Dropout
Attention 里的 view / matmul / einsum / softmax / topk
Embedding / 位置编码
Flatten / 标准化统计

后续可选缺口

后续如果继续补,可以写更细的专题:

可选文档内容
10-ModuleList与Parameter专门解释 DLinear individual=True 分支
11-masked_fill与掩码解释 attention mask 和 imputation mask
12-register_buffer与模型状态专门解释位置编码为什么不是 parameter
13-contiguous与view解释 attention 输出里 contiguous() 的原因

7. 一句话结论

如果按学习收益排序,当前最值得单独写的基础层函数是:

text
AvgPool1d
Linear
Conv1d
ReplicationPad1d + unfold
LayerNorm
Attention 里的 matmul/einsum/softmax
Flatten
Embedding

这批文档已经按这个顺序补齐。后续遇到新的源码基础函数,继续按“源码坐标 -> 知识点索引 -> shape 流 -> toy 小算例 -> 常见错误”的模板追加即可。

*记录并在线阅读我的笔记*