Skip to content

FoundationModel¶

skforecast.foundation._foundation_model.FoundationModel ¶

FoundationModel(model_id, **kwargs)

Scikit-learn compatible interface for foundation time-series models.

Currently supports Amazon Chronos-2, Google TimesFM 2.5 and 3.0, Salesforce Moirai-2, TabICLv2, TabPFN-TS, TFC-T0, Synthefy Nori and EDF Lab TS-ICL. For full skforecast ecosystem integration (backtesting, model selection, etc.) use ForecasterFoundation instead.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID. The adapter is resolved automatically from the model_id prefix. Available model IDs:

Amazon Chronos-2 (supports exog):

  • 'amazon/chronos-2'
  • 'autogluon/chronos-2-small'
  • 'autogluon/chronos-2-synth'

Google TimesFM 2.5 (does not support exog):

  • 'google/timesfm-2.5-200m-pytorch'

Google TimesFM 3.0 (supports exog):

  • 'google/timesfm-3.0-pytorch'

Salesforce Moirai-2 (does not support exog):

  • 'Salesforce/moirai-2.0-R-small'

TabICLv2 (supports exog):

  • 'soda-inria/tabicl'

Prior Labs TabPFN-TS (supports exog):

  • 'priorlabs/tabpfn-ts'

The Forecasting Company T0 (supports exog):

  • 'theforecastingcompany/t0-alpha'

Synthefy Nori (supports exog):

  • 'Synthefy/Nori'
  • 'Synthefy/Nori-30M'
  • 'Synthefy/Nori-100M'

EDF Lab TS-ICL (supports exog):

  • 'taharnbl/TS-ICL'

See References for links to model documentation and model cards.

required
**kwargs Any

Additional keyword arguments forwarded to the underlying adapter. Valid keys depend on the model selected by model_id. See the corresponding adapter class documentation or the model card linked in the References section below for the full parameter list.

Commonly used kwargs by model:

  • Amazon Chronos-2 (ChronosAdapter): context_length (int, default 8192), device_map (str, default 'auto'), torch_dtype (object, default None), predict_kwargs (dict, default None), cross_learning (bool, default False).
  • Google TimesFM 2.5 (TimesFM25Adapter): context_length (int, default 512), max_horizon (int, default 512), forecast_config_kwargs (dict, default None).
  • Google TimesFM 3.0 (TimesFM3Adapter): context_length (int, default 2048), device (str, default 'auto'), predict_kwargs (dict, default None).
  • Salesforce Moirai-2 (MoiraiAdapter): context_length (int, default 2048), device (str, default 'auto').
  • TabICLv2 (TabICLAdapter): context_length (int, default 4096), point_estimate (str, default 'mean'), tabicl_config (dict, default None), temporal_features (list, default None), show_progress (bool, default False; set to True to show the tqdm bar emitted during inference).
  • Prior Labs TabPFN-TS (TabPFNAdapter): context_length (int, default 32768), mode (str, default 'local'), point_estimate (str, default 'median'), tabpfn_model_config (dict, default None), temporal_features (list, default None), show_progress (bool, default False; set to True to show the tqdm bar emitted during inference).
  • The Forecasting Company T0 (T0Adapter): context_length (int, default 8192), device_map (str, default 'auto'), torch_dtype (object, default None).
  • Synthefy Nori (NoriAdapter): context_length (int, default 4096), point_estimate (str, default 'mean'), add_calendar_features (bool, default True), n_fourier_terms (int, default 2), nori_config (dict, default None).
  • EDF Lab TS-ICL (TSICLAdapter): checkpoint_version (str, default 'tsicl-v1.ckpt'), context_length (int, default 4096), device (str, default 'auto'), allow_auto_download (bool, default True).
{}

Attributes:

Name Type Description
adapter object

The underlying adapter instance, instantiated automatically based on the model_id prefix. The concrete type depends on the model, e.g. ChronosAdapter for autogluon/chronos-* models.

model_id str

HuggingFace model ID. Mirrors adapter.model_id.

context_ dict[str, pandas Series]

Per-series dict of pandas Series containing the last context_length observations from the training data, stored during fit. Mirrors adapter.context_.

context_exog_ dict

Per-series dict of pandas DataFrame containing the last context_length exog variables from the training data, stored during fit. None if the adapter does not support exogenous variables or no exog was provided. Mirrors adapter.context_exog_.

context_length int

Maximum number of historical observations used as context. Mirrors adapter.context_length.

allow_exog bool

Whether the underlying adapter supports exogenous variables.

supports_past_only_covariates bool

Whether the underlying adapter uses historical exog columns that have no future values as past-only covariates. If False, such columns are ignored at predict time and an IgnoredArgumentWarning is issued.

supports_heterogeneous_covariates bool

Whether the underlying adapter can forecast series with different exog columns in the same backend call. If False, series are grouped by their exog columns at predict time and the adapter is called once per group.

supports_nan_in_series bool

Whether the underlying adapter accepts NaN values in the series used as context. If False, a context with NaN raises a ValueError at predict time.

index_type_ type

Type of index of the input used in training.

index_freq_ pandas DateOffset, int

Frequency of the index of the input used in training. A pandas DateOffset for DatetimeIndex or an int step for RangeIndex.

context_range_ dict[str, pandas Index]

First and last values of the index of the data used during training for each series.

series_names_in_ list

Names of the series (levels) provided by the user during training.

is_multiple_series_ bool

Whether the model was fitted with multiple series.

exog_in_ bool

If the model has been trained using exogenous variable/s.

exog_names_in_ list

Names of the exogenous variables used during training. None if no exog was provided.

exog_names_in_per_series_ dict

Names of the exogenous variables used during training for each series. None if no exog was provided.

exog_type_in_ type

Type of exogenous variable/s used in training. None if no exog was provided.

creation_date str

Date of creation.

is_fitted bool

Tag to identify if the model has been fitted (trained).

fit_date str

Date of last fit.

skforecast_version str

Version of skforecast library used to create the model.

python_version str

Version of python used to create the model.

Notes

Each adapter imports its own backend library lazily (i.e. inside the method that first needs it) rather than at module level. This means that only the library required by the adapter you actually use needs to be installed, other foundation-model backends remain optional.

Device handling is not uniform across adapters; each mirrors the convention of its own backend, so the kwarg used to select the device differs by model:

  • device_map (plus torch_dtype), HuggingFace from_pretrained style: Chronos, T0.
  • device string, resolved internally to a concrete accelerator: Moirai, TS-ICL, TimesFM 3.0.
  • Through the backend configuration dict: TabICL (tabicl_config), TabPFN (tabpfn_model_config), Nori (nori_config).
  • No device parameter: TimesFM 2.5, which relies on its backend's own default device selection.
References

.. [1] Amazon Chronos - GitHub repository. https://github.com/amazon-science/chronos-forecasting

.. [2] Amazon Chronos - HuggingFace collection. https://huggingface.co/collections/amazon/chronos-models-65f1791d630a8d57cb718444

.. [3] Google TimesFM - GitHub repository. https://github.com/google-research/timesfm

.. [4] Google TimesFM - HuggingFace collection. https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6

.. [5] Salesforce Moirai (uni2ts) - GitHub repository. https://github.com/SalesforceAIResearch/uni2ts

.. [6] Salesforce Moirai-R - HuggingFace collection. https://huggingface.co/collections/Salesforce/moirai-r-models-65c8d3a94c51428c300e0742

.. [7] TabICL - GitHub repository. https://github.com/soda-inria/tabicl

.. [8] TabICL - Documentation. https://tabicl.readthedocs.io/en/latest/

.. [9] TabPFN-TS - GitHub repository. https://github.com/PriorLabs/tabpfn-time-series

.. [10] Prior Labs TabPFN - Documentation. https://docs.priorlabs.ai/

.. [11] The Forecasting Company T0 - GitHub repository. https://github.com/theforecastingcompany/tfc-t0

.. [12] The Forecasting Company T0 - HuggingFace model card. https://huggingface.co/theforecastingcompany/t0-alpha

.. [13] Synthefy Nori - GitHub repository. https://github.com/Synthefy/synthefy-nori

.. [14] Synthefy Nori - HuggingFace model card. https://huggingface.co/Synthefy/Nori

.. [15] EDF Lab TS-ICL - GitHub repository. https://github.com/EDF-Lab/ts-icl

.. [16] EDF Lab TS-ICL - HuggingFace model card. https://huggingface.co/taharnbl/TS-ICL

Methods:

Name Description
fit

Fit the model by storing the training series and optional exog.

predict

Predict n steps ahead.

get_params

Get parameters for this estimator (sklearn-compatible).

set_params

Set parameters for this estimator (sklearn-compatible).

Source code in skforecast/foundation/_foundation_model.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def __init__(
    self,
    model_id: str,
    **kwargs: Any,
) -> None:

    adapter_cls                    = _resolve_adapter(model_id)
    self.adapter                   = adapter_cls(model_id=model_id, **kwargs)
    self.index_type_               = None
    self.index_freq_               = None
    self.context_range_            = None
    self.series_names_in_          = None
    self.is_multiple_series_       = False
    self.exog_in_                  = False
    self.exog_names_in_            = None
    self.exog_names_in_per_series_ = None
    self.exog_type_in_             = None
    self.creation_date             = pd.Timestamp.today().strftime('%Y-%m-%d %H:%M:%S')
    self.fit_date                  = None
    self.skforecast_version        = __version__
    self.python_version            = sys.version.split(" ")[0]

Attributes¶

adapter instance-attribute ¶

adapter = adapter_cls(model_id=model_id, **kwargs)

index_type_ instance-attribute ¶

index_type_ = None

index_freq_ instance-attribute ¶

index_freq_ = None

context_range_ instance-attribute ¶

context_range_ = None

series_names_in_ instance-attribute ¶

series_names_in_ = None

is_multiple_series_ instance-attribute ¶

is_multiple_series_ = False

exog_in_ instance-attribute ¶

exog_in_ = False

exog_names_in_ instance-attribute ¶

exog_names_in_ = None

exog_names_in_per_series_ instance-attribute ¶

exog_names_in_per_series_ = None

exog_type_in_ instance-attribute ¶

exog_type_in_ = None

creation_date instance-attribute ¶

creation_date = pd.Timestamp.today().strftime(
    "%Y-%m-%d %H:%M:%S"
)

fit_date instance-attribute ¶

fit_date = None

skforecast_version instance-attribute ¶

skforecast_version = __version__

python_version instance-attribute ¶

python_version = sys.version.split(' ')[0]

model_id property ¶

model_id

HuggingFace model ID.

Returns:

Name Type Description
model_id str

HuggingFace model ID. Mirrors adapter.model_id.

context_ property ¶

context_

Context stored during fit, used as default context for predict if no override is provided.

Returns:

Name Type Description
context_ dict[str, Series]

Per-series dict of pandas Series containing the last context_length observations from the training data, stored during fit. Mirrors adapter.context_.

context_exog_ property ¶

context_exog_

Context stored during fit, used as default context for predict if no override is provided.

Returns:

Name Type Description
context_exog_ (dict[str, DataFrame], None)

Per-series dict of pandas DataFrame containing the last context_length exog variables from the training data, stored during fit. None if the adapter does not support exogenous variables or no exog was provided. Mirrors adapter.context_exog_.

context_length property ¶

context_length

Maximum number of historical observations used as context.

Returns:

Name Type Description
context_length int

Maximum context length. Mirrors adapter.context_length.

allow_exog property ¶

allow_exog

Whether the underlying adapter supports exogenous variables.

Returns:

Name Type Description
allow_exog bool

True if the adapter accepts and uses exog; False if it ignores covariates (e.g. TimesFM 2.5, Moirai-2).

supports_past_only_covariates property ¶

supports_past_only_covariates

Whether the underlying adapter uses historical exog columns without future values as past-only covariates.

Returns:

Name Type Description
supports_past_only_covariates bool

True if a column present in the historical exog but absent from the future exog is used as a past-only covariate (Chronos-2, TS-ICL, TimesFM 3.0). False if the adapter only uses covariates that also have future values, in which case such columns are ignored and an IgnoredArgumentWarning is issued at predict time (TabICL, TabPFN-TS, TFC-T0, Nori).

supports_heterogeneous_covariates property ¶

supports_heterogeneous_covariates

Whether the underlying adapter can forecast series with different exog columns in the same backend call.

Returns:

Name Type Description
supports_heterogeneous_covariates bool

True if the backend accepts, in one call, series whose exog columns differ (TFC-T0, TabPFN-TS, Nori, and the adapters that ignore exog). False if every series in a call must have the same columns (Chronos-2, TS-ICL, TabICL, TimesFM 3.0); in that case predict groups the series by their exog columns and calls the adapter once per group.

supports_nan_in_series property ¶

supports_nan_in_series

Whether the underlying adapter accepts NaN values in the series used as context.

Returns:

Name Type Description
supports_nan_in_series bool

True if a context with NaN values can be forwarded to the backend. False if predict must raise a ValueError when any series of the context contains NaN.

is_fitted property ¶

is_fitted

Whether the model has been fitted.

Returns:

Name Type Description
is_fitted bool

True after fit has been called at least once, False otherwise.

Methods:¶

fit ¶

fit(series, exog=None)

Fit the model by storing the training series and optional exog.

Parameters:

Name Type Description Default
series pandas Series, pandas DataFrame, dict

Training time series.

  • If pandas Series: single-series mode.
  • If wide pandas DataFrame (each column = one series): multi-series mode.
  • If dict[str, pandas Series]: multi-series mode; keys are series names.
required
exog pandas Series, pandas DataFrame, dict

Historical exogenous variables aligned to series.

  • If pandas Series or pandas DataFrame: broadcast to all series.
  • If dict: per-series exogenous variables.
None

Returns:

