mcy98's picture
Upload folder using huggingface_hub
22e9602 verified
Raw History Blame Contribute Delete
12.9 kB
import torch
from torch.nn import KLDivLoss
# Assume 'self' is an object that has attributes like 'patch_len_threshold',
# 'kl_loss', and 'model' as described in the context of the functions.
def fouriour_based_adaptive_patching(self, true, pred):
"""
Implements the Fourier-based Adaptive Patching (FAP) module described in Section 3.3 of the paper.
This function adaptively segments the true and predicted time series into patches based on the
dominant frequency of the ground truth series.
Functionality and Paper Correspondence:
- The function first calculates the Fast Fourier Transform (FFT) of the ground truth series (`true`)
using `torch.fft.rfft` to analyze its frequency components, which corresponds to the first part
of Equation (2) in the paper.
- It identifies the dominant frequency by finding the `argmax` of the frequency amplitudes. This
directly implements `f = arg max(A)` from Equation (2).
- The period is then calculated as `true.shape[1] // top_index`, which is the code's implementation
of `p = ceil(T/f)` as described in Section 3.3. `true.shape[1]` is the total length `T`.
- The final patch length (`patch_len`) is determined using `min(period // 2, self.patch_len_threshold)`.
The `self.patch_len_threshold` corresponds to the hyperparameter `δ` in the paper.
- The stride is set to half the patch length (`stride = patch_len // 2`), which matches the paper's
description of `S = ceil(P/2)` in the last paragraph of Section 3.3.
- Finally, it calls a helper function `self.create_patches` to segment both `true` and `pred` series
into overlapping patches (`true_patch`, `pred_patch`).
Discrepancy between Code and Paper:
- Equation (3) in the paper defines the final patch length as `P = min(p, δ)`, where `p` is the
dominant period. However, the code implements it as `patch_len = min(period // 2, ...)`.
The division of the period by 2 is an implementation choice not explicitly mentioned in the
paper's formula, likely to ensure patches capture finer-grained sub-patterns within a full period.
"""
# Get patch length and stride
# Corresponds to Equation (2): applying FFT to the ground truth to find the dominant frequency.
true_fft = torch.fft.rfft(true, dim=1)
frequency_list = torch.abs(true_fft).mean(0).mean(-1)
# The first component (DC offset) is ignored to focus on periodic patterns.
frequency_list[:1] = 0.0
top_index = torch.argmax(frequency_list)
# Calculate the period corresponding to the dominant frequency.
# This implements p = T / f from Section 3.3.
period = (true.shape[1] // top_index)
# Determine the final patch length, corresponding to Equation (3).
# Note the discrepancy: the code uses 'period // 2' instead of just 'period'.
patch_len = min(period // 2, self.patch_len_threshold)
# The stride is set to half the patch length, as described in Section 3.3.
stride = patch_len // 2
# Patching
# This helper function (not shown) segments the series into patches Y_p and Y_hat_p.
true_patch = self.create_patches(true, patch_len, stride=stride)
pred_patch = self.create_patches(pred, patch_len, stride=stride)
return true_patch, pred_patch
def patch_wise_structural_loss(self, true_patch, pred_patch):
"""
Calculates the three components of the Patch-wise Structural (PS) loss as described in Section 3.4.
This function computes the correlation, variance, and mean losses between the ground truth and
predicted patches.
Functionality and Paper Correspondence:
- Correlation Loss (`linear_corr_loss`): This part of the code implements Equation (4). It calculates
the Pearson Correlation Coefficient (PCC) for each pair of patches and computes the loss as
`(1 - PCC)`. The mean, standard deviation, and covariance are calculated as intermediate steps.
- Variance Loss (`var_loss`): This implements the variance loss described by Equation (6). It uses
the Kullback-Leibler (KL) divergence between the softmax distributions of the true and predicted
patches (`KL(softmax(Y_p) || softmax(Y_hat_p))`). The code uses `log_softmax` for the predicted
patch for numerical stability and compatibility with PyTorch's `KLDivLoss`.
- Mean Loss (`mean_loss`): This implements Equation (7), which is the Mean Absolute Error (MAE)
between the mean values of the true and predicted patches.
Implementation Details not in Paper:
- A small epsilon (`1e-5`) is added to the denominator during the correlation calculation to prevent
division by zero, which is a standard practice for numerical stability.
"""
# Calculate mean of each patch for both true and predicted series.
true_patch_mean = torch.mean(true_patch, dim=-1, keepdim=True)
pred_patch_mean = torch.mean(pred_patch, dim=-1, keepdim=True)
# Calculate variance and standard deviation for each patch.
true_patch_var = torch.var(true_patch, dim=-1, keepdim=True, unbiased=False)
pred_patch_var = torch.var(pred_patch, dim=-1, keepdim=True, unbiased=False)
true_patch_std = torch.sqrt(true_patch_var)
pred_patch_std = torch.sqrt(pred_patch_var)
# Calculate Covariance between true and predicted patches.
true_pred_patch_cov = torch.mean((true_patch - true_patch_mean) * (pred_patch - pred_patch_mean), dim=-1, keepdim=True)
# 1. Calculate correlation loss (L_Corr) based on Equation (4).
# The formula for the Pearson Correlation Coefficient (PCC) is implemented here.
patch_linear_corr = (true_pred_patch_cov + 1e-5) / (true_patch_std * pred_patch_std + 1e-5)
linear_corr_loss = (1.0 - patch_linear_corr).mean()
# 2. Calculate variance loss (L_Var) based on Equation (6).
# This is KL(softmax(true) || softmax(pred)).
# Using log_softmax for the prediction is a standard, numerically stable way to compute KL divergence.
true_patch_softmax = torch.softmax(true_patch, dim=-1)
pred_patch_softmax = torch.log_softmax(pred_patch, dim=-1)
var_loss = self.kl_loss(pred_patch_softmax, true_patch_softmax).sum(dim=-1).mean()
# 3. Calculate mean loss (L_Mean) based on Equation (7).
# This is the Mean Absolute Error (MAE) between patch means.
mean_loss = torch.abs(true_patch_mean - pred_patch_mean).mean()
return linear_corr_loss, var_loss, mean_loss
def ps_loss(self, true, pred):
"""
Orchestrates the calculation of the final PS loss by combining its three main components.
Functionality and Paper Correspondence:
- This function follows the overall structure shown in Figure 2 of the paper.
- It first calls `fouriour_based_adaptive_patching` to segment the series (Step 1 in Figure 2).
- It then calls `patch_wise_structural_loss` to compute the individual loss components (Step 2).
- It uses `gradient_based_dynamic_weighting` to calculate the adaptive weights `alpha`, `beta`,
and `gamma` (Step 3).
- Finally, it computes the total `ps_loss` as the weighted sum of the three components, which
corresponds to Equation (8): L_PS = α*L_Corr + β*L_Var + γ*L_Mean.
"""
# Step 1: Fourier-based Adaptive Patching.
true_patch, pred_patch = self.fouriour_based_adaptive_patching(true, pred)
# Step 2: Calculate the three individual patch-wise structural loss components.
corr_loss, var_loss, mean_loss = self.patch_wise_structural_loss(true_patch, pred_patch)
# Step 3: Calculate adaptive weights for each loss component.
alpha, beta, gamma = self.gradient_based_dynamic_weighting(true, pred, corr_loss, var_loss, mean_loss)
# Final PS loss calculation, corresponding to Equation (8).
ps_loss = alpha * corr_loss + beta * var_loss + gamma * mean_loss
return ps_loss
def gradient_based_dynamic_weighting(self, true, pred, corr_loss, var_loss, mean_loss):
"""
Implements the Gradient-based Dynamic Weighting (GDW) strategy from Section 3.5.
This function dynamically balances the three loss components by adjusting their weights based on
their gradient magnitudes and the similarity between the true and predicted series.
Functionality and Paper Correspondence:
- Scaling Factors (`linear_sim`, `var_sim`): The code first calculates two similarity metrics
that correspond to the scaling factors `c` and `v` from Equation (12). These are used to
adjust the weight of the mean loss. `linear_sim` represents correlation similarity and `var_sim`
represents variance similarity.
- Gradient Calculation: It computes the gradient of each loss component with respect to the
parameters of a specific model layer (`self.model.Linear_Trend`). This corresponds to the
gradient calculation `∇_W L` in Equation (9).
- Weight Calculation (`alpha`, `beta`, `gamma`): The weights are calculated based on the L2-norm
of the gradients, which aligns with the methodology described in Section 3.5 and the formula
logic in Equation (11). Each weight is the ratio of the average gradient norm to the individual
component's gradient norm.
- Gamma Adjustment: The weight `gamma` (for the mean loss) is further scaled by the product of the
`linear_sim` and `var_sim` scores. This implements the paper's strategy to increase the
mean loss's influence as the model's predictions improve in terms of correlation and variance.
Implementation Details not in Paper:
- The gradients are calculated with respect to `self.model.Linear_Trend.parameters()`. The paper
generally refers to "the model's output layer parameters (W)". This specific layer name
implies that the code is tailored for a DLinear-style model backbone, which contains a
`Linear_Trend` component. This is a specific implementation choice not generalized in the paper.
- The use of `.detach()` is crucial for preventing the weight calculations from being part of the
computation graph for the final loss, ensuring that the weights act as static multipliers
in the current training step.
Discrepancy between Code and Paper:
- Equation (12) defines `c = (1 + σ_YY_hat) / (2 * σ_Y * σ_Y_hat)`. The code implements the
`linear_sim` factor as `(1.0 + linear_corr) * 0.5`. Assuming `linear_corr` is the PCC (`ρ`),
this matches the formula if `ρ = σ_YY_hat / (σ_Y * σ_Y_hat)`. This is a plausible implementation.
"""
# Permute dimensions to calculate statistics over the time dimension for the whole series.
true = true.permute(0, 2, 1)
pred = pred.permute(0, 2, 1)
# Calculate similarity metrics 'c' and 'v' from Equation (12) for the entire series.
# These will be used to scale the gamma weight.
true_mean = torch.mean(true, dim=-1, keepdim=True)
pred_mean = torch.mean(pred, dim=-1, keepdim=True)
true_var = torch.var(true, dim=-1, keepdim=True, unbiased=False)
pred_var = torch.var(pred, dim=-1, keepdim=True, unbiased=False)
true_std = torch.sqrt(true_var)
pred_std = torch.sqrt(pred_var)
true_pred_cov = torch.mean((true - true_mean) * (pred - pred_mean), dim=-1, keepdim=True)
# linear_sim corresponds to the 'c' factor in Equation (12).
linear_sim = (true_pred_cov + 1e-5) / (true_std * pred_std + 1e-5)
linear_sim = (1.0 + linear_sim) * 0.5 # Normalize to [0, 1]
# var_sim corresponds to the 'v' factor in Equation (12).
var_sim = (2*true_std*pred_std + 1e-5) / (true_var + pred_var + 1e-5)
# Gradient-based dynamic weighting, corresponds to Equations (9), (10), and (11).
# The paper mentions using the "output layer parameters", this implementation specifically uses
# parameters from 'Linear_Trend', suggesting it's designed for a DLinear-like backbone.
corr_gradient = torch.autograd.grad(corr_loss, self.model.Linear_Trend.parameters(), create_graph=True)[0]
var_gradient = torch.autograd.grad(var_loss, self.model.Linear_Trend.parameters(), create_graph=True)[0]
mean_gradient = torch.autograd.grad(mean_loss, self.model.Linear_Trend.parameters(), create_graph=True)[0]
# Calculate the average gradient magnitude as per Equation (10).
gradiant_avg = (corr_gradient + var_gradient + mean_gradient) / 3.0
# Calculate weights alpha, beta, and gamma as per Equation (11).
# .detach() is used to treat the calculated weights as constants for the current optimization step.
aplha = gradiant_avg.norm().detach() / corr_gradient.norm().detach()
beta = gradiant_avg.norm().detach() / var_gradient.norm().detach()
gamma = gradiant_avg.norm().detach() / mean_gradient.norm().detach()
# Scale gamma using the similarity scores, as described in Section 3.5.
gamma = gamma * torch.mean(linear_sim*var_sim).detach()
return aplha, beta, gamma