Backtest every Timestral checkpoint on 321 electricity customers, pick the most accurate one, and forecast every series with it.

Batch forecasting and backtesting

Code available on GitHub. See Time series models for setup, the container image, and the metrics.

This tutorial forecasts next week’s hourly electricity consumption for 321 customers. It first backtests all four Timestral checkpoints on the last four weeks of history, picks the one with the lowest weighted quantile loss, and then forecasts every customer with it.

The work fans out into one task per model and shard of customers. Each task is cached, retried on spot capacity, and checkpointed, so:

  • a re-run of the pipeline skips every shard that already finished,
  • a preempted shard resumes from its last completed backtest window, and
  • the driver that coordinates them stays small and on on-demand capacity.
            flowchart LR
    D[load_dataset<br/>cached] --> B
    subgraph B[backtest]
      direction TB
      B1["5M × 8 shards"]
      B2["28M × 8 shards"]
      B3["123M × 8 shards"]
      B4["209M × 8 shards"]
    end
    B --> C{lowest WQL}
    C --> F["forecast_shard × 8<br/>champion model"]
    F --> O[forecasts.parquet<br/>+ report]
        

Run it

python batch_forecasting.py

The script runs the pipeline on the first 32 customers. To forecast all 321, pass n_series=0:

flyte run batch_forecasting.py forecast_pipeline --n_series 0

The data

The Monash electricity dataset holds three years of hourly consumption, in kW, for 321 customers. Each row of the Parquet file is one customer, with its timestamps and values stored as arrays.

batch_forecasting.py
# Hourly electricity consumption (kW) for 321 customers, 2012-2014, from the
# Monash forecasting archive.
DATA_URL = (
    "https://huggingface.co/datasets/autogluon/chronos_datasets/resolve/main/"
    "monash_electricity_hourly/train-00000-of-00001.parquet"
)
SEASON = 24  # daily seasonality, for the seasonal-naive MASE baseline

load_dataset copies the file into object storage once. Because it’s cached, every later run of the pipeline reads the stored copy instead of downloading it again. Each shard task then reads only its own customers from that file.

batch_forecasting.py
@forecast_env.task(cache="auto", retries=3)
async def load_dataset(url: str = DATA_URL) -> flyte.io.File:
    """Copy the dataset into object storage once. Later runs hit the cache."""
    local = Path(tempfile.mkdtemp()) / "electricity_hourly.parquet"
    urllib.request.urlretrieve(url, local)
    return await flyte.io.File.from_local(str(local))

Two environments

Forecasting runs in a CPU environment. interruptible=True lets those tasks run on spot capacity. The driver only coordinates the run and renders the report, so it gets a separate small environment that isn’t interruptible. A preemption then costs one shard, never the whole run.

batch_forecasting.py
# Forecasting tasks run on CPU. `interruptible=True` lets them use spot capacity;
# retries absorb preemptions, and checkpoints keep the work already done.
FORECAST_CPUS = 4

forecast_env = flyte.TaskEnvironment(
    name="timestral-batch",
    image=timestral_image,
    resources=flyte.Resources(cpu=FORECAST_CPUS, memory="8Gi"),
    interruptible=True,
)

# The driver only orchestrates and renders the report, so it stays small and
# on on-demand capacity.
driver_env = flyte.TaskEnvironment(
    name="timestral-batch-driver",
    image=timestral_image,
    resources=flyte.Resources(cpu=1, memory="2Gi"),
    depends_on=[forecast_env],
)

Backtest one shard

backtest_shard scores one checkpoint on one shard of customers. For each backtest window, it forecasts horizon hours from the context_length hours before the cutoff, then scores the forecast against what happened. All customers in the shard go through the model in one batched call.