Name Type Description
self FoundationModel
Source code in skforecast/foundation/_foundation_model.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
def fit(
    self,
    series: pd.Series | pd.DataFrame | dict[str, pd.Series],
    exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
) -> FoundationModel:
    """
    Fit the model by storing the training series and optional exog.

    Parameters
    ----------
    series : pandas Series, pandas DataFrame, dict
        Training time series.

        - If `pandas Series`: single-series mode.
        - If wide `pandas DataFrame` (each column = one series):
        multi-series mode.
        - If `dict[str, pandas Series]`: multi-series mode; keys are
        series names.
    exog : pandas Series, pandas DataFrame, dict, default None
        Historical exogenous variables aligned to `series`.

        - If `pandas Series` or `pandas DataFrame`: broadcast to all
        series.
        - If `dict`: per-series exogenous variables.

    Returns
    -------
    self : FoundationModel

    """

    self.index_type_                = None
    self.index_freq_                = None
    self.context_range_             = None
    self.series_names_in_           = None
    self.is_multiple_series_        = False
    self.exog_in_                   = False
    self.exog_names_in_             = None
    self.exog_names_in_per_series_  = None
    self.exog_type_in_              = None
    self.fit_date                   = None

    context, series_indexes, series_names_in_, context_exog, exog_names_in_ = (
        self._check_preprocess_context(
            series = series,
            exog   = exog,
        )
    )

    self.adapter.fit(
        context      = context,
        context_exog = context_exog,
    )

    self.series_names_in_    = series_names_in_
    self.is_multiple_series_ = len(series_names_in_) > 1

    if context_exog is not None and len(exog_names_in_) > 0:
        self.exog_in_ = True
        self.exog_names_in_ = exog_names_in_
        self.exog_names_in_per_series_ = {
            k: list(v.columns) if v is not None else None
            for k, v in context_exog.items()
        }
        self.exog_type_in_ = type(exog)

    self.fit_date = pd.Timestamp.today().strftime('%Y-%m-%d %H:%M:%S')
    self.context_range_ = {
        series_name: series_index[[0, -1]]
        for series_name, series_index in series_indexes.items()
    }
    self.index_type_ = type(series_indexes[series_names_in_[0]])
    if isinstance(series_indexes[series_names_in_[0]], pd.DatetimeIndex):
        self.index_freq_ = series_indexes[series_names_in_[0]].freq
    else:
        self.index_freq_ = series_indexes[series_names_in_[0]].step

    return self

predict ¶

predict(
    steps,
    levels=None,
    context=None,
    context_exog=None,
    exog=None,
    quantiles=None,
    check_inputs=True,
)

Predict n steps ahead.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
levels (str, list)

Subset of series to predict. If None, all series in context are predicted.

None
context pandas Series, pandas DataFrame, dict

Override the stored context with this window.

  • If pandas Series: single-series override.
  • If wide pandas DataFrame or dict[str, pandas Series]: multi-series override.
None
context_exog pandas Series, pandas DataFrame, dict

Historical exog corresponding to context.

None
exog pandas Series, pandas DataFrame, dict

Future known exogenous variables for the forecast horizon.

  • If pandas Series or pandas DataFrame: broadcast to all series.
  • If dict: per-series exogenous variables.
None
quantiles (list, tuple)

Quantile levels to return, e.g. [0.1, 0.5, 0.9]. If None, returns a point forecast (median).

None
check_inputs bool

If True, the context and context_exog inputs are validated and normalized via _check_preprocess_context and the columns of exog are validated against context_exog. If False, context must already be a dict[str, pandas Series] and context_exog must be a dict[str, pandas DataFrame | None] or None; context_exog and exog are still aligned to the context and to the forecast horizon. This argument is created for internal use and is not recommended to be changed.

True

Returns:

Name Type Description
predictions pandas DataFrame

Value of predictions. The DataFrame includes the following columns:

  • level: Name of the series.
  • pred: Predicted values (point forecast, median).

If quantiles is not None, the pred column is replaced by one column per quantile level (e.g., q_0.1, q_0.5, q_0.9).

Notes

Foundation models are pre-trained and do not learn from the data passed to fit. The fit method only stores context (the last context_length observations) and metadata. This leads to four distinct behaviors depending on the combination of is_fitted and context:

  • Not fitted, context=None: raises ValueError. There is no context available for prediction.
  • Fitted, context=None: uses the context and context_exog_ stored during fit. If the user supplies context_exog, it is ignored with a warning.
  • Not fitted, context provided (zero-shot mode): The model uses context and context_exog (if provided) as context for prediction.
  • Fitted, context provided: Stored context is ignored, the provided context and context_exog (if provided) are used for prediction.

When the adapter supports exogenous variables, the columns of the future exog are validated per series against the historical exog used as context. A future column with no historical values raises a ValueError. A historical column with no future values is a past-only covariate: it is used as such when supports_past_only_covariates is True, and ignored with an IgnoredArgumentWarning otherwise.

Before calling the adapter, the historical exog of each series is aligned to the index of its context and the future exog to its forecast horizon (missing timestamps are filled with NaN and reported with a MissingValuesWarning). Each series keeps its own exog columns. When supports_heterogeneous_covariates is False, the series are grouped by their exog columns (past-only and future) and the adapter is called once per group, so the prediction of a series never depends on the exog columns of the other series.

Source code in skforecast/foundation/_foundation_model.py
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
def predict(
    self,
    steps: int,
    levels: str | list[str] | None = None,
    context: pd.Series | pd.DataFrame | dict[str, pd.Series] | None = None,
    context_exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
    exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
    quantiles: list[float] | tuple[float] | None = None,
    check_inputs: bool = True,
) -> pd.DataFrame:
    """
    Predict n steps ahead.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    levels : str, list, default None
        Subset of series to predict. If `None`, all series in `context` are 
        predicted. 
    context : pandas Series, pandas DataFrame, dict, default None
        Override the stored context with this window.

        - If `pandas Series`: single-series override.
        - If wide `pandas DataFrame` or `dict[str, pandas Series]`:
        multi-series override.
    context_exog : pandas Series, pandas DataFrame, dict, default None
        Historical exog corresponding to `context`.
    exog : pandas Series, pandas DataFrame, dict, default None
        Future known exogenous variables for the forecast horizon.

        - If `pandas Series` or `pandas DataFrame`: broadcast to all
        series.
        - If `dict`: per-series exogenous variables.
    quantiles : list, tuple, default None
        Quantile levels to return, e.g. `[0.1, 0.5, 0.9]`. If `None`,
        returns a point forecast (median).
    check_inputs : bool, default True
        If `True`, the `context` and `context_exog` inputs are validated
        and normalized via `_check_preprocess_context` and the columns
        of `exog` are validated against `context_exog`. If `False`,
        `context` must already be a `dict[str, pandas Series]` and
        `context_exog` must be a `dict[str, pandas DataFrame | None]`
        or `None`; `context_exog` and `exog` are still aligned to the
        context and to the forecast horizon. This argument is created
        for internal use and is not recommended to be changed.

    Returns
    -------
    predictions : pandas DataFrame
        Value of predictions. The DataFrame includes the following columns:

        - level: Name of the series.
        - pred: Predicted values (point forecast, median).

        If `quantiles` is not `None`, the `pred` column is replaced by
        one column per quantile level (e.g., `q_0.1`, `q_0.5`, `q_0.9`).

    Notes
    -----
    Foundation models are pre-trained and do not learn from the data passed 
    to `fit`. The `fit` method only stores context (the last `context_length` 
    observations) and metadata. This leads to four distinct behaviors 
    depending on the combination of `is_fitted` and `context`:

    - **Not fitted, `context=None`**: raises `ValueError`. There is no context 
    available for prediction.
    - **Fitted, `context=None`**: uses the context and `context_exog_` stored 
    during `fit`. If the user supplies `context_exog`, it is ignored with a 
    warning.
    - **Not fitted, `context` provided (zero-shot mode)**: The model uses 
    `context` and `context_exog` (if provided) as context for prediction.
    - **Fitted, `context` provided**: Stored context is ignored, the 
    provided `context` and `context_exog` (if provided) are used for
    prediction.

    When the adapter supports exogenous variables, the columns of the
    future `exog` are validated per series against the historical exog
    used as context. A future column with no historical values raises a
    `ValueError`. A historical column with no future values is a
    past-only covariate: it is used as such when
    `supports_past_only_covariates` is `True`, and ignored with an
    `IgnoredArgumentWarning` otherwise.

    Before calling the adapter, the historical exog of each series is
    aligned to the index of its context and the future `exog` to its
    forecast horizon (missing timestamps are filled with NaN and reported
    with a `MissingValuesWarning`). Each series keeps its own exog
    columns. When `supports_heterogeneous_covariates` is `False`, the
    series are grouped by their exog columns (past-only and future) and
    the adapter is called once per group, so the prediction of a series
    never depends on the exog columns of the other series.

    """

    if not self.is_fitted and context is None:
        raise ValueError(
            "Call `fit` before `predict`, or pass `context`."
        )

    if (
        isinstance(steps, bool)
        or not isinstance(steps, (int, np.integer))
        or steps < 1
    ):
        raise ValueError("`steps` must be a positive integer.")

    if quantiles is not None:
        if not isinstance(quantiles, (list, tuple)):
            raise TypeError(
                "`quantiles` must be a `list` or `tuple`. For example, quantiles "
                "0.1, 0.5, and 0.9 should be as `quantiles = [0.1, 0.5, 0.9]`."
            )
        for q in quantiles:
            if not 0.0 <= q <= 1.0:
                raise ValueError(
                    f"All quantiles must be between 0 and 1. Got {q}."
                )

    # Context (past data)
    if context is None:
        if context_exog is not None:
            warnings.warn(
                "`context_exog` is ignored when `context` is not provided. "
                "The stored `context_exog_` from `fit` is used instead.",
                IgnoredArgumentWarning,
                stacklevel=3,
            )
        context = self.adapter.context_
        series_names_in = self.series_names_in_
        context_exog = self.adapter.context_exog_
    elif check_inputs:
        context, _, series_names_in, context_exog, _ = self._check_preprocess_context(
            series = context,
            exog   = context_exog,
        )
    else:
        if not context:
            raise ValueError("`context` cannot be an empty dictionary.")
        series_names_in = list(context.keys())

    if levels is not None:
        if len(levels) == 0:
            raise ValueError("`levels` must be a single string or a list-like of strings, but cannot be empty.")
        requested_levels = [levels] if isinstance(levels, str) else list(levels)
        unknown = [lv for lv in requested_levels if lv not in series_names_in]
        if unknown:
            raise ValueError(
                f"`levels` {unknown} not found in available series "
                f"{list(series_names_in)}."
            )
        series_names_in = requested_levels
        context = {
            series_name: context[series_name] for series_name in requested_levels
        }
        if context_exog is not None:
            context_exog = {
                series_name: context_exog.get(series_name)
                for series_name in requested_levels
            }

    # Future exog
    if not self.allow_exog:
        has_exog = (exog is not None) or (context_exog is not None)
        if has_exog:
            warnings.warn(
                f"{type(self.adapter).__name__} does not currently "
                "support covariates. `exog` and `context_exog` "
                "are ignored.",
                IgnoredArgumentWarning,
                stacklevel=3,
            )
            exog = None
            context_exog = None
    else:
        # Alignment runs on every path: adapters rely on `context_exog`
        # sharing the index of `context` and on `exog` covering exactly
        # `steps` rows. With `check_inputs=False` (internal backtesting
        # path) only the column check is skipped:
        # `_extract_data_folds_multiseries` slices `context_exog` and
        # `exog` from the same per-series DataFrame, so their columns
        # always match by construction.
        if context_exog is not None:
            context_exog = align_context_exog(
                               context         = context,
                               context_exog    = context_exog,
                               series_names_in = series_names_in,
                           )
        exog = self._prepare_future_exog(
                   steps           = steps,
                   context         = context,
                   exog            = exog,
                   series_names_in = series_names_in,
               )
        if check_inputs:
            self._check_exog_columns(
                context_exog    = context_exog,
                exog            = exog,
                series_names_in = series_names_in,
            )

    if not self.adapter.supports_nan_in_series:
        series_with_nan = [
            series_name
            for series_name in series_names_in
            if context[series_name].isna().any()
        ]
        if series_with_nan:
            raise ValueError(
                f"{type(self.adapter).__name__} does not accept NaN values "
                f"in the series used as context. Series with NaN: "
                f"{series_with_nan}. Impute or drop them before predicting."
            )

    # Adapters whose backend requires identical covariate columns in a
    # batch are called once per group of series sharing the same columns.
    if self.adapter.supports_heterogeneous_covariates:
        series_groups = [series_names_in]
    else:
        series_groups = group_series_by_exog_signature(
                            series_names_in = series_names_in,
                            context_exog    = context_exog,
                            exog            = exog,
                        )

    # Adapter returns dict[str, np.ndarray] with shape (steps, n_q)
    raw_predictions: dict[str, np.ndarray] = {}
    for series_names_group in series_groups:
        raw_predictions.update(
            self.adapter.predict(
                steps        = steps,
                context      = {
                    series_name: context[series_name]
                    for series_name in series_names_group
                },
                context_exog = (
                    {
                        series_name: context_exog[series_name]
                        for series_name in series_names_group
                    }
                    if context_exog is not None else None
                ),
                exog         = (
                    {
                        series_name: exog[series_name]
                        for series_name in series_names_group
                    }
                    if exog is not None else None
                ),
                quantiles    = quantiles,
            )
        )

    # Build long-format DataFrame from raw predictions
    n_series = len(series_names_in)
    per_series_indices = [
        expand_index(context[series_name].index, steps=steps)
        for series_name in series_names_in
    ]

    if n_series == 1:
        long_index = per_series_indices[0]
    else:
        idx_arr = np.column_stack(
            [idx.to_numpy() for idx in per_series_indices]
        ).ravel()
        long_index = (
            pd.DatetimeIndex(idx_arr)
            if isinstance(per_series_indices[0], pd.DatetimeIndex)
            else pd.Index(idx_arr)
        )
    level_col = np.tile(series_names_in, steps)

    col_names = ["pred"] if quantiles is None else [f"q_{q}" for q in quantiles]
    n_cols = len(col_names)
    # Pre-allocate (steps, n_series, n_cols), fill per series, then reshape
    # to step-major (steps*n_series, n_cols), one allocation instead of one
    # per quantile, and the ravel order matches level_col / long_index.
    pred_matrix = np.empty((steps, n_series, n_cols), dtype=np.float64)
    for i, series_name in enumerate(series_names_in):
        pred_matrix[:, i, :] = raw_predictions[series_name]
    pred_matrix = pred_matrix.reshape(steps * n_series, n_cols)
    predictions: dict[str, np.ndarray] = {"level": level_col}
    for j, col in enumerate(col_names):
        predictions[col] = pred_matrix[:, j]

    predictions = pd.DataFrame(predictions, index=long_index)

    return predictions

get_params ¶

get_params(deep=True)

Get parameters for this estimator (sklearn-compatible).

Parameters:

Name Type Description Default
deep bool

Not used, present here for API consistency by convention.

True

Returns:

Name Type Description
params dict

Parameter names mapped to their current values.

Notes

Required so that sklearn.base.clone can create an unfitted copy of this object. clone is invoked when a ForecasterFoundation is constructed (in its __init__) and by deepcopy_forecaster during model selection and hyperparameter search. The pre-loaded pipeline is intentionally excluded so that clones are created without copying heavy model weights; the pipeline is reloaded lazily on the first predict call.

Source code in skforecast/foundation/_foundation_model.py
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
def get_params(self, deep: bool = True) -> dict:
    """
    Get parameters for this estimator (sklearn-compatible).

    Parameters
    ----------
    deep : bool, default True
        Not used, present here for API consistency by convention.

    Returns
    -------
    params : dict
        Parameter names mapped to their current values.

    Notes
    -----
    Required so that `sklearn.base.clone` can create an unfitted copy of
    this object. `clone` is invoked when a `ForecasterFoundation` is
    constructed (in its `__init__`) and by `deepcopy_forecaster` during
    model selection and hyperparameter search. The pre-loaded pipeline is
    intentionally excluded so that clones are created without copying heavy
    model weights; the pipeline is reloaded lazily on the first `predict`
    call.

    """

    return self.adapter.get_params()

