Chronos Tutorial: Amazon's Time Series Foundation Model for Zero-Shot Forecasting
Chronos is a family of time series foundation models developed by Amazon Science. Unlike traditional forecasting models that require training on specific data, Chronos can perform zero-shot predictions — simply provide historical data, and the model generates forecasts without any fine-tuning. In this tutorial, we'll learn how to use Chronos for various real-world forecasting scenarios.
What is Chronos?
Chronos transforms the time series forecasting paradigm with an approach inspired by Large Language Models (LLMs). Instead of predicting numerical values directly, Chronos tokenizes time series values into discrete tokens using scaling and quantization, then trains a language model (based on the T5 architecture) on these tokens.
Key advantages of Chronos:
- Zero-shot forecasting: No training required on the target dataset
- Probabilistic forecasting: Produces prediction distributions, not just point estimates
- Multiple model sizes: From Tiny (8M parameters) to Large (710M parameters)
- Pretrained on public data: Trained on 27 public datasets plus synthetic data from Gaussian processes
- HuggingFace compatible: Easy to use through the Transformers ecosystem
Installation and Setup
System Requirements
- Python 3.9 or later
- PyTorch 2.0+
- GPU with at least 4GB VRAM (optional, CPU works too)
Package Installation
pip install chronos-forecasting
pip install torch
pip install pandas matplotlib
For NVIDIA GPU usage:
pip install torch --index-url https://download.pytorch.org/whl/cu121
pip install chronos-forecasting
Verify the installation:
import chronos
import torch
print(f"Chronos version: {chronos.version}")
print(f"PyTorch version: {torch.version}")
print(f"CUDA available: {torch.cuda.isavailable()}")
Basic Usage: Your First Forecast
Let's start with a simple example using synthetic data.
Making a Simple Prediction
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from chronos import ChronosPipeline
pipeline = ChronosPipeline.frompretrained(
"amazon/chronos-t5-small",
devicemap="auto",
torchdtype=torch.float32,
)
np.random.seed(42)
t = np.arange(0, 200)
trend = 0.05 t
seasonal = 10 np.sin(2 np.pi t / 30)
noise = np.random.normal(0, 1, len(t))
data = trend + seasonal + noise
context = torch.tensor(data, dtype=torch.float32)
forecast = pipeline.predict(
context=context,
predictionlength=30,
numsamples=20,
)
print(f"Forecast shape: {forecast.shape}")
Output: torch.Size([20, 30]) -> 20 samples, 30 time steps
Visualizing Forecast Results
forecastnp = forecast.numpy()
median
forecast = np.median(forecastnp, axis=0)
low
bound = np.percentile(forecastnp, 10, axis=0)
high
bound = np.percentile(forecastnp, 90, axis=0)
fig, ax = plt.subplots(figsize=(14, 6))
history
range = range(len(data))
forecastrange = range(len(data), len(data) + 30)
ax.plot(historyrange, data, color="blue", label="Historical Data")
ax.plot(forecastrange, medianforecast, color="red", label="Median Forecast")
ax.fillbetween(
forecastrange,
lowbound,
highbound,
color="red",
alpha=0.2,
label="80% Prediction Interval",
)
ax.setxlabel("Time")
ax.setylabel("Value")
ax.settitle("Chronos: Time Series Forecast")
ax.legend()
plt.tightlayout()
plt.savefig("chronosbasicforecast.png", dpi=150)
plt.show()
Choosing the Right Model
Chronos offers several model sizes. The choice depends on your accuracy needs and available resources.
| Model | Parameters | VRAM | Speed | Use Case |
|-------|-----------|------|-------|----------|
| chronos-t5-tiny | 8M | ~500MB | Very fast | Prototyping, edge devices |
| chronos-t5-mini | 20M | ~1GB | Fast | Development, batch processing |
| chronos-t5-small | 46M | ~2GB | Medium | Light production |
| chronos-t5-base | 200M | ~4GB | Slow | Standard production |
| chronos-t5-large | 710M | ~8GB | Very slow | Maximum accuracy |
modelnames = [
"amazon/chronos-t5-tiny",
"amazon/chronos-t5-mini",
"amazon/chronos-t5-small",
"amazon/chronos-t5-base",
"amazon/chronos-t5-large",
]
pipeline = ChronosPipeline.from
pretrained(
"amazon/chronos-t5-base",
devicemap="auto",
torchdtype=torch.bfloat16,
)
For GPUs with limited memory, use torchdtype=torch.bfloat16 or torch.float16 to reduce VRAM usage by up to half.
Advanced Usage
Forecasting with Real Data: Daily Sales
import pandas as pd
from chronos import ChronosPipeline
import torch
dates = pd.daterange("2024-01-01", periods=365, freq="D")
np.random.seed(42)
base = 1000
trend = np.linspace(0, 200, 365)
weekly = 150 np.sin(2 np.pi np.arange(365) / 7)
monthly = 300 np.sin(2 np.pi np.arange(365) / 30)
noise = np.random.normal(0, 50, 365)
sales = base + trend + weekly + monthly + noise
sales = np.maximum(sales, 0)
df = pd.DataFrame({"date": dates, "sales": sales})
pipeline = ChronosPipeline.frompretrained(
"amazon/chronos-t5-small",
devicemap="auto",
torchdtype=torch.float32,
)
context = torch.tensor(df["sales"].values, dtype=torch.float32)
forecast = pipeline.predict(
context=context,
predictionlength=30,
numsamples=50,
)
forecastdates = pd.daterange(
start=df["date"].iloc[-1] + pd.Timedelta(days=1),
periods=30,
freq="D",
)
forecastnp = forecast.numpy()
forecastdf = pd.DataFrame({
"date": forecastdates,
"median": np.median(forecastnp, axis=0),
"p10": np.percentile(forecastnp, 10, axis=0),
"p90": np.percentile(forecastnp, 90, axis=0),
})
print(forecastdf.head(10))
Batch Forecasting: Multiple Time Series at Once
Chronos supports batch prediction to process multiple time series simultaneously, which is far more efficient than predicting one at a time.
serieslist = []
num
series = 5
for i in range(numseries):
np.random.seed(i)
t = np.arange(0, 150)
base = np.random.uniform(50, 200)
amplitude = np.random.uniform(5, 30)
period = np.random.uniform(20, 50)
series = base + amplitude np.sin(2 np.pi t / period)
series += np.random.normal(0, 2, len(t))
serieslist.append(torch.tensor(series, dtype=torch.float32))
forecasts = pipeline.predict(
context=serieslist,
predictionlength=20,
numsamples=30,
)
print(f"Batch forecast shape: {forecasts.shape}")
Output: torch.Size([5, 30, 20]) -> 5 series, 30 samples, 20 steps
fig, axes = plt.subplots(1, numseries, figsize=(20, 4))
for i in range(numseries):
ax = axes[i]
history = serieslist[i].numpy()
fc = forecasts[i].numpy()
median = np.median(fc, axis=0)
p10 = np.percentile(fc, 10, axis=0)
p90 = np.percentile(fc, 90, axis=0)
hrange = range(len(history))
frange = range(len(history), len(history) + len(median))
ax.plot(hrange, history, color="blue", linewidth=0.8)
ax.plot(frange, median, color="red", linewidth=1.2)
ax.fillbetween(frange, p10, p90, color="red", alpha=0.2)
ax.settitle(f"Series {i+1}")
plt.tightlayout()
plt.savefig("chronosbatchforecast.png", dpi=150)
plt.show()
Handling Missing Values
Chronos can handle missing values (NaN) in historical data. The model will automatically interpolate the missing sections.
datawithgaps = data.copy()
datawithgaps[50:55] = np.nan
datawithgaps[100:110] = np.nan
datawithgaps[150:153] = np.nan
context = torch.tensor(datawithgaps, dtype=torch.float32)
forecast = pipeline.predict(
context=context,
predictionlength=30,
numsamples=20,
)
print("Forecast succeeded despite missing values!")
print(f"NaN count in input: {np.isnan(datawithgaps).sum()}")
Controlling Confidence Intervals
By adjusting numsamples, you can control the granularity of the prediction distribution.
for nsamples in [10, 50, 200]:
forecast = pipeline.predict(
context=context,
predictionlength=30,
numsamples=nsamples,
)
fc = forecast.numpy()
median = np.median(fc, axis=0)
p5 = np.percentile(fc, 5, axis=0)
p95 = np.percentile(fc, 95, axis=0)
width = np.mean(p95 - p5)
print(f"Samples={nsamples:3d} | Average interval width: {width:.2f}")
Adjusting Temperature for Variability Control
The temperature parameter controls how varied the prediction samples are. Higher temperature produces more diverse predictions, while lower temperature yields more conservative forecasts.
for temp in [0.5, 1.0, 1.5, 2.0]:
forecast = pipeline.predict(
context=context,
predictionlength=30,
numsamples=50,
temperature=temp,
)
fc = forecast.numpy()
spread = np.std(fc, axis=0).mean()
print(f"Temperature={temp:.1f} | Average std: {spread:.3f}")
Integration with Pandas and Data Science Workflows
Complete Forecasting Pipeline
import pandas as pd
import numpy as np
import torch
from chronos import ChronosPipeline
def forecastdataframe(
df: pd.DataFrame,
valuecol: str,
datecol: str,
horizon: int = 30,
model: str = "amazon/chronos-t5-small",
numsamples: int = 50,
) -> pd.DataFrame:
"""Generate forecast from a pandas DataFrame."""
pipeline = ChronosPipeline.frompretrained(
model, devicemap="auto", torchdtype=torch.float32
)
context = torch.tensor(df[valuecol].values, dtype=torch.float32)
forecast = pipeline.predict(
context=context,
predictionlength=horizon,
numsamples=numsamples,
)
forecastnp = forecast.numpy()
freq = pd.inferfreq(df[datecol])
if freq is None:
freq = "D"
futuredates = pd.daterange(
start=df[datecol].iloc[-1] + pd.tseries.frequencies.tooffset(freq),
periods=horizon,
freq=freq,
)
result = pd.DataFrame({
datecol: futuredates,
"forecastmedian": np.median(forecastnp, axis=0),
"forecastmean": np.mean(forecastnp, axis=0),
"forecastp10": np.percentile(forecastnp, 10, axis=0),
"forecastp25": np.percentile(forecastnp, 25, axis=0),
"forecastp75": np.percentile(forecastnp, 75, axis=0),
"forecastp90": np.percentile(forecastnp, 90, axis=0),
})
return result
df = pd.DataFrame({
"date": pd.daterange("2024-01-01", periods=365, freq="D"),
"revenue": np.cumsum(np.random.normal(100, 20, 365)),
})
forecastdf = forecastdataframe(
df, valuecol="revenue", datecol="date", horizon=30
)
print(forecastdf.head())
Model Evaluation with Backtesting
from sklearn.metrics import meanabsoluteerror, meansquarederror
def backtestchronos(
data: np.ndarray,
modelname: str = "amazon/chronos-t5-small",
testsize: int = 30,
numsamples: int = 50,
) -> dict:
"""Evaluate Chronos performance with train/test split."""
train = data[:-testsize]
test = data[-testsize:]
pipeline = ChronosPipeline.frompretrained(
modelname, devicemap="auto", torchdtype=torch.float32
)
context = torch.tensor(train, dtype=torch.float32)
forecast = pipeline.predict(
context=context,
predictionlength=testsize,
numsamples=numsamples,
)
forecastnp = forecast.numpy()
medianpred = np.median(forecastnp, axis=0)
mae = meanabsoluteerror(test, medianpred)
rmse = np.sqrt(meansquarederror(test, medianpred))
mape = np.mean(np.abs((test - medianpred) / (test + 1e-8))) 100
p10 = np.percentile(forecastnp, 10, axis=0)
p90 = np.percentile(forecastnp, 90, axis=0)
coverage = np.mean((test >= p10) & (test <= p90))
return {
"mae": mae,
"rmse": rmse,
"mape": mape,
"coverage80": coverage,
"predictions": medianpred,
"actuals": test,
}
t = np.arange(0, 300)
data = 50 + 0.1 t + 10 np.sin(2 np.pi t / 30) + np.random.normal(0, 2, 300)
results = backtestchronos(data)
print(f"MAE: {results['mae']:.2f}")
print(f"RMSE: {results['rmse']:.2f}")
print(f"MAPE: {results['mape']:.2f}%")
print(f"Coverage 80%: {results['coverage80']:.2%}")
Comparison with Statistical Models
from statsmodels.tsa.holtwinters import ExponentialSmoothing
def comparemodels(data, testsize=30):
train = data[:-testsize]
test = data[-testsize:]
pipeline = ChronosPipeline.frompretrained(
"amazon/chronos-t5-small",
devicemap="auto",
torchdtype=torch.float32,
)
context = torch.tensor(train, dtype=torch.float32)
chronosforecast = pipeline.predict(
context=context, predictionlength=testsize, numsamples=50
)
chronospred = np.median(chronosforecast.numpy(), axis=0)
hwmodel = ExponentialSmoothing(
train, seasonalperiods=30, trend="add", seasonal="add"
).fit()
hwpred = hwmodel.forecast(testsize)
chronosmae = meanabsoluteerror(test, chronospred)
hwmae = meanabsoluteerror(test, hwpred)
print(f"{'Model':<25} {'MAE':>10}")
print("-" 37)
print(f"{'Chronos (T5-Small)':<25} {chronosmae:>10.2f}")
print(f"{'Holt-Winters':<25} {hwmae:>10.2f}")
return {
"chronosmae": chronosmae,
"hwmae": hwmae,
}
t = np.arange(0, 300)
data = 100 + 0.2 t + 20 np.sin(2 np.pi * t / 30) + np.random.normal(0, 3, 300)
comparemodels(data)
Best Practices
1. Data Preprocessing
def preprocessforchronos(series: pd.Series) -> torch.Tensor:
"""Preprocess time series before feeding to Chronos."""
values = series.values.astype(np.float64)
if np.isnan(values).all():
raise ValueError("All values are NaN")
if np.isinf(values).any():
values = np.where(np.isinf(values), np.nan, values)
return torch.tensor(values, dtype=torch.float32)
2. Performance Optimization
pipeline = ChronosPipeline.frompretrained(
"amazon/chronos-t5-base",
devicemap="auto",
torchdtype=torch.bfloat16,
)
with torch.inferencemode():
forecast = pipeline.predict(
context=context,
predictionlength=30,
numsamples=50,
)
3. Caching the Model for Multiple Predictions
class ChronosForecaster:
def init(self, modelname="amazon/chronos-t5-small"):
self.pipeline = ChronosPipeline.frompretrained(
modelname,
devicemap="auto",
torchdtype=torch.float32,
)
def forecast(self, data, horizon=30, numsamples=50):
context = torch.tensor(data, dtype=torch.float32)
return self.pipeline.predict(
context=context,
predictionlength=horizon,
numsamples=numsamples,
)
def forecastbatch(self, datalist, horizon=30, numsamples=50):
contexts = [
torch.tensor(d, dtype=torch.float32) for d in datalist
]
return self.pipeline.predict(
context=contexts,
predictionlength=horizon,
numsamples=numsamples,
)
forecaster = ChronosForecaster("amazon/chronos-t5-small")
seriesa = np.random.normal(100, 10, 200)
seriesb = np.random.normal(50, 5, 150)
fca = forecaster.forecast(seriesa, horizon=14)
fcb = forecaster.forecast(seriesb, horizon=14)
fcbatch = forecaster.forecastbatch([seriesa, seriesb], horizon=14)
4. Key Tips for Optimal Results
Context length: Provide enough historical data. Aim for at least 2-3 times the length of the seasonal cycle. For data with weekly patterns, provide at least 14-21 data points. Choose the right model size: For exploration and prototyping, usechronos-t5-tiny or chronos-t5-mini. For production, use chronos-t5-base or larger.
Use sufficient numsamples: At least 20 samples for stable prediction intervals. For critical business decisions, use 100+ samples.
Watch for data scale: Chronos handles scaling internally, but ensure there are no extreme outliers that could affect tokenization.
Always evaluate: Always perform backtesting on historical data before using forecasts for business decisions.
When to Use Chronos vs Other Models?
Use Chronos when:- You have many different time series and don't want to train separate models for each
- Historical data is limited and insufficient for training a model from scratch
- You need quick baseline forecasts without tuning
- Probabilistic forecasts (prediction intervals) are needed
- You have specific domain knowledge and important exogenous features (regressors)
- The dataset is very large and simple statistical models already perform well
- Latency is critical (statistical models like ETS are much faster)
- High model interpretability is required
Conclusion
Chronos brings a new paradigm to time series forecasting with its foundation model approach. Its zero-shot capability allows you to get reasonable forecasts without investing time in feature engineering and model tuning. While not a complete replacement for models specifically trained on particular domains, Chronos is a powerful tool as a baseline and for scenarios where deployment speed matters more than marginal accuracy gains.
Next steps to explore:
- Fine-tuning Chronos on your domain-specific dataset
- Comparing with other foundation models like TimesFM and Moirai
- Integrating Chronos into MLOps pipelines using tools like MLflow or Weights & Biases
- Building a forecasting API using FastAPI with Chronos as the backend