Skip to main content

Chronos: Pretrained models for time series forecasting

Project description

Chronos: Learning the Language of Time Series

preprint huggingface huggingface fev aws faq License: MIT

🚀 News

  • 14 Feb 2025: 🚀 Chronos-Bolt is now available on Amazon SageMaker JumpStart! Check out the tutorial notebook to learn how to deploy Chronos endpoints for production use in 3 lines of code.
  • 12 Dec 2024: 📊 We released fev, a lightweight package for benchmarking time series forecasting models based on the Hugging Face datasets library.
  • 26 Nov 2024: ⚡️ Chronos-Bolt models released on HuggingFace. Chronos-Bolt models are more accurate (5% lower error), up to 250x faster and 20x more memory efficient than the original Chronos models of the same size!
  • 27 Jun 2024: 🚀 Released datasets used in the paper and an evaluation script to compute the WQL and MASE scores reported in the paper.
  • 17 May 2024: 🐛 Fixed an off-by-one error in bin indices in the output_transform. This simple fix significantly improves the overall performance of Chronos. We will update the results in the next revision on ArXiv.
  • 10 May 2024: 🚀 We added the code for pretraining and fine-tuning Chronos models. You can find it in this folder. We also added a script for generating synthetic time series data from Gaussian processes (KernelSynth; see Section 4.2 in the paper for details). Check out the usage examples.
  • 19 Apr 2024: 🚀 Chronos is now supported on AutoGluon-TimeSeries, the powerful AutoML package for time series forecasting which enables model ensembles, cloud deployments, and much more. Get started with the tutorial.
  • 08 Apr 2024: 🧪 Experimental MLX inference support added. If you have an Apple Silicon Mac, you can now obtain significantly faster forecasts from Chronos compared to CPU inference. This provides an alternative way to exploit the GPU on your Apple Silicon Macs together with the "mps" support in PyTorch.
  • 25 Mar 2024: 🚀 v1.1.0 released with inference optimizations and pipeline.embed to extract encoder embeddings from Chronos.
  • 13 Mar 2024: 🚀 Chronos paper and inference code released.

✨ Introduction

Chronos is a family of pretrained time series forecasting models based on language model architectures. A time series is transformed into a sequence of tokens via scaling and quantization, and a language model is trained on these tokens using the cross-entropy loss. Once trained, probabilistic forecasts are obtained by sampling multiple future trajectories given the historical context. Chronos models have been trained on a large corpus of publicly available time series data, as well as synthetic data generated using Gaussian processes.

For details on Chronos models, training data and procedures, and experimental results, please refer to the paper Chronos: Learning the Language of Time Series.


Fig. 1: High-level depiction of Chronos. (Left) The input time series is scaled and quantized to obtain a sequence of tokens. (Center) The tokens are fed into a language model which may either be an encoder-decoder or a decoder-only model. The model is trained using the cross-entropy loss. (Right) During inference, we autoregressively sample tokens from the model and map them back to numerical values. Multiple trajectories are sampled to obtain a predictive distribution.

Architecture

The models in this repository are based on the T5 architecture. The only difference is in the vocabulary size: Chronos-T5 models use 4096 different tokens, compared to 32128 of the original T5 models, resulting in fewer parameters.

Zero-Shot Results

The following figure showcases the remarkable zero-shot performance of Chronos and Chronos-Bolt models on 27 datasets against local models, task-specific models and other pretrained models. For details on the evaluation setup and other results, please refer to the paper.


Fig. 2: Performance of different models on Benchmark II, comprising 27 datasets not seen by Chronos and Chronos-Bolt models during training. This benchmark provides insights into the zero-shot performance of Chronos and Chronos-Bolt models against local statistical models, which fit parameters individually for each time series, task-specific models trained on each task, and pretrained models trained on a large corpus of time series. Pretrained Models (Other) indicates that some (or all) of the datasets in Benchmark II may have been in the training corpus of these models. The probabilistic (WQL) and point (MASE) forecasting metrics were normalized using the scores of the Seasonal Naive baseline and aggregated through a geometric mean to obtain the Agg. Relative WQL and MASE, respectively.

📈 Usage

To perform inference with Chronos or Chronos-Bolt models, the easiest way is to install this package through pip:

pip install chronos-forecasting

If you're interested in pretraining, fine-tuning, and other research & development, clone and install the package from source:

# Clone the repository
git clone https://github.com/amazon-science/chronos-forecasting.git

# Install in editable mode with extra training-related dependencies
cd chronos-forecasting && pip install --editable ".[training]"

[!TIP] This repository is intended for research purposes and provides a minimal interface to Chronos models. For reliable production use, we recommend the following options:

  • AutoGluon provides effortless fine-tuning, augmenting Chronos models with exogenous information through covariate regressors, ensembling with other statistical and machine learning models. Check out the AutoGluon Chronos tutorial.
  • SageMaker JumpStart makes it easy to deploy Chronos inference endpoints to AWS with just a few lines of code. Check out this tutorial for more details.

Forecasting

A minimal example showing how to perform forecasting using Chronos and Chronos-Bolt models:

import pandas as pd  # requires: pip install pandas
import torch
from chronos import BaseChronosPipeline

pipeline = BaseChronosPipeline.from_pretrained(
    "amazon/chronos-t5-small",  # use "amazon/chronos-bolt-small" for the corresponding Chronos-Bolt model
    device_map="cuda",  # use "cpu" for CPU inference
    torch_dtype=torch.bfloat16,
)