set_params ¶

set_params(**params)

Set parameters for this estimator (sklearn-compatible).

After calling this method, the FoundationModel is reset to an unfitted state.

Parameters:

Name Type Description Default
**params

Estimator parameters forwarded to the underlying adapter's set_params. Use model_id to change the model ID; the adapter class is fixed at construction, so a model_id served by a different adapter (or by none) raises a ValueError. All other keys are adapter-specific.

{}

Returns:

Name Type Description
self FoundationModel

The same object with updated parameters.

Source code in skforecast/foundation/_foundation_model.py
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
def set_params(self, **params) -> FoundationModel:
    """
    Set parameters for this estimator (sklearn-compatible).

    After calling this method, the FoundationModel is reset to an unfitted state.

    Parameters
    ----------
    **params :
        Estimator parameters forwarded to the underlying adapter's
        `set_params`. Use `model_id` to change the model ID; the adapter
        class is fixed at construction, so a `model_id` served by a
        different adapter (or by none) raises a `ValueError`. All other
        keys are adapter-specific.

    Returns
    -------
    self : FoundationModel
        The same object with updated parameters.

    """

    if "model_id" in params:
        new_adapter_cls = _resolve_adapter(params["model_id"])
        if new_adapter_cls is not type(self.adapter):
            raise ValueError(
                f"`model_id` {params['model_id']!r} is served by "
                f"{new_adapter_cls.__name__}, but this FoundationModel uses "
                f"{type(self.adapter).__name__}. The adapter is fixed at "
                f"construction: create a new FoundationModel to switch "
                f"model family."
            )

    try:
        self.adapter.set_params(**params)
    except ValueError as exc:
        adapter_name = type(self.adapter).__name__
        message = str(exc).replace(
            f"Invalid parameter(s) for {adapter_name}:",
            "Invalid parameter(s) for FoundationModel:",
        )
        raise ValueError(message) from exc

    self.index_type_               = None
    self.index_freq_               = None
    self.context_range_            = None
    self.series_names_in_          = None
    self.is_multiple_series_       = False
    self.exog_in_                  = False
    self.exog_names_in_            = None
    self.exog_names_in_per_series_ = None
    self.exog_type_in_             = None
    self.fit_date                  = None
    self.adapter.context_          = None
    self.adapter.context_exog_     = None
    self.adapter.is_fitted         = False

    return self

skforecast.foundation._adapters.ChronosAdapter ¶

ChronosAdapter(
    model_id,
    *,
    pipeline=None,
    context_length=8192,
    predict_kwargs=None,
    device_map="auto",
    torch_dtype=None,
    cross_learning=False
)

Adapter for Amazon Chronos foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "autogluon/chronos-2-small".

required
pipeline BaseChronosPipeline

Pre-loaded pipeline instance. If None, the pipeline is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Defaults to 8192, which matches the maximum context window of Chronos. Must be a positive integer.

8192
predict_kwargs dict

Additional keyword arguments forwarded to the pipeline's predict_quantiles method.

None
device_map str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu", forwarded to BaseChronosPipeline.from_pretrained.

'auto'
torch_dtype object

Torch dtype forwarded to BaseChronosPipeline.from_pretrained.

None
cross_learning bool

If True, Chronos shares information across the series that are forecast in the same batch when predicting in multi-series mode. Forwarded directly to predict_quantiles. Ignored in single-series mode. FoundationModel batches together only the series that share the same covariate columns, so cross-learning applies within each of those groups.

False

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

predict_kwargs dict

Additional keyword arguments forwarded to predict_quantiles.

device_map str

Device map string for model loading.

torch_dtype object

Torch dtype for model loading.

cross_learning bool

Whether cross-series learning is enabled.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. False for Chronos: FoundationModel groups the series by covariate signature and calls predict once per group.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context. True for Chronos, which treats them as missing values.

is_fitted bool

Whether the adapter has been fitted.

Notes

NaN values in covariates are treated by Chronos as missing values.

References

.. [1] https://github.com/amazon-science/chronos-forecasting

.. [2] https://huggingface.co/amazon/chronos-2

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "autogluon/chronos-2-small".

required
pipeline BaseChronosPipeline

Pre-loaded pipeline instance. If None, the pipeline is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is and the model handles reduced context gracefully. Defaults to 8192, which matches the maximum context window of Chronos. Must be a positive integer.

8192
predict_kwargs dict

Additional keyword arguments forwarded verbatim to the pipeline's predict_quantiles method.

None
device_map str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu", forwarded to BaseChronosPipeline.from_pretrained.

'auto'
torch_dtype object

Torch dtype forwarded to BaseChronosPipeline.from_pretrained (e.g. torch.bfloat16).

None
cross_learning bool

If True, Chronos shares information across all series in the batch when predicting in multi-series mode. Forwarded directly to predict_quantiles. Ignored in single-series mode.

False

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the pipeline when model_id,

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using the Chronos pipeline.

