Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[devops] Upgrade to lightning 2.0 #1514

Merged
merged 26 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
26cb5bd
relax torch to greater 2
ourownstory Jan 16, 2024
6cac2bb
upgrade lightning to 2.0, open version limits of other packages
ourownstory Jan 16, 2024
35133f5
upgrade to python3.11
ourownstory Jan 17, 2024
32146f7
re-relax python versions
ourownstory Jan 17, 2024
4176a75
merge main
ourownstory Jan 17, 2024
2fd30b1
merge py3.11
ourownstory Jan 17, 2024
329931a
merge main
ourownstory Jan 17, 2024
1222282
Merge branch 'main' into upgrade-lightning-2
ourownstory Jan 17, 2024
b059658
Merge branch 'main' into upgrade-lightning-2
ourownstory Jan 17, 2024
5e0428d
upgrade to lightning 2+
MaiBe-ctrl Jun 19, 2024
293755e
Merge branch 'main' into upgrade-lightning-2
MaiBe-ctrl Jun 19, 2024
65caa47
fix toml file
MaiBe-ctrl Jun 19, 2024
7f62f38
fic poetry
MaiBe-ctrl Jun 19, 2024
7cc25c9
added kaleido
MaiBe-ctrl Jun 19, 2024
7f71169
downgrade numpy
MaiBe-ctrl Jun 19, 2024
2b2a060
fix linting
MaiBe-ctrl Jun 20, 2024
2001d8d
added python 3.12
MaiBe-ctrl Jun 20, 2024
6ebb274
clean up pyproject.toml dependencies
ourownstory Jun 21, 2024
a0f921a
update poetry lock
ourownstory Jun 21, 2024
cadcc7b
Merge branch 'main' into upgrade-lightning-2
ourownstory Jun 21, 2024
64b4e17
changed is True
MaiBe-ctrl Jun 21, 2024
c4773e9
changed bool check
MaiBe-ctrl Jun 21, 2024
cfbe96e
Merge branch 'main' into upgrade-lightning-2
ourownstory Jun 21, 2024
891ba53
uncomment test_glocal lines 152 onward
ourownstory Jun 21, 2024
0be90e7
Merge branch 'main' into upgrade-lightning-2
ourownstory Jun 21, 2024
c4037b0
Merge branch 'main' into upgrade-lightning-2
ourownstory Jun 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions neuralprophet/configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
import types
from collections import OrderedDict
from dataclasses import dataclass, field
from typing import Callable, Iterable, List, Optional
from typing import Callable, List, Optional
from typing import OrderedDict as OrderedDictType
from typing import Type, Union

import numpy as np
import pandas as pd
import torch

from neuralprophet import df_utils, np_types, utils, utils_torch
from neuralprophet import df_utils, np_types, utils_torch
from neuralprophet.custom_loss_metrics import PinballLoss
from neuralprophet.hdays_utils import get_holidays_from_country

Expand Down Expand Up @@ -305,7 +305,7 @@
log.error("Invalid growth for global_local mode '{}'. Set to 'global'".format(self.trend_global_local))
self.trend_global_local = "global"

if self.trend_local_reg < 0:

Check failure on line 308 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Operator "<" not supported for "None" (reportOptionalOperand)
log.error("Invalid negative trend_local_reg '{}'. Set to False".format(self.trend_local_reg))
self.trend_local_reg = False

Expand Down Expand Up @@ -354,13 +354,13 @@
log.error("Invalid global_local mode '{}'. Set to 'global'".format(self.global_local))
self.global_local = "global"

