← Back to Pull requests

[ENH] Add `forecaster` support and remove `_pkg` class for new API #2434

Open
phoeenniixx opened this pull request with 4335 lines diff across 60 files
View on GitHub
phoeenniixx phoeenniixx commented on Sep 20, 2026 13:05 UTC
Author

Adds forecaster class as per #2407
stacks on #2423

Note


Need to change the target branch (even in workflow) once the base branch is merged (Datamodule).

Stack


  • TimeSeries - #2410

  • Datamodule - #2423

  • Forecaster - #2434 <- This PR
  • (Still a WiP, I will update the desc once all the changes etc are made)

    Diff: 4335 lines (+2807 / -1528) across 60 files Reviewer: phoeenniixx Review duration: 52091m
    All Vouch review confidence checks passed
    Residual risk 0.16 = Change Risk (0.93) × (1 − Review Confidence (0.83)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.93 · 4335 lines diff across 60 files
    0.93
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    82%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    18 items
    phoeenniixx phoeenniixx commented on code on Sep 28, 2026 11:55 UTC
    Code Review
    .github/workflows/test.yml:1
    @@ -5,9 +5,9 @@ name: Test
     
     on:
       push:
    -    branches: [v2-dev]
    +    branches: [dm]

    need to change this once #2423 is merged!

    codecov[bot] codecov[bot] commented on Sep 28, 2026 12:54 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 95.04021% with 37 lines in your changes missing coverage. Please review.
    :warning: Please upload report for BASE (v2-dev@4c9d6bd). Learn more about missing BASE report.

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | ...ytorch\_forecasting/models/base/\_base\_forecaster.py | 78.97% | 37 Missing :warning: |

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff            @@
    ##             v2-dev    #2434   +/-   ##
    =========================================
      Coverage          ?   88.41%           
    =========================================
      Files             ?      202           
      Lines             ?    11683           
      Branches          ?        0           
    =========================================
      Hits              ?    10329           
      Misses            ?     1354           
      Partials          ?        0           
    

    | Flag | Coverage Δ | |
    |---|---|---|
    | cpu | 88.41% <95.04%> (?) | |
    | pytest | 88.41% <95.04%> (?) | |

    Flags with carried forward coverage won't be shown. Click here to find out more.
    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    phoeenniixx phoeenniixx commented on Oct 04, 2026 13:26 UTC
    Author

    Few open Questions:

  • Should we add inverse transform feat in this PR or in new PR (will need some updates to ScalerAdapter etc)

  • Should mode=="raw" also be somehow wrapped inside TimeSeries or should we move it to predict_raw() or similar method? And we remove mode param. predict give 2D preds, predict_quantile in quantiles etc...

  • We also need to think of the shape of data - we return 3D tensors and a list of tensors for multi-target in forward(), i.e, the raw preds are 3D or a list of 3D tensors. I think for a cleaner design we should move to 4D tensors? To prevent isinstance checks everywhere to differentiate between single target and multi-target cases?

  • We need to update the serialization in v2 (see #2323) as #2323 is not merged, should move those changes to this PR (or some PR stacked on this?) as this change would make changes to BaseForecaster and Datamodules etc anyway!
  • phoeenniixx phoeenniixx commented on Oct 08, 2026 18:32 UTC
    Author

    still need to update docs/notebooks. As we are already on a large diff here, i think we should do this in another PR?

    CloseChoice CloseChoice commented on code on Oct 09, 2026 13:42 UTC
    Code Review
    pytorch_forecasting/models/frets/_frets_forecaster_v2.py:1
    @@ -0,0 +1,204 @@
    +"""FreTS forecaster."""
    +
    +from pathlib import Path
    +from typing import Any
    +
    +from lightning.pytorch import Trainer
    +from torch import nn
    +from torch.optim import Optimizer
    +
    +from pytorch_forecasting.models.base._base_forecaster import BaseForecaster
    +
    +
    +class FreTSForecaster(BaseForecaster):
    +    """FreTS forecaster (v2).
    +
    +    Parameters
    +    ----------
    +    embed_size : int, default=128
    +        Dimension of the learnable token embedding.
    +    hidden_size : int, default=256
    +        Hidden size of the FC output head.
    +    channel_independence : bool, default=True
    +        If True, each channel is processed independently (only temporal
    +        frequency mixing). If False, cross-channel frequency mixing is
    +        applied first.
    +    sparsity_threshold : float, default=0.01
    +        Soft-shrinkage threshold for frequency coefficient sparsity.
    +    loss : Metric, optional
    +        Loss to optimise. Defaults to
    +        :class:`~pytorch_forecasting.metrics.MAE`.
    +    logging_metrics : list of nn.Module, optional
    +        Additional metrics logged during training and validation.
    +    optimizer : Optimizer or str, optional
    +        Optimizer used for training. Default is ``"adam"``.
    +    optimizer_params : dict, optional
    +        Parameters forwarded to the optimizer constructor.
    +    lr_scheduler : str, optional
    +        Learning rate scheduler name.
    +    lr_scheduler_params : dict, optional
    +        Parameters forwarded to the LR scheduler constructor.
    +    trainer : lightning.pytorch.Trainer, optional
    +        See :class:`~pytorch_forecasting.models.base.BaseForecaster`.
    +    datamodule : EncoderDecoderTimeSeriesDataModule, optional
    +        Configured, data-less datamodule. See
    +        :class:`~pytorch_forecasting.models.base.BaseForecaster`.
    +    ckpt_path : str or Path, optional
    +        See :class:`~pytorch_forecasting.models.base.BaseForecaster`.
    +    """
    +
    +    _tags = {
    +        "info:name": "FreTS",
    +        "info:compute": 2,
    +        "info:y_type": ["numeric"],
    +        "authors": ["echo-xiao"],
    +        "capability:exogenous": True,
    +        "capability:multivariate": True,
    +        "capability:pred_int": False,
    +        "capability:flexible_history_length": False,
    +        "capability:cold_start": False,
    +    }
    +
    +    def __init__(
    +        self,
    +        embed_size: int = 128,
    +        hidden_size: int = 256,
    +        channel_independence: bool = True,
    +        sparsity_threshold: float = 0.01,
    +        loss: nn.Module | None = None,
    +        logging_metrics: list[nn.Module] | None = None,
    +        optimizer: Optimizer | str | None = "adam",
    +        optimizer_params: dict | None = None,
    +        lr_scheduler: str | None = None,
    +        lr_scheduler_params: dict | None = None,
    +        trainer: Trainer | None = None,
    +        datamodule: Any = None,
    +        ckpt_path: str | Path | None = None,
    +    ):
    +        self.embed_size = embed_size
    +        self.hidden_size = hidden_size
    +        self.channel_independence = channel_independence
    +        self.sparsity_threshold = sparsity_threshold
    +        self.loss = loss
    +        self.logging_metrics = logging_metrics
    +        self.optimizer = optimizer
    +        self.optimizer_params = optimizer_params
    +        self.lr_scheduler = lr_scheduler
    +        self.lr_scheduler_params = lr_scheduler_params
    +        self.trainer = trainer
    +        self.datamodule = datamodule
    +        self.ckpt_path = ckpt_path
    +        super().__init__(
    +            trainer=self.trainer, datamodule=self.datamodule, ckpt_path=self.ckpt_path
    +        )
    +
    +    @classmethod
    +    def get_cls(cls):
    +        """Get model class.
    +
    +        Returns
    +        -------
    +        FreTS : type
    +            The model class.
    +        """
    +        from pytorch_forecasting.models.frets._frets_v2 import FreTS
    +
    +        return FreTS
    +
    +    @classmethod
    +    def get_datamodule_cls(cls):
    +        """Get datamodule class used for training.
    +
    +        Returns
    +        -------
    +        EncoderDecoderTimeSeriesDataModule : type
    +            The datamodule class.
    +        """
    +        from pytorch_forecasting.data.data_module import (
    +            EncoderDecoderTimeSeriesDataModule,
    +        )
    +
    +        return EncoderDecoderTimeSeriesDataModule
    +
    +    def get_model_params(self) -> dict[str, Any]:
    +        """Kwargs for ``get_cls()``, with ``None`` sentinels resolved."""
    +        from pytorch_forecasting.metrics import MAE

    I think either we put the import to the top of the file or we should import it only if necessary:

    if self.loss is None:
                from pytorch_forecasting.metrics import MAE
                loss = MAE()
    ...
    return dict(...,
                 loss=self.loss or loss,
                 ...)
    

    CloseChoice CloseChoice commented on code on Oct 09, 2026 13:43 UTC
    Code Review
    pytorch_forecasting/models/mlp/_decodermlp_forecaster_v2.py:1
    @@ -0,0 +1,174 @@
    +"""DecoderMLP forecaster."""
    +
    +from pathlib import Path
    +from typing import Any
    +
    +from lightning.pytorch import Trainer
    +from torch import nn
    +from torch.optim import Optimizer
    +
    +from pytorch_forecasting.models.base._base_forecaster import BaseForecaster
    +
    +
    +class DecoderMLPForecaster(BaseForecaster):
    +    """DecoderMLP forecaster (v2).
    +
    +    Parameters
    +    ----------
    +    hidden_size : int, default=300
    +        Hidden layer width of the MLP.
    +    n_hidden_layers : int, default=3
    +        Number of hidden layers.
    +    dropout : float, default=0.1
    +        Dropout probability.
    +    norm : bool, default=True
    +        Whether to apply ``LayerNorm`` in the MLP.
    +    activation_class : str, default="ReLU"
    +        Name of a ``torch.nn`` activation class.
    +    loss : nn.Module, optional
    +        Loss function for training. Defaults to ``MAE()``.
    +    logging_metrics : Optional[list[nn.Module]], default=None
    +        Metrics to log during training, validation, and testing.
    +    optimizer : Optional[Union[Optimizer, str]], default="adam"
    +        Optimizer to use for training.
    +    optimizer_params : Optional[dict], default=None
    +        Parameters for the optimizer.
    +    lr_scheduler : Optional[str], default=None
    +        Learning rate scheduler to use.
    +    lr_scheduler_params : Optional[dict], default=None
    +        Parameters for the learning rate scheduler.
    +    trainer : lightning.pytorch.Trainer, optional
    +        See :class:`~pytorch_forecasting.models.base.BaseForecaster`.
    +    datamodule : EncoderDecoderTimeSeriesDataModule, optional
    +        Configured, data-less datamodule. See
    +        :class:`~pytorch_forecasting.models.base.BaseForecaster`.
    +    ckpt_path : str or Path, optional
    +        See :class:`~pytorch_forecasting.models.base.BaseForecaster`.
    +    """
    +
    +    _tags = {
    +        "info:name": "DecoderMLP_v2",
    +        "info:compute": 1,
    +        "authors": ["jdb78", "echo-xiao"],
    +        # TODO: the v2 datamodule supports categorical inputs but not
    +        # categorical targets yet; add "categorical" to y_type once
    +        # EncoderDecoderTimeSeriesDataModule supports categorical targets.
    +        "info:y_type": ["numeric"],
    +        "capability:exogenous": True,
    +        "capability:multivariate": False,
    +        "capability:pred_int": True,
    +        "capability:flexible_history_length": True,
    +        "capability:cold_start": True,
    +    }
    +
    +    def __init__(
    +        self,
    +        hidden_size: int = 300,
    +        n_hidden_layers: int = 3,
    +        dropout: float = 0.1,
    +        norm: bool = True,
    +        activation_class: str = "ReLU",
    +        loss: nn.Module | None = None,
    +        logging_metrics: list[nn.Module] | None = None,
    +        optimizer: Optimizer | str | None = "adam",
    +        optimizer_params: dict | None = None,
    +        lr_scheduler: str | None = None,
    +        lr_scheduler_params: dict | None = None,
    +        trainer: Trainer | None = None,
    +        datamodule: Any = None,
    +        ckpt_path: str | Path | None = None,
    +    ):
    +        self.hidden_size = hidden_size
    +        self.n_hidden_layers = n_hidden_layers
    +        self.dropout = dropout
    +        self.norm = norm
    +        self.activation_class = activation_class
    +        self.loss = loss
    +        self.logging_metrics = logging_metrics
    +        self.optimizer = optimizer
    +        self.optimizer_params = optimizer_params
    +        self.lr_scheduler = lr_scheduler
    +        self.lr_scheduler_params = lr_scheduler_params
    +        self.trainer = trainer
    +        self.datamodule = datamodule
    +        self.ckpt_path = ckpt_path
    +        super().__init__(
    +            trainer=self.trainer, datamodule=self.datamodule, ckpt_path=self.ckpt_path
    +        )
    +
    +    @classmethod
    +    def get_cls(cls):
    +        """Get model class."""
    +        from pytorch_forecasting.models.mlp._decodermlp_v2 import DecoderMLP_v2
    +
    +        return DecoderMLP_v2
    +
    +    @classmethod
    +    def get_datamodule_cls(cls):
    +        """Get the underlying DataModule class."""
    +        from pytorch_forecasting.data.data_module import (
    +            EncoderDecoderTimeSeriesDataModule,
    +        )
    +
    +        return EncoderDecoderTimeSeriesDataModule
    +
    +    def get_model_params(self) -> dict[str, Any]:
    +        """Kwargs for ``get_cls()``, with ``None`` sentinels resolved."""
    +        from pytorch_forecasting.metrics import MAE
    +
    +        return dict(
    +            hidden_size=self.hidden_size,
    +            n_hidden_layers=self.n_hidden_layers,
    +            dropout=self.dropout,
    +            norm=self.norm,
    +            activation_class=self.activation_class,
    +            loss=MAE() if self.loss is None else self.loss,

    same here as above regarding the imports

    CloseChoice CloseChoice commented on code on Oct 09, 2026 14:05 UTC
    Code Review
    pytorch_forecasting/models/base/_base_forecaster.py:1
    @@ -0,0 +1,407 @@
    +from pathlib import Path
    +import pickle
    +from typing import Any, Optional, Union
    +
    +from lightning import Trainer
    +from lightning.pytorch.callbacks import ModelCheckpoint
    +from lightning.pytorch.core.datamodule import LightningDataModule
    +import numpy as np
    +import torch
    +from torch.utils.data import DataLoader
    +import yaml
    +
    +from pytorch_forecasting.data import TimeSeries
    +from pytorch_forecasting.models.base._base_object import _BasePtObject_v2
    +
    +
    +class BaseForecaster(_BasePtObject_v2):
    +    """
    +    Base forecaster class acting as a high-level wrapper for the Lightning workflow.
    +
    +    Model parameters are flattened into the concrete subclass's ``__init__``; the
    +    model is built inside ``fit`` from the datamodule's ``metadata``. The class
    +    manages model, datamodule and trainer, and provides streamlined ``fit`` and
    +    ``predict`` methods.
    +
    +    Parameters
    +    ----------
    +    trainer : lightning.Trainer, optional
    +        Trainer used by ``fit`` when none is passed there. Defaults to ``Trainer()``.
    +    datamodule : LightningDataModule, optional
    +        A configured but data-less datamodule; ``fit`` attaches the data with
    +        ``with_data``. Defaults to ``get_datamodule_cls()()``, or to the
    +        ``datamodule_cfg.pkl`` saved next to ``ckpt_path`` if loading.
    +    ckpt_path : Union[str, Path], optional
    +        Path to the checkpoint from which to load the model. Defaults to None.
    +    """
    +
    +    def __init__(
    +        self,
    +        trainer: Trainer | None = None,
    +        datamodule: Any = None,
    +        ckpt_path: str | Path | None = None,
    +    ):
    +        self.trainer = trainer
    +        self.datamodule = datamodule
    +        self.ckpt_path = ckpt_path
    +        super().__init__()
    +
    +        self._loaded_datamodule_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="datamodule_cfg.pkl"
    +        )
    +        self.metadata = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="metadata.pkl"
    +        )
    +        self._loaded_model_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="model_cfg.pkl"
    +        )
    +
    +        self.model = None
    +        self.trainer_ = None
    +        self.datamodule_ = None
    +        self._is_fitted = False
    +        if self.ckpt_path:
    +            self._build_model(metadata=self.metadata)
    +
    +    @staticmethod
    +    def _load_config(
    +        config: dict | str | Path | None,
    +        ckpt_path: str | Path | None = None,
    +        auto_file_name: str | None = None,
    +    ) -> dict:
    +        """
    +        Loads configuration from a dictionary, YAML file, or Pickle file.
    +        """
    +        if config is None:
    +            if ckpt_path and auto_file_name:
    +                path = Path(ckpt_path).parent / auto_file_name
    +                if path.exists():
    +                    with open(path, "rb") as f:
    +                        return pickle.load(f)  # noqa : S301
    +            return {}
    +
    +        if isinstance(config, dict):
    +            return config
    +
    +        path = Path(config)
    +        if not path.exists():
    +            raise FileNotFoundError(f"Configuration file not found: {path}")
    +
    +        suffix = path.suffix.lower()
    +
    +        if suffix in [".yaml", ".yml"]:
    +            with open(path) as f:
    +                return yaml.safe_load(f) or {}
    +
    +        elif suffix == ".pkl":
    +            with open(path, "rb") as f:
    +                return pickle.load(f)  # noqa: S301
    +        else:
    +            raise ValueError(
    +                f"Unsupported config format: {suffix}. Use .yaml, .yml, or .pkl"
    +            )
    +
    +    @classmethod
    +    def get_cls(cls):
    +        """Get the underlying model class."""
    +        raise NotImplementedError("Subclasses must implement `get_cls`.")
    +
    +    @classmethod
    +    def get_datamodule_cls(cls):
    +        """Get the underlying DataModule class."""
    +        raise NotImplementedError("Subclasses must implement `get_datamodule_cls`.")
    +
    +    def get_model_params(self) -> dict[str, Any]:
    +        """Return the kwargs for ``get_cls()``, excluding ``metadata``."""
    +        raise NotImplementedError("Subclasses must implement `get_model_params`.")
    +
    +    @property
    +    def model_cfg(self) -> dict[str, Any]:
    +        """Model kwargs, as passed to ``get_cls()``."""
    +        return self.get_model_params()
    +
    +    @property
    +    def datamodule_cfg(self) -> dict[str, Any]:
    +        """Constructor kwargs of the datamodule, fitted one preferred."""
    +        dm = self.datamodule_ if self.datamodule_ is not None else self.datamodule
    +        if dm is None:
    +            return self._loaded_datamodule_cfg
    +        if hasattr(dm, "_init_kwargs"):
    +            return dm._init_kwargs
    +        return dict(getattr(dm, "hparams", {}))
    +
    +    @classmethod
    +    def get_test_dataset_from(cls, **kwargs):
    +        """
    +        Creates and returns D1 TimeSeries dataSet objects for testing.
    +        """
    +        from pytorch_forecasting.tests._data_scenarios import (
    +            data_with_covariates_v2,
    +            make_datasets_v2,
    +        )
    +
    +        raw_data = data_with_covariates_v2()
    +
    +        datasets_info = make_datasets_v2(raw_data, **kwargs)
    +
    +        return {
    +            "train": datasets_info["training_dataset"],
    +            "predict": datasets_info["validation_dataset"],
    +        }
    +
    +    def _check_is_fitted(self, method_name: str | None = None):
    +        """Raise ``RuntimeError`` if ``fit`` has not been called."""
    +        if not self._is_fitted:
    +            caller = f"`{method_name}` " if method_name else ""
    +            raise RuntimeError(
    +                f"{type(self).__name__} is not fitted yet; {caller}requires "
    +                "`fit` to be called first."
    +            )
    +
    +    def _build_model(self, metadata: dict):
    +        """Instantiates the model, either from a checkpoint or from config."""
    +        model_cls = self.get_cls()
    +        if self.ckpt_path:

    Here is a problem, this only updates self.model but other properites are missed when reloading from checkpoint.

    E.g.

    """Existing checkpoint limitation: reload loses fitted preprocessing state."""
    
    import warnings
    from pathlib import Path
    from tempfile import TemporaryDirectory
    
    from lightning.pytorch import Trainer
    import numpy as np
    import pandas as pd
    import torch
    
    from pytorch_forecasting.data import TimeSeries
    from pytorch_forecasting.data.data_module import EncoderDecoderTimeSeriesDataModule
    from pytorch_forecasting.models.mlp import DecoderMLPForecaster
    
    warnings.filterwarnings("ignore", message=".*experimental.*")
    torch.manual_seed(0)
    
    frame = pd.DataFrame({
        "group": np.repeat(np.arange(10), 20),
        "time": np.tile(np.arange(20), 10),
        "target": 100.0 + np.tile(np.arange(20), 10),
        "feature": np.tile(np.arange(20), 10).astype(float),
    })
    data = TimeSeries(
        frame, time="time", target="target", group=["group"],
        num=["feature"], known=["feature"],
    )
    
    TRAINER_KWARGS = dict(
        accelerator="cpu", max_epochs=1, limit_train_batches=1,
        limit_val_batches=1, logger=False, enable_progress_bar=False,
        enable_model_summary=False, num_sanity_val_steps=0,
    )
    
    from sklearn.preprocessing import StandardScaler
    
    with TemporaryDirectory(prefix="forecaster-review-") as directory:
        original = DecoderMLPForecaster(
            hidden_size=4, n_hidden_layers=1,
            datamodule=EncoderDecoderTimeSeriesDataModule(
                max_encoder_length=4, max_prediction_length=3,
                target_normalizer="auto", scalers={"feature": StandardScaler()},
            ),
        )
        checkpoint = original.fit(
            data, trainer=Trainer(**TRAINER_KWARGS, default_root_dir=directory),
            ckpt_dir=directory,
        )
        assert checkpoint.is_file()
        before_loader = original._load_dataloader(data)
        loaded = DecoderMLPForecaster(ckpt_path=checkpoint)
        after_loader = loaded._load_dataloader(data)
        breakpoint()
        before_dm = before_loader.dataset.data_module
        after_dm = after_loader.dataset.data_module
        before_x = next(iter(before_loader))[0]
        after_x = next(iter(after_loader))[0]
        print("Target fitted before / after reload:",
              before_dm._target_normalizer_fitted, after_dm._target_normalizer_fitted)
        print("Features fitted before / after reload:",
              before_dm._feature_scalers_fitted, after_dm._feature_scalers_fitted)
        for key in ("target_past", "decoder_cont"):
            print(f"{key} mean before / after reload:",
                  before_x[key].mean().item(), after_x[key].mean().item())
            assert not torch.allclose(before_x[key], after_x[key])
        assert before_dm._target_normalizer_fitted and before_dm._feature_scalers_fitted
        assert not after_dm._target_normalizer_fitted and not after_dm._feature_scalers_fitted
        print("BUG reproduced: checkpoint reload changes preprocessing of identical input data.")
    

    CloseChoice CloseChoice commented on code on Oct 09, 2026 14:07 UTC
    Code Review
    pytorch_forecasting/models/base/_base_forecaster.py:1
    @@ -0,0 +1,407 @@
    +from pathlib import Path
    +import pickle
    +from typing import Any, Optional, Union
    +
    +from lightning import Trainer
    +from lightning.pytorch.callbacks import ModelCheckpoint
    +from lightning.pytorch.core.datamodule import LightningDataModule
    +import numpy as np
    +import torch
    +from torch.utils.data import DataLoader
    +import yaml
    +
    +from pytorch_forecasting.data import TimeSeries
    +from pytorch_forecasting.models.base._base_object import _BasePtObject_v2
    +
    +
    +class BaseForecaster(_BasePtObject_v2):
    +    """
    +    Base forecaster class acting as a high-level wrapper for the Lightning workflow.
    +
    +    Model parameters are flattened into the concrete subclass's ``__init__``; the
    +    model is built inside ``fit`` from the datamodule's ``metadata``. The class
    +    manages model, datamodule and trainer, and provides streamlined ``fit`` and
    +    ``predict`` methods.
    +
    +    Parameters
    +    ----------
    +    trainer : lightning.Trainer, optional
    +        Trainer used by ``fit`` when none is passed there. Defaults to ``Trainer()``.
    +    datamodule : LightningDataModule, optional
    +        A configured but data-less datamodule; ``fit`` attaches the data with
    +        ``with_data``. Defaults to ``get_datamodule_cls()()``, or to the
    +        ``datamodule_cfg.pkl`` saved next to ``ckpt_path`` if loading.
    +    ckpt_path : Union[str, Path], optional
    +        Path to the checkpoint from which to load the model. Defaults to None.
    +    """
    +
    +    def __init__(
    +        self,
    +        trainer: Trainer | None = None,
    +        datamodule: Any = None,
    +        ckpt_path: str | Path | None = None,
    +    ):
    +        self.trainer = trainer
    +        self.datamodule = datamodule
    +        self.ckpt_path = ckpt_path
    +        super().__init__()
    +
    +        self._loaded_datamodule_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="datamodule_cfg.pkl"
    +        )
    +        self.metadata = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="metadata.pkl"
    +        )
    +        self._loaded_model_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="model_cfg.pkl"
    +        )
    +
    +        self.model = None
    +        self.trainer_ = None
    +        self.datamodule_ = None
    +        self._is_fitted = False
    +        if self.ckpt_path:
    +            self._build_model(metadata=self.metadata)
    +
    +    @staticmethod
    +    def _load_config(
    +        config: dict | str | Path | None,
    +        ckpt_path: str | Path | None = None,
    +        auto_file_name: str | None = None,
    +    ) -> dict:
    +        """
    +        Loads configuration from a dictionary, YAML file, or Pickle file.
    +        """
    +        if config is None:
    +            if ckpt_path and auto_file_name:
    +                path = Path(ckpt_path).parent / auto_file_name
    +                if path.exists():
    +                    with open(path, "rb") as f:
    +                        return pickle.load(f)  # noqa : S301
    +            return {}
    +
    +        if isinstance(config, dict):
    +            return config
    +
    +        path = Path(config)
    +        if not path.exists():
    +            raise FileNotFoundError(f"Configuration file not found: {path}")
    +
    +        suffix = path.suffix.lower()
    +
    +        if suffix in [".yaml", ".yml"]:
    +            with open(path) as f:
    +                return yaml.safe_load(f) or {}
    +
    +        elif suffix == ".pkl":
    +            with open(path, "rb") as f:
    +                return pickle.load(f)  # noqa: S301
    +        else:
    +            raise ValueError(
    +                f"Unsupported config format: {suffix}. Use .yaml, .yml, or .pkl"
    +            )
    +
    +    @classmethod
    +    def get_cls(cls):
    +        """Get the underlying model class."""
    +        raise NotImplementedError("Subclasses must implement `get_cls`.")
    +
    +    @classmethod
    +    def get_datamodule_cls(cls):
    +        """Get the underlying DataModule class."""
    +        raise NotImplementedError("Subclasses must implement `get_datamodule_cls`.")
    +
    +    def get_model_params(self) -> dict[str, Any]:
    +        """Return the kwargs for ``get_cls()``, excluding ``metadata``."""
    +        raise NotImplementedError("Subclasses must implement `get_model_params`.")
    +
    +    @property
    +    def model_cfg(self) -> dict[str, Any]:
    +        """Model kwargs, as passed to ``get_cls()``."""
    +        return self.get_model_params()
    +
    +    @property
    +    def datamodule_cfg(self) -> dict[str, Any]:
    +        """Constructor kwargs of the datamodule, fitted one preferred."""
    +        dm = self.datamodule_ if self.datamodule_ is not None else self.datamodule
    +        if dm is None:
    +            return self._loaded_datamodule_cfg
    +        if hasattr(dm, "_init_kwargs"):
    +            return dm._init_kwargs
    +        return dict(getattr(dm, "hparams", {}))
    +
    +    @classmethod
    +    def get_test_dataset_from(cls, **kwargs):
    +        """
    +        Creates and returns D1 TimeSeries dataSet objects for testing.
    +        """
    +        from pytorch_forecasting.tests._data_scenarios import (
    +            data_with_covariates_v2,
    +            make_datasets_v2,
    +        )
    +
    +        raw_data = data_with_covariates_v2()
    +
    +        datasets_info = make_datasets_v2(raw_data, **kwargs)
    +
    +        return {
    +            "train": datasets_info["training_dataset"],
    +            "predict": datasets_info["validation_dataset"],
    +        }
    +
    +    def _check_is_fitted(self, method_name: str | None = None):
    +        """Raise ``RuntimeError`` if ``fit`` has not been called."""
    +        if not self._is_fitted:
    +            caller = f"`{method_name}` " if method_name else ""
    +            raise RuntimeError(
    +                f"{type(self).__name__} is not fitted yet; {caller}requires "
    +                "`fit` to be called first."
    +            )
    +
    +    def _build_model(self, metadata: dict):
    +        """Instantiates the model, either from a checkpoint or from config."""
    +        model_cls = self.get_cls()
    +        if self.ckpt_path:
    +            self.model = model_cls.load_from_checkpoint(

    I actually think there is quite something wrong with the serialization of this.

    """PR #2434: refitting a loaded forecaster saves incompatible model config."""
    
    import warnings
    from pathlib import Path
    from tempfile import TemporaryDirectory
    
    from lightning.pytorch import Trainer
    import numpy as np
    import pandas as pd
    import torch
    
    from pytorch_forecasting.data import TimeSeries
    from pytorch_forecasting.data.data_module import EncoderDecoderTimeSeriesDataModule
    from pytorch_forecasting.models.mlp import DecoderMLPForecaster
    
    warnings.filterwarnings("ignore", message=".*experimental.*")
    torch.manual_seed(0)
    
    frame = pd.DataFrame({
        "group": np.repeat(np.arange(10), 20),
        "time": np.tile(np.arange(20), 10),
        "target": 100.0 + np.tile(np.arange(20), 10),
        "feature": np.tile(np.arange(20), 10).astype(float),
    })
    data = TimeSeries(
        frame, time="time", target="target", group=["group"],
        num=["feature"], known=["feature"],
    )
    
    TRAINER_KWARGS = dict(
        accelerator="cpu", max_epochs=1, limit_train_batches=1,
        limit_val_batches=1, logger=False, enable_progress_bar=False,
        enable_model_summary=False, num_sanity_val_steps=0,
    )
    
    with TemporaryDirectory(prefix="forecaster-review-") as directory:
        root = Path(directory)
        original = DecoderMLPForecaster(
            hidden_size=4, n_hidden_layers=1,
            datamodule=EncoderDecoderTimeSeriesDataModule(
                max_encoder_length=4, max_prediction_length=3,
            ),
        )
        first_path = original.fit(
            data, trainer=Trainer(**TRAINER_KWARGS, default_root_dir=root),
            ckpt_dir=root / "first",
        )
        assert first_path.is_file()
        loaded = DecoderMLPForecaster(ckpt_path=first_path)
        print("Loaded wrapper hidden_size:", loaded.hidden_size)
        print("Loaded model hidden_size:", loaded.model.hidden_size)
        assert loaded.hidden_size != loaded.model.hidden_size
        second_path = loaded.fit(
            data, trainer=Trainer(**TRAINER_KWARGS, default_root_dir=root),
            ckpt_dir=root / "second",
        )
        assert second_path.is_file()
        try:
            DecoderMLPForecaster(ckpt_path=second_path)
        except RuntimeError as error:
            assert "size mismatch" in str(error)
            print("BUG reproduced: reloading the second checkpoint fails:")
            print(error)
        else:
            raise AssertionError("Reload succeeded; the reported bug was not reproduced.")
    

    Couldn't we simply store all init parameters as well and then set them again when loading as a first try to tackle serialization?

    CloseChoice CloseChoice commented on code on Oct 09, 2026 14:08 UTC
    Code Review
    tests/test_models/test_tft_v2.py:1
    @@ -395,3 +397,82 @@ def test_model_with_datamodule_integration(
             actual_batch_size,
             MAX_PREDICTION_LENGTH_TEST,
         )
    +

    here's one more error codex found. Trainer does not work properly when reused.

    """PR #2434: a reused Trainer skips training a freshly rebuilt model."""
    
    import warnings
    from pathlib import Path
    from tempfile import TemporaryDirectory
    
    from lightning.pytorch import Trainer
    import numpy as np
    import pandas as pd
    import torch
    
    from pytorch_forecasting.data import TimeSeries
    from pytorch_forecasting.data.data_module import EncoderDecoderTimeSeriesDataModule
    from pytorch_forecasting.models.mlp import DecoderMLPForecaster
    
    warnings.filterwarnings("ignore", message=".*experimental.*")
    torch.manual_seed(0)
    
    frame = pd.DataFrame({
        "group": np.repeat(np.arange(10), 20),
        "time": np.tile(np.arange(20), 10),
        "target": 100.0 + np.tile(np.arange(20), 10),
        "feature": np.tile(np.arange(20), 10).astype(float),
    })
    data = TimeSeries(
        frame, time="time", target="target", group=["group"],
        num=["feature"], known=["feature"],
    )
    
    TRAINER_KWARGS = dict(
        accelerator="cpu", max_epochs=1, limit_train_batches=1,
        limit_val_batches=1, logger=False, enable_progress_bar=False,
        enable_model_summary=False, num_sanity_val_steps=0,
    )
    
    from lightning.pytorch.callbacks import Callback
    
    
    class CaptureTraining(Callback):
        def __init__(self):
            self.batches = 0
            self.before = {}
    
        def on_fit_start(self, trainer, model):
            self.before = {key: value.clone() for key, value in model.state_dict().items()}
    
        def on_train_batch_end(self, trainer, model, outputs, batch, batch_idx):
            self.batches += 1
    
    
    with TemporaryDirectory(prefix="forecaster-review-") as directory:
        capture = CaptureTraining()
        trainer = Trainer(
            **TRAINER_KWARGS, callbacks=[capture], enable_checkpointing=False,
            default_root_dir=directory,
        )
        forecaster = DecoderMLPForecaster(
            hidden_size=4, n_hidden_layers=1, trainer=trainer,
            datamodule=EncoderDecoderTimeSeriesDataModule(
                max_encoder_length=4, max_prediction_length=3,
            ),
        )
        forecaster.fit(data, save_ckpt=False)
        first_model = forecaster.model
        first_batches = capture.batches
        first_step = trainer.global_step
        assert first_batches > 0
        forecaster.fit(data, save_ckpt=False)
        unchanged = all(
            torch.equal(value, capture.before[key])
            for key, value in forecaster.model.state_dict().items()
        )
        print("Cumulative training batches after first / second fit:", first_batches, capture.batches)
        print("Global step after first / second fit:", first_step, trainer.global_step)
        print("Second model unchanged from initialization:", unchanged)
        print("Forecaster reports fitted:", forecaster._is_fitted)
        assert forecaster.model is not first_model
        assert capture.batches == first_batches and trainer.global_step == first_step
        assert unchanged and forecaster._is_fitted
        print("BUG reproduced: the second fit marks a fresh, untrained model as fitted.")
    

    CloseChoice CloseChoice commented on code on Oct 09, 2026 14:09 UTC
    Code Review
    pytorch_forecasting/models/scinet/_scinet_forecaster_v2.py:1
    @@ -0,0 +1,195 @@
    +"""SCINet forecaster."""

    Seems like this is incompatible with the data module:

    """PR #2434: default SCINet model and automatic datamodule are incompatible."""
    
    import warnings
    
    import numpy as np
    import pandas as pd
    
    from pytorch_forecasting.data import TimeSeries
    from pytorch_forecasting.models.scinet import SCINetForecaster
    
    warnings.filterwarnings("ignore", message=".*experimental.*")
    frame = pd.DataFrame({
        "group": np.repeat(np.arange(10), 40),
        "time": np.tile(np.arange(40), 10),
        "target": 100.0 + np.tile(np.arange(40), 10),
        "feature": np.tile(np.arange(40), 10).astype(float),
    })
    data = TimeSeries(
        frame, time="time", target="target", group=["group"], num=["feature"],
    )
    forecaster = SCINetForecaster()
    try:
        # Model construction fails before a Trainer or checkpoint directory is created.
        forecaster.fit(data, save_ckpt=False)
    except ValueError as error:
        assert "context_length (30)" in str(error) and "divisible" in str(error)
        print(f"BUG reproduced: {type(error).__name__}: {error}")
    else:
        raise AssertionError("Fit succeeded; the reported bug was not reproduced.")
    

    CloseChoice CloseChoice requested changes on Oct 09, 2026 14:09 UTC
    Changes Requested Reviewer

    Requested changes.

    phoeenniixx phoeenniixx commented on code on Oct 16, 2026 13:53 UTC
    Code Review
    pytorch_forecasting/models/scinet/_scinet_forecaster_v2.py:1
    @@ -0,0 +1,195 @@
    +"""SCINet forecaster."""

    I think this is something of an issue with the defaults. I think we need to update the defaults and add a test to prevent this from happening again.

    Thanks for pointing this out

    Raised an issue #2469

    phoeenniixx phoeenniixx commented on code on Oct 16, 2026 13:56 UTC
    Code Review
    tests/test_models/test_tft_v2.py:1
    @@ -395,3 +397,82 @@ def test_model_with_datamodule_integration(
             actual_batch_size,
             MAX_PREDICTION_LENGTH_TEST,
         )
    +

    After discussions - we are going to reset Trainer in fit everytime

    phoeenniixx phoeenniixx commented on code on Oct 16, 2026 13:56 UTC
    Code Review
    pytorch_forecasting/models/base/_base_forecaster.py:1
    @@ -0,0 +1,407 @@
    +from pathlib import Path
    +import pickle
    +from typing import Any, Optional, Union
    +
    +from lightning import Trainer
    +from lightning.pytorch.callbacks import ModelCheckpoint
    +from lightning.pytorch.core.datamodule import LightningDataModule
    +import numpy as np
    +import torch
    +from torch.utils.data import DataLoader
    +import yaml
    +
    +from pytorch_forecasting.data import TimeSeries
    +from pytorch_forecasting.models.base._base_object import _BasePtObject_v2
    +
    +
    +class BaseForecaster(_BasePtObject_v2):
    +    """
    +    Base forecaster class acting as a high-level wrapper for the Lightning workflow.
    +
    +    Model parameters are flattened into the concrete subclass's ``__init__``; the
    +    model is built inside ``fit`` from the datamodule's ``metadata``. The class
    +    manages model, datamodule and trainer, and provides streamlined ``fit`` and
    +    ``predict`` methods.
    +
    +    Parameters
    +    ----------
    +    trainer : lightning.Trainer, optional
    +        Trainer used by ``fit`` when none is passed there. Defaults to ``Trainer()``.
    +    datamodule : LightningDataModule, optional
    +        A configured but data-less datamodule; ``fit`` attaches the data with
    +        ``with_data``. Defaults to ``get_datamodule_cls()()``, or to the
    +        ``datamodule_cfg.pkl`` saved next to ``ckpt_path`` if loading.
    +    ckpt_path : Union[str, Path], optional
    +        Path to the checkpoint from which to load the model. Defaults to None.
    +    """
    +
    +    def __init__(
    +        self,
    +        trainer: Trainer | None = None,
    +        datamodule: Any = None,
    +        ckpt_path: str | Path | None = None,
    +    ):
    +        self.trainer = trainer
    +        self.datamodule = datamodule
    +        self.ckpt_path = ckpt_path
    +        super().__init__()
    +
    +        self._loaded_datamodule_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="datamodule_cfg.pkl"
    +        )
    +        self.metadata = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="metadata.pkl"
    +        )
    +        self._loaded_model_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="model_cfg.pkl"
    +        )
    +
    +        self.model = None
    +        self.trainer_ = None
    +        self.datamodule_ = None
    +        self._is_fitted = False
    +        if self.ckpt_path:
    +            self._build_model(metadata=self.metadata)
    +
    +    @staticmethod
    +    def _load_config(
    +        config: dict | str | Path | None,
    +        ckpt_path: str | Path | None = None,
    +        auto_file_name: str | None = None,
    +    ) -> dict:
    +        """
    +        Loads configuration from a dictionary, YAML file, or Pickle file.
    +        """
    +        if config is None:
    +            if ckpt_path and auto_file_name:
    +                path = Path(ckpt_path).parent / auto_file_name
    +                if path.exists():
    +                    with open(path, "rb") as f:
    +                        return pickle.load(f)  # noqa : S301
    +            return {}
    +
    +        if isinstance(config, dict):
    +            return config
    +
    +        path = Path(config)
    +        if not path.exists():
    +            raise FileNotFoundError(f"Configuration file not found: {path}")
    +
    +        suffix = path.suffix.lower()
    +
    +        if suffix in [".yaml", ".yml"]:
    +            with open(path) as f:
    +                return yaml.safe_load(f) or {}
    +
    +        elif suffix == ".pkl":
    +            with open(path, "rb") as f:
    +                return pickle.load(f)  # noqa: S301
    +        else:
    +            raise ValueError(
    +                f"Unsupported config format: {suffix}. Use .yaml, .yml, or .pkl"
    +            )
    +
    +    @classmethod
    +    def get_cls(cls):
    +        """Get the underlying model class."""
    +        raise NotImplementedError("Subclasses must implement `get_cls`.")
    +
    +    @classmethod
    +    def get_datamodule_cls(cls):
    +        """Get the underlying DataModule class."""
    +        raise NotImplementedError("Subclasses must implement `get_datamodule_cls`.")
    +
    +    def get_model_params(self) -> dict[str, Any]:
    +        """Return the kwargs for ``get_cls()``, excluding ``metadata``."""
    +        raise NotImplementedError("Subclasses must implement `get_model_params`.")
    +
    +    @property
    +    def model_cfg(self) -> dict[str, Any]:
    +        """Model kwargs, as passed to ``get_cls()``."""
    +        return self.get_model_params()
    +
    +    @property
    +    def datamodule_cfg(self) -> dict[str, Any]:
    +        """Constructor kwargs of the datamodule, fitted one preferred."""
    +        dm = self.datamodule_ if self.datamodule_ is not None else self.datamodule
    +        if dm is None:
    +            return self._loaded_datamodule_cfg
    +        if hasattr(dm, "_init_kwargs"):
    +            return dm._init_kwargs
    +        return dict(getattr(dm, "hparams", {}))
    +
    +    @classmethod
    +    def get_test_dataset_from(cls, **kwargs):
    +        """
    +        Creates and returns D1 TimeSeries dataSet objects for testing.
    +        """
    +        from pytorch_forecasting.tests._data_scenarios import (
    +            data_with_covariates_v2,
    +            make_datasets_v2,
    +        )
    +
    +        raw_data = data_with_covariates_v2()
    +
    +        datasets_info = make_datasets_v2(raw_data, **kwargs)
    +
    +        return {
    +            "train": datasets_info["training_dataset"],
    +            "predict": datasets_info["validation_dataset"],
    +        }
    +
    +    def _check_is_fitted(self, method_name: str | None = None):
    +        """Raise ``RuntimeError`` if ``fit`` has not been called."""
    +        if not self._is_fitted:
    +            caller = f"`{method_name}` " if method_name else ""
    +            raise RuntimeError(
    +                f"{type(self).__name__} is not fitted yet; {caller}requires "
    +                "`fit` to be called first."
    +            )
    +
    +    def _build_model(self, metadata: dict):
    +        """Instantiates the model, either from a checkpoint or from config."""
    +        model_cls = self.get_cls()
    +        if self.ckpt_path:
    +            self.model = model_cls.load_from_checkpoint(

    The Serialization issue would be taken on in the coming PRs

    Thanks!

    phoeenniixx phoeenniixx commented on code on Oct 16, 2026 13:57 UTC
    Code Review
    pytorch_forecasting/models/base/_base_forecaster.py:1
    @@ -0,0 +1,407 @@
    +from pathlib import Path
    +import pickle
    +from typing import Any, Optional, Union
    +
    +from lightning import Trainer
    +from lightning.pytorch.callbacks import ModelCheckpoint
    +from lightning.pytorch.core.datamodule import LightningDataModule
    +import numpy as np
    +import torch
    +from torch.utils.data import DataLoader
    +import yaml
    +
    +from pytorch_forecasting.data import TimeSeries
    +from pytorch_forecasting.models.base._base_object import _BasePtObject_v2
    +
    +
    +class BaseForecaster(_BasePtObject_v2):
    +    """
    +    Base forecaster class acting as a high-level wrapper for the Lightning workflow.
    +
    +    Model parameters are flattened into the concrete subclass's ``__init__``; the
    +    model is built inside ``fit`` from the datamodule's ``metadata``. The class
    +    manages model, datamodule and trainer, and provides streamlined ``fit`` and
    +    ``predict`` methods.
    +
    +    Parameters
    +    ----------
    +    trainer : lightning.Trainer, optional
    +        Trainer used by ``fit`` when none is passed there. Defaults to ``Trainer()``.
    +    datamodule : LightningDataModule, optional
    +        A configured but data-less datamodule; ``fit`` attaches the data with
    +        ``with_data``. Defaults to ``get_datamodule_cls()()``, or to the
    +        ``datamodule_cfg.pkl`` saved next to ``ckpt_path`` if loading.
    +    ckpt_path : Union[str, Path], optional
    +        Path to the checkpoint from which to load the model. Defaults to None.
    +    """
    +
    +    def __init__(
    +        self,
    +        trainer: Trainer | None = None,
    +        datamodule: Any = None,
    +        ckpt_path: str | Path | None = None,
    +    ):
    +        self.trainer = trainer
    +        self.datamodule = datamodule
    +        self.ckpt_path = ckpt_path
    +        super().__init__()
    +
    +        self._loaded_datamodule_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="datamodule_cfg.pkl"
    +        )
    +        self.metadata = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="metadata.pkl"
    +        )
    +        self._loaded_model_cfg = self._load_config(
    +            None, ckpt_path=self.ckpt_path, auto_file_name="model_cfg.pkl"
    +        )
    +
    +        self.model = None
    +        self.trainer_ = None
    +        self.datamodule_ = None
    +        self._is_fitted = False
    +        if self.ckpt_path:
    +            self._build_model(metadata=self.metadata)
    +
    +    @staticmethod
    +    def _load_config(
    +        config: dict | str | Path | None,
    +        ckpt_path: str | Path | None = None,
    +        auto_file_name: str | None = None,
    +    ) -> dict:
    +        """
    +        Loads configuration from a dictionary, YAML file, or Pickle file.
    +        """
    +        if config is None:
    +            if ckpt_path and auto_file_name:
    +                path = Path(ckpt_path).parent / auto_file_name
    +                if path.exists():
    +                    with open(path, "rb") as f:
    +                        return pickle.load(f)  # noqa : S301
    +            return {}
    +
    +        if isinstance(config, dict):
    +            return config
    +
    +        path = Path(config)
    +        if not path.exists():
    +            raise FileNotFoundError(f"Configuration file not found: {path}")
    +
    +        suffix = path.suffix.lower()
    +
    +        if suffix in [".yaml", ".yml"]:
    +            with open(path) as f:
    +                return yaml.safe_load(f) or {}
    +
    +        elif suffix == ".pkl":
    +            with open(path, "rb") as f:
    +                return pickle.load(f)  # noqa: S301
    +        else:
    +            raise ValueError(
    +                f"Unsupported config format: {suffix}. Use .yaml, .yml, or .pkl"
    +            )
    +
    +    @classmethod
    +    def get_cls(cls):
    +        """Get the underlying model class."""
    +        raise NotImplementedError("Subclasses must implement `get_cls`.")
    +
    +    @classmethod
    +    def get_datamodule_cls(cls):
    +        """Get the underlying DataModule class."""
    +        raise NotImplementedError("Subclasses must implement `get_datamodule_cls`.")
    +
    +    def get_model_params(self) -> dict[str, Any]:
    +        """Return the kwargs for ``get_cls()``, excluding ``metadata``."""
    +        raise NotImplementedError("Subclasses must implement `get_model_params`.")
    +
    +    @property
    +    def model_cfg(self) -> dict[str, Any]:
    +        """Model kwargs, as passed to ``get_cls()``."""
    +        return self.get_model_params()
    +
    +    @property
    +    def datamodule_cfg(self) -> dict[str, Any]:
    +        """Constructor kwargs of the datamodule, fitted one preferred."""
    +        dm = self.datamodule_ if self.datamodule_ is not None else self.datamodule
    +        if dm is None:
    +            return self._loaded_datamodule_cfg
    +        if hasattr(dm, "_init_kwargs"):
    +            return dm._init_kwargs
    +        return dict(getattr(dm, "hparams", {}))
    +
    +    @classmethod
    +    def get_test_dataset_from(cls, **kwargs):
    +        """
    +        Creates and returns D1 TimeSeries dataSet objects for testing.
    +        """
    +        from pytorch_forecasting.tests._data_scenarios import (
    +            data_with_covariates_v2,
    +            make_datasets_v2,
    +        )
    +
    +        raw_data = data_with_covariates_v2()
    +
    +        datasets_info = make_datasets_v2(raw_data, **kwargs)
    +
    +        return {
    +            "train": datasets_info["training_dataset"],
    +            "predict": datasets_info["validation_dataset"],
    +        }
    +
    +    def _check_is_fitted(self, method_name: str | None = None):
    +        """Raise ``RuntimeError`` if ``fit`` has not been called."""
    +        if not self._is_fitted:
    +            caller = f"`{method_name}` " if method_name else ""
    +            raise RuntimeError(
    +                f"{type(self).__name__} is not fitted yet; {caller}requires "
    +                "`fit` to be called first."
    +            )
    +
    +    def _build_model(self, metadata: dict):
    +        """Instantiates the model, either from a checkpoint or from config."""
    +        model_cls = self.get_cls()
    +        if self.ckpt_path:

    The Serialization issue would be taken on in the coming PRs

    Thanks!

    phoeenniixx phoeenniixx commented on code on Oct 20, 2026 06:29 UTC
    Code Review
    tests/test_models/test_tft_v2.py:1
    @@ -395,3 +397,82 @@ def test_model_with_datamodule_integration(
             actual_batch_size,
             MAX_PREDICTION_LENGTH_TEST,
         )
    +

    Hi @CloseChoice, after some thought, i changed __init__ signature to accept trainer_kwargs rather than a whole Trainer instance, as we are never going to use that instance anyway and just take its args to create a new instance everytime in fit. Do you think it is better this way, or should I rollback to accepting Trainer instance - which will add some complexity of extracting the kwargs ourselves

    phoeenniixx phoeenniixx commented on code on Oct 20, 2026 06:30 UTC
    Code Review
    tests/test_models/test_tft_v2.py:1
    @@ -395,3 +397,82 @@ def test_model_with_datamodule_integration(
             actual_batch_size,
             MAX_PREDICTION_LENGTH_TEST,
         )
    +

    FYI @fkiraly

    Reviewers
    Assignees
    phoeenniixx phoeenniixx
    Labels
    risk: low confidence: 82.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 92.5% (HIGH) · Higher = larger blast radius
    92.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.8% · Lower = rushed or shallow review
    82.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 15.9% · Safe to merge
    15.9%