学术
模块更新于 2026-11-21· 浏览 1· 下载 0

DPR 非平稳模式校准

局部卷积感知上下文,尺度化余弦软路由混合共享响应基,再以逐特征残差乘法校准隐藏状态。小幅初始化接近恒等映射,无需专家网络分发。

时间序列时间序列预测非平稳序列软路由特征调制预测模型

结构图

DPR 非平稳模式校准结构图
DPR 非平稳模式校准结构图

局部卷积感知上下文,尺度化余弦软路由混合共享响应基,再以逐特征残差乘法校准隐藏状态。小幅初始化接近恒等映射,无需专家网络分发。

论文信息

  • 论文:Perceive, Route, Modulate: Dynamic Pattern Recalibration for Time Series Forecasting

核心痛点

一条时间序列里,平稳、周期与突发波动可能交替出现。共享骨干之外,还需要显式调节局部特征增益的路径。

模块亮点

  • 局部卷积感知上下文,尺度化余弦软路由混合共享响应基,再以逐特征残差乘法校准隐藏状态。小幅初始化接近恒等映射,无需专家网络分发。

适用场景

多种预测骨干的末端隐藏表征,尤其关注局部波动变化。稳定序列收益可能较小,其他任务需单独验证。

插入位置建议

  • 优先放预测头前,检查三维输入的Token语义与隐藏维,通道独立骨干需逐变量重排恢复。分块表征可选逐点感知,训练循环外部加入响应基正交惩罚,在线场景另外检查信息可见性。

适用任务

  • 多种预测骨干的末端隐藏表征
  • 尤其关注局部波动变化。稳定序列收益可能较小
  • 其他任务需单独验证

完整代码

dpr.py
"""DPR:动态模式重校准(Dynamic Pattern Recalibration)即插即用算子。
论文:Perceive, Route, Modulate: Dynamic Pattern Recalibration for Time Series Forecasting。

真实时间序列的局部动态与波动持续漂移,而主流预测骨干对所有时间步共享同一套变换,缺少逐 token 的特征增益调节。DPR 以“感知—路由—调制”三步实现:并行深度一维卷积(k=3/7)提取多尺度局部上下文;小型 MLP 与 K 个可学习路由原型做尺度化余弦 softmax,得到连续路由分布;再由该分布凸组合 K×d 响应基,以 h⊙(1+γm) 的残差 Hadamard 形式重校准隐藏状态。本模块即该算子,可直接插在任意骨干的预测头之前,参数量极小、随序列长度线性。
"""

from __future__ import annotations

import sys
from typing import Sequence

import torch
import torch.nn as nn
import torch.nn.functional as F


class DPR(nn.Module):
    """Dynamic Pattern Recalibration: Perceive -> Route -> Modulate.

    Args:
        d: hidden feature dim of each temporal token.
        basis_size: K, number of learned response patterns (routing prototypes).
        logit_scale: initial routing temperature tau (learnable).
        gamma_init: initial residual scaling factor gamma (learnable).
        kernel_sizes: depthwise conv kernels used for multi-scale perception.
        context_mode: "depthwise" (multi-scale, Eq. 2) or "pointwise" for
            patch-level tokens that already aggregate a local window.
    """

    def __init__(
        self,
        d: int,
        basis_size: int = 8,
        logit_scale: float = 2.0,
        gamma_init: float = 0.1,
        kernel_sizes: Sequence[int] = (3, 7),
        context_mode: str = "depthwise",
    ) -> None:
        super().__init__()
        if context_mode not in ("depthwise", "pointwise"):
            raise ValueError("context_mode must be 'depthwise' or 'pointwise'")
        self.d = d
        self.K = basis_size

        # Perceive: parallel depthwise 1D convs, same padding, no channel mixing.
        if context_mode == "depthwise":
            self.convs = nn.ModuleList(
                nn.Conv1d(d, d, k, padding="same", groups=d) for k in kernel_sizes
            )
            ctx_dim = d * len(kernel_sizes)  # dctx = 2d in the paper
        else:
            self.convs = nn.ModuleList([nn.Conv1d(d, d, 1, groups=d)])
            ctx_dim = d

        # Route: context query -> soft assignment over K learnable prototypes.
        self.dc = max(16, d // 4)  # routing dim d_c
        self.proj = nn.Linear(ctx_dim, self.dc)
        self.prototypes = nn.Parameter(torch.empty(basis_size, self.dc))  # E: K x dc
        self.logit_scale = nn.Parameter(torch.tensor(float(logit_scale)))  # tau

        # Modulate: shared response basis + learnable residual gain.
        self.basis = nn.Parameter(torch.empty(basis_size, d))  # M: K x d
        self.gamma = nn.Parameter(torch.tensor(float(gamma_init)))  # scalar gamma

        with torch.no_grad():
            self.prototypes.normal_(std=0.02)
            self.basis.normal_(std=0.02)

    def forward(self, h: torch.Tensor) -> torch.Tensor:
        """Recalibrate token-level hidden states.

        Args:
            h: (B, L, d) hidden states at the L temporal positions.
        Returns:
            (B, L, d) recalibrated hidden states, same dtype/device as input.
        """
        B, L, d = h.shape
        # Perceive: (B, L, d) -> (B, d, L) -> concat -> (B, dctx, L) -> (B, L, dctx)
        hcf = h.transpose(1, 2)
        z = torch.cat([conv(hcf) for conv in self.convs], dim=1).transpose(1, 2)
        # Route: temperature-scaled cosine softmax over L2-normalized keys (Eq. 3).
        c = F.gelu(self.proj(z))  # (B, L, dc)
        c_hat = F.normalize(c, dim=-1)
        e_hat = F.normalize(self.prototypes, dim=-1)  # (K, dc)
        pi = torch.softmax(self.logit_scale * (c_hat @ e_hat.t()), dim=-1)  # (B, L, K)
        # Modulate: convex basis mixture + residual Hadamard gain (Eq. 4).
        # The orthogonal regularizer is a training-only loss term, so it is not here.
        m = pi @ self.basis  # (B, L, d)
        return h * (1.0 + self.gamma * m)


if __name__ == "__main__":
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    torch.manual_seed(0)
    x = torch.randn(2, 12, 64)  # (B, L, d)
    for mode in ("depthwise", "pointwise"):
        dpr = DPR(d=64, basis_size=8, context_mode=mode).eval()
        with torch.no_grad():
            y = dpr(x)
            y_short = dpr(torch.randn(5, 3, 64))  # short sequence / larger batch
        n_params = sum(p.numel() for p in dpr.parameters())
        print(
            f"[{mode}] in={tuple(x.shape)} out={tuple(y.shape)} "
            f"short_in=(5, 3, 64) short_out={tuple(y_short.shape)} params={n_params}"
        )

环境与依赖

Python 3.9+

继续浏览

下一篇DPW 固定基底适配对预训练的 V 投影做 SVD,得到一组固定的降维基底,只训练后续升维和可选缩放,把可训练参数压得很低;适配结果再与调用侧的前缀响应融合。

相关资源