batch_forecasting.py
@forecast_env.task(cache="auto", retries=3)
async def backtest_shard(
    data: flyte.io.File,
    series_ids: list[str],
    model: str,
    cutoffs: list[int],
    context_length: int,
    horizon: int,
) -> ShardScore:
    """Score one model on one shard of series over several backtest windows."""
    import numpy as np

    _, _, values = await read_series(data, series_ids)
    forecaster = load_forecaster(TIMESTRAL_MODELS[model], FORECAST_CPUS)

    # Resume from the windows a previous attempt already scored.
    checkpoint = flyte.ctx().checkpoint
    done: dict[str, dict] = {}
    if checkpoint is not None and (prev := await checkpoint.load()) is not None:
        done = json.loads(prev.read_bytes())

    for cutoff in cutoffs:
        if str(cutoff) in done:
            continue
        context = values[:, cutoff - context_length : cutoff]
        actual = values[:, cutoff : cutoff + horizon]

        start = time.perf_counter()
        forecast = forecaster.forecast(context, prediction_length=horizon)
        seconds = time.perf_counter() - start

        quantiles = forecast.quantiles[:, 0].numpy()  # (series, horizon, 21)
        median = forecast.median[:, 0].numpy()  # (series, horizon)
        done[str(cutoff)] = {
            "mase": [
                mase(actual[i], median[i], context[i], SEASON) for i in range(len(series_ids))
            ],
            "wql": [
                weighted_quantile_loss(actual[i], quantiles[i]) for i in range(len(series_ids))
            ],
            "seconds": seconds,
        }
        if checkpoint is not None:
            await checkpoint.save(json.dumps(done).encode())

    return ShardScore(
        model=model,
        n_forecasts=sum(len(w["mase"]) for w in done.values()),
        mase=float(np.nanmean([m for w in done.values() for m in w["mase"]])),
        wql=float(np.nanmean([q for w in done.values() for q in w["wql"]])),
        seconds=sum(w["seconds"] for w in done.values()),
    )

Three layers make this task durable:

  • Caching. cache="auto" keys the result on the task’s inputs: the dataset, the customer IDs, the model, and the windows. Re-run the pipeline after adding a checkpoint and only the new checkpoint’s shards execute.
  • Retries. retries=3 re-runs the task after a preemption, an out-of-memory kill, or a failed weight download.
  • Checkpoints. After each window, the task saves the scores so far with flyte.ctx().checkpoint. A retry loads them and skips the finished windows. See Intra-task checkpoints.

Fan out the backtest

backtest launches every model and shard pair at once with asyncio.gather. Each checkpoint’s tasks are grouped in the UI with flyte.group, and the per-shard scores are combined into one score per checkpoint, weighted by the number of forecasts.

batch_forecasting.py
@driver_env.task
async def backtest(
    data: flyte.io.File,
    series_ids: list[str],
    models: list[str],
    n_shards: int,
    n_windows: int,
    context_length: int,
    horizon: int,
    series_length: int,
) -> list[ModelScore]:
    """Fan out every (model, shard) pair and aggregate a leaderboard."""
    # Rolling-origin backtest: the last `n_windows` horizons of each series.
    cutoffs = [series_length - horizon * k for k in range(n_windows, 0, -1)]
    shards = shard(series_ids, n_shards)

    async def score_model(model: str) -> ModelScore:
        with flyte.group(f"backtest-{model}"):
            results = await asyncio.gather(
                *(
                    backtest_shard(data, ids, model, cutoffs, context_length, horizon)
                    for ids in shards
                )
            )
        n = sum(r.n_forecasts for r in results)
        return ModelScore(
            model=model,
            n_forecasts=n,
            mase=sum(r.mase * r.n_forecasts for r in results) / n,
            wql=sum(r.wql * r.n_forecasts for r in results) / n,
            ms_per_series=1000 * sum(r.seconds for r in results) / n,
        )

    return list(await asyncio.gather(*(score_model(m) for m in models)))

The cutoffs are a rolling origin: the last n_windows one-week windows of each series. Each window’s context ends where the window begins, so no forecast sees the values it’s scored against.

