← Back to Pull requests

[DO NOT MERGE] Experimental Design for new v2 API #2398

Open
phoeenniixx opened this pull request with 2673 lines diff across 6 files
View on GitHub
phoeenniixx phoeenniixx commented on Aug 27, 2026 17:48 UTC
Author

This PR tries a new prototype for new design.
Created _proto to have the files with major changes and some minor changes (like to EncoderDecoderDM) has been made in place.

NOTE


This is a prototype - not to be merged as here the idea is just to get a minimal working state of the design to test out how it feels. I have done somethings which will not happen in ACTUAL implementation. Like
BaseForecaster is inheriting from BasePkg which will not happen in actuality as BaseFroecaster will REPLACE BasePkg.
Special nb for this prototype - will replace the current tutorials
_proto folder with Forecaster, TimeSeries_datatype etc files. which will be present in their designated folders and not in this folder
TimeSeries_datatype will be renamed to TimeSeries if we decide to move on with this plan

What should a reviewer concentrate their feedback on?

Just the notebook and try out the vignettes and play around with it. This PR is not meant for the "code review" but just for the review of the vignettes and design

Try the notebook on colab (i have added a cell to install the branch as well)

AI Generated, so it SHOULD NOT BE MERGED
Only raised to try out the new interface and get feedback. If approved, will be implemented over a stack of PRs :)

Diff: 2673 lines (+2639 / -34) across 6 files Reviewer: fkiraly Review duration: 80167m
All Vouch review confidence checks passed
Residual risk 0.06 = Change Risk (0.57) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.57 · 2673 lines diff across 6 files
0.57
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.90 · 5 substantive comment(s)
0.90
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
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
Real PR Conversation Timeline
25 items
phoeenniixx phoeenniixx commented on Aug 27, 2026 17:50 UTC
Author

I still need to add forecaster etc. I have already added what i think will be added to this PR in the description. I willl update the desc if something changes

review-notebook-app[bot] review-notebook-app[bot] commented on Aug 31, 2026 18:07 UTC
Bot

Check out this pull request on&nbsp; <a href="https://app.reviewnb.com/sktime/pytorch-forecasting/pull/2398"><img align="absmiddle" alt="ReviewNB" height="30" class="BotMessageButtonImage" src="https://raw.githubusercontent.com/ReviewNB/support/master/images/button_reviewnb.png" style="height: 30px !important;"/></a>

See visual diffs & provide feedback on Jupyter Notebooks.

---

<i>Powered by <a href='https://www.reviewnb.com/?utm_source=gh'>ReviewNB</a></i>

CloseChoice CloseChoice commented on Sep 02, 2026 11:44 UTC
Contributor

I think this design is good. I played around with it in your notebook and that is fine.

I just got issues when trying to play with this from scratch:

from pytorch_forecasting._proto._timeseries_datatype import TimeSeries_datatype as TimeSeries

tft = TFTForecaster()
ts = TimeSeries(data_df,
                time="time_idx")
tft.fit(ts)

This resulted in an error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[5], line 6
      2 
      3 tft = TFTForecaster()
      4 ts = TimeSeries(data_df,
      5                 time="time_idx")
----> 6 tft.fit(ts)

File ~/programming/pytorch-forecasting/pytorch_forecasting/_proto/_base_forecaster.py:135, in BaseForecaster.fit(self, data, trainer)
    131 self.model_ = self.get_cls()(
    132     **self.model_cfg, metadata=self.datamodule_.metadata
    133 )
    134 self.trainer_ = self._resolve_trainer(trainer)
--> 135 self.trainer_.fit(self.model_, datamodule=self.datamodule_)
    137 self._is_fitted = True
    138 return self

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/trainer.py:584, in Trainer.fit(self, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path, weights_only)
    582 self.training = True
    583 self.should_stop = False
--> 584 call._call_and_handle_interrupt(
    585     self,
    586     self._fit_impl,
    587     model,
    588     train_dataloaders,
    589     val_dataloaders,
    590     datamodule,
    591     ckpt_path,
    592     weights_only,
    593 )

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/call.py:49, in _call_and_handle_interrupt(trainer, trainer_fn, *args, **kwargs)
     47     if trainer.strategy.launcher is not None:
     48         return trainer.strategy.launcher.launch(trainer_fn, *args, trainer=trainer, **kwargs)
---> 49     return trainer_fn(*args, **kwargs)
     51 except _TunerExitException:
     52     _call_teardown_hook(trainer)

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/trainer.py:630, in Trainer._fit_impl(self, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path, weights_only)
    623     download_model_from_registry(ckpt_path, self)
    624 ckpt_path = self._checkpoint_connector._select_ckpt_path(
    625     self.state.fn,
    626     ckpt_path,
    627     model_provided=True,
    628     model_connected=self.lightning_module is not None,
    629 )