Source code in skforecast/foundation/_adapters.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def __init__(
    self,
    model_id: str,
    *,
    pipeline: Any | None = None,
    context_length: int = 8192,
    predict_kwargs: dict[str, Any] | None = None,
    device_map: str = "auto",
    torch_dtype: Any | None = None,
    cross_learning: bool = False,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. "autogluon/chronos-2-small".
    pipeline : BaseChronosPipeline, default None
        Pre-loaded pipeline instance. If `None`, the pipeline is
        loaded lazily on the first call to `predict`.
    context_length : int, default 8192
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if
        `context` is longer than `context_length` it is trimmed to
        this length before inference; if it is shorter, all available
        observations are passed as-is and the model handles reduced
        context gracefully. Defaults to 8192, which matches the
        maximum context window of Chronos. Must be a positive
        integer.
    predict_kwargs : dict, default None
        Additional keyword arguments forwarded verbatim to the
        pipeline's `predict_quantiles` method.
    device_map : str, default 'auto'
        Device placement for the model. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU). Also accepts
        explicit values such as `"cuda"`, `"mps"`, or `"cpu"`,
        forwarded to `BaseChronosPipeline.from_pretrained`.
    torch_dtype : object, default None
        Torch dtype forwarded to `BaseChronosPipeline.from_pretrained`
        (e.g. `torch.bfloat16`).
    cross_learning : bool, default False
        If `True`, Chronos shares information across all series in
        the batch when predicting in multi-series mode. Forwarded
        directly to `predict_quantiles`. Ignored in single-series mode.

    """

    _validate_positive_int("context_length", context_length)

    self.model_id       = model_id
    self._pipeline      = pipeline
    self.context_       = None
    self.context_exog_  = None
    self.context_length = context_length
    self.predict_kwargs = predict_kwargs or {}
    self.device_map     = device_map
    self.torch_dtype    = torch_dtype
    self.cross_learning = cross_learning
    self.is_fitted      = False

Attributes¶

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = True

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = False

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

predict_kwargs instance-attribute ¶

predict_kwargs = predict_kwargs or {}

device_map instance-attribute ¶

device_map = device_map

torch_dtype instance-attribute ¶

torch_dtype = torch_dtype

cross_learning instance-attribute ¶

cross_learning = cross_learning

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, cross_learning, context_length, device_map, torch_dtype, predict_kwargs.

Source code in skforecast/foundation/_adapters.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `cross_learning`, `context_length`,
        `device_map`, `torch_dtype`, `predict_kwargs`.

    """
    return {
        'model_id':       self.model_id,
        'cross_learning': self.cross_learning,
        'context_length': self.context_length,
        'device_map':     self.device_map,
        'torch_dtype':    self.torch_dtype,
        'predict_kwargs': self.predict_kwargs or None,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the pipeline when model_id, device_map, or torch_dtype changes, since those are baked into the loaded pipeline.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, cross_learning, context_length, device_map, torch_dtype, predict_kwargs.

{}

Returns:

Name Type Description
self ChronosAdapter
Source code in skforecast/foundation/_adapters.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def set_params(self, **params) -> ChronosAdapter:
    """
    Set adapter parameters. Resets the pipeline when `model_id`,
    `device_map`, or `torch_dtype` changes, since those are baked into the
    loaded pipeline.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `cross_learning`, `context_length`,
        `device_map`, `torch_dtype`, `predict_kwargs`.

    Returns
    -------
    self : ChronosAdapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        if "predict_kwargs" in candidate_params:
            candidate_params["predict_kwargs"] = (
                candidate_params["predict_kwargs"] or {}
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            (
                {"model_id", "device_map", "torch_dtype"},
                lambda: setattr(self, "_pipeline", None),
            ),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since Chronos is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self ChronosAdapter
Source code in skforecast/foundation/_adapters.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
) -> ChronosAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since Chronos is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : ChronosAdapter

    """

    self.context_ = context
    self.context_exog_ = context_exog
    self.is_fitted = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the Chronos pipeline.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog dict

Per-series past covariates (already trimmed).

required
exog dict

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return. If None, a point forecast (median, quantile 0.5) is produced.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Source code in skforecast/foundation/_adapters.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
    exog: dict[str, pd.DataFrame | pd.Series | None],
    quantiles: list[float] | tuple[float] | None
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the Chronos pipeline.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict
        Per-series past covariates (already trimmed).
    exog : dict
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return. If `None`, a point forecast
        (median, quantile 0.5) is produced.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    """

    # NOTE: the pipeline is loaded lazily here so that the adapter can be
    # instantiated and fitted without requiring Chronos to be installed.
    self._load_pipeline()

    series_names_in = list(context.keys())
    quantile_levels = list(quantiles) if quantiles is not None else [0.5]

    inputs_list = [
        self._build_chronos_input(
            context      = context[series_name].to_numpy(),
            context_exog = (
                context_exog.get(series_name) if context_exog is not None else None
            ),
            exog         = exog.get(series_name) if exog is not None else None,
        )
        for series_name in series_names_in
    ]

    quantile_preds, _ = self._pipeline.predict_quantiles(
        inputs            = inputs_list,
        prediction_length = steps,
        quantile_levels   = quantile_levels,
        cross_learning    = self.cross_learning if len(series_names_in) > 1 else False,
        **self.predict_kwargs,
    )

    predictions: dict[str, np.ndarray] = {}
    for i, series_name in enumerate(series_names_in):
        q_arr = _tensor_to_numpy(quantile_preds[i].squeeze(0))
        predictions[series_name] = q_arr

    return predictions

skforecast.foundation._adapters.TimesFM25Adapter ¶

TimesFM25Adapter(
    model_id,
    *,
    model=None,
    context_length=512,
    max_horizon=512,
    forecast_config_kwargs=None
)

Adapter for Google TimesFM 2.5 foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "google/timesfm-2.5-200m-pytorch". Must start with "google/timesfm-2.5".

required
model object

Pre-loaded model instance. If None, the model is loaded lazily on the first predict call. If passed directly, it should already be compiled.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

512
max_horizon int

Maximum forecast horizon. If predict is called with steps > max_horizon, a ValueError is raised. The model is compiled lazily for the exact requested steps (up to this ceiling) to avoid unnecessary decode iterations. Must be a positive integer.

512
forecast_config_kwargs dict

Additional keyword arguments forwarded verbatim to timesfm.ForecastConfig at compile time. Supported keys: normalize_inputs, use_continuous_quantile_head, force_flip_invariance, infer_is_positive, fix_quantile_crossing. Do not include max_context or max_horizon here, since those are controlled by the corresponding adapter parameters.

None

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ (dict, None)

Stored historical exogenous variables after fitting. Never used by this adapter, since TimesFM 2.5 does not support covariates.

context_length int

Maximum number of historical observations used as context.

max_horizon int

Maximum forecast horizon.

forecast_config_kwargs dict

Additional keyword arguments forwarded to ForecastConfig.

allow_exog bool

Whether this adapter accepts exogenous variables. Always False.

supports_past_only_covariates bool

Whether historical exog columns without future values are used as past-only covariates. Always False.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. Always True, since covariates are ignored.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context. Always True.

is_fitted bool

Whether the adapter has been fitted.

Notes

TimesFM 2.5 supports only the fixed quantile levels [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]. Requesting any other level raises a ValueError. The point forecast is documented by TimesFM as the mean (in practice the 2.5 checkpoint returns a value equal to quantile 0.5).

Compilation behavior. The model is compiled lazily on the first predict call, sized for the exact number of steps requested (not for max_horizon, which only acts as an upper bound and validation ceiling). When steps is constant across calls, as in a typical backtesting loop, compilation happens only once, on the first fold. A later predict that requests more steps than any previous call triggers a single recompilation for the larger horizon. To avoid any runtime compilation altogether, pass an already-compiled model via the model argument.

References

.. [1] https://github.com/google-research/timesfm

.. [2] https://huggingface.co/google/timesfm-2.5-200m-pytorch

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "google/timesfm-2.5-200m-pytorch". Must start with "google/timesfm-2.5".

required
model object

Pre-loaded model instance. If None, the model is loaded lazily on the first predict call.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are passed as-is. Must be a positive integer.

512
max_horizon int

Maximum forecast horizon. If predict is called with steps > max_horizon, a ValueError is raised. The model is compiled lazily for the exact requested steps (up to this ceiling) to avoid unnecessary decode iterations. Must be a positive integer.

512
forecast_config_kwargs dict

Additional keyword arguments forwarded verbatim to timesfm.ForecastConfig at compile time.

None

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when parameters that affect

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using the TimesFM 2.5 model.

Source code in skforecast/foundation/_adapters.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 512,
    max_horizon: int = 512,
    forecast_config_kwargs: dict[str, Any] | None = None,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. `"google/timesfm-2.5-200m-pytorch"`.
        Must start with `"google/timesfm-2.5"`.
    model : object, default None
        Pre-loaded model instance. If `None`, the model is loaded
        lazily on the first `predict` call.
    context_length : int, default 512
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` are stored. At `predict` time, if `context` is
        longer than `context_length` it is trimmed to this length;
        if it is shorter, all available observations are passed as-is.
        Must be a positive integer.
    max_horizon : int, default 512
        Maximum forecast horizon. If `predict` is called with
        `steps > max_horizon`, a `ValueError` is raised. The model is
        compiled lazily for the exact requested `steps` (up to this
        ceiling) to avoid unnecessary decode iterations. Must be a
        positive integer.
    forecast_config_kwargs : dict, default None
        Additional keyword arguments forwarded verbatim to
        `timesfm.ForecastConfig` at compile time.

    """

    _validate_model_id_prefix(model_id, self._MODEL_ID_PREFIX, type(self).__name__)
    _validate_positive_int("context_length", context_length)
    _validate_positive_int("max_horizon", max_horizon)

    self.model_id               = model_id
    self._model                 = model
    self.context_               = None
    self.context_exog_          = None
    self.context_length         = context_length
    self.max_horizon            = max_horizon
    self.forecast_config_kwargs = forecast_config_kwargs or {}
    self.is_fitted              = False

Attributes¶

SUPPORTED_QUANTILES class-attribute instance-attribute ¶

SUPPORTED_QUANTILES = [
    0.1,
    0.2,
    0.3,
    0.4,
    0.5,
    0.6,
    0.7,
    0.8,
    0.9,
]

allow_exog class-attribute instance-attribute ¶

allow_exog = False

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = False

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = True

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

max_horizon instance-attribute ¶

max_horizon = max_horizon

forecast_config_kwargs instance-attribute ¶

forecast_config_kwargs = forecast_config_kwargs or {}

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, max_horizon, forecast_config_kwargs.

Source code in skforecast/foundation/_adapters.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `max_horizon`,
        `forecast_config_kwargs`.

    """

    return {
        'model_id':               self.model_id,
        'context_length':         self.context_length,
        'max_horizon':            self.max_horizon,
        'forecast_config_kwargs': self.forecast_config_kwargs or None,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the model when parameters that affect loading or compilation change.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, max_horizon, forecast_config_kwargs.

{}

Returns:

Name Type Description
self TimesFM25Adapter
Notes

All four parameters affect the loaded (and compiled) model, so changing any of them discards the cached model, which is reloaded and recompiled lazily on the next predict call.

Source code in skforecast/foundation/_adapters.py
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
def set_params(self, **params) -> TimesFM25Adapter:
    """
    Set adapter parameters. Resets the model when parameters that affect
    loading or compilation change.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `max_horizon`,
        `forecast_config_kwargs`.

    Returns
    -------
    self : TimesFM25Adapter

    Notes
    -----
    All four parameters affect the loaded (and compiled) model, so
    changing any of them discards the cached model, which is reloaded
    and recompiled lazily on the next `predict` call.

    """

    def validate(candidate_params: dict) -> dict:
        if "model_id" in candidate_params:
            _validate_model_id_prefix(
                candidate_params["model_id"],
                self._MODEL_ID_PREFIX,
                type(self).__name__,
            )
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        if "max_horizon" in candidate_params:
            _validate_positive_int("max_horizon", candidate_params["max_horizon"])
        if "forecast_config_kwargs" in candidate_params:
            candidate_params["forecast_config_kwargs"] = (
                candidate_params["forecast_config_kwargs"] or {}
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            (
                {"model_id", "context_length", "max_horizon",
                 "forecast_config_kwargs"},
                lambda: setattr(self, "_model", None),
            ),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since TimesFM is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables. Stored for API consistency but never used, since TimesFM 2.5 does not support covariates.

required

Returns:

Name Type Description
self TimesFM25Adapter
Source code in skforecast/foundation/_adapters.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
) -> TimesFM25Adapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since TimesFM is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables. Stored for API
        consistency but never used, since TimesFM 2.5 does not support
        covariates.

    Returns
    -------
    self : TimesFM25Adapter

    """

    self.context_ = context
    self.context_exog_ = context_exog
    self.is_fitted = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the TimesFM 2.5 model.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog Any

Not used, present here for API consistency by convention.

required
exog Any

Not used, present here for API consistency by convention.

required
quantiles list of float or None

Quantile levels. Must be a subset of SUPPORTED_QUANTILES.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Notes

A ValueError is raised if a requested quantile level is not in SUPPORTED_QUANTILES or if steps exceeds max_horizon.

Source code in skforecast/foundation/_adapters.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: Any,
    exog: Any,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the TimesFM 2.5 model.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : Any
        Not used, present here for API consistency by convention.
    exog : Any
        Not used, present here for API consistency by convention.
    quantiles : list of float or None
        Quantile levels. Must be a subset of `SUPPORTED_QUANTILES`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    Notes
    -----
    A `ValueError` is raised if a requested quantile level is not in
    `SUPPORTED_QUANTILES` or if `steps` exceeds `max_horizon`.

    """

    quantile_list = _validate_supported_quantiles(
        quantiles, self.SUPPORTED_QUANTILES, "TimesFM"
    )

    if steps > self.max_horizon:
        raise ValueError(
            f"`steps` ({steps}) exceeds `max_horizon` ({self.max_horizon})."
        )

    self._load_model()
    self._ensure_compiled(steps)

    series_names_in = list(context.keys())
    inputs_list = [
        context[series_name].to_numpy() for series_name in series_names_in
    ]

    point_forecast, quantile_forecast = self._model.forecast(
        horizon=steps,
        inputs=inputs_list,
    )
    # point_forecast  : (n_series, steps)
    # quantile_forecast: (n_series, steps, 10), idx 0 = mean, 1-9 = q0.1-q0.9

    predictions: dict[str, np.ndarray] = {}
    for i, series_name in enumerate(series_names_in):
        if quantile_list is None:
            # Point forecast: shape (steps, 1)
            predictions[series_name] = np.asarray(point_forecast[i]).reshape(-1, 1)
        else:
            quantile_indices = [round(q * 10) for q in quantile_list]
            qf = np.asarray(quantile_forecast[i])
            # (steps, n_quantiles)
            predictions[series_name] = qf[:, quantile_indices]

    return predictions

skforecast.foundation._adapters.TimesFM3Adapter ¶

TimesFM3Adapter(
    model_id,
    *,
    model=None,
    context_length=2048,
    device="auto",
    predict_kwargs=None
)

Adapter for Google TimesFM 3.0 foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "google/timesfm-3.0-pytorch". Must start with "google/timesfm-3.0".

required
model object

Pre-loaded TimesFM3Forecaster instance. If None, the model is loaded lazily on the first predict call.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer. TimesFM 3.0 supports context lengths up to roughly 15,360.

2048
device str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu", forwarded to TimesFM3Forecaster.from_pretrained.

'auto'
predict_kwargs dict

Additional keyword arguments forwarded verbatim to predict_batch (e.g. use_znorm, make_positive, use_symmetric_averaging, sort_quantiles). Cannot include contexts, horizon, return_quantiles, past_only_covariates, past_future_covariates, padding_mode, or ts_ids, which are managed internally.

None

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ (dict, None)

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

device str

Device placement for the model.

predict_kwargs dict

Additional keyword arguments forwarded to predict_batch.

allow_exog bool

Whether this adapter accepts exogenous variables. Always True.

supports_past_only_covariates bool

Whether historical exog columns without future values are used as past-only covariates. Always True.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. Always False: predict_batch stacks the covariate arrays of every series in a call, so FoundationModel groups the series by covariate signature and calls predict once per group.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context. Always True.

is_fitted bool

Whether the adapter has been fitted.

Notes

TimesFM 3.0 supports only the fixed quantile levels [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]. Requesting any other level raises a ValueError. The point forecast is the median (quantile 0.5).

For each series, columns present in its future exog become known-future covariates spanning context + horizon, built by concatenating the matching historical column from context_exog with the future values; columns present only in its context_exog become past-only covariates. Every series is forwarded with its own covariate columns only: FoundationModel batches together the series that share the same set of past-only and known-future columns and calls predict once per group, so the prediction of a series never depends on the covariates of the other series in the batch. Covariates must be numeric; encode categoricals as numbers (e.g. via transformer_exog) before passing them. NaN values inside covariates and inside the target series are linearly interpolated by the backend, and leading NaNs in the target trim the context and its covariates accordingly.

There is no compile step and no horizon ceiling: context length and horizon are handled internally by predict_batch.

The pre-trained weights are released under a non-commercial license, so loading them raises a LicenseWarning.

References

.. [1] https://github.com/google-research/timesfm

.. [2] https://huggingface.co/google/timesfm-3.0-pytorch

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "google/timesfm-3.0-pytorch". Must start with "google/timesfm-3.0".

required
model object

Pre-loaded TimesFM3Forecaster instance. If None, the model is loaded lazily on the first predict call.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are passed as-is. Must be a positive integer.

2048
device str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU).

'auto'
predict_kwargs dict

Additional keyword arguments forwarded verbatim to predict_batch.

None

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when parameters that affect

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using the TimesFM 3.0 model.

Source code in skforecast/foundation/_adapters.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 2048,
    device: str = "auto",
    predict_kwargs: dict[str, Any] | None = None,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. `"google/timesfm-3.0-pytorch"`. Must
        start with `"google/timesfm-3.0"`.
    model : object, default None
        Pre-loaded `TimesFM3Forecaster` instance. If `None`, the model
        is loaded lazily on the first `predict` call.
    context_length : int, default 2048
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` are stored. At `predict` time, if `context` is
        longer than `context_length` it is trimmed to this length;
        if it is shorter, all available observations are passed as-is.
        Must be a positive integer.
    device : str, default 'auto'
        Device placement for the model. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU).
    predict_kwargs : dict, default None
        Additional keyword arguments forwarded verbatim to
        `predict_batch`.

    """

    _validate_model_id_prefix(model_id, self._MODEL_ID_PREFIX, type(self).__name__)
    _validate_positive_int("context_length", context_length)
    predict_kwargs = predict_kwargs or {}
    self._validate_predict_kwargs(predict_kwargs)

    self.model_id       = model_id
    self._model         = model
    self.context_       = None
    self.context_exog_  = None
    self.context_length = context_length
    self.device         = device
    self.predict_kwargs = predict_kwargs
    self.is_fitted      = False

Attributes¶

SUPPORTED_QUANTILES class-attribute instance-attribute ¶

SUPPORTED_QUANTILES = [
    0.1,
    0.2,
    0.3,
    0.4,
    0.5,
    0.6,
    0.7,
    0.8,
    0.9,
]

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = True

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = False

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

device instance-attribute ¶

device = device

predict_kwargs instance-attribute ¶

predict_kwargs = predict_kwargs

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, device, predict_kwargs.

Source code in skforecast/foundation/_adapters.py
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `device`, `predict_kwargs`.

    """

    return {
        'model_id':       self.model_id,
        'context_length': self.context_length,
        'device':         self.device,
        'predict_kwargs': self.predict_kwargs or None,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the model when parameters that affect loading change.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, device, predict_kwargs.

{}

Returns:

Name Type Description
self TimesFM3Adapter
Notes

Only model_id and device affect the loaded model, so only those discard the cached model. context_length and predict_kwargs are applied at predict time and never trigger a reload.

Source code in skforecast/foundation/_adapters.py
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
def set_params(self, **params) -> TimesFM3Adapter:
    """
    Set adapter parameters. Resets the model when parameters that affect
    loading change.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `device`,
        `predict_kwargs`.

    Returns
    -------
    self : TimesFM3Adapter

    Notes
    -----
    Only `model_id` and `device` affect the loaded model, so only those
    discard the cached model. `context_length` and `predict_kwargs` are
    applied at predict time and never trigger a reload.

    """

    def validate(candidate_params: dict) -> dict:
        if "model_id" in candidate_params:
            _validate_model_id_prefix(
                candidate_params["model_id"],
                self._MODEL_ID_PREFIX,
                type(self).__name__,
            )
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        if "predict_kwargs" in candidate_params:
            candidate_params["predict_kwargs"] = (
                candidate_params["predict_kwargs"] or {}
            )
            self._validate_predict_kwargs(candidate_params["predict_kwargs"])
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            ({"model_id", "device"}, lambda: setattr(self, "_model", None)),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since TimesFM is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self TimesFM3Adapter
Source code in skforecast/foundation/_adapters.py
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
) -> TimesFM3Adapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since TimesFM is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : TimesFM3Adapter

    """

    self.context_ = context
    self.context_exog_ = context_exog
    self.is_fitted = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the TimesFM 3.0 model.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog (dict, None)

Per-series historical exogenous variables (already trimmed). For each series, columns not also present in its exog are forwarded as past-only covariates.

required
exog (dict, None)

Per-series future exogenous variables for the forecast horizon. Each column is forwarded as a known-future covariate of that series, concatenated with its historical values.

required
quantiles list of float or None

Quantile levels. Must be a subset of SUPPORTED_QUANTILES.

required

Returns:

Name Type Description
predictions dict

Keys are series names, in the same order as context. Each value is a 2-D array of shape (steps, n_quantiles).

Notes

A ValueError is raised if a requested quantile level is not in SUPPORTED_QUANTILES. There is no horizon ceiling.

predict_batch requires all series in one call to share the same covariate layout. FoundationModel guarantees it by grouping the series by covariate signature (get_exog_signature) and calling predict once per group, so the signature of the first series sets the column order for the whole batch. Series of different lengths are accepted: predict_batch left-pads every series and its covariates to the batch context length.

With covariates present, padding_mode="edge" is passed to predict_batch (the default chosen here); with no covariates, padding_mode="none" is used. predict_batch internally rounds the horizon up to a multiple of the output patch length. "edge" repeats the last known-future covariate value up to that rounded length, so those extra positions enter the final patch unmasked, whereas "none" leaves them masked. Both modes return steps rows for any steps ("edge" is not required); "edge" matches the default used by TimesFM's own predict() and can shift the last patch's predictions relative to "none". The point forecast (quantiles is None) is the model's median quantile.

Source code in skforecast/foundation/_adapters.py
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the TimesFM 3.0 model.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict, None
        Per-series historical exogenous variables (already trimmed).
        For each series, columns not also present in its `exog` are
        forwarded as past-only covariates.
    exog : dict, None
        Per-series future exogenous variables for the forecast
        horizon. Each column is forwarded as a known-future covariate
        of that series, concatenated with its historical values.
    quantiles : list of float or None
        Quantile levels. Must be a subset of `SUPPORTED_QUANTILES`.

    Returns
    -------
    predictions : dict
        Keys are series names, in the same order as `context`. Each
        value is a 2-D array of shape `(steps, n_quantiles)`.

    Notes
    -----
    A `ValueError` is raised if a requested quantile level is not in
    `SUPPORTED_QUANTILES`. There is no horizon ceiling.

    `predict_batch` requires all series in one call to share the same
    covariate layout. `FoundationModel` guarantees it by grouping the
    series by covariate signature (`get_exog_signature`) and calling
    `predict` once per group, so the signature of the first series sets
    the column order for the whole batch. Series of different lengths
    are accepted: `predict_batch` left-pads every series and its
    covariates to the batch context length.

    With covariates present, `padding_mode="edge"` is passed to
    `predict_batch` (the default chosen here); with no covariates,
    `padding_mode="none"` is used. `predict_batch` internally rounds the
    horizon up to a multiple of the output patch length. `"edge"` repeats
    the last known-future covariate value up to that rounded length, so
    those extra positions enter the final patch unmasked, whereas
    `"none"` leaves them masked. Both modes return `steps` rows for any
    `steps` ("edge" is not required); `"edge"` matches the default used by
    TimesFM's own `predict()` and can shift the last patch's predictions
    relative to `"none"`. The point forecast (`quantiles is None`) is the
    model's median quantile.

    """

    quantile_list = _validate_supported_quantiles(
        quantiles, self.SUPPORTED_QUANTILES, "TimesFM"
    )

    self._load_model()

    names = list(context.keys())

    # Every series in a call shares the same covariate columns
    # (`FoundationModel` groups them by covariate signature), so the
    # signature of the first series sets the column order for the batch.
    past_only_cols, fut_cols = get_exog_signature(
        context_exog = context_exog.get(names[0]) if context_exog is not None else None,
        exog         = exog.get(names[0]) if exog is not None else None,
    )
    has_covariates = bool(past_only_cols) or bool(fut_cols)
    contexts = [context[series_name].to_numpy() for series_name in names]

    past_only_list: list[np.ndarray | None] = []
    past_future_list: list[np.ndarray | None] = []
    for series_name in names:
        past_only, past_future = self._build_covariates(
            context_exog   = (
                context_exog.get(series_name) if context_exog is not None else None
            ),
            exog           = exog.get(series_name) if exog is not None else None,
            past_only_cols = past_only_cols,
            fut_cols       = fut_cols,
        )
        past_only_list.append(past_only)
        past_future_list.append(past_future)

    results = self._model.predict_batch(
        contexts               = contexts,
        horizon                = steps,
        past_only_covariates   = past_only_list if has_covariates else None,
        past_future_covariates = past_future_list if has_covariates else None,
        return_quantiles       = quantile_list is not None,
        padding_mode           = "edge" if has_covariates else "none",
        **self.predict_kwargs,
    )
    outs = dict(zip(names, results))

    if quantile_list is not None:
        quantile_indices = self._match_quantile_indices(
            list(self._model.config.quantiles), quantile_list
        )

    predictions: dict[str, np.ndarray] = {}
    for series_name in names:
        out = outs[series_name]
        if quantile_list is None:
            predictions[series_name] = np.asarray(out.forecast).reshape(-1, 1)
        else:
            predictions[series_name] = (
                np.asarray(out.quantiles)[:, quantile_indices]
            )

    return predictions

skforecast.foundation._adapters.MoiraiAdapter ¶

MoiraiAdapter(
    model_id,
    *,
    module=None,
    context_length=2048,
    device="auto"
)

Adapter for Salesforce Moirai foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "Salesforce/moirai-2.0-R-small". Must be a Salesforce/moirai-2.0-R-{small,base,large} variant.

required
module object

Pre-loaded Moirai2Module instance. If None, the module is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

2048
device str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu".

'auto'

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Not used, present here for API consistency by convention.

context_length int

Maximum number of historical observations used as context.

device str

Device placement for the model.

_forecast_obj object

Internal Moirai forecast object, populated at the first call to predict.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. True, since covariates are ignored.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context.

is_fitted bool

Whether the adapter has been fitted.

Notes

Moirai supports only the fixed quantile levels [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]. Requesting any other level raises a ValueError.

Covariate support via the high-level Moirai2Forecast.predict() API is not functional: the padding/truncation loop inside predict() clips every list-valued field (including feat_dynamic_real) to context_length, discarding the future portion that future covariates require. Passing exog or context_exog issues an IgnoredArgumentWarning and the values are discarded.

References

.. [1] https://github.com/SalesforceAIResearch/uni2ts

.. [2] https://huggingface.co/Salesforce/moirai-2.0-R-small

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "Salesforce/moirai-2.0-R-small".

required
module object

Pre-loaded Moirai2Module instance. If None, the module is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are passed as-is. Must be a positive integer.

2048
device str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu".

'auto'

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the module and forecast object when

fit

Store the training series.

predict

Generate predictions using Moirai.

Source code in skforecast/foundation/_adapters.py
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
def __init__(
    self,
    model_id: str,
    *,
    module: Any | None = None,
    context_length: int = 2048,
    device: str = "auto",
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. `"Salesforce/moirai-2.0-R-small"`.
    module : object, default None
        Pre-loaded `Moirai2Module` instance. If `None`, the module
        is loaded lazily on the first call to `predict`.
    context_length : int, default 2048
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` are stored. At `predict` time, if `context`
        is longer than `context_length` it is trimmed to this length;
        if it is shorter, all available observations are passed as-is.
        Must be a positive integer.
    device : str, default 'auto'
        Device placement for the model. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU). Also accepts
        explicit values such as `"cuda"`, `"mps"`, or `"cpu"`.

    """

    _validate_positive_int("context_length", context_length)

    self.model_id       = model_id
    self._module        = module
    self.context_       = None
    self.context_exog_  = None
    self.context_length = context_length
    self.device         = device
    self._forecast_obj  = None
    self.is_fitted      = False

Attributes¶

SUPPORTED_QUANTILES class-attribute instance-attribute ¶

SUPPORTED_QUANTILES = [
    0.1,
    0.2,
    0.3,
    0.4,
    0.5,
    0.6,
    0.7,
    0.8,
    0.9,
]

allow_exog class-attribute instance-attribute ¶

allow_exog = False

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = False

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = True

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

device instance-attribute ¶

device = device

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, device.

Source code in skforecast/foundation/_adapters.py
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `device`.
    """
    return {
        'model_id':       self.model_id,
        'context_length': self.context_length,
        'device':         self.device,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the module and forecast object when model_id, context_length, or device changes.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, device.

{}

Returns:

Name Type Description
self MoiraiAdapter
Source code in skforecast/foundation/_adapters.py
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
def set_params(self, **params) -> MoiraiAdapter:
    """
    Set adapter parameters. Resets the module and forecast object when
    `model_id`, `context_length`, or `device` changes.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `device`.

    Returns
    -------
    self : MoiraiAdapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        return candidate_params

    def _reset_module() -> None:
        self._module = None
        self._forecast_obj = None

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            ({"model_id", "context_length", "device"}, _reset_module),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series. No model training occurs since Moirai is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog Any

Not used, present here for API consistency by convention.

required

Returns:

Name Type Description
self MoiraiAdapter
Source code in skforecast/foundation/_adapters.py
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: Any,
) -> MoiraiAdapter:
    """
    Store the training series.
    No model training occurs since Moirai is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : Any
        Not used, present here for API consistency by convention.

    Returns
    -------
    self : MoiraiAdapter

    """

    self.context_ = context
    self.is_fitted = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using Moirai.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict pandas Series

