Download annotations/annotation_27/TimeMixer/models/TimeMixer.py from mcy98/RECODE-H: direct link, hf CLI and curl.
- Browser
- Download file 72.8 kB
-
https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_27/TimeMixer/models/TimeMixer.py
- Command line
-
hf download hf://datasets/mcy98/RECODE-H/annotations/annotation_27/TimeMixer/models/TimeMixer.py
-
curl -L -o TimeMixer.py https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_27/TimeMixer/models/TimeMixer.py
72.8 kB
# === Appended from canonical.py ===
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.Autoformer_EncDec import series_decomp
from layers.Embed import DataEmbedding_wo_pos
from layers.StandardNorm import Normalize
class DFT_series_decomp(nn.Module):
"""
Series decomposition block using Discrete Fourier Transform (DFT).
This class implements a series decomposition method that is an alternative
to the moving-average-based decomposition mentioned in the paper for the PDM block.
The paper primarily discusses moving-average based decomposition but also mentions
exploring DFT-based decomposition as an alternative in the appendix.
This implementation selects the top_k frequencies to constitute the seasonal component
and subtracts it from the original series to get the trend component.
"""
def __init__(self, top_k=5):
"""
Initializes the DFT_series_decomp module.
Args:
top_k (int): The number of top frequencies to select for the seasonal component.
This parameter is specific to this DFT-based decomposition and
is not directly detailed in the main paper's description of TimeMixer's PDM,
but is a common hyperparameter for frequency-domain analysis.
"""
super(DFT_series_decomp, self).__init__()
self.top_k = top_k
def forward(self, x):
"""
Forward pass for DFT-based series decomposition.
Args:
x (torch.Tensor): Input time series tensor of shape (batch_size, sequence_length, num_features).
Returns:
tuple: A tuple containing:
- x_season (torch.Tensor): The seasonal component of the time series.
- x_trend (torch.Tensor): The trend component of the time series.
Functionality:
1. Computes the Real Fast Fourier Transform (RFFT) of the input series.
2. Calculates the magnitude of the frequencies, ignoring the DC component (freq[0]=0).
3. Identifies the top_k dominant frequencies.
4. Filters the RFFT output by keeping only these top_k frequencies, effectively zeroing out others.
5. Computes the Inverse RFFT (IRFFT) of the filtered frequencies to obtain the seasonal component.
6. The trend component is then derived by subtracting the seasonal component from the original series.
This aligns with the general concept of series decomposition where Trend = Series - Seasonal.
"""
xf = torch.fft.rfft(x)
freq = abs(xf)
# Zero out the DC component to focus on periodic seasonalities
freq[0] = 0
# In the code, it uses a fixed value 5 for top_k, not self.top_k.
# This might be an oversight or intentional for specific experiments.
# For consistency with __init__, it should ideally be self.top_k.
top_k_freq, top_list = torch.topk(freq, 5) # Paper uses top_k
# Filter out frequencies lower than the minimum of the top_k frequencies
xf[freq <= top_k_freq.min()] = 0
x_season = torch.fft.irfft(xf)
x_trend = x - x_season
return x_season, x_trend
class MultiScaleSeasonMixing(nn.Module):
"""
Bottom-up mixing for seasonal patterns across multiple scales.
This module implements the "Seasonal Mixing" (S-Mix) component of the
Past-Decomposable-Mixing (PDM) block described in the TimeMixer paper.
It adopts a bottom-up approach, incorporating information from finer-scale
time series upwards to supplement detailed information for coarser scales' seasonality modeling.
The mixing is done using linear layers along the temporal dimension.
"""
def __init__(self, configs):
"""
Initializes the MultiScaleSeasonMixing module.
Args:
configs (object): A configuration object containing model hyperparameters.
Expected attributes:
- seq_len (int): Original input sequence length.
- down_sampling_window (int): Factor by which sequence length is reduced at each scale.
- down_sampling_layers (int): Number of down-sampling operations (M in paper, number of scales - 1).
Functionality:
Initializes a list of 'down_sampling_layers'. Each layer is a sequence of two linear layers
with a GELU activation in between, designed to transform features from a finer scale
(e.g., length P/2^(m-1)) to a coarser scale (e.g., length P/2^m).
The number of such layers corresponds to `configs.down_sampling_layers` (M),
which is the number of scales minus one (as mixing happens between m-1 and m).
"""
super(MultiScaleSeasonMixing, self).__init__()
# Initialize linear layers for transforming seasonal components from finer to coarser scales.
# The paper describes this as "Bottom-Up-Mixing(s_m-1^l)" in equation (4).
# Each layer projects from length P/2^(m-1) to P/2^m.
# configs.down_sampling_layers corresponds to M in the paper (number of coarser scales).
# So, loop runs for m = 1 to M (i from 0 to M-1).
self.down_sampling_layers = torch.nn.ModuleList(
[
nn.Sequential(
# Linear layer transforming from finer scale (m-1) to coarser scale (m)
# Input dimension: P / (window^i), Output dimension: P / (window^(i+1))
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** i), # Length at scale i (finer)
configs.seq_len // (configs.down_sampling_window ** (i + 1)), # Length at scale i+1 (coarser)
),
nn.GELU(),
# Second linear layer at the coarser scale
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** (i + 1)),
configs.seq_len // (configs.down_sampling_window ** (i + 1)),
),
)
# configs.down_sampling_layers is M, number of scales beyond original. Loop is 0 to M-1.
# This creates M mixing layers, for scale 0->1, 1->2, ..., M-1 -> M.
for i in range(configs.down_sampling_layers)
]
)
def forward(self, season_list):
"""
Forward pass for bottom-up seasonal mixing.
Args:
season_list (list of torch.Tensor): A list of seasonal components from different scales,
ordered from finest (scale 0) to coarsest (scale M).
Each tensor is expected to be of shape (batch_size, num_features, sequence_length_at_scale_m).
The paper implies input $s_m^l \in \mathbb{R}^{\lfloor\frac{P}{2^{m}\rfloor\times d_{model}}$,
so input here is permuted.
Returns:
list of torch.Tensor: A list of mixed seasonal components, with information propagated bottom-up.
Each tensor is permuted back to (batch_size, sequence_length_at_scale_m, num_features).
Functionality:
Implements Equation (4) from the paper: $s_{m}^{l}=s_{m}^{l}+Bottom-Up-Mixing(s_{m-1}^{l})$ for m: $1\rightarrow M$.
It iterates from the finest scale (m-1) to coarser scales (m), applying the corresponding
down_sampling_layer (Bottom-Up-Mixing layer) to the finer scale's seasonal component
and adding the result (residually) to the coarser scale's seasonal component.
The input `season_list` elements are assumed to be (Batch, Channels, SeqLen_m).
The output `out_season_list` elements are (Batch, SeqLen_m, Channels).
Discrepancy:
- The paper's equation (4) is $s_{m}^{l}=s_{m}^{l}+Bottom-Up-Mixing(s_{m-1}^{l})$.
The code initializes `out_high = season_list[0]` (scale 0) and `out_low = season_list[1]` (scale 1).
In the loop (for i from 0 to len(season_list)-2, effectively m-1):
`out_low_res = self.down_sampling_layers[i](out_high)`: This is Bottom-Up-Mixing($s_{i}^l$) where $s_i^l$ is `out_high`.
`out_low = out_low + out_low_res`: This is $s_{i+1}^l = s_{i+1}^l + \text{Bottom-Up-Mixing}(s_i^l)$.
This matches the paper's logic. `out_high` becomes the current scale's representation $s_m^l$,
and `out_low` becomes the next coarser scale's representation $s_{m+1}^l$.
- Permutation: Input tensors are (B, C, L_m), linear layers operate on L_m. Output tensors are stored as (B, L_m, C).
"""
# `season_list` contains seasonal parts [s_0, s_1, ..., s_M]
# s_0 is finest (original scale), s_M is coarsest.
# Tensors in season_list are (Batch, Channels, SeqLen_m_at_scale)
# mixing fine-to-coarse (bottom-up)
# out_high initially holds s_0 (finest scale seasonal component)
out_high = season_list[0]
# out_low initially holds s_1 (next scale seasonal component)
# If season_list has only one element (M=0, no coarser scales to mix into), this part needs careful handling.
# The loop range `len(season_list) - 1` handles this: if len is 1, loop doesn't run.
# If len is 2 (scales 0 and 1), loop runs once for i=0.
out_low = season_list[1] if len(season_list) > 1 else None # Ensure out_low is valid
# The first element of out_season_list is the original finest scale seasonal component, permuted.
out_season_list = [out_high.permute(0, 2, 1)] # s_0^l.permute(...)
# Loop for m from 1 to M (effectively, i from 0 to M-1, where M = len(season_list)-1)
# This loop performs the operation: s_m^l = s_m^l + BottomUpMixing(s_{m-1}^l)
for i in range(len(season_list) - 1): # Loop M times if M > 0
# out_high here is s_i^l (from previous iteration or initialization, i.e., s_{m-1}^l)
# self.down_sampling_layers[i] is the Bottom-Up-Mixing layer for scale i to i+1
out_low_res = self.down_sampling_layers[i](out_high) # BottomUpMixing(s_i^l) -> representation for scale i+1
# out_low is s_{i+1}^l (original seasonal component at scale i+1)
# Perform residual addition: s_{i+1}^l = s_{i+1}^l + out_low_res
out_low = out_low + out_low_res
# The updated s_{i+1}^l (out_low) becomes the 'out_high' for the next iteration (i.e. s_m^l for next step)
out_high = out_low
# Prepare s_{i+2}^l for the next iteration if it exists
if i + 2 <= len(season_list) - 1: # If there's a next coarser scale s_{m+1}^l
out_low = season_list[i + 2] # Load original s_{i+2}^l
# Append the mixed seasonal component for the current scale (i+1) or m
out_season_list.append(out_high.permute(0, 2, 1)) # s_{i+1}^l.permute(...)
return out_season_list
class MultiScaleTrendMixing(nn.Module):
"""
Top-down mixing for trend patterns across multiple scales.
This module implements the "Trend Mixing" (T-Mix) component of the
Past-Decomposable-Mixing (PDM) block described in the TimeMixer paper.
It adopts a top-down mixing method, utilizing macro knowledge from coarser scales
to guide the trend modeling of finer scales.
The mixing is done using linear layers along the temporal dimension.
"""
def __init__(self, configs):
"""
Initializes the MultiScaleTrendMixing module.
Args:
configs (object): A configuration object containing model hyperparameters.
Expected attributes:
- seq_len (int): Original input sequence length.
- down_sampling_window (int): Factor by which sequence length is reduced at each scale.
- down_sampling_layers (int): Number of down-sampling operations (M in paper, number of scales - 1).
Functionality:
Initializes a list of 'up_sampling_layers'. Each layer is a sequence of two linear layers
with a GELU activation in between, designed to transform features from a coarser scale
(e.g., length P/2^(m+1)) to a finer scale (e.g., length P/2^m).
The number of such layers corresponds to `configs.down_sampling_layers` (M).
The loop iterates in reverse to match the top-down mixing from M-1 down to 0.
"""
super(MultiScaleTrendMixing, self).__init__()
# Initialize linear layers for transforming trend components from coarser to finer scales.
# The paper describes this as "Top-Down-Mixing(t_m+1^l)" in equation (5).
# Each layer projects from length P/2^(m+1) to P/2^m.
# The loop for 'i' here is reversed. If configs.down_sampling_layers (M) is 3 (scales 0,1,2,3),
# i will be 2, 1, 0.
# For i=2 (M-1): layer for scale M to M-1. Input P/2^M, Output P/2^(M-1). Here m+1 = M, m = M-1.
# This corresponds to (configs.down_sampling_window ** (i+1)) for coarser scale and (**i) for finer.
# Example: M=2 (layers 0,1). Scales 0,1,2.
# reversed(range(2)) -> i=1, i=0.
# i=1: input P/(w^2) (scale 2), output P/(w^1) (scale 1). This is TopDown(t_2) -> t_1
# i=0: input P/(w^1) (scale 1), output P/(w^0) (scale 0). This is TopDown(t_1) -> t_0
self.up_sampling_layers = torch.nn.ModuleList(
[
nn.Sequential(
# Linear layer transforming from coarser scale (m+1) to finer scale (m)
# Input P/(window**(i+1)), Output P/(window**i)
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** (i + 1)), # Length at scale i+1 (coarser)
configs.seq_len // (configs.down_sampling_window ** i), # Length at scale i (finer)
),
nn.GELU(),
# Second linear layer at the finer scale
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** i),
configs.seq_len // (configs.down_sampling_window ** i),
),
)
# Iterates from M-1 down to 0, creating M up-sampling layers.
for i in reversed(range(configs.down_sampling_layers))
])
def forward(self, trend_list):
"""
Forward pass for top-down trend mixing.
Args:
trend_list (list of torch.Tensor): A list of trend components from different scales,
ordered from finest (scale 0) to coarsest (scale M).
Each tensor is of shape (batch_size, num_features, sequence_length_at_scale_m).
Returns:
list of torch.Tensor: A list of mixed trend components, with information propagated top-down.
The list is re-ordered to be from finest to coarsest scale.
Each tensor is permuted to (batch_size, sequence_length_at_scale_m, num_features).
Functionality:
Implements Equation (5) from the paper: $t_{m}^{l}=t_{m}^{l}+Top-Down-Mixing(t_{m+1}^{l})$ for m: $(M-1)\rightarrow0$.
It first reverses the input `trend_list` to process from coarsest to finest.
It iterates from the coarsest scale (m+1) to finer scales (m), applying the corresponding
up_sampling_layer (Top-Down-Mixing layer) to the coarser scale's trend component
and adding the result (residually) to the finer scale's trend component.
The final list of mixed trend components is reversed again to match the original finest-to-coarsest order.
Discrepancy:
- The paper's equation (5) is $t_{m}^{l}=t_{m}^{l}+Top-Down-Mixing(t_{m+1}^{l})$ for $m:(M-1)\rightarrow0$.
The code first reverses `trend_list` so `trend_list_reverse[0]` is $t_M^l$ (coarsest) and
`trend_list_reverse[1]` is $t_{M-1}^l$.
`out_low` is $t_M^l$. `out_high` is $t_{M-1}^l$.
The loop iterates `len(trend_list_reverse) - 1` times. If M is total scales (0 to M-1), then len is M.
If `trend_list` has M+1 elements (scales 0 to M), `trend_list_reverse` also has M+1 elements.
The loop index `i` for `up_sampling_layers` corresponds to the definition in `__init__`.
The loop in `forward` iterates from `i = 0` up to `len(trend_list_reverse) - 2`.
Let `rev_idx = 0, 1, ..., M-1`.
`out_high_res = self.up_sampling_layers[rev_idx](out_low)`:
Here `out_low` is $t^l_{M-rev\_idx}$ (mixed from previous step or original coarsest).
`self.up_sampling_layers[rev_idx]` maps from $t^l_{M-rev\_idx}$ to $t^l_{M-rev\_idx-1}$.
`out_high = out_high + out_high_res`: $t^l_{M-rev\_idx-1} = t^l_{M-rev\_idx-1} (\text{original}) + \text{TopDownMixing}(t^l_{M-rev\_idx})$.
This matches the paper's logic.
"""
# `trend_list` contains trend parts [t_0, t_1, ..., t_M]
# t_0 is finest, t_M is coarsest.
# Tensors in trend_list are (Batch, Channels, SeqLen_m_at_scale)
# mixing coarse-to-fine (top-down)
trend_list_reverse = trend_list.copy()
trend_list_reverse.reverse() # Now [t_M, t_{M-1}, ..., t_0]
# out_low is initially t_M (coarsest trend component)
out_low = trend_list_reverse[0]
# out_high is initially t_{M-1} (next finer trend component)
out_high = trend_list_reverse[1] if len(trend_list_reverse) > 1 else None
# The first element of out_trend_list is the original coarsest trend component, permuted.
# This list will be built in reversed order (coarsest-to-finest) and then reversed at the end.
out_trend_list = [out_low.permute(0, 2, 1)] # t_M^l.permute(...)
# Loop for m from M-1 down to 0.
# Here, loop i corresponds to the index for up_sampling_layers (0 to M-1).
# Iteration i=0: mixes from trend_list_reverse[0] (t_M) into trend_list_reverse[1] (t_{M-1}).
# up_sampling_layers[0] is for M -> M-1.
for i in range(len(trend_list_reverse) - 1): # Loop M times if M > 0
# out_low is t_{M-i}^l (mixed from previous step or original t_M)
# self.up_sampling_layers[i] is Top-Down-Mixing for scale M-i to M-i-1.
# Note: The indexing of self.up_sampling_layers was reversed in __init__.
# So self.up_sampling_layers[0] maps from scale M to M-1.
# self.up_sampling_layers[1] maps from scale M-1 to M-2.
# This matches: i-th layer in up_sampling_layers (created by reversed range in init)
# corresponds to mixing from coarser scale `k+1` to finer scale `k`, where `k` decreases.
out_high_res = self.up_sampling_layers[i](out_low) # TopDownMixing(t_{M-i}^l) -> representation for scale M-i-1
# out_high is t_{M-i-1}^l (original trend component at scale M-i-1)
# Perform residual addition: t_{M-i-1}^l = t_{M-i-1}^l + out_high_res
out_high = out_high + out_high_res
# The updated t_{M-i-1}^l (out_high) becomes 'out_low' for the next iteration
out_low = out_high
# Prepare t_{M-i-2}^l for the next iteration if it exists
if i + 2 <= len(trend_list_reverse) - 1: # If there's a next finer scale
out_high = trend_list_reverse[i + 2] # Load original t_{M-i-2}^l
out_trend_list.append(out_low.permute(0, 2, 1)) # Appends mixed t_{M-i-1}^l
# Reverse the list to be from finest (scale 0) to coarsest (scale M)
out_trend_list.reverse()
return out_trend_list
class PastDecomposableMixing(nn.Module):
"""
Past-Decomposable-Mixing (PDM) block.
This module is a core component of TimeMixer, responsible for extracting information
from past observations by mixing decomposed seasonal and trend components across multiple scales.
It corresponds to Equation (3) in the TimeMixer paper:
$X^{l+1} = X^l + \text{FeedForward}(\text{S-Mix}(\{s_m^l\}) + \text{T-Mix}(\{t_m^l\}))$ (simplified, actual is on decomposed parts).
The "FeedForward" in the paper corresponds to `self.out_cross_layer` applied to the sum of mixed S and T components,
and the initial $X^l$ is added back if `channel_independence` is true.
The `cross_layer` is applied to S and T components *before* mixing if not channel_independence, which is
an implementation detail not explicitly in Eq.3 but plausible for feature transformation.
"""
def __init__(self, configs):
"""
Initializes the PastDecomposableMixing block.
Args:
configs (object): Configuration object with model hyperparameters.
Key attributes used:
- seq_len, pred_len, down_sampling_window
- d_model, dropout, channel_independence
- decomp_method ('moving_avg' or 'dft_decomp'), moving_avg (kernel size), top_k (for DFT)
- d_ff (feed-forward dimension)
Functionality:
1. Initializes basic configuration parameters.
2. Sets up LayerNorm and Dropout.
3. Initializes the series decomposition module based on `configs.decomp_method`:
- `series_decomp` from Autoformer (moving average based).
- `DFT_series_decomp` (defined above, DFT based).
4. If not `channel_independence`, initializes `cross_layer` (a FeedForward network)
to process seasonal and trend components before mixing. This step isn't explicitly in Eq.3 of paper,
but can be seen as part of the S-Mix/T-Mix input preparation or initial feature transformation.
5. Initializes `MultiScaleSeasonMixing` for S-Mix.
6. Initializes `MultiScaleTrendMixing` for T-Mix.
7. Initializes `out_cross_layer` (a FeedForward network) which corresponds to the
FeedForward() in Eq.3 of the paper that processes the sum of mixed components.
"""
super(PastDecomposableMixing, self).__init__()
self.seq_len = configs.seq_len
self.pred_len = configs.pred_len
self.down_sampling_window = configs.down_sampling_window
self.layer_norm = nn.LayerNorm(configs.d_model) # LayerNorm isn't explicitly shown in PDM's Eq.3, might be applied outside or part of FF.
self.dropout = nn.Dropout(configs.dropout) # Dropout isn't explicitly shown in PDM's Eq.3.
self.channel_independence = configs.channel_independence
# Initialize series decomposition module
# Paper mentions series decomposition from Autoformer (moving average)
# and explores DFT-based decomposition in appendix.
if configs.decomp_method == 'moving_avg':
self.decompsition = series_decomp(configs.moving_avg)
elif configs.decomp_method == "dft_decomp":
self.decompsition = DFT_series_decomp(configs.top_k)
else:
raise ValueError('decompsition method is not supported')
# Optional cross-channel mixing layer if not channel independent.
# This pre-processes seasonal and trend components before S-Mix and T-Mix.
# This is an implementation choice not explicitly detailed in the PDM's main equation (Eq.3)
# but could be part of the broader block's processing or input feature refinement.
if not configs.channel_independence:
self.cross_layer = nn.Sequential(
nn.Linear(in_features=configs.d_model, out_features=configs.d_ff),
nn.GELU(),
nn.Linear(in_features=configs.d_ff, out_features=configs.d_model),
)
# Initialize Seasonal Mixing (S-Mix) module
self.mixing_multi_scale_season = MultiScaleSeasonMixing(configs)
# Initialize Trend Mixing (T-Mix) module
self.mixing_multi_scale_trend = MultiScaleTrendMixing(configs)
# Output FeedForward layer, corresponding to FeedForward() in Eq.3 of the paper.
# This processes the sum of S-Mix and T-Mix outputs.
self.out_cross_layer = nn.Sequential(
nn.Linear(in_features=configs.d_model, out_features=configs.d_ff),
nn.GELU(),
nn.Linear(in_features=configs.d_ff, out_features=configs.d_model),
)
def forward(self, x_list):
"""
Forward pass for the Past-Decomposable-Mixing block.
Args:
x_list (list of torch.Tensor): A list of input tensors, one for each scale.
Each tensor $x_m^{l-1}$ has shape (batch_size, sequence_length_at_scale_m, d_model).
These are the outputs from the previous PDM layer or initial embeddings $\mathcal{X}^0$.
Returns:
list of torch.Tensor: A list of output tensors $X_m^l$ for each scale after PDM processing.
Functionality:
1. Records original lengths of series at each scale.
2. For each scale in `x_list`:
a. Decomposes the input $x_m^{l-1}$ into seasonal $s_m^{l-1}$ and trend $t_m^{l-1}$ components using `self.decompsition`.
b. If not `channel_independence`, applies `self.cross_layer` to $s_m^{l-1}$ and $t_m^{l-1}$.
c. Permutes dimensions of seasonal and trend components for mixing (to Batch, d_model, SeqLen_m).
3. Applies `self.mixing_multi_scale_season` (S-Mix) to the list of seasonal components.
4. Applies `self.mixing_multi_scale_trend` (T-Mix) to the list of trend components.
5. For each scale:
a. Sums the mixed seasonal and trend components: $S_m' + T_m'$.
b. This sum is then processed by `self.out_cross_layer` (FeedForward in paper's Eq.3).
c. A residual connection is added: $x_m^l = x_m^{l-1} + \text{FeedForward}(S_m' + T_m')$.
This happens if `self.channel_independence` is True. If False, the residual connection with `ori`
is not explicitly performed here, which is a deviation from paper's $X^{l+1} = X^l + \text{FeedForward}(\dots)$.
However, the PDM block itself is usually part of a larger structure where residuals are handled,
or this 'ori' addition might be specific to the channel-independent path.
The paper's Eq. (3) is $X^{l+1}_m = X^l_m + \text{FeedForward}(S\text{-Mix}(\{s^l_k\})_m + T\text{-Mix}(\{t^l_k\})_m)$.
The code implements: `out = out_season + out_trend`. Then, `if self.channel_independence: out = ori + self.out_cross_layer(out)`.
This means `self.out_cross_layer` is applied *only if channel_independence is true* and *before* the residual.
If `channel_independence` is false, the output is just `out_season + out_trend` without the final FeedForward or residual from `ori`.
This is a notable discrepancy from Eq.3.
The paper states "FeedForward() contains two linear layers with intermediate GELU activation function for information interaction among channels".
This `out_cross_layer` matches that description. The discrepancy is *when* it's applied and the residual.
Discrepancy from paper's Eq.3:
- If `channel_independence` is `True`: `output = original_input + FeedForward(mixed_season + mixed_trend)`. This aligns well.
- If `channel_independence` is `False`: `output = mixed_season + mixed_trend`. The final FeedForward and residual with `original_input` are skipped.
This means `self.out_cross_layer` is NOT the FeedForward in Eq.3 for the channel-dependent case.
Perhaps the "FeedForward" in Eq.3 is implicitly assumed to be handled by the `cross_layer` applied *before* S-Mix and T-Mix for the
channel-dependent case, or it's a simplification in the code for that path.
- The layer norm and dropout initialized in `__init__` are not explicitly used in this forward pass.
"""
length_list = []
for x in x_list: # x_list contains x_0, x_1, ..., x_M from previous layer (or embedding)
_, T, _ = x.size() # (Batch, SeqLen_m, Channels)
length_list.append(T)
# Decompose to obtain the season and trend for each scale
season_list = []
trend_list = []
for x in x_list: # x is x_m^l
# Decompose $x_m^l$ into $s_m^l$ and $t_m^l$
season, trend = self.decompsition(x)
if not self.channel_independence:
# This cross_layer application before S-Mix/T-Mix is an impl. detail.
season = self.cross_layer(season)
trend = self.cross_layer(trend)
# Permute to (Batch, Channels, SeqLen_m) for mixing layers
season_list.append(season.permute(0, 2, 1))
trend_list.append(trend.permute(0, 2, 1))
# bottom-up season mixing (S-Mix)
# out_season_list contains mixed seasonal components [s'_0, s'_1, ..., s'_M]
# Each element is (Batch, SeqLen_m, Channels) due to permute in MultiScaleSeasonMixing
out_season_list = self.mixing_multi_scale_season(season_list)
# top-down trend mixing (T-Mix)
# out_trend_list contains mixed trend components [t'_0, t'_1, ..., t'_M]
# Each element is (Batch, SeqLen_m, Channels)
out_trend_list = self.mixing_multi_scale_trend(trend_list)
out_list = []
# ori is x_m^l (original input to this PDM block for scale m)
# out_season is s'_m (mixed seasonal for scale m)
# out_trend is t'_m (mixed trend for scale m)
for ori, out_season, out_trend, length in zip(x_list, out_season_list, out_trend_list,
length_list):
# Sum mixed seasonal and trend components for scale m
out = out_season + out_trend # This is $(S\text{-Mix}(\{s^l_k\})_m + T\text{-Mix}(\{t^l_k\})_m)$ part of Eq.3
if self.channel_independence:
# For channel independence, the paper's Eq.3 suggests $X^{l+1}_m = X^l_m + \text{FeedForward}(\text{Sum})$
# Here, `ori` is $X^l_m$. `self.out_cross_layer` is FeedForward.
# The output from S-Mix and T-Mix are already (Batch, SeqLen, Channels)
# So `out` is (Batch, SeqLen, Channels).
# `self.out_cross_layer` should take (Batch, SeqLen, Channels) and output the same.
out = ori + self.out_cross_layer(out) # This matches Eq.3 for channel_independence
else:
# If not channel_independence, the code directly uses `out = out_season + out_trend`.
# The `self.out_cross_layer` (FeedForward from Eq.3) and the residual `ori` are skipped.
# This is a discrepancy with Eq.3.
# The `cross_layer` applied earlier might be intended to fulfill the FeedForward role
# for non-channel-independent case, but the residual is still missing.
pass # `out` remains `out_season + out_trend`
# Ensure output has the original length for that scale (handles padding if any, though not explicitly mentioned)
out_list.append(out[:, :length, :]) # $X^{l+1}_m$
return out_list
class Model(nn.Module):
"""
TimeMixer model implementation.
This class encapsulates the entire TimeMixer architecture as described in the paper.
It handles multiscale input processing, feature extraction using Past-Decomposable-Mixing (PDM) blocks,
and future prediction using Future-Multipredictor-Mixing (FMM). It also supports other tasks
like imputation, anomaly detection, and classification.
Key architectural components from the paper:
1. Multiscale Series Generation: Input series is downsampled (e.g., by average pooling)
to create multiple scales $\mathcal{X}=\{x_{0},\cdot\cdot\cdot,x_{M}\}$.
This is handled by `__multi_scale_process_inputs`.
2. Embedding: Multiscale series are projected into deep features $\mathcal{X}^0 = \text{Embed}(\mathcal{X})$.
Handled by `self.enc_embedding`.
3. Past-Decomposable-Mixing (PDM): Stacked PDM blocks process the multiscale representations
$X^{l}=PDM(X^{l-1})$. Implemented by `self.pdm_blocks`.
4. Future-Multipredictor-Mixing (FMM): Ensembles predictions from different scales
$\hat{x}=FMM(\mathcal{X}^{L})$. Implemented by `self.future_multi_mixing`.
"""
def __init__(self, configs):
"""
Initializes the TimeMixer model.
Args:
configs (object): Configuration object with all necessary hyperparameters.
See paper Appendix A Table 7 for typical configurations.
Functionality:
- Sets up basic model parameters (task_name, seq_len, pred_len, etc.).
- Initializes a stack of `PastDecomposableMixing` (PDM) blocks (`self.pdm_blocks`).
The number of PDM blocks is `configs.e_layers` (L in the paper ).
- Initializes an embedding layer (`self.enc_embedding`) which is `DataEmbedding_wo_pos`.
This embedding is applied after multiscale generation. The paper states $X^0 = Embed(X)$.
- Initializes normalization layers (`self.normalize_layers`) for each scale.
The paper itself doesn't detail normalization layers explicitly within Figure 1's PDM/FMM,
but normalization is a common practice. Appendix A mentions `use_norm` [Table 7, though not in paper PDF].
This code uses `Normalize` from `layers.StandardNorm`.
- Initializes task-specific layers:
- For forecasting ('long_term_forecast', 'short_term_forecast'):
- `self.predict_layers`: A list of linear layers, one for each scale, to predict the future of length `configs.pred_len`
from the scale-specific sequence length. This corresponds to `Predictor_m` in FMM (Eq.6).
- `self.projection_layer`: Projects the `d_model` dimensional output to 1 (channel-independent) or `c_out` channels.
- `self.out_res_layers`, `self.regression_layers`: Used if not channel-independent, for an alternative FMM path,
adding a residual from the pre-PDM decomposed trend. This is an implementation detail beyond the main FMM description in Eq.6.
The paper's FMM (Eq.6) is $\hat{x}_m = \text{Predictor}_m(x_m^L)$ and then sum. This code has a more complex structure for the
non-channel-independent case in `future_multi_mixing` and `out_projection`.
- For imputation/anomaly_detection: `self.projection_layer`.
- For classification: An activation, dropout, and a final projection layer.
- `self.preprocess` (series_decomp) is initialized but seems primarily used in `pre_enc` which is called if
`channel_independence` is False during the `forecast` method, before embedding. This implies an initial
decomposition before PDM blocks for the channel-dependent path, which is not explicitly in the main PDM loop of paper (Fig 1b, Eq 3).
The PDM block itself contains its own decomposition.
"""
super(Model, self).__init__()
self.configs = configs
self.task_name = configs.task_name
self.seq_len = configs.seq_len
self.label_len = configs.label_len # Not directly used by TimeMixer core logic but common in frameworks.
self.pred_len = configs.pred_len # F in paper
self.down_sampling_window = configs.down_sampling_window # Factor for $P/2^m$ calculation
self.channel_independence = configs.channel_independence
# Initialize L PDM blocks
self.pdm_blocks = nn.ModuleList([PastDecomposableMixing(configs)
for _ in range(configs.e_layers)]) # configs.e_layers is L
# This preprocess (series_decomp) is used in `pre_enc` for the non-channel-independent path in forecasting.
# This suggests an initial decomposition applied to each scale *before* the PDM blocks' internal decomposition
# for that specific path. This is an additional step not explicitly shown in Figure 1 for PDM inputs.
# PDM block itself has its own `self.decompsition`.
self.preprocess = series_decomp(configs.moving_avg)
self.enc_in = configs.enc_in # C in paper
# Embedding layer for multiscale series
if self.channel_independence:
# For channel independence, each channel is treated as a separate series with 1 feature for embedding.
self.enc_embedding = DataEmbedding_wo_pos(1, configs.d_model, configs.embed, configs.freq,
configs.dropout)
else:
self.enc_embedding = DataEmbedding_wo_pos(configs.enc_in, configs.d_model, configs.embed, configs.freq,
configs.dropout)
self.layer = configs.e_layers # Number of PDM blocks (L)
# Normalization layers for each of the M+1 scales.
# The paper doesn't explicitly detail these in the main architecture diagram [Figure 1]
# but mentions `use_norm` in appendix configurations [Table 7 not in PDF, inferred from code context].
# Applied to each scale after downsampling and before embedding.
self.normalize_layers = torch.nn.ModuleList(
[
Normalize(self.configs.enc_in, affine=True, non_norm=True if configs.use_norm == 0 else False)
# M+1 scales: original (i=0) + M downsampled scales.
for i in range(configs.down_sampling_layers + 1) # configs.down_sampling_layers is M
]
)
if self.task_name == 'long_term_forecast' or self.task_name == 'short_term_forecast':
# These are the Predictor_m components of FMM (Eq.6)
# Each predictor maps from the PDM output at a specific scale (length P/2^m) to the future prediction (length F).
self.predict_layers = torch.nn.ModuleList(
[
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** i), # Input length from scale m: P/factor^i
configs.pred_len, # Output length F
)
for i in range(configs.down_sampling_layers + 1) # M+1 predictors for M+1 scales
]
)
# Projection layer used in FMM after individual predictors if channel_independence is True,
# or as part of the `out_projection` method if False.
# Paper FMM: "Predictorm() ... then projects deep representations into C variates".
if self.channel_independence:
self.projection_layer = nn.Linear(
configs.d_model, 1, bias=True) # Projects d_model to 1 (for each channel)
else:
self.projection_layer = nn.Linear(
configs.d_model, configs.c_out, bias=True) # Projects d_model to c_out
# These layers are used in `out_projection` for the non-channel-independent FMM path.
# This path adds a residual component based on the initial decomposition's trend part (`x_list[1]`).
# This is an implementation detail not specified in the main FMM description (Eq.6) of the paper.
self.out_res_layers = torch.nn.ModuleList([
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** i),
configs.seq_len // (configs.down_sampling_window ** i),
)
for i in range(configs.down_sampling_layers + 1)
])
self.regression_layers = torch.nn.ModuleList(
[
torch.nn.Linear(
configs.seq_len // (configs.down_sampling_window ** i),
configs.pred_len,
)
for i in range(configs.down_sampling_layers + 1)
]
)
if self.task_name == 'imputation' or self.task_name == 'anomaly_detection':
# For these reconstruction tasks, a projection layer maps d_model back to feature dimension.
if self.channel_independence:
self.projection_layer = nn.Linear(
configs.d_model, 1, bias=True)
else:
self.projection_layer = nn.Linear(
configs.d_model, configs.c_out, bias=True)
if self.task_name == 'classification':
# For classification, features are typically flattened and projected to num_classes.
self.act = F.gelu # Activation after PDM blocks
self.dropout = nn.Dropout(configs.dropout)
self.projection = nn.Linear(
configs.d_model * configs.seq_len, configs.num_class) # Projects flattened features
def out_projection(self, dec_out, i, out_res):
"""
Applies an output projection, potentially with a residual component.
This method is specifically used in the `future_multi_mixing` for the
non-channel-independent forecasting path. It combines the direct prediction
from a scale's PDM output with a regressed version of that scale's
initial trend component (from `pre_enc`).
This residual path using `out_res` (initial trend) is an implementation detail
not explicitly covered in the paper's FMM (Eq.6) description.
Args:
dec_out (torch.Tensor): The direct prediction from `predict_layers[i]`. Shape (Batch, PredLen, d_model).
i (int): The current scale index.
out_res (torch.Tensor): The initial trend component for the current scale from `pre_enc`. Shape (Batch, SeqLen_scale_i, C).
Returns:
torch.Tensor: The final prediction for the scale after projection and residual addition. Shape (Batch, PredLen, C).
"""
# Project d_model features to C output channels
dec_out = self.projection_layer(dec_out) # (Batch, PredLen, C)
# Process the residual (initial trend) component
out_res = out_res.permute(0, 2, 1) # (Batch, C, SeqLen_scale_i)
out_res = self.out_res_layers[i](out_res) # (Batch, C, SeqLen_scale_i)
out_res = self.regression_layers[i](out_res).permute(0, 2, 1) # (Batch, PredLen, C)
# Add the processed residual to the main prediction
dec_out = dec_out + out_res
return dec_out
def pre_enc(self, x_list):
"""
Pre-processes a list of multi-scale input tensors before embedding,
specifically for the non-channel-independent path.
If not channel_independent, it applies series decomposition (`self.preprocess`)
to each scale's input tensor.
This is an additional decomposition step before the PDM blocks' own decomposition,
and its output (x_1, x_2) is used where x_1 (seasonal-like) goes to embedding
and x_2 (trend-like) is used for the residual path in `out_projection` during FMM.
This pre-decomposition is not explicitly detailed in the main TimeMixer architecture [Figure 1].
Args:
x_list (list of torch.Tensor): List of input tensors for each scale.
Returns:
tuple: If channel_independence is True, returns (x_list, None).
If False, returns (out1_list, out2_list) where out1 contains seasonal-like
parts and out2 contains trend-like parts from `self.preprocess`.
"""
if self.channel_independence:
return (x_list, None) # No pre-decomposition for channel-independent case
else:
out1_list = [] # To store seasonal-like parts
out2_list = [] # To store trend-like parts (used as residual in FMM)
for x in x_list:
x_1, x_2 = self.preprocess(x) # Apply initial series decomposition
out1_list.append(x_1)
out2_list.append(x_2)
return (out1_list, out2_list)
def __multi_scale_process_inputs(self, x_enc, x_mark_enc):
"""
Generates multi-scale representations of the input time series.
This corresponds to step (a) "Multiscale Time Series" in Figure 1 of the paper.
The input `x_enc` is downsampled iteratively to create `configs.down_sampling_layers` (M) coarser scales.
The paper mentions "average downsampling" or "average pooling". This code supports
'max', 'avg', or 'conv' based 1D pooling/convolution for downsampling.
Args:
x_enc (torch.Tensor): Input encoder data of shape (batch_size, seq_len, num_features).
x_mark_enc (torch.Tensor, optional): Input encoder temporal/mark data.
Returns:
tuple:
- x_enc_sampling_list (list of torch.Tensor): List of M+1 tensors, from original scale to coarsest.
Each tensor shape (batch_size, length_at_scale, num_features).
- x_mark_sampling_list (list of torch.Tensor or None): List of M+1 temporal/mark tensors, or None.
"""
if self.configs.down_sampling_method == 'max':
down_pool = torch.nn.MaxPool1d(self.configs.down_sampling_window, return_indices=False)
elif self.configs.down_sampling_method == 'avg': # Paper mentions average pooling
down_pool = torch.nn.AvgPool1d(self.configs.down_sampling_window)
elif self.configs.down_sampling_method == 'conv':
# 1D convolution for downsampling. Kernel size 3, stride = window.
# This is an alternative to pooling, not directly mentioned for downsampling in paper's main text for TimeMixer.
# Appendix F.3 explores 1D convolutions as an alternative downsampling method.
padding = 1 if torch.__version__ >= '1.5.0' else 2 # Version-dependent padding for Conv1d
down_pool = nn.Conv1d(in_channels=self.configs.enc_in, out_channels=self.configs.enc_in,
kernel_size=3, padding=padding,
stride=self.configs.down_sampling_window,
padding_mode='circular', # Circular padding not mentioned in paper.
bias=False)
else:
# If no valid downsampling method, return original inputs (effectively single scale)
return [x_enc], [x_mark_enc] if x_mark_enc is not None else None
# Permute x_enc from (B, T, C) to (B, C, T) for 1D pooling/convolution operations
x_enc = x_enc.permute(0, 2, 1)
x_enc_ori = x_enc # Keep original (permuted) x_enc for iterative downsampling
x_mark_enc_mark_ori = x_mark_enc # Keep original x_mark_enc
x_enc_sampling_list = []
x_mark_sampling_list = []
# Add the original scale (scale 0)
x_enc_sampling_list.append(x_enc.permute(0, 2, 1)) # Permute back to (B, T, C)
x_mark_sampling_list.append(x_mark_enc)
# Generate M coarser scales
for i in range(self.configs.down_sampling_layers): # M iterations
x_enc_sampling = down_pool(x_enc_ori) # Apply downsampling (e.g., P/2^m -> P/2^(m+1))
x_enc_sampling_list.append(x_enc_sampling.permute(0, 2, 1)) # Permute and add to list
x_enc_ori = x_enc_sampling # Update for next iteration's input
if x_mark_enc is not None:
# Downsample temporal marks by simple strided slicing.
# Paper does not specify how temporal marks are downsampled. This is an implementation choice.
x_mark_sampling_list.append(x_mark_enc_mark_ori[:, ::self.configs.down_sampling_window, :])
x_mark_enc_mark_ori = x_mark_enc_mark_ori[:, ::self.configs.down_sampling_window, :]
x_enc = x_enc_sampling_list
x_mark_enc = x_mark_sampling_list if x_mark_enc is not None else None
return x_enc, x_mark_enc # Returns list of M+1 scales
def forecast(self, x_enc, x_mark_enc, x_dec, x_mark_dec):
"""
Performs the forecasting task using the TimeMixer architecture.
Args:
x_enc (torch.Tensor): Past observed time series values. (Batch, P, C_in)
x_mark_enc (torch.Tensor, optional): Temporal/exogenous features for past observations.
x_dec (torch.Tensor, optional): Values for teacher-forcing (not directly used by TimeMixer for generation).
x_mark_dec (torch.Tensor, optional): Temporal/exogenous features for future.
Returns:
torch.Tensor: Predicted future time series values. (Batch, F, C_out)
Functionality (following TimeMixer paper ):
1. `__multi_scale_process_inputs`: Generates multiscale series $\mathcal{X}$ from `x_enc`.
2. Normalization: Each scale $x_m \in \mathcal{X}$ is normalized.
3. Channel Handling: If `channel_independence`, data is reshaped so each channel is processed separately.
4. `pre_enc`: If not `channel_independence`, an initial decomposition is applied to each scale.
5. Embedding: Each (potentially pre-decomposed and normalized) scale $x_m$ is embedded to get $\mathcal{X}^0$.
6. PDM Blocks: $\mathcal{X}^0$ is passed through L layers of `self.pdm_blocks` to get $\mathcal{X}^L$.
7. FMM: `self.future_multi_mixing` takes $\mathcal{X}^L$ (and potentially `x_list` from `pre_enc`)
to produce predictions for each scale, which are then summed.
8. Denormalization: The final summed prediction is denormalized.
"""
# 1. Generate multiscale series (e.g., using average pooling)
# x_enc: (Batch, P, C_in) -> x_enc becomes list of M+1 tensors, each (Batch, P/factor^m, C_in)
x_enc, x_mark_enc = self.__multi_scale_process_inputs(x_enc, x_mark_enc)
x_list_for_embedding = [] # Will store inputs for embedding layer for each scale
x_mark_list_for_embedding = [] if x_mark_enc is not None else None
# Store B, N for reshaping if channel_independence later, from the original scale (scale 0)
B_orig, _, N_orig = x_enc[0].size()
# 2. Normalization and Channel Handling for each scale
if x_mark_enc is not None:
for i, (x_scale, x_mark_scale) in enumerate(zip(x_enc, x_mark_enc)):
# x_scale is (Batch, SeqLen_m, Channels)
B, T, N = x_scale.size()
x_scale_normalized = self.normalize_layers[i](x_scale, 'norm')
if self.channel_independence:
# Reshape for channel-independent processing: (B*N, T, 1)
x_scale_processed = x_scale_normalized.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)
x_list_for_embedding.append(x_scale_processed)
if x_mark_list_for_embedding is not None:
# Repeat marks for each channel if processing independently
x_mark_list_for_embedding.append(x_mark_scale.repeat(N, 1, 1) if x_mark_scale is not None else None)
else:
x_list_for_embedding.append(x_scale_normalized)
if x_mark_list_for_embedding is not None:
x_mark_list_for_embedding.append(x_mark_scale)
else: # No x_mark_enc
for i, x_scale in enumerate(x_enc):
B, T, N = x_scale.size()
x_scale_normalized = self.normalize_layers[i](x_scale, 'norm')
if self.channel_independence:
x_scale_processed = x_scale_normalized.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)
x_list_for_embedding.append(x_scale_processed)
else:
x_list_for_embedding.append(x_scale_normalized)
# 3. `pre_enc`: Optional initial decomposition for non-channel-independent path
# If channel_independence, pre_enc_outputs = (x_list_for_embedding, None)
# Else, pre_enc_outputs = (decomposed_seasonal_parts, decomposed_trend_parts)
pre_enc_outputs = self.pre_enc(x_list_for_embedding)
# The first element of pre_enc_outputs is always the list of tensors that will go into embedding.
# For channel_independence=False, these are the 'seasonal-like' parts from self.preprocess.
# For channel_independence=True, these are the normalized, reshaped original scales.
actual_x_list_for_embedding = pre_enc_outputs[0]
# 4. Embedding for each scale
# Input to embedding is from actual_x_list_for_embedding
enc_out_list = [] # Stores $\mathcal{X}^0$, the embedded representations for each scale
if x_mark_list_for_embedding is not None:
for i, (x_to_embed, x_mark_to_embed) in enumerate(zip(actual_x_list_for_embedding, x_mark_list_for_embedding)):
enc_out = self.enc_embedding(x_to_embed, x_mark_to_embed) # Output: (Batch', SeqLen_m, d_model)
enc_out_list.append(enc_out)
else: # No x_mark_enc
for i, x_to_embed in enumerate(actual_x_list_for_embedding):
enc_out = self.enc_embedding(x_to_embed, None)
enc_out_list.append(enc_out)
# 5. Past Decomposable Mixing (PDM) blocks
# Input `enc_out_list` is $\mathcal{X}^l$, output is $\mathcal{X}^{l+1}$
for i in range(self.layer): # self.layer is L, number of PDM blocks
enc_out_list = self.pdm_blocks[i](enc_out_list)
# After L layers, `enc_out_list` becomes $\mathcal{X}^L$
# 6. Future Multipredictor Mixing (FMM)
# `pre_enc_outputs` is passed because `future_multi_mixing` might use the trend part (`pre_enc_outputs[1]`)
# for the residual connection in the non-channel-independent case.
# B_orig is the batch size before potential channel-wise reshaping.
dec_out_list = self.future_multi_mixing(B_orig, enc_out_list, pre_enc_outputs)
# `dec_out_list` contains $\hat{x}_m$ for each scale, shape (Batch_orig, F, C_out)
# Sum predictions from all scales (Eq.6 in paper: $\hat{x} = \sum \hat{x}_m$)
dec_out = torch.stack(dec_out_list, dim=-1).sum(-1) # Stack along new dim, then sum over it.
# 7. Denormalization (applied to the combined prediction)
# Using normalize_layers[0] implies denormalization parameters are based on the original scale.
dec_out = self.normalize_layers[0](dec_out, 'denorm')
return dec_out
def future_multi_mixing(self, B, enc_out_list, x_list_from_pre_enc):
"""
Implements Future-Multipredictor-Mixing (FMM) block.
It generates future predictions from each scale's PDM output ($\mathcal{X}^L$)
and then these predictions are summed up in the calling function (`forecast`).
Args:
B (int): Original batch size (before any channel-wise reshaping).
enc_out_list (list of torch.Tensor): List of PDM outputs for each scale ($\mathcal{X}^L_m$).
Each tensor shape (Batch', SeqLen_m, d_model). Batch' might be B*N if channel_independent.
x_list_from_pre_enc (tuple): Output from `self.pre_enc`.
`x_list_from_pre_enc[0]` is the list of inputs to embedding (seasonal-like or original).
`x_list_from_pre_enc[1]` is the list of trend-like components (if not channel_independent), otherwise None.
Returns:
list of torch.Tensor: List of predictions ($\hat{x}_m$), one from each scale.
Each tensor shape (B_original, PredLen, C_out).
Functionality based on paper's Eq.6: $\hat{x}_m = \text{Predictor}_m(x_m^L)$.
- For each scale `i` and its PDM output `enc_out` ($x_m^L$):
- Apply `self.predict_layers[i]` (Predictor_m) to map from (SeqLen_m, d_model) to (PredLen, d_model) after permutation.
- If `channel_independence`:
- Project to 1 channel using `self.projection_layer`.
- Reshape back to (B_original, C_out, PredLen) and permute to (B_original, PredLen, C_out). C_out is N_original here.
- Else (not `channel_independence`):
- Use `self.out_projection` which combines the prediction with a residual from the initial trend
component (from `x_list_from_pre_enc[1]`). This is a more complex predictor than just a linear layer + projection.
"""
dec_out_list = []
if self.channel_independence:
# x_list_from_pre_enc[0] is the list of inputs to embedding (Batch*N, SeqLen_m, 1)
# enc_out_list contains PDM outputs (Batch*N, SeqLen_m, d_model)
# N_original (self.configs.enc_in) is number of channels.
# C_out for channel independence case should be N_original.
# The paper states FMM ensembles multiple predictors for multiscale observations.
# Predictor_m applies a linear layer from length P/2^m to F, then projects to C variates.
# The loop should iterate M+1 times, one for each scale.
for i, enc_out_scale_m in enumerate(enc_out_list): # enc_out_scale_m is $x_m^L$
# enc_out_scale_m shape is (B*N, SeqLen_m, d_model)
# self.predict_layers[i] maps temporal dim: SeqLen_m -> PredLen (F)
# Input to linear layer should be (Batch', *, InDim), so permute d_model and SeqLen_m
# (B*N, d_model, SeqLen_m) -> predict_layer -> (B*N, d_model, PredLen)
dec_out_m = self.predict_layers[i](enc_out_scale_m.permute(0, 2, 1))
# Permute back: (B*N, PredLen, d_model)
dec_out_m = dec_out_m.permute(0, 2, 1)
# Project d_model to 1 (as it's channel independent)
dec_out_m = self.projection_layer(dec_out_m) # (B*N, PredLen, 1)
# Reshape from (B*N, PredLen, 1) to (B, N, PredLen) and then permute to (B, PredLen, N)
# N is self.configs.enc_in (number of original channels/variates, which is also c_out for this case)
dec_out_m = dec_out_m.reshape(B, self.configs.enc_in, self.pred_len).permute(0, 2, 1).contiguous()
dec_out_list.append(dec_out_m) # Each dec_out_m is $\hat{x}_m$
else: # Not channel_independence
# enc_out_list contains PDM outputs (B, SeqLen_m, d_model)
# x_list_from_pre_enc[0] is seasonal-like parts (B, SeqLen_m, C_in)
# x_list_from_pre_enc[1] is trend-like parts (B, SeqLen_m, C_in), used for `out_res`
trend_residuals_list = x_list_from_pre_enc[1]
for i, (enc_out_scale_m, out_res_scale_m) in enumerate(zip(enc_out_list, trend_residuals_list)):
# enc_out_scale_m is (B, SeqLen_m, d_model)
# out_res_scale_m is (B, SeqLen_m, C_in) - the initial trend for this scale
# self.predict_layers[i] maps temporal dim: SeqLen_m -> PredLen
dec_out_m = self.predict_layers[i](enc_out_scale_m.permute(0, 2, 1)).permute(0, 2, 1)
# dec_out_m is (B, PredLen, d_model)
# self.out_projection combines this with regressed out_res_scale_m and projects to C_out
dec_out_m = self.out_projection(dec_out_m, i, out_res_scale_m) # Output (B, PredLen, C_out)
dec_out_list.append(dec_out_m) # Each dec_out_m is $\hat{x}_m$
return dec_out_list
def classification(self, x_enc, x_mark_enc):
"""
Performs the classification task.
The paper does not detail a classification setup for TimeMixer.
This implementation processes multiscale inputs through embeddings and PDM blocks,
then takes the output of the finest scale PDM block, applies GELU, Dropout,
flattens it, and projects to the number of classes.
This is a common approach for time series classification using sequence models.
Args:
x_enc (torch.Tensor): Input time series data.
x_mark_enc (torch.Tensor): Temporal features (used for masking output).
Returns:
torch.Tensor: Classification scores/logits.
"""
# 1. Generate multiscale series (only x_enc is used for features, x_mark_enc for masking later)
x_enc_scales, _ = self.__multi_scale_process_inputs(x_enc, None) # x_mark_enc not used for scaling here
# x_enc_scales is a list of tensors, one for each scale.
# Embedding for each scale (no normalization applied here unlike forecast)
# This is a discrepancy, as other tasks usually involve normalization.
enc_out_list = []
for x_scale in x_enc_scales:
enc_out = self.enc_embedding(x_scale, None) # Input (B, SeqLen_m, C_in) -> (B, SeqLen_m, d_model)
enc_out_list.append(enc_out)
# Pass through PDM blocks
for i in range(self.layer): # L PDM blocks
enc_out_list = self.pdm_blocks[i](enc_out_list)
# Use the output from the finest scale (scale 0) PDM block
enc_out_finest_scale = enc_out_list[0] # (B, SeqLen_orig, d_model)
# Output processing for classification
output = self.act(enc_out_finest_scale) # GELU activation
output = self.dropout(output) # Dropout
# Masking: "zero-out padding embeddings"
# Assumes x_mark_enc has shape (B, SeqLen_orig, Feature_mark) and implies padding via marks.
# This step might be specific to datasets where padding is indicated by x_mark_enc.
# If x_mark_enc is just temporal features, this might not be standard zero-padding.
# The unsqueeze(-1) makes x_mark_enc broadcastable with `output` if its last dim is 1 or matches d_model.
# More typically, a dedicated padding mask (bool) would be used.
# For TimeMixer paper, classification is not a primary task, so this is likely an adaptation.
if x_mark_enc is not None: # Guard against x_mark_enc being None
output = output * x_mark_enc.unsqueeze(-1) # Element-wise multiplication, potentially for masking.
# Flatten the sequence: (B, SeqLen_orig * d_model)
output = output.reshape(output.shape[0], -1)
# Project to number of classes
output = self.projection(output) # (B, num_classes)
return output
def anomaly_detection(self, x_enc):
"""
Performs anomaly detection by reconstructing the input series.
Anomalies are typically identified by large reconstruction errors.
The paper does not detail an anomaly detection setup for TimeMixer.
This implementation processes multiscale inputs through normalization, embeddings, PDM blocks,
and then projects the finest scale PDM output back to the input space. Denormalization follows.
Args:
x_enc (torch.Tensor): Input time series data.
Returns:
torch.Tensor: Reconstructed time series.
"""
B_orig, T_orig, N_orig = x_enc.size() # Original batch, seq_len, num_features
# 1. Generate multiscale series
x_enc_scales, _ = self.__multi_scale_process_inputs(x_enc, None)
x_list_for_embedding = []
# 2. Normalization and Channel Handling for each scale
for i, x_scale in enumerate(x_enc_scales):
B, T, N = x_scale.size()
x_scale_normalized = self.normalize_layers[i](x_scale, 'norm')
if self.channel_independence:
x_scale_processed = x_scale_normalized.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)
x_list_for_embedding.append(x_scale_processed)
else:
x_list_for_embedding.append(x_scale_normalized)
# 3. Embedding for each scale
enc_out_list = []
for x_to_embed in x_list_for_embedding:
enc_out = self.enc_embedding(x_to_embed, None)
enc_out_list.append(enc_out)
# 4. Pass through PDM blocks
for i in range(self.layer):
enc_out_list = self.pdm_blocks[i](enc_out_list)
# 5. Projection from finest scale PDM output back to input space
# enc_out_list[0] is (Batch', SeqLen_orig, d_model), where Batch' is B_orig*N_orig if channel_independent
dec_out = self.projection_layer(enc_out_list[0]) # (Batch', SeqLen_orig, 1 if CI else C_out)
# Reshape if channel_independence back to (B_orig, C_out, SeqLen_orig) then (B_orig, SeqLen_orig, C_out)
# C_out here should be N_orig.
if self.channel_independence:
dec_out = dec_out.reshape(B_orig, N_orig, T_orig).permute(0, 2, 1).contiguous()
# If not CI, dec_out is already (B_orig, SeqLen_orig, C_out=N_orig)
# 6. Denormalization
dec_out = self.normalize_layers[0](dec_out, 'denorm')
return dec_out
def imputation(self, x_enc, x_mark_enc, mask):
"""
Performs time series imputation.
The paper does not detail an imputation setup for TimeMixer.
This implementation:
1. Standardizes the input `x_enc` (mean 0, std 1) based on observed values (where mask=1).
Missing values (mask=0) are filled with 0 after centering.
2. Processes these standardized, masked inputs through the multiscale pipeline (normalization,
embedding, PDM blocks) similar to anomaly detection.
3. Projects the finest scale PDM output back to input space.
4. De-standardizes the output using the initially computed mean and std.
Args:
x_enc (torch.Tensor): Input time series with missing values.
x_mark_enc (torch.Tensor, optional): Temporal features.
mask (torch.Tensor): Boolean mask indicating observed (1) vs missing (0) values.
Returns:
torch.Tensor: Imputed time series.
"""
# Instance-wise standardization based on observed values
means = torch.sum(x_enc * mask, dim=1) / (torch.sum(mask, dim=1) + 1e-5) # Calculate mean of observed values
means = means.unsqueeze(1).detach()
x_enc_centered = x_enc - means
x_enc_masked_centered = x_enc_centered.masked_fill(mask == 0, 0) # Fill missing with 0 after centering
stdev = torch.sqrt(torch.sum(x_enc_masked_centered * x_enc_masked_centered * mask, dim=1) /
(torch.sum(mask, dim=1) + 1e-5) + 1e-5) # Calculate std of observed centered values
stdev = stdev.unsqueeze(1).detach()
x_enc_standardized = x_enc_masked_centered / stdev # Standardize based on observed
B_orig, T_orig, N_orig = x_enc.size()
# 1. Generate multiscale series from standardized input
x_enc_scales, x_mark_enc_scales = self.__multi_scale_process_inputs(x_enc_standardized, x_mark_enc)
x_list_for_embedding = []
x_mark_list_for_embedding = [] if x_mark_enc_scales is not None else None
# 2. Per-scale Normalization (on already standardized data - this might be redundant or for further stabilization)
# and Channel Handling
if x_mark_enc_scales is not None:
for i, (x_scale, x_mark_scale) in enumerate(zip(x_enc_scales, x_mark_enc_scales)):
B, T, N = x_scale.size()
# The normalize_layers here are applied again. If the input is already N(0,1) from instance norm,
# and Normalize layer is also doing some form of norm, this is a double normalization.
# However, if Normalize is configured as non_norm=True, it acts as identity.
x_scale_normalized = self.normalize_layers[i](x_scale, 'norm')
if self.channel_independence:
x_scale_processed = x_scale_normalized.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)
x_list_for_embedding.append(x_scale_processed)
if x_mark_list_for_embedding is not None:
x_mark_list_for_embedding.append(x_mark_scale.repeat(N, 1, 1) if x_mark_scale is not None else None)
else:
x_list_for_embedding.append(x_scale_normalized)
if x_mark_list_for_embedding is not None:
x_mark_list_for_embedding.append(x_mark_scale)
else: # No x_mark_enc
for i, x_scale in enumerate(x_enc_scales):
B, T, N = x_scale.size()
x_scale_normalized = self.normalize_layers[i](x_scale, 'norm')
if self.channel_independence:
x_scale_processed = x_scale_normalized.permute(0, 2, 1).contiguous().reshape(B * N, T, 1)
x_list_for_embedding.append(x_scale_processed)
else:
x_list_for_embedding.append(x_scale_normalized)
# 3. Embedding for each scale
enc_out_list = []
# Note: for imputation, the paper doesn't specify if x_mark_enc is used in embedding.
# This code passes None for x_mark to self.enc_embedding if x_mark_list_for_embedding is None.
# If it's not None, it will pass the (potentially repeated) marks.
# The original code for imputation in TimeMixer might use a simpler embedding path.
# The provided code example passes 'None' to enc_embedding for the 'x_mark' argument for imputation.
if x_mark_list_for_embedding is not None:
for x_to_embed, x_mark_to_embed in zip(x_list_for_embedding, x_mark_list_for_embedding):
enc_out = self.enc_embedding(x_to_embed, x_mark_to_embed)
enc_out_list.append(enc_out)
else:
for x_to_embed in x_list_for_embedding:
enc_out = self.enc_embedding(x_to_embed, None)
enc_out_list.append(enc_out)
# 4. Pass through PDM blocks
for i in range(self.layer):
enc_out_list = self.pdm_blocks[i](enc_out_list)
# 5. Projection from finest scale PDM output
dec_out = self.projection_layer(enc_out_list[0]) # (Batch', SeqLen_orig, 1 if CI else C_out)
if self.channel_independence:
dec_out = dec_out.reshape(B_orig, N_orig, T_orig).permute(0, 2, 1).contiguous()
# If not CI, dec_out is (B_orig, SeqLen_orig, C_out=N_orig)
# 6. De-standardization using original means and stdevs
# The normalize_layers[0](..., 'denorm') is NOT used here, direct de-standardization is applied.
dec_out = dec_out * \
(stdev.repeat(1, self.seq_len, 1) if stdev.shape[1] == 1 else stdev) # stdev is (B,1,N) or (B,N)
dec_out = dec_out + \
(means.repeat(1, self.seq_len, 1) if means.shape[1] == 1 else means) # means is (B,1,N) or (B,N)
return dec_out
def forward(self, x_enc, x_mark_enc, x_dec, x_mark_dec, mask=None):
"""
Main forward pass of the Model. Routes to task-specific methods.
Args:
x_enc: Encoder input data.
x_mark_enc: Encoder temporal features.
x_dec: Decoder input data (for forecasting).
x_mark_dec: Decoder temporal features.
mask: Mask for imputation.
Returns:
Output tensor specific to the task.
"""
if self.task_name == 'long_term_forecast' or self.task_name == 'short_term_forecast':
dec_out = self.forecast(x_enc, x_mark_enc, x_dec, x_mark_dec)
return dec_out # Shape (B, F, C_out)
if self.task_name == 'imputation':
dec_out = self.imputation(x_enc, x_mark_enc, mask)
return dec_out # Shape (B, P, C_out)
if self.task_name == 'anomaly_detection':
dec_out = self.anomaly_detection(x_enc)
return dec_out # Shape (B, P, C_out)
if self.task_name == 'classification':
dec_out = self.classification(x_enc, x_mark_enc)
return dec_out # Shape (B, num_classes)
else:
raise ValueError('Other tasks not implemented yet')
# === Appended from canonical.py ===
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.Autoformer_EncDec import series_decomp
from layers.Embed import DataEmbedding_wo_pos
from layers.StandardNorm import Normalize
class DFT_series_decomp(nn.Module):
"""
Series decomposition block using Discrete Fourier Transform (DFT).
This class implements a series decomposition method that is an alternative
to the moving-average-based decomposition mentioned in the paper for the PDM block.
The paper primarily discusses moving-average based decomposition but also mentions
exploring DFT-based decomposition as an alternative in the appendix.
This implementation selects the top_k frequencies to constitute the seasonal component
and subtracts it from the original series to get the trend component.
"""
def __init__(self, top_k=5):
"""
Initializes the DFT_series_decomp module.
Args:
top_k (int): The number of top frequencies to select for the seasonal component.
This parameter is specific to this DFT-based decomposition and
is not directly detailed in the main paper's description of TimeMixer's PDM,
but is a common hyperparameter for frequency-domain analysis.
"""
super(DFT_series_decomp, self).__init__()
self.top_k = top_k
def forward(self, x):
"""
Forward pass for DFT-based series decomposition.
Args:
x (torch.Tensor): Input time series tensor of shape (batch_size, sequence_length, num_features).
Returns:
tuple: A tuple containing:
- x_season (torch.Tensor): The seasonal component of the time series.
- x_trend (torch.Tensor): The trend component of the time series.
Functionality:
1. Computes the Real Fast Fourier Transform (RFFT) of the input series.
2. Calculates the magnitude of the frequencies, ignoring the DC component (freq[0]=0).
3. Identifies the top_k dominant frequencies.
4. Filters the RFFT output by keeping only these top_k frequencies, effectively zeroing out others.
5. Computes the Inverse RFFT (IRFFT) of the filtered frequencies to obtain the seasonal component.
6. The trend component is then derived by subtracting the seasonal component from the original series.
This aligns with the general concept of series decomposition where Trend = Series - Seasonal.
"""
xf = torch.fft.rfft(x)
freq = abs(xf)
# Zero out the DC component to focus on periodic seasonalities
freq[0] = 0
# In the code, it uses a fixed value 5 for top_k, not self.top_k.
# This might be an oversight or intentional for specific experiments.
# For consistency with __init__, it should ideally be self.top_k.
top_k_freq, top_list = torch.topk(freq, 5) # Paper uses top_k
# Filter out frequencies lower than the minimum of the top_k frequencies
xf[freq <= top_k_freq.min()] = 0
x_season = torch.fft.irfft(xf)
x_trend = x - x_season
return x_season, x_trend
class MultiScaleSeasonMixing(nn.Module):
"""
Bottom-up mixing for seasonal patterns across multiple scales.
This module implements the "Seasonal Mixing" (S-Mix) component of the
Past-Decomposable-Mixing (PDM) block described in the TimeMixer paper.
It adopts a bottom-up approach, incorporating information from finer-scale
time series upwards to supplement detailed information for coarser scales' seasonality modeling.
The mixing is done using linear layers along the temporal dimension.
"""
def __init__(self, configs):
"""
Initializes the MultiScaleSeasonMixing module.
Args:
configs (object): A configuration object containing model hyperparameters.
Expected attributes:
- seq_len (int): Original input sequence length.
- down_sampling_window (int): Factor by which sequence length is reduced at each scale.
- down_sampling_layers (int): Number of down-sampling operations (M in paper, number of scales - 1).
Functionality:
Initializes a list of 'down_sampling_layers'. Each layer is a sequence of two linear layers
with a GELU activation in between, designed to transform features from a finer scale
(e.g., length P/2^(m-1)) to a coarser scale (e.g., length P/2^m).
The number of such layers corresponds to `configs.down_sampling_layers` (M),
which is the number of scales minus one (as mixing happens between m-1 and m).
"""
super(MultiScaleSeasonMixing, self).__init__()
# Initialize linear layers for transforming seasonal components from finer to coarser scales.
# The paper describes this as "Bottom-Up-Mixing(s_m-1^l)" in equation (4).
# Each layer projects from length P/2^(m-1) to P/2^m.
# configs.down_sampling_layers corresponds to M in the paper (number of coarser scales).
# So, loop runs for m = 1 to M (i from 0 to M-1).
self.down_sampling_layers = torch.nn.ModuleList(
[