Skip to content

TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting.

Python
9.2 KB
Raw Blame
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TimesFM 3.0 PyTorch Inference Demo\n",
    "\n",
    "This interactive notebook demonstrates zero-shot time series forecasting using **TimesFM 3.0** (PyTorch).\n",
    "\n",
    "### Key Features Highlighted:\n",
    "1. **Promotion Example with Dynamic Covariates**: Context length = 2048, Forecast Horizon = 512 with dynamic past-future promotion indicator.\n",
    "2. **Synthetic Curves (Horizon > 64)**: Evaluating long horizons across sine waves and linear trend extrapolation.\n",
    "3. **GPU Acceleration**: Automatic CUDA inference with quantile uncertainty intervals."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setup and Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import torch\n",
    "\n",
    "from timesfm3 import TimesFM3Forecaster\n",
    "\n",
    "# Set random seeds for reproducibility\n",
    "np.random.seed(42)\n",
    "torch.manual_seed(42)\n",
    "\n",
    "print(f\"PyTorch version: {torch.__version__}\")\n",
    "print(f\"CUDA available: {torch.cuda.is_available()}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Initialize TimesFM 3.0 Forecaster\n",
    "\n",
    "We instantiate `TimesFM3Forecaster` from the default Hugging Face pretrained checkpoint (`google/timesfm-3.0-pytorch`).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load TimesFM 3.0 directly from Hugging Face Hub (default: \"google/timesfm-3.0-pytorch\")\n",
    "forecaster = TimesFM3Forecaster.from_pretrained(\n",
    "    \"google/timesfm-3.0-pytorch\",\n",
    "    per_core_batch_size=4,\n",
    ")\n",
    "\n",
    "print(f\"TimesFM3 forecaster loaded successfully on device: {forecaster.device}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Scenario 1: Promotion Example with Dynamic Covariates\n",
    "\n",
    "- **Context Length**: 2048\n",
    "- **Forecast Horizon**: 512\n",
    "- **Past-Future Covariates**: Binary promotion covariate (0 or 1) spanning the full length (2560 steps).\n",
    "- **Target Multiplier**: Target value is boosted by 5x during active promotions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "context_len = 2048\n",
    "horizon_len = 512\n",
    "total_len = context_len + horizon_len\n",
    "time = np.arange(total_len)\n",
    "\n",
    "# Generate promotion indicator\n",
    "promotions = np.zeros(total_len, dtype=np.float32)\n",
    "# Promotion in context\n",
    "promotions[1130:1180] = 1.0\n",
    "# Promotions in forecast horizon\n",
    "promotions[2250:2290] = 1.0\n",
    "promotions[2320:2355] = 1.0\n",
    "\n",
    "pfc_np = np.array([promotions], dtype=np.float32)\n",
    "\n",
    "# Generate base target: periodic sine + noise\n",
    "base_target = 2.0 + np.sin(time / 20.0) + np.random.randn(total_len) * 0.15\n",
    "# Apply 5x promo boost\n",
    "target_full = (base_target * np.where(promotions == 1.0, 5.0, 1.0)).astype(np.float32)\n",
    "\n",
    "context = target_full[:context_len]\n",
    "actual_horizon = target_full[context_len:]\n",
    "\n",
    "print(f\"Context shape: {context.shape}\")\n",
    "print(f\"Horizon length: {horizon_len}\")\n",
    "print(f\"Past-Future Covariates shape: {pfc_np.shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run zero-shot forecast with dynamic past-future covariates\n",
    "torch_out = forecaster.predict(\n",
    "    context=context,\n",
    "    horizon=horizon_len,\n",
    "    past_future_covariates=pfc_np,\n",
    "    return_quantiles=True,\n",
    ")\n",
    "\n",
    "print(\"Forecast generated successfully!\")\n",
    "print(f\"Point forecast shape: {torch_out.forecast.shape}\")\n",
    "print(f\"Quantiles shape: {torch_out.quantiles.shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot Promotion Example\n",
    "time_context = np.arange(context_len)\n",
    "time_horizon = np.arange(context_len, total_len)\n",
    "\n",
    "fig, axes = plt.subplots(2, 1, figsize=(16, 8), sharex=True)\n",
    "\n",
    "# Subplot 0: Target, Actual Horizon, and PyTorch Forecast\n",
    "axes[0].plot(time_context, context, label=\"Context (Input)\", color=\"black\", alpha=0.7, linewidth=1.2)\n",
    "axes[0].plot(time_horizon, actual_horizon, label=\"Actual Horizon (Ground Truth)\", linestyle=\"--\", color=\"gray\", alpha=0.8)\n",
    "axes[0].plot(time_horizon, torch_out.forecast, label=\"TimesFM3 Median Forecast (p50)\", color=\"#ff7f0e\", linewidth=2.5)\n",
    "if torch_out.quantiles is not None:\n",
    "    axes[0].fill_between(\n",
    "        time_horizon,\n",
    "        torch_out.quantiles[:, 0],\n",
    "        torch_out.quantiles[:, -1],\n",
    "        color=\"salmon\",\n",
    "        alpha=0.3,\n",
    "        label=\"p10-p90 Prediction Interval\",\n",
    "    )\n",
    "axes[0].set_title(\"TimesFM 3.0 Promotion Example Forecast (Context 2048, Horizon 512)\", fontsize=14)\n",
    "axes[0].set_ylabel(\"Target Value\", fontsize=12)\n",
    "axes[0].legend(loc=\"upper left\")\n",
    "axes[0].grid(True, alpha=0.3)\n",
    "\n",
    "# Subplot 1: Past-Future Promotion Covariate\n",
    "axes[1].plot(time, promotions, label=\"Promotion Indicator (0 or 1)\", color=\"green\", drawstyle=\"steps-mid\", linewidth=1.5)\n",
    "axes[1].fill_between(time, 0, promotions, color=\"green\", alpha=0.2)\n",
    "axes[1].set_title(\"Past-Future Covariate: Promotions Timeline\", fontsize=12)\n",
    "axes[1].set_ylabel(\"Promotion Active\", fontsize=12)\n",
    "axes[1].set_xlabel(\"Time Step (t)\", fontsize=12)\n",
    "axes[1].set_yticks([0, 1])\n",
    "axes[1].legend(loc=\"upper left\")\n",
    "axes[1].grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Scenario 2: Long Horizon Synthetic Curves (Horizon 128 > 64)\n",
    "\n",
    "Evaluates rolling patch autoregressive decoding across:\n",
    "1. **Sine Curve** (periodic continuation)\n",
    "2. **Linear Trend** (linear detrending extrapolation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "synth_context_len = 256\n",
    "synth_horizon_len = 128\n",
    "synth_total_len = synth_context_len + synth_horizon_len\n",
    "t_synth = np.linspace(0, 8 * np.pi, synth_total_len, dtype=np.float32)\n",
    "\n",
    "# Series 0: Sine wave\n",
    "s_sine = np.sin(t_synth)\n",
    "# Series 1: Linear trend line\n",
    "s_line = np.arange(synth_total_len, dtype=np.float32) * 0.05 + 2.0\n",
    "\n",
    "contexts = [s_sine[:synth_context_len], s_line[:synth_context_len]]\n",
    "ground_truths = [s_sine[synth_context_len:], s_line[synth_context_len:]]\n",
    "\n",
    "# Batch predict\n",
    "synth_outputs = list(forecaster.predict_batch(contexts, horizon=synth_horizon_len))\n",
    "\n",
    "# Compute metrics\n",
    "sine_mae = np.mean(np.abs(synth_outputs[0].forecast - ground_truths[0]))\n",
    "line_mae = np.mean(np.abs(synth_outputs[1].forecast - ground_truths[1]))\n",
    "\n",
    "print(f\"Sine Curve Mean Absolute Error: {sine_mae:.6f}\")\n",
    "print(f\"Linear Trend Mean Absolute Error: {line_mae:.6f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot Synthetic Curves\n",
    "fig, axes = plt.subplots(2, 1, figsize=(14, 8), sharex=True)\n",
    "t_ctx = np.arange(synth_context_len)\n",
    "t_hor = np.arange(synth_context_len, synth_total_len)\n",
    "titles = [\n",
    "    f\"Sine Curve Forecast (MAE: {sine_mae:.6f})\",\n",
    "    f\"Linear Trend Forecast (MAE: {line_mae:.6f})\",\n",
    "]\n",
    "\n",
    "for i, ax in enumerate(axes):\n",
    "    ax.plot(t_ctx, contexts[i], label=\"Context (Input)\", color=\"black\", linewidth=1.5)\n",
    "    ax.plot(t_hor, ground_truths[i], label=\"Ground Truth\", color=\"gray\", linestyle=\"--\", alpha=0.7)\n",
    "    ax.plot(t_hor, synth_outputs[i].forecast, label=\"TimesFM3 Forecast\", color=\"#ff7f0e\", linewidth=2.5)\n",
    "    ax.set_title(titles[i], fontsize=13)\n",
    "    ax.set_ylabel(\"Value\", fontsize=11)\n",
    "    ax.legend(loc=\"upper left\")\n",
    "    ax.grid(True, alpha=0.3)\n",
    "\n",
    "axes[1].set_xlabel(\"Time Step\", fontsize=12)\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}