Forecast with the champion

forecast_shard forecasts the week after the data ends, for one shard, and writes all 21 quantiles per hour to Parquet.

batch_forecasting.py
@forecast_env.task(cache="auto", retries=3)
async def forecast_shard(
    data: flyte.io.File,
    series_ids: list[str],
    model: str,
    context_length: int,
    horizon: int,
) -> flyte.io.File:
    """Forecast the next `horizon` steps for a shard and write them as Parquet."""
    import numpy as np
    import pandas as pd

    ids, timestamps, values = await read_series(data, series_ids)
    forecaster = load_forecaster(TIMESTRAL_MODELS[model], FORECAST_CPUS)
    forecast = forecaster.forecast(values[:, -context_length:], prediction_length=horizon)
    quantiles = forecast.quantiles[:, 0].numpy()  # (series, horizon, 21)

    future = pd.date_range(timestamps[-1], periods=horizon + 1, freq="h")[1:]
    frame = pd.DataFrame(
        {
            "id": np.repeat(ids, horizon),
            "timestamp": np.tile(future, len(ids)),
            **{
                f"q{level:g}": quantiles[:, :, k].ravel()
                for k, level in enumerate(QUANTILE_LEVELS)
            },
        }
    )
    out = Path(tempfile.mkdtemp()) / f"forecast_{model}_{ids[0]}.parquet"
    frame.to_parquet(out)
    return await flyte.io.File.from_local(str(out))

The pipeline task ties the steps together. It picks the checkpoint with the lowest WQL, forecasts every shard with it, and returns two outputs: the champion’s Hugging Face repo ID and the combined forecasts.

batch_forecasting.py
@driver_env.task(report=True)
async def forecast_pipeline(
    models: list[str] = list(TIMESTRAL_MODELS),
    n_series: int = 0,
    n_shards: int = 8,
    n_windows: int = 4,
    context_length: int = 2048,
    horizon: int = 168,
) -> tuple[str, flyte.io.File]:
    """Backtest all models, pick the champion by WQL, forecast every series with it.

    Returns the champion's Hugging Face repo id and a Parquet file of forecasts.
    """
    import pandas as pd

    data = await load_dataset()
    path = await data.download()
    meta = pd.read_parquet(path, columns=["id"])
    series_ids = meta["id"].tolist()[: n_series or None]
    series_length = len(
        pd.read_parquet(path, filters=[("id", "==", series_ids[0])])["target"].iloc[0]
    )

    scores = await backtest(
        data, series_ids, models, n_shards, n_windows, context_length, horizon, series_length
    )
    champion = min(scores, key=lambda s: s.wql)

    with flyte.group(f"forecast-{champion.model}"):
        shard_files = await asyncio.gather(
            *(
                forecast_shard(data, ids, champion.model, context_length, horizon)
                for ids in shard(series_ids, n_shards)
            )
        )
    frames = [pd.read_parquet(await f.download()) for f in shard_files]
    forecasts = pd.concat(frames, ignore_index=True)
    out = Path(tempfile.mkdtemp()) / "forecasts.parquet"
    forecasts.to_parquet(out)
    forecasts_file = await flyte.io.File.from_local(str(out))

    await render_report(path, scores, champion, forecasts, horizon)
    return TIMESTRAL_MODELS[champion.model], forecasts_file

The run’s report shows the leaderboard and fan charts for a few customers: history in grey, the median forecast, and the 10-90% and 1-99% bands.

The first output is a plain string, so the online forecasting API can be deployed to serve whichever checkpoint the latest run of this pipeline picked.

Scale it up

  • More series. n_shards fixes the number of shards, so each shard’s work grows with the dataset. For larger datasets, raise n_shards so each task stays a few minutes long. A shorter task loses less work to a preemption.
  • Longer context. Timestral reads up to 32,768 steps. A longer context_length costs more compute per forecast but lets the model see yearly seasonality in hourly data.