self.periods = OrderedDict(

Check failure on line 357 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

No overloads for "__init__" match the provided arguments (reportCallIssue)
{

Check failure on line 358 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Argument of type "dict[str, Season]" cannot be assigned to parameter "iterable" of type "Iterable[list[bytes]]" in function "__init__" (reportArgumentType)
"yearly": Season(
resolution=6,
period=365.25,
arg=self.yearly_arg,
global_local=(

Check failure on line 363 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Argument of type "SeasonGlobalLocalMode | Literal['auto']" cannot be assigned to parameter "global_local" of type "SeasonGlobalLocalMode" in function "__init__" (reportArgumentType)
self.yearly_global_local
if self.yearly_global_local in ["global", "local"]
else self.global_local
Expand All @@ -371,7 +371,7 @@
resolution=3,
period=7,
arg=self.weekly_arg,
global_local=(

Check failure on line 374 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Argument of type "SeasonGlobalLocalMode | Literal['auto']" cannot be assigned to parameter "global_local" of type "SeasonGlobalLocalMode" in function "__init__" (reportArgumentType)
self.weekly_global_local
if self.weekly_global_local in ["global", "local"]
else self.global_local
Expand All @@ -382,7 +382,7 @@
resolution=6,
period=1,
arg=self.daily_arg,
global_local=(

Check failure on line 385 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Argument of type "SeasonGlobalLocalMode | Literal['auto']" cannot be assigned to parameter "global_local" of type "SeasonGlobalLocalMode" in function "__init__" (reportArgumentType)
self.daily_global_local if self.daily_global_local in ["global", "local"] else self.global_local
),
condition_name=None,
Expand All @@ -390,7 +390,7 @@
}
)

if self.seasonality_local_reg < 0:

Check failure on line 393 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Operator "<" not supported for "None" (reportOptionalOperand)
log.error("Invalid negative seasonality_local_reg '{}'. Set to False".format(self.seasonality_local_reg))
self.seasonality_local_reg = False

Expand All @@ -410,7 +410,7 @@
resolution=resolution,
period=period,
arg=arg,
global_local=global_local if global_local in ["global", "local"] else self.global_local,

Check failure on line 413 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Argument of type "str" cannot be assigned to parameter "global_local" of type "SeasonGlobalLocalMode" in function "__init__"   Type "str" is incompatible with type "SeasonGlobalLocalMode"     "str" is incompatible with type "Literal['global']"     "str" is incompatible with type "Literal['local']"     "str" is incompatible with type "Literal['glocal']" (reportArgumentType)
condition_name=condition_name,
)

Expand Down Expand Up @@ -486,7 +486,7 @@
regressors: OrderedDict = field(init=False) # contains RegressorConfig objects

def __post_init__(self):
self.regressors = None

Check failure on line 489 in neuralprophet/configure.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot assign to attribute "regressors" for class "ConfigFutureRegressors*"   "None" is incompatible with "OrderedDict[Unknown, Unknown]" (reportAttributeAccessIssue)


@dataclass
Expand Down
14 changes: 7 additions & 7 deletions neuralprophet/custom_loss_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ def forward(self, outputs, target):
"""
target = target.repeat(1, 1, len(self.quantiles)) # increase the quantile dimension of the targets
differences = target - outputs
base_losses = self.loss_func(outputs, target) # dimensions - [n_batch, n_forecasts, no. of quantiles]
positive_losses = (
torch.tensor(self.quantiles, device=target.device).unsqueeze(dim=0).unsqueeze(dim=0) * base_losses
base_losses = self.loss_func(outputs, target).float() # dimensions - [n_batch, n_forecasts, no. of quantiles]
quantiles_tensor = (
torch.tensor(self.quantiles, device=target.device, dtype=torch.float32).unsqueeze(dim=0).unsqueeze(dim=0)
)
negative_losses = (
1 - torch.tensor(self.quantiles, device=target.device).unsqueeze(dim=0).unsqueeze(dim=0)
) * base_losses
positive_losses = quantiles_tensor * base_losses
negative_losses = (1 - quantiles_tensor) * base_losses
differences = differences.float()
pinball_losses = torch.where(differences >= 0, positive_losses, negative_losses)
multiplier = torch.ones(size=(1, 1, len(self.quantiles)), device=target.device)
multiplier = torch.ones(size=(1, 1, len(self.quantiles)), device=target.device, dtype=torch.float32)
multiplier[:, :, 0] = 2
pinball_losses = multiplier * pinball_losses # double the loss for the median quantile
return pinball_losses
14 changes: 9 additions & 5 deletions neuralprophet/forecaster.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import torch
from matplotlib import pyplot
from matplotlib.axes import Axes
from pytorch_lightning.tuner.tuning import Tuner
from torch.utils.data import DataLoader

from neuralprophet import configure, df_utils, np_types, time_dataset, time_net, utils, utils_metrics
Expand Down Expand Up @@ -1104,7 +1105,7 @@
# Only display the plot if the session is interactive, eg. do not show in github actions since it
# causes an error in the Windows and MacOS environment
if matplotlib.is_interactive():
fig

Check warning on line 1108 in neuralprophet/forecaster.py

View workflow job for this annotation

GitHub Actions / pyright

Expression value is unused (reportUnusedExpression)

self.fitted = True
return metrics_df
Expand Down Expand Up @@ -2756,6 +2757,8 @@
else:
self.model = self._init_model()

self.model.train_loader = train_loader

# Init the Trainer
self.trainer, checkpoint_callback = utils.configure_trainer(
config_train=self.config_train,
Expand All @@ -2780,8 +2783,9 @@
# Set parameters for the learning rate finder
self.config_train.set_lr_finder_args(dataset_size=dataset_size, num_batches=len(train_loader))
# Find suitable learning rate
lr_finder = self.trainer.tuner.lr_find(
self.model,
tuner = Tuner(self.trainer)
lr_finder = tuner.lr_find(
model=self.model,
train_dataloaders=train_loader,
val_dataloaders=val_loader,
**self.config_train.lr_finder_args,
Expand All @@ -2802,8 +2806,9 @@
# Set parameters for the learning rate finder
self.config_train.set_lr_finder_args(dataset_size=dataset_size, num_batches=len(train_loader))
# Find suitable learning rate
lr_finder = self.trainer.tuner.lr_find(
self.model,
tuner = Tuner(self.trainer)
lr_finder = tuner.lr_find(
model=self.model,
train_dataloaders=train_loader,
**self.config_train.lr_finder_args,
)
Expand Down Expand Up @@ -2831,7 +2836,6 @@

if not metrics_enabled:
return None

# Return metrics collected in logger as dataframe
metrics_df = pd.DataFrame(self.metrics_logger.history)
return metrics_df
Expand Down
1 change: 1 addition & 0 deletions neuralprophet/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class ProgressBar(TQDMProgressBar):
def __init__(self, *args, **kwargs):
self.epochs = kwargs.pop("epochs")
super().__init__(*args, **kwargs)
self.main_progress_bar = super().init_train_tqdm()

def on_train_epoch_start(self, trainer: "pl.Trainer", *_) -> None:
self.main_progress_bar.reset(self.epochs)
Expand Down
6 changes: 5 additions & 1 deletion neuralprophet/time_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,7 +795,8 @@ def training_step(self, batch, batch_idx):
scheduler.step()

# Manually track the loss for the lr finder
self.trainer.fit_loop.running_loss.append(loss)
self.log("train_loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True)
self.log("reg_loss", reg_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True)

# Metrics
if self.metrics_enabled:
Expand Down Expand Up @@ -983,6 +984,9 @@ def denormalize(self, ts):
ts = scale_y * ts + shift_y
return ts

def train_dataloader(self):
return self.train_loader


class FlatNet(nn.Module):
"""
Expand Down
7 changes: 1 addition & 6 deletions neuralprophet/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@
import os
import sys
from collections import OrderedDict
from typing import IO, TYPE_CHECKING, BinaryIO, Iterable, Optional, Union
from typing import IO, TYPE_CHECKING, BinaryIO, Optional, Union

import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch

from neuralprophet import utils_torch
from neuralprophet.hdays_utils import get_country_holidays
from neuralprophet.logger import ProgressBar

if TYPE_CHECKING:
Expand Down Expand Up @@ -375,7 +374,7 @@
seasonal_dims[name] = resolution
return seasonal_dims


Check warning on line 377 in neuralprophet/utils.py

View workflow job for this annotation

GitHub Actions / flake8

blank line contains whitespace
def config_events_to_model_dims(config_events: Optional[ConfigEvents], config_country_holidays):
"""
Convert user specified events configurations along with country specific
Expand Down Expand Up @@ -856,10 +855,6 @@
"""
config = config.copy()

# Enable Learning rate finder if not learning rate provided
if config_train.learning_rate is None:
config["auto_lr_find"] = True

# Set max number of epochs
if hasattr(config_train, "epochs"):
if config_train.epochs is not None:
Expand Down
Loading
Loading