check model
#Конфигурация модели
config = TimeSeriesTransformerConfig(
#длина прогноза
prediction_length=prediction_length,
# длина контекста:
context_length=context_length,
# лаг для расчета позиционного ембединга через get_lags_for_frequency:
lags_sequence=lags_sequence,
#количество временных признаков:
num_time_features=len(time_features) + 1,
# количество категориальных признаков:
num_static_categorical_features=1,
# размерность категориальных признаков, для бинарной классификации будет [2]:
cardinality=[2],
# для каждого категорильного признака задаем размерность ембедингов:
embedding_dimension=[2],
#Дропаут рейт и скейлинг
dropout_rate=0.2,
# scaling='std',
#Задаем степень свободы для распределения Стьюдента
num_parallel_samples = parallel_samples,
dof=parallel_samples-2,
def create_new_model():
model = TimeSeriesTransformerForPrediction(config)
code
return model
is that right to say that this decoder from transformer return array with points with prediction length len and then this layer project to 3 scalar (mean, std, dof), based on this values we create student distribution with prediction length len and then compare it with real distribution for each point with -LNN
Assistant
The explanation you have given seems generally correct with respect to the workflow of a time series transformer model that is designed to predict statistical parameters (mean, standard deviation, and degrees of freedom) of a Student's t-distribution for each time point in the prediction horizon. Here's a detailed breakdown to confirm your understanding:
Decoder Output:
The transformer decoder outputs an array with the shape corresponding to the prediction length and specific features for each time step in that prediction horizon.
Projection Layer:
This output is passed through a linear projection layer which maps each time point's features to three scalars: the mean, standard deviation, and degrees of freedom of the Student's t-distribution. Essentially, for each point in the prediction horizon, the model outputs these three parameters.
Student's t-Distribution:
Using the predicted mean, standard deviation, and degrees of freedom for each future time step, a Student's t-distribution is constructed.
Comparison with Real Distribution:
The predicted distribution is then compared with the actual observed data points. Typically, this could be done using a log-likelihood loss function (often referred to in the context of the negative log-likelihood, or NLL), comparing the predicted distribution with the observed values for each time step. The objective is to minimize this loss, thereby ensuring that the predicted distribution closely matches the real distribution of the sequence data.
So, your description aligns well with the actual steps involved in a time series forecasting model that uses transformers to predict distributional parameters. The negative log-likelihood loss function should indeed be used to evaluate how well the predicted Student's t-distribution matches the observed data.
However, a few technical points to correct or clarify:
Ensure that the "d_model" dimension aligns with the transformer architecture's requirements.
The degrees of freedom (dof) should typically be constrained to be greater than 2 for Student's t-distribution to ensure a valid distribution, which your code hints at by using parallel_samples-2.
The exact implementation of these steps might vary slightly based on the specific framework or library you're using for the transformer architecture.
Here is a reminder of the noteworthy parts of your configuration:
python
User
are you sure that model return array with prediction horizon and then for each step in horizen its project 3 values?
Assistant
Apologies for any confusion earlier. Let's clarify this in detail.
In a time series transformer model, typically, the decoder's job is to produce a sequence of predictions over the forecast horizon. For each time step in the forecast horizon, you might need the model to output a few different parameters that define the predictive distribution for that time step.
However, the decoder itself does not directly produce an array with these parameters. Instead, it typically outputs a hidden state representation for each time step, which then gets projected to the required parameters through a separate layer.
Here's a more precise step-by-step breakdown of how this process generally works:
Decoder Output:
The decoder outputs a sequence of hidden states, one for each time step in the forecast horizon. Let's denote this output as (\mathbf{H} = [\mathbf{h}_1, \mathbf{h}_2, \ldots, \mathbf{h}_T]), where (T) is the prediction horizon length.
Linear Projection (or Fully Connected Layer):
Each hidden state (\mathbf{h}_t) is then passed through one or more linear layers (projection layers) to produce the desired parameters of the output distribution. For a model predicting parameters of a Student's t-distribution, this would be the mean ((\mu_t)), standard deviation ((\sigma_t)), and degrees of freedom ((\nu_t)).
Formally, we apply transformations such as:
[
\mu_t = \mathbf{W}\mu \mathbf{h}t + \mathbf{b}\mu
]
[
\log \sigma_t = \mathbf{W}\sigma \mathbf{h}t + \mathbf{b}\sigma
]
[
\log \nu_t = \mathbf{W}\nu \mathbf{h}t + \mathbf{b}\nu
]
Here, (\mathbf{W}\mu), (\mathbf{W}\sigma), and (\mathbf{W}\nu) are weight matrices, and (\mathbf{b}\mu), (\mathbf{b}\sigma), and (\mathbf{b}_\nu) are biases. The logarithm ensures that (\sigma) and (\nu) are positive.
Generate Distribution:
With these parameters for each time step, we generate the Student's t-distribution for each point in the prediction horizon.
Loss Calculation:
The predicted distributions are then compared to the actual distributions of the historical data points using an appropriate loss function, such as the negative log-likelihood (NLL).
So, based on the descriptions above, the sequence of operations includes:
The decoder produces an array of hidden state vectors (each vector corresponds to a time step in the prediction horizon).
Each hidden state vector is passed through projection layers to output the mean, standard deviation, and degrees of freedom of the Student's t-distribution.
User
so when we do forward pass, first we put into model input shape and model return output shape in 1 step, this output shape before projection is equal to prediction horizon, but we project it into 3 values( mean, std, dof), them we return hidden state of model with prediction horizon into model, step over 1 step and proceed on next time point, then when we finished will all time step, we create a stundent's distribution for all time point and evaluate LNN via compute DFS and then log of that, then we add each log from time step into loss with minus sigh and this loss we will use in backpropagation
Assistant
Your understanding captures most of the key steps in the forward pass and evaluation of a time series transformer model predicting the parameters of a Student's t-distribution. Let's refine and summarize the process step by step:
Input to the Model:
You start by inputting a sequence (with the appropriate shape) into the model. This input includes your context sequence (the historical data points from which the model will generate predictions).
Transformation through Encoder and Decoder:
The ensemble of encoder and decoder components of the transformer processes the input sequence.
The decoder generates hidden state vectors for each time step in the prediction horizon.
Projection to Distribution Parameters:
Each hidden state vector from the decoder is projected into three scalars: the mean ((\mu)), the standard deviation (( \sigma )), and the degrees of freedom ((\nu)) of the Student's t-distribution.
These projections are usually done using linear layers.
Generate Distributions:
Using the predicted parameters (mean, std, dof), you create the Student's t-distribution for each time point in the prediction horizon.
Compute Negative Log-Likelihood (NLL) Loss:
With the predicted distributions, you calculate the log-likelihood of the observed data.
The negative log-likelihood (NLL) is then computed. Essentially, for each point in the prediction horizon, you compute the log-likelihood of the actual value under the predicted distribution, then take the negative.
Sum these log-likelihoods across all time points in the prediction horizon to get the total loss.
Backpropagation:
Use the computed total loss for backpropagation to update the model parameters.
Let's refine the code for clarity:
python
User
so how that we use parallel samples via training? is that our model n of parallel samples generate hidden state for each point and then we use agg function over each samples?
Assistant
Great question! When discussing parallel samples in the context of a time series model, it's important to understand how they are utilized during both training and inference.
Parallel Samples in Training:
The term "parallel samples" is often used in probabilistic forecasting to generate multiple forecast trajectories (or samples) in parallel from the model. This is particularly useful for capturing uncertainties in the predictions. In training, however, the concept is slightly different.
During training:
We typically do not use parallel samples directly. Instead, we focus on learning the parameters of the distributions (e.g., mean, std, dof for a Student's t-distribution) that will later be used to produce multiple samples during inference.
The model is trained on batches of data, where each batch contains multiple sequences (or time series) processed in parallel, but it does this independently for each sequence within the batch.
Parallel Samples in Inference:
During inference:
Once the model is trained, parallel samples can be used to draw multiple trajectories from the predictive distribution for each time step in the forecast horizon.
This involves sampling from the predicted distribution parameters (mean, std, dof) multiple times to generate various plausible future paths.
Here's how to incorporate the concept of parallel samples into the model during inference and not overcomplicate the training step:
Model Training: Train the model as usual by predicting the distribution parameters.
Model Inference with Parallel Samples:
During inference, use the learned parameters to generate multiple forecast samples.
Let's adapt the code to reflect generating parallel forecast samples during inference:
Training:
The training remains unchanged from the previous explanation. We do not need to concern ourselves with parallel samples during training.
Inference with Parallel Samples:
Generate multiple samples from the Student's t-distribution using the predicted parameters.
python
User
so via trainig we don't samples several times and on inferense we do
Assistant
Yes, that's correct! To summarize and further clarify:
Training Phase:
Objective: During the training phase, the model's primary goal is to learn the parameters of the predictive distributions (e.g., mean, standard deviation, degrees of freedom for a Student's t-distribution) based on the historical time series data.
No Multiple Sampling: During training, you do not generate multiple samples from the distribution. Instead, you focus on learning the distributional parameters by minimizing the negative log-likelihood (NLL) or another appropriate loss function that directly evaluates how well the predicted distribution fits the observed data.
Batch Processing: Training typically involves processing batches of historical sequences to update the model weights effectively. Each sequence in the batch is processed independently.
Inference Phase:
Objective: During the inference phase, you use the learned distributional parameters to generate forecasts.
Multiple Sampling: This is where you generate multiple forecast samples (trajectories) using the learned distribution parameters to capture the uncertainty in the predictions.
Parallel Samples: The model produces multiple plausible future paths by sampling from the predicted distributions for each time step in the forecast horizon, which helps in providing a probabilistic forecast rather than a single deterministic forecast.
Evaluating a probabilistic model by generating multiple parallel samples during each epoch can indeed be computationally expensive and time-consuming. To alleviate the computational burden while still achieving reliable validation, you can consider the following strategies:
Strategies:
Use a Subset for Validation:
Instead of generating samples for the entire validation dataset each epoch, select a smaller, representative subset of the validation dataset.
Perform the full evaluation (e.g., generate parallel samples) on this subset.
Staggered Full Validation:
Perform the full-scale validation (i.e., generate the full number of parallel samples) less frequently. For example, instead of evaluating every epoch, you can do so every N epochs.
During other epochs, perform a quick validation without multiple sampling, leveraging the predicted mean values.
Checkpoint Full Validation:
Save model checkpoints at regular intervals, and defer full validation to a post-training phase. This ensures no significant delays during the training loop.
Efficient Sampling:
Optimize the generation process by parallelizing the sampling step as much as possible. Utilize all available computational resources effectively.
Consider reducing the number of samples generated during training by sampling fewer paths for intermediate evaluations.
Below is an adapted version of your training code that incorporates these strategies. The goal is to balance the need for accurate validation with computational efficiency.
Adapted Training Code
Include Required Libraries
Make sure you have:
python
import numpy as np
import torch
from scipy.special import gammaln
from torch.optim import AdamW
from tqdm import tqdm
import os
import mlflow
import logging
Main Training Loop Adaptation
Update your train_model function to incorporate efficient validation:
python
User
is anything else to do quick validation? or maybe don't validate and just stop when training loss won't be changeable?
Assistant
Deciding when and how to perform validation during training requires balancing computational efficiency and the need for reliable progress tracking. Here are additional strategies and thoughts to consider:
Additional Strategies for Quick Validation
Early Stopping Based on Training Loss:
If the primary concern is overfitting, you can monitor the training loss and use it as a criterion for early stopping. This method, however, may not always be reliable since low training loss does not guarantee good generalization on validation data.
Smaller Validation Set:
Use a smaller validation set for quick validation. Although this might introduce some variance, it can still provide a reasonable check on generalization.
Validation on Sum of Log-Likelihoods:
Instead of generating multiple samples, you could directly validate using the sum of log-likelihoods (similar to negative log-likelihood used in training). This allows you to skip the sampling step and still get a sense of how well the model is performing in terms of fitting the distribution.
Gradient Checkpointing:
Use gradient checkpointing techniques to reduce memory usage and possibly speed up evaluation on larger models.
Adaptive Evaluation Frequency:
Start by evaluating more frequently in the early epochs when learning is more volatile, and reduce the frequency as training progresses and the model starts to converge.
Learning Rate Scheduler:
Use a learning rate scheduler that reduces the learning rate when a metric (e.g., training loss) plateaus. This can help in indirectly ensuring that the model converges before stopping.
Example of Early Stopping Based on Training Loss
Here is an approach that leverages training loss for early stopping while performing minimal validation checks:
python
User
and i can use forfard output from model on other dataset to get a loss, can't i
def evaluate_2(model, dataloader):
model.eval()
code
for batch in tqdm(dataloader):
with torch.no_grad():
outputs = model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
future_values=batch["future_values"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
future_observed_mask=batch["future_observed_mask"].to(device),
)
loss = outputs.loss
return loss.item()
Assistant
Yes, you can certainly use the forward pass output from your model on a validation dataset to compute a loss, which can be used for validation purposes. This approach avoids the computational expense of generating multiple samples during each validation step, while still providing a measure of how well the model is performing on unseen data.
In the function you provided evaluate_2, you're leveraging the forward pass output of the model to compute the loss. This loss can be directly used for validation without generating multiple samples. However, note that the implementation could be refined to aggregate the loss across all batches in the dataloader to get a single scalar value representing the average validation loss.
Here's an enhanced version of the evaluate_2 function, which aggregates the loss over all batches:
python
def evaluate_2(model, dataloader):
model.eval()
total_loss = 0.0
batch_count = 0
for batch in tqdm(dataloader, desc="Validating"):
with torch.no_grad():
outputs = model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
future_values=batch["future_values"].to(device), # Add this if future values are part of the input
past_observed_mask=batch["past_observed_mask"].to(device),
future_observed_mask=batch["future_observed_mask"].to(device),
)
loss = outputs.loss
total_loss += loss.item()
batch_count += 1
# Calculate average loss over all batches
avg_loss = total_loss / batch_count
return avg_loss
User
ok, when i try to generate, how much samples do i need to use?
Assistant
The number of samples you generate during inference when using a probabilistic model depends on several factors, including the desired accuracy of your forecasts, the computational resources available, and the specific requirements of your application (e.g., whether you need highly detailed probability distributions or just a rough estimate).
General Guidelines for Number of Samples
Baseline: Start with 100 samples.
This is typically a good starting point and provides a balance between accuracy and computational efficiency.
High-Accuracy Applications:
For applications requiring high accuracy in probability distributions, consider using 500 to 1000 samples.
This can be especially important when dealing with rare events or systems where uncertainty is a critical factor.
Resource Constraints:
If computational resources are limited, you can reduce the number of samples. Even 20-50 samples can still provide a reasonable estimate of the distribution.
Keep in mind that fewer samples might lead to less accurate representations of the predictive distribution.
Adaptive Sampling:
Use an adaptive approach where you start with a smaller number of samples and increase if necessary based on the quality of the results. This can be done iteratively during development.
Example Usage in Code
Assuming you decide to start with 100 samples, your inference function could look something like this:
def create_new_model():
model = TimeSeriesTransformerForPrediction(config)
return model
You might want to ensure other parts of your model pipeline (data preprocessing, model training, etc.) are correctly set up to complement this configuration, particularly how you handle distributions and your choice of loss function for training the model.
These parameters are used to form the predictive distributions for each time step in the prediction horizon.
Technically, the decoder outputs hidden representations for each point in the horizon, and these are then transformed (projected) to the required parameters (mean, std, dof) for each time point separately.
Here is an example code snippet to reflect this process:
python
import torch
import torch.nn as nn
class TimeSeriesTransformerForPrediction(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# Simplified example: assume self.decoder is implemented elsewhere
self.decoder = nn.Transformer(d_model=config.d_model, num_decoder_layers=config.decoder_layers)
# Linear layers to project the hidden state vectors to parameters of the Student's t-distribution
self.mean_projection = nn.Linear(config.d_model, 1) # Mean prediction
self.log_std_projection = nn.Linear(config.d_model, 1) # Log of std, to ensure it's positive
self.log_dof_projection = nn.Linear(config.d_model, 1) # Log of dof, to ensure it's positive
def forward(self, x):
# Assume x is the input sequence, and we get hidden states from the decoder
hidden_states = self.decoder(x)
# Project hidden states to mean, log_std, and log_dof
means = self.mean_projection(hidden_states)
log_stds = self.log_std_projection(hidden_states)
log_dofs = self.log_dof_projection(hidden_states)
stds = torch.exp(log_stds)
dofs = torch.exp(log_dofs) + 2 # Ensure dof > 2
return means, stds, dofs
# Example configuration instance
config = TimeSeriesTransformerConfig(
prediction_length=10,
context_length=20,
lags_sequence=[1, 2, 3],
num_time_features=5,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
dropout_rate=0.2,
num_parallel_samples=100,
dof=98, # Just an example value
encoder_layers=4,
decoder_layers=4,
d_model=64,
)
# Model creation example
model = TimeSeriesTransformerForPrediction(config)
In summary, the decoder itself produces a hidden state for each time step, and these hidden states are then projected to the desired output parameters. The points in the prediction horizon are thus "decoded" step by step, each producing the parameters for a Student's t-distribution.
import torch
import torch.nn as nn
import torch.distributions as dist
class TimeSeriesTransformerForPrediction(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.encoder = nn.TransformerEncoder(nn.TransformerEncoderLayer(d_model=config.d_model, nhead=4), num_layers=config.encoder_layers)
self.decoder = nn.TransformerDecoder(nn.TransformerDecoderLayer(d_model=config.d_model, nhead=4), num_layers=config.decoder_layers)
self.mean_projection = nn.Linear(config.d_model, 1)
self.log_std_projection = nn.Linear(config.d_model, 1)
self.log_dof_projection = nn.Linear(config.d_model, 1)
def forward(self, x):
# Encoder processes the input context sequence
memory = self.encoder(x)
# Initializing the decoder input; assume initial input sequence given
decoder_input = x[-1].unsqueeze(0)
hidden_states = []
for _ in range(self.config.prediction_length):
# Decoder processes the previous outputs
hs = self.decoder(decoder_input, memory)
hidden_states.append(hs[-1])
# Prepare input for next step by appending new hs[-1] to decoder_input
decoder_input = torch.cat((decoder_input, hs[-1].unsqueeze(0)), dim=0)
hidden_states = torch.cat(hidden_states, dim=0).transpose(0, 1) # Shape should be [batch_size, prediction_length, d_model]
means = self.mean_projection(hidden_states) # Shape: [batch_size, prediction_length, 1]
log_stds = self.log_std_projection(hidden_states) # Shape: [batch_size, prediction_length, 1]
log_dofs = self.log_dof_projection(hidden_states) # Shape: [batch_size, prediction_length, 1]
stds = torch.exp(log_stds)
dofs = torch.exp(log_dofs) + 2 # Ensures dof > 2
return means, stds, dofs
def negative_log_likelihood_loss(means, stds, dofs, targets):
nll_loss = 0
for t in range(means.size(1)):
dist_t = dist.StudentT(df=dofs[:, t], loc=means[:, t], scale=stds[:, t])
log_prob = dist_t.log_prob(targets[:, t])
nll_loss += -log_prob.mean()
return nll_loss
# Example configuration and model instantiation
config = TimeSeriesTransformerConfig(
prediction_length=10,
context_length=20,
lags_sequence=[1, 2, 3],
num_time_features=5,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
dropout_rate=0.2,
num_parallel_samples=100,
dof=98,
encoder_layers=4,
decoder_layers=4,
d_model=64,
)
model = TimeSeriesTransformerForPrediction(config)
# Example usage
inputs = torch.randn(config.context_length, 32, config.d_model) # [context_length, batch_size, d_model]
targets = torch.randn(32, config.prediction_length) # [batch_size, prediction_length]
means, stds, dofs = model(inputs)
loss = negative_log_likelihood_loss(means, stds, dofs, targets)
# Perform backpropagation
loss.backward()
Key Points:
Decoder Sequence Generation: Hidden states at each step are fed into the decoder until the entire prediction horizon is covered.
Parameter Projection: Hidden states are projected to parameters of the Student's t-distribution.
Log-Likelihood Computation: Calculate the log-likelihood of the true values under the predicted distributions to generate a loss.
Backpropagation: The negative log-likelihood loss is then used to perform backpropagation.
This refined explanation and code align with the process you described, ensuring each step in the prediction horizon is correctly handled and the loss computed for model training.
Training: Focuses on learning the distribution parameters (means, stds, dofs). No direct involvement of parallel samples.
Inference:
Generate Parallel Samples: Create multiple forecast trajectories by sampling from the predicted distributions (using the generated parameters).
This involves calling the generate_parallel_samples method during inference to produce multiple future paths.
Negative Log-Likelihood Loss: Standard loss calculation during training remains unchanged.
By generating multiple samples during inference, you can obtain a diverse set of possible future outcomes, capturing the uncertainty inherently. This method yields a comprehensive forecasting framework that is capable of probabilistic predictions.
Here's an example that outlines how you can implement the training and inference phases, emphasizing when and where the sampling takes place:
python
import torch
import torch.nn as nn
import torch.distributions as dist
class TimeSeriesTransformerForPrediction(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.encoder = nn.TransformerEncoder(
nn.TransformerEncoderLayer(d_model=config.d_model, nhead=4), num_layers=config.encoder_layers)
self.decoder = nn.TransformerDecoder(
nn.TransformerDecoderLayer(d_model=config.d_model, nhead=4), num_layers=config.decoder_layers)
self.mean_projection = nn.Linear(config.d_model, 1)
self.log_std_projection = nn.Linear(config.d_model, 1)
self.log_dof_projection = nn.Linear(config.d_model, 1)
def forward(self, x):
memory = self.encoder(x)
decoder_input = x[-1].unsqueeze(0)
hidden_states = []
for _ in range(self.config.prediction_length):
hs = self.decoder(decoder_input, memory)
hidden_states.append(hs[-1])
decoder_input = torch.cat((decoder_input, hs[-1].unsqueeze(0)), dim=0)
hidden_states = torch.cat(hidden_states, dim=0).transpose(0, 1)
means = self.mean_projection(hidden_states)
log_stds = self.log_std_projection(hidden_states)
log_dofs = self.log_dof_projection(hidden_states)
stds = torch.exp(log_stds)
dofs = torch.exp(log_dofs) + 2
return means, stds, dofs
def generate_parallel_samples(self, means, stds, dofs, n_samples):
batch_size, prediction_length = means.shape[:2]
samples = []
for _ in range(n_samples):
sample_batch = []
for t in range(prediction_length):
dist_t = dist.StudentT(df=dofs[:, t], loc=means[:, t], scale=stds[:, t])
sample_batch.append(dist_t.sample())
samples.append(torch.stack(sample_batch, dim=1))
return torch.stack(samples, dim=1) # Shape: [batch_size, n_samples, prediction_length]
def negative_log_likelihood_loss(means, stds, dofs, targets):
nll_loss = 0
for t in range(means.size(1)):
dist_t = dist.StudentT(df=dofs[:, t], loc=means[:, t], scale=stds[:, t])
log_prob = dist_t.log_prob(targets[:, t])
nll_loss += -log_prob.mean()
return nll_loss
# Configuration instance
config = TimeSeriesTransformerConfig(
prediction_length=10,
context_length=20,
lags_sequence=[1, 2, 3],
num_time_features=5,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
dropout_rate=0.2,
num_parallel_samples=100,
dof=98,
encoder_layers=4,
decoder_layers=4,
d_model=64,
)
# Model instantiation
model = TimeSeriesTransformerForPrediction(config)
# Example data for training
inputs = torch.randn(config.context_length, 32, config.d_model) # [context_length, batch_size, d_model]
targets = torch.randn(32, config.prediction_length) # [batch_size, prediction_length]
# Forward pass during training
means, stds, dofs = model(inputs)
loss = negative_log_likelihood_loss(means, stds, dofs, targets)
# Backpropagation
loss.backward()
# Inference with parallel samples
n_samples = config.num_parallel_samples
parallel_samples = model.generate_parallel_samples(means, stds, dofs, n_samples)
Key Takeaways:
Training Phase:
Focus on learning the distribution parameters (mean, std, dof) with no multiple sampling involved.
Use negative log-likelihood loss for model training.
Inference Phase:
Generate multiple samples (parallel samples) from the predicted distribution to capture the uncertainty in forecasts.
Use these samples to provide probabilistic forecasts.
This approach ensures that you efficiently train your model and utilize parallel samples during inference to produce robust probabilistic forecasts.
with mlflow.start_run(experiment_id=experiment_id, run_name=run_name):
mlflow.log_param("num_epoch", num_epoch)
mlflow.log_param("batch_size", batch_size)
mlflow.log_param("numbers_of_validation_batches", num_val_batches)
mlflow.log_param("model_architecture", str(create_new_model()))
filename = 'all_dataframe'
# for filename in tqdm(os.listdir(work_signals_path)):
# file_path = os.path.join(work_signals_path, filename)
# if os.path.isfile(file_path) and filename.endswith('.csv'):
# df = pd.read_csv(file_path)
# df.rename(columns={'Unnamed: 0': 'Время'}, inplace=True)
# df[['Статус АВРЧМ', 'Признак по уставке', 'hour', 'day_of_week']] = df[['Статус АВРЧМ', 'Признак по уставке', 'hour', 'day_of_week']].astype(int)
# df = transform_dataframe(df)
# # Проверка условия для детекции выбросов
# condition_met = df['07MAA10CT001'].max() <= global_upper_bound and df['07MAA10CT001'].min() >= global_lower_bound
# if condition_met:
# continue
df = transform_dataframe(df)
dataset = create_dataset_func(df, context_length, step_in_dataset, prediction_length, separation)
dataset.set_transform(partial(transform_start_field, freq=time_freq))
train_dataloader = create_train_val_dataloader(config, time_freq, dataset['train'], batch_size, name='train')
val_dataloader = create_train_val_dataloader(config, time_freq, dataset['test'], batch_size, name='validation')
try:
old_model = create_new_model()
old_model.load_state_dict(torch.load(best_model_path))
logging.info(f"Веса лучшей модели восстановлены: {best_model_path}")
except Exception:
logging.error("Не найдена лучшая модель в директории")
logging.info(f'Старт обучения модели на датафрейме в папке {work_signals_path} с файлом {filename}')
train_model(num_epoch, num_val_batches, train_dataloader, val_dataloader, dataset['test'], best_model_path, filename)
# train_model_with_replay_and_ewc(num_epoch,
# num_val_batches,
# train_dataloader,
# val_dataloader,
# dataset['validation'],
# best_model_path,
# filename,
# anomaly_files,
# global_lower_bound,
# global_upper_bound)
logging.info(f'Закончено обучения модели на датафрейме в папке {work_signals_path} с файлом № {filename}')
trainable_df_counter += 1
try:
old_model = create_new_model()
old_model.load_state_dict(torch.load(best_model_path))
logging.info(f"Веса лучшей модели восстановлены: {best_model_path}")
mlflow.log_artifact(model_path)
except Exception:
logging.error("Не найдена лучшая модель в директории")
mlflow.end_run()
MLFLOW = False
logging.info(f'В обучении использовано {trainable_df_counter} датафреймов с данными')
old_model
so as you see i need each epoch to evaluate (e.g. generate n of samples for my data) what could you suggest with that (evaluatin via generation n of samples is very expansive)
evaluate_quick: A quicker evaluation method that uses only the mean (avoiding generating multiple samples). This is used during intermediate epochs to save computational time.
evaluate: The full evaluation with multiple sample generations, used less frequently to keep track of model performance comprehensively.
Reduced Frequency of Full Validation:
Perform the full validation (with full sample generation) less frequently, such as every 10 epochs, to ensure training progresses efficiently.
Use the quicker validation method in other epochs to keep track of model performance without incurring high computational costs.
This approach balances the need for rigorous validation with the computational constraints, ensuring that your training process remains efficient without sacrificing model evaluation quality.
def train_model_with_training_loss_stop(num_epoch,
num_val_batches,
train_dataloader,
val_dataloader,
val_dataset,
old_model_path,
filename,
patience=10,
min_delta=1e-4):
best_train_loss = np.inf
new_model = create_new_model()
new_model.to(device)
optimizer = AdamW(new_model.parameters(), lr=1e-4, betas=(0.9, 0.98), weight_decay=1e-2)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=10, factor=0.5)
early_stopping = CustomEarlyStoppingCallback(patience=patience, min_delta=min_delta, verbose=True)
new_model, optimizer, train_dataloader = accelerator.prepare(new_model, optimizer, train_dataloader)
temp_path = f'{old_model_path}_temp'
new_model.train()
no_improvement_count = 0
for epoch in tqdm(range(num_epoch)):
epoch_train_loss = 0
for idx, batch in enumerate(train_dataloader):
optimizer.zero_grad()
outputs = new_model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
future_values=batch["future_values"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
future_observed_mask=batch["future_observed_mask"].to(device),
)
loss = outputs.loss
epoch_train_loss += loss.item()
accelerator.backward(loss)
optimizer.step()
if idx % 100 == 0:
print(f"Epoch {epoch + 1}, Step {idx + 1}, LNN Loss: {loss.item()}")
epoch_train_loss /= len(train_dataloader)
# Storage of the temporary best model
if epoch_train_loss < best_train_loss - min_delta:
best_train_loss = epoch_train_loss
no_improvement_count = 0
best_temp_model_path = os.path.join(os.getcwd(), temp_path)
torch.save(new_model.state_dict(), best_temp_model_path)
else:
no_improvement_count += 1
if no_improvement_count >= patience:
print("Stopping due to no improvement in training loss.")
torch.save(new_model.state_dict(), old_model_path)
break
# Reduce learning rate once no improvement
scheduler.step(epoch_train_loss)
# Occasionally do a full validation
if epoch % 10 == 0:
val_loss_nll = evaluate(new_model, val_dataloader, val_dataset, num_val_batches)
mlflow.log_metric(f"Val_loss LNN {filename} датафрейм", val_loss_nll, step=epoch)
logging.info(f"Epoch {epoch + 1}, Training LNN Loss: {epoch_train_loss}")
mlflow.log_metric(f"Training Loss -LNN {filename}", epoch_train_loss, step=epoch)
torch.save(new_model.state_dict(), old_model_path)
In this modified training loop:
Training Loss Monitoring: The training loss is used for early stopping. If there's no significant improvement in training loss for a set number of epochs (patience), training stops.
Occasional Full Validation: Perform full validation less frequently (e.g., every 10 epochs) to ensure the model's generalization.
Additional Considerations
Post-Training Validation:
After training, you can perform a thorough validation using the best model saved during training. This ensures you have a robust evaluation without affecting the training efficiency.
Interim Models:
Save interim models periodically (e.g., best models based on training loss) and perform full validation in a separate process or script.
Hybrid Approach:
Combine quick validation strategies with occasional full validations to ensure reliability. For example:
python
for epoch in tqdm(range(num_epoch)):
... # Training loop
# Quick validation every epoch or few epochs
if epoch % 2 == 0:
val_loss_nll_quick = evaluate_quick(new_model, val_dataloader, val_dataset, num_val_batches//2)
# Full validation less frequently
if epoch % 10 == 0:
val_loss_nll_full = evaluate(new_model, val_dataloader, val_dataset, num_val_batches)
By applying these strategies, you can remain efficient in your training loop while ensuring the model is periodically validated to detect overfitting and generalization issues.
Integration in Training Loop
You can integrate this function into your training loop to periodically compute the validation loss:
python
def train_model_with_training_loss_stop(num_epoch,
num_val_batches,
train_dataloader,
val_dataloader,
val_dataset,
old_model_path,
filename,
patience=10,
min_delta=1e-4):
best_train_loss = np.inf
new_model = create_new_model()
new_model.to(device)
optimizer = AdamW(new_model.parameters(), lr=1e-4, betas=(0.9, 0.98), weight_decay=1e-2)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=10, factor=0.5)
early_stopping = CustomEarlyStoppingCallback(patience=patience, min_delta=min_delta, verbose=True)
new_model, optimizer, train_dataloader = accelerator.prepare(new_model, optimizer, train_dataloader)
temp_path = f'{old_model_path}_temp'
new_model.train()
no_improvement_count = 0
for epoch in tqdm(range(num_epoch)):
epoch_train_loss = 0
for idx, batch in enumerate(train_dataloader):
optimizer.zero_grad()
outputs = new_model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
future_values=batch["future_values"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
future_observed_mask=batch["future_observed_mask"].to(device),
)
loss = outputs.loss
epoch_train_loss += loss.item()
accelerator.backward(loss)
optimizer.step()
if idx % 100 == 0:
print(f"Epoch {epoch + 1}, Step {idx + 1}, LNN Loss: {loss.item()}")
epoch_train_loss /= len(train_dataloader)
# Storage of the temporary best model
if epoch_train_loss < best_train_loss - min_delta:
best_train_loss = epoch_train_loss
no_improvement_count = 0
best_temp_model_path = os.path.join(os.getcwd(), temp_path)
torch.save(new_model.state_dict(), best_temp_model_path)
else:
no_improvement_count += 1
if no_improvement_count >= patience:
print("Stopping due to no improvement in training loss.")
torch.save(new_model.state_dict(), old_model_path)
break
# Reduce learning rate once no improvement
scheduler.step(epoch_train_loss)
# Occasionally do a full validation
if epoch % 10 == 0:
val_loss_nll = evaluate_2(new_model, val_dataloader)
mlflow.log_metric(f"Val_loss LNN {filename} датафрейм", val_loss_nll, step=epoch)
logging.info(f"Epoch {epoch + 1}, Training LNN Loss: {epoch_train_loss}")
mlflow.log_metric(f"Training Loss -LNN {filename}", epoch_train_loss, step=epoch)
torch.save(new_model.state_dict(), old_model_path)
Points to Note:
Forward Pass: The evaluate_2 function uses the forward pass to compute the loss on the validation set without sampling multiple trajectories, making it quicker.
Average Loss Calculation: The loss is averaged over all batches to provide a single value that summarizes the model performance on the validation dataset.
Periodic Validation: The main training loop integrates this quick validation every 10 epochs (or other suitable frequency) to monitor performance.
Early Stopping: The training loop incorporates early stopping based on improvements in training loss, with periodic (less frequent) validation checks.
This strategy ensures efficient training while still monitoring the model's validation performance periodically, helping you strike the right balance between computational expense and validation thoroughness.
def generate_forecasts(model, dataloader, num_samples=100):
model.eval()
forecasts_samples = []
for batch in tqdm(dataloader, desc="Generating Forecasts"):
with torch.no_grad():
outputs = model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
)
means = outputs[0]
stds = outputs[1]
dofs = outputs[2]
# Generate parallel samples
samples = model.generate_parallel_samples(means, stds, dofs, num_samples)
forecasts_samples.append(samples)
forecasts_samples = torch.cat(forecasts_samples, dim=0) # Shape should be [total_batches * batch_size, num_samples, prediction_length]
return forecasts_samples
# Example usage of the function
num_samples = 100
forecasts_samples = generate_forecasts(model, inference_dataloader, num_samples=num_samples)
Considerations:
Evaluating Samples:
After generating the samples, you might want to analyze metrics like mean, standard deviation, percentiles, etc., over the generated samples to summarize the forecast distributions.
Memory Usage:
Generating a large number of samples can consume significant memory, so ensure your system has enough resources to handle this.
Adjust Based on Results:
Start with a baseline (e.g., 100 samples) and evaluate the output. If the uncertainty estimates aren't detailed enough or if there are visible artifacts in the predictions, increase the number of samples.
Example Evaluation Function
Here's how you might perform the evaluation with these generated forecasts:
python
def evaluate_forecasts(forecasts_samples, targets):
"""
Evaluate the generated forecast samples against the true values.
Args:
- forecasts_samples: Tensor of shape [num_batches * batch_size, num_samples, prediction_length]
- targets: Tensor of shape [num_batches * batch_size, prediction_length]
Returns:
- Evaluation metrics (e.g., mean negative log-likelihood)
"""
total_nll = 0
num_points = 0
for i, target in enumerate(targets):
sample_means = forecasts_samples[i].mean(dim=0)
sample_stds = forecasts_samples[i].std(dim=0)
sample_dofs = model.config.dof
nll = negative_log_likelihood_student_t(
torch.tensor(sample_means),
torch.tensor(target),
torch.tensor(sample_stds),
torch.tensor(sample_dofs)
)
total_nll += nll
num_points += 1
return total_nll / num_points
# Assuming forecasts_samples and true_targets are ready
true_targets = torch.stack([ts["target"][-prediction_length:] for ts in val_dataset])
mean_nll = evaluate_forecasts(forecasts_samples, true_targets)
print(f"Mean Negative Log-Likelihood: {mean_nll}")
This process ensures that you are validating the probabilistic forecasts effectively, and the number of samples used can be adjusted based on the precision required and the computational resources available. Starting with a baseline and adapting as necessary is a pragmatic approach.