Per-series context windows (already trimmed to context_length).

required
context_exog Any

Not used, present here for API consistency by convention.

required
exog Any

Not used, present here for API consistency by convention.

required
quantiles list of float or None

Quantile levels. Must be a subset of SUPPORTED_QUANTILES.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Notes

A ValueError is raised if a requested quantile level is not in SUPPORTED_QUANTILES.

Source code in skforecast/foundation/_adapters.py
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: Any,
    exog: Any,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using Moirai.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict pandas Series
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : Any
        Not used, present here for API consistency by convention.
    exog : Any
        Not used, present here for API consistency by convention.
    quantiles : list of float or None
        Quantile levels. Must be a subset of `SUPPORTED_QUANTILES`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    Notes
    -----
    A `ValueError` is raised if a requested quantile level is not in
    `SUPPORTED_QUANTILES`.

    """

    quantile_list = _validate_supported_quantiles(
        quantiles, self.SUPPORTED_QUANTILES, "Moirai"
    )

    quantile_levels = quantile_list if quantile_list is not None else [0.5]
    quantile_indices = [
        next(
            i for i, supported_quantile in enumerate(self.SUPPORTED_QUANTILES)
            if abs(q - supported_quantile) < 1e-9
        )
        for q in quantile_levels
    ]

    series_names_in = list(context.keys())
    inputs_list = [
        context[series_name].to_numpy(dtype=np.float32).reshape(-1, 1)
        for series_name in series_names_in
    ]

    raw = self._run_inference(inputs_list, steps)

    predictions: dict[str, np.ndarray] = {}
    for i, series_name in enumerate(series_names_in):
        # (steps, n_quantiles)
        predictions[series_name] = raw[i][quantile_indices, :].T

    return predictions

skforecast.foundation._adapters.TabICLAdapter ¶

TabICLAdapter(
    model_id,
    *,
    model=None,
    context_length=4096,
    point_estimate="mean",
    tabicl_config=None,
    temporal_features=None,
    show_progress=False
)

Adapter for TabICL zero-shot time-series foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "soda-inria/tabicl".

required
model object

Pre-instantiated TabICLForecaster instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

4096
point_estimate str

Method used to derive the point forecast from the TabICL output. Accepted values: 'mean', 'median'.

'mean'
tabicl_config dict

Additional keyword arguments forwarded verbatim to TabICLRegressor at inference time. If None, defaults to empty dict (TabICL's own defaults).

None
temporal_features list

List of TimeTransform instances applied to the time series before inference. If None, TabICL uses its default transforms: [IndexEncoder(), DatetimeEncoder(), AutoPeriodicEncoder()]. Pass an empty list to disable all temporal feature engineering.

None
show_progress bool

If False, the tqdm progress bar emitted by the underlying TabICL dispatch loop (GPU 0: ...) is suppressed.

False

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

point_estimate str

Point forecast method.

tabicl_config dict

Additional configuration forwarded to TabICLRegressor.

temporal_features list

Temporal feature transforms applied to the series.

show_progress bool

Whether the TabICL dispatch progress bar is shown.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. False for TabICL, whose long-format input frame holds one column set for every series: FoundationModel groups the series by covariate signature and calls predict once per group.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context. True: TabICL drops the rows whose target is NaN.

is_fitted bool

Whether the adapter has been fitted.

_model object

Internal TabICLForecaster instance. None until the first call to predict, after which it is cached for reuse.

Notes

TabICL supports arbitrary quantile levels (any float in [0, 1]), unlike models with fixed quantile sets such as TimesFM or Moirai.

Covariate support is available: extra columns in context and exog are forwarded as covariates. TabICL uses only the intersection of columns present in both context and future data. NaN values in the future covariates are accepted by TabICL with a warning.

Series with a RangeIndex are accepted. Internally, TabICL requires datetime timestamps, so a synthetic daily DatetimeIndex (starting 2000-01-01) is used. Calendar-based transforms (DatetimeEncoder, AutoPeriodicEncoder) will not be meaningful for such series; consider passing temporal_features=[] or temporal_features=[IndexEncoder()] in that case.

References

.. [1] https://github.com/soda-inria/tabicl

.. [2] https://tabicl.readthedocs.io/en/latest/

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "soda-inria/tabicl".

required
model object

Pre-instantiated TabICLForecaster instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is. Must be a positive integer.

4096
point_estimate str

Method used to derive the point forecast. Accepted values: 'mean', 'median'.

'mean'
tabicl_config dict

Additional keyword arguments forwarded verbatim to TabICLRegressor at inference time.

None
temporal_features list

List of TimeTransform instances applied before inference. If None, TabICL uses its defaults. Pass [] to disable all temporal feature engineering.

None
show_progress bool

If False, the tqdm progress bar emitted by the underlying TabICL dispatch loop (GPU 0: ...) is suppressed by redirecting stderr during the predict_df call.

False

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when a parameter that affects

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using TabICL.

Source code in skforecast/foundation/_adapters.py
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 4096,
    point_estimate: str = "mean",
    tabicl_config: dict[str, Any] | None = None,
    temporal_features: list[Any] | None = None,
    show_progress: bool = False,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. `"soda-inria/tabicl"`.
    model : object, default None
        Pre-instantiated `TabICLForecaster` instance. If `None`, a new
        instance is created lazily on the first call to `predict`.
        Intended for testing only.
    context_length : int, default 4096
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if
        `context` is longer than `context_length` it is trimmed to
        this length before inference; if it is shorter, all available
        observations are passed as-is. Must be a positive integer.
    point_estimate : str, default 'mean'
        Method used to derive the point forecast. Accepted values:
        `'mean'`, `'median'`.
    tabicl_config : dict, default None
        Additional keyword arguments forwarded verbatim to
        `TabICLRegressor` at inference time.
    temporal_features : list, default None
        List of `TimeTransform` instances applied before inference. If
        `None`, TabICL uses its defaults. Pass `[]` to disable all
        temporal feature engineering.
    show_progress : bool, default False
        If `False`, the tqdm progress bar emitted by the underlying
        TabICL dispatch loop (`GPU 0: ...`) is suppressed by
        redirecting stderr during the `predict_df` call.

    """

    _validate_positive_int("context_length", context_length)
    if point_estimate not in ("mean", "median"):
        raise ValueError(
            f"`point_estimate` must be 'mean' or 'median'. Got {point_estimate!r}."
        )

    self.model_id          = model_id
    self._model            = model
    self.context_          = None
    self.context_exog_     = None
    self.context_length    = context_length
    self.point_estimate    = point_estimate
    self.tabicl_config     = tabicl_config or {}
    self.temporal_features = temporal_features
    self.show_progress     = show_progress
    self.is_fitted         = False

Attributes¶

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = False

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = False

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

point_estimate instance-attribute ¶

point_estimate = point_estimate

tabicl_config instance-attribute ¶

tabicl_config = tabicl_config or {}

temporal_features instance-attribute ¶

temporal_features = temporal_features

show_progress instance-attribute ¶

show_progress = show_progress

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, point_estimate, tabicl_config, temporal_features, show_progress. tabicl_config is returned as None when no additional config was set (i.e. when the internal dict is empty).