df = pd.read_csv(
    "https://raw.githubusercontent.com/AileenNielsen/TimeSeriesAnalysisWithPython/master/data/AirPassengers.csv"
)

# context must be either a 1D tensor, a list of 1D tensors,
# or a left-padded 2D tensor with batch as the first dimension
# quantiles is an fp32 tensor with shape [batch_size, prediction_length, num_quantile_levels]
# mean is an fp32 tensor with shape [batch_size, prediction_length]
quantiles, mean = pipeline.predict_quantiles(
    context=torch.tensor(df["#Passengers"]),
    prediction_length=12,
    quantile_levels=[0.1, 0.5, 0.9],
)

For the original Chronos models, pipeline.predict can be used to draw forecast samples. More options for predict_kwargs in pipeline.predict_quantiles can be found with:

from chronos import ChronosPipeline, ChronosBoltPipeline

print(ChronosPipeline.predict.__doc__)  # for Chronos models
print(ChronosBoltPipeline.predict.__doc__)  # for Chronos-Bolt models

We can now visualize the forecast:

import matplotlib.pyplot as plt  # requires: pip install matplotlib

forecast_index = range(len(df), len(df) + 12)
low, median, high = quantiles[0, :, 0], quantiles[0, :, 1], quantiles[0, :, 2]

plt.figure(figsize=(8, 4))
plt.plot(df["#Passengers"], color="royalblue", label="historical data")
plt.plot(forecast_index, median, color="tomato", label="median forecast")
plt.fill_between(forecast_index, low, high, color="tomato", alpha=0.3, label="80% prediction interval")
plt.legend()
plt.grid()
plt.show()

Extracting Encoder Embeddings

A minimal example showing how to extract encoder embeddings from Chronos models:

import pandas as pd
import torch
from chronos import ChronosPipeline

pipeline = ChronosPipeline.from_pretrained(
    "amazon/chronos-t5-small",
    device_map="cuda",
    torch_dtype=torch.bfloat16,
)

df = pd.read_csv("https://raw.githubusercontent.com/AileenNielsen/TimeSeriesAnalysisWithPython/master/data/AirPassengers.csv")

# context must be either a 1D tensor, a list of 1D tensors,
# or a left-padded 2D tensor with batch as the first dimension
context = torch.tensor(df["#Passengers"])
embeddings, tokenizer_state = pipeline.embed(context)

Pretraining, fine-tuning and evaluation

Scripts for pretraining, fine-tuning and evaluating Chronos models can be found in this folder.

:floppy_disk: Datasets

Datasets used in the Chronos paper for pretraining and evaluation (both in-domain and zero-shot) are available through the HuggingFace repos: autogluon/chronos_datasets and autogluon/chronos_datasets_extra. Check out these repos for instructions on how to download and use the datasets.

🔥 Coverage

📝 Citation

If you find Chronos models useful for your research, please consider citing the associated paper:

@article{ansari2024chronos,
  title={Chronos: Learning the Language of Time Series},
  author={Ansari, Abdul Fatir and Stella, Lorenzo and Turkmen, Caner and Zhang, Xiyuan, and Mercado, Pedro and Shen, Huibin and Shchur, Oleksandr and Rangapuram, Syama Syndar and Pineda Arango, Sebastian and Kapoor, Shubham and Zschiegner, Jasper and Maddix, Danielle C. and Mahoney, Michael W. and Torkkola, Kari and Gordon Wilson, Andrew and Bohlke-Schneider, Michael and Wang, Yuyang},
  journal={Transactions on Machine Learning Research},
  issn={2835-8856},
  year={2024},
  url={https://openreview.net/forum?id=gerNCVqqtR}
}

🛡️ Security

See CONTRIBUTING for more information.

📃 License

This project is licensed under the Apache-2.0 License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chronos_forecasting-1.5.1.tar.gz (531.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chronos_forecasting-1.5.1-py3-none-any.whl (29.4 kB view details)

Uploaded Python 3

File details

Details for the file chronos_forecasting-1.5.1.tar.gz.

File metadata

  • Download URL: chronos_forecasting-1.5.1.tar.gz
  • Upload date:
  • Size: 531.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for chronos_forecasting-1.5.1.tar.gz
Algorithm Hash digest
SHA256 060f95a1b8c17d703311515865dbd7e9fb1164439f0773300d4c21947695979f
MD5 d84e83c993ba91523b028f4daf34a9b3
BLAKE2b-256 49a37703519415a58b84b886887713f310c50b5b064328bc1aaf25dffe993a39

See more details on using hashes here.

Provenance

The following attestation bundles were made for chronos_forecasting-1.5.1.tar.gz:

Publisher: publish-to-pypi.yml on amazon-science/chronos-forecasting

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chronos_forecasting-1.5.1-py3-none-any.whl.

File metadata

File hashes

Hashes for chronos_forecasting-1.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 97a4d7c5271a24568c9a1e23dba27a7152a80c7251efaa1cfd959d437666676f
MD5 c37846a6bf491f87c38baba6985fff2d
BLAKE2b-256 37d1f2dc05772f2b59147cac9e2b26944444e8b87b7923f556711584e0b712ee

See more details on using hashes here.

Provenance

The following attestation bundles were made for chronos_forecasting-1.5.1-py3-none-any.whl:

Publisher: publish-to-pypi.yml on amazon-science/chronos-forecasting

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page