Chronos2ModelWrapper
Python template · sinapsis_darts_forecasting.templates.time_series_model
Overview
Base Template for Darts Time Series forecasting models.
Chronos2Model — inherited documentation
The base class for "global" forecasting models, handling several time series and optional covariates.
Global forecasting models expand upon the functionality of `ForecastingModel` in 4 ways: 1. Models can be fitted on many series (multivariate or univariate) with different indices. 2. The input series used by :func:`predict()` can be different from the series used to fit the model. 3. Covariates can be supported (multivariate or univariate). 4. They can allow for multivariate target series and covariates.
The name "global" stems from the fact that a training set of a forecasting model of this class is not constrained to a temporally contiguous, "local", time series.
All implementations must implement the :func:`fit()` and :func:`predict()` methods. The :func:`fit()` method is meant to train the model on one or several training time series, along with optional covariates.
If :func:`fit()` has been called with only one training and covariate series as argument, then calling :func:`predict()` will forecast the future of this series. Otherwise, the user has to provide to :func:`predict()` the series they want to forecast, as well as covariates, if needed.Chronos-2 Model for zero-shot forecasting.
This is an implementation of Amazon's Chronos-2 model [1]_, [2]_, ported from `amazon-science/chronos-forecasting <https://github.com/amazon-science/chronos-forecasting>`_ with adaptations to use the Darts API. From the original authors:
"Chronos-2 is a 120M-parameter, encoder-only time series foundation model for zero-shot forecasting. It supports univariate, multivariate, and covariate-informed tasks within a single architecture. Inspired by the T5 encoder, Chronos-2 produces multi-step-ahead quantile forecasts and uses a group attention mechanism for efficient in-context learning across related series and covariates. Trained on a combination of real-world and large-scale synthetic datasets, it achieves state-of-the-art zero-shot accuracy among public models on fev-bench, GIFT-Eval, and Chronos Benchmark II. Chronos-2 is also highly efficient, delivering over 300 time series forecasts per second on a single A10G GPU and supporting both GPU and CPU inference."
This model supports past covariates (known for `input_chunk_length` points before prediction time), and future covariates (known for `output_chunk_length` points after prediction time).
By default, using this model will automatically download and cache the pre-trained model from HuggingFace Hub (amazon/chronos-2). Alternatively, you can specify a local directory containing the model config and weights using the ``local_dir`` parameter.
Two other variants of Chronos-2 are available on HuggingFace Hub:
- `autogluon/chronos-2-small <https://huggingface.co/autogluon/chronos-2-small>`_: a smaller 28M parameter Chronos-2 model. - `autogluon/chronos-2-synth <https://huggingface.co/autogluon/chronos-2-synth>`_: a 120M parameter Chronos-2 model trained on synthetic data only.
To use either of those variants, specify the ``hub_model_name`` parameter to the desired model ID.
By default, this model is deterministic and outputs only the median (0.5 quantile). To enable probabilistic forecasts, pass a :class:`~darts.utils.likelihood_models.torch.QuantileRegression` instance to the ``likelihood`` parameter. The quantiles used must be a subset of those used during Chronos-2 pre-training, see below for details. It is recommended to call :func:`predict()` with ``predict_likelihood_parameters=True`` or ``num_samples >> 1`` to get meaningful results.
Parameters ---------- input_chunk_length Number of time steps in the past to take as a model input (per chunk). Applies to the target series, and past and/or future covariates (if the model supports it). Maximum is 8192 for Chronos-2. output_chunk_length Number of time steps predicted at once (per chunk) by the internal model. Also, the number of future values from future covariates to use as a model input (if the model supports future covariates). It is not the same as forecast horizon `n` used in `predict()`, which is the desired number of prediction points generated using either a one-shot- or autoregressive forecast. Setting `n <= output_chunk_length` prevents auto-regression. This is useful when the covariates don't extend far enough into the future, or to prohibit the model from using future values of past and / or future covariates for prediction (depending on the model's covariate support). For Chronos-2, `output_chunk_length + output_chunk_shift` must be less than or equal to 1024. output_chunk_shift Optionally, the number of steps to shift the start of the output chunk into the future (relative to the input chunk end). This will create a gap between the input and output. If the model supports `future_covariates`, the future values are extracted from the shifted output chunk. Predictions will start `output_chunk_shift` steps after the end of the target `series`. If `output_chunk_shift` is set, the model cannot generate autoregressive predictions (`n > output_chunk_length`). likelihood The likelihood model to be used for probabilistic forecasts. Must be ``None`` or an instance of :class:`~darts.utils.likelihood_models.torch.QuantileRegression`. If using ``QuantileRegression``, the quantiles must be a subset of those used during Chronos-2 pre-training: [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99]. Default: ``None``, which will make Chronos-2 deterministic (median quantile only). hub_model_name The model ID on HuggingFace Hub. Default: ``"amazon/chronos-2"``. Other available variants include ``"autogluon/chronos-2-small"`` and ``"autogluon/chronos-2-synth"``. hub_model_revision The model version to use. This can be a branch name, tag name, or commit hash. Default is ``None``, which will use the default branch from ``hub_model_name``. local_dir Optional local directory to load the pre-downloaded model. If specified and the directory is empty, the model will be downloaded from HuggingFace Hub and saved to this directory. Default is ``None``, which will use a cache directory managed by ``huggingface_hub`` instead. Note that this is different from the ``work_dir`` parameter used for saving model checkpoints during fine-tuning. **kwargs Optional arguments to initialize the pytorch_lightning.Module, pytorch_lightning.Trainer, and Darts' :class:`TorchForecastingModel`.
loss_fn PyTorch loss function used for fine-tuning a deterministic Chronos-2 model. Ignored for probabilistic Chronos-2 when ``likelihood`` is specified. Default: ``nn.MSELoss()``. torch_metrics A torch metric or a ``MetricCollection`` used for evaluation. A full list of available metrics can be found at https://torchmetrics.readthedocs.io/en/latest/. Default: ``None``. optimizer_cls The PyTorch optimizer class to be used. Default: ``torch.optim.Adam``. optimizer_kwargs Optionally, some keyword arguments for the PyTorch optimizer (e.g., ``{'lr': 1e-3}`` for specifying a learning rate). Otherwise, the default values of the selected ``optimizer_cls`` will be used. Default: ``None``. lr_scheduler_cls Optionally, the PyTorch learning rate scheduler class to be used. Specifying ``None`` corresponds to using a constant learning rate. Default: ``None``. lr_scheduler_kwargs Optionally, some keyword arguments for the PyTorch learning rate scheduler. Default: ``None``. use_reversible_instance_norm Whether to use reversible instance normalization `RINorm` against distribution shift. Ignored by Chronos-2 as it has its own `RINorm` implementation. batch_size Number of time series (input and output sequences) used in each training pass. Default: ``32``. n_epochs Number of epochs over which to train the model. Default: ``100``. model_name Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified, defaults to the following string ``"YYYY-mm-dd_HH_MM_SS_torch_model_run_PID"``, where the initial part of the name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at the same time by different processes to share the same model_name). E.g., ``"2021-06-14_09_53_32_torch_model_run_44607"``. work_dir Path of the working directory, where to save checkpoints and Tensorboard summaries. Default: current working directory. log_tensorboard If set, use Tensorboard to log the different parameters. The logs will be located in: ``"{work_dir}/darts_logs/{model_name}/logs/"``. Default: ``False``. nr_epochs_val_period Number of epochs to wait before evaluating the validation loss (if a validation ``TimeSeries`` is passed to the :func:`fit()` method). Default: ``1``. force_reset If set to ``True``, any previously-existing model with the same name will be reset (all checkpoints will be discarded). Default: ``False``. save_checkpoints Whether to automatically save the untrained model and checkpoints from training. To load the model from checkpoint, call :func:`MyModelClass.load_from_checkpoint()`, where :class:`MyModelClass` is the :class:`TorchForecastingModel` class that was used (such as :class:`TFTModel`, :class:`NBEATSModel`, etc.). If set to ``False``, the model can still be manually saved using :func:`save()` and loaded using :func:`load()`. Default: ``False``. add_encoders A large number of past and future covariates can be automatically generated with `add_encoders`. This can be done by adding multiple pre-defined index encoders and/or custom user-made functions that will be used as index encoders. Additionally, a transformer such as Darts' :class:`Scaler` can be added to transform the generated covariates. This happens all under one hood and only needs to be specified at model creation. Read :meth:`SequentialEncoder <darts.dataprocessing.encoders.SequentialEncoder>` to find out more about ``add_encoders``. Default: ``None``. An example showing some of ``add_encoders`` features:
.. highlight:: python .. code-block:: python
def encode_year(idx): return (idx.year - 1950) / 50
add_encoders={ 'cyclic': {'future': ['month']}, 'datetime_attribute': {'future': ['hour', 'dayofweek']}, 'position': {'past': ['relative'], 'future': ['relative']}, 'custom': {'past': [encode_year]}, 'transformer': Scaler(), 'tz': 'CET' } .. random_state Controls the randomness of the weights initialization and reproducible forecasting. pl_trainer_kwargs By default :class:`TorchForecastingModel` creates a PyTorch Lightning Trainer with several useful presets that performs the training, validation and prediction processes. These presets include automatic checkpointing, tensorboard logging, setting the torch device and more. With ``pl_trainer_kwargs`` you can add additional kwargs to instantiate the PyTorch Lightning trainer object. Check the `PL Trainer documentation <https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html>`__ for more information about the supported kwargs. Default: ``None``. Running on GPU(s) is also possible using ``pl_trainer_kwargs`` by specifying keys ``"accelerator", "devices", and "auto_select_gpus"``. Some examples for setting the devices inside the ``pl_trainer_kwargs`` dict:
- ``{"accelerator": "cpu"}`` for CPU, - ``{"accelerator": "gpu", "devices": [i]}`` to use only GPU ``i`` (``i`` must be an integer), - ``{"accelerator": "gpu", "devices": -1, "auto_select_gpus": True}`` to use all available GPUS.
For more info, see here: https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html#trainer-flags , and https://pytorch-lightning.readthedocs.io/en/stable/accelerators/gpu_basic.html#train-on-multiple-gpus
With parameter ``"callbacks"`` you can add custom or PyTorch-Lightning built-in callbacks to Darts' :class:`TorchForecastingModel`. Below is an example for adding EarlyStopping to the training process. The model will stop training early if the validation loss `val_loss` does not improve beyond specifications. For more information on callbacks, visit: `PyTorch Lightning Callbacks <https://pytorch-lightning.readthedocs.io/en/stable/extensions/callbacks.html>`__
.. highlight:: python .. code-block:: python
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
# stop training when validation loss does not decrease more than 0.05 (`min_delta`) over # a period of 5 epochs (`patience`) my_stopper = EarlyStopping( monitor="val_loss", patience=5, min_delta=0.05, mode='min', )
pl_trainer_kwargs={"callbacks": [my_stopper]} ..
Note that you can also use a custom PyTorch Lightning Trainer for training and prediction with optional parameter ``trainer`` in :func:`fit()` and :func:`predict()`. show_warnings whether to show warnings raised from PyTorch Lightning. Useful to detect potential issues of your forecasting use case. Default: ``False``.
References ---------- .. [1] A. Ansari, O. Shchur, J. Küken et al. "Chronos-2: From Univariate to Universal Forecasting", 2025. arXiv https://arxiv.org/abs/2510.15821. .. [2] "Introducing Chronos-2: From univariate to universal forecasting", 2025. Amazon Science Blog. https://www.amazon.science/blog/introducing-chronos-2-from-univariate-to-universal-forecasting
Examples -------- >>> from darts.datasets import WeatherDataset >>> from darts.models import Chronos2Model >>> # load data in float32 format (macOS issues with float64 and PyTorch) >>> series = WeatherDataset().load().astype("float32") >>> # predicting atmospheric pressure >>> target = series['p (mbar)'][:100] >>> # optionally, use past observed rainfall (pretending to be unknown beyond index 100) >>> past_cov = series['rain (mm)'][:100] >>> # optionally, use future temperatures (pretending this component is a forecast) >>> future_cov = series['T (degC)'][:106] >>> # by default, Chronos2Model is deterministic; to enable probabilistic forecasts, >>> # set likelihood to QuantileRegression and use a subset of the pre-trained quantiles >>> model = Chronos2Model( >>> input_chunk_length=6, >>> output_chunk_length=6, >>> ) >>> # calling fit is still mandatory to ensure consistent number of components; however, >>> # Chronos2Model is training-free and the model weights are not updated >>> model.fit(target, past_covariates=past_cov, future_covariates=future_cov) >>> # when Chronos2Model is probabilistic, set ``predict_likelihood_parameters=True`` >>> # or ``num_samples>>1`` to get meaningful results >>> pred = model.predict(6) >>> print(pred.all_values()) [[[1005.7576 ]] [[1005.7418 ]] [[1005.7186 ]] [[1005.7074 ]] [[1005.6928 ]] [[1005.69617]]]
.. note:: Fine-tuning of Chronos-2 is not supported at the moment. .. note:: Chronos-2 is licensed under the `Apache-2.0 License <https://github.com/amazon-science/chronos-forecasting/blob/main/LICENSE>`_, copyright Amazon.com, Inc. or its affiliates. By using this model, you agree to the terms and conditions of the license. .. warning:: Due to differences in probabilistic sampling methods, zero-shot forecasts obtained here would differ from those obtained using the original implementation when prediction horizon `n` is larger than 1024.
Capabilities
Capabilities: not setInstallation
Install the published package using pip or uv.
pip install sinapsis-darts-forecasting==1.0.0uv pip install sinapsis-darts-forecasting==1.0.0uv add sinapsis-darts-forecasting==1.0.0Configuration
Effective fields from the inspector schema, including nested Pydantic model fields.
Optional
Default: null
Optional
Default: false
Optional
Default: 10
Required
Default: null
Configuration example
Generated from documented defaults. Replace any placeholders and complete required nested settings before running.
templates:
- template_name: "Chronos2ModelWrapper"
class_name: "Chronos2ModelWrapper"
attributes:
validation_mode: false
forecast_horizon: 10
chronos2model_init: {}
View original docstring example
The source example references XGBModelWrapper, not Chronos2ModelWrapper.
agent:
name: my_test_agent
templates:
- template_name: InputTemplate
class_name: InputTemplate
attributes: {}
- template_name: XGBModelWrapper
class_name: XGBModelWrapper
template_input: InputTemplate
attributes:
forecast_horizon: 100
xgbmodel_init:
lags: 30
lags_past_covariates: 30
output_chunk_length: 100
random_state: 42
n_estimators: 200
learning_rate: 0.1
max_depth: 6
For a full list of options use the sinapsis cli: sinapsis info --all-template-names.
If you want to see all available models, please visit:
https://unit8co.github.io/darts/generated_api/darts.models.forecasting.htmlInheritance
sinapsis_darts_forecasting.templates.time_series_model.TimeSeriesModelEnvironment variables
Environment definitions belong to their canonical Python modules.