--> 630 self._run(model, ckpt_path=ckpt_path, weights_only=weights_only)
    632 assert self.state.stopped
    633 self.training = False

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/trainer.py:1079, in Trainer._run(self, model, ckpt_path, weights_only)
   1074 self._signal_connector.register_signal_handlers()
   1076 # ----------------------------
   1077 # RUN THE TRAINER
   1078 # ----------------------------
-> 1079 results = self._run_stage()
   1081 # ----------------------------
   1082 # POST-Training CLEAN UP
   1083 # ----------------------------
   1084 log.debug(f"{self.__class__.__name__}: trainer tearing down")

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/trainer.py:1123, in Trainer._run_stage(self)
   1121         self._run_sanity_check()
   1122     with torch.autograd.set_detect_anomaly(self._detect_anomaly):
-> 1123         self.fit_loop.run()
   1124     return None
   1125 raise RuntimeError(f"Unexpected state {self.state}")

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/loops/fit_loop.py:209, in _FitLoop.run(self)
    208 def run(self) -> None:
--> 209     self.setup_data()
    210     if self.skip:
    211         return

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/loops/fit_loop.py:238, in _FitLoop.setup_data(self)
    235 log.debug(f"{self.__class__.__name__}: resetting train dataloader")
    237 source = self._data_source
--> 238 train_dataloader = _request_dataloader(source)
    239 trainer.strategy.barrier("train_dataloader()")
    241 if not isinstance(train_dataloader, CombinedLoader):

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:335, in _request_dataloader(data_source)
    324 """Requests a dataloader by calling dataloader hooks corresponding to the given stage.
    325 
    326 Returns:
    327     The requested dataloader
    328 
    329 """
    330 with _replace_dunder_methods(DataLoader, "dataset"), _replace_dunder_methods(BatchSampler):
    331     # under this context manager, the arguments passed to `DataLoader.__init__` will be captured and saved as
    332     # attributes on the instance in case the dataloader needs to be re-instantiated later by Lightning.
    333     # Also, it records all attribute setting and deletion using patched `__setattr__` and `__delattr__`
    334     # methods so that the re-instantiated object is as close to the original as possible.
--> 335     return data_source.dataloader()

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/connectors/data_connector.py:302, in _DataLoaderSource.dataloader(self)
    300 if isinstance(self.instance, pl.LightningDataModule):
    301     assert self.instance.trainer is not None
--> 302     return call._call_lightning_datamodule_hook(self.instance.trainer, self.name)
    303 assert self.instance is not None
    304 return self.instance

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/pytorch/trainer/call.py:199, in _call_lightning_datamodule_hook(trainer, hook_name, *args, **kwargs)
    197 if callable(fn):
    198     with trainer.profiler.profile(f"[LightningDataModule]{trainer.datamodule.__class__.__name__}.{hook_name}"):
--> 199         return fn(*args, **kwargs)
    200 return None

File ~/programming/pytorch-forecasting/pytorch_forecasting/data/data_module/_encoder_decoder_data_module.py:1190, in EncoderDecoderTimeSeriesDataModule.train_dataloader(self)
   1189 def train_dataloader(self):
-> 1190     return DataLoader(
   1191         self.train_dataset,
   1192         batch_size=self.batch_size,
   1193         num_workers=self.num_workers,
   1194         shuffle=True,
   1195         collate_fn=self.collate_fn,
   1196     )

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/fabric/utilities/data.py:325, in _wrap_init_method.<locals>.wrapper(obj, *args, **kwargs)
    322     elif store_explicit_arg in kwargs:
    323         object.__setattr__(obj, f"__{store_explicit_arg}", kwargs[store_explicit_arg])
--> 325 init(obj, *args, **kwargs)
    326 object.__setattr__(obj, "__pl_inside_init", old_inside_init)

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/lightning/fabric/utilities/data.py:325, in _wrap_init_method.<locals>.wrapper(obj, *args, **kwargs)
    322     elif store_explicit_arg in kwargs:
    323         object.__setattr__(obj, f"__{store_explicit_arg}", kwargs[store_explicit_arg])
--> 325 init(obj, *args, **kwargs)
    326 object.__setattr__(obj, "__pl_inside_init", old_inside_init)

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:401, in DataLoader.__init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn, multiprocessing_context, generator, prefetch_factor, persistent_workers, pin_memory_device, in_order)
    399 else:  # map-style
    400     if shuffle:
--> 401         sampler = RandomSampler(dataset, generator=generator)  # type: ignore[arg-type]
    402     else:
    403         sampler = SequentialSampler(dataset)  # type: ignore[arg-type]