Source code in skforecast/foundation/_adapters.py
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `point_estimate`,
        `tabicl_config`, `temporal_features`, `show_progress`.
        `tabicl_config` is returned as `None` when no additional
        config was set (i.e. when the internal dict is empty).

    """
    return {
        "model_id":          self.model_id,
        "context_length":    self.context_length,
        "point_estimate":    self.point_estimate,
        "tabicl_config":     self.tabicl_config or None,
        "temporal_features": self.temporal_features,
        "show_progress":     self.show_progress,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the model when a parameter that affects the TabICLForecaster instance changes; toggling show_progress does not reset the model.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, point_estimate, tabicl_config, temporal_features, show_progress.

{}

Returns:

Name Type Description
self TabICLAdapter
Source code in skforecast/foundation/_adapters.py
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
def set_params(self, **params) -> TabICLAdapter:
    """
    Set adapter parameters. Resets the model when a parameter that affects
    the `TabICLForecaster` instance changes; toggling `show_progress` does
    not reset the model.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `point_estimate`,
        `tabicl_config`, `temporal_features`, `show_progress`.

    Returns
    -------
    self : TabICLAdapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        if "point_estimate" in candidate_params and candidate_params[
            "point_estimate"
        ] not in ("mean", "median"):
            raise ValueError(
                f"`point_estimate` must be 'mean' or 'median'. "
                f"Got {candidate_params['point_estimate']!r}."
            )
        if "tabicl_config" in candidate_params:
            candidate_params["tabicl_config"] = (
                candidate_params["tabicl_config"] or {}
            )
        if "show_progress" in candidate_params and not isinstance(
            candidate_params["show_progress"], bool
        ):
            raise ValueError(
                f"`show_progress` must be a bool. "
                f"Got {candidate_params['show_progress']!r}."
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            (
                {"model_id", "context_length", "point_estimate",
                 "tabicl_config", "temporal_features"},
                lambda: setattr(self, "_model", None),
            ),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since TabICL is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self TabICLAdapter
Source code in skforecast/foundation/_adapters.py
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
) -> TabICLAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since TabICL is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : TabICLAdapter

    """

    self.context_      = context
    self.context_exog_ = context_exog
    self.is_fitted     = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using TabICL.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict pandas Series

Per-series context windows (already trimmed to context_length).

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series past covariates (already trimmed).

required
exog dict pandas DataFrame, pandas Series, or None

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return. If None, a point forecast is produced (shape (steps, 1)). Accepts any float in [0, 1].

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D numpy ndarray of shape (steps, n_quantiles).

Source code in skforecast/foundation/_adapters.py
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using TabICL.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict pandas Series
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series past covariates (already trimmed).
    exog : dict pandas DataFrame, pandas Series, or None
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return. If `None`, a point forecast is
        produced (shape `(steps, 1)`). Accepts any float in `[0, 1]`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D numpy ndarray of
        shape `(steps, n_quantiles)`.

    """

    self._load_model()

    quantile_list = list(quantiles) if quantiles is not None else None
    tabicl_quantiles = (
        quantile_list
        if quantile_list is not None
        else [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    )

    series_names_in = list(context.keys())

    first_series = next(iter(context.values()))
    is_datetime = isinstance(first_series.index, pd.DatetimeIndex)

    if not is_datetime:
        warnings.warn(
            "TabICLAdapter received series with a non-DatetimeIndex. "
            "TabICL requires datetime timestamps internally; a synthetic "
            "daily DatetimeIndex (starting 2000-01-01) will be used. "
            "Calendar-based temporal features (DatetimeEncoder, "
            "AutoPeriodicEncoder) will not be meaningful for "
            "integer-indexed data. Consider passing "
            "`temporal_features=[]` to disable calendar feature "
            "transforms.",
            # stacklevel=3: TabICLAdapter.predict → FoundationModel.predict → user
            stacklevel=3,
        )

    context_df = self._build_context_df(
                     series_names = series_names_in, 
                     context      = context, 
                     context_exog = context_exog, 
                     is_datetime  = is_datetime
                 )

    future_df = self._build_future_df(
                    series_names = series_names_in, 
                    context      = context, 
                    exog         = exog, 
                    steps        = steps, 
                    is_datetime  = is_datetime
                )

    _stderr_cm = (
        contextlib.redirect_stderr(io.StringIO())
        if not self.show_progress
        else contextlib.nullcontext()
    )
    with _stderr_cm:
        result_df = self._model.predict_df(
                        context_df = context_df,
                        future_df  = future_df,
                        quantiles  = tabicl_quantiles,
                    )

    # result_df is a plain DataFrame with MultiIndex (item_id, timestamp).
    # columns: "target" (str) and quantile levels as float column names.
    predictions: dict[str, np.ndarray] = {}
    for series_name in series_names_in:
        group = result_df.loc[series_name]  # DataFrame indexed by timestamp
        if quantile_list is None:
            predictions[series_name] = group["target"].to_numpy().reshape(-1, 1)
        else:
            predictions[series_name] = group[quantile_list].to_numpy()

    return predictions

skforecast.foundation._adapters.TabPFNAdapter ¶

TabPFNAdapter(
    model_id,
    *,
    model=None,
    context_length=32768,
    mode="local",
    point_estimate="median",
    tabpfn_model_config=None,
    temporal_features=None,
    show_progress=False
)

Adapter for Prior Labs TabPFN-TS zero-shot time-series foundation models.

TabPFN-TS frames forecasting as tabular regression: the series is featurized (running index, calendar features, automatically detected seasonal features) and a TabPFN regressor predicts the forecast horizon zero-shot.

Parameters:

Name Type Description Default
model_id str

Model ID, e.g. "priorlabs/tabpfn-ts". Used only to resolve this adapter; the underlying checkpoint is controlled by tabpfn_model_config (key model_path).

required
model object

Pre-instantiated TabPFNTSPipeline instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Defaults to 32768, which matches the TabPFN-TS ship configuration; lower values (e.g. 4096) speed up inference at a small accuracy cost. Must be a positive integer.

32768
mode str

Inference mode. 'local' runs the TabPFN model locally (CUDA > MPS > CPU selected automatically by the library; the checkpoint is downloaded on first use). 'client' sends the featurized data to the Prior Labs cloud API via tabpfn-client (no GPU needed, requires an account/API key).

'local'
point_estimate str

Method used to aggregate the TabPFN ensemble output into the point forecast. Accepted values: 'mean', 'median', 'mode'.

'median'
tabpfn_model_config dict

Additional configuration forwarded verbatim to the underlying TabPFN regressor (e.g. model_path, device). If None, the library defaults are used.

None
temporal_features list

List of FeatureGenerator instances applied to the time series before inference. If None, TabPFN-TS uses its default transforms: [RunningIndexFeature(), CalendarFeature(), AutoSeasonalFeature()]. Pass an empty list to disable all temporal feature engineering.

None
show_progress bool

If False, the tqdm progress bar emitted by the underlying TabPFN-TS dispatch loop (Predicting time series: ... on CPU, GPU 0: ... on GPU) is suppressed.

False

Attributes:

Name Type Description
model_id str

Model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

mode str

Inference mode, 'local' or 'client'.

point_estimate str

Point forecast aggregation method.

tabpfn_model_config dict

Additional configuration forwarded to the TabPFN regressor.

temporal_features list

Temporal feature transforms applied to the series.

show_progress bool

Whether the tqdm progress bar is shown during inference.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. True: the library handles the missing cells of the long-format input frame.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context.

is_fitted bool

Whether the adapter has been fitted.

_model object

Internal TabPFNTSPipeline instance. None until the first call to predict, after which it is cached for reuse.

Notes

TabPFN-TS supports arbitrary quantile levels (any float in (0, 1)), unlike models with fixed quantile sets such as TimesFM or Moirai.

Covariate support is available for known-future covariates: extra columns present in both the historical context and the forecast horizon are used by the model. Covariates without future values are discarded by the library.

Series with a RangeIndex are accepted. Internally, TabPFN-TS requires datetime timestamps, so a synthetic daily DatetimeIndex (starting 2000-01-01) is used. Calendar-based transforms (CalendarFeature) will not be meaningful for such series; consider passing temporal_features=[] or [RunningIndexFeature()] in that case.

References

.. [1] https://github.com/PriorLabs/tabpfn-time-series

.. [2] https://priorlabs.ai/

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

Model ID, e.g. "priorlabs/tabpfn-ts".

required
model object

Pre-instantiated TabPFNTSPipeline instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is. Must be a positive integer.

32768
mode str

Inference mode. Accepted values: 'local', 'client'.

'local'
point_estimate str

Method used to aggregate the TabPFN ensemble output into the point forecast. Accepted values: 'mean', 'median', 'mode'.

'median'
tabpfn_model_config dict

Additional configuration forwarded verbatim to the underlying TabPFN regressor.

None
temporal_features list

List of FeatureGenerator instances applied before inference. If None, TabPFN-TS uses its defaults. Pass [] to disable all temporal feature engineering.

None
show_progress bool

If False, the tqdm progress bar emitted by the underlying TabPFN-TS dispatch loop (Predicting time series: ... on CPU, GPU 0: ... on GPU) is suppressed.

False

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when a parameter that affects

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using TabPFN-TS.

Source code in skforecast/foundation/_adapters.py
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 32768,
    mode: str = "local",
    point_estimate: str = "median",
    tabpfn_model_config: dict[str, Any] | None = None,
    temporal_features: list[Any] | None = None,
    show_progress: bool = False,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        Model ID, e.g. `"priorlabs/tabpfn-ts"`.
    model : object, default None
        Pre-instantiated `TabPFNTSPipeline` instance. If `None`, a new
        instance is created lazily on the first call to `predict`.
        Intended for testing only.
    context_length : int, default 32768
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if
        `context` is longer than `context_length` it is trimmed to
        this length before inference; if it is shorter, all available
        observations are passed as-is. Must be a positive integer.
    mode : str, default 'local'
        Inference mode. Accepted values: `'local'`, `'client'`.
    point_estimate : str, default 'median'
        Method used to aggregate the TabPFN ensemble output into the
        point forecast. Accepted values: `'mean'`, `'median'`, `'mode'`.
    tabpfn_model_config : dict, default None
        Additional configuration forwarded verbatim to the underlying
        TabPFN regressor.
    temporal_features : list, default None
        List of `FeatureGenerator` instances applied before inference.
        If `None`, TabPFN-TS uses its defaults. Pass `[]` to disable all
        temporal feature engineering.
    show_progress : bool, default False
        If `False`, the tqdm progress bar emitted by the underlying
        TabPFN-TS dispatch loop (`Predicting time series: ...` on CPU,
        `GPU 0: ...` on GPU) is suppressed.

    """

    _validate_positive_int("context_length", context_length)
    if mode not in ("local", "client"):
        raise ValueError(
            f"`mode` must be 'local' or 'client'. Got {mode!r}."
        )
    if point_estimate not in ("mean", "median", "mode"):
        raise ValueError(
            f"`point_estimate` must be 'mean', 'median' or 'mode'. "
            f"Got {point_estimate!r}."
        )

    self.model_id            = model_id
    self._model              = model
    self.context_            = None
    self.context_exog_       = None
    self.context_length      = context_length
    self.mode                = mode
    self.point_estimate      = point_estimate
    self.tabpfn_model_config = tabpfn_model_config or {}
    self.temporal_features   = temporal_features
    self.show_progress       = show_progress
    self.is_fitted           = False

Attributes¶

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = False

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = True

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

mode instance-attribute ¶

mode = mode

point_estimate instance-attribute ¶

point_estimate = point_estimate

tabpfn_model_config instance-attribute ¶

tabpfn_model_config = tabpfn_model_config or {}

temporal_features instance-attribute ¶

temporal_features = temporal_features

show_progress instance-attribute ¶

show_progress = show_progress

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, mode, point_estimate, tabpfn_model_config, temporal_features, show_progress. tabpfn_model_config is returned as None when no additional config was set (i.e. when the internal dict is empty).

Source code in skforecast/foundation/_adapters.py
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `mode`, `point_estimate`,
        `tabpfn_model_config`, `temporal_features`, `show_progress`.
        `tabpfn_model_config` is returned as `None` when no additional
        config was set (i.e. when the internal dict is empty).

    """
    return {
        "model_id":            self.model_id,
        "context_length":      self.context_length,
        "mode":                self.mode,
        "point_estimate":      self.point_estimate,
        "tabpfn_model_config": self.tabpfn_model_config or None,
        "temporal_features":   self.temporal_features,
        "show_progress":       self.show_progress,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the model when a parameter that affects the TabPFNTSPipeline instance changes; toggling show_progress does not reset the model.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, mode, point_estimate, tabpfn_model_config, temporal_features, show_progress.

{}

Returns:

Name Type Description
self TabPFNAdapter
Source code in skforecast/foundation/_adapters.py
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
def set_params(self, **params) -> TabPFNAdapter:
    """
    Set adapter parameters. Resets the model when a parameter that affects
    the `TabPFNTSPipeline` instance changes; toggling `show_progress` does
    not reset the model.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `mode`,
        `point_estimate`, `tabpfn_model_config`, `temporal_features`,
        `show_progress`.

    Returns
    -------
    self : TabPFNAdapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        if "mode" in candidate_params and candidate_params["mode"] not in (
            "local", "client"
        ):
            raise ValueError(
                f"`mode` must be 'local' or 'client'. "
                f"Got {candidate_params['mode']!r}."
            )
        if "point_estimate" in candidate_params and candidate_params[
            "point_estimate"
        ] not in ("mean", "median", "mode"):
            raise ValueError(
                f"`point_estimate` must be 'mean', 'median' or 'mode'. "
                f"Got {candidate_params['point_estimate']!r}."
            )
        if "tabpfn_model_config" in candidate_params:
            candidate_params["tabpfn_model_config"] = (
                candidate_params["tabpfn_model_config"] or {}
            )
        if "show_progress" in candidate_params and not isinstance(
            candidate_params["show_progress"], bool
        ):
            raise ValueError(
                f"`show_progress` must be a bool. "
                f"Got {candidate_params['show_progress']!r}."
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            (
                {"model_id", "context_length", "mode", "point_estimate",
                 "tabpfn_model_config", "temporal_features"},
                lambda: setattr(self, "_model", None),
            ),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since TabPFN-TS is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self TabPFNAdapter
Source code in skforecast/foundation/_adapters.py
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
) -> TabPFNAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since TabPFN-TS is a zero-shot inference
    model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : TabPFNAdapter

    """

    self.context_      = context
    self.context_exog_ = context_exog
    self.is_fitted     = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using TabPFN-TS.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict pandas Series

Per-series context windows (already trimmed to context_length).

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series past covariates (already trimmed).

required
exog dict pandas DataFrame, pandas Series, or None

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return. If None, a point forecast is produced (shape (steps, 1)). Accepts any float in [0, 1].

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D numpy ndarray of shape (steps, n_quantiles).

Source code in skforecast/foundation/_adapters.py
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using TabPFN-TS.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict pandas Series
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series past covariates (already trimmed).
    exog : dict pandas DataFrame, pandas Series, or None
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return. If `None`, a point forecast is
        produced (shape `(steps, 1)`). Accepts any float in `[0, 1]`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D numpy ndarray of
        shape `(steps, n_quantiles)`.

    """

    self._load_model()

    quantile_list = list(quantiles) if quantiles is not None else None
    tabpfn_quantiles = (
        quantile_list
        if quantile_list is not None
        else [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    )

    series_names_in = list(context.keys())

    first_series = next(iter(context.values()))
    is_datetime = isinstance(first_series.index, pd.DatetimeIndex)

    if not is_datetime:
        warnings.warn(
            "TabPFNAdapter received series with a non-DatetimeIndex. "
            "TabPFN-TS requires datetime timestamps internally; a "
            "synthetic daily DatetimeIndex (starting 2000-01-01) will be "
            "used. Calendar-based temporal features (CalendarFeature) "
            "will not be meaningful for integer-indexed data. Consider "
            "passing `temporal_features=[]` to disable calendar feature "
            "transforms.",
            # stacklevel=3: TabPFNAdapter.predict → FoundationModel.predict → user
            stacklevel=3,
        )

    context_df = self._build_context_df(
                     series_names = series_names_in,
                     context      = context,
                     context_exog = context_exog,
                     is_datetime  = is_datetime
                 )

    future_df = self._build_future_df(
                    series_names = series_names_in,
                    context      = context,
                    exog         = exog,
                    steps        = steps,
                    is_datetime  = is_datetime
                )

    _stderr_cm = (
        contextlib.redirect_stderr(io.StringIO())
        if not self.show_progress
        else contextlib.nullcontext()
    )
    with _stderr_cm:
        result_df = self._model.predict_df(
                        context_df = context_df,
                        future_df  = future_df,
                        quantiles  = tabpfn_quantiles,
                    )

    # result_df is a DataFrame with MultiIndex (item_id, timestamp).
    # columns: "target" (str) and quantile levels as float column names.
    predictions: dict[str, np.ndarray] = {}
    for series_name in series_names_in:
        group = result_df.loc[series_name]  # DataFrame indexed by timestamp
        if quantile_list is None:
            predictions[series_name] = group["target"].to_numpy().reshape(-1, 1)
        else:
            predictions[series_name] = group[quantile_list].to_numpy()

    return predictions

skforecast.foundation._adapters.T0Adapter ¶

T0Adapter(
    model_id,
    *,
    model=None,
    context_length=8192,
    device_map="auto",
    torch_dtype=None
)

Adapter for The Forecasting Company T0 foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "theforecastingcompany/t0-alpha".

required
model T0Forecaster

Pre-loaded model instance. If None, the model is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

8192
device_map str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu".

'auto'
torch_dtype object

Torch dtype the loaded model is cast to (e.g. torch.bfloat16). When None the model keeps its default float32 weights.

None

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

device_map str

Device map string for model loading.

torch_dtype object

Torch dtype for model loading.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. True: T0 defines NaN as an absent covariate value, so the adapter pools the columns of all series and fills the missing cells with NaN.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context.

is_fitted bool

Whether the adapter has been fitted.

Notes

T0 conditions on covariates that are known over both the context and the forecast horizon (future-known covariates). skforecast exogenous variables map exactly onto this channel: their historical values (context_exog, aligned to the context) are concatenated with their future values (exog, aligned to the horizon) to form the [context + horizon] covariate stream that T0 expects. Covariates must be numeric; encode categoricals as numbers before passing them. A series with no future exog is forecast without covariates.

T0 checkpoints (e.g. theforecastingcompany/t0-alpha) are gated on the Hugging Face Hub: visit the model page while logged in to accept its license, then authenticate locally (hf auth login or the HF_TOKEN environment variable) before first use.

References

.. [1] https://github.com/theforecastingcompany/tfc-t0

.. [2] https://huggingface.co/theforecastingcompany/t0-alpha

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "theforecastingcompany/t0-alpha".

required
model T0Forecaster

Pre-loaded model instance. If None, the model is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is. Must be a positive integer.

8192
device_map str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu".

'auto'
torch_dtype object

Torch dtype the loaded model is cast to (e.g. torch.bfloat16). When None the model keeps its default float32 weights.

None

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when a device, dtype, or

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using the T0 model.

Source code in skforecast/foundation/_adapters.py
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 8192,
    device_map: str = "auto",
    torch_dtype: Any | None = None,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. "theforecastingcompany/t0-alpha".
    model : T0Forecaster, default None
        Pre-loaded model instance. If `None`, the model is loaded
        lazily on the first call to `predict`.
    context_length : int, default 8192
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if `context`
        is longer than `context_length` it is trimmed to this length
        before inference; if it is shorter, all available observations
        are passed as-is. Must be a positive integer.
    device_map : str, default 'auto'
        Device placement for the model. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU). Also accepts explicit
        values such as `"cuda"`, `"mps"`, or `"cpu"`.
    torch_dtype : object, default None
        Torch dtype the loaded model is cast to (e.g. `torch.bfloat16`).
        When `None` the model keeps its default `float32` weights.

    """

    _validate_positive_int("context_length", context_length)

    self.model_id       = model_id
    self._model         = model
    self.context_       = None
    self.context_exog_  = None
    self.context_length = context_length
    self.device_map     = device_map
    self.torch_dtype    = torch_dtype
    self.is_fitted      = False

Attributes¶

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = False

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = True

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

device_map instance-attribute ¶

device_map = device_map

torch_dtype instance-attribute ¶

torch_dtype = torch_dtype

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, device_map, torch_dtype.

Source code in skforecast/foundation/_adapters.py
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `device_map`, `torch_dtype`.

    """
    return {
        'model_id':       self.model_id,
        'context_length': self.context_length,
        'device_map':     self.device_map,
        'torch_dtype':    self.torch_dtype,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the model when a device, dtype, or model_id param changes, since those are baked into the loaded model.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, device_map, torch_dtype.

{}

Returns:

Name Type Description
self T0Adapter
Source code in skforecast/foundation/_adapters.py
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
def set_params(self, **params) -> T0Adapter:
    """
    Set adapter parameters. Resets the model when a device, dtype, or
    model_id param changes, since those are baked into the loaded model.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `device_map`,
        `torch_dtype`.

    Returns
    -------
    self : T0Adapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            (
                {"model_id", "device_map", "torch_dtype"},
                lambda: setattr(self, "_model", None),
            ),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since T0 is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self T0Adapter
Source code in skforecast/foundation/_adapters.py
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
) -> T0Adapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since T0 is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : T0Adapter

    """

    self.context_ = context
    self.context_exog_ = context_exog
    self.is_fitted = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the T0 model.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog dict

Per-series past covariates (already trimmed).

required
exog dict

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return, in the requested order. If None, a point forecast (median, quantile 0.5) is produced.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles) with columns ordered to match quantiles.

Source code in skforecast/foundation/_adapters.py
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
    exog: dict[str, pd.DataFrame | pd.Series | None],
    quantiles: list[float] | tuple[float] | None
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the T0 model.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to `context_length`).
    context_exog : dict
        Per-series past covariates (already trimmed).
    exog : dict
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return, in the requested order. If `None`, a
        point forecast (median, quantile 0.5) is produced.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)` with columns ordered to match `quantiles`.

    """

    # NOTE: the model is loaded lazily here so that the adapter can be
    # instantiated and fitted without requiring tfc-t0 to be installed.
    self._load_model()

    requested = list(quantiles) if quantiles is not None else [0.5]
    # T0 requires sorted, unique levels in (0, 1); query those, then
    # reindex the columns back to the order the caller asked for.
    query_levels = sorted(set(requested))

    series_names = list(context.keys())
    arrays = [
        np.asarray(context[series_name].to_numpy(), dtype=np.float32)
        for series_name in series_names
    ]
    lengths = [a.shape[0] for a in arrays]
    context_length = max(lengths)

    # All series are forecast in a single batched call. Series shorter than
    # the longest are left-padded with NaN, which T0 treats as MISSING; the
    # forecast origin therefore aligns at the end of the window for every
    # series.
    context_batch = np.full((len(series_names), context_length), np.nan, dtype=np.float32)
    for row, array in zip(context_batch, arrays):
        row[context_length - array.shape[0]:] = array

    future_covariates = self._build_future_covariates(
        series_names   = series_names,
        context_exog   = context_exog,
        exog           = exog,
        context_length = context_length,
        steps          = steps,
    )

    forecast = self._model.predict(
        context           = context_batch,
        horizon           = steps,
        quantiles         = query_levels,
        future_covariates = future_covariates,
    )

    q_arr = _tensor_to_numpy(forecast.quantiles)

    quantile_column_indices = [query_levels.index(q) for q in requested]
    return {
        series_name: q_arr[i][:, quantile_column_indices]
        for i, series_name in enumerate(series_names)
    }

skforecast.foundation._adapters.NoriAdapter ¶

NoriAdapter(
    model_id,
    *,
    model=None,
    context_length=4096,
    point_estimate="mean",
    add_calendar_features=True,
    n_fourier_terms=2,
    nori_config=None
)

Adapter for Synthefy Nori zero-shot tabular foundation models.

Nori is a tabular regression foundation model that predicts via in-context learning: given labeled context rows it predicts query rows in a single forward pass, with no task-specific training or fine-tuning. This adapter frames forecasting as tabular regression: each series is featurized (running index, calendar features, Fourier seasonal terms, and optional known-future covariates) and a NoriRegressor predicts the forecast horizon zero-shot.

Parameters:

Name Type Description Default
model_id str

Model ID, e.g. "Synthefy/Nori" (6M), "Synthefy/Nori-30M" or "Synthefy/Nori-100M". Used to resolve this adapter and, unless overridden in nori_config, to select the checkpoint downloaded from HuggingFace.

required
model object

Pre-instantiated NoriRegressor instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to use as context rows. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

4096
point_estimate str

Method used to derive the point forecast from Nori's predictive distribution. Accepted values: 'mean', 'median', 'mode'.

'mean'
add_calendar_features bool

If True, add calendar features (month, day, day-of-week, day-of-year, quarter, hour) when the series has a DatetimeIndex. Ignored for RangeIndex series.

True
n_fourier_terms int

Number of Fourier (sin/cos) seasonal harmonics added on the yearly and weekly cycles for datetime series (or on the running index for RangeIndex series). Set 0 to disable. Must be a non-negative integer.

2
nori_config dict

Keyword arguments forwarded verbatim to NoriRegressor at instantiation (e.g. device, token, augmentations). The checkpoint defaults to model_id and can be overridden here with model (a registry name such as 'nori-6m' or a HuggingFace repo id) or model_path (a local checkpoint file, which takes precedence over model).

None

Attributes:

Name Type Description
model_id str

Model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

point_estimate str

Point forecast method.

add_calendar_features bool

Whether calendar features are added for datetime series.

n_fourier_terms int

Number of Fourier seasonal harmonics added.

nori_config dict

Additional configuration forwarded to NoriRegressor.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. True: every series is fitted and predicted in its own NoriRegressor call.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context. True: NoriRegressor rejects NaN, so the adapter drops the context rows whose target (or any feature) is NaN before the in-context fit.

is_fitted bool

Whether the adapter has been fitted.

_model object

Internal NoriRegressor instance. None until the first call to predict, after which it is cached for reuse.

Notes

Nori supports arbitrary quantile levels (any float strictly in (0, 1)), unlike models with fixed quantile sets such as TimesFM or Moirai. A bar_distribution checkpoint does not support quantiles.

Covariate support is available for known-future covariates: columns present in both the historical context and the forecast horizon are used as features. Covariates without future values are ignored. Covariates must be numeric; encode categoricals as numbers before passing them.

Series with a RangeIndex are accepted; only running-index and Fourier(index) features are meaningful there (calendar features are skipped).

References

.. [1] https://github.com/Synthefy/synthefy-nori

.. [2] https://huggingface.co/Synthefy/Nori

.. [3] https://docs.synthefy.com/nori/

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

Model ID, e.g. "Synthefy/Nori".

required
model object

Pre-instantiated NoriRegressor instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is. Must be a positive integer.

4096
point_estimate str

Method used to derive the point forecast. Accepted values: 'mean', 'median', 'mode'.

'mean'
add_calendar_features bool

If True, add calendar features when the series has a DatetimeIndex. Ignored for RangeIndex series.

True
n_fourier_terms int

Number of Fourier seasonal harmonics added. Set 0 to disable. Must be a non-negative integer.

2
nori_config dict

Keyword arguments forwarded verbatim to NoriRegressor at instantiation. The checkpoint defaults to model_id and can be overridden here with model or model_path.

None

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the loaded model when a parameter baked

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using Nori.

Source code in skforecast/foundation/_adapters.py
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 4096,
    point_estimate: str = "mean",
    add_calendar_features: bool = True,
    n_fourier_terms: int = 2,
    nori_config: dict[str, Any] | None = None,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        Model ID, e.g. `"Synthefy/Nori"`.
    model : object, default None
        Pre-instantiated `NoriRegressor` instance. If `None`, a new
        instance is created lazily on the first call to `predict`.
        Intended for testing only.
    context_length : int, default 4096
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if `context`
        is longer than `context_length` it is trimmed to this length
        before inference; if it is shorter, all available observations are
        passed as-is. Must be a positive integer.
    point_estimate : str, default 'mean'
        Method used to derive the point forecast. Accepted values:
        `'mean'`, `'median'`, `'mode'`.
    add_calendar_features : bool, default True
        If `True`, add calendar features when the series has a
        `DatetimeIndex`. Ignored for `RangeIndex` series.
    n_fourier_terms : int, default 2
        Number of Fourier seasonal harmonics added. Set `0` to disable.
        Must be a non-negative integer.
    nori_config : dict, default None
        Keyword arguments forwarded verbatim to `NoriRegressor` at
        instantiation. The checkpoint defaults to `model_id` and can be
        overridden here with `model` or `model_path`.

    """

    _validate_positive_int("context_length", context_length)
    if point_estimate not in ("mean", "median", "mode"):
        raise ValueError(
            f"`point_estimate` must be 'mean', 'median' or 'mode'. "
            f"Got {point_estimate!r}."
        )
    if not isinstance(add_calendar_features, bool):
        raise ValueError(
            f"`add_calendar_features` must be a bool. "
            f"Got {add_calendar_features!r}."
        )
    if not isinstance(n_fourier_terms, int) or n_fourier_terms < 0:
        raise ValueError(
            f"`n_fourier_terms` must be a non-negative integer. "
            f"Got {n_fourier_terms!r}."
        )

    self.model_id              = model_id
    self._model                = model
    self.context_              = None
    self.context_exog_         = None
    self.context_length        = context_length
    self.point_estimate        = point_estimate
    self.add_calendar_features = add_calendar_features
    self.n_fourier_terms       = n_fourier_terms
    self.nori_config           = nori_config or {}
    self.is_fitted             = False

Attributes¶

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = False

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = True

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

context_length instance-attribute ¶

context_length = context_length

point_estimate instance-attribute ¶

point_estimate = point_estimate

add_calendar_features instance-attribute ¶

add_calendar_features = add_calendar_features

n_fourier_terms instance-attribute ¶

n_fourier_terms = n_fourier_terms

nori_config instance-attribute ¶

nori_config = nori_config or {}

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, point_estimate, add_calendar_features, n_fourier_terms, nori_config. nori_config is returned as None when no additional config was set (i.e. when the internal dict is empty).

Source code in skforecast/foundation/_adapters.py
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `point_estimate`,
        `add_calendar_features`, `n_fourier_terms`, `nori_config`.
        `nori_config` is returned as `None` when no additional config was
        set (i.e. when the internal dict is empty).

    """
    return {
        "model_id":              self.model_id,
        "context_length":        self.context_length,
        "point_estimate":        self.point_estimate,
        "add_calendar_features": self.add_calendar_features,
        "n_fourier_terms":       self.n_fourier_terms,
        "nori_config":           self.nori_config or None,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the loaded model when a parameter baked into the NoriRegressor instance changes (model_id, nori_config); featurization/inference-time parameters (context_length, point_estimate, add_calendar_features, n_fourier_terms) do not reset the model.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, point_estimate, add_calendar_features, n_fourier_terms, nori_config.

{}

Returns:

Name Type Description
self NoriAdapter
Source code in skforecast/foundation/_adapters.py
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
def set_params(self, **params) -> NoriAdapter:
    """
    Set adapter parameters. Resets the loaded model when a parameter baked
    into the `NoriRegressor` instance changes (`model_id`, `nori_config`);
    featurization/inference-time parameters (`context_length`,
    `point_estimate`, `add_calendar_features`, `n_fourier_terms`) do not
    reset the model.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `point_estimate`,
        `add_calendar_features`, `n_fourier_terms`, `nori_config`.

    Returns
    -------
    self : NoriAdapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        if "point_estimate" in candidate_params and candidate_params[
            "point_estimate"
        ] not in ("mean", "median", "mode"):
            raise ValueError(
                f"`point_estimate` must be 'mean', 'median' or 'mode'. "
                f"Got {candidate_params['point_estimate']!r}."
            )
        if "add_calendar_features" in candidate_params and not isinstance(
            candidate_params["add_calendar_features"], bool
        ):
            raise ValueError(
                f"`add_calendar_features` must be a bool. "
                f"Got {candidate_params['add_calendar_features']!r}."
            )
        if "n_fourier_terms" in candidate_params and (
            not isinstance(candidate_params["n_fourier_terms"], int)
            or candidate_params["n_fourier_terms"] < 0
        ):
            raise ValueError(
                f"`n_fourier_terms` must be a non-negative integer. "
                f"Got {candidate_params['n_fourier_terms']!r}."
            )
        if "nori_config" in candidate_params:
            candidate_params["nori_config"] = (
                candidate_params["nori_config"] or {}
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            ({"model_id", "nori_config"}, lambda: setattr(self, "_model", None)),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since Nori is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self NoriAdapter
Source code in skforecast/foundation/_adapters.py
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
) -> NoriAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since Nori is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : NoriAdapter

    """

    self.context_      = context
    self.context_exog_ = context_exog
    self.is_fitted     = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using Nori.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict pandas Series

Per-series context windows (already trimmed to context_length).

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series past covariates (already trimmed).

required
exog dict pandas DataFrame, pandas Series, or None

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return, in the requested order. Must lie strictly in (0, 1). If None, a point forecast is produced (shape (steps, 1)).

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D numpy ndarray of shape (steps, n_quantiles) with columns ordered to match quantiles.

Notes

A ValueError is raised if a requested quantile level is not strictly in (0, 1).

Source code in skforecast/foundation/_adapters.py
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using Nori.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict pandas Series
        Per-series context windows (already trimmed to `context_length`).
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series past covariates (already trimmed).
    exog : dict pandas DataFrame, pandas Series, or None
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return, in the requested order. Must lie
        strictly in `(0, 1)`. If `None`, a point forecast is produced
        (shape `(steps, 1)`).

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D numpy ndarray of shape
        `(steps, n_quantiles)` with columns ordered to match `quantiles`.

    Notes
    -----
    A `ValueError` is raised if a requested quantile level is not
    strictly in `(0, 1)`.

    """

    quantile_list = list(quantiles) if quantiles is not None else None
    if quantile_list is not None and any(
        (q <= 0.0) or (q >= 1.0) for q in quantile_list
    ):
        raise ValueError(
            "NoriAdapter quantiles must lie strictly in (0, 1). "
            f"Got {quantile_list!r}."
        )

    # Nori does not guarantee that the output column order matches the
    # requested quantiles, so query sorted, unique levels and reindex the
    # columns back to the caller's order afterwards.
    if quantile_list is not None:
        query_levels = sorted(set(quantile_list))
        quantile_column_indices = [query_levels.index(q) for q in quantile_list]

    self._load_model()

    first_series = next(iter(context.values()))
    is_datetime = isinstance(first_series.index, pd.DatetimeIndex)
    if not is_datetime and self.add_calendar_features:
        warnings.warn(
            "NoriAdapter received series with a non-DatetimeIndex; "
            "calendar features are skipped. Only running-index and "
            "Fourier(index) features are used.",
            # stacklevel=3: NoriAdapter.predict → FoundationModel.predict → user
            stacklevel=3,
        )

    predictions: dict[str, np.ndarray] = {}
    for series_name, series in context.items():
        ctx_exog = (
            context_exog.get(series_name) if context_exog is not None else None
        )
        fut_exog = exog.get(series_name) if exog is not None else None
        exog_cols = self._known_future_columns(ctx_exog, fut_exog)

        X_ctx = self._featurize(
            series, is_datetime, ctx_exog, exog_cols, offset=0, n=len(series)
        )
        X_fut = self._featurize(
            series, is_datetime, fut_exog, exog_cols, offset=len(series), n=steps
        )
        y_ctx = series.to_numpy(dtype=float)

        # NoriRegressor rejects NaN. Rows whose target or any feature is
        # NaN are dropped from the context: the running-index feature is
        # an absolute offset, so dropping interior rows keeps the
        # remaining rows correctly positioned in time.
        valid_rows = ~np.isnan(y_ctx) & ~np.isnan(X_ctx).any(axis=1)
        if not valid_rows.any():
            raise ValueError(
                f"Series '{series_name}' has no context rows without NaN in the "
                f"target and the covariates. NoriAdapter cannot predict it."
            )
        X_ctx = X_ctx[valid_rows]
        y_ctx = y_ctx[valid_rows]

        # Nori fits in-context (no gradient training); the cached model is
        # re-conditioned on each series' context rows before predicting.
        self._model.fit(X_ctx, y_ctx)

        if quantile_list is None:
            y_hat = self._model.predict(X_fut, output_type=self.point_estimate)
            predictions[series_name] = self._to_numpy(y_hat).reshape(-1, 1)
        else:
            q = self._to_numpy(
                self._model.predict(
                    X_fut, output_type="quantiles", quantiles=query_levels
                )
            )
            # Nori returns (n_quantiles, steps); skforecast expects
            # (steps, n_quantiles). Reorder columns to the requested order.
            q = q.reshape(len(query_levels), steps).T
            predictions[series_name] = q[:, quantile_column_indices]

    return predictions

skforecast.foundation._adapters.TSICLAdapter ¶

TSICLAdapter(
    model_id,
    *,
    model=None,
    checkpoint_version="tsicl-v1.ckpt",
    context_length=4096,
    device="auto",
    allow_auto_download=True
)

Adapter for EDF Lab TS-ICL foundation model.

Parameters:

Name Type Description Default
model_id str

Model ID, e.g. "taharnbl/TS-ICL". Used only to resolve this adapter; the underlying checkpoint is always downloaded from the taharnbl/TS-ICL Hugging Face repository, controlled by checkpoint_version.

required
model object

Pre-instantiated TSICL model instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
checkpoint_version str

Checkpoint filename to download from the taharnbl/TS-ICL Hugging Face repository.

'tsicl-v1.ckpt'
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

4096
device str

Device placement for inference. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu". Note that TS-ICL currently falls back to CPU whenever CUDA is unavailable, so "mps" has no effect on Apple Silicon.

'auto'
allow_auto_download bool

Whether to allow automatic download of the checkpoint from Hugging Face Hub if it is not already cached locally.

True

Attributes:

Name Type Description
model_id str

Model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

checkpoint_version str

Checkpoint filename downloaded from Hugging Face Hub.

context_length int

Maximum number of historical observations used as context.

device str

Device placement for inference.

allow_auto_download bool

Whether automatic checkpoint download is allowed.

supports_heterogeneous_covariates bool

Whether series with different covariate columns can be forecast in the same backend call. False for TS-ICL: FoundationModel groups the series by covariate signature and calls predict once per group.

supports_nan_in_series bool

Whether the backend accepts NaN values in the series used as context.

is_fitted bool

Whether the adapter has been fitted.

Notes

TS-ICL conditions on covariates that are known over the context, the forecast horizon, or both. skforecast exogenous variables map directly onto this channel: historical values (context_exog) are forwarded as past_covariates and future values (exog) as future_covariates. Covariates must be numeric; encode categoricals as numbers before passing them.

TS-ICL only supports quantile levels on a 0.01 grid in [0.01, 0.99] (i.e. a subset of [0.01, 0.02, ..., 0.99]); requesting any other level raises a ValueError from the underlying library.

References

.. [1] https://github.com/EDF-Lab/ts-icl

.. [2] https://huggingface.co/taharnbl/TS-ICL

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

Model ID, e.g. "taharnbl/TS-ICL". Used only to resolve this adapter.

required
model object

Pre-instantiated TSICL model instance. If None, a new instance is created lazily on the first call to predict.

None
checkpoint_version str

Checkpoint filename to download from the taharnbl/TS-ICL Hugging Face repository.

'tsicl-v1.ckpt'
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is. Must be a positive integer.

4096
device str

Device placement for inference. "auto" selects the best available accelerator (CUDA > MPS > CPU).

'auto'
allow_auto_download bool

Whether to allow automatic download of the checkpoint from Hugging Face Hub if it is not already cached locally.

True

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when checkpoint_version

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using the TS-ICL model.

Source code in skforecast/foundation/_adapters.py
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    checkpoint_version: str = "tsicl-v1.ckpt",
    context_length: int = 4096,
    device: str = "auto",
    allow_auto_download: bool = True,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        Model ID, e.g. `"taharnbl/TS-ICL"`. Used only to resolve this
        adapter.
    model : object, default None
        Pre-instantiated `TSICL` model instance. If `None`, a new
        instance is created lazily on the first call to `predict`.
    checkpoint_version : str, default 'tsicl-v1.ckpt'
        Checkpoint filename to download from the `taharnbl/TS-ICL`
        Hugging Face repository.
    context_length : int, default 4096
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if
        `context` is longer than `context_length` it is trimmed to
        this length before inference; if it is shorter, all available
        observations are passed as-is. Must be a positive integer.
    device : str, default 'auto'
        Device placement for inference. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU).
    allow_auto_download : bool, default True
        Whether to allow automatic download of the checkpoint from
        Hugging Face Hub if it is not already cached locally.

    """

    _validate_positive_int("context_length", context_length)

    self.model_id             = model_id
    self._model               = model
    self._resolved_device     = None
    self.context_             = None
    self.context_exog_        = None
    self.checkpoint_version   = checkpoint_version
    self.context_length       = context_length
    self.device               = device
    self.allow_auto_download  = allow_auto_download
    self.is_fitted            = False

Attributes¶

allow_exog class-attribute instance-attribute ¶

allow_exog = True

supports_past_only_covariates class-attribute instance-attribute ¶

supports_past_only_covariates = True

supports_heterogeneous_covariates class-attribute instance-attribute ¶

supports_heterogeneous_covariates = False

supports_nan_in_series class-attribute instance-attribute ¶

supports_nan_in_series = True

model_id instance-attribute ¶

model_id = model_id

context_ instance-attribute ¶

context_ = None

context_exog_ instance-attribute ¶

context_exog_ = None

checkpoint_version instance-attribute ¶

checkpoint_version = checkpoint_version

context_length instance-attribute ¶

context_length = context_length

device instance-attribute ¶

device = device

allow_auto_download instance-attribute ¶

allow_auto_download = allow_auto_download

is_fitted instance-attribute ¶

is_fitted = False

Methods:¶

get_params ¶

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, checkpoint_version, context_length, device, allow_auto_download.

Source code in skforecast/foundation/_adapters.py
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `checkpoint_version`, `context_length`,
        `device`, `allow_auto_download`.

    """
    return {
        'model_id':             self.model_id,
        'checkpoint_version':   self.checkpoint_version,
        'context_length':       self.context_length,
        'device':               self.device,
        'allow_auto_download':  self.allow_auto_download,
    }

set_params ¶

set_params(**params)

Set adapter parameters. Resets the model when checkpoint_version or allow_auto_download changes, since those control which checkpoint is loaded.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, checkpoint_version, context_length, device, allow_auto_download.

{}

Returns:

Name Type Description
self TSICLAdapter
Source code in skforecast/foundation/_adapters.py
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
def set_params(self, **params) -> TSICLAdapter:
    """
    Set adapter parameters. Resets the model when `checkpoint_version`
    or `allow_auto_download` changes, since those control which
    checkpoint is loaded.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `checkpoint_version`, `context_length`,
        `device`, `allow_auto_download`.

    Returns
    -------
    self : TSICLAdapter

    """

    def validate(candidate_params: dict) -> dict:
        if "context_length" in candidate_params:
            _validate_positive_int(
                "context_length", candidate_params["context_length"]
            )
        return candidate_params

    return _apply_set_params(
        self, params,
        validate=validate,
        resets=(
            (
                {"checkpoint_version", "allow_auto_download"},
                lambda: setattr(self, "_model", None),
            ),
            ({"device"}, lambda: setattr(self, "_resolved_device", None)),
        ),
    )

fit ¶

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since TS-ICL is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self TSICLAdapter
Source code in skforecast/foundation/_adapters.py
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
) -> TSICLAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since TS-ICL is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : TSICLAdapter

    """

    self.context_ = context
    self.context_exog_ = context_exog
    self.is_fitted = True

    return self

predict ¶

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the TS-ICL model.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog dict

Per-series past covariates (already trimmed).

required
exog dict

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return. If None, a point forecast (median, quantile 0.5) is produced.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Source code in skforecast/foundation/_adapters.py
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
    exog: dict[str, pd.DataFrame | pd.Series | None],
    quantiles: list[float] | tuple[float] | None
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the TS-ICL model.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict
        Per-series past covariates (already trimmed).
    exog : dict
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return. If `None`, a point forecast
        (median, quantile 0.5) is produced.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    """

    # NOTE: the model is loaded lazily here so that the adapter can be
    # instantiated and fitted without requiring tsicl to be installed.
    self._load_model()

    import torch

    quantile_list = list(quantiles) if quantiles is not None else None
    query_levels = quantile_list if quantile_list is not None else [0.5]

    series_names_in = list(context.keys())
    inputs_list = [
        self._build_tsicl_input(
            context      = context[series_name].to_numpy(),
            context_exog = (
                context_exog.get(series_name) if context_exog is not None else None
            ),
            exog         = exog.get(series_name) if exog is not None else None,
        )
        for series_name in series_names_in
    ]

    if self._resolved_device is None:
        self._resolved_device = _resolve_torch_device(self.device)
    device = torch.device(self._resolved_device)

    _, quantile_preds = self._model.forecast(
        inputs            = inputs_list,
        prediction_length = steps,
        quantile_levels   = query_levels,
        context_length    = self.context_length,
        device            = device,
        denormalize       = True,
        squeeze_output    = False,
    )

    predictions: dict[str, np.ndarray] = {}
    for i, series_name in enumerate(series_names_in):
        q_arr = _tensor_to_numpy(quantile_preds[i])
        predictions[series_name] = q_arr[0]  # drop the single-variate dim

    return predictions