# How to Perform Zero-Shot Forecasting with TimesFM: A Complete Implementation Guide

> Learn how to perform zero-shot forecasting with TimesFM using our implementation guide. Configure hyperparameters, load checkpoints, and forecast raw time-series data easily with this powerful tool.

- Repository: [Google Research/timesfm](https://github.com/google-research/timesfm)
- Tags: how-to-guide
- Published: 2026-04-02

---

**Zero-shot forecasting with TimesFM requires only three steps: configure inference hyperparameters with `TimesFmHparams`, load a pretrained checkpoint via `TimesFmCheckpoint`, and call the `forecast` method on your raw time-series data—no training or fine-tuning required.**

The google-research/timesfm repository provides a foundation model for time-series forecasting capable of generating predictions on entirely new datasets without additional training. By leveraging pretrained checkpoints hosted on Hugging Face, you can execute zero-shot forecasting through a unified Python API that abstracts backend differences between PyTorch and Flax. This guide breaks down the exact source code implementation to help you run inference correctly.

## Understanding the Zero-Shot Architecture

TimesFM separates inference logic into a shared abstraction and backend-specific implementations. The `TimesFmBase` class in [`v1/src/timesfm/timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/v1/src/timesfm/timesfm_base.py) handles preprocessing, padding, and the high-level `forecast` method (line 447), while `TimesFmTorch` in [`v1/src/timesfm/timesfm_torch.py`](https://github.com/google-research/timesfm/blob/main/v1/src/timesfm/timesfm_torch.py) manages PyTorch-specific checkpoint loading and decoder invocation. This architecture allows the same zero-shot workflow to function across different computational backends.

## Configuring the Inference Pipeline

### Define Hyperparameters with TimesFmHparams

Located in [`v1/src/timesfm/timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/v1/src/timesfm/timesfm_base.py) around line 145, the `TimesFmHparams` dataclass specifies the minimal configuration required for inference. You must set the prediction horizon, context window, and desired quantiles.

Key parameters include:

- `horizon_len`: Number of future steps to predict
- `context_len`: Maximum historical steps the model observes (typically 512 for the 200M checkpoint)
- `quantiles`: Tuple of quantile levels for probabilistic forecasts
- `point_forecast_mode`: Either `"median"` or `"mean"` for the deterministic output

### Specify Checkpoints with TimesFmCheckpoint

The `TimesFmCheckpoint` class (line 185 in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py)) defines where to fetch pretrained weights. For zero-shot forecasting, point this to a public Hugging Face repository. The `google/timesfm-1.0-200m-pytorch` checkpoint is the recommended starting point for PyTorch users.

When you instantiate the model, the constructor automatically invokes `load_from_checkpoint`, which downloads weights and initializes the transformer decoder defined in [`v1/src/timesfm/pytorch_patched_decoder.py`](https://github.com/google-research/timesfm/blob/main/v1/src/timesfm/pytorch_patched_decoder.py).

### Instantiate the Backend

Import the top-level API from [`src/timesfm/__init__.py`](https://github.com/google-research/timesfm/blob/main/src/timesfm/__init__.py) and create a model instance. By default, this uses the PyTorch backend (`TimesFmTorch`), though a Flax implementation (`TimesFmJax`) exists for JAX users.

```python
import timesfm

model = timesfm.TimesFm(
    hparams=timesfm.TimesFmHparams(
        horizon_len=12,
        context_len=512,
        quantiles=[0.1, 0.5, 0.9],
        point_forecast_mode="median"
    ),
    checkpoint=timesfm.TimesFmCheckpoint(
        huggingface_repo_id="google/timesfm-1.0-200m-pytorch"
    )
)

```

## Executing Zero-Shot Forecasts

### Preparing Input Series

The `forecast` method expects a list of one-dimensional NumPy arrays with `float32` dtype. Each array represents a single time series. The implementation in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py) automatically handles missing values through linear interpolation (see `strip_leading_nans` and interpolation utilities), but you should ensure your data contains at least one valid observation.

```python
import numpy as np
import pandas as pd

# Load your data

df = pd.read_csv("timeseries.csv")
raw_values = df["value"].values.astype(np.float32)

# Wrap in a list (required even for single series)

inputs = [raw_values]

```

### Frequency Encoding and Mapping

TimesFM categorizes frequencies into three buckets: **0** (high frequency: daily, hourly), **1** (medium: weekly, monthly), and **2** (low: yearly, quarterly). Pass these integer codes directly to `forecast`, or use the `freq_map` helper function (line 53 in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py)) to convert Pandas frequency strings.

```python

# High frequency encoding (e.g., daily data)

freqs = [0]

```

### The forecast Method Deep Dive

The `forecast` method (line 447 in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py)) orchestrates the full inference pipeline:

1. Preprocesses inputs (padding, frequency encoding, NaN handling)
2. Delegates to `_forecast` for backend-specific model invocation
3. Post-processes outputs to extract point forecasts and quantile distributions

The method returns a tuple of `(point_forecast, quantile_forecast)`. The point forecast shape is `(num_series, horizon_len)`, while quantiles have shape `(num_series, horizon_len, num_quantiles)`. Note that when extracting specific quantiles from the raw output, the first channel contains the mean, so quantile indices are offset by 1 (e.g., index 8 corresponds to the 0.9 quantile in the default configuration).