File ~/programming/pytorch-forecasting/.venv/lib/python3.13/site-packages/torch/utils/data/sampler.py:149, in RandomSampler.__init__(self, data_source, replacement, num_samples, generator)
    144     raise TypeError(
    145         f"replacement should be a boolean value, but got replacement={self.replacement}"
    146     )
    148 if not isinstance(self.num_samples, int) or self.num_samples <= 0:
--> 149     raise ValueError(
    150         f"num_samples should be a positive integer value, but got num_samples={self.num_samples}"
    151     )

ValueError: num_samples should be a positive integer value, but got num_samples=0

Sure, I did not specify the arguments for TimeSeries_datatype properly, but this error message does not help me at all. I also think this should raise an error on creation time of the time series (seems like group is the missing parameter here!)

I would also think that when doing

ds = tft.predict(ts)

the resulting columns should be exactly named as the input cols when doing

ds.to_pandas()

currently we get:

<img width="393" height="470" alt="Screenshot From 2026-09-02 13-47-43" src="https://github.com/user-attachments/assets/e45e98a7-4cae-484f-9a72-c7cf1885b9eb" />

But I understand that these are secondary issues.

phoeenniixx phoeenniixx commented on Sep 02, 2026 12:00 UTC
Author

Thanks for the review @CloseChoice!

  • For the errors - yes, the error handling is not good rn, but tbh i didnt focus that much on it, as it can be added once we actually implement the classes

  • For the predictions. I think we currently lack the complete implementation of the inverse transforms even, I agree we should have the exact format as the input, this can be easily handled via TimSeries_datatype now. We just need to implement this, it is not present in the current branch
  • The current branch is just a Proof of concept, and if you all like it then we can create complete workstreams and implement each feature step - by - step

    fkiraly fkiraly commented on code on Sep 04, 2026 16:18 UTC
    Code Review
    docs/source/tutorials/new_v2_proto.ipynb:1
    @@ -0,0 +1,1634 @@
    +{
    + "cells": [
    +  {
    +   "metadata": {},
    +   "cell_type": "markdown",
    +   "source": "Install the branch",
    +   "id": "dc4be0556b5e56ff"
    +  },
    +  {
    +   "metadata": {},
    +   "cell_type": "code",
    +   "outputs": [],
    +   "execution_count": null,
    +   "source": [
    +    "!pip install git+https://github.com/phoeenniixx/pytorch-forecasting.git@ptf-new-design"

    general best practice suggestion: jupyter notebooks should not modify the runtime environment...

    phoeenniixx phoeenniixx commented on code on Sep 04, 2026 16:22 UTC
    Code Review
    docs/source/tutorials/new_v2_proto.ipynb:1
    @@ -0,0 +1,1634 @@
    +{
    + "cells": [
    +  {
    +   "metadata": {},
    +   "cell_type": "markdown",
    +   "source": "Install the branch",
    +   "id": "dc4be0556b5e56ff"
    +  },
    +  {
    +   "metadata": {},
    +   "cell_type": "code",
    +   "outputs": [],
    +   "execution_count": null,
    +   "source": [
    +    "!pip install git+https://github.com/phoeenniixx/pytorch-forecasting.git@ptf-new-design"

    yes, this was intentionally added so that people can run this notebook direclty in colab as well if they want to. As we are not going to merge this, I thought it provides the reviewer some flexibility (not setting up ptf in their env) and then pulling the branch.

    fkiraly fkiraly requested changes on Sep 04, 2026 16:30 UTC
    Changes Requested Reviewer

    Very nice! I think this is great!

    I have one question though:

  • why is TimeSeries no longer a Dataset? Is there anything that forces us to move away from standard APIs resp classes? I do not see anything that we could not do with a dataset
  • phoeenniixx phoeenniixx commented on Sep 04, 2026 16:58 UTC
    Author

    * why is TimeSeries no longer a Dataset? Is there anything that forces us to move away from standard APIs resp classes? I do not see anything that we could not do with a dataset

    I think Dataset signifies something more - a data conatiner - and not datatype. And the user should not think that it is another dataset layer, but as a datatype. The dataset makes me think something that handles data and not some otehr representation of data. This data set is never used actually as it is passed to dm for further operations. The thing is - we dont need TimeSeries to be a dataset. It being dataset doesnt add anything over what we have rn as a class, (we can still have __getitem__, etc) but adds some complexity (inheritance)

    I also think in future, we can refactor this datatype to be more "generic" (removing torch or any other dep completely) and be used for "communication" between packages (like sktime and ptf - or maybe even inbetween sktime as well). But the complete idea is still not consolidated in my mind.

    Also, we already have a Private dataset class for each Datamodules, and if we loose anything on not having TimeSeries as Dataset (which i think is None) - we get it anyway via the private dataset classes.

    What do you think? should we move back to it being Dataset?

    fkiraly fkiraly commented on Sep 10, 2026 08:40 UTC
    Contributor

    My thinking is guided by staying close to vanilla torch and lightning conventions with input/data formats (while staying away from the strong coupling to pandas that is a problem in v1).

    This should imo be a strong design principle. Departing from conventions in all parts of the design is not good - it introduces usage friction, and maintenance burden.

    Per my current understanding, Dataset (and/or a child class) is what the user will expect, and is familiar with, as the first object when handling data for torch / lightning - would you agree, or disagree?

    echo-xiao echo-xiao commented on Sep 21, 2026 22:50 UTC
    Contributor

    i think the layered architecture is great. and I found a missing part that could be a small problem.

    i think the trainer lifecycle and repeated-fit contract are undefined. i used a second fit with the same trainer, it silently yields an untrained model marked as fitted. here is the code:

    from lightning.pytorch import Trainer
    from pytorch_forecasting.data.examples import load_toydata
    from pytorch_forecasting._proto._tft_forecaster import TFTForecaster
    from pytorch_forecasting._proto._timeseries_datatype import TimeSeries_datatype
    
    df = load_toydata(20, 50)
    data_january = TimeSeries_datatype(
        df[df["series_id"] < 10], time="time_idx", target="y", group=["series_id"]
    )
    data_february = TimeSeries_datatype(
        df[df["series_id"] >= 10], time="time_idx", target="y", group=["series_id"]
    )
    
    trainer = Trainer(max_epochs=1, logger=False, enable_checkpointing=False)
    forecaster = TFTForecaster(hidden_size=16, num_layers=1, attention_head_size=2,
                               trainer=trainer)
    
    forecaster.fit(data_january)
    step_after_january = trainer.global_step
    model_after_january = forecaster.model_
    
    forecaster.fit(data_february)   # returns without error
    step_after_february = trainer.global_step
    model_after_february = forecaster.model_
    
    print("optimization steps in second fit:", step_after_february - step_after_january)
    print("same model object across fits:   ", model_after_january is model_after_february)
    print("forecaster._is_fitted:           ", forecaster._is_fitted)
    

    here is my output:
    <img width="729" height="128" alt="Screenshot 2026-09-21 at 3 47 58 PM" src="https://github.com/user-attachments/assets/a86c21d7-4934-41f6-bdfd-0f8c7de5f9ff" />

    CloseChoice CloseChoice commented on code on Sep 22, 2026 11:58 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last

    Tbh I am a fan of

    Explicit is better than implicit.

    from the Python Zen and would therefore require the user to specify time and target. All others can have default=None. Num and cat can be inferred from the dtype if not explicitly provided.

    But this is a side discussion and would break code (but that is what major versions are good for).

    CloseChoice CloseChoice commented on code on Sep 22, 2026 12:01 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)

    I would assume the length of a dataset is the number of observations. Maybe I should check how Autogluon and darts handle this.

    CloseChoice CloseChoice commented on code on Sep 22, 2026 12:02 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)
    +
    +    def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
    +        """Get time series data for given index.
    +
    +        Returns
    +        -------
    +        t : numpy.ndarray of shape (n_timepoints,)
    +            Time index for each time point in the past or present. Aligned with `y`,
    +            and `x` not ending in `f`.

    not ending in f? What does that mean

    CloseChoice CloseChoice commented on code on Sep 22, 2026 12:18 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)
    +
    +    def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
    +        """Get time series data for given index.
    +
    +        Returns
    +        -------
    +        t : numpy.ndarray of shape (n_timepoints,)
    +            Time index for each time point in the past or present. Aligned with `y`,
    +            and `x` not ending in `f`.
    +
    +        y : torch.Tensor of shape (n_timepoints, n_targets)
    +            Target values for each time point. Rows are time points, aligned with `t`.
    +
    +        x : torch.Tensor of shape (n_timepoints, n_features)
    +            Features for each time point. Rows are time points, aligned with `t`.
    +
    +        group : torch.Tensor of shape (n_groups,)
    +            Group identifiers for time series instances.
    +
    +        st : torch.Tensor of shape (n_static_features,)
    +            Static features.
    +
    +        cutoff_time : float or numpy.float64
    +            Cutoff time for the time series instance.
    +
    +        Other Returns
    +        -------------
    +        weights : torch.Tensor of shape (n_timepoints,), optional
    +            Only included if weights are not `None`.
    +        """
    +        time = self.time
    +        feature_cols = self.feature_cols
    +        _target = self._target
    +        _known = self._known
    +        _static = self._static
    +        _group = self._group
    +        _groups = self._groups
    +        _group_ids = self._group_ids
    +        weight = self.weight
    +        data_future = self.data_future
    +
    +        group_id = _group_ids[index]
    +
    +        if _group:
    +            mask = _groups[group_id]
    +            data = self.data.loc[mask]
    +        else:
    +            data = self.data
    +
    +        cutoff_time = data[time].max()
    +
    +        # PyTorch wants writeable arrays
    +        data_vals = data[time].to_numpy(copy=True)
    +        data_tgt_vals = data[_target].to_numpy(copy=True)
    +        data_feat_vals = data[feature_cols].to_numpy(copy=True)
    +
    +        result = {
    +            "t": data_vals,
    +            "y": torch.tensor(data_tgt_vals),
    +            "x": torch.tensor(data_feat_vals),
    +            "group": torch.tensor([self._group_to_idx[group_id]], dtype=torch.long),
    +            # PyTorch wants writeable arrays
    +            "st": torch.tensor(
    +                data[_static].iloc[0].to_numpy(copy=True) if _static else []
    +            ),
    +            "cutoff_time": cutoff_time,
    +        }
    +
    +        if data_future is not None:
    +            if _group:
    +                group_arg = (
    +                    self._group[0]
    +                    if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                    else self._group
    +                )
    +                future_mask = self.data_future.groupby(group_arg).groups[group_id]
    +                future_data = self.data_future.loc[future_mask]
    +            else:
    +                future_data = self.data_future
    +
    +            data_fut_vals = future_data[time].values
    +
    +            combined_times = np.concatenate([data_vals, data_fut_vals])

    Is this just the numpy version of

    data["source"] = "data"
    future_data["source"] = "future_data"
    df_complete = pd.concat([data, future_data])
    df_complete.duplicated(subset=["time"], keep="first")
    
    data = df_complete[df_complete["source"] == "data"]
    future_data = df_complete[df_complete["source"] == "future_data"]
    
    ...
    

    ?

    CloseChoice CloseChoice commented on code on Sep 23, 2026 09:39 UTC
    Code Review
    pytorch_forecasting/data/data_module/_encoder_decoder_data_module.py:1
    @@ -215,13 +331,52 @@ def _build_cont_scalers(self):
                 if name in self._scalers
             ]
     
    +    def with_data(
    +        self,
    +        data: Union[TimeSeries, "TimeSeries_datatype"],  # noqa: F821

    when should the renaming of TimeSeries_datatype -> TimeSeries happen.

    CloseChoice CloseChoice commented on code on Sep 23, 2026 13:13 UTC
    Code Review
    pytorch_forecasting/data/data_module/_encoder_decoder_data_module.py:1
    @@ -295,30 +444,32 @@ def _prepare_metadata(self):
                 static_cont_count = (
                     len(self.time_series_metadata["cols"]["st"]) - static_cat_count
                 )
    -
    -            metadata["static_categorical_features"] = static_cat_count
    -            metadata["static_continuous_features"] = static_cont_count
             else:
    -            metadata["static_categorical_features"] = 0
    -            metadata["static_continuous_features"] = 0
    -
    -        metadata.update(
    -            {
    -                "max_encoder_length": self.max_encoder_length,
    -                "max_prediction_length": self.max_prediction_length,
    -                "min_encoder_length": self._min_encoder_length,
    -                "min_prediction_length": self._min_prediction_length,
    -            }
    +            static_cat_count = 0
    +            static_cont_count = 0
    +
    +        return DataModuleMetadata(
    +            encoder_cat=encoder_cat_count,
    +            encoder_cont=encoder_cont_count,
    +            decoder_cat=decoder_cat_count,
    +            decoder_cont=decoder_cont_count,
    +            target=target_count,
    +            static_categorical_features=static_cat_count,
    +            static_continuous_features=static_cont_count,
    +            max_encoder_length=self.max_encoder_length,
    +            max_prediction_length=self.max_prediction_length,
    +            min_encoder_length=self._min_encoder_length,
    +            min_prediction_length=self._min_prediction_length,
             )
     
    -        return metadata
    -
         @property
         def metadata(self):

    return type annotation would be good.

    CloseChoice CloseChoice requested changes on Sep 23, 2026 13:13 UTC
    Changes Requested Reviewer

    Requested changes.

    phoeenniixx phoeenniixx commented on code on Sep 23, 2026 14:57 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last

    Yeah this is soemthing that we should discuss, i am not very sure which parts should be inferred directly. What are your preferences?

    But this is a side discussion and would break code (but that is what major versions are good for).

    Yes. that is why we should settle it now, before we make this new design public?

    phoeenniixx phoeenniixx commented on code on Sep 23, 2026 15:00 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)

    Umm, the no of groups are kinda same thing, no? What do you suggest? it should be total no of data points? But in some cases no of groups might define the actual data correctly, mainly because we send the __getitem__ here currently "per group" - meaning dataset[idx] would give group at that idx

    phoeenniixx phoeenniixx commented on code on Sep 23, 2026 15:02 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)
    +
    +    def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
    +        """Get time series data for given index.
    +
    +        Returns
    +        -------
    +        t : numpy.ndarray of shape (n_timepoints,)
    +            Time index for each time point in the past or present. Aligned with `y`,
    +            and `x` not ending in `f`.

    future

    phoeenniixx phoeenniixx commented on code on Sep 23, 2026 15:04 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)
    +
    +    def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
    +        """Get time series data for given index.
    +
    +        Returns
    +        -------
    +        t : numpy.ndarray of shape (n_timepoints,)
    +            Time index for each time point in the past or present. Aligned with `y`,
    +            and `x` not ending in `f`.

    I think the docstring is not clear enough, I will update this in #2410.
    Thanks!

    phoeenniixx phoeenniixx commented on code on Sep 23, 2026 15:07 UTC
    Code Review
    pytorch_forecasting/_proto/_timeseries_datatype.py:1
    @@ -0,0 +1,459 @@
    +"""
    +``TimeSeries`` datatype - prototype for the v2 redesign.
    +"""
    +
    +from dataclasses import dataclass, field, fields, replace
    +from typing import Any
    +from warnings import warn
    +
    +import numpy as np
    +import pandas as pd
    +import torch
    +
    +from pytorch_forecasting.utils._coerce import _coerce_to_list
    +
    +__all__ = ["TimeSeriesMetadata", "TimeSeries_datatype"]
    +
    +
    +@dataclass(frozen=True)
    +class TimeSeriesMetadata:
    +    """Schema of a :class:`TimeSeries_datatype`.
    +
    +    Same content as the ``metadata`` dict of ``TimeSeries``, as a dataclass.
    +    Mapping-style access is kept so that code written against the dict version
    +    keeps working.
    +
    +    Parameters
    +    ----------
    +    cols : dict { 'y': list[str], 'x': list[str], 'st': list[str] }
    +        Names of columns for y, x, and static features, in the same order as
    +        the column dimensions of the corresponding tensors.
    +    col_type : dict[str, str]
    +        Maps column names to "F" (numerical) or "C" (categorical).
    +    col_known : dict[str, str]
    +        Maps column names to "K" (future known) or "U" (future unknown).
    +    is_prediction : bool, default=False
    +        Whether the object holds predictions. Predictions have no static
    +        features and no known/unknown split.
    +    """
    +
    +    cols: dict[str, list[str]]
    +    col_type: dict[str, str] = field(default_factory=dict)
    +    col_known: dict[str, str] = field(default_factory=dict)
    +    is_prediction: bool = False
    +
    +    def __getitem__(self, key: str) -> Any:
    +        if key not in self.keys():
    +            raise KeyError(key)
    +        return getattr(self, key)
    +
    +    def get(self, key: str, default: Any = None) -> Any:
    +        if key not in self.keys():
    +            return default
    +        return getattr(self, key)
    +
    +    def keys(self) -> list[str]:
    +        return [f.name for f in fields(self)]
    +
    +    def __contains__(self, key: object) -> bool:
    +        return key in self.keys()
    +
    +    def __iter__(self):
    +        return iter(self.keys())
    +
    +
    +class TimeSeries_datatype:
    +    """Container for time series data stored in a pandas DataFrame.
    +
    +    Parameters
    +    ----------
    +    data : pd.DataFrame
    +        data frame with sequence data.
    +        Column names must all be str, and contain str as referred to below.
    +    data_future : pd.DataFrame, optional, default=None
    +        data frame with future data.
    +        May contain only columns that are in time, group, weight, known,
    +        or static.
    +    time : str, optional, default = first col not in group_ids, weight, target,
    +        static.
    +        integer typed column denoting the time index within ``data``.
    +    target : str or List[str], optional, default = last column (at iloc -1)
    +        column(s) in ``data`` denoting the forecasting target.
    +    group : List[str], optional, default = None
    +        list of column names identifying a time series instance within ``data``.
    +    weight : str, optional, default=None
    +        column name for weights.
    +    num : list of str, optional, default = all columns with dtype in "fi"
    +        list of numerical variables in ``data``.
    +    cat : list of str, optional, default = all columns with dtype in "Obc"
    +        list of categorical variables in ``data``.
    +    known : list of str, optional, default = all variables
    +        list of variables that change over time and are known in the future.
    +    unknown : list of str, optional, default = no variables
    +        list of variables that are not known in the future.
    +    static : list of str, optional, default = all variables not in known, unknown
    +        list of variables that do not change over time.
    +    """
    +
    +    def __init__(
    +        self,
    +        data: pd.DataFrame,
    +        data_future: pd.DataFrame | None = None,
    +        time: str | None = None,
    +        target: str | list[str] | None = None,
    +        group: list[str] | None = None,
    +        weight: str | None = None,
    +        num: list[str | list[str]] | None = None,
    +        cat: list[str | list[str]] | None = None,
    +        known: list[str | list[str]] | None = None,
    +        unknown: list[str | list[str]] | None = None,
    +        static: list[str | list[str]] | None = None,
    +    ):
    +        self.data = data
    +        self.data_future = data_future
    +        self.time = time
    +        self.target = target
    +        self.group = group
    +        self.weight = weight
    +        self.num = num
    +        self.cat = cat
    +        self.known = known
    +        self.unknown = unknown
    +        self.static = static
    +
    +        warn(
    +            "TimeSeries_datatype is a prototype of the reworked "
    +            "pytorch-forecasting data layer, for design testing only. "
    +            "It is not part of the public API and may change or disappear "
    +            "without warning. Feedback and suggestions are very welcome in "
    +            "pytorch-forecasting issue 1736, "
    +            "https://github.com/sktime/pytorch-forecasting/issues/1736",
    +            UserWarning,
    +        )
    +
    +        # handle defaults, coercion, and derived attributes
    +        self._target = _coerce_to_list(target)
    +        self._group = _coerce_to_list(group)
    +        self._num = _coerce_to_list(num)
    +        self._cat = _coerce_to_list(cat)
    +        self._known = _coerce_to_list(known)
    +        self._unknown = _coerce_to_list(unknown)
    +        self._static = _coerce_to_list(static)
    +
    +        self._infer_columns()
    +
    +        self.feature_cols = [
    +            col
    +            for col in data.columns
    +            if col not in [self.time] + self._group + [self.weight] + self._target
    +        ]
    +        if self._group:
    +            group_arg = (
    +                self._group[0]
    +                if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                else self._group
    +            )
    +            self._groups = self.data.groupby(group_arg).groups
    +            self._group_ids = list(self._groups.keys())
    +        else:
    +            self._groups = {"_single_group": self.data.index}
    +            self._group_ids = ["_single_group"]
    +        # create mapping from group id to index for efficient lookup
    +        self._group_to_idx = {gid: i for i, gid in enumerate(self._group_ids)}
    +
    +        self._prepare_metadata()
    +
    +        # overwrite __init__ params for upwards compatibility with AS PRs
    +        self.group = self._group
    +        self.target = self._target
    +        self.num = self._num
    +        self.cat = self._cat
    +        self.known = self._known
    +        self.unknown = self._unknown
    +        self.static = self._static
    +
    +    def _infer_columns(self):
    +        """Fill in ``time``, ``target``, ``num`` and ``cat`` from the data frame.
    +
    +        Applies the defaults promised by the docstring: target is the last
    +        column, time is the first column not otherwise spoken for, and the
    +        num/cat split follows the column dtypes.
    +        """
    +        cols = list(self.data.columns)
    +
    +        if not self._target:
    +            self._target = [cols[-1]]
    +
    +        if self.time is None:
    +            taken = set(self._group) | set(self._target) | set(self._static)
    +            taken.add(self.weight)
    +            self.time = next((col for col in cols if col not in taken), None)
    +            if self.time is None:
    +                raise ValueError(
    +                    "no column is left to use as the time index: every column "
    +                    f"of `data` ({cols}) is already used as group, target, "
    +                    "static or weight. Pass `time` explicitly."
    +                )
    +
    +        index_cols = set(self._group) | {self.time, self.weight}
    +        typed = [col for col in cols if col not in index_cols]
    +
    +        if not self._num and not self._cat:
    +            self._num = [c for c in typed if self.data[c].dtype.kind in "fi"]
    +            self._cat = [c for c in typed if self.data[c].dtype.kind in "Obc"]
    +
    +    def _prepare_metadata(self):
    +        """Prepare metadata for the dataset.
    +
    +        Same content as ``TimeSeries._prepare_metadata``, but stored as a
    +        :class:`TimeSeriesMetadata` instead of a dict.
    +        """
    +        col_type = {}
    +        col_known = {}
    +
    +        for col in self._target + self.feature_cols + self._static:
    +            col_type[col] = "C" if col in self._cat else "F"
    +            col_known[col] = "K" if col in self._known else "U"
    +
    +        self.metadata = TimeSeriesMetadata(
    +            cols={
    +                "y": self._target,
    +                "x": self.feature_cols,
    +                "st": self._static,
    +            },
    +            col_type=col_type,
    +            col_known=col_known,
    +        )
    +
    +    def __len__(self) -> int:
    +        """Return number of time series in the dataset."""
    +        return len(self._group_ids)
    +
    +    def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
    +        """Get time series data for given index.
    +
    +        Returns
    +        -------
    +        t : numpy.ndarray of shape (n_timepoints,)
    +            Time index for each time point in the past or present. Aligned with `y`,
    +            and `x` not ending in `f`.
    +
    +        y : torch.Tensor of shape (n_timepoints, n_targets)
    +            Target values for each time point. Rows are time points, aligned with `t`.
    +
    +        x : torch.Tensor of shape (n_timepoints, n_features)
    +            Features for each time point. Rows are time points, aligned with `t`.
    +
    +        group : torch.Tensor of shape (n_groups,)
    +            Group identifiers for time series instances.
    +
    +        st : torch.Tensor of shape (n_static_features,)
    +            Static features.
    +
    +        cutoff_time : float or numpy.float64
    +            Cutoff time for the time series instance.
    +
    +        Other Returns
    +        -------------
    +        weights : torch.Tensor of shape (n_timepoints,), optional
    +            Only included if weights are not `None`.
    +        """
    +        time = self.time
    +        feature_cols = self.feature_cols
    +        _target = self._target
    +        _known = self._known
    +        _static = self._static
    +        _group = self._group
    +        _groups = self._groups
    +        _group_ids = self._group_ids
    +        weight = self.weight
    +        data_future = self.data_future
    +
    +        group_id = _group_ids[index]
    +
    +        if _group:
    +            mask = _groups[group_id]
    +            data = self.data.loc[mask]
    +        else:
    +            data = self.data
    +
    +        cutoff_time = data[time].max()
    +
    +        # PyTorch wants writeable arrays
    +        data_vals = data[time].to_numpy(copy=True)
    +        data_tgt_vals = data[_target].to_numpy(copy=True)
    +        data_feat_vals = data[feature_cols].to_numpy(copy=True)
    +
    +        result = {
    +            "t": data_vals,
    +            "y": torch.tensor(data_tgt_vals),
    +            "x": torch.tensor(data_feat_vals),
    +            "group": torch.tensor([self._group_to_idx[group_id]], dtype=torch.long),
    +            # PyTorch wants writeable arrays
    +            "st": torch.tensor(
    +                data[_static].iloc[0].to_numpy(copy=True) if _static else []
    +            ),
    +            "cutoff_time": cutoff_time,
    +        }
    +
    +        if data_future is not None:
    +            if _group:
    +                group_arg = (
    +                    self._group[0]
    +                    if isinstance(self._group, (list, tuple)) and len(self._group) == 1
    +                    else self._group
    +                )
    +                future_mask = self.data_future.groupby(group_arg).groups[group_id]
    +                future_data = self.data_future.loc[future_mask]
    +            else:
    +                future_data = self.data_future
    +
    +            data_fut_vals = future_data[time].values
    +
    +            combined_times = np.concatenate([data_vals, data_fut_vals])

    kinda similar i think, we do concatenate past and future, but we also sort them for each unique time stamp

    phoeenniixx phoeenniixx commented on code on Sep 23, 2026 15:09 UTC
    Code Review
    pytorch_forecasting/data/data_module/_encoder_decoder_data_module.py:1
    @@ -215,13 +331,52 @@ def _build_cont_scalers(self):
                 if name in self._scalers
             ]
     
    +    def with_data(
    +        self,
    +        data: Union[TimeSeries, "TimeSeries_datatype"],  # noqa: F821

    I think this should happen in #2423

    agobbifbk agobbifbk commented on Oct 07, 2026 12:13 UTC
    Contributor

    I have some comments too, they may overlap with the previous be patient in case:

    1- Minimal - with Forecaster:

    for me is ok to have this kind of minimum engagement BUT: the context and the future steps should me mandatory without default, at least the user should set reasonable numbers by himself. Moreover i would like to see something like: I will use these covariates in the past and these in the future (categorical too) like a signature or __repr__ of the object. Moreover TimeSeries_datatype is a strange name, this is a specific D1 layer for CSV and pandas, the name should suggest this no? Finally:

    preds.to_pandas().head()
    

    the results should have the same names as the input, reporting also the real value (if we do backtesting), the time index of the prediction (this prediction has been made at time t) and the lag otherwise we can not do backtesting.

    3- Minimal without forecaster:
    Also in this case is not clear to the user where he need to put information about the context length and horizon steps. In this case i think is the D2 layers that governs the choice right? Again not clear for the user that he needs 3 ingredients: d1, d2 and model. Maybe a naming convention can help (some prefix or suffix in the class names?)

    General consideration:

  • I still don't get why there are TorchNormalizer and sklearn scaler mixed, why we don't scale the target as the same as we scale the inputs? Moreover if I have 20 covariates I need to define a scaler for each?

  • I would like to see in the notebook also the save-load procedure
  • Hope this can help, happy to answer questions during weekly meeting if something is not clear!

    THX for the work!

    Reviewers
    Assignees
    phoeenniixx phoeenniixx
    Labels
    risk: low confidence: 89.2% 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: 57.3% (MEDIUM) · Higher = larger blast radius
    57.3%
    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: 89.2% · Lower = rushed or shallow review
    89.2%
    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: 6.2% · Safe to merge
    6.2%