File size: 8,274 Bytes
c4b87d2 0a58567 c4b87d2 0a58567 c4b87d2 0a58567 c4b87d2 0a58567 c4b87d2 0a58567 c4b87d2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
{
"cells": [
{
"cell_type": "markdown",
"id": "231c6227",
"metadata": {},
"source": [
"# Quick Start: Univariate Quantile Forecasting (CUDA, bfloat16)\n",
"\n",
"This notebook demonstrates how to:\n",
"- Generate synthetic sine wave time series data\n",
"- Pack data into `BatchTimeSeriesContainer`\n",
"- Load a pretrained model (from Dropbox)\n",
"- Run inference with bfloat16 on CUDA\n",
"- Visualize predictions\n"
]
},
{
"cell_type": "markdown",
"id": "bb6c5424-1c63-4cb0-a818-45d4199914e5",
"metadata": {},
"source": [
"## 1) Setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "612a78e8",
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"\n",
"import numpy as np\n",
"import torch\n",
"\n",
"# Ensure CUDA is available\n",
"if not torch.cuda.is_available():\n",
" raise RuntimeError(\"CUDA is required to run this demo. No CUDA device detected.\")\n",
"\n",
"device = torch.device(\"cuda:0\")\n",
"\n",
"# Resolve repository root to be robust to running from subdirectories (e.g., examples/)\n",
"repo_root = Path.cwd()\n",
"if not (repo_root / \"configs\").exists():\n",
" repo_root = repo_root.parent\n",
"\n",
"# Inline plotting\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"id": "3facf37d-0a77-4222-8464-6e42182547f8",
"metadata": {},
"source": [
"## 2) Define Checkpoint Path"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "16dcb883",
"metadata": {},
"outputs": [],
"source": [
"CHECKPOINT_DIR = repo_root / \"models\"\n",
"CHECKPOINT_NAME = \"checkpoint_38M.pth\"\n",
"CHECKPOINT_PATH = CHECKPOINT_DIR / CHECKPOINT_NAME\n",
"\n",
"# Ensure the models directory exists\n",
"CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)\n",
"\n",
"if not CHECKPOINT_PATH.exists():\n",
" print(f\"--- WARNING: Checkpoint not found at: {CHECKPOINT_PATH} ---\")\n",
" print(\"Please ensure 'checkpoint_38M.pth' is in the 'models/' directory.\")\n",
" print(\"If you cloned from Hugging Face, you may need to run 'git lfs pull'.\")\n",
" raise FileNotFoundError(f\"Model checkpoint not found at {CHECKPOINT_PATH}\")\n",
"else:\n",
" print(f\"Using existing checkpoint at {CHECKPOINT_PATH}\")"
]
},
{
"cell_type": "markdown",
"id": "9be77e34-0c7a-4056-822f-ed2e3e090c40",
"metadata": {},
"source": [
"## 3) Generate synthetic sine wave data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1127526c",
"metadata": {},
"outputs": [],
"source": [
"from src.synthetic_generation.generator_params import SineWaveGeneratorParams\n",
"from src.synthetic_generation.sine_waves.sine_wave_generator_wrapper import (\n",
" SineWaveGeneratorWrapper,\n",
")\n",
"\n",
"batch_size = 3\n",
"total_length = 1024\n",
"seed = 2025\n",
"\n",
"sine_params = SineWaveGeneratorParams(global_seed=seed, length=total_length)\n",
"wrapper = SineWaveGeneratorWrapper(sine_params)\n",
"\n",
"batch = wrapper.generate_batch(batch_size=batch_size, seed=seed)\n",
"values = torch.from_numpy(batch.values).to(torch.float32)\n",
"if values.ndim == 2:\n",
" values = values.unsqueeze(-1) # [B, S, 1]\n",
"\n",
"future_length = 256\n",
"history_values = values[:, :-future_length, :]\n",
"future_values = values[:, -future_length:, :]\n",
"\n",
"print(\"History:\", history_values.shape, \"Future:\", future_values.shape)"
]
},
{
"cell_type": "markdown",
"id": "a8844488-e51c-4805-baa9-491bfc67e8ca",
"metadata": {},
"source": [
"## 4) Build BatchTimeSeriesContainer"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f3b4d361",
"metadata": {},
"outputs": [],
"source": [
"from src.data.containers import BatchTimeSeriesContainer\n",
"\n",
"container = BatchTimeSeriesContainer(\n",
" history_values=history_values.to(device),\n",
" future_values=future_values.to(device),\n",
" start=batch.start,\n",
" frequency=batch.frequency,\n",
")\n",
"\n",
"container.batch_size, container.history_length, container.future_length"
]
},
{
"cell_type": "markdown",
"id": "b5e7e790-a9aa-49c2-9d45-2dc823036883",
"metadata": {},
"source": [
"## 5) Load model and run inference"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1dd4e0e4",
"metadata": {},
"outputs": [],
"source": [
"import yaml\n",
"from src.models.model import TimeSeriesModel\n",
"\n",
"with open(repo_root / \"configs/example.yaml\") as f:\n",
" config = yaml.safe_load(f)\n",
"\n",
"model = TimeSeriesModel(**config[\"TimeSeriesModel\"]).to(device)\n",
"ckpt = torch.load(CHECKPOINT_PATH, map_location=device)\n",
"model.load_state_dict(ckpt[\"model_state_dict\"])\n",
"model.eval()\n",
"\n",
"# bfloat16 autocast on CUDA\n",
"with (\n",
" torch.no_grad(),\n",
" torch.autocast(device_type=\"cuda\", dtype=torch.bfloat16, enabled=True),\n",
"):\n",
" output = model(container)\n",
"\n",
"preds = output[\"result\"].to(torch.float32)\n",
"if hasattr(model, \"scaler\") and \"scale_statistics\" in output:\n",
" preds = model.scaler.inverse_scale(preds, output[\"scale_statistics\"])\n",
"\n",
"preds.shape"
]
},
{
"cell_type": "markdown",
"id": "ba16120f-27c8-4462-91cb-c9b3e0630a9d",
"metadata": {},
"source": [
"## 6) Plot predictions"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9bf02a0b",
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"plt.set_loglevel(\"error\")\n",
"\n",
"# preds: [B, P, N, Q] for quantiles (univariate -> N=1)\n",
"preds_np = preds.cpu().numpy()\n",
"\n",
"batch_size = preds_np.shape[0]\n",
"prediction_length = preds_np.shape[1]\n",
"num_quantiles = preds_np.shape[-1]\n",
"\n",
"for i in range(batch_size):\n",
" fig, ax = plt.subplots(figsize=(12, 4))\n",
"\n",
" history = container.history_values[i, :, 0].detach().cpu().numpy()\n",
" future = container.future_values[i, :, 0].detach().cpu().numpy()\n",
"\n",
" # Time axes\n",
" hist_t = np.arange(len(history))\n",
" fut_t = np.arange(len(history), len(history) + len(future))\n",
"\n",
" # Plot history and ground truth future\n",
" ax.plot(hist_t, history, label=\"History\", color=\"black\")\n",
" ax.plot(fut_t, future, label=\"Ground Truth\", color=\"blue\")\n",
"\n",
" # Plot quantiles\n",
" median_idx = num_quantiles // 2\n",
" ax.plot(\n",
" fut_t,\n",
" preds_np[i, :, 0, median_idx],\n",
" label=\"Prediction (Median)\",\n",
" color=\"orange\",\n",
" linestyle=\"--\",\n",
" )\n",
" if num_quantiles >= 3:\n",
" ax.fill_between(\n",
" fut_t,\n",
" preds_np[i, :, 0, 0],\n",
" preds_np[i, :, 0, -1],\n",
" color=\"orange\",\n",
" alpha=0.2,\n",
" label=\"Prediction Interval\",\n",
" )\n",
"\n",
" ax.axvline(x=len(history), color=\"k\", linestyle=\":\", alpha=0.7)\n",
" ax.set_xlabel(\"Time Steps\")\n",
" ax.set_ylabel(\"Value\")\n",
" ax.set.title(f\"Sample {i + 1}\")\n",
" ax.legend()\n",
" ax.grid(True, alpha=0.3)\n",
" plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|