## Complete Code Example

The following minimal example demonstrates the full zero-shot pipeline, matching the reference implementation in [`timesfm-forecasting/examples/global-temperature/run_forecast.py`](https://github.com/google-research/timesfm/blob/main/timesfm-forecasting/examples/global-temperature/run_forecast.py):

```python
import numpy as np
import pandas as pd
import timesfm

# 1. Configure inference

hparams = timesfm.TimesFmHparams(
    horizon_len=12,
    context_len=512,
    quantiles=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99),
    point_forecast_mode="median"
)

# 2. Load pretrained checkpoint

checkpoint = timesfm.TimesFmCheckpoint(
    huggingface_repo_id="google/timesfm-1.0-200m-pytorch"
)

# 3. Initialize model

model = timesfm.TimesFm(hparams=hparams, checkpoint=checkpoint)

# 4. Prepare data

df = pd.read_csv("my_data.csv")
series = df["value"].values.astype(np.float32)
inputs = [series]
freqs = [0]  # High frequency

# 5. Run zero-shot inference

point_forecasts, quantile_forecasts = model.forecast(
    inputs=inputs,
    freq=freqs,
    window_size=None,  # No trend-residual decomposition

    normalize=False    # Keep original scale

)

print(f"Point forecast shape: {point_forecasts[0].shape}")  # (12,)

print(f"Quantile forecast shape: {quantile_forecasts[0].shape}")  # (12, 10)

# Extract 90th percentile (index 8 in default quantile list)

q90 = quantile_forecasts[0][:, 8]

```

## Handling Common Edge Cases

**Checkpoint Format Errors**: Newer checkpoint versions (v2.5+) store weights as `safetensors`, which are incompatible with `torch.load`. Use the `google/timesfm-1.0-200m-pytorch` checkpoint or convert the format manually to avoid load failures in [`timesfm_torch.py`](https://github.com/google-research/timesfm/blob/main/timesfm_torch.py).

**Missing Value Handling**: While the model linearly interpolates internal NaNs, long stretches of leading NaNs may produce empty arrays after preprocessing. Validate that your input contains sufficient valid data points before calling `forecast`.

**Quantile Indexing**: The raw tensor returned by the patched decoder places the mean in the first channel. When accessing quantiles directly from `quantile_forecasts`, remember that index `i` corresponds to your specified quantiles list, but the underlying tensor structure uses `[..., 1 + i]` for the actual quantile values versus the mean at `[..., 0]`.

**Device Selection**: The PyTorch backend defaults to GPU if CUDA is available, but you can force CPU by setting environment variables before instantiation. Mismatched device specifications will trigger runtime errors during the `load_from_checkpoint` phase.

## Summary

- **Zero-shot forecasting** requires only `TimesFmHparams`, `TimesFmCheckpoint`, and the `forecast` method—no training data or fine-tuning loops.
- The **shared base class** in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py) handles preprocessing and orchestration, while backend files like [`timesfm_torch.py`](https://github.com/google-research/timesfm/blob/main/timesfm_torch.py) manage model execution.
- **Input preparation** involves converting series to `float32` NumPy arrays and selecting the correct frequency bucket (0, 1, or 2).
- **Checkpoint loading** happens automatically during model instantiation, pulling weights directly from Hugging Face repositories like `google/timesfm-1.0-200m-pytorch`.
- **Output extraction** provides both point forecasts (median or mean) and full quantile distributions for probabilistic planning.

## Frequently Asked Questions

### What is zero-shot forecasting in TimesFM?

Zero-shot forecasting refers to generating predictions on new time-series datasets without any additional training or domain-specific fine-tuning. TimesFM achieves this by loading pretrained foundation model checkpoints that generalize across diverse temporal patterns, allowing immediate inference through the `forecast` method as implemented in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py).

### Do I need a GPU to run TimesFM zero-shot inference?

No, though GPUs significantly accelerate inference for long contexts or batch forecasting. The PyTorch backend in [`timesfm_torch.py`](https://github.com/google-research/timesfm/blob/main/timesfm_torch.py) automatically detects CUDA availability but falls back to CPU execution if necessary. You can verify device placement by checking tensor locations after the `load_from_checkpoint` call completes.

### How does TimesFM handle missing values in input series?

The preprocessing pipeline in [`timesfm_base.py`](https://github.com/google-research/timesfm/blob/main/timesfm_base.py) automatically applies linear interpolation to internal NaN values using `strip_leading_nans` and interpolation utilities. However, if your series contains extensive leading NaNs that exceed the context length, the method may return empty arrays. Ensure at least one valid observation exists or manually impute missing values before passing data to `forecast`.

### Where can I find official example scripts for zero-shot forecasting?

The repository provides a complete working example in [`timesfm-forecasting/examples/global-temperature/run_forecast.py`](https://github.com/google-research/timesfm/blob/main/timesfm-forecasting/examples/global-temperature/run_forecast.py), which demonstrates loading NOAA temperature data, configuring the model for zero-shot inference, and exporting results to CSV/JSON formats. This script follows the exact API patterns documented in the core library files.