### TimesFM Forecasting Example Source: https://github.com/google-research/timesfm/blob/master/README.md Demonstrates how to load a TimesFM model and perform forecasting with specified configuration. Ensure torch and numpy are installed. ```python import torch import numpy as np import timesfm torch.set_float32_matmul_precision("high") model = timesfm.TimesFM_2p5_200M_torch.from_pretrained("google/timesfm-2.5-200m-pytorch") model.compile( timesfm.ForecastConfig( max_context=1024, max_horizon=256, normalize_inputs=True, use_continuous_quantile_head=True, force_flip_invariance=True, infer_is_positive=True, fix_quantile_crossing=True, ) ) point_forecast, quantile_forecast = model.forecast( horizon=12, inputs=[ np.linspace(0, 1, 100), np.sin(np.linspace(0, 20, 67)), ], # Two dummy inputs ) point_forecast.shape # (2, 12) quantile_forecast.shape # (2, 12, 10): mean, then 10th to 90th quantiles. ``` -------------------------------- ### Install Dependencies Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/examples/finetuning/README.md Install the required libraries for running the fine-tuning workflow. ```bash pip install transformers accelerate peft pandas pyarrow scikit-learn ``` -------------------------------- ### Install TimesFM Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Install the package using uv or pip, selecting the appropriate backend. ```bash # Using uv (fast) uv pip install timesfm[torch] # Or using pip pip install timesfm[torch] # For JAX/Flax backend (faster on TPU/GPU) uv pip install timesfm[flax] ``` -------------------------------- ### Run Example Scripts Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Execute the provided example scripts for global temperature forecasting, anomaly detection, and covariate forecasting. ```bash # Run all three examples: cd examples/global-temperature && python run_forecast.py && python visualize_forecast.py cd examples/anomaly-detection && python detect_anomalies.py cd examples/covariates-forecasting && python demo_covariates.py ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Commands to install optional packages for Flax backend support or scikit-learn integration. ```bash pip install jax[cuda] ``` ```bash pip install flax ``` ```bash pip install scikit-learn ``` -------------------------------- ### Install PyTorch Dependencies Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Install the required PyTorch version based on your specific hardware environment. ```bash # CUDA 12.1 (NVIDIA GPU) pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121 # CPU only pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu # Apple Silicon (MPS) pip install torch>=2.0.0 # MPS support is built-in ``` -------------------------------- ### Minimal Forecasting Example Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Initialize the model and perform a basic forecast on a 1D input array. ```python import torch, numpy as np, timesfm torch.set_float32_matmul_precision("high") model = timesfm.TimesFM_2p5_200M_torch.from_pretrained( "google/timesfm-2.5-200m-pytorch" ) model.compile(timesfm.ForecastConfig( max_context=1024, max_horizon=256, normalize_inputs=True, use_continuous_quantile_head=True, force_flip_invariance=True, infer_is_positive=True, fix_quantile_crossing=True, )) point, quantiles = model.forecast(horizon=24, inputs=[ np.sin(np.linspace(0, 20, 200)), # any 1-D array ]) # point.shape == (1, 24) — median forecast # quantiles.shape == (1, 24, 10) — 10th–90th percentile bands ``` -------------------------------- ### Local Install of TimesFM Source: https://github.com/google-research/timesfm/blob/master/README.md Clone the repository and install TimesFM in an editable mode with specified dependencies using uv. ```shell git clone https://github.com/google-research/timesfm.git cd timesfm # Create a virtual environment uv venv # Activate the environment source .venv/bin/activate # Install the package in editable mode with torch uv pip install -e .[torch] # Or with flax uv pip install -e .[flax] # And when XReg is needed uv pip install -e .[xreg] ``` -------------------------------- ### Reproduce Forecast Execution Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/examples/global-temperature/README.md Commands to install necessary dependencies and execute the forecasting pipeline. ```bash # Install dependencies uv pip install "timesfm[torch]" matplotlib pandas numpy # Run the complete example cd scientific-skills/timesfm-forecasting/examples/global-temperature ./run_example.sh ``` -------------------------------- ### Install TimesFM from PyPI Source: https://github.com/google-research/timesfm/blob/master/README.md Install the TimesFM package with optional dependencies for torch, flax, or xreg using pip. ```shell pip install timesfm[torch] # Or with flax pip install timesfm[flax] # And when XReg is needed pip install timesfm[xreg] ``` -------------------------------- ### Install TimesFM Agent Skill Source: https://github.com/google-research/timesfm/blob/master/AGENTS.md Commands to copy the skill directory into global or project-level agent skills folders. ```bash # Cursor / Claude Code / OpenCode / Codex (global install) cp -r timesfm-forecasting/ ~/.cursor/skills/ cp -r timesfm-forecasting/ ~/.claude/skills/ # Or project-level cp -r timesfm-forecasting/ .cursor/skills/ ``` -------------------------------- ### Compile ForecastConfig for Tier 1 (Minimal) Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Use this configuration for CPU-only setups with 4-8 GB RAM, limiting max context to 512 for light exploration and prototyping. ```python model.compile(timesfm.ForecastConfig( max_context=512, max_horizon=128, per_core_batch_size=4, normalize_inputs=True, use_continuous_quantile_head=True, fix_quantile_crossing=True, )) ``` -------------------------------- ### Forecast with Covariates Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Runs inference for time series forecasting using exogenous variables. Requires the `timesfm[xreg]` installation. Dynamic covariates must match the combined length of context and horizon. ```python point, quantiles = model.forecast_with_covariates( inputs=inputs, dynamic_numerical_covariates={"temp": [temp_array1, temp_array2]}, dynamic_categorical_covariates={"dow": [dow_array1, dow_array2]}, static_categorical_covariates={"region": ["east", "west"]}, xreg_mode="xreg + timesfm", ) ``` -------------------------------- ### Run System Preflight Check Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Execute the mandatory system requirements check to verify RAM, GPU, disk space, and environment compatibility before loading the model. ```bash python scripts/check_system.py ``` -------------------------------- ### Troubleshoot Model Downloads Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Configure the Hugging Face cache directory or perform a manual download using the CLI. ```bash # Set a different cache directory export HF_HOME=/path/with/more/space # Or download manually huggingface-cli download google/timesfm-2.5-200m-pytorch ``` -------------------------------- ### Initialize TimesFM Model Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/examples/global-temperature/README.md Compares the documented GitHub README initialization with the actual working API implementation. ```python model = timesfm.TimesFm( context_len=512, horizon_len=128, backend="gpu", ) model.load_from_google_repo("google/timesfm-2.5-200m-pytorch") ``` ```python hparams = timesfm.TimesFmHparams(horizon_len=12) checkpoint = timesfm.TimesFmCheckpoint( huggingface_repo_id="google/timesfm-1.0-200m-pytorch" ) model = timesfm.TimesFm(hparams=hparams, checkpoint=checkpoint) ``` -------------------------------- ### Check System Requirements Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Use the preflight checker script to validate system memory and dataset fit before loading the model. ```bash python scripts/check_system.py \ --num-series 1000 \ --context-length 1024 \ --batch-size 32 ``` -------------------------------- ### TimesFM_2p5_200M_torch Forecasting with Covariates Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Performs time series forecasting using exogenous variables (covariates). Requires the `timesfm[xreg]` installation. ```APIDOC ## `timesfm.TimesFM_2p5_200M_torch.forecast_with_covariates()` ### Description Run inference with exogenous variables (requires `timesfm[xreg]`). ### Method `forecast_with_covariates` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **inputs** (list[np.ndarray]) - Target time series. - **dynamic_numerical_covariates** (dict[str, list[np.ndarray]]) - Time-varying numeric features. - **dynamic_categorical_covariates** (dict[str, list[np.ndarray]]) - Time-varying categorical features. - **static_categorical_covariates** (dict[str, list[str]]) - Fixed categorical features per series. - **xreg_mode** (str) - Mode for integrating covariates: `"xreg + timesfm"` or `"timesfm + xreg"`. ### Request Example ```python point, quantiles = model.forecast_with_covariates( inputs=inputs, dynamic_numerical_covariates={"temp": [temp_array1, temp_array2]}, dynamic_categorical_covariates={"dow": [dow_array1, dow_array2]}, static_categorical_covariates={"region": ["east", "west"]}, xreg_mode="xreg + timesfm", ) ``` ### Response #### Success Response (200) - **point** (`np.ndarray`) - Point forecasts. - **quantiles** (`np.ndarray`) - Quantile forecasts. #### Response Example ```json { "point": "", "quantiles": "" } ``` ### Note Dynamic covariates must have a length equal to `context + horizon` for each series. ``` -------------------------------- ### Memory Estimation and System Checks Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Guidelines for estimating RAM requirements based on dataset size and context length, and using the preflight checker script. ```APIDOC ## Memory Estimation ### Formula RAM (GB) ≈ 0.8 + 0.5 + (0.0002 × num_series × context_length) ### Preflight Checker ```bash python scripts/check_system.py \ --num-series 1000 \ --context-length 1024 \ --batch-size 32 ``` ``` -------------------------------- ### Tune Performance and Memory Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Provides guidelines for setting batch sizes based on hardware and demonstrates chunked processing for memory-constrained environments. ```python # Always set on Ampere+ GPUs (A100, RTX 3090+) torch.set_float32_matmul_precision("high") # Batch size guidelines: # GPU 8 GB VRAM: per_core_batch_size=64 # GPU 16 GB VRAM: per_core_batch_size=128 # CPU 8 GB RAM: per_core_batch_size=8 # CPU 16 GB RAM: per_core_batch_size=32 # Memory-constrained: process in chunks CHUNK = 50 results = [] for i in range(0, len(inputs), CHUNK): p, q = model.forecast(horizon=H, inputs=inputs[i:i+CHUNK]) results.append((p, q)) ``` -------------------------------- ### Estimate System Memory Requirements Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Run this script to calculate memory usage for a specific dataset configuration. ```bash python scripts/check_system.py \ --num-series 1000 \ --context-length 1024 \ --horizon 24 \ --batch-size 32 \ --estimate-only ``` -------------------------------- ### Evaluate TimesFM 2.5 Adapter Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/examples/finetuning/README.md Run the evaluation mode to test a previously trained adapter without retraining. ```bash # Evaluate a previously trained adapter (skip training) python finetune_lora.py --eval_only --output_dir timesfm2_5-retail-lora ``` -------------------------------- ### Compile ForecastConfig for Tier 3 (Production) Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Recommended for production environments with GPUs (16+ GB VRAM) or Apple Silicon (32+ GB), supporting large-scale batch forecasting with a max context of 4096 or higher. ```python model.compile(timesfm.ForecastConfig( max_context=4096, max_horizon=256, per_core_batch_size=128, normalize_inputs=True, use_continuous_quantile_head=True, fix_quantile_crossing=True, )) ``` -------------------------------- ### Run System Check Script Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Executes the preflight system checker to validate environment and estimate memory requirements. ```bash # Basic system check python scripts/check_system.py # Check if your specific dataset will fit python scripts/check_system.py \ --num-series 1000 \ --context-length 1024 \ --horizon 24 \ --batch-size 32 ``` -------------------------------- ### Run TimesFM Tests Source: https://github.com/google-research/timesfm/blob/master/AGENTS.md Command to execute the test suite for the v1 codebase. ```bash pytest v1/tests/ ``` -------------------------------- ### Prepare Data from Numpy Arrays Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Convert 2-D arrays or generate 1-D arrays for model input. ```python # 2-D array (rows = series, cols = time steps) data = np.load("timeseries.npy") # shape (N, T) inputs = [data[i] for i in range(data.shape[0])] # Or from 1-D inputs = [np.sin(np.linspace(0, 10, 200))] ``` -------------------------------- ### Compile ForecastConfig for Tier 2 (Standard) Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Suitable for CPU with 16 GB RAM or GPU with 4-8 GB VRAM, this configuration uses a max context of 1024 for batch forecasting and evaluation. ```python model.compile(timesfm.ForecastConfig( max_context=1024, max_horizon=256, per_core_batch_size=64, normalize_inputs=True, use_continuous_quantile_head=True, fix_quantile_crossing=True, )) ``` -------------------------------- ### Perform System Memory Estimation Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Run a memory estimation check for a specific number of series and context length without performing a full forecast. ```bash python scripts/check_system.py \ --num-series 5000 \ --context-length 2048 \ --estimate-only ``` -------------------------------- ### Load TimesFM Model Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Loads the TimesFM 2.5 (200M parameters) PyTorch model from Hugging Face. Use `force_download=True` to re-download weights if they are already cached. ```python model = timesfm.TimesFM_2p5_200M_torch.from_pretrained( "google/timesfm-2.5-200m-pytorch", cache_dir=None, # Optional: custom cache directory force_download=True, # Re-download even if cached ) ``` -------------------------------- ### Prepare Exogenous Covariates Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Covariates must have a length equal to the sum of the context length and the forecast horizon. ```python import numpy as np context_len = 100 # length of historical data horizon = 24 # forecast horizon total_len = context_len + horizon # Dynamic numerical: temperature forecast for each series temp = [ np.random.randn(total_len).astype(np.float32), # Series 1 np.random.randn(total_len).astype(np.float32), # Series 2 ] ``` -------------------------------- ### Initialize and Update Time-Series Chart Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/examples/global-temperature/output/interactive_forecast.html Initializes a Chart.js instance with fixed axis extents and provides a function to update the chart based on animation steps. ```javascript function initChart() { const ctx = document.getElementById('chart').getContext('2d'); // Calculate fixed extents const finalStep = animationData.animation_steps[animationData.animation_steps.length - 1]; allDates = [ ...animationData.actual_data.dates, ...finalStep.forecast_dates ]; // Y extent from all values const allValues = [ ...animationData.actual_data.values, ...finalStep.point_forecast, ...finalStep.q10, ...finalStep.q90 ]; yMin = Math.min(...allValues) - 0.05; yMax = Math.max(...allValues) + 0.05; chart = new Chart(ctx, { type: 'line', data: { labels: allDates, datasets: [ { label: 'All Observed', data: animationData.actual_data.values.map((v, i) => ({x: animationData.actual_data.dates[i], y: v})), borderColor: '#9ca3af', borderWidth: 1, pointRadius: 2, pointBackgroundColor: '#9ca3af', fill: false, tension: 0.1, order: 1, }, { label: 'Final Forecast', data: [...Array(animationData.actual_data.dates.length).fill(null), ...finalStep.point_forecast], borderColor: '#fca5a5', borderWidth: 1, borderDash: [4, 4], pointRadius: 2, pointBackgroundColor: '#fca5a5', fill: false, tension: 0.1, order: 2, }, { label: 'Data Used', data: [], borderColor: '#3b82f6', backgroundColor: 'rgba(59, 130, 246, 0.1)', borderWidth: 2.5, pointRadius: 4, pointBackgroundColor: '#3b82f6', fill: false, tension: 0.1, order: 10, }, { label: '90% CI Lower', data: [], borderColor: 'transparent', backgroundColor: 'rgba(239, 68, 68, 0.08)', fill: '+1', pointRadius: 0, tension: 0.1, order: 5, }, { label: '90% CI Upper', data: [], borderColor: 'transparent', backgroundColor: 'rgba(239, 68, 68, 0.08)', fill: false, pointRadius: 0, tension: 0.1, order: 5, }, { label: '80% CI Lower', data: [], borderColor: 'transparent', backgroundColor: 'rgba(239, 68, 68, 0.2)', fill: '+1', pointRadius: 0, tension: 0.1, order: 6, }, { label: '80% CI Upper', data: [], borderColor: 'transparent', backgroundColor: 'rgba(239, 68, 68, 0.2)', fill: false, pointRadius: 0, tension: 0.1, order: 6, }, { label: 'Forecast', data: [], borderColor: '#ef4444', backgroundColor: 'rgba(239, 68, 68, 0.1)', borderWidth: 2.5, pointRadius: 4, pointBackgroundColor: '#ef4444', fill: false, tension: 0.1, order: 7, }, ] }, options: { responsive: true, maintainAspectRatio: false, interaction: { intersect: false, mode: 'index' }, plugins: { legend: { display: false }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.8)', titleColor: '#fff', bodyColor: '#fff', padding: 12, }, }, scales: { x: { grid: { color: 'rgba(255, 255, 255, 0.05)' }, ticks: { color: '#9ca3af', maxRotation: 45, minRotation: 45 }, }, y: { grid: { color: 'rgba(255, 255, 255, 0.05)' }, ticks: { color: '#9ca3af', callback: v => v.toFixed(2) + '°C' }, min: yMin, max: yMax, }, }, animation: { duration: 150 }, }, }); } function updateChart(stepIndex) { if (!animationData || !chart) return; const step = animationData.animation_steps[stepIndex]; const finalStep = animationData.animation_steps[animationData.animation_steps.length - 1]; const actual = animationData.actual_d ``` -------------------------------- ### Train TimesFM 2.5 with LoRA Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/examples/finetuning/README.md Execute the training script with default or custom hyperparameters. ```bash # Fine-tune with default settings on the retail sales dataset python finetune_lora.py # Custom hyperparameters python finetune_lora.py \ --epochs 20 \ --batch_size 64 \ --lr 5e-5 \ --lora_r 8 \ --lora_alpha 16 \ --context_len 64 \ --horizon_len 13 \ --output_dir my-retail-adapter ``` -------------------------------- ### Execute CSV Forecasting CLI Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Run end-to-end forecasting on a CSV file using the provided CLI script. ```bash python scripts/forecast_csv.py input.csv \ --horizon 24 \ --date-col date \ --value-cols sales,revenue \ --output forecasts.csv ``` -------------------------------- ### Configure TimesFM ForecastConfig Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Defines the forecasting behavior using ForecastConfig. Recommended settings include normalizing inputs and enabling continuous quantile heads for better accuracy. ```python timesfm.ForecastConfig( max_context=1024, # Max context window max_horizon=256, # Max forecast horizon normalize_inputs=True, # RECOMMENDED — prevents scale instability per_core_batch_size=32, # Tune for memory use_continuous_quantile_head=True, # Better quantile accuracy for long horizons force_flip_invariance=True, # Ensures f(-x) = -f(x) infer_is_positive=True, # Clamp forecasts ≥ 0 when all inputs > 0 fix_quantile_crossing=True, # Ensure q10 ≤ q20 ≤ ... ≤ q90 return_backcast=False, # Return backcast (for covariate workflows) ) ``` -------------------------------- ### Optimize CPU Inference Speed Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Improve performance by setting matmul precision and reducing the context length in the model configuration. ```python # Ensure matmul precision is set import torch torch.set_float32_matmul_precision("high") # Use smaller context model.compile(timesfm.ForecastConfig( max_context=256, # Shorter context = faster ... )) ``` -------------------------------- ### Compile TimesFM Model Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Compiles the loaded TimesFM model with specified forecast configurations. This step is mandatory before calling the `forecast()` method. ```python model.compile( timesfm.ForecastConfig( max_context=1024, max_horizon=256, normalize_inputs=True, per_core_batch_size=32, use_continuous_quantile_head=True, force_flip_invariance=True, infer_is_positive=True, fix_quantile_crossing=True, ) ) ``` -------------------------------- ### TimesFM_2p5_200M_torch Model Loading Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Loads a pre-trained TimesFM 2.5 (200M parameters) model using the PyTorch backend. Allows specifying a cache directory and forcing re-download of model weights. ```APIDOC ## `timesfm.TimesFM_2p5_200M_torch.from_pretrained()` ### Description Loads a pre-trained TimesFM 2.5 model. ### Method `from_pretrained` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python model = timesfm.TimesFM_2p5_200M_torch.from_pretrained( "google/timesfm-2.5-200m-pytorch", cache_dir=None, # Optional: custom cache directory force_download=True, # Re-download even if cached ) ``` ### Response #### Success Response (200) - **model** (`TimesFM_2p5_200M_torch` instance) - Initialized model instance (not yet compiled). #### Response Example ```json { "model": "" } ``` ``` -------------------------------- ### TimesFM_2p5_200M_torch Model Compilation Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Compiles the loaded TimesFM model with specified forecast configurations. This step must be completed before running forecasts. ```APIDOC ## `timesfm.TimesFM_2p5_200M_torch.compile()` ### Description Compiles the model with the given forecast configuration. Must be called before `forecast()`. ### Method `compile` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **forecast_config** (`timesfm.ForecastConfig`) - Configuration object for forecasting. ### Request Example ```python model.compile( timesfm.ForecastConfig( max_context=1024, max_horizon=256, normalize_inputs=True, per_core_batch_size=32, use_continuous_quantile_head=True, force_flip_invariance=True, infer_is_positive=True, fix_quantile_crossing=True, ) ) ``` ### Response #### Success Response (200) None (operation modifies the model in-place). #### Response Example None ``` -------------------------------- ### Model Configuration Parameters Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Configuration options for the TimesFM model to control prediction intervals, sign invariance, positivity constraints, quantile ordering, and backcast returns. ```APIDOC ## Model Configuration Parameters ### Parameters - **use_continuous_quantile_head** (bool) - Optional - Default: False. Use 30M-parameter continuous quantile head for better interval calibration. - **force_flip_invariance** (bool) - Optional - Default: True. Ensures the model satisfies f(-x) = -f(x). - **infer_is_positive** (bool) - Optional - Default: True. Automatically detect if all input values are positive and clamp forecasts >= 0. - **fix_quantile_crossing** (bool) - Optional - Default: False. Post-process quantiles to ensure monotonicity (q10 <= q20 <= ... <= q90). - **return_backcast** (bool) - Optional - Default: False. Return the model's reconstruction of the input (backcast) in addition to forecast. ``` -------------------------------- ### ForecastConfig Configuration Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Defines the configuration object used to control forecasting behavior, including context windows, normalization, and quantile head settings. ```APIDOC ## ForecastConfig ### Description Configuration object for initializing TimesFM model behavior. ### Parameters - **max_context** (int) - Optional - Max context window size. - **max_horizon** (int) - Optional - Max forecast horizon. - **normalize_inputs** (bool) - Optional - Whether to normalize inputs to prevent scale instability. - **per_core_batch_size** (int) - Optional - Batch size per core for memory tuning. - **use_continuous_quantile_head** (bool) - Optional - Enables continuous quantile head for better accuracy. - **force_flip_invariance** (bool) - Optional - Ensures f(-x) = -f(x). - **infer_is_positive** (bool) - Optional - Clamps forecasts >= 0 when inputs are positive. - **fix_quantile_crossing** (bool) - Optional - Ensures monotonic quantiles (q10 <= q20 <= ... <= q90). - **return_backcast** (bool) - Optional - Whether to return backcast. ``` -------------------------------- ### Forecast with Covariates in TimesFM Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Use this to forecast with dynamic and static covariates. Ensure covariates are correctly formatted and aligned with input data. ```python dow = [ np.tile(np.arange(7), total_len // 7 + 1)[:total_len], # Series 1 np.tile(np.arange(7), total_len // 7 + 1)[:total_len], # Series 2 ] regions = ["east", "west"] point, quantiles = model.forecast_with_covariates( inputs=[values1, values2], dynamic_numerical_covariates={"temperature": temp}, dynamic_categorical_covariates={"day_of_week": dow}, static_categorical_covariates={"region": regions}, xreg_mode="xreg + timesfm", ) ``` -------------------------------- ### Anomaly Detection via Quantiles Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Identify anomalies by comparing actual values against quantile intervals. ```python point, q = model.forecast(horizon=H, inputs=[values]) lower_90 = q[0, :, 1] # 10th percentile upper_90 = q[0, :, 9] # 90th percentile actual = test_values anomalies = (actual < lower_90) | (actual > upper_90) ``` -------------------------------- ### Resolve Out of Memory Errors Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/system_requirements.md Adjust batch size and context length in ForecastConfig, or process inputs in smaller chunks to manage memory usage. ```python # Reduce batch size model.compile(timesfm.ForecastConfig( per_core_batch_size=4, # Start very small max_context=512, # Reduce context ... )) # Process in chunks for i in range(0, len(inputs), 50): chunk = inputs[i:i+50] p, q = model.forecast(horizon=H, inputs=chunk) ``` -------------------------------- ### TimesFM ForecastConfig Parameters Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Details the parameters available for configuring the TimesFM forecast behavior. ```APIDOC ## `timesfm.ForecastConfig` ### Description Immutable dataclass controlling all forecast behavior. ### Parameters - **max_context** (int, default=0) - Maximum number of historical time points to use as context. 0 uses the model's maximum (16,384 for v2.5). N truncates series to the last N points. Best practice: Set to the length of your longest series, or 512–2048 for speed. - **max_horizon** (int, default=0) - Maximum forecast horizon. 0 uses the model's maximum. N forecasts up to N steps. Best practice: Set to your expected maximum forecast length. - **normalize_inputs** (bool, default=False) - Whether to z-normalize each series before feeding to the model. True (RECOMMENDED) normalizes to zero mean, unit variance. False uses raw values. False is acceptable if series are already normalized or close to scale 1.0. - **per_core_batch_size** (int, default=1) - Number of series processed per device in each batch. Increase for throughput, decrease if Out Of Memory (OOM). See `references/system_requirements.md` for recommended values by hardware. - **use_continuous_quantile_head** (bool, default=False) - Whether to use a continuous quantile head. - **force_flip_invariance** (bool, default=True) - Whether to force flip invariance. - **infer_is_positive** (bool, default=True) - Whether to infer if the series is positive. - **fix_quantile_crossing** (bool, default=False) - Whether to fix quantile crossing. - **return_backcast** (bool, default=False) - Whether to return the backcast. - **quantiles** (list[float], default=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) - List of quantiles to compute. - **decode_index** (int, default=5) - Decoding index. ``` -------------------------------- ### Load Data from Excel Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Extract numeric columns from an Excel file into the required list format. ```python df = pd.read_excel("data.xlsx", sheet_name="Sheet1") inputs = [df[col].dropna().values.astype(np.float32) for col in df.select_dtypes(include=[np.number]).columns] ``` -------------------------------- ### Perform Single Series Forecast Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Loads a pre-trained model and generates a forecast for a single time series, including visualization of historical data and prediction intervals. ```python import torch, numpy as np, pandas as pd, timesfm, matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt torch.set_float32_matmul_precision("high") model = timesfm.TimesFM_2p5_200M_torch.from_pretrained( "google/timesfm-2.5-200m-pytorch" ) model.compile(timesfm.ForecastConfig( max_context=512, max_horizon=52, normalize_inputs=True, use_continuous_quantile_head=True, fix_quantile_crossing=True, )) df = pd.read_csv("weekly_demand.csv", parse_dates=["week"]) values = df["demand"].values.astype(np.float32) point, quantiles = model.forecast(horizon=52, inputs=[values]) fig, ax = plt.subplots(figsize=(12, 5)) ax.plot(values[-104:], label="Historical") x_fc = range(len(values[-104:]), len(values[-104:]) + 52) ax.plot(x_fc, point[0], label="Forecast", color="tab:orange") ax.fill_between(x_fc, quantiles[0, :, 1], quantiles[0, :, 9], alpha=0.2, color="tab:orange", label="80% PI") ax.legend(); ax.set_title("52-Week Demand Forecast") plt.tight_layout(); plt.savefig("forecast.png", dpi=150) ``` -------------------------------- ### Verify Anomaly Detection Output Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Use this script to load and verify the anomaly detection results from a JSON file. It checks if the 'critical' score for September 2023 meets the expected threshold. ```python import json d = json.load(open('examples/anomaly-detection/output/anomaly_detection.json')) assert d['context_summary']['critical'] >= 1, 'Sep 2023 must be CRITICAL' print('Anomaly detection: PASS') ``` -------------------------------- ### Verify Covariates Regression Output Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md This script reads a CSV file containing sales data with covariates and asserts that the number of rows matches the expected count. Ensure the file path is correct. ```python import pandas as pd df = pd.read_csv('examples/covariates-forecasting/output/sales_with_covariates.csv') assert len(df) == 108, f'Expected 108 rows, got {len(df)}' print('Covariates: PASS') ``` -------------------------------- ### Process Large Datasets in Chunks Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Split large input batches into smaller chunks to manage memory usage during forecasting. ```python CHUNK_SIZE = 100 for i in range(0, len(inputs), CHUNK_SIZE): chunk = inputs[i:i+CHUNK_SIZE] point, quantiles = model.forecast(horizon=H, inputs=chunk) # Save chunk results ``` -------------------------------- ### Load Data from Parquet Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Extract numeric columns from a Parquet file into the required list format. ```python df = pd.read_parquet("data.parquet") inputs = [df[col].dropna().values.astype(np.float32) for col in df.select_dtypes(include=[np.number]).columns] ``` -------------------------------- ### Evaluate Forecast Accuracy Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Calculates standard error metrics like MAE, RMSE, MAPE, and PI coverage for a given forecast. ```python H = 24 train, actual = values[:-H], values[-H:] point, quantiles = model.forecast(horizon=H, inputs=[train]) pred = point[0] mae = np.mean(np.abs(actual - pred)) rmse = np.sqrt(np.mean((actual - pred) ** 2)) mape = np.mean(np.abs((actual - pred) / actual)) * 100 coverage = np.mean((actual >= quantiles[0, :, 1]) & (actual <= quantiles[0, :, 9])) * 100 print(f"MAE: {mae:.2f} | RMSE: {rmse:.2f} | MAPE: {mape:.1f}% | 80% PI Coverage: {coverage:.1f}%") ``` -------------------------------- ### TimesFM Forecast Configuration Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Defines the immutable configuration for TimesFM forecasting, controlling parameters like context length, horizon, normalization, and batch size. ```python @dataclasses.dataclass(frozen=True) class ForecastConfig: max_context: int = 0 max_horizon: int = 0 normalize_inputs: bool = False per_core_batch_size: int = 1 use_continuous_quantile_head: bool = False force_flip_invariance: bool = True infer_is_positive: bool = True fix_quantile_crossing: bool = False return_backcast: bool = False quantiles: list[float] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] decode_index: int = 5 ``` -------------------------------- ### model.forecast Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Performs forecasting on provided input series. ```APIDOC ## model.forecast ### Description Generates point forecasts and quantiles for a list of input time series. ### Parameters - **horizon** (int) - Required - The number of steps to forecast. - **inputs** (list) - Required - A list of numpy arrays representing the input time series. ### Response - **point** (numpy.ndarray) - The point forecasts. - **quantiles** (numpy.ndarray) - The calculated quantiles for the forecast. ``` -------------------------------- ### Handle Leading NaNs Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Leading NaNs are automatically stripped by the model. ```text # Input: [NaN, NaN, 1.0, 2.0, 3.0] # Actual: [1.0, 2.0, 3.0] ``` -------------------------------- ### Extract Quantile Forecasts Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Access specific quantile slices from the model output. ```python point, q = model.forecast(horizon=H, inputs=data) lower_80 = q[:, :, 1] # 10th percentile upper_80 = q[:, :, 9] # 90th percentile median = q[:, :, 5] ``` -------------------------------- ### Perform Batch Forecasting Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Processes multiple time series simultaneously and exports the results to a JSON file. ```python df = pd.read_csv("all_stores.csv", parse_dates=["date"], index_col="date") inputs = [df[col].dropna().values.astype(np.float32) for col in df.columns] point, quantiles = model.forecast(horizon=30, inputs=inputs) import json results = {col: {"forecast": point[i].tolist(), "lower_80": quantiles[i, :, 1].tolist(), "upper_80": quantiles[i, :, 9].tolist()} for i, col in enumerate(df.columns)} with open("batch_forecasts.json", "w") as f: json.dump(results, f, indent=2) ``` -------------------------------- ### Prepare Data from Pandas DataFrame Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Extract series from a DataFrame for single or multiple columns. ```python # Single column inputs = [df["temperature"].values.astype(np.float32)] # Multiple columns inputs = [df[col].dropna().values.astype(np.float32) for col in numeric_cols] ``` -------------------------------- ### Perform Time Series Forecasting Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/api_reference.md Generates forecasts for one or more time series using the compiled TimesFM model. Handles leading NaNs by stripping them and internal NaNs via linear interpolation. Series longer than `max_context` are truncated, and shorter ones are padded. ```python point_forecast, quantile_forecast = model.forecast( horizon=24, inputs=[array1, array2, ...], ) ``` -------------------------------- ### Load Data from JSON Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/references/data_preparation.md Parse a JSON object where keys are series names and values are lists of data points. ```python import json with open("data.json") as f: data = json.load(f) # Assumes {"series_name": [values...], ...} inputs = [np.array(values, dtype=np.float32) for values in data.values()] ``` -------------------------------- ### Forecast with Covariates Source: https://github.com/google-research/timesfm/blob/master/timesfm-forecasting/SKILL.md Include exogenous variables in the forecast using the xreg mode. ```python point, quantiles = model.forecast_with_covariates( inputs=inputs, dynamic_numerical_covariates={"price": price_arrays}, dynamic_categorical_covariates={"holiday": holiday_arrays}, static_categorical_covariates={"region": region_labels}, xreg_mode="xreg + timesfm", # or "timesfm + xreg" ) ```