Forecasting, backtesting, anomaly detection, and capacity planning with time-series foundation models.

Time series models

Tutorials for forecasting and monitoring time series with Timestral, Mistral AI’s family of time-series foundation models.

Timestral forecasts any series zero-shot, with no training on your data. It reads up to 32,768 steps of history, forecasts several variates jointly, and conditions on covariates: past-only, known-future, and categorical. Every forecast is probabilistic, with 21 quantile levels from 0.01 to 0.99. The four checkpoints share one architecture and differ only in size:

Checkpoint Hugging Face repo Weights
Timestral-5M mistralai/Timestral-5M 21 MB
Timestral-28M mistralai/Timestral-28M 111 MB
Timestral-123M mistralai/Timestral-123M 490 MB
Timestral-209M mistralai/Timestral-209M 837 MB

All four run on CPU, so the tutorials scale out across CPU tasks and app replicas instead of GPUs.

Setup

The code for all four tutorials is in one directory and shares a common.py module with the container image, model loading, and metrics.

git clone https://github.com/unionai/unionai-examples
cd unionai-examples/v2/tutorials/timestral
pip install "flyte>=2.12.0" fastapi uvicorn numpy
flyte create config --endpoint <your-endpoint> --project <your-project> --domain development --builder local --registry <your-registry>

Replace <your-endpoint> with your Flyte endpoint and <your-registry> with a container registry your cluster can pull from, such as ghcr.io/<your-org>. Images are built on your machine and pushed to that registry, so Docker must be running and logged in to it (docker login ghcr.io).

The container image

Timestral isn’t on PyPI, so the image installs it from GitHub, pinned to a commit so every task and every replica loads the same code. A CPU build of PyTorch keeps the image small.

common.py
# Timestral installs from GitHub, pinned to a commit so every task in every run
# loads the same code. A CPU build of torch keeps the image small: Timestral does
# not need a GPU.
TIMESTRAL_COMMIT = "a534bdbd244d64f3d9d743f46c7bf6fc330ed4ff"

timestral_image = (
    flyte.Image.from_debian_base(name="timestral", python_version=(3, 12))
    .with_apt_packages("git")
    .with_pip_packages("torch", index_url="https://download.pytorch.org/whl/cpu")
    .with_pip_packages(
        f"timestral @ git+https://github.com/mistralai/timestral.git@{TIMESTRAL_COMMIT}",
        "numpy",
        "pandas",
        "pyarrow",
        "httpx",
    )
)

Loading a checkpoint

load_forecaster loads each checkpoint once per process. Within a task, every forecast reuses the loaded model. In an app, every request on a replica reuses it. num_threads sets the PyTorch thread count to the CPUs the task or app requests. Inside a pod, os.cpu_count() reports the node’s cores, not the pod’s CPU quota, and threads beyond the quota get throttled.

common.py
@functools.lru_cache(maxsize=4)
def load_forecaster(model_id: str, num_threads: int):
    """Load a Timestral checkpoint once per process.

    The cache matters when a container serves many forecasts: an app replica, or a
    task environment whose containers are reused across tasks.

    `num_threads` should match the CPUs the task or app requests. Inside a pod,
    `os.cpu_count()` reports the node's cores, not the pod's CPU quota, and more
    torch threads than the quota allows get throttled.
    """
    import torch
    from timestral import TimestralForecaster

    torch.set_num_threads(num_threads)
    return TimestralForecaster.from_pretrained(model_id, device="cpu")

A forecast takes a context array shaped (series, variates, time), or (series, time) for one variate. NaN marks a missing value. The result holds a quantile tensor shaped (series, variates, horizon, 21):

forecaster = load_forecaster("mistralai/Timestral-28M", num_threads=4)
forecast = forecaster.forecast(context, prediction_length=168)
forecast.quantiles  # (series, variates, 168, 21)
forecast.median     # (series, variates, 168)

Measuring accuracy

The tutorials score forecasts with two metrics from the GIFT-Eval benchmark. MASE compares the median forecast’s error to a seasonal-naive forecast, so a value below 1.0 beats “same as last season”. WQL, weighted quantile loss, scores all 21 quantiles, so it rewards well-calibrated uncertainty as well as an accurate median.

common.py
def mase(actual, median, history, season: int) -> float:
    """Mean absolute scaled error: forecast MAE divided by the in-sample MAE of a
    seasonal-naive forecast. Below 1.0 beats "same as last season"."""
    import numpy as np

    scale = np.nanmean(np.abs(history[season:] - history[:-season]))
    if not np.isfinite(scale) or scale == 0:
        return float("nan")
    return float(np.nanmean(np.abs(actual - median)) / scale)

def weighted_quantile_loss(actual, quantiles) -> float:
    """Weighted quantile loss (WQL), the probabilistic metric used by GIFT-Eval:
    pinball loss summed over quantile levels, normalized by the actuals.

    ``actual`` is (horizon,), ``quantiles`` is (horizon, 21).
    """
    import numpy as np

    levels = np.asarray(QUANTILE_LEVELS)
    diff = actual[:, None] - quantiles
    pinball = np.maximum(levels * diff, (levels - 1) * diff)
    denom = np.nansum(np.abs(actual))
    if denom == 0:
        return float("nan")
    return float(2 * np.nansum(pinball) / denom / len(levels))

Durability in these tutorials

Each tutorial uses Flyte features that keep a forecasting workload correct when something fails. Some protect the logic of a run, so work is never repeated or lost. Others protect the infrastructure, so a failed node or a traffic spike doesn’t take the workload down.

Feature What it protects Tutorial
Task caching A re-run skips every shard, download, and API call that already finished. Batch, capacity planning
Intra-task checkpoints A preempted task resumes from its last completed backtest window. Batch
Retries Batch tasks on spot capacity retry after a preemption, and capacity planning retries the rate-limited weather API with backoff. Batch, capacity planning
Traces and durable sleep A crashed loop replays completed steps from the record, without re-reading, re-forecasting, or re-alerting. Anomaly monitoring
External conditions A run pauses for a typed human decision, with a timeout and a default. Anomaly monitoring, capacity planning
Triggers A deployed task runs on a schedule. Anomaly monitoring
App scaling and run outputs A warm, autoscaling API serves the model a pipeline selected. Online API