From 1b60a63bba9ce60aa114c35941d8aac245a2ea12 Mon Sep 17 00:00:00 2001 From: Benjamin Walker Date: Sat, 21 Nov 2026 14:54:54 +0000 Subject: [PATCH 1/2] Add ci-proto foundation model adapter --- .github/copilot-instructions.md | 13 +- .github/workflows/foundation-backends.yml | 2 +- AGENTS.md | 13 +- docs/api/FoundationModel.md | 3 + docs/llms-full.txt | 72 ++- docs/llms.txt | 4 +- docs/releases/releases.md | 5 + docs/user_guides/foundation-ci-proto.md | 93 ++++ llms-full.txt | 72 ++- llms.txt | 4 +- mkdocs.yml | 1 + skforecast/foundation/_adapters.py | 260 ++++++++++ .../foundation/_forecaster_foundation.py | 22 +- skforecast/foundation/_foundation_model.py | 43 +- skforecast/foundation/_model_info.py | 10 +- skforecast/foundation/_utils.py | 6 + .../test_CIprotoAdapter.py | 451 ++++++++++++++++++ .../tests_foundation_models/test_clone.py | 3 +- .../test_list_adapters.py | 5 +- .../test_resolve_adapter.py | 2 + skforecast/model_selection/_validation.py | 23 +- ...est_backtesting_foundation_full_history.py | 50 ++ skills/choosing-a-forecaster/SKILL.md | 4 +- skills/complete-api-reference/SKILL.md | 2 +- .../references/forecaster-constructors.md | 2 +- skills/foundation-forecasting/SKILL.md | 26 +- .../references/adapter-parameters.md | 25 +- skills/prediction-intervals/SKILL.md | 2 +- tools/ai/README.md | 2 +- tools/ai/llms-base.txt | 13 +- tools/docs/hooks/page_meta.yml | 6 + tools/foundation_compat/adapters.toml | 5 + tools/foundation_compat/tests/contracts.py | 15 + 33 files changed, 1127 insertions(+), 132 deletions(-) create mode 100644 docs/user_guides/foundation-ci-proto.md create mode 100644 skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py create mode 100644 skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 197e192bb..3c085fa8f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -124,7 +124,7 @@ skforecast/ ├── direct/ # ForecasterDirect, ForecasterDirectMultiVariate ├── deep_learning/ # ForecasterRnn, create_and_compile_model ├── foundation/ # FoundationModel, ForecasterFoundation, get_model_info, list_adapters -│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) ├── stats/ # Arima, Sarimax, Ets, Arar, acf, pacf, calculate_lag_autocorrelation ├── preprocessing/ # TimeSeriesDifferentiator, RollingFeatures, CalendarFeatures, │ # QuantileBinner, ConformalIntervalCalibrator, reshape_* functions @@ -145,7 +145,7 @@ skforecast/ - **Forecasters inheriting from `ForecasterBase`**: ForecasterRecursive, ForecasterRecursiveMultiSeries, ForecasterRecursiveClassifier, ForecasterDirect, ForecasterDirectMultiVariate, ForecasterRnn - **Standalone forecasters (no inheritance)**: ForecasterStats, ForecasterEquivalentDate, ForecasterFoundation - Statistical models in `stats/` are wrapped by `ForecasterStats` (in `recursive/`) -- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`) resolved from the HuggingFace `model_id` +- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, `CIprotoAdapter`) resolved from the HuggingFace `model_id` - `model_selection/` functions work with all forecaster types - `preprocessing/` classes can be passed to forecasters via `transformer_y`, `transformer_exog`, `window_features` @@ -159,7 +159,7 @@ skforecast/ | ForecasterDirectMultiVariate | Multivariate forecasting (multiple series as features) | | ForecasterRnn | Deep learning (RNN/LSTM) forecasting | | ForecasterStats | Statistical models (ARIMA, SARIMAX, ETS, ARAR) | -| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) | +| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) | | ForecasterRecursiveClassifier | Classification-based forecasting | | ForecasterEquivalentDate | Baseline forecaster using equivalent past dates | @@ -543,7 +543,7 @@ forecaster = ForecasterStats(estimator=Ets(m=12, model='AAA')) ## Foundation Models (Zero-Shot) -Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. +Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `continuousintelligence>=0.2.0`, `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. `FoundationModel` is the low-level interface; `ForecasterFoundation` wraps it to integrate with the rest of the skforecast ecosystem (backtesting, model selection, uniform `predict` / `predict_interval` / `predict_quantiles` API). @@ -584,6 +584,7 @@ Supported adapters (selected automatically from `model_id`). Query them programm | TSICLAdapter (EDF Lab) | `taharnbl/TS-ICL` | Yes (past & future covariates) | 4096 | Subset of `[0.01, 0.02, ..., 0.99]` | | TimestralAdapter (Mistral AI) | `mistralai/Timestral` | Yes (past, known-future and categorical covariates) | 4096 | Subset of `[0.01, 0.05, 0.1, ..., 0.95, 0.99]` (21 levels) | | TiRex2Adapter (NX-AI) | `NX-AI/TiRex-2` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` | +| CIprotoAdapter (Continuous Intelligence) | `ContinuousIntelligence/ci-proto` | Yes (past, known-future and categorical covariates) | None (all available history) | `[0.1, 0.2, ..., 0.9]` | ```python from skforecast.foundation import get_model_info, list_adapters @@ -610,13 +611,13 @@ list_adapters(as_frame=True) ``` Key points: -- `fit()` only stores the last `context_length` observations and metadata. It does **not** train the model. +- `fit()` stores the last `context_length` observations and metadata, or all available history when `context_length=None`. It does **not** train the model. - The index must have a frequency (`data.asfreq(...)`), same requirement as other skforecast forecasters. - `predict(..., context=...)` lets you override the stored context (used internally by backtesting). - Use `backtesting_foundation` (not `backtesting_forecaster`) to evaluate a `ForecasterFoundation`. It deep-copies `cv` and forces `refit=True`, `fixed_train_size=False`, so the context window expands with each fold up to `context_length`; no weights are ever trained. - Use `bayesian_search_foundation` (not `bayesian_search_forecaster`) to tune inference-time parameters such as `context_length`. Only `TimeSeriesFold` is supported. - Loading a model whose weights are released under a license that restricts commercial use (TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, Timestral) raises a `LicenseWarning` naming the license and a link to the model card; review the link, since terms vary (e.g. TabPFN-TS permits commercial use under an enterprise license; Timestral grants no rights to companies above USD 20 million of monthly revenue). Absence of the warning does not guarantee a model's license is unrestricted. Suppress it like any other skforecast warning (`suppress_warnings=True` or `warnings.simplefilter`). -- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. +- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. - Multi-series input may be heterogeneous: series can have different lengths, a different subset of exog columns each, and NaN values. Each series is forecast with its own exog columns only. When the backend needs identical covariate columns in a batch (`forecaster.supports_heterogeneous_covariates` is `False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral), the series are grouped by their exog columns and the backend is called once per group, so the forecast of a series never depends on the exog of the others. `forecaster.supports_nan_in_series` tells whether the backend accepts NaN in the context. - Timestral: with a known covariate that is constant over the context and changes over the horizon (a price, or a 0/1 indicator that is 0 over the whole context), the upper quantiles can become very large (mistralai/timestral#7); a `FeatureOutOfRangeWarning` names the affected series and columns, and setting their historical values to NaN avoids it. - TiRex-2: each checkpoint forecasts at most `future_len` steps ahead (320 for `NX-AI/TiRex-2`, 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). All the series go to the backend in the same call whatever their exog, in calls of at most 64 series. diff --git a/.github/workflows/foundation-backends.yml b/.github/workflows/foundation-backends.yml index acf286240..689b52650 100644 --- a/.github/workflows/foundation-backends.yml +++ b/.github/workflows/foundation-backends.yml @@ -71,7 +71,7 @@ jobs: matrix: # Same entries as tools/foundation_compat/adapters.toml (checked by # the unit test test_backends_compat_config.py). - adapter: [chronos, timesfm25, timesfm3, moirai, tabicl, tabpfn, t0, nori, tsicl, timestral, tirex2] + adapter: [chronos, timesfm25, timesfm3, moirai, tabicl, tabpfn, t0, nori, tsicl, timestral, tirex2, ci_proto] steps: - name: Checkout code uses: actions/checkout@v7 diff --git a/AGENTS.md b/AGENTS.md index 197e192bb..3c085fa8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -124,7 +124,7 @@ skforecast/ ├── direct/ # ForecasterDirect, ForecasterDirectMultiVariate ├── deep_learning/ # ForecasterRnn, create_and_compile_model ├── foundation/ # FoundationModel, ForecasterFoundation, get_model_info, list_adapters -│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) ├── stats/ # Arima, Sarimax, Ets, Arar, acf, pacf, calculate_lag_autocorrelation ├── preprocessing/ # TimeSeriesDifferentiator, RollingFeatures, CalendarFeatures, │ # QuantileBinner, ConformalIntervalCalibrator, reshape_* functions @@ -145,7 +145,7 @@ skforecast/ - **Forecasters inheriting from `ForecasterBase`**: ForecasterRecursive, ForecasterRecursiveMultiSeries, ForecasterRecursiveClassifier, ForecasterDirect, ForecasterDirectMultiVariate, ForecasterRnn - **Standalone forecasters (no inheritance)**: ForecasterStats, ForecasterEquivalentDate, ForecasterFoundation - Statistical models in `stats/` are wrapped by `ForecasterStats` (in `recursive/`) -- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`) resolved from the HuggingFace `model_id` +- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, `CIprotoAdapter`) resolved from the HuggingFace `model_id` - `model_selection/` functions work with all forecaster types - `preprocessing/` classes can be passed to forecasters via `transformer_y`, `transformer_exog`, `window_features` @@ -159,7 +159,7 @@ skforecast/ | ForecasterDirectMultiVariate | Multivariate forecasting (multiple series as features) | | ForecasterRnn | Deep learning (RNN/LSTM) forecasting | | ForecasterStats | Statistical models (ARIMA, SARIMAX, ETS, ARAR) | -| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) | +| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) | | ForecasterRecursiveClassifier | Classification-based forecasting | | ForecasterEquivalentDate | Baseline forecaster using equivalent past dates | @@ -543,7 +543,7 @@ forecaster = ForecasterStats(estimator=Ets(m=12, model='AAA')) ## Foundation Models (Zero-Shot) -Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. +Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `continuousintelligence>=0.2.0`, `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. `FoundationModel` is the low-level interface; `ForecasterFoundation` wraps it to integrate with the rest of the skforecast ecosystem (backtesting, model selection, uniform `predict` / `predict_interval` / `predict_quantiles` API). @@ -584,6 +584,7 @@ Supported adapters (selected automatically from `model_id`). Query them programm | TSICLAdapter (EDF Lab) | `taharnbl/TS-ICL` | Yes (past & future covariates) | 4096 | Subset of `[0.01, 0.02, ..., 0.99]` | | TimestralAdapter (Mistral AI) | `mistralai/Timestral` | Yes (past, known-future and categorical covariates) | 4096 | Subset of `[0.01, 0.05, 0.1, ..., 0.95, 0.99]` (21 levels) | | TiRex2Adapter (NX-AI) | `NX-AI/TiRex-2` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` | +| CIprotoAdapter (Continuous Intelligence) | `ContinuousIntelligence/ci-proto` | Yes (past, known-future and categorical covariates) | None (all available history) | `[0.1, 0.2, ..., 0.9]` | ```python from skforecast.foundation import get_model_info, list_adapters @@ -610,13 +611,13 @@ list_adapters(as_frame=True) ``` Key points: -- `fit()` only stores the last `context_length` observations and metadata. It does **not** train the model. +- `fit()` stores the last `context_length` observations and metadata, or all available history when `context_length=None`. It does **not** train the model. - The index must have a frequency (`data.asfreq(...)`), same requirement as other skforecast forecasters. - `predict(..., context=...)` lets you override the stored context (used internally by backtesting). - Use `backtesting_foundation` (not `backtesting_forecaster`) to evaluate a `ForecasterFoundation`. It deep-copies `cv` and forces `refit=True`, `fixed_train_size=False`, so the context window expands with each fold up to `context_length`; no weights are ever trained. - Use `bayesian_search_foundation` (not `bayesian_search_forecaster`) to tune inference-time parameters such as `context_length`. Only `TimeSeriesFold` is supported. - Loading a model whose weights are released under a license that restricts commercial use (TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, Timestral) raises a `LicenseWarning` naming the license and a link to the model card; review the link, since terms vary (e.g. TabPFN-TS permits commercial use under an enterprise license; Timestral grants no rights to companies above USD 20 million of monthly revenue). Absence of the warning does not guarantee a model's license is unrestricted. Suppress it like any other skforecast warning (`suppress_warnings=True` or `warnings.simplefilter`). -- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. +- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. - Multi-series input may be heterogeneous: series can have different lengths, a different subset of exog columns each, and NaN values. Each series is forecast with its own exog columns only. When the backend needs identical covariate columns in a batch (`forecaster.supports_heterogeneous_covariates` is `False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral), the series are grouped by their exog columns and the backend is called once per group, so the forecast of a series never depends on the exog of the others. `forecaster.supports_nan_in_series` tells whether the backend accepts NaN in the context. - Timestral: with a known covariate that is constant over the context and changes over the horizon (a price, or a 0/1 indicator that is 0 over the whole context), the upper quantiles can become very large (mistralai/timestral#7); a `FeatureOutOfRangeWarning` names the affected series and columns, and setting their historical values to NaN avoids it. - TiRex-2: each checkpoint forecasts at most `future_len` steps ahead (320 for `NX-AI/TiRex-2`, 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). All the series go to the backend in the same call whatever their exog, in calls of at most 64 series. diff --git a/docs/api/FoundationModel.md b/docs/api/FoundationModel.md index 4b136020b..ed30e6f9e 100644 --- a/docs/api/FoundationModel.md +++ b/docs/api/FoundationModel.md @@ -34,6 +34,9 @@ ::: skforecast.foundation._adapters.TiRex2Adapter options: show_bases: false +::: skforecast.foundation._adapters.CIprotoAdapter + options: + show_bases: false ::: skforecast.foundation._model_info.get_model_info ::: skforecast.foundation._model_info.list_adapters ::: skforecast.foundation._model_info.FoundationModelInfo diff --git a/docs/llms-full.txt b/docs/llms-full.txt index b971e9365..f7b4641db 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -42,7 +42,7 @@ skforecast/ ├── direct/ # ForecasterDirect, ForecasterDirectMultiVariate ├── deep_learning/ # ForecasterRnn, create_and_compile_model ├── foundation/ # FoundationModel, ForecasterFoundation, get_model_info, list_adapters -│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) ├── stats/ # Arima, Sarimax, Ets, Arar, acf, pacf, calculate_lag_autocorrelation ├── preprocessing/ # TimeSeriesDifferentiator, RollingFeatures, CalendarFeatures, │ # QuantileBinner, ConformalIntervalCalibrator, reshape_* functions @@ -63,7 +63,7 @@ skforecast/ - **Forecasters inheriting from `ForecasterBase`**: ForecasterRecursive, ForecasterRecursiveMultiSeries, ForecasterRecursiveClassifier, ForecasterDirect, ForecasterDirectMultiVariate, ForecasterRnn - **Standalone forecasters (no inheritance)**: ForecasterStats, ForecasterEquivalentDate, ForecasterFoundation - Statistical models in `stats/` are wrapped by `ForecasterStats` (in `recursive/`) -- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`) resolved from the HuggingFace `model_id` +- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, `CIprotoAdapter`) resolved from the HuggingFace `model_id` - `model_selection/` functions work with all forecaster types - `preprocessing/` classes can be passed to forecasters via `transformer_y`, `transformer_exog`, `window_features` @@ -77,7 +77,7 @@ skforecast/ | ForecasterDirectMultiVariate | Multivariate forecasting (multiple series as features) | | ForecasterRnn | Deep learning (RNN/LSTM) forecasting | | ForecasterStats | Statistical models (ARIMA, SARIMAX, ETS, ARAR) | -| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) | +| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) | | ForecasterRecursiveClassifier | Classification-based forecasting | | ForecasterEquivalentDate | Baseline forecaster using equivalent past dates | @@ -461,7 +461,7 @@ forecaster = ForecasterStats(estimator=Ets(m=12, model='AAA')) ## Foundation Models (Zero-Shot) -Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. +Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `continuousintelligence>=0.2.0`, `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. `FoundationModel` is the low-level interface; `ForecasterFoundation` wraps it to integrate with the rest of the skforecast ecosystem (backtesting, model selection, uniform `predict` / `predict_interval` / `predict_quantiles` API). @@ -502,6 +502,7 @@ Supported adapters (selected automatically from `model_id`). Query them programm | TSICLAdapter (EDF Lab) | `taharnbl/TS-ICL` | Yes (past & future covariates) | 4096 | Subset of `[0.01, 0.02, ..., 0.99]` | | TimestralAdapter (Mistral AI) | `mistralai/Timestral` | Yes (past, known-future and categorical covariates) | 4096 | Subset of `[0.01, 0.05, 0.1, ..., 0.95, 0.99]` (21 levels) | | TiRex2Adapter (NX-AI) | `NX-AI/TiRex-2` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` | +| CIprotoAdapter (Continuous Intelligence) | `ContinuousIntelligence/ci-proto` | Yes (past, known-future and categorical covariates) | None (all available history) | `[0.1, 0.2, ..., 0.9]` | ```python from skforecast.foundation import get_model_info, list_adapters @@ -528,13 +529,13 @@ list_adapters(as_frame=True) ``` Key points: -- `fit()` only stores the last `context_length` observations and metadata. It does **not** train the model. +- `fit()` stores the last `context_length` observations and metadata, or all available history when `context_length=None`. It does **not** train the model. - The index must have a frequency (`data.asfreq(...)`), same requirement as other skforecast forecasters. - `predict(..., context=...)` lets you override the stored context (used internally by backtesting). - Use `backtesting_foundation` (not `backtesting_forecaster`) to evaluate a `ForecasterFoundation`. It deep-copies `cv` and forces `refit=True`, `fixed_train_size=False`, so the context window expands with each fold up to `context_length`; no weights are ever trained. - Use `bayesian_search_foundation` (not `bayesian_search_forecaster`) to tune inference-time parameters such as `context_length`. Only `TimeSeriesFold` is supported. - Loading a model whose weights are released under a license that restricts commercial use (TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, Timestral) raises a `LicenseWarning` naming the license and a link to the model card; review the link, since terms vary (e.g. TabPFN-TS permits commercial use under an enterprise license; Timestral grants no rights to companies above USD 20 million of monthly revenue). Absence of the warning does not guarantee a model's license is unrestricted. Suppress it like any other skforecast warning (`suppress_warnings=True` or `warnings.simplefilter`). -- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. +- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. - Multi-series input may be heterogeneous: series can have different lengths, a different subset of exog columns each, and NaN values. Each series is forecast with its own exog columns only. When the backend needs identical covariate columns in a batch (`forecaster.supports_heterogeneous_covariates` is `False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral), the series are grouped by their exog columns and the backend is called once per group, so the forecast of a series never depends on the exog of the others. `forecaster.supports_nan_in_series` tells whether the backend accepts NaN in the context. - Timestral: with a known covariate that is constant over the context and changes over the horizon (a price, or a 0/1 indicator that is 0 over the whole context), the upper quantiles can become very large (mistralai/timestral#7); a `FeatureOutOfRangeWarning` names the affected series and columns, and setting their historical values to NaN avoids it. - TiRex-2: each checkpoint forecasts at most `future_len` steps ahead (320 for `NX-AI/TiRex-2`, 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). All the series go to the backend in the same call whatever their exog, in calls of at most 64 series. @@ -780,7 +781,7 @@ the chosen model adds value. | **General purpose** (start here) | `ForecasterRecursive` | Default choice. One model, recursive multi-step. Works with any sklearn-compatible estimator (LightGBM, XGBoost, CatBoost, RandomForest, etc.). Supports lags, window features, exog, differentiation, transformers, weight functions, and all probabilistic prediction methods (bootstrapping, conformal, quantiles, distributions) | | **Horizon-dependent patterns** (e.g., predicting at 1h vs 24h requires different relationships) | `ForecasterDirect` | Trains one independent model per step — no error propagation. Better when the predictive relationship changes significantly across the forecast horizon. Requires `steps` at init; parallelizable with `n_jobs` | | **Statistical baseline** | `ForecasterStats` | Wraps ARIMA, SARIMAX, ETS, ARAR. Use as a benchmark to compare against ML models, or when the series is very short (< 200 obs) and ML overfits | -| **Zero-shot / cold-start / no training data** | `ForecasterFoundation` | Wraps pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2). `fit()` only stores context, no training. Strong zero-shot accuracy, also for short or new series; needs more compute to predict. See the `foundation-forecasting` skill | +| **Zero-shot / cold-start / no training data** | `ForecasterFoundation` | Wraps pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, ci-proto). `fit()` only stores context, no training. Strong zero-shot accuracy, also for short or new series; needs more compute to predict. See the `foundation-forecasting` skill | | **Naive baseline** | `ForecasterEquivalentDate` | Predicts using equivalent past dates (e.g., same weekday last week). Use as a sanity-check baseline. See the `baseline-forecasting` skill | ## Step 2b — Multiple Series @@ -790,7 +791,7 @@ the chosen model adds value. | **Forecast many series with a shared model** (start here) | `ForecasterRecursiveMultiSeries` | One global model learns cross-series patterns. Supports DataFrame or dict input (dict allows series with different date ranges). Encoding options: `'ordinal'` (default), `'ordinal_category'`, `'onehot'`, `None`. Supports per-series transformers, per-series differentiation, series_weights | | **Other series are features for one target** | `ForecasterDirectMultiVariate` | All series become input features to predict a single `level`. Per-series lags via dict (`{'sales': [1,7], 'price': [1]}`). One model per step — no error propagation | | **Deep learning / complex nonlinear patterns** | `ForecasterRnn` | Keras-based RNN/LSTM/GRU. Single model outputs all steps and levels simultaneously via 3D tensors. Only conformal intervals (no bootstrapping). Requires keras | -| **Zero-shot / pre-trained generalist** | `ForecasterFoundation` | Global zero-shot forecasts via Chronos-2 / TimesFM 2.5/3.0 / Moirai-2 / TabICL / TabPFN-TS / TFC-T0 / Nori / TS-ICL / Timestral / TiRex-2. `fit()` only stores context. Native quantile intervals. Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral and TiRex-2 support exog; TimesFM 2.5 & Moirai-2 do not. See the `foundation-forecasting` skill | +| **Zero-shot / pre-trained generalist** | `ForecasterFoundation` | Global zero-shot forecasts via Chronos-2 / TimesFM 2.5/3.0 / Moirai-2 / TabICL / TabPFN-TS / TFC-T0 / Nori / TS-ICL / Timestral / TiRex-2. `fit()` only stores context. Native quantile intervals. Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2 and ci-proto support exog; TimesFM 2.5 & Moirai-2 do not. See the `foundation-forecasting` skill | ## Decision Flowchart @@ -2372,8 +2373,8 @@ Scan before writing code. Each row lists a rule, the symptom when it is broken, |------|---------|----------| | `fit()` stores context only; it never trains the model | Expecting training to happen or weights to update | Treat the model as pre-trained; evaluate with `backtesting_foundation` | | `cv.refit` and `cv.fixed_train_size` are overridden by `backtesting_foundation` | `IgnoredArgumentWarning` when `refit=True` or `fixed_train_size=False` | Leave them at their defaults; the context window expands per fold either way | -| Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, T0, Nori, TS-ICL, Timestral, and TiRex-2 use `exog`; TimesFM 2.5 and Moirai-2 ignore it | `IgnoredArgumentWarning`, forecast made without `exog` | Pick an exog-capable adapter when covariates matter | -| TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 restrict quantiles to `[0.1, 0.2, ..., 0.9]`; TS-ICL to a 0.01 grid; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`) | Requested quantile rejected or unsupported | Request only supported quantiles, or use an adapter allowing any quantile in (0, 1) | +| Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto use `exog`; TimesFM 2.5 and Moirai-2 ignore it | `IgnoredArgumentWarning`, forecast made without `exog` | Pick an exog-capable adapter when covariates matter | +| TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto restrict quantiles to `[0.1, 0.2, ..., 0.9]`; TS-ICL to a 0.01 grid; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`) | Requested quantile rejected or unsupported | Request only supported quantiles, or use an adapter allowing any quantile in (0, 1) | | Each backend library must be installed separately | `ModuleNotFoundError` / `ImportError` on first use | `pip install` the matching backend (see Installation) | | Tuning uses `bayesian_search_foundation`, never `bayesian_search_forecaster*` | `TypeError` on the forecaster type or on `OneStepAheadFold` | Call `bayesian_search_foundation` with a `TimeSeriesFold` | | Weights for TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, and Timestral are released under licenses that restrict commercial use (terms vary, e.g. TabPFN-TS allows commercial use under an enterprise license, Timestral excludes companies above USD 20 million of monthly revenue); no warning does not mean a model is unrestricted | `LicenseWarning` on first model load | Review the linked license before commercial use; suppress the warning with `suppress_warnings=True` if already reviewed | @@ -2393,6 +2394,7 @@ pip install tsicl # For TS-ICL pip install synthefy-nori # For Nori pip install "timestral @ git+https://github.com/mistralai/timestral.git" # For Timestral (not on PyPI) pip install tirex-2 # For TiRex-2 (Python >= 3.11) +pip install "continuousintelligence>=0.2.0" # For ci-proto ``` Models are downloaded from HuggingFace on first use. @@ -2456,9 +2458,9 @@ model = FoundationModel( ) ``` -## With Exogenous Variables (Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2) +## With Exogenous Variables (Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto) -Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2 (`allow_exog=True`) accept exogenous variables. TimesFM 2.5 and Moirai-2 ignore them. At predict time the future `exog` columns are validated per series against the historical exog: a future column with no history raises `ValueError`; a historical column with no future values is a past-only covariate, used by Chronos-2, TS-ICL, TimesFM 3.0, Timestral and TiRex-2 (`supports_past_only_covariates=True`) and ignored with an `IgnoredArgumentWarning` by TabICL, TabPFN-TS, TFC-T0 and Nori. Series in a multi-series input may differ in length and in their exog columns: each series is forecast with its own columns, and adapters whose backend needs identical columns per batch (`supports_heterogeneous_covariates=False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral) are called once per group of series sharing the same columns, so the forecast of a series never depends on the exog of the others. +Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto (`allow_exog=True`) accept exogenous variables. TimesFM 2.5 and Moirai-2 ignore them. At predict time the future `exog` columns are validated per series against the historical exog: a future column with no history raises `ValueError`; a historical column with no future values is a past-only covariate, used by Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2 and ci-proto (`supports_past_only_covariates=True`) and ignored with an `IgnoredArgumentWarning` by TabICL, TabPFN-TS, TFC-T0 and Nori. Series in a multi-series input may differ in length and in their exog columns: each series is forecast with its own columns, and adapters whose backend needs identical columns per batch (`supports_heterogeneous_covariates=False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral) are called once per group of series sharing the same columns, so the forecast of a series never depends on the exog of the others. ```python # Historical + future exog (must cover the forecast horizon) @@ -2487,7 +2489,7 @@ predictions = forecaster.predict_quantiles( # Columns: ['level', 'q_0.1', 'q_0.5', 'q_0.9'] ``` -For TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2, requested quantiles must be a subset of `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]`. TS-ICL accepts any level on a finer 0.01 grid in `[0.01, 0.99]` (e.g. `0.05`, `0.37`); off-grid levels raise a `ValueError`. Timestral returns 21 fixed levels: `0.01`, `0.05`, every multiple of `0.05` up to `0.95`, and `0.99`; any other level raises a `ValueError`. Chronos-2, TabICL, TabPFN-TS, TFC-T0 and Nori support any quantile in `(0, 1)`. +For TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto, requested quantiles must be a subset of `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]`. TS-ICL accepts any level on a finer 0.01 grid in `[0.01, 0.99]` (e.g. `0.05`, `0.37`); off-grid levels raise a `ValueError`. Timestral returns 21 fixed levels: `0.01`, `0.05`, every multiple of `0.05` up to `0.95`, and `0.99`; any other level raises a `ValueError`. Chronos-2, TabICL, TabPFN-TS, TFC-T0 and Nori support any quantile in `(0, 1)`. ## Choosing a Model @@ -2504,6 +2506,7 @@ For TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2, requested quantiles must be a s | `taharnbl/TS-ICL` (EDF Lab) | Yes | 4096 | Past & future covariates, fine-grained (0.01) quantile grid | | `mistralai/Timestral-*` (Mistral AI) | Yes | 4096 | Long context, past, future and categorical covariates (the 209M checkpoint is the most accurate) | | `NX-AI/TiRex-2` (NX-AI) | Yes | 2048 | Past & future covariates, series with different covariates in one call, horizons up to 320 steps | +| `ContinuousIntelligence/ci-proto` | Yes | None (all available history) | Past, known-future and categorical covariates | The adapter is resolved automatically from the `model_id` prefix — no need to import adapter classes directly. @@ -2609,20 +2612,20 @@ automatically to the last `context_length` observations. 1. **Expecting `fit()` to train the model**: it only stores context. The weights come from HuggingFace. 2. **Index without frequency**: call `series.asfreq('h')` (or similar) before `fit` — skforecast requires a frequency. -3. **Passing `exog` to TimesFM 2.5 / Moirai-2**: ignored with an `IgnoredArgumentWarning`. Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2 support exogenous variables. -4. **Requesting unsupported quantiles**: TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 are restricted to the nine deciles `0.1 … 0.9` ; TS-ICL is restricted to a 0.01 grid in `[0.01, 0.99]`; Timestral to its 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`). +3. **Passing `exog` to TimesFM 2.5 / Moirai-2**: ignored with an `IgnoredArgumentWarning`. Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto support exogenous variables. +4. **Requesting unsupported quantiles**: TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto are restricted to the nine deciles `0.1 … 0.9` ; TS-ICL is restricted to a 0.01 grid in `[0.01, 0.99]`; Timestral to its 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`). 5. **Large model downloads**: first call can be slow; consider using smaller variants (`*-small`) for experimentation. -6. **Forgetting to install the backend**: each foundation model requires its own library (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`). Install only the one(s) you need. `tfc-t0` needs its PyTorch runtime, the `torch` extra (`pip install "tfc-t0[torch]>=0.6"`). `tirex-2` requires Python >= 3.11. +6. **Forgetting to install the backend**: each foundation model requires its own library (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`, `continuousintelligence>=0.2.0`). Install only the one(s) you need. `tfc-t0` needs its PyTorch runtime, the `torch` extra (`pip install "tfc-t0[torch]>=0.6"`). `tirex-2` requires Python >= 3.11. 7. **Tuning a parameter that forces a model reload**: `model_id` and device/dtype arguments reload the model on every trial, and `context_length` does the same on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS. -8. **Assuming TimesFM 3.0 accepts categorical covariates**: it does not, and neither do Nori, T0, TS-ICL, and TiRex-2 (`ValueError`). Only Chronos-2 and Timestral accept them natively. `ForecasterFoundation` has no `transformer_exog`, so encode categoricals as numbers in `exog` before passing it to `fit` and `predict`. +8. **Assuming TimesFM 3.0 accepts categorical covariates**: it does not, and neither do Nori, T0, TS-ICL, and TiRex-2 (`ValueError`). Chronos-2, Timestral and ci-proto accept them natively. `ForecasterFoundation` has no `transformer_exog`, so encode categoricals as numbers in `exog` before passing it to `fit` and `predict`. 9. **Passing a future `exog` column that was not in the historical exog** (`fit` without that column, or `context` without `context_exog`): `ValueError` on every adapter. Pass the same columns to `fit` (or `context_exog`) and to `predict`. -10. **Predicting without `exog` after fitting with exog on TabICL, TabPFN-TS, T0 or Nori**: the historical columns are ignored (`IgnoredArgumentWarning`) and the forecast uses no covariates, as if the model had been fitted without exog. Only Chronos-2, TS-ICL, TimesFM 3.0, Timestral and TiRex-2 use them as past-only covariates. +10. **Predicting without `exog` after fitting with exog on TabICL, TabPFN-TS, T0 or Nori**: the historical columns are ignored (`IgnoredArgumentWarning`) and the forecast uses no covariates, as if the model had been fitted without exog. Only Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2 and ci-proto use them as past-only covariates. 11. **Timestral with a known covariate that is constant over the context and changes over the horizon** (a price that has not moved, or a 0/1 holiday or promotion indicator that is 0 over the whole context): the upper quantiles, and sometimes the median, can become very large ([mistralai/timestral#7](https://github.com/mistralai/timestral/issues/7)). The adapter issues a `FeatureOutOfRangeWarning` naming the series and columns; set the historical values of those columns to NaN. With known covariates, Timestral's forecast of the first steps also depends on `steps`, so do not compare backtests with a different `steps` step by step. 12. **Asking TiRex-2 for more than 320 steps**: `NX-AI/TiRex-2` forecasts at most 320 steps ahead (`future_len` of the checkpoint; 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). Use another adapter for longer horizons. ## References -See [references/adapter-parameters.md](references/adapter-parameters.md) for the per-adapter constructor parameters of `ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, and `TiRex2Adapter`. Each adapter section is self-contained; the last two sections (tunable parameters and model reload cost, common behavior) apply to every adapter, so read them too. +See [references/adapter-parameters.md](references/adapter-parameters.md) for the per-adapter constructor parameters of `ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, and `CIprotoAdapter`. Each adapter section is self-contained; the last two sections (tunable parameters and model reload cost, common behavior) apply to every adapter, so read them too. See the user guide [Foundation models with heterogeneous series](https://skforecast.org/latest/user_guides/foundation-forecasting-with-heterogeneous-series.html) for a worked example with series of different lengths, different exog columns and NaN, and for the table of what each backend requires and tolerates. @@ -2868,6 +2871,22 @@ For each series, columns present in its future `exog` become future covariates s **License**: Apache-2.0, so loading the weights raises no `LicenseWarning`. +## CIprotoAdapter + +**Model prefix:** `ContinuousIntelligence/ci-proto`. Install `continuousintelligence>=0.2.0`. + +**Context window:** up to 2 million observations. All supplied history is used by default. The backend automatically selects between variants tuned for shorter and longer contexts; 16,384 observations is the variant-selection threshold, not a history limit. + +| Parameter | Default | Meaning | +|-----------|---------|---------| +| `context_length` | `None` | All available history. Set a positive integer only to impose a retention limit. | +| `device` | `"auto"` | CUDA if available, otherwise CPU. Explicit `"cpu"` or `"cuda"` are supported. | +| `revision` | `None` | Hugging Face revision shared by weights and calibration; a full SHA pins them. | + +Past-only, known-future and categorical covariates are supported. Labels are encoded per series over history and horizon; missing labels remain NaN. Each series is forecast independently using its own history, covariates and dates. + +The published checkpoint returns deciles 0.1 through 0.9; point forecasts use the median. The adapter selects rows using the loaded quantile grid and validates the returned shape. + ## Tunable Parameters and Model Reload Cost The parameters that can be changed after construction (via `set_params`, and therefore searched with `bayesian_search_foundation`) are exactly the keys returned by each adapter's `get_params()`. Any other key raises `ValueError`. Note that `model` / `pipeline` / `module` are constructor-only and are **not** settable. @@ -2887,12 +2906,13 @@ Being accepted is not the same as being worth searching. Most adapters expose ru | NoriAdapter | `model_id`, `context_length`, `point_estimate`, `add_calendar_features`, `n_fourier_terms`, `nori_config` | `context_length`, `point_estimate`, `add_calendar_features`, `n_fourier_terms`, (`nori_config`) | `model_id`, `nori_config` | | TimestralAdapter | `model_id`, `context_length`, `device`, `predict_kwargs` | `context_length`, (`predict_kwargs`) | `model_id`, `device` | | TiRex2Adapter | `model_id`, `context_length`, `device`, `predict_kwargs` | `context_length`, (`predict_kwargs`) | `model_id`, `device` | +| CIprotoAdapter | `model_id`, `context_length`, `device`, `revision` | `context_length` | `model_id`, `device`, `revision` | Parameters in parentheses are backend passthrough dicts: they can hold quality-relevant settings but are awkward to search, so treat them as advanced. Two consequences that matter when tuning: -- **`context_length` is not uniformly cheap.** It reloads the model on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS; it is free on Chronos-2, TimesFM 3.0, T0, TS-ICL, Nori, Timestral and TiRex-2. +- **`context_length` is not uniformly cheap.** It reloads the model on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS; it is free on Chronos-2, TimesFM 3.0, T0, TS-ICL, Nori, Timestral, TiRex-2 and ci-proto. - **Reset only on change.** All foundation adapters compare the old and new values first (via the shared `set_params` helper), so re-sampling an identical value never triggers a reload. A reload happens only when a reload-triggering key is set to a genuinely new value, for example sampling a different `context_length` on TimesFM 2.5, Moirai-2, TabICL or TabPFN-TS. `model_id` forces a reload on every adapter except `TSICLAdapter`, where the checkpoint is selected by `checkpoint_version` instead. @@ -2905,19 +2925,19 @@ All adapters implement the same minimal interface: - `predict(steps, context, context_exog, exog, quantiles)`: returns a `dict[str, np.ndarray]` of shape `(steps, n_quantiles)` keyed by series name. - `get_params()` / `set_params(**kwargs)`: sklearn-style parameter access. - `allow_exog` / `supports_past_only_covariates` / `supports_heterogeneous_covariates` / `supports_nan_in_series`: class attributes read by `FoundationModel` to decide how exog and NaN are handled. When `supports_heterogeneous_covariates` is `False` (Chronos-2, TS-ICL, TabICL, TimesFM 3.0, T0, Timestral), `FoundationModel.predict` groups the series by their (past-only, future) exog columns and calls `adapter.predict` once per group; adapters never receive a batch with mixed covariate columns. When `supports_nan_in_series` is `False`, a context with NaN raises `ValueError` before the adapter is called (all current adapters accept NaN; Nori drops the NaN rows itself). When `max_series_per_call` is an integer (Timestral: 50, TiRex-2: 64), `FoundationModel.predict` splits each group into consecutive chunks of at most that many series and calls `adapter.predict` once per chunk, because the cost per series, and the memory, of the backend grow with the size of the batch; `None` (every other adapter) sends each group in one call. When `requires_equal_length_context` is `True` (T0, Timestral), `FoundationModel` left-pads the context and the historical exog of each call with NaN to the length of its longest series. -- `supports_categorical_covariates` / `requires_hf_auth` / `requires_provider_auth` / `weights_repo_id` / `weights_in_hf_cache` / `backend_package` / `default_model_id` / `SUPPORTED_QUANTILES`: descriptive class attributes. They are exposed, together with the ones above and the default `context_length`, through `get_model_info` and `list_adapters`. `supports_categorical_covariates` is `True` only for Chronos-2 and Timestral (non-numeric covariates are passed natively); `requires_hf_auth` is `True` when the weights are gated on the Hugging Face Hub (currently none of the supported models); `requires_provider_auth` is `True` only for TabPFN-TS (Prior Labs token and license acceptance, outside the Hugging Face Hub); `weights_repo_id` is the fixed Hugging Face repository of the backends that ignore `model_id` (`jingang/TabICL`, `Prior-Labs/tabpfn_3_5`, `taharnbl/TS-ICL`) and `None` when the weights are downloaded from `model_id`; `weights_in_hf_cache` is `False` only for TabPFN-TS, which keeps the weights in its own cache directory; `SUPPORTED_QUANTILES` is `None` when any level in `(0, 1)` is accepted. +- `supports_categorical_covariates` / `requires_hf_auth` / `requires_provider_auth` / `weights_repo_id` / `weights_in_hf_cache` / `backend_package` / `default_model_id` / `SUPPORTED_QUANTILES`: descriptive class attributes. They are exposed, together with the ones above and the default `context_length`, through `get_model_info` and `list_adapters`. `supports_categorical_covariates` is `True` for Chronos-2, Timestral and ci-proto (non-numeric covariates are passed natively); `requires_hf_auth` is `True` when the weights are gated on the Hugging Face Hub (currently none of the supported models); `requires_provider_auth` is `True` only for TabPFN-TS (Prior Labs token and license acceptance, outside the Hugging Face Hub); `weights_repo_id` is the fixed Hugging Face repository of the backends that ignore `model_id` (`jingang/TabICL`, `Prior-Labs/tabpfn_3_5`, `taharnbl/TS-ICL`) and `None` when the weights are downloaded from `model_id`; `weights_in_hf_cache` is `False` only for TabPFN-TS, which keeps the weights in its own cache directory; `SUPPORTED_QUANTILES` is `None` when any level in `(0, 1)` is accepted. ### Exog column validation at predict time `FoundationModel.predict` (and therefore `ForecasterFoundation.predict`, `predict_interval`, `predict_quantiles`) validates, per series, the columns of the future `exog` against the historical exog used as context (the one stored by `fit`, or `context_exog` when `context` is given). The check is skipped on the internal backtesting path, where both come from the same DataFrame. On every path, before the adapter is called, the historical exog of each series is reindexed to the index of its context and the future `exog` to the forecast horizon; missing timestamps are filled with NaN and reported with a `MissingValuesWarning`. No columns are ever added: a series only carries its own exog columns. For adapters with `supports_past_only_covariates=False`, the historical columns without future values are removed before the adapter is called, also on the backtesting path, so the forecast is the same as without those columns (the backends of TabICL and TabPFN-TS do not discard them on their own). -| Situation (per series) | Adapters with `supports_past_only_covariates=True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2) | Adapters with `supports_past_only_covariates=False` (TabICL, TabPFN-TS, T0, Nori) | +| Situation (per series) | Adapters with `supports_past_only_covariates=True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto) | Adapters with `supports_past_only_covariates=False` (TabICL, TabPFN-TS, T0, Nori) | |---------------------------------------------------------|---------------------------------------------------------------|---------------------------------------------------------------| | Future `exog` column with no historical values | `ValueError` | `ValueError` | | Historical column with no future values (`exog=None` or a subset of columns) | Used as a past-only covariate, no warning | Removed before calling the adapter, `IgnoredArgumentWarning` listing the columns and series | | Same columns on both sides (any order) | OK | OK | -Backend libraries (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`) are imported **lazily** inside the adapter method that needs them, so only the backend for the adapter you actually use needs to be installed. +Backend libraries (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`, `continuousintelligence>=0.2.0`) are imported **lazily** inside the adapter method that needs them, so only the backend for the adapter you actually use needs to be installed. ================================================================================ # SKILL: baseline-forecasting @@ -4856,7 +4876,7 @@ predictions = forecaster.predict_quantiles( ) ``` -TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 restrict quantiles to `[0.1, 0.2, …, 0.9]`; TS-ICL restricts them to a 0.01 grid in `[0.01, 0.99]`; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`); Chronos-2, TabICL, TabPFN-TS, TFC-T0, and Nori accept any quantile in `(0, 1)`. See the `foundation-forecasting` skill for details. +TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto restrict quantiles to `[0.1, 0.2, …, 0.9]`; TS-ICL restricts them to a 0.01 grid in `[0.01, 0.99]`; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`); Chronos-2, TabICL, TabPFN-TS, TFC-T0, and Nori accept any quantile in `(0, 1)`. See the `foundation-forecasting` skill for details. ## During Backtesting @@ -6799,7 +6819,7 @@ Use this when you need exact parameter names, types, defaults, or method signatu - `ForecasterStats` — statistical models (ARIMA, ETS, SARIMAX, ARAR) - `ForecasterEquivalentDate` — baseline using past offsets - `ForecasterRnn` — deep learning (RNN/LSTM/GRU) -- `ForecasterFoundation` — zero-shot with foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2) +- `ForecasterFoundation` — zero-shot with foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, ci-proto) - `FoundationModel` — low-level foundation model wrapper used by `ForecasterFoundation` - `get_model_info` / `list_adapters`: capabilities of a foundation model (exog, quantiles, context length, backend, license) without installing its backend @@ -7012,7 +7032,7 @@ FoundationModel( # torch_dtype : object (Chronos-2, T0) # cross_learning : bool (Chronos-2 only) # max_horizon, forecast_config_kwargs (TimesFM 2.5 only) - # predict_kwargs (Chronos-2, TimesFM 3.0, Timestral, TiRex-2) + # predict_kwargs (Chronos-2, TimesFM 3.0, Timestral, TiRex-2, ci-proto) # point_estimate, tabicl_config, temporal_features, show_progress (TabICL) # mode, point_estimate, tabpfn_model_config, temporal_features, show_progress (TabPFN-TS) # (T0 uses only context_length, device_map, torch_dtype) diff --git a/docs/llms.txt b/docs/llms.txt index 7aa1164de..4221ea783 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -19,7 +19,7 @@ Skforecast supports recursive and direct multi-step forecasting strategies, glob - [ForecasterDirectMultiVariate](https://skforecast.org/latest/api/forecasterdirectmultivariate): Multivariate forecasting using multiple series as input features - [ForecasterRnn](https://skforecast.org/latest/api/forecasterrnn): Deep learning forecasting with RNN/LSTM architectures - [ForecasterStats](https://skforecast.org/latest/api/forecasterstats): Statistical models (ARIMA, SARIMAX, ETS, ARAR) with sklearn-compatible interface -- [ForecasterFoundation](https://skforecast.org/latest/api/forecasterfoundation): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +- [ForecasterFoundation](https://skforecast.org/latest/api/forecasterfoundation): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) - [ForecasterRecursiveClassifier](https://skforecast.org/latest/api/forecasterrecursiveclassifier): Classification-based forecasting for categorical time series - [ForecasterEquivalentDate](https://skforecast.org/latest/api/forecasterequivalentdate): Baseline forecaster using equivalent past dates @@ -63,7 +63,7 @@ Skforecast supports recursive and direct multi-step forecasting strategies, glob ## Foundation Models -- [Forecasting with foundation models](https://skforecast.org/latest/user_guides/foundation-forecasting-models.html): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2). Evaluate with `backtesting_foundation` and tune inference-time parameters such as `context_length` with `bayesian_search_foundation` +- [Forecasting with foundation models](https://skforecast.org/latest/user_guides/foundation-forecasting-models.html): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto). Evaluate with `backtesting_foundation` and tune inference-time parameters such as `context_length` with `bayesian_search_foundation` - [Foundation models with heterogeneous series](https://skforecast.org/latest/user_guides/foundation-forecasting-with-heterogeneous-series.html): Series with different lengths, different exogenous variables and missing values in a single ForecasterFoundation: per-series alignment, grouping by exog columns and the predict and backtesting rules of each backend ## Deep Learning diff --git a/docs/releases/releases.md b/docs/releases/releases.md index 40eb7ae00..a210f95f5 100644 --- a/docs/releases/releases.md +++ b/docs/releases/releases.md @@ -12,6 +12,11 @@ All significant changes to this project are documented in this release file. +## Unreleased + ++ Feature New `CIprotoAdapter` adds Continuous Intelligence ci-proto to `FoundationModel` and `ForecasterFoundation`, supporting context windows of up to **2 million observations**, with automatic selection between variants tuned for shorter and longer histories, past-only, known-future and categorical covariates, and native decile forecasts. [User guide](../user_guides/foundation-ci-proto.md) + + ## 0.27.0 Nov 11, 2026 { id="0.27.0" } The main changes in this release are: diff --git a/docs/user_guides/foundation-ci-proto.md b/docs/user_guides/foundation-ci-proto.md new file mode 100644 index 000000000..0d4968b69 --- /dev/null +++ b/docs/user_guides/foundation-ci-proto.md @@ -0,0 +1,93 @@ +--- +title: Forecasting with ci-proto +description: Forecast with ci-proto in skforecast using past and known-future covariates, categorical inputs, calendar dates, native quantiles and long contexts. +--- + +# Forecasting with ci-proto + +[ci-proto](https://huggingface.co/ContinuousIntelligence/ci-proto) is a pretrained +forecasting model from Continuous Intelligence. The adapter uses the published +Python backend, supporting context windows of up to **2 million observations** +and automatic selection between variants tuned for shorter and longer histories. + +## Installation and first forecast + +Install the optional backend separately: + +~~~bash +pip install skforecast "continuousintelligence>=0.2.0" +~~~ + +The backend supports Python 3.10 to 3.14. On Linux x86-64 its dependencies include +the CUDA compiler toolchain. CPU inference is supported through the same API. + +~~~python +import numpy as np +import pandas as pd +from skforecast.foundation import FoundationModel, ForecasterFoundation + +index = pd.date_range("2026-01-01", periods=384, freq="h") +sales = pd.Series( + 20 + np.sin(np.arange(384) * 2 * np.pi / 24), + index=index, + name="sales", +) +model = FoundationModel( + model_id="ContinuousIntelligence/ci-proto", + device="cpu", + # revision="", +) +forecaster = ForecasterFoundation(estimator=model) +forecaster.fit(series=sales) +prediction = forecaster.predict(steps=24) +interval = forecaster.predict_interval(steps=24, interval=[0.1, 0.9]) +quantiles = forecaster.predict_quantiles(steps=24, quantiles=[0.1, 0.5, 0.9]) +~~~ + +The backend is loaded at the first prediction. Fitting stores observations and +metadata without training model weights. A point forecast is the median. The +published checkpoint supplies the nine deciles from 0.1 to 0.9; other quantiles +are rejected. Quantile rows are matched against the loaded checkpoint's grid. + +## Covariates and multiple series + +Past-only columns in historical exog become past covariates. Columns also +provided in future exog become known-future covariates, with their history +followed by their future values. Numeric, boolean, nullable and categorical +columns are supported. Categorical labels receive per-series codes consistent +over history and horizon; missing values remain missing. + +Each series is forecast independently using its own history, covariates and +forecast origin. Series may have different lengths and different covariate +columns. + +DatetimeIndex inputs supply actual history and future timestamps in epoch +nanoseconds, so the tensor backend uses UTC for calendar features. Monthly and +other calendar frequencies are expanded using pandas offsets. RangeIndex +inputs have no calendar features. + +## Context window + +ci-proto supports context windows of up to **2 million observations**. By +default the adapter retains and forwards all supplied history. The backend +automatically selects the variant tuned for shorter contexts up to 16,384 +observations, or the variant tuned for longer contexts. The switch at 16,384 +does not crop the history, and no extra setting is needed to use longer inputs. + +`context_length=None`, the default, keeps all available history during fitting, +prediction and backtesting. Set a positive `context_length` only when you want +to impose a limit on retained history. + +For evaluation use the existing skforecast +[foundation backtesting workflow](foundation-forecasting-models.ipynb). + +## Licence + +The code and weights use the +[ci-proto Code and Model Licence](https://github.com/continuousintelligence/ci/blob/main/LICENCE). + +**In brief:** Free for research and commercial use, subject to the attribution +and notification requirements in Section 10. Redistribution and use in +externally available products or services require public attribution and a +one-time notification to Continuous Intelligence. Purely internal use is exempt +from these additional requirements. diff --git a/llms-full.txt b/llms-full.txt index b971e9365..f7b4641db 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -42,7 +42,7 @@ skforecast/ ├── direct/ # ForecasterDirect, ForecasterDirectMultiVariate ├── deep_learning/ # ForecasterRnn, create_and_compile_model ├── foundation/ # FoundationModel, ForecasterFoundation, get_model_info, list_adapters -│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) ├── stats/ # Arima, Sarimax, Ets, Arar, acf, pacf, calculate_lag_autocorrelation ├── preprocessing/ # TimeSeriesDifferentiator, RollingFeatures, CalendarFeatures, │ # QuantileBinner, ConformalIntervalCalibrator, reshape_* functions @@ -63,7 +63,7 @@ skforecast/ - **Forecasters inheriting from `ForecasterBase`**: ForecasterRecursive, ForecasterRecursiveMultiSeries, ForecasterRecursiveClassifier, ForecasterDirect, ForecasterDirectMultiVariate, ForecasterRnn - **Standalone forecasters (no inheritance)**: ForecasterStats, ForecasterEquivalentDate, ForecasterFoundation - Statistical models in `stats/` are wrapped by `ForecasterStats` (in `recursive/`) -- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`) resolved from the HuggingFace `model_id` +- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, `CIprotoAdapter`) resolved from the HuggingFace `model_id` - `model_selection/` functions work with all forecaster types - `preprocessing/` classes can be passed to forecasters via `transformer_y`, `transformer_exog`, `window_features` @@ -77,7 +77,7 @@ skforecast/ | ForecasterDirectMultiVariate | Multivariate forecasting (multiple series as features) | | ForecasterRnn | Deep learning (RNN/LSTM) forecasting | | ForecasterStats | Statistical models (ARIMA, SARIMAX, ETS, ARAR) | -| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) | +| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) | | ForecasterRecursiveClassifier | Classification-based forecasting | | ForecasterEquivalentDate | Baseline forecaster using equivalent past dates | @@ -461,7 +461,7 @@ forecaster = ForecasterStats(estimator=Ets(m=12, model='AAA')) ## Foundation Models (Zero-Shot) -Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. +Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `continuousintelligence>=0.2.0`, `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. `FoundationModel` is the low-level interface; `ForecasterFoundation` wraps it to integrate with the rest of the skforecast ecosystem (backtesting, model selection, uniform `predict` / `predict_interval` / `predict_quantiles` API). @@ -502,6 +502,7 @@ Supported adapters (selected automatically from `model_id`). Query them programm | TSICLAdapter (EDF Lab) | `taharnbl/TS-ICL` | Yes (past & future covariates) | 4096 | Subset of `[0.01, 0.02, ..., 0.99]` | | TimestralAdapter (Mistral AI) | `mistralai/Timestral` | Yes (past, known-future and categorical covariates) | 4096 | Subset of `[0.01, 0.05, 0.1, ..., 0.95, 0.99]` (21 levels) | | TiRex2Adapter (NX-AI) | `NX-AI/TiRex-2` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` | +| CIprotoAdapter (Continuous Intelligence) | `ContinuousIntelligence/ci-proto` | Yes (past, known-future and categorical covariates) | None (all available history) | `[0.1, 0.2, ..., 0.9]` | ```python from skforecast.foundation import get_model_info, list_adapters @@ -528,13 +529,13 @@ list_adapters(as_frame=True) ``` Key points: -- `fit()` only stores the last `context_length` observations and metadata. It does **not** train the model. +- `fit()` stores the last `context_length` observations and metadata, or all available history when `context_length=None`. It does **not** train the model. - The index must have a frequency (`data.asfreq(...)`), same requirement as other skforecast forecasters. - `predict(..., context=...)` lets you override the stored context (used internally by backtesting). - Use `backtesting_foundation` (not `backtesting_forecaster`) to evaluate a `ForecasterFoundation`. It deep-copies `cv` and forces `refit=True`, `fixed_train_size=False`, so the context window expands with each fold up to `context_length`; no weights are ever trained. - Use `bayesian_search_foundation` (not `bayesian_search_forecaster`) to tune inference-time parameters such as `context_length`. Only `TimeSeriesFold` is supported. - Loading a model whose weights are released under a license that restricts commercial use (TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, Timestral) raises a `LicenseWarning` naming the license and a link to the model card; review the link, since terms vary (e.g. TabPFN-TS permits commercial use under an enterprise license; Timestral grants no rights to companies above USD 20 million of monthly revenue). Absence of the warning does not guarantee a model's license is unrestricted. Suppress it like any other skforecast warning (`suppress_warnings=True` or `warnings.simplefilter`). -- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. +- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. - Multi-series input may be heterogeneous: series can have different lengths, a different subset of exog columns each, and NaN values. Each series is forecast with its own exog columns only. When the backend needs identical covariate columns in a batch (`forecaster.supports_heterogeneous_covariates` is `False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral), the series are grouped by their exog columns and the backend is called once per group, so the forecast of a series never depends on the exog of the others. `forecaster.supports_nan_in_series` tells whether the backend accepts NaN in the context. - Timestral: with a known covariate that is constant over the context and changes over the horizon (a price, or a 0/1 indicator that is 0 over the whole context), the upper quantiles can become very large (mistralai/timestral#7); a `FeatureOutOfRangeWarning` names the affected series and columns, and setting their historical values to NaN avoids it. - TiRex-2: each checkpoint forecasts at most `future_len` steps ahead (320 for `NX-AI/TiRex-2`, 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). All the series go to the backend in the same call whatever their exog, in calls of at most 64 series. @@ -780,7 +781,7 @@ the chosen model adds value. | **General purpose** (start here) | `ForecasterRecursive` | Default choice. One model, recursive multi-step. Works with any sklearn-compatible estimator (LightGBM, XGBoost, CatBoost, RandomForest, etc.). Supports lags, window features, exog, differentiation, transformers, weight functions, and all probabilistic prediction methods (bootstrapping, conformal, quantiles, distributions) | | **Horizon-dependent patterns** (e.g., predicting at 1h vs 24h requires different relationships) | `ForecasterDirect` | Trains one independent model per step — no error propagation. Better when the predictive relationship changes significantly across the forecast horizon. Requires `steps` at init; parallelizable with `n_jobs` | | **Statistical baseline** | `ForecasterStats` | Wraps ARIMA, SARIMAX, ETS, ARAR. Use as a benchmark to compare against ML models, or when the series is very short (< 200 obs) and ML overfits | -| **Zero-shot / cold-start / no training data** | `ForecasterFoundation` | Wraps pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2). `fit()` only stores context, no training. Strong zero-shot accuracy, also for short or new series; needs more compute to predict. See the `foundation-forecasting` skill | +| **Zero-shot / cold-start / no training data** | `ForecasterFoundation` | Wraps pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, ci-proto). `fit()` only stores context, no training. Strong zero-shot accuracy, also for short or new series; needs more compute to predict. See the `foundation-forecasting` skill | | **Naive baseline** | `ForecasterEquivalentDate` | Predicts using equivalent past dates (e.g., same weekday last week). Use as a sanity-check baseline. See the `baseline-forecasting` skill | ## Step 2b — Multiple Series @@ -790,7 +791,7 @@ the chosen model adds value. | **Forecast many series with a shared model** (start here) | `ForecasterRecursiveMultiSeries` | One global model learns cross-series patterns. Supports DataFrame or dict input (dict allows series with different date ranges). Encoding options: `'ordinal'` (default), `'ordinal_category'`, `'onehot'`, `None`. Supports per-series transformers, per-series differentiation, series_weights | | **Other series are features for one target** | `ForecasterDirectMultiVariate` | All series become input features to predict a single `level`. Per-series lags via dict (`{'sales': [1,7], 'price': [1]}`). One model per step — no error propagation | | **Deep learning / complex nonlinear patterns** | `ForecasterRnn` | Keras-based RNN/LSTM/GRU. Single model outputs all steps and levels simultaneously via 3D tensors. Only conformal intervals (no bootstrapping). Requires keras | -| **Zero-shot / pre-trained generalist** | `ForecasterFoundation` | Global zero-shot forecasts via Chronos-2 / TimesFM 2.5/3.0 / Moirai-2 / TabICL / TabPFN-TS / TFC-T0 / Nori / TS-ICL / Timestral / TiRex-2. `fit()` only stores context. Native quantile intervals. Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral and TiRex-2 support exog; TimesFM 2.5 & Moirai-2 do not. See the `foundation-forecasting` skill | +| **Zero-shot / pre-trained generalist** | `ForecasterFoundation` | Global zero-shot forecasts via Chronos-2 / TimesFM 2.5/3.0 / Moirai-2 / TabICL / TabPFN-TS / TFC-T0 / Nori / TS-ICL / Timestral / TiRex-2. `fit()` only stores context. Native quantile intervals. Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2 and ci-proto support exog; TimesFM 2.5 & Moirai-2 do not. See the `foundation-forecasting` skill | ## Decision Flowchart @@ -2372,8 +2373,8 @@ Scan before writing code. Each row lists a rule, the symptom when it is broken, |------|---------|----------| | `fit()` stores context only; it never trains the model | Expecting training to happen or weights to update | Treat the model as pre-trained; evaluate with `backtesting_foundation` | | `cv.refit` and `cv.fixed_train_size` are overridden by `backtesting_foundation` | `IgnoredArgumentWarning` when `refit=True` or `fixed_train_size=False` | Leave them at their defaults; the context window expands per fold either way | -| Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, T0, Nori, TS-ICL, Timestral, and TiRex-2 use `exog`; TimesFM 2.5 and Moirai-2 ignore it | `IgnoredArgumentWarning`, forecast made without `exog` | Pick an exog-capable adapter when covariates matter | -| TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 restrict quantiles to `[0.1, 0.2, ..., 0.9]`; TS-ICL to a 0.01 grid; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`) | Requested quantile rejected or unsupported | Request only supported quantiles, or use an adapter allowing any quantile in (0, 1) | +| Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto use `exog`; TimesFM 2.5 and Moirai-2 ignore it | `IgnoredArgumentWarning`, forecast made without `exog` | Pick an exog-capable adapter when covariates matter | +| TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto restrict quantiles to `[0.1, 0.2, ..., 0.9]`; TS-ICL to a 0.01 grid; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`) | Requested quantile rejected or unsupported | Request only supported quantiles, or use an adapter allowing any quantile in (0, 1) | | Each backend library must be installed separately | `ModuleNotFoundError` / `ImportError` on first use | `pip install` the matching backend (see Installation) | | Tuning uses `bayesian_search_foundation`, never `bayesian_search_forecaster*` | `TypeError` on the forecaster type or on `OneStepAheadFold` | Call `bayesian_search_foundation` with a `TimeSeriesFold` | | Weights for TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, and Timestral are released under licenses that restrict commercial use (terms vary, e.g. TabPFN-TS allows commercial use under an enterprise license, Timestral excludes companies above USD 20 million of monthly revenue); no warning does not mean a model is unrestricted | `LicenseWarning` on first model load | Review the linked license before commercial use; suppress the warning with `suppress_warnings=True` if already reviewed | @@ -2393,6 +2394,7 @@ pip install tsicl # For TS-ICL pip install synthefy-nori # For Nori pip install "timestral @ git+https://github.com/mistralai/timestral.git" # For Timestral (not on PyPI) pip install tirex-2 # For TiRex-2 (Python >= 3.11) +pip install "continuousintelligence>=0.2.0" # For ci-proto ``` Models are downloaded from HuggingFace on first use. @@ -2456,9 +2458,9 @@ model = FoundationModel( ) ``` -## With Exogenous Variables (Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2) +## With Exogenous Variables (Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto) -Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2 (`allow_exog=True`) accept exogenous variables. TimesFM 2.5 and Moirai-2 ignore them. At predict time the future `exog` columns are validated per series against the historical exog: a future column with no history raises `ValueError`; a historical column with no future values is a past-only covariate, used by Chronos-2, TS-ICL, TimesFM 3.0, Timestral and TiRex-2 (`supports_past_only_covariates=True`) and ignored with an `IgnoredArgumentWarning` by TabICL, TabPFN-TS, TFC-T0 and Nori. Series in a multi-series input may differ in length and in their exog columns: each series is forecast with its own columns, and adapters whose backend needs identical columns per batch (`supports_heterogeneous_covariates=False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral) are called once per group of series sharing the same columns, so the forecast of a series never depends on the exog of the others. +Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto (`allow_exog=True`) accept exogenous variables. TimesFM 2.5 and Moirai-2 ignore them. At predict time the future `exog` columns are validated per series against the historical exog: a future column with no history raises `ValueError`; a historical column with no future values is a past-only covariate, used by Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2 and ci-proto (`supports_past_only_covariates=True`) and ignored with an `IgnoredArgumentWarning` by TabICL, TabPFN-TS, TFC-T0 and Nori. Series in a multi-series input may differ in length and in their exog columns: each series is forecast with its own columns, and adapters whose backend needs identical columns per batch (`supports_heterogeneous_covariates=False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral) are called once per group of series sharing the same columns, so the forecast of a series never depends on the exog of the others. ```python # Historical + future exog (must cover the forecast horizon) @@ -2487,7 +2489,7 @@ predictions = forecaster.predict_quantiles( # Columns: ['level', 'q_0.1', 'q_0.5', 'q_0.9'] ``` -For TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2, requested quantiles must be a subset of `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]`. TS-ICL accepts any level on a finer 0.01 grid in `[0.01, 0.99]` (e.g. `0.05`, `0.37`); off-grid levels raise a `ValueError`. Timestral returns 21 fixed levels: `0.01`, `0.05`, every multiple of `0.05` up to `0.95`, and `0.99`; any other level raises a `ValueError`. Chronos-2, TabICL, TabPFN-TS, TFC-T0 and Nori support any quantile in `(0, 1)`. +For TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto, requested quantiles must be a subset of `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]`. TS-ICL accepts any level on a finer 0.01 grid in `[0.01, 0.99]` (e.g. `0.05`, `0.37`); off-grid levels raise a `ValueError`. Timestral returns 21 fixed levels: `0.01`, `0.05`, every multiple of `0.05` up to `0.95`, and `0.99`; any other level raises a `ValueError`. Chronos-2, TabICL, TabPFN-TS, TFC-T0 and Nori support any quantile in `(0, 1)`. ## Choosing a Model @@ -2504,6 +2506,7 @@ For TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2, requested quantiles must be a s | `taharnbl/TS-ICL` (EDF Lab) | Yes | 4096 | Past & future covariates, fine-grained (0.01) quantile grid | | `mistralai/Timestral-*` (Mistral AI) | Yes | 4096 | Long context, past, future and categorical covariates (the 209M checkpoint is the most accurate) | | `NX-AI/TiRex-2` (NX-AI) | Yes | 2048 | Past & future covariates, series with different covariates in one call, horizons up to 320 steps | +| `ContinuousIntelligence/ci-proto` | Yes | None (all available history) | Past, known-future and categorical covariates | The adapter is resolved automatically from the `model_id` prefix — no need to import adapter classes directly. @@ -2609,20 +2612,20 @@ automatically to the last `context_length` observations. 1. **Expecting `fit()` to train the model**: it only stores context. The weights come from HuggingFace. 2. **Index without frequency**: call `series.asfreq('h')` (or similar) before `fit` — skforecast requires a frequency. -3. **Passing `exog` to TimesFM 2.5 / Moirai-2**: ignored with an `IgnoredArgumentWarning`. Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2 support exogenous variables. -4. **Requesting unsupported quantiles**: TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 are restricted to the nine deciles `0.1 … 0.9` ; TS-ICL is restricted to a 0.01 grid in `[0.01, 0.99]`; Timestral to its 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`). +3. **Passing `exog` to TimesFM 2.5 / Moirai-2**: ignored with an `IgnoredArgumentWarning`. Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto support exogenous variables. +4. **Requesting unsupported quantiles**: TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto are restricted to the nine deciles `0.1 … 0.9` ; TS-ICL is restricted to a 0.01 grid in `[0.01, 0.99]`; Timestral to its 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`). 5. **Large model downloads**: first call can be slow; consider using smaller variants (`*-small`) for experimentation. -6. **Forgetting to install the backend**: each foundation model requires its own library (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`). Install only the one(s) you need. `tfc-t0` needs its PyTorch runtime, the `torch` extra (`pip install "tfc-t0[torch]>=0.6"`). `tirex-2` requires Python >= 3.11. +6. **Forgetting to install the backend**: each foundation model requires its own library (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`, `continuousintelligence>=0.2.0`). Install only the one(s) you need. `tfc-t0` needs its PyTorch runtime, the `torch` extra (`pip install "tfc-t0[torch]>=0.6"`). `tirex-2` requires Python >= 3.11. 7. **Tuning a parameter that forces a model reload**: `model_id` and device/dtype arguments reload the model on every trial, and `context_length` does the same on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS. -8. **Assuming TimesFM 3.0 accepts categorical covariates**: it does not, and neither do Nori, T0, TS-ICL, and TiRex-2 (`ValueError`). Only Chronos-2 and Timestral accept them natively. `ForecasterFoundation` has no `transformer_exog`, so encode categoricals as numbers in `exog` before passing it to `fit` and `predict`. +8. **Assuming TimesFM 3.0 accepts categorical covariates**: it does not, and neither do Nori, T0, TS-ICL, and TiRex-2 (`ValueError`). Chronos-2, Timestral and ci-proto accept them natively. `ForecasterFoundation` has no `transformer_exog`, so encode categoricals as numbers in `exog` before passing it to `fit` and `predict`. 9. **Passing a future `exog` column that was not in the historical exog** (`fit` without that column, or `context` without `context_exog`): `ValueError` on every adapter. Pass the same columns to `fit` (or `context_exog`) and to `predict`. -10. **Predicting without `exog` after fitting with exog on TabICL, TabPFN-TS, T0 or Nori**: the historical columns are ignored (`IgnoredArgumentWarning`) and the forecast uses no covariates, as if the model had been fitted without exog. Only Chronos-2, TS-ICL, TimesFM 3.0, Timestral and TiRex-2 use them as past-only covariates. +10. **Predicting without `exog` after fitting with exog on TabICL, TabPFN-TS, T0 or Nori**: the historical columns are ignored (`IgnoredArgumentWarning`) and the forecast uses no covariates, as if the model had been fitted without exog. Only Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2 and ci-proto use them as past-only covariates. 11. **Timestral with a known covariate that is constant over the context and changes over the horizon** (a price that has not moved, or a 0/1 holiday or promotion indicator that is 0 over the whole context): the upper quantiles, and sometimes the median, can become very large ([mistralai/timestral#7](https://github.com/mistralai/timestral/issues/7)). The adapter issues a `FeatureOutOfRangeWarning` naming the series and columns; set the historical values of those columns to NaN. With known covariates, Timestral's forecast of the first steps also depends on `steps`, so do not compare backtests with a different `steps` step by step. 12. **Asking TiRex-2 for more than 320 steps**: `NX-AI/TiRex-2` forecasts at most 320 steps ahead (`future_len` of the checkpoint; 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). Use another adapter for longer horizons. ## References -See [references/adapter-parameters.md](references/adapter-parameters.md) for the per-adapter constructor parameters of `ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, and `TiRex2Adapter`. Each adapter section is self-contained; the last two sections (tunable parameters and model reload cost, common behavior) apply to every adapter, so read them too. +See [references/adapter-parameters.md](references/adapter-parameters.md) for the per-adapter constructor parameters of `ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, and `CIprotoAdapter`. Each adapter section is self-contained; the last two sections (tunable parameters and model reload cost, common behavior) apply to every adapter, so read them too. See the user guide [Foundation models with heterogeneous series](https://skforecast.org/latest/user_guides/foundation-forecasting-with-heterogeneous-series.html) for a worked example with series of different lengths, different exog columns and NaN, and for the table of what each backend requires and tolerates. @@ -2868,6 +2871,22 @@ For each series, columns present in its future `exog` become future covariates s **License**: Apache-2.0, so loading the weights raises no `LicenseWarning`. +## CIprotoAdapter + +**Model prefix:** `ContinuousIntelligence/ci-proto`. Install `continuousintelligence>=0.2.0`. + +**Context window:** up to 2 million observations. All supplied history is used by default. The backend automatically selects between variants tuned for shorter and longer contexts; 16,384 observations is the variant-selection threshold, not a history limit. + +| Parameter | Default | Meaning | +|-----------|---------|---------| +| `context_length` | `None` | All available history. Set a positive integer only to impose a retention limit. | +| `device` | `"auto"` | CUDA if available, otherwise CPU. Explicit `"cpu"` or `"cuda"` are supported. | +| `revision` | `None` | Hugging Face revision shared by weights and calibration; a full SHA pins them. | + +Past-only, known-future and categorical covariates are supported. Labels are encoded per series over history and horizon; missing labels remain NaN. Each series is forecast independently using its own history, covariates and dates. + +The published checkpoint returns deciles 0.1 through 0.9; point forecasts use the median. The adapter selects rows using the loaded quantile grid and validates the returned shape. + ## Tunable Parameters and Model Reload Cost The parameters that can be changed after construction (via `set_params`, and therefore searched with `bayesian_search_foundation`) are exactly the keys returned by each adapter's `get_params()`. Any other key raises `ValueError`. Note that `model` / `pipeline` / `module` are constructor-only and are **not** settable. @@ -2887,12 +2906,13 @@ Being accepted is not the same as being worth searching. Most adapters expose ru | NoriAdapter | `model_id`, `context_length`, `point_estimate`, `add_calendar_features`, `n_fourier_terms`, `nori_config` | `context_length`, `point_estimate`, `add_calendar_features`, `n_fourier_terms`, (`nori_config`) | `model_id`, `nori_config` | | TimestralAdapter | `model_id`, `context_length`, `device`, `predict_kwargs` | `context_length`, (`predict_kwargs`) | `model_id`, `device` | | TiRex2Adapter | `model_id`, `context_length`, `device`, `predict_kwargs` | `context_length`, (`predict_kwargs`) | `model_id`, `device` | +| CIprotoAdapter | `model_id`, `context_length`, `device`, `revision` | `context_length` | `model_id`, `device`, `revision` | Parameters in parentheses are backend passthrough dicts: they can hold quality-relevant settings but are awkward to search, so treat them as advanced. Two consequences that matter when tuning: -- **`context_length` is not uniformly cheap.** It reloads the model on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS; it is free on Chronos-2, TimesFM 3.0, T0, TS-ICL, Nori, Timestral and TiRex-2. +- **`context_length` is not uniformly cheap.** It reloads the model on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS; it is free on Chronos-2, TimesFM 3.0, T0, TS-ICL, Nori, Timestral, TiRex-2 and ci-proto. - **Reset only on change.** All foundation adapters compare the old and new values first (via the shared `set_params` helper), so re-sampling an identical value never triggers a reload. A reload happens only when a reload-triggering key is set to a genuinely new value, for example sampling a different `context_length` on TimesFM 2.5, Moirai-2, TabICL or TabPFN-TS. `model_id` forces a reload on every adapter except `TSICLAdapter`, where the checkpoint is selected by `checkpoint_version` instead. @@ -2905,19 +2925,19 @@ All adapters implement the same minimal interface: - `predict(steps, context, context_exog, exog, quantiles)`: returns a `dict[str, np.ndarray]` of shape `(steps, n_quantiles)` keyed by series name. - `get_params()` / `set_params(**kwargs)`: sklearn-style parameter access. - `allow_exog` / `supports_past_only_covariates` / `supports_heterogeneous_covariates` / `supports_nan_in_series`: class attributes read by `FoundationModel` to decide how exog and NaN are handled. When `supports_heterogeneous_covariates` is `False` (Chronos-2, TS-ICL, TabICL, TimesFM 3.0, T0, Timestral), `FoundationModel.predict` groups the series by their (past-only, future) exog columns and calls `adapter.predict` once per group; adapters never receive a batch with mixed covariate columns. When `supports_nan_in_series` is `False`, a context with NaN raises `ValueError` before the adapter is called (all current adapters accept NaN; Nori drops the NaN rows itself). When `max_series_per_call` is an integer (Timestral: 50, TiRex-2: 64), `FoundationModel.predict` splits each group into consecutive chunks of at most that many series and calls `adapter.predict` once per chunk, because the cost per series, and the memory, of the backend grow with the size of the batch; `None` (every other adapter) sends each group in one call. When `requires_equal_length_context` is `True` (T0, Timestral), `FoundationModel` left-pads the context and the historical exog of each call with NaN to the length of its longest series. -- `supports_categorical_covariates` / `requires_hf_auth` / `requires_provider_auth` / `weights_repo_id` / `weights_in_hf_cache` / `backend_package` / `default_model_id` / `SUPPORTED_QUANTILES`: descriptive class attributes. They are exposed, together with the ones above and the default `context_length`, through `get_model_info` and `list_adapters`. `supports_categorical_covariates` is `True` only for Chronos-2 and Timestral (non-numeric covariates are passed natively); `requires_hf_auth` is `True` when the weights are gated on the Hugging Face Hub (currently none of the supported models); `requires_provider_auth` is `True` only for TabPFN-TS (Prior Labs token and license acceptance, outside the Hugging Face Hub); `weights_repo_id` is the fixed Hugging Face repository of the backends that ignore `model_id` (`jingang/TabICL`, `Prior-Labs/tabpfn_3_5`, `taharnbl/TS-ICL`) and `None` when the weights are downloaded from `model_id`; `weights_in_hf_cache` is `False` only for TabPFN-TS, which keeps the weights in its own cache directory; `SUPPORTED_QUANTILES` is `None` when any level in `(0, 1)` is accepted. +- `supports_categorical_covariates` / `requires_hf_auth` / `requires_provider_auth` / `weights_repo_id` / `weights_in_hf_cache` / `backend_package` / `default_model_id` / `SUPPORTED_QUANTILES`: descriptive class attributes. They are exposed, together with the ones above and the default `context_length`, through `get_model_info` and `list_adapters`. `supports_categorical_covariates` is `True` for Chronos-2, Timestral and ci-proto (non-numeric covariates are passed natively); `requires_hf_auth` is `True` when the weights are gated on the Hugging Face Hub (currently none of the supported models); `requires_provider_auth` is `True` only for TabPFN-TS (Prior Labs token and license acceptance, outside the Hugging Face Hub); `weights_repo_id` is the fixed Hugging Face repository of the backends that ignore `model_id` (`jingang/TabICL`, `Prior-Labs/tabpfn_3_5`, `taharnbl/TS-ICL`) and `None` when the weights are downloaded from `model_id`; `weights_in_hf_cache` is `False` only for TabPFN-TS, which keeps the weights in its own cache directory; `SUPPORTED_QUANTILES` is `None` when any level in `(0, 1)` is accepted. ### Exog column validation at predict time `FoundationModel.predict` (and therefore `ForecasterFoundation.predict`, `predict_interval`, `predict_quantiles`) validates, per series, the columns of the future `exog` against the historical exog used as context (the one stored by `fit`, or `context_exog` when `context` is given). The check is skipped on the internal backtesting path, where both come from the same DataFrame. On every path, before the adapter is called, the historical exog of each series is reindexed to the index of its context and the future `exog` to the forecast horizon; missing timestamps are filled with NaN and reported with a `MissingValuesWarning`. No columns are ever added: a series only carries its own exog columns. For adapters with `supports_past_only_covariates=False`, the historical columns without future values are removed before the adapter is called, also on the backtesting path, so the forecast is the same as without those columns (the backends of TabICL and TabPFN-TS do not discard them on their own). -| Situation (per series) | Adapters with `supports_past_only_covariates=True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2) | Adapters with `supports_past_only_covariates=False` (TabICL, TabPFN-TS, T0, Nori) | +| Situation (per series) | Adapters with `supports_past_only_covariates=True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto) | Adapters with `supports_past_only_covariates=False` (TabICL, TabPFN-TS, T0, Nori) | |---------------------------------------------------------|---------------------------------------------------------------|---------------------------------------------------------------| | Future `exog` column with no historical values | `ValueError` | `ValueError` | | Historical column with no future values (`exog=None` or a subset of columns) | Used as a past-only covariate, no warning | Removed before calling the adapter, `IgnoredArgumentWarning` listing the columns and series | | Same columns on both sides (any order) | OK | OK | -Backend libraries (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`) are imported **lazily** inside the adapter method that needs them, so only the backend for the adapter you actually use needs to be installed. +Backend libraries (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`, `continuousintelligence>=0.2.0`) are imported **lazily** inside the adapter method that needs them, so only the backend for the adapter you actually use needs to be installed. ================================================================================ # SKILL: baseline-forecasting @@ -4856,7 +4876,7 @@ predictions = forecaster.predict_quantiles( ) ``` -TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 restrict quantiles to `[0.1, 0.2, …, 0.9]`; TS-ICL restricts them to a 0.01 grid in `[0.01, 0.99]`; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`); Chronos-2, TabICL, TabPFN-TS, TFC-T0, and Nori accept any quantile in `(0, 1)`. See the `foundation-forecasting` skill for details. +TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto restrict quantiles to `[0.1, 0.2, …, 0.9]`; TS-ICL restricts them to a 0.01 grid in `[0.01, 0.99]`; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`); Chronos-2, TabICL, TabPFN-TS, TFC-T0, and Nori accept any quantile in `(0, 1)`. See the `foundation-forecasting` skill for details. ## During Backtesting @@ -6799,7 +6819,7 @@ Use this when you need exact parameter names, types, defaults, or method signatu - `ForecasterStats` — statistical models (ARIMA, ETS, SARIMAX, ARAR) - `ForecasterEquivalentDate` — baseline using past offsets - `ForecasterRnn` — deep learning (RNN/LSTM/GRU) -- `ForecasterFoundation` — zero-shot with foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2) +- `ForecasterFoundation` — zero-shot with foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, ci-proto) - `FoundationModel` — low-level foundation model wrapper used by `ForecasterFoundation` - `get_model_info` / `list_adapters`: capabilities of a foundation model (exog, quantiles, context length, backend, license) without installing its backend @@ -7012,7 +7032,7 @@ FoundationModel( # torch_dtype : object (Chronos-2, T0) # cross_learning : bool (Chronos-2 only) # max_horizon, forecast_config_kwargs (TimesFM 2.5 only) - # predict_kwargs (Chronos-2, TimesFM 3.0, Timestral, TiRex-2) + # predict_kwargs (Chronos-2, TimesFM 3.0, Timestral, TiRex-2, ci-proto) # point_estimate, tabicl_config, temporal_features, show_progress (TabICL) # mode, point_estimate, tabpfn_model_config, temporal_features, show_progress (TabPFN-TS) # (T0 uses only context_length, device_map, torch_dtype) diff --git a/llms.txt b/llms.txt index 7aa1164de..4221ea783 100644 --- a/llms.txt +++ b/llms.txt @@ -19,7 +19,7 @@ Skforecast supports recursive and direct multi-step forecasting strategies, glob - [ForecasterDirectMultiVariate](https://skforecast.org/latest/api/forecasterdirectmultivariate): Multivariate forecasting using multiple series as input features - [ForecasterRnn](https://skforecast.org/latest/api/forecasterrnn): Deep learning forecasting with RNN/LSTM architectures - [ForecasterStats](https://skforecast.org/latest/api/forecasterstats): Statistical models (ARIMA, SARIMAX, ETS, ARAR) with sklearn-compatible interface -- [ForecasterFoundation](https://skforecast.org/latest/api/forecasterfoundation): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +- [ForecasterFoundation](https://skforecast.org/latest/api/forecasterfoundation): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) - [ForecasterRecursiveClassifier](https://skforecast.org/latest/api/forecasterrecursiveclassifier): Classification-based forecasting for categorical time series - [ForecasterEquivalentDate](https://skforecast.org/latest/api/forecasterequivalentdate): Baseline forecaster using equivalent past dates @@ -63,7 +63,7 @@ Skforecast supports recursive and direct multi-step forecasting strategies, glob ## Foundation Models -- [Forecasting with foundation models](https://skforecast.org/latest/user_guides/foundation-forecasting-models.html): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2). Evaluate with `backtesting_foundation` and tune inference-time parameters such as `context_length` with `bayesian_search_foundation` +- [Forecasting with foundation models](https://skforecast.org/latest/user_guides/foundation-forecasting-models.html): Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto). Evaluate with `backtesting_foundation` and tune inference-time parameters such as `context_length` with `bayesian_search_foundation` - [Foundation models with heterogeneous series](https://skforecast.org/latest/user_guides/foundation-forecasting-with-heterogeneous-series.html): Series with different lengths, different exogenous variables and missing values in a single ForecasterFoundation: per-series alignment, grouping by exog columns and the predict and backtesting rules of each backend ## Deep Learning diff --git a/mkdocs.yml b/mkdocs.yml index fac69c1c2..c4c7e6b54 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -55,6 +55,7 @@ nav: - Dependent multivariate series forecasting: user_guides/dependent-multi-series-multivariate-forecasting.ipynb - Foundation Models: - Forecasting with foundation models: user_guides/foundation-forecasting-models.ipynb + - Forecasting with ci-proto: user_guides/foundation-ci-proto.md - Heterogeneous series with different lengths, exogenous variables and missing values: user_guides/foundation-forecasting-with-heterogeneous-series.ipynb - Statistical Models: - ForecasterStats: user_guides/forecasting-statistical-models.ipynb diff --git a/skforecast/foundation/_adapters.py b/skforecast/foundation/_adapters.py index 65c418946..d97b4f28b 100644 --- a/skforecast/foundation/_adapters.py +++ b/skforecast/foundation/_adapters.py @@ -6547,6 +6547,265 @@ def _load_model(self) -> None: ) +class CIprotoAdapter(_AdapterBase): + """ + Adapter for Continuous Intelligence ci-proto. + + Parameters + ---------- + model_id : str + Hugging Face model ID starting with `"ContinuousIntelligence/ci-proto"`. + model : object, default None + Pre-loaded `continuousintelligence.Forecaster`, intended for testing. + Otherwise the model is loaded on the first prediction. + context_length : int, None, default None + Optional limit on retained historical observations. By default all + available history is passed to ci-proto, which automatically selects + its short-context or long-context variant. The published model supports + context windows of up to 2 million observations. + device : str, default 'auto' + `"auto"` selects CUDA when available and CPU otherwise. Explicit values + are `"cpu"` and `"cuda"`, the devices supported by the backend. + revision : str, default None + Hugging Face revision passed to `continuousintelligence.load_model`. + Use a full commit SHA for reproducible weights and calibration. + + Notes + ----- + The optional `continuousintelligence>=0.2.0` backend supplies the released + preprocessing, calibration and long-horizon forecasting. Point forecasts + use its median; quantiles are selected from the loaded model's own grid. + + Each target is forecast independently with its own history and covariates. + + Dated series retain their own history and future dates as epoch nanoseconds, + used by the backend for calendar features. RangeIndex inputs do not receive + artificial dates. Categorical covariates are encoded per series using + consistent history/future codes; missing labels remain NaN. + + References + ---------- + .. [1] https://github.com/continuousintelligence/ci + .. [2] https://huggingface.co/ContinuousIntelligence/ci-proto + + """ + + SUPPORTED_QUANTILES: list[float] = [ + 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 + ] + allow_exog: bool = True + supports_past_only_covariates: bool = True + supports_categorical_covariates: bool = True + supports_heterogeneous_covariates: bool = True + requires_equal_length_context: bool = False + max_series_per_call: int | None = None + supports_nan_in_series: bool = True + requires_hf_auth: bool = False + requires_provider_auth: bool = False + weights_repo_id: str | None = None + weights_in_hf_cache: bool = True + backend_package: str = "continuousintelligence>=0.2.0" + default_model_id: str = "ContinuousIntelligence/ci-proto" + _MODEL_ID_PREFIX: str = "ContinuousIntelligence/ci-proto" + + def __init__( + self, + model_id: str, + *, + model: Any | None = None, + context_length: int | None = None, + device: str = "auto", + revision: str | None = None, + ) -> None: + """Initialise the adapter without importing or loading the backend.""" + _validate_model_id_prefix(model_id, self._MODEL_ID_PREFIX, type(self).__name__) + if context_length is not None: + _validate_positive_int("context_length", context_length) + self._validate_device(device) + self.model_id = model_id + self._model = model + self.context_length = context_length + self.device = device + self.revision = revision + self.context_ = None + self.context_exog_ = None + self.is_fitted = False + + @staticmethod + def _validate_device(device: str) -> None: + """Validate the device names accepted by the ci-proto loader.""" + if device not in ("auto", "cpu", "cuda"): + raise ValueError( + "CIprotoAdapter `device` must be 'auto', 'cpu' or 'cuda'. " + f"Got {device!r}." + ) + + def get_params(self) -> dict: + """Return constructor parameters, excluding the injected backend.""" + return { + "model_id": self.model_id, + "context_length": self.context_length, + "device": self.device, + "revision": self.revision, + } + + def set_params(self, **params) -> CIprotoAdapter: + """Set parameters and reload when the checkpoint or device changes.""" + 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 candidate_params.get("context_length") is not None: + _validate_positive_int( + "context_length", candidate_params["context_length"] + ) + if "device" in candidate_params: + self._validate_device(candidate_params["device"]) + return candidate_params + + return _apply_set_params( + self, + params, + validate=validate, + resets=( + ( + {"model_id", "device", "revision"}, + lambda: setattr(self, "_model", None), + ), + ), + ) + + @staticmethod + def _encode_covariate(values: pd.Series) -> tuple[np.ndarray, bool]: + """Convert numeric values or categorical labels, retaining missing data.""" + if pd.api.types.is_complex_dtype(values.dtype): + raise ValueError("CIprotoAdapter covariates must contain real values.") + categorical = isinstance(values.dtype, pd.CategoricalDtype) or not ( + pd.api.types.is_numeric_dtype(values.dtype) + or pd.api.types.is_bool_dtype(values.dtype) + ) + if categorical: + codes, _ = pd.factorize(values, use_na_sentinel=True) + array = np.where(codes < 0, np.nan, codes).astype(np.float32) + else: + array = values.to_numpy(dtype=np.float32, na_value=np.nan) + return array, categorical + + def _build_inputs( + self, + steps: int, + context: pd.Series, + context_exog: pd.DataFrame | pd.Series | None, + exog: pd.DataFrame | pd.Series | None, + ) -> dict[str, Any]: + """Translate one independent series without padding it to other histories.""" + import torch + + past_cols, future_cols = get_exog_signature(context_exog, exog) + ctx = ( + context_exog.to_frame() + if isinstance(context_exog, pd.Series) else context_exog + ) + fut = exog.to_frame() if isinstance(exog, pd.Series) else exog + past, future = [], [] + categorical_past, categorical_future = [], [] + for col_idx, col in enumerate(past_cols): + values, categorical = self._encode_covariate(ctx[col]) + past.append(values) + if categorical: + categorical_past.append(col_idx) + for col_idx, col in enumerate(future_cols): + combined = pd.concat([ctx[col], fut[col]], ignore_index=True) + if any( + isinstance(frame[col].dtype, pd.CategoricalDtype) + for frame in (ctx, fut) + ): + combined = combined.astype("category") + values, categorical = self._encode_covariate(combined) + future.append(values) + if categorical: + categorical_future.append(col_idx) + + dated = isinstance(context.index, pd.DatetimeIndex) + dates = ( + context.index.append(expand_index(context.index, steps)) + if dated else None + ) + return { + "history": torch.from_numpy( + context.to_numpy(dtype=np.float32, na_value=np.nan)[None, :] + ), + "past_covariates": torch.from_numpy(np.stack(past)) if past else None, + "future_covariates": ( + torch.from_numpy(np.stack(future)) if future else None + ), + "categorical_past": tuple(categorical_past), + "categorical_future": tuple(categorical_future), + "timestamps": ( + torch.from_numpy(dates.as_unit("ns").asi8) if dated else None + ), + "freq": context.index.freqstr if dated else None, + } + + 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]: + """Forecast independent targets and return `(steps, n_quantiles)` per series.""" + requested = _validate_supported_quantiles( + quantiles, self.SUPPORTED_QUANTILES, "ci-proto" + ) + self._load_model() + grid = _tensor_to_numpy(self._model.quantiles) + if grid.ndim != 1: + raise ValueError("ci-proto must expose a one-dimensional quantile grid.") + indices = _match_quantile_indices( + grid.tolist(), requested if requested is not None else [0.5] + ) + predictions = {} + expected_shape = (1, len(grid), steps) + for name, series in context.items(): + inputs = self._build_inputs( + steps, + series, + (context_exog or {}).get(name), + (exog or {}).get(name), + ) + forecasts = _tensor_to_numpy( + self._model.forecast(horizon=steps, **inputs) + ) + if forecasts.shape != expected_shape: + raise ValueError( + "ci-proto returned an unexpected forecast shape for " + f"{name!r}: {forecasts.shape!r}. Expected {expected_shape}." + ) + predictions[name] = forecasts[0, indices, :].T + + return predictions + + def _load_model(self) -> None: + """Lazily load the weights and calibration from the same Hub revision.""" + if self._model is not None: + return + try: + from continuousintelligence import load_model + except ImportError as exc: + raise ImportError( + f"{self.backend_package} is required for {type(self).__name__}. " + f'Install it with `pip install "{self.backend_package}"`.' + ) from exc + self._model = load_model( + self.model_id, device=self.device, revision=self.revision + ) + + _ADAPTER_REGISTRY: dict[str, type] = { # Only Chronos-2 checkpoints: Chronos and Chronos-Bolt pipelines take a # different input format and do not accept `cross_learning`. @@ -6555,6 +6814,7 @@ def _load_model(self) -> None: "google/timesfm-2.5": TimesFM25Adapter, "google/timesfm-3.0": TimesFM3Adapter, "NX-AI/TiRex-2": TiRex2Adapter, + "ContinuousIntelligence/ci-proto": CIprotoAdapter, # Only Moirai-2 checkpoints: the configs of Moirai 1.x and Moirai-MoE lack # arguments required by `Moirai2Module` (`patch_size`, `d_ff`). "Salesforce/moirai-2": MoiraiAdapter, diff --git a/skforecast/foundation/_forecaster_foundation.py b/skforecast/foundation/_forecaster_foundation.py index 52b5e8387..11ea87bae 100644 --- a/skforecast/foundation/_forecaster_foundation.py +++ b/skforecast/foundation/_forecaster_foundation.py @@ -67,10 +67,10 @@ class ForecasterFoundation: Alias for `context_`. last_window_exog_ : dict Alias for `context_exog_`. - context_length : int - Maximum number of historical observations used as context. Delegates - to `estimator.context_length`. - window_size : int + context_length : int, None + Maximum number of historical observations used as context, or `None` + for all available history. Delegates to `estimator.context_length`. + window_size : int, None Desired number of historical observations used as context by the model. Always equals `context_length`. allow_exog : bool @@ -204,14 +204,15 @@ def __init__( } @property - def context_length(self) -> int: + def context_length(self) -> int | None: """ Maximum number of historical observations used as context. Returns ------- - context_length : int - Maximum context length. Delegates to `estimator.context_length`. + context_length : int, None + Maximum context length, or `None` for all available history. + Delegates to `estimator.context_length`. """ return self.estimator.context_length @@ -228,15 +229,16 @@ def model_id(self) -> str: return self.estimator.model_id @property - def window_size(self) -> int: + def window_size(self) -> int | None: """ Desired number of historical observations used as context by the model. Always equals `context_length`. Returns ------- - window_size : int - Context window size. Delegates to `estimator.context_length`. + window_size : int, None + Context window size, or `None` for all available history. + Delegates to `estimator.context_length`. """ return self.estimator.context_length diff --git a/skforecast/foundation/_foundation_model.py b/skforecast/foundation/_foundation_model.py index f0ad137a6..0162b8628 100644 --- a/skforecast/foundation/_foundation_model.py +++ b/skforecast/foundation/_foundation_model.py @@ -41,7 +41,7 @@ class FoundationModel: Currently supports Amazon Chronos-2, Google TimesFM 2.5 and 3.0, Salesforce Moirai-2, TabICLv2, TabPFN-TS, TFC-T0, Synthefy Nori, EDF Lab TS-ICL, - Mistral AI Timestral and NX-AI TiRex-2. + Mistral AI Timestral, NX-AI TiRex-2 and Continuous Intelligence ci-proto. For full skforecast ecosystem integration (backtesting, model selection, etc.) use `ForecasterFoundation` instead. @@ -102,6 +102,10 @@ class FoundationModel: - `'NX-AI/TiRex-2'` + Continuous Intelligence ci-proto (supports `exog`): + + - `'ContinuousIntelligence/ci-proto'` + See References for links to model documentation and model cards. **kwargs : Additional keyword arguments forwarded to the underlying adapter. @@ -151,6 +155,12 @@ class FoundationModel: - **NX-AI TiRex-2** (`TiRex2Adapter`): `context_length` (int, default 2048), `device` (str, default `'auto'`), `predict_kwargs` (dict, default None). + - **Continuous Intelligence ci-proto** (`CIprotoAdapter`): + `context_length` (int or None, default None, retains all history), + `device` (str, default `'auto'`, CUDA or CPU), `revision` (str, + default None). The backend automatically selects the short-context + or long-context variant; the model supports up to 2 million + context observations. Attributes ---------- @@ -169,9 +179,9 @@ class FoundationModel: 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`. + context_length : int, None + Maximum number of historical observations used as context. `None` + retains all available history. Mirrors `adapter.context_length`. allow_exog : bool Whether the underlying adapter supports exogenous variables. supports_past_only_covariates : bool @@ -236,7 +246,7 @@ class FoundationModel: - `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, Timestral, TiRex-2. + Moirai, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto. - 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 @@ -372,14 +382,15 @@ def context_exog_(self) -> dict[str, pd.DataFrame] | None: return self.adapter.context_exog_ @property - def context_length(self) -> int: + def context_length(self) -> int | None: """ Maximum number of historical observations used as context. Returns ------- - context_length : int - Maximum context length. Mirrors `adapter.context_length`. + context_length : int, None + Maximum context length. `None` retains all available history. + Mirrors `adapter.context_length`. """ return self.adapter.context_length @@ -407,7 +418,7 @@ def supports_past_only_covariates(self) -> bool: 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, Timestral, TiRex-2). `False` + (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto). `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, @@ -425,7 +436,7 @@ def supports_heterogeneous_covariates(self) -> bool: ------- supports_heterogeneous_covariates : bool `True` if the backend accepts, in one call, series whose exog - columns differ (TabPFN-TS, Nori, TiRex-2, and the adapters that + columns differ (TabPFN-TS, Nori, TiRex-2, ci-proto, 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, TFC-T0, Timestral); in that case `predict` groups the series by their @@ -564,14 +575,15 @@ def _check_preprocess_context( ------- context : dict Per-series dict of pandas Series, trimmed to the last - `context_length` observations. + `context_length` observations, or all history when it is `None`. series_indexes : dict Index of each series before trimming. series_names_in_ : list Names of the series. context_exog : dict or None Per-series dict of exogenous DataFrames trimmed to the last - `context_length` observations. `None` if `exog` is `None`. + `context_length` observations, or all history when it is `None`. + `None` if `exog` is `None`. exog_names_in_ : list or None Names of the exogenous variables. `None` if `exog` is `None`. @@ -601,14 +613,17 @@ def _check_preprocess_context( trim_series_nan = False, ) + context_start = ( + -self.context_length if self.context_length is not None else None + ) context = { - series_name: series_values.iloc[-self.context_length :] + series_name: series_values.iloc[context_start :] for series_name, series_values in series_dict.items() } if exog is not None: context_exog = { series_name: ( - series_exog.iloc[-self.context_length :] + series_exog.iloc[context_start :] if series_exog is not None else None ) diff --git a/skforecast/foundation/_model_info.py b/skforecast/foundation/_model_info.py index 50b10670f..d61f23b80 100644 --- a/skforecast/foundation/_model_info.py +++ b/skforecast/foundation/_model_info.py @@ -44,8 +44,9 @@ class FoundationModelInfo: Model ID prefixes routed to `adapter`. default_model_id : str Model ID used by default for `adapter`. - default_context_length : int + default_context_length : int, None Default maximum number of historical observations used as context. + `None` retains all available history. backend_package : str Package that provides the backend, as passed to `pip install`. allow_exog : bool @@ -107,7 +108,7 @@ class FoundationModelInfo: adapter: str model_id_prefixes: tuple[str, ...] default_model_id: str - default_context_length: int + default_context_length: int | None backend_package: str allow_exog: bool supports_past_only_covariates: bool @@ -254,8 +255,13 @@ def list_adapters( ] if as_frame: + context_lengths = [adapter.default_context_length for adapter in adapters] adapters = pd.DataFrame( [asdict(adapter) for adapter in adapters] ).set_index("adapter") + if any(length is None for length in context_lengths): + adapters["default_context_length"] = pd.Series( + context_lengths, index=adapters.index, dtype=object + ) return adapters diff --git a/skforecast/foundation/_utils.py b/skforecast/foundation/_utils.py index b17028cfe..366dd6f5a 100644 --- a/skforecast/foundation/_utils.py +++ b/skforecast/foundation/_utils.py @@ -268,6 +268,12 @@ def _tensor_to_numpy(values: Any) -> np.ndarray: # commercial-use restriction, it does not mean the license has been confirmed # permissive. _MODEL_LICENSES: dict[str, tuple[str, str | None, bool, str | None]] = { + "ContinuousIntelligence/ci-proto": ( + "ci-proto-licence", + "https://github.com/continuousintelligence/ci/blob/main/LICENCE", + False, + None, + ), "amazon/chronos-2": ( "Apache-2.0", None, diff --git a/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py b/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py new file mode 100644 index 000000000..2bda98347 --- /dev/null +++ b/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py @@ -0,0 +1,451 @@ +# Unit tests for the ci-proto adapter. +# ============================================================================== +import builtins +import sys +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest +from sklearn.base import clone + +from skforecast.foundation import FoundationModel, ForecasterFoundation, get_model_info +from skforecast.foundation._adapters import CIprotoAdapter + +torch = pytest.importorskip("torch") +MODEL_ID = "ContinuousIntelligence/ci-proto" + + +class FakeCIprotoModel: + """Mirror the published Forecaster signature and record per-series inputs.""" + + def __init__(self, quantiles=None): + self.quantiles = torch.tensor( + CIprotoAdapter.SUPPORTED_QUANTILES if quantiles is None else quantiles + ) + self.calls = [] + + def forecast( + self, + history, + horizon=320, + *, + past_covariates=None, + future_covariates=None, + categorical_past=(), + categorical_future=(), + timestamps=None, + freq=None, + series_ids=None, + static_features=None, + ): + self.calls.append( + { + "history": history.clone(), + "horizon": horizon, + "past_covariates": past_covariates, + "future_covariates": future_covariates, + "categorical_past": categorical_past, + "categorical_future": categorical_future, + "timestamps": timestamps, + "freq": freq, + "series_ids": series_ids, + } + ) + return ( + history[:, -1, None, None] + + self.quantiles[None, :, None] + + torch.arange(horizon)[None, None, :] + ) + + +def make_context(length=4, end="2026-01-04", freq="D"): + """A regular target with a meaningful forecast origin.""" + return pd.Series( + np.arange(1, length + 1, dtype=float), + index=pd.date_range(end=end, periods=length, freq=freq), + name="sales", + ) + + +def test_defaults_and_clone_without_backend(): + model = FoundationModel(MODEL_ID, revision="abc123") + model.fit(make_context()) + cloned = clone(model) + assert cloned.get_params() == model.get_params() + assert cloned.adapter._model is None + assert not cloned.is_fitted + assert model.adapter.context_length is None + assert model.adapter.requires_equal_length_context is False + assert model.adapter.max_series_per_call is None + + +@pytest.mark.parametrize("device", ["mps", "cuda:0", None, 1]) +def test_invalid_device(device): + with pytest.raises(ValueError, match="device.*must be"): + CIprotoAdapter(MODEL_ID, device=device) + + +@pytest.mark.parametrize("length", [0, -1, "12", 1.5]) +def test_invalid_context_length(length): + with pytest.raises(ValueError, match="positive integer"): + CIprotoAdapter(MODEL_ID, context_length=length) + + +@pytest.mark.parametrize( + "parameter,value", + [ + ("model_id", MODEL_ID + "-alternative"), + ("device", "cpu"), + ("revision", "pinned"), + ], +) +def test_set_params_resets_backend(parameter, value): + adapter = CIprotoAdapter(MODEL_ID, model=FakeCIprotoModel()) + assert adapter.set_params(**{parameter: value}) is adapter + assert adapter._model is None + + +def test_set_params_is_atomic_and_context_does_not_reload(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + adapter.set_params(context_length=20000) + assert adapter._model is backend + with pytest.raises(ValueError, match="device"): + adapter.set_params(context_length=42, device="mps") + assert adapter.context_length == 20000 + assert adapter._model is backend + + +def test_backend_load_is_lazy_cached_and_revision_pinned(monkeypatch): + calls = [] + backend = FakeCIprotoModel() + + def load_model(checkpoint, *, device, revision): + calls.append((checkpoint, device, revision)) + return backend + + monkeypatch.setitem( + sys.modules, "continuousintelligence", SimpleNamespace(load_model=load_model) + ) + adapter = CIprotoAdapter(MODEL_ID, device="cpu", revision="abc123") + adapter.fit({"sales": make_context()}, None) + assert calls == [] + for _ in range(2): + adapter.predict(2, adapter.context_, None, None, None) + assert calls == [(MODEL_ID, "cpu", "abc123")] + + +def test_missing_backend_has_install_hint(monkeypatch): + original = builtins.__import__ + + def importing(name, *args, **kwargs): + if name == "continuousintelligence": + raise ImportError("backend not installed") + return original(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", importing) + adapter = CIprotoAdapter(MODEL_ID) + with pytest.raises( + ImportError, match='pip install "continuousintelligence>=0.2.0"' + ): + adapter.predict(2, {"sales": make_context()}, None, None, None) + + +@pytest.mark.parametrize("quantiles", [None, [0.9, 0.1, 0.5]]) +def test_quantile_selection_uses_loaded_grid(quantiles): + backend = FakeCIprotoModel([0.9, 0.5, 0.1]) + adapter = CIprotoAdapter(MODEL_ID, model=backend) + prediction = adapter.predict(2, {"sales": make_context()}, None, None, quantiles) + expected = np.array([0.5] if quantiles is None else quantiles) + np.testing.assert_allclose(prediction["sales"], 4 + expected[None, :] + [[0], [1]]) + + +def test_unsupported_quantiles_fail_before_loading(): + adapter = CIprotoAdapter(MODEL_ID) + with pytest.raises(ValueError, match="only supports quantile"): + adapter.predict(2, {"sales": make_context()}, None, None, [0.05]) + assert adapter._model is None + + +def test_missing_checkpoint_quantile_fails_before_forecasting(): + backend = FakeCIprotoModel([0.1, 0.9]) + adapter = CIprotoAdapter(MODEL_ID, model=backend) + with pytest.raises(ValueError, match="Quantile 0.5 not found"): + adapter.predict(2, {"sales": make_context()}, None, None, None) + assert backend.calls == [] + + +@pytest.mark.parametrize("shape", [(1, 9, 1), (2, 9, 2), (1, 2, 9), (9, 2)]) +def test_malformed_backend_output(shape): + backend = FakeCIprotoModel() + backend.forecast = lambda **kwargs: torch.zeros(shape) + adapter = CIprotoAdapter(MODEL_ID, model=backend) + with pytest.raises(ValueError, match="unexpected forecast shape"): + adapter.predict(2, {"sales": make_context()}, None, None, None) + + +def test_dated_unequal_contexts_keep_their_own_lengths_and_origins(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + context = {"later": make_context(), "earlier": make_context(2, "2026-01-02")} + context["later"].iloc[1] = np.nan + before = {name: series.copy() for name, series in context.items()} + adapter.predict(3, context, None, None, None) + later, earlier = backend.calls + assert later["history"].dtype == torch.float32 + assert later["history"].shape == (1, 4) + assert earlier["history"].shape == (1, 2) + np.testing.assert_allclose(earlier["history"][0], [1, 2]) + assert torch.isnan(later["history"][0, 1]) + assert later["freq"] == earlier["freq"] == "D" + assert later["series_ids"] is earlier["series_ids"] is None + expected = pd.date_range("2026-01-01", periods=5, freq="D").as_unit("ns").asi8 + np.testing.assert_array_equal(earlier["timestamps"], expected) + for name in context: + pd.testing.assert_series_equal(context[name], before[name]) + + +def test_range_index_does_not_fabricate_calendar_dates(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + adapter.predict(2, {"sales": pd.Series([1.0, 2.0])}, None, None, None) + assert backend.calls[0]["timestamps"] is None + assert backend.calls[0]["freq"] is None + + +def test_past_and_future_covariates_keep_each_series_history(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + context = {"long": make_context(), "short": make_context(2)} + historical, future = {}, {} + for name, series in context.items(): + historical[name] = pd.DataFrame( + { + "past": pd.array(range(len(series)), dtype="Int64"), + "known": pd.array([True] * len(series), dtype="boolean"), + }, + index=series.index, + ) + future[name] = pd.DataFrame({"known": [False, True]}) + historical["short"].iloc[0, 0] = pd.NA + adapter.predict(2, context, historical, future, None) + long, short = backend.calls + assert long["past_covariates"].shape == (1, 4) + np.testing.assert_allclose(short["past_covariates"][0], [np.nan, 1]) + np.testing.assert_allclose(short["future_covariates"][0], [1, 1, 0, 1]) + assert short["categorical_past"] == () + assert short["categorical_future"] == () + + +def test_categorical_codes_match_history_and_future_and_keep_missing_labels(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + series = make_context() + historical = { + "sales": pd.DataFrame( + { + "past": ["a", None, "a", "b"], + "known": ["red", "blue", "red", None], + }, + index=series.index, + ) + } + future = {"sales": pd.DataFrame({"known": ["blue", "new"]})} + adapter.predict(2, {"sales": series}, historical, future, None) + call = backend.calls[0] + assert call["categorical_past"] == (0,) + assert call["categorical_future"] == (0,) + np.testing.assert_allclose(call["past_covariates"][0], [0, np.nan, 0, 1]) + np.testing.assert_allclose(call["future_covariates"][0], [0, 1, 0, np.nan, 1, 2]) + + +def test_complex_covariates_are_rejected(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + series = make_context() + historical = {"sales": pd.DataFrame({"x": [1j] * 4}, index=series.index)} + with pytest.raises(ValueError, match="real values"): + adapter.predict(2, {"sales": series}, historical, None, None) + + +@pytest.mark.parametrize( + "history_values,future_values,expected", + [ + ([1, 2, 1, 2], [2, 3], [0, 1, 0, 1, 1, 2]), + ([False, True, False, True], [True, True], [0, 1, 0, 1, 1, 1]), + ], +) +def test_categorical_dtype_survives_different_history_and_future_categories( + history_values, future_values, expected +): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + series = make_context() + historical = { + "sales": pd.DataFrame( + {"known": pd.Categorical(history_values)}, index=series.index + ) + } + future = {"sales": pd.DataFrame({"known": pd.Categorical(future_values)})} + adapter.predict(2, {"sales": series}, historical, future, None) + assert backend.calls[0]["categorical_future"] == (0,) + np.testing.assert_allclose(backend.calls[0]["future_covariates"][0], expected) + + +def test_FoundationModel_sends_one_target_per_backend_call(): + backend = FakeCIprotoModel() + model = FoundationModel(MODEL_ID, model=backend) + series = {f"s{i}": make_context() for i in range(70)} + model.fit(series) + predictions = model.predict(2) + assert len(backend.calls) == 70 + assert all(call["history"].shape == (1, 4) for call in backend.calls) + assert all(call["series_ids"] is None for call in backend.calls) + assert len(predictions) == 140 + + +def test_heterogeneous_covariates_are_forwarded_per_series_without_union_columns(): + backend = FakeCIprotoModel() + model = FoundationModel(MODEL_ID, model=backend) + series = {name: make_context() for name in ["a", "b", "bare"]} + historical = { + "a": pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0]}, index=series["a"].index), + "b": pd.DataFrame({"other": [5.0, 6.0, 7.0, 8.0]}, index=series["b"].index), + } + model.fit(series, exog=historical) + model.predict(2) + assert len(backend.calls) == 3 + np.testing.assert_allclose(backend.calls[0]["past_covariates"], [[1, 2, 3, 4]]) + np.testing.assert_allclose(backend.calls[1]["past_covariates"], [[5, 6, 7, 8]]) + assert backend.calls[2]["past_covariates"] is None + + +def test_predict_forwards_requested_horizon(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + prediction = adapter.predict(1000, {"sales": make_context()}, None, None, None) + assert prediction["sales"].shape == (1000, 1) + assert backend.calls[0]["horizon"] == 1000 + + +def test_metadata_describes_the_published_model(): + info = get_model_info(MODEL_ID) + assert info.adapter == "CIprotoAdapter" + assert info.backend_package == "continuousintelligence>=0.2.0" + assert info.default_context_length is None + assert info.supports_categorical_covariates + assert info.supports_past_only_covariates + assert info.supports_heterogeneous_covariates + assert info.license == "ci-proto-licence" + assert not info.commercial_use_restricted + + +@pytest.mark.parametrize("method", ["predict", "predict_interval", "predict_quantiles"]) +def test_forecaster_public_api_with_covariates(monkeypatch, method): + """Verify clone, exog alignment, output dates and native uncertainty together.""" + backend = FakeCIprotoModel() + monkeypatch.setitem( + sys.modules, + "continuousintelligence", + SimpleNamespace(load_model=lambda *args, **kwargs: backend), + ) + forecaster = ForecasterFoundation(estimator=FoundationModel(MODEL_ID)) + series = make_context() + historical = pd.DataFrame( + {"past": [2.0, 3.0, 4.0, 5.0], "known": ["a", "b", "a", "b"]}, + index=series.index, + ) + future = pd.DataFrame( + {"known": ["b", "c"]}, + index=pd.date_range("2026-01-05", periods=2, freq="D"), + ) + forecaster.fit(series=series, exog=historical) + kwargs = {} + if method == "predict_interval": + kwargs["interval"] = [0.1, 0.9] + elif method == "predict_quantiles": + kwargs["quantiles"] = [0.9, 0.1] + result = getattr(forecaster, method)(steps=2, exog=future, **kwargs) + pd.testing.assert_index_equal(result.index, future.index, check_names=False) + column = "q_0.9" if method == "predict_quantiles" else "pred" + np.testing.assert_allclose( + result[column], [4.9, 5.9] if column == "q_0.9" else [4.5, 5.5] + ) + assert backend.calls[-1]["categorical_future"] == (0,) + assert backend.calls[-1]["past_covariates"].shape == (1, 4) + + +def test_predict_preserves_unequal_history_lengths(): + backend = FakeCIprotoModel() + model = FoundationModel(MODEL_ID, model=backend, context_length=32768) + model.fit({"short": make_context(), "long": make_context(20000)}) + model.predict(2) + assert [call["history"].shape for call in backend.calls] == [(1, 4), (1, 20000)] + + +def test_monthly_dates_use_calendar_offsets(): + backend = FakeCIprotoModel() + adapter = CIprotoAdapter(MODEL_ID, model=backend) + series = make_context(3, end="2026-03-31", freq="ME") + adapter.predict(2, {"sales": series}, None, None, None) + expected = pd.DatetimeIndex(["2026-04-30", "2026-05-31"]).as_unit("ns").asi8 + np.testing.assert_array_equal(backend.calls[0]["timestamps"][-2:], expected) + + +@pytest.mark.parametrize("length", [20000, 2000000]) +@pytest.mark.parametrize("use_context_override", [False, True]) +def test_default_passes_all_history_and_covariates(length, use_context_override): + """Neither fit nor predict overrides may truncate history at 16,384.""" + backend = FakeCIprotoModel() + model = FoundationModel(MODEL_ID, model=backend) + series = pd.Series(np.arange(length, dtype=float), name="sales") + historical = pd.DataFrame({"past": series + 1, "known": series + 2}) + future = pd.DataFrame( + {"known": [length + 2.0, length + 3.0]}, + index=pd.RangeIndex(length, length + 2), + ) + if use_context_override: + model.predict( + 2, + context=series, + context_exog=historical, + exog=future, + ) + else: + model.fit(series, exog=historical) + assert len(model.context_["sales"]) == length + assert len(model.context_exog_["sales"]) == length + model.predict(2, exog=future) + call = backend.calls[0] + assert call["history"].shape == (1, length) + assert call["history"][0, 0] == 0 + assert call["past_covariates"].shape == (1, length) + assert call["past_covariates"][0, 0] == 1 + assert call["future_covariates"].shape == (1, length + 2) + assert call["future_covariates"][0, 0] == 2 + + +def test_explicit_context_limit_is_optional_and_can_be_removed(): + backend = FakeCIprotoModel() + model = FoundationModel(MODEL_ID, model=backend, context_length=128) + series = make_context(20000) + model.fit(series) + model.predict(2) + assert backend.calls[-1]["history"].shape == (1, 128) + model.set_params(context_length=None) + assert model.adapter._model is backend + model.fit(series) + model.predict(2) + assert backend.calls[-1]["history"].shape == (1, 20000) + + +def test_forecaster_and_metadata_represent_all_history_without_a_numeric_limit(): + model = FoundationModel(MODEL_ID) + forecaster = ForecasterFoundation(estimator=model) + assert forecaster.context_length is None + assert forecaster.window_size is None + from skforecast.foundation import list_adapters + + frame = list_adapters(as_frame=True) + assert frame.loc["CIprotoAdapter", "default_context_length"] is None diff --git a/skforecast/foundation/tests/tests_foundation_models/test_clone.py b/skforecast/foundation/tests/tests_foundation_models/test_clone.py index 0a1cb453f..35d89e2bf 100644 --- a/skforecast/foundation/tests/tests_foundation_models/test_clone.py +++ b/skforecast/foundation/tests/tests_foundation_models/test_clone.py @@ -21,10 +21,11 @@ "Synthefy/Nori", "mistralai/Timestral-28M", "NX-AI/TiRex-2", + "ContinuousIntelligence/ci-proto", ], ids=[ "chronos", "timesfm", "timesfm3", "moirai", "tabicl", "tabpfn", "t0", - "tsicl", "nori", "timestral", "tirex2", + "tsicl", "nori", "timestral", "tirex2", "ci_proto", ], ) def test_clone_round_trip_every_adapter_default_params(model_id): diff --git a/skforecast/foundation/tests/tests_foundation_models/test_list_adapters.py b/skforecast/foundation/tests/tests_foundation_models/test_list_adapters.py index c73259629..c0705a618 100644 --- a/skforecast/foundation/tests/tests_foundation_models/test_list_adapters.py +++ b/skforecast/foundation/tests/tests_foundation_models/test_list_adapters.py @@ -20,6 +20,7 @@ def test_list_adapters_output(): ("TimesFM25Adapter", "google/timesfm-2.5-200m-pytorch"), ("TimesFM3Adapter", "google/timesfm-3.0-pytorch"), ("TiRex2Adapter", "NX-AI/TiRex-2"), + ("CIprotoAdapter", "ContinuousIntelligence/ci-proto"), ("MoiraiAdapter", "Salesforce/moirai-2.0-R-small"), ("TabICLAdapter", "soda-inria/tabicl"), ("TabPFNAdapter", "priorlabs/tabpfn-ts"), @@ -116,6 +117,8 @@ def test_list_adapters_every_adapter_declares_its_capabilities(adapter_cls): assert quantiles is None or list(quantiles) == sorted(set(quantiles)) context_length = inspect.signature(adapter_cls).parameters["context_length"] - assert isinstance(context_length.default, int) + assert context_length.default is None or ( + isinstance(context_length.default, int) and context_length.default > 0 + ) assert get_model_info(adapter_cls.default_model_id).adapter == adapter_cls.__name__ diff --git a/skforecast/foundation/tests/tests_foundation_models/test_resolve_adapter.py b/skforecast/foundation/tests/tests_foundation_models/test_resolve_adapter.py index 7af3765bb..3d2281850 100644 --- a/skforecast/foundation/tests/tests_foundation_models/test_resolve_adapter.py +++ b/skforecast/foundation/tests/tests_foundation_models/test_resolve_adapter.py @@ -14,6 +14,7 @@ TSICLAdapter, TimestralAdapter, TiRex2Adapter, + CIprotoAdapter, _resolve_adapter, _ADAPTER_REGISTRY, ) @@ -42,6 +43,7 @@ ("mistralai/Timestral-123M", TimestralAdapter), ("mistralai/Timestral-209M", TimestralAdapter), ("NX-AI/TiRex-2", TiRex2Adapter), + ("ContinuousIntelligence/ci-proto", CIprotoAdapter), ], ids=lambda x: str(x), ) diff --git a/skforecast/model_selection/_validation.py b/skforecast/model_selection/_validation.py index 6c89e91d3..d76ff2a6f 100644 --- a/skforecast/model_selection/_validation.py +++ b/skforecast/model_selection/_validation.py @@ -2997,11 +2997,15 @@ def _backtesting_foundation( cv = deepcopy(cv) if cv.refit is True or cv.fixed_train_size is False: + context_message = ( + "using all available history." + if forecaster.context_length is None else + f"up to the maximum context length ({forecaster.context_length})." + ) warnings.warn( - f"Foundation models are zero-shot and do not learn from training data. " - f"Arguments `refit` and `fixed_train_size` have no effect and are " - f"ignored. The context window grows with each fold up to the maximum " - f"context length ({forecaster.context_length}).", + "Foundation models are zero-shot and do not learn from training data. " + "Arguments `refit` and `fixed_train_size` have no effect and are " + f"ignored. The context window grows with each fold {context_message}", IgnoredArgumentWarning ) cv.refit = True @@ -3016,11 +3020,16 @@ def _backtesting_foundation( levels = levels ) + # Fold splitting needs a finite last window; the actual context is rebuilt + # from the training span below, so one observation suffices when unbounded. cv.set_params({ - 'window_size': forecaster.window_size, + 'window_size': forecaster.window_size or 1, 'return_all_indexes': False, 'verbose': verbose, }) + context_start = ( + -forecaster.context_length if forecaster.context_length is not None else None + ) overlapping_folds = cv.overlapping_folds if not isinstance(metric, list): @@ -3080,7 +3089,7 @@ def _backtesting_foundation( series_name: ( series[series_name] .loc[level_series.index[0]:train_loc_end] - .iloc[-forecaster.context_length :] + .iloc[context_start :] ) for series_name, level_series in context.items() if series[series_name].loc[test_loc_start:test_loc_end].notna().any() @@ -3114,7 +3123,7 @@ def _backtesting_foundation( if exog is not None: context_exog = { series_name: ( - series_exog.iloc[-forecaster.context_length :] + series_exog.iloc[context_start :] if series_exog is not None else None ) diff --git a/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py b/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py new file mode 100644 index 000000000..b167a383c --- /dev/null +++ b/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py @@ -0,0 +1,50 @@ +# Tests of full-history foundation backtesting. +import numpy as np +import pandas as pd +import pytest + +from skforecast.foundation import FoundationModel, ForecasterFoundation +from skforecast.foundation.tests.tests_foundation_models.test_CIprotoAdapter import ( + FakeCIprotoModel, + MODEL_ID, +) +from skforecast.model_selection import TimeSeriesFold, backtesting_foundation + + +@pytest.mark.parametrize("context_length", [None, 64]) +def test_backtesting_keeps_full_history_unless_a_limit_is_requested(context_length): + initial_size = 16400 + series = pd.Series(np.arange(initial_size + 4, dtype=float), name="sales") + exog = pd.DataFrame({"past": series + 1, "known": series + 2}) + backend = FakeCIprotoModel() + forecaster = ForecasterFoundation( + estimator=FoundationModel(MODEL_ID, context_length=context_length) + ) + forecaster.estimator.adapter._model = backend + cv = TimeSeriesFold( + steps=2, + initial_train_size=initial_size, + refit=False, + fixed_train_size=True, + verbose=False, + ) + metrics, predictions = backtesting_foundation( + forecaster=forecaster, + series=series, + exog=exog, + cv=cv, + metric="mean_absolute_error", + show_progress=False, + ) + assert len(backend.calls) == 2 + for call, train_size in zip(backend.calls, [initial_size, initial_size + 2]): + retained = train_size if context_length is None else context_length + assert call["history"].shape == (1, retained) + assert call["past_covariates"] is None + assert call["future_covariates"].shape == (2, retained + 2) + assert call["history"][0, 0] == train_size - retained + assert call["future_covariates"][0, 0] == train_size - retained + 2 + pd.testing.assert_index_equal( + predictions.index, pd.RangeIndex(initial_size, initial_size + 4) + ) + np.testing.assert_allclose(metrics["mean_absolute_error"], 0.5) diff --git a/skills/choosing-a-forecaster/SKILL.md b/skills/choosing-a-forecaster/SKILL.md index 3a6a66312..1854bc92d 100644 --- a/skills/choosing-a-forecaster/SKILL.md +++ b/skills/choosing-a-forecaster/SKILL.md @@ -47,7 +47,7 @@ the chosen model adds value. | **General purpose** (start here) | `ForecasterRecursive` | Default choice. One model, recursive multi-step. Works with any sklearn-compatible estimator (LightGBM, XGBoost, CatBoost, RandomForest, etc.). Supports lags, window features, exog, differentiation, transformers, weight functions, and all probabilistic prediction methods (bootstrapping, conformal, quantiles, distributions) | | **Horizon-dependent patterns** (e.g., predicting at 1h vs 24h requires different relationships) | `ForecasterDirect` | Trains one independent model per step — no error propagation. Better when the predictive relationship changes significantly across the forecast horizon. Requires `steps` at init; parallelizable with `n_jobs` | | **Statistical baseline** | `ForecasterStats` | Wraps ARIMA, SARIMAX, ETS, ARAR. Use as a benchmark to compare against ML models, or when the series is very short (< 200 obs) and ML overfits | -| **Zero-shot / cold-start / no training data** | `ForecasterFoundation` | Wraps pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2). `fit()` only stores context, no training. Strong zero-shot accuracy, also for short or new series; needs more compute to predict. See the `foundation-forecasting` skill | +| **Zero-shot / cold-start / no training data** | `ForecasterFoundation` | Wraps pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, ci-proto). `fit()` only stores context, no training. Strong zero-shot accuracy, also for short or new series; needs more compute to predict. See the `foundation-forecasting` skill | | **Naive baseline** | `ForecasterEquivalentDate` | Predicts using equivalent past dates (e.g., same weekday last week). Use as a sanity-check baseline. See the `baseline-forecasting` skill | ## Step 2b — Multiple Series @@ -57,7 +57,7 @@ the chosen model adds value. | **Forecast many series with a shared model** (start here) | `ForecasterRecursiveMultiSeries` | One global model learns cross-series patterns. Supports DataFrame or dict input (dict allows series with different date ranges). Encoding options: `'ordinal'` (default), `'ordinal_category'`, `'onehot'`, `None`. Supports per-series transformers, per-series differentiation, series_weights | | **Other series are features for one target** | `ForecasterDirectMultiVariate` | All series become input features to predict a single `level`. Per-series lags via dict (`{'sales': [1,7], 'price': [1]}`). One model per step — no error propagation | | **Deep learning / complex nonlinear patterns** | `ForecasterRnn` | Keras-based RNN/LSTM/GRU. Single model outputs all steps and levels simultaneously via 3D tensors. Only conformal intervals (no bootstrapping). Requires keras | -| **Zero-shot / pre-trained generalist** | `ForecasterFoundation` | Global zero-shot forecasts via Chronos-2 / TimesFM 2.5/3.0 / Moirai-2 / TabICL / TabPFN-TS / TFC-T0 / Nori / TS-ICL / Timestral / TiRex-2. `fit()` only stores context. Native quantile intervals. Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral and TiRex-2 support exog; TimesFM 2.5 & Moirai-2 do not. See the `foundation-forecasting` skill | +| **Zero-shot / pre-trained generalist** | `ForecasterFoundation` | Global zero-shot forecasts via Chronos-2 / TimesFM 2.5/3.0 / Moirai-2 / TabICL / TabPFN-TS / TFC-T0 / Nori / TS-ICL / Timestral / TiRex-2. `fit()` only stores context. Native quantile intervals. Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2 and ci-proto support exog; TimesFM 2.5 & Moirai-2 do not. See the `foundation-forecasting` skill | ## Decision Flowchart diff --git a/skills/complete-api-reference/SKILL.md b/skills/complete-api-reference/SKILL.md index 2096a4986..d32d063fc 100644 --- a/skills/complete-api-reference/SKILL.md +++ b/skills/complete-api-reference/SKILL.md @@ -31,7 +31,7 @@ Use this when you need exact parameter names, types, defaults, or method signatu - `ForecasterStats` — statistical models (ARIMA, ETS, SARIMAX, ARAR) - `ForecasterEquivalentDate` — baseline using past offsets - `ForecasterRnn` — deep learning (RNN/LSTM/GRU) -- `ForecasterFoundation` — zero-shot with foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2) +- `ForecasterFoundation` — zero-shot with foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, ci-proto) - `FoundationModel` — low-level foundation model wrapper used by `ForecasterFoundation` - `get_model_info` / `list_adapters`: capabilities of a foundation model (exog, quantiles, context length, backend, license) without installing its backend diff --git a/skills/complete-api-reference/references/forecaster-constructors.md b/skills/complete-api-reference/references/forecaster-constructors.md index 8deacc5b7..0f6652c66 100644 --- a/skills/complete-api-reference/references/forecaster-constructors.md +++ b/skills/complete-api-reference/references/forecaster-constructors.md @@ -163,7 +163,7 @@ FoundationModel( # torch_dtype : object (Chronos-2, T0) # cross_learning : bool (Chronos-2 only) # max_horizon, forecast_config_kwargs (TimesFM 2.5 only) - # predict_kwargs (Chronos-2, TimesFM 3.0, Timestral, TiRex-2) + # predict_kwargs (Chronos-2, TimesFM 3.0, Timestral, TiRex-2, ci-proto) # point_estimate, tabicl_config, temporal_features, show_progress (TabICL) # mode, point_estimate, tabpfn_model_config, temporal_features, show_progress (TabPFN-TS) # (T0 uses only context_length, device_map, torch_dtype) diff --git a/skills/foundation-forecasting/SKILL.md b/skills/foundation-forecasting/SKILL.md index b6ab171fe..d9484192c 100644 --- a/skills/foundation-forecasting/SKILL.md +++ b/skills/foundation-forecasting/SKILL.md @@ -4,7 +4,7 @@ description: > Forecasts time series zero-shot with pre-trained foundation models (Amazon Chronos-2, Google TimesFM 2.5/3.0, Salesforce Moirai-2, Soda-INRIA TabICL, Prior Labs TabPFN-TS, The Forecasting Company T0, EDF Lab TS-ICL, Synthefy Nori, - Mistral AI Timestral, NX-AI TiRex-2) via ForecasterFoundation and + Mistral AI Timestral, NX-AI TiRex-2, ci-proto) via ForecasterFoundation and FoundationModel. Covers single and multi-series workflows, exogenous variables, prediction intervals / quantiles, backtesting, and inference-time parameter search (context_length tuning). @@ -42,8 +42,8 @@ Scan before writing code. Each row lists a rule, the symptom when it is broken, |------|---------|----------| | `fit()` stores context only; it never trains the model | Expecting training to happen or weights to update | Treat the model as pre-trained; evaluate with `backtesting_foundation` | | `cv.refit` and `cv.fixed_train_size` are overridden by `backtesting_foundation` | `IgnoredArgumentWarning` when `refit=True` or `fixed_train_size=False` | Leave them at their defaults; the context window expands per fold either way | -| Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, T0, Nori, TS-ICL, Timestral, and TiRex-2 use `exog`; TimesFM 2.5 and Moirai-2 ignore it | `IgnoredArgumentWarning`, forecast made without `exog` | Pick an exog-capable adapter when covariates matter | -| TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 restrict quantiles to `[0.1, 0.2, ..., 0.9]`; TS-ICL to a 0.01 grid; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`) | Requested quantile rejected or unsupported | Request only supported quantiles, or use an adapter allowing any quantile in (0, 1) | +| Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto use `exog`; TimesFM 2.5 and Moirai-2 ignore it | `IgnoredArgumentWarning`, forecast made without `exog` | Pick an exog-capable adapter when covariates matter | +| TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto restrict quantiles to `[0.1, 0.2, ..., 0.9]`; TS-ICL to a 0.01 grid; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`) | Requested quantile rejected or unsupported | Request only supported quantiles, or use an adapter allowing any quantile in (0, 1) | | Each backend library must be installed separately | `ModuleNotFoundError` / `ImportError` on first use | `pip install` the matching backend (see Installation) | | Tuning uses `bayesian_search_foundation`, never `bayesian_search_forecaster*` | `TypeError` on the forecaster type or on `OneStepAheadFold` | Call `bayesian_search_foundation` with a `TimeSeriesFold` | | Weights for TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, and Timestral are released under licenses that restrict commercial use (terms vary, e.g. TabPFN-TS allows commercial use under an enterprise license, Timestral excludes companies above USD 20 million of monthly revenue); no warning does not mean a model is unrestricted | `LicenseWarning` on first model load | Review the linked license before commercial use; suppress the warning with `suppress_warnings=True` if already reviewed | @@ -63,6 +63,7 @@ pip install tsicl # For TS-ICL pip install synthefy-nori # For Nori pip install "timestral @ git+https://github.com/mistralai/timestral.git" # For Timestral (not on PyPI) pip install tirex-2 # For TiRex-2 (Python >= 3.11) +pip install "continuousintelligence>=0.2.0" # For ci-proto ``` Models are downloaded from HuggingFace on first use. @@ -126,9 +127,9 @@ model = FoundationModel( ) ``` -## With Exogenous Variables (Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2) +## With Exogenous Variables (Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto) -Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2 (`allow_exog=True`) accept exogenous variables. TimesFM 2.5 and Moirai-2 ignore them. At predict time the future `exog` columns are validated per series against the historical exog: a future column with no history raises `ValueError`; a historical column with no future values is a past-only covariate, used by Chronos-2, TS-ICL, TimesFM 3.0, Timestral and TiRex-2 (`supports_past_only_covariates=True`) and ignored with an `IgnoredArgumentWarning` by TabICL, TabPFN-TS, TFC-T0 and Nori. Series in a multi-series input may differ in length and in their exog columns: each series is forecast with its own columns, and adapters whose backend needs identical columns per batch (`supports_heterogeneous_covariates=False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral) are called once per group of series sharing the same columns, so the forecast of a series never depends on the exog of the others. +Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto (`allow_exog=True`) accept exogenous variables. TimesFM 2.5 and Moirai-2 ignore them. At predict time the future `exog` columns are validated per series against the historical exog: a future column with no history raises `ValueError`; a historical column with no future values is a past-only covariate, used by Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2 and ci-proto (`supports_past_only_covariates=True`) and ignored with an `IgnoredArgumentWarning` by TabICL, TabPFN-TS, TFC-T0 and Nori. Series in a multi-series input may differ in length and in their exog columns: each series is forecast with its own columns, and adapters whose backend needs identical columns per batch (`supports_heterogeneous_covariates=False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral) are called once per group of series sharing the same columns, so the forecast of a series never depends on the exog of the others. ```python # Historical + future exog (must cover the forecast horizon) @@ -157,7 +158,7 @@ predictions = forecaster.predict_quantiles( # Columns: ['level', 'q_0.1', 'q_0.5', 'q_0.9'] ``` -For TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2, requested quantiles must be a subset of `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]`. TS-ICL accepts any level on a finer 0.01 grid in `[0.01, 0.99]` (e.g. `0.05`, `0.37`); off-grid levels raise a `ValueError`. Timestral returns 21 fixed levels: `0.01`, `0.05`, every multiple of `0.05` up to `0.95`, and `0.99`; any other level raises a `ValueError`. Chronos-2, TabICL, TabPFN-TS, TFC-T0 and Nori support any quantile in `(0, 1)`. +For TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto, requested quantiles must be a subset of `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]`. TS-ICL accepts any level on a finer 0.01 grid in `[0.01, 0.99]` (e.g. `0.05`, `0.37`); off-grid levels raise a `ValueError`. Timestral returns 21 fixed levels: `0.01`, `0.05`, every multiple of `0.05` up to `0.95`, and `0.99`; any other level raises a `ValueError`. Chronos-2, TabICL, TabPFN-TS, TFC-T0 and Nori support any quantile in `(0, 1)`. ## Choosing a Model @@ -174,6 +175,7 @@ For TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2, requested quantiles must be a s | `taharnbl/TS-ICL` (EDF Lab) | Yes | 4096 | Past & future covariates, fine-grained (0.01) quantile grid | | `mistralai/Timestral-*` (Mistral AI) | Yes | 4096 | Long context, past, future and categorical covariates (the 209M checkpoint is the most accurate) | | `NX-AI/TiRex-2` (NX-AI) | Yes | 2048 | Past & future covariates, series with different covariates in one call, horizons up to 320 steps | +| `ContinuousIntelligence/ci-proto` | Yes | None (all available history) | Past, known-future and categorical covariates | The adapter is resolved automatically from the `model_id` prefix — no need to import adapter classes directly. @@ -279,19 +281,19 @@ automatically to the last `context_length` observations. 1. **Expecting `fit()` to train the model**: it only stores context. The weights come from HuggingFace. 2. **Index without frequency**: call `series.asfreq('h')` (or similar) before `fit` — skforecast requires a frequency. -3. **Passing `exog` to TimesFM 2.5 / Moirai-2**: ignored with an `IgnoredArgumentWarning`. Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, and TiRex-2 support exogenous variables. -4. **Requesting unsupported quantiles**: TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 are restricted to the nine deciles `0.1 … 0.9` ; TS-ICL is restricted to a 0.01 grid in `[0.01, 0.99]`; Timestral to its 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`). +3. **Passing `exog` to TimesFM 2.5 / Moirai-2**: ignored with an `IgnoredArgumentWarning`. Only Chronos-2, TimesFM 3.0, TabICL, TabPFN-TS, TFC-T0, Nori, TS-ICL, Timestral, TiRex-2, and ci-proto support exogenous variables. +4. **Requesting unsupported quantiles**: TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto are restricted to the nine deciles `0.1 … 0.9` ; TS-ICL is restricted to a 0.01 grid in `[0.01, 0.99]`; Timestral to its 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`). 5. **Large model downloads**: first call can be slow; consider using smaller variants (`*-small`) for experimentation. -6. **Forgetting to install the backend**: each foundation model requires its own library (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`). Install only the one(s) you need. `tfc-t0` needs its PyTorch runtime, the `torch` extra (`pip install "tfc-t0[torch]>=0.6"`). `tirex-2` requires Python >= 3.11. +6. **Forgetting to install the backend**: each foundation model requires its own library (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`, `continuousintelligence>=0.2.0`). Install only the one(s) you need. `tfc-t0` needs its PyTorch runtime, the `torch` extra (`pip install "tfc-t0[torch]>=0.6"`). `tirex-2` requires Python >= 3.11. 7. **Tuning a parameter that forces a model reload**: `model_id` and device/dtype arguments reload the model on every trial, and `context_length` does the same on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS. -8. **Assuming TimesFM 3.0 accepts categorical covariates**: it does not, and neither do Nori, T0, TS-ICL, and TiRex-2 (`ValueError`). Only Chronos-2 and Timestral accept them natively. `ForecasterFoundation` has no `transformer_exog`, so encode categoricals as numbers in `exog` before passing it to `fit` and `predict`. +8. **Assuming TimesFM 3.0 accepts categorical covariates**: it does not, and neither do Nori, T0, TS-ICL, and TiRex-2 (`ValueError`). Chronos-2, Timestral and ci-proto accept them natively. `ForecasterFoundation` has no `transformer_exog`, so encode categoricals as numbers in `exog` before passing it to `fit` and `predict`. 9. **Passing a future `exog` column that was not in the historical exog** (`fit` without that column, or `context` without `context_exog`): `ValueError` on every adapter. Pass the same columns to `fit` (or `context_exog`) and to `predict`. -10. **Predicting without `exog` after fitting with exog on TabICL, TabPFN-TS, T0 or Nori**: the historical columns are ignored (`IgnoredArgumentWarning`) and the forecast uses no covariates, as if the model had been fitted without exog. Only Chronos-2, TS-ICL, TimesFM 3.0, Timestral and TiRex-2 use them as past-only covariates. +10. **Predicting without `exog` after fitting with exog on TabICL, TabPFN-TS, T0 or Nori**: the historical columns are ignored (`IgnoredArgumentWarning`) and the forecast uses no covariates, as if the model had been fitted without exog. Only Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2 and ci-proto use them as past-only covariates. 11. **Timestral with a known covariate that is constant over the context and changes over the horizon** (a price that has not moved, or a 0/1 holiday or promotion indicator that is 0 over the whole context): the upper quantiles, and sometimes the median, can become very large ([mistralai/timestral#7](https://github.com/mistralai/timestral/issues/7)). The adapter issues a `FeatureOutOfRangeWarning` naming the series and columns; set the historical values of those columns to NaN. With known covariates, Timestral's forecast of the first steps also depends on `steps`, so do not compare backtests with a different `steps` step by step. 12. **Asking TiRex-2 for more than 320 steps**: `NX-AI/TiRex-2` forecasts at most 320 steps ahead (`future_len` of the checkpoint; 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). Use another adapter for longer horizons. ## References -See [references/adapter-parameters.md](references/adapter-parameters.md) for the per-adapter constructor parameters of `ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, and `TiRex2Adapter`. Each adapter section is self-contained; the last two sections (tunable parameters and model reload cost, common behavior) apply to every adapter, so read them too. +See [references/adapter-parameters.md](references/adapter-parameters.md) for the per-adapter constructor parameters of `ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, and `CIprotoAdapter`. Each adapter section is self-contained; the last two sections (tunable parameters and model reload cost, common behavior) apply to every adapter, so read them too. See the user guide [Foundation models with heterogeneous series](https://skforecast.org/latest/user_guides/foundation-forecasting-with-heterogeneous-series.html) for a worked example with series of different lengths, different exog columns and NaN, and for the table of what each backend requires and tolerates. diff --git a/skills/foundation-forecasting/references/adapter-parameters.md b/skills/foundation-forecasting/references/adapter-parameters.md index 132a22a74..b134eaefd 100644 --- a/skills/foundation-forecasting/references/adapter-parameters.md +++ b/skills/foundation-forecasting/references/adapter-parameters.md @@ -237,6 +237,22 @@ For each series, columns present in its future `exog` become future covariates s **License**: Apache-2.0, so loading the weights raises no `LicenseWarning`. +## CIprotoAdapter + +**Model prefix:** `ContinuousIntelligence/ci-proto`. Install `continuousintelligence>=0.2.0`. + +**Context window:** up to 2 million observations. All supplied history is used by default. The backend automatically selects between variants tuned for shorter and longer contexts; 16,384 observations is the variant-selection threshold, not a history limit. + +| Parameter | Default | Meaning | +|-----------|---------|---------| +| `context_length` | `None` | All available history. Set a positive integer only to impose a retention limit. | +| `device` | `"auto"` | CUDA if available, otherwise CPU. Explicit `"cpu"` or `"cuda"` are supported. | +| `revision` | `None` | Hugging Face revision shared by weights and calibration; a full SHA pins them. | + +Past-only, known-future and categorical covariates are supported. Labels are encoded per series over history and horizon; missing labels remain NaN. Each series is forecast independently using its own history, covariates and dates. + +The published checkpoint returns deciles 0.1 through 0.9; point forecasts use the median. The adapter selects rows using the loaded quantile grid and validates the returned shape. + ## Tunable Parameters and Model Reload Cost The parameters that can be changed after construction (via `set_params`, and therefore searched with `bayesian_search_foundation`) are exactly the keys returned by each adapter's `get_params()`. Any other key raises `ValueError`. Note that `model` / `pipeline` / `module` are constructor-only and are **not** settable. @@ -256,12 +272,13 @@ Being accepted is not the same as being worth searching. Most adapters expose ru | NoriAdapter | `model_id`, `context_length`, `point_estimate`, `add_calendar_features`, `n_fourier_terms`, `nori_config` | `context_length`, `point_estimate`, `add_calendar_features`, `n_fourier_terms`, (`nori_config`) | `model_id`, `nori_config` | | TimestralAdapter | `model_id`, `context_length`, `device`, `predict_kwargs` | `context_length`, (`predict_kwargs`) | `model_id`, `device` | | TiRex2Adapter | `model_id`, `context_length`, `device`, `predict_kwargs` | `context_length`, (`predict_kwargs`) | `model_id`, `device` | +| CIprotoAdapter | `model_id`, `context_length`, `device`, `revision` | `context_length` | `model_id`, `device`, `revision` | Parameters in parentheses are backend passthrough dicts: they can hold quality-relevant settings but are awkward to search, so treat them as advanced. Two consequences that matter when tuning: -- **`context_length` is not uniformly cheap.** It reloads the model on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS; it is free on Chronos-2, TimesFM 3.0, T0, TS-ICL, Nori, Timestral and TiRex-2. +- **`context_length` is not uniformly cheap.** It reloads the model on TimesFM 2.5 (but **not** TimesFM 3.0), Moirai-2, TabICL and TabPFN-TS; it is free on Chronos-2, TimesFM 3.0, T0, TS-ICL, Nori, Timestral, TiRex-2 and ci-proto. - **Reset only on change.** All foundation adapters compare the old and new values first (via the shared `set_params` helper), so re-sampling an identical value never triggers a reload. A reload happens only when a reload-triggering key is set to a genuinely new value, for example sampling a different `context_length` on TimesFM 2.5, Moirai-2, TabICL or TabPFN-TS. `model_id` forces a reload on every adapter except `TSICLAdapter`, where the checkpoint is selected by `checkpoint_version` instead. @@ -274,16 +291,16 @@ All adapters implement the same minimal interface: - `predict(steps, context, context_exog, exog, quantiles)`: returns a `dict[str, np.ndarray]` of shape `(steps, n_quantiles)` keyed by series name. - `get_params()` / `set_params(**kwargs)`: sklearn-style parameter access. - `allow_exog` / `supports_past_only_covariates` / `supports_heterogeneous_covariates` / `supports_nan_in_series`: class attributes read by `FoundationModel` to decide how exog and NaN are handled. When `supports_heterogeneous_covariates` is `False` (Chronos-2, TS-ICL, TabICL, TimesFM 3.0, T0, Timestral), `FoundationModel.predict` groups the series by their (past-only, future) exog columns and calls `adapter.predict` once per group; adapters never receive a batch with mixed covariate columns. When `supports_nan_in_series` is `False`, a context with NaN raises `ValueError` before the adapter is called (all current adapters accept NaN; Nori drops the NaN rows itself). When `max_series_per_call` is an integer (Timestral: 50, TiRex-2: 64), `FoundationModel.predict` splits each group into consecutive chunks of at most that many series and calls `adapter.predict` once per chunk, because the cost per series, and the memory, of the backend grow with the size of the batch; `None` (every other adapter) sends each group in one call. When `requires_equal_length_context` is `True` (T0, Timestral), `FoundationModel` left-pads the context and the historical exog of each call with NaN to the length of its longest series. -- `supports_categorical_covariates` / `requires_hf_auth` / `requires_provider_auth` / `weights_repo_id` / `weights_in_hf_cache` / `backend_package` / `default_model_id` / `SUPPORTED_QUANTILES`: descriptive class attributes. They are exposed, together with the ones above and the default `context_length`, through `get_model_info` and `list_adapters`. `supports_categorical_covariates` is `True` only for Chronos-2 and Timestral (non-numeric covariates are passed natively); `requires_hf_auth` is `True` when the weights are gated on the Hugging Face Hub (currently none of the supported models); `requires_provider_auth` is `True` only for TabPFN-TS (Prior Labs token and license acceptance, outside the Hugging Face Hub); `weights_repo_id` is the fixed Hugging Face repository of the backends that ignore `model_id` (`jingang/TabICL`, `Prior-Labs/tabpfn_3_5`, `taharnbl/TS-ICL`) and `None` when the weights are downloaded from `model_id`; `weights_in_hf_cache` is `False` only for TabPFN-TS, which keeps the weights in its own cache directory; `SUPPORTED_QUANTILES` is `None` when any level in `(0, 1)` is accepted. +- `supports_categorical_covariates` / `requires_hf_auth` / `requires_provider_auth` / `weights_repo_id` / `weights_in_hf_cache` / `backend_package` / `default_model_id` / `SUPPORTED_QUANTILES`: descriptive class attributes. They are exposed, together with the ones above and the default `context_length`, through `get_model_info` and `list_adapters`. `supports_categorical_covariates` is `True` for Chronos-2, Timestral and ci-proto (non-numeric covariates are passed natively); `requires_hf_auth` is `True` when the weights are gated on the Hugging Face Hub (currently none of the supported models); `requires_provider_auth` is `True` only for TabPFN-TS (Prior Labs token and license acceptance, outside the Hugging Face Hub); `weights_repo_id` is the fixed Hugging Face repository of the backends that ignore `model_id` (`jingang/TabICL`, `Prior-Labs/tabpfn_3_5`, `taharnbl/TS-ICL`) and `None` when the weights are downloaded from `model_id`; `weights_in_hf_cache` is `False` only for TabPFN-TS, which keeps the weights in its own cache directory; `SUPPORTED_QUANTILES` is `None` when any level in `(0, 1)` is accepted. ### Exog column validation at predict time `FoundationModel.predict` (and therefore `ForecasterFoundation.predict`, `predict_interval`, `predict_quantiles`) validates, per series, the columns of the future `exog` against the historical exog used as context (the one stored by `fit`, or `context_exog` when `context` is given). The check is skipped on the internal backtesting path, where both come from the same DataFrame. On every path, before the adapter is called, the historical exog of each series is reindexed to the index of its context and the future `exog` to the forecast horizon; missing timestamps are filled with NaN and reported with a `MissingValuesWarning`. No columns are ever added: a series only carries its own exog columns. For adapters with `supports_past_only_covariates=False`, the historical columns without future values are removed before the adapter is called, also on the backtesting path, so the forecast is the same as without those columns (the backends of TabICL and TabPFN-TS do not discard them on their own). -| Situation (per series) | Adapters with `supports_past_only_covariates=True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2) | Adapters with `supports_past_only_covariates=False` (TabICL, TabPFN-TS, T0, Nori) | +| Situation (per series) | Adapters with `supports_past_only_covariates=True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto) | Adapters with `supports_past_only_covariates=False` (TabICL, TabPFN-TS, T0, Nori) | |---------------------------------------------------------|---------------------------------------------------------------|---------------------------------------------------------------| | Future `exog` column with no historical values | `ValueError` | `ValueError` | | Historical column with no future values (`exog=None` or a subset of columns) | Used as a past-only covariate, no warning | Removed before calling the adapter, `IgnoredArgumentWarning` listing the columns and series | | Same columns on both sides (any order) | OK | OK | -Backend libraries (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`) are imported **lazily** inside the adapter method that needs them, so only the backend for the adapter you actually use needs to be installed. +Backend libraries (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0`, `synthefy-nori`, `tsicl`, `timestral`, `tirex-2`, `continuousintelligence>=0.2.0`) are imported **lazily** inside the adapter method that needs them, so only the backend for the adapter you actually use needs to be installed. diff --git a/skills/prediction-intervals/SKILL.md b/skills/prediction-intervals/SKILL.md index ef3bdf4ed..1babdb718 100644 --- a/skills/prediction-intervals/SKILL.md +++ b/skills/prediction-intervals/SKILL.md @@ -147,7 +147,7 @@ predictions = forecaster.predict_quantiles( ) ``` -TimesFM (2.5 and 3.0), Moirai-2 and TiRex-2 restrict quantiles to `[0.1, 0.2, …, 0.9]`; TS-ICL restricts them to a 0.01 grid in `[0.01, 0.99]`; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`); Chronos-2, TabICL, TabPFN-TS, TFC-T0, and Nori accept any quantile in `(0, 1)`. See the `foundation-forecasting` skill for details. +TimesFM (2.5 and 3.0), Moirai-2, TiRex-2 and ci-proto restrict quantiles to `[0.1, 0.2, …, 0.9]`; TS-ICL restricts them to a 0.01 grid in `[0.01, 0.99]`; Timestral to 21 levels (`0.01`, `0.05`, `0.1`, ..., `0.95`, `0.99`); Chronos-2, TabICL, TabPFN-TS, TFC-T0, and Nori accept any quantile in `(0, 1)`. See the `foundation-forecasting` skill for details. ## During Backtesting diff --git a/tools/ai/README.md b/tools/ai/README.md index 8a2608351..192686ddb 100644 --- a/tools/ai/README.md +++ b/tools/ai/README.md @@ -168,7 +168,7 @@ All marked with `` header and tracked in `.gitattributes` | `feature-selection` | — | RFECV, SelectFromModel | | `drift-detection` | — | RangeDriftDetector, PopulationDriftDetector | | `deep-learning-forecasting` | `architecture-options.md` | ForecasterRnn, LSTM/GRU | -| `foundation-forecasting` | `adapter-parameters.md` | ForecasterFoundation, Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2 | +| `foundation-forecasting` | `adapter-parameters.md` | ForecasterFoundation, Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto | | `choosing-a-forecaster` | — | Decision guide for forecaster selection | | `baseline-forecasting` | — | ForecasterEquivalentDate and naive baselines | | `troubleshooting-common-errors` | — | Common mistakes and fixes | diff --git a/tools/ai/llms-base.txt b/tools/ai/llms-base.txt index db0e0d30c..e57a79823 100644 --- a/tools/ai/llms-base.txt +++ b/tools/ai/llms-base.txt @@ -38,7 +38,7 @@ skforecast/ ├── direct/ # ForecasterDirect, ForecasterDirectMultiVariate ├── deep_learning/ # ForecasterRnn, create_and_compile_model ├── foundation/ # FoundationModel, ForecasterFoundation, get_model_info, list_adapters -│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) +│ # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) ├── stats/ # Arima, Sarimax, Ets, Arar, acf, pacf, calculate_lag_autocorrelation ├── preprocessing/ # TimeSeriesDifferentiator, RollingFeatures, CalendarFeatures, │ # QuantileBinner, ConformalIntervalCalibrator, reshape_* functions @@ -59,7 +59,7 @@ skforecast/ - **Forecasters inheriting from `ForecasterBase`**: ForecasterRecursive, ForecasterRecursiveMultiSeries, ForecasterRecursiveClassifier, ForecasterDirect, ForecasterDirectMultiVariate, ForecasterRnn - **Standalone forecasters (no inheritance)**: ForecasterStats, ForecasterEquivalentDate, ForecasterFoundation - Statistical models in `stats/` are wrapped by `ForecasterStats` (in `recursive/`) -- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`) resolved from the HuggingFace `model_id` +- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`, `CIprotoAdapter`) resolved from the HuggingFace `model_id` - `model_selection/` functions work with all forecaster types - `preprocessing/` classes can be passed to forecasters via `transformer_y`, `transformer_exog`, `window_features` @@ -73,7 +73,7 @@ skforecast/ | ForecasterDirectMultiVariate | Multivariate forecasting (multiple series as features) | | ForecasterRnn | Deep learning (RNN/LSTM) forecasting | | ForecasterStats | Statistical models (ARIMA, SARIMAX, ETS, ARAR) | -| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) | +| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2, ci-proto) | | ForecasterRecursiveClassifier | Classification-based forecasting | | ForecasterEquivalentDate | Baseline forecaster using equivalent past dates | @@ -457,7 +457,7 @@ forecaster = ForecasterStats(estimator=Ets(m=12, model='AAA')) ## Foundation Models (Zero-Shot) -Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. +Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `continuousintelligence>=0.2.0`, `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use. `FoundationModel` is the low-level interface; `ForecasterFoundation` wraps it to integrate with the rest of the skforecast ecosystem (backtesting, model selection, uniform `predict` / `predict_interval` / `predict_quantiles` API). @@ -498,6 +498,7 @@ Supported adapters (selected automatically from `model_id`). Query them programm | TSICLAdapter (EDF Lab) | `taharnbl/TS-ICL` | Yes (past & future covariates) | 4096 | Subset of `[0.01, 0.02, ..., 0.99]` | | TimestralAdapter (Mistral AI) | `mistralai/Timestral` | Yes (past, known-future and categorical covariates) | 4096 | Subset of `[0.01, 0.05, 0.1, ..., 0.95, 0.99]` (21 levels) | | TiRex2Adapter (NX-AI) | `NX-AI/TiRex-2` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` | +| CIprotoAdapter (Continuous Intelligence) | `ContinuousIntelligence/ci-proto` | Yes (past, known-future and categorical covariates) | None (all available history) | `[0.1, 0.2, ..., 0.9]` | ```python from skforecast.foundation import get_model_info, list_adapters @@ -524,13 +525,13 @@ list_adapters(as_frame=True) ``` Key points: -- `fit()` only stores the last `context_length` observations and metadata. It does **not** train the model. +- `fit()` stores the last `context_length` observations and metadata, or all available history when `context_length=None`. It does **not** train the model. - The index must have a frequency (`data.asfreq(...)`), same requirement as other skforecast forecasters. - `predict(..., context=...)` lets you override the stored context (used internally by backtesting). - Use `backtesting_foundation` (not `backtesting_forecaster`) to evaluate a `ForecasterFoundation`. It deep-copies `cv` and forces `refit=True`, `fixed_train_size=False`, so the context window expands with each fold up to `context_length`; no weights are ever trained. - Use `bayesian_search_foundation` (not `bayesian_search_forecaster`) to tune inference-time parameters such as `context_length`. Only `TimeSeriesFold` is supported. - Loading a model whose weights are released under a license that restricts commercial use (TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, Timestral) raises a `LicenseWarning` naming the license and a link to the model card; review the link, since terms vary (e.g. TabPFN-TS permits commercial use under an enterprise license; Timestral grants no rights to companies above USD 20 million of monthly revenue). Absence of the warning does not guarantee a model's license is unrestricted. Suppress it like any other skforecast warning (`suppress_warnings=True` or `warnings.simplefilter`). -- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. +- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2, ci-proto), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column. - Multi-series input may be heterogeneous: series can have different lengths, a different subset of exog columns each, and NaN values. Each series is forecast with its own exog columns only. When the backend needs identical covariate columns in a batch (`forecaster.supports_heterogeneous_covariates` is `False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral), the series are grouped by their exog columns and the backend is called once per group, so the forecast of a series never depends on the exog of the others. `forecaster.supports_nan_in_series` tells whether the backend accepts NaN in the context. - Timestral: with a known covariate that is constant over the context and changes over the horizon (a price, or a 0/1 indicator that is 0 over the whole context), the upper quantiles can become very large (mistralai/timestral#7); a `FeatureOutOfRangeWarning` names the affected series and columns, and setting their historical values to NaN avoids it. - TiRex-2: each checkpoint forecasts at most `future_len` steps ahead (320 for `NX-AI/TiRex-2`, 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). All the series go to the backend in the same call whatever their exog, in calls of at most 64 series. diff --git a/tools/docs/hooks/page_meta.yml b/tools/docs/hooks/page_meta.yml index 4ec27cf2e..24058d287 100644 --- a/tools/docs/hooks/page_meta.yml +++ b/tools/docs/hooks/page_meta.yml @@ -129,6 +129,12 @@ user_guides/dependent-multi-series-multivariate-forecasting.ipynb: Multivariate time series forecasting in Python with ForecasterDirectMultiVariate: predict a series from the lags of several series. +user_guides/foundation-ci-proto.md: + title: Forecasting with ci-proto + description: >- + Forecast with ci-proto in skforecast using past and known-future covariates, + categorical inputs, calendar dates, native quantiles and long contexts. + user_guides/foundation-forecasting-models.ipynb: title: Forecasting with foundation models description: >- diff --git a/tools/foundation_compat/adapters.toml b/tools/foundation_compat/adapters.toml index 4741b0857..06e456c4b 100644 --- a/tools/foundation_compat/adapters.toml +++ b/tools/foundation_compat/adapters.toml @@ -74,3 +74,8 @@ model_id = "mistralai/Timestral-5M" adapter = "TiRex2Adapter" backend_package = "tirex-2" model_id = "NX-AI/TiRex-2" + +[ci_proto] +adapter = "CIprotoAdapter" +backend_package = "continuousintelligence>=0.2.0" +model_id = "ContinuousIntelligence/ci-proto" diff --git a/tools/foundation_compat/tests/contracts.py b/tools/foundation_compat/tests/contracts.py index 85a859663..5233d468e 100644 --- a/tools/foundation_compat/tests/contracts.py +++ b/tools/foundation_compat/tests/contracts.py @@ -190,6 +190,21 @@ }, {"target": "timestral:Forecast", "kwargs": ["quantiles", "quantile_levels"]}, ], + "ci_proto": [ + { + "target": "continuousintelligence:load_model", + "n_positional": 1, + "kwargs": ["device", "revision"], + }, + {"target": "continuousintelligence:Forecaster.quantiles"}, + { + "target": "continuousintelligence:Forecaster.forecast", + "kwargs": [ + "history", "horizon", "past_covariates", "future_covariates", + "categorical_past", "categorical_future", "timestamps", "freq", + ], + }, + ], "tirex2": [ {"target": "tirex2:load_model", "n_positional": 1, "kwargs": ["device"]}, { From 1042e847674c38727063307f4112b460ac20d42d Mon Sep 17 00:00:00 2001 From: Benjamin Walker Date: Sat, 21 Nov 2026 15:46:22 +0000 Subject: [PATCH 2/2] Use shared lightweight torch fixtures for ci-proto unit tests --- .../fixtures_adapters.py | 10 +++++--- .../test_CIprotoAdapter.py | 23 ++++++++++++------- ...est_backtesting_foundation_full_history.py | 10 +++++++- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/skforecast/foundation/tests/tests_foundation_models/fixtures_adapters.py b/skforecast/foundation/tests/tests_foundation_models/fixtures_adapters.py index 6f1dcfa4a..c07436630 100644 --- a/skforecast/foundation/tests/tests_foundation_models/fixtures_adapters.py +++ b/skforecast/foundation/tests/tests_foundation_models/fixtures_adapters.py @@ -819,9 +819,9 @@ def to(self, device): class FakeTorch: """ - Minimal `torch` stand-in with the two attributes the adapter uses: - `float32` and `as_tensor`. The tensors it builds are numpy arrays viewed as - `FakeTensor`, so their values and shapes can be asserted directly. + Minimal `torch` stand-in with the dtype and tensor conversions used by the + adapters. The tensors it builds are numpy arrays viewed as `FakeTensor`, + so their values and shapes can be asserted directly. """ float32 = np.float32 @@ -830,6 +830,10 @@ class FakeTorch: def as_tensor(value, dtype=None): return np.asarray(value, dtype=dtype).view(FakeTensor) + @staticmethod + def from_numpy(value): + return value.view(FakeTensor) + class FakeTimeseriesType: """ diff --git a/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py b/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py index 2bda98347..1a2f891d3 100644 --- a/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py +++ b/skforecast/foundation/tests/tests_foundation_models/test_CIprotoAdapter.py @@ -11,17 +11,24 @@ from skforecast.foundation import FoundationModel, ForecasterFoundation, get_model_info from skforecast.foundation._adapters import CIprotoAdapter +from .fixtures_adapters import FakeTorch -torch = pytest.importorskip("torch") MODEL_ID = "ContinuousIntelligence/ci-proto" +@pytest.fixture(autouse=True) +def fake_torch(monkeypatch): + """Use the same lightweight torch stand-in as the other adapter tests.""" + monkeypatch.setitem(sys.modules, "torch", FakeTorch) + + class FakeCIprotoModel: """Mirror the published Forecaster signature and record per-series inputs.""" def __init__(self, quantiles=None): - self.quantiles = torch.tensor( - CIprotoAdapter.SUPPORTED_QUANTILES if quantiles is None else quantiles + self.quantiles = np.asarray( + CIprotoAdapter.SUPPORTED_QUANTILES if quantiles is None else quantiles, + dtype=np.float32, ) self.calls = [] @@ -41,7 +48,7 @@ def forecast( ): self.calls.append( { - "history": history.clone(), + "history": history.copy(), "horizon": horizon, "past_covariates": past_covariates, "future_covariates": future_covariates, @@ -55,7 +62,7 @@ def forecast( return ( history[:, -1, None, None] + self.quantiles[None, :, None] - + torch.arange(horizon)[None, None, :] + + np.arange(horizon, dtype=np.float32)[None, None, :] ) @@ -179,7 +186,7 @@ def test_missing_checkpoint_quantile_fails_before_forecasting(): @pytest.mark.parametrize("shape", [(1, 9, 1), (2, 9, 2), (1, 2, 9), (9, 2)]) def test_malformed_backend_output(shape): backend = FakeCIprotoModel() - backend.forecast = lambda **kwargs: torch.zeros(shape) + backend.forecast = lambda **kwargs: np.zeros(shape) adapter = CIprotoAdapter(MODEL_ID, model=backend) with pytest.raises(ValueError, match="unexpected forecast shape"): adapter.predict(2, {"sales": make_context()}, None, None, None) @@ -193,11 +200,11 @@ def test_dated_unequal_contexts_keep_their_own_lengths_and_origins(): before = {name: series.copy() for name, series in context.items()} adapter.predict(3, context, None, None, None) later, earlier = backend.calls - assert later["history"].dtype == torch.float32 + assert later["history"].dtype == np.float32 assert later["history"].shape == (1, 4) assert earlier["history"].shape == (1, 2) np.testing.assert_allclose(earlier["history"][0], [1, 2]) - assert torch.isnan(later["history"][0, 1]) + assert np.isnan(later["history"][0, 1]) assert later["freq"] == earlier["freq"] == "D" assert later["series_ids"] is earlier["series_ids"] is None expected = pd.date_range("2026-01-01", periods=5, freq="D").as_unit("ns").asi8 diff --git a/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py b/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py index b167a383c..499a3e8ec 100644 --- a/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py +++ b/skforecast/model_selection/tests/tests_validation/test_backtesting_foundation_full_history.py @@ -1,9 +1,14 @@ # Tests of full-history foundation backtesting. +import sys + import numpy as np import pandas as pd import pytest from skforecast.foundation import FoundationModel, ForecasterFoundation +from skforecast.foundation.tests.tests_foundation_models.fixtures_adapters import ( + FakeTorch, +) from skforecast.foundation.tests.tests_foundation_models.test_CIprotoAdapter import ( FakeCIprotoModel, MODEL_ID, @@ -12,7 +17,10 @@ @pytest.mark.parametrize("context_length", [None, 64]) -def test_backtesting_keeps_full_history_unless_a_limit_is_requested(context_length): +def test_backtesting_keeps_full_history_unless_a_limit_is_requested( + context_length, monkeypatch +): + monkeypatch.setitem(sys.modules, "torch", FakeTorch) initial_size = 16400 series = pd.Series(np.arange(initial_size + 4, dtype=float), name="sales") exog = pd.DataFrame({"past": series + 1, "known": series + 2})