timesfm-forecasting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TimesFM Forecasting

TimesFM 预测

Overview

概述

TimesFM (Time Series Foundation Model) is a pretrained decoder-only foundation model developed by Google Research for time-series forecasting. It works zero-shot — feed it any univariate time series and it returns point forecasts with calibrated quantile prediction intervals, no training required.
This skill includes a mandatory preflight system checker that verifies RAM, GPU memory, and disk space before the model is ever loaded so the agent never crashes the user's machine.
Key numbers: TimesFM 2.5 uses 200M parameters (~800 MB on disk, ~1.5 GB in RAM on CPU, ~1 GB VRAM on GPU). The archived v1/v2 500M-parameter model needs ~32 GB RAM. Always run the system checker first.
TimesFM(Time Series Foundation Model,时间序列基础模型)是Google Research开发的一款仅解码器架构的预训练基础模型,专为时间序列预测设计。它支持**zero-shot(零样本)**预测——只需输入任意单变量时间序列,即可返回带校准分位数预测区间的点预测结果,无需训练。
该技能包含一个强制预检系统检查器,会在加载模型前验证RAM、GPU内存和磁盘空间,避免代理程序导致用户机器崩溃。
关键参数:TimesFM 2.5拥有2亿参数(磁盘占用约800MB,CPU内存占用约1.5GB,GPU显存占用约1GB)。已归档的v1/v2版本为5亿参数模型,需要约32GB内存。请务必先运行系统检查器。

When to Use This Skill

适用场景

Use this skill when:
  • Forecasting any univariate time series (sales, demand, sensor, vitals, price, weather)
  • You need zero-shot forecasting without training a custom model
  • You want probabilistic forecasts with calibrated prediction intervals (quantiles)
  • You have time series of any length (the model handles 1–16,384 context points)
  • You need to batch-forecast hundreds or thousands of series efficiently
  • You want a foundation model approach instead of hand-tuning ARIMA/ETS parameters
  • You need covariate forecasting with exogenous variables (price, promotions, holidays, day-of-week effects) → use
    forecast_with_covariates()
    (TimesFM 2.5 +
    pip install timesfm[xreg]
    )
Do not use this skill when:
  • You need classical statistical models with coefficient interpretation → use
    statsmodels
  • You need time series classification or clustering → use
    aeon
  • You need multivariate vector autoregression or Granger causality → use
    statsmodels
  • Your data is tabular (not temporal) → use
    scikit-learn
  • You cannot install optional dependencies → XReg requires scikit-learn and JAX
Note on Anomaly Detection: TimesFM does not have built-in anomaly detection, but you can use the quantile forecasts as prediction intervals — values outside the 90% CI (q10–q90) are statistically unusual. See
examples/anomaly-detection/
for a full example.
在以下场景中使用该技能:
  • 任意单变量时间序列(销售额、需求、传感器数据、生命体征、价格、天气)进行预测
  • 您需要零样本预测,无需训练自定义模型
  • 您需要带校准预测区间(分位数)的概率预测
  • 您的时间序列为任意长度(模型支持1–16384个上下文点)
  • 您需要高效地对数百或数千个序列进行批量预测
  • 您希望采用基础模型方案,而非手动调优ARIMA/ETS参数
  • 您需要结合外生变量(价格、促销、节假日、星期效应)的协变量预测 → 使用
    forecast_with_covariates()
    (需TimesFM 2.5 +
    pip install timesfm[xreg]
请勿在以下场景中使用该技能:
  • 您需要可解释系数的经典统计模型 → 使用
    statsmodels
  • 您需要时间序列分类或聚类 → 使用
    aeon
  • 您需要多变量向量自回归或格兰杰因果检验 → 使用
    statsmodels
  • 您的数据为表格型(非时序数据) → 使用
    scikit-learn
  • 您无法安装可选依赖 → XReg需要scikit-learn和JAX
异常检测说明:TimesFM没有内置异常检测功能,但您可以将分位数预测作为预测区间——超出90%置信区间(q10–q90)的值在统计上属于异常情况。完整示例请查看
examples/anomaly-detection/
目录。

⚠️ Mandatory Preflight: System Requirements Check

⚠️ 强制预检:系统要求检查

CRITICAL — ALWAYS run the system checker before loading the model for the first time.
bash
python scripts/check_system.py
This script checks:
  1. Available RAM — warns if below 4 GB, blocks if below 2 GB
  2. GPU availability — detects CUDA/MPS devices and VRAM
  3. Disk space — verifies room for the ~800 MB model download
  4. Python version — requires 3.10+
  5. Existing installation — checks if
    timesfm
    and
    torch
    are installed
Note: Model weights are NOT stored in this repository. TimesFM weights (~800 MB) download on-demand from HuggingFace on first use and cache in
~/.cache/huggingface/
.
mermaid
flowchart TD
    start["🚀 Run check_system.py"] --> ram{"RAM ≥ 4 GB?"}
    ram -->|"Yes"| gpu{"GPU available?"}
    ram -->|"No (2-4 GB)"| warn_ram["⚠️ Warning: tight RAM<br/>CPU-only, small batches"]
    ram -->|"No (< 2 GB)"| block["🛑 BLOCKED<br/>Insufficient memory"]
    warn_ram --> disk
    gpu -->|"CUDA / MPS"| vram{"VRAM ≥ 2 GB?"}
    gpu -->|"CPU only"| cpu_ok["✅ CPU mode<br/>Slower but works"]
    vram -->|"Yes"| gpu_ok["✅ GPU mode<br/>Fast inference"]
    vram -->|"No"| cpu_ok
    gpu_ok --> disk{"Disk ≥ 2 GB free?"}
    cpu_ok --> disk
    disk -->|"Yes"| ready["✅ READY<br/>Safe to load model"]
    disk -->|"No"| block_disk["🛑 BLOCKED<br/>Need space for weights"]
重要提示——首次加载模型前务必运行系统检查器。
bash
python scripts/check_system.py
该脚本会检查:
  1. 可用RAM — 低于4GB时发出警告,低于2GB时阻止运行
  2. GPU可用性 — 检测CUDA/MPS设备及显存
  3. 磁盘空间 — 验证是否有足够空间下载约800MB的模型
  4. Python版本 — 需要3.10及以上版本
  5. 现有安装情况 — 检查
    timesfm
    torch
    是否已安装
注意:模型权重未存储在本仓库中。TimesFM权重(约800MB)会在首次使用时从HuggingFace按需下载,并缓存到
~/.cache/huggingface/
目录。
mermaid
flowchart TD
    start["🚀 Run check_system.py"] --> ram{"RAM ≥ 4 GB?"}
    ram -->|"Yes"| gpu{"GPU available?"}
    ram -->|"No (2-4 GB)"| warn_ram["⚠️ Warning: tight RAM<br/>CPU-only, small batches"]
    ram -->|"No (< 2 GB)"| block["🛑 BLOCKED<br/>Insufficient memory"]
    warn_ram --> disk
    gpu -->|"CUDA / MPS"| vram{"VRAM ≥ 2 GB?"}
    gpu -->|"CPU only"| cpu_ok["✅ CPU mode<br/>Slower but works"]
    vram -->|"Yes"| gpu_ok["✅ GPU mode<br/>Fast inference"]
    vram -->|"No"| cpu_ok
    gpu_ok --> disk{"Disk ≥ 2 GB free?"}
    cpu_ok --> disk
    disk -->|"Yes"| ready["✅ READY<br/>Safe to load model"]
    disk -->|"No"| block_disk["🛑 BLOCKED<br/>Need space for weights"]

Dataset Preflight (NEW)

数据集预检(新增)

Before loading your actual data, verify it will fit in memory:
bash
undefined
加载实际数据前,先验证其是否能适配内存:
bash
undefined

Quick estimate for your dataset

快速估算您的数据集所需内存

python scripts/check_system.py
--num-series 1000
--context-length 1024
--horizon 24
--batch-size 32
--estimate-only

This will show you the estimated memory requirements and warn if your dataset is too large.

**Memory Estimation Formula**:
`RAM ≈ 0.8 GB (model) + 0.5 GB (overhead) + (0.2 MB × num_series × context_length / 1000)`

**Example Outputs**:

✅ **Dataset Fits**:
Total CPU memory: 2.34 GB Total GPU memory: 2.15 GB

⚠️ **Dataset Too Large**:
Dataset requires ~12.5 GB RAM but system has 8.0 GB. Try: context_length=512 or process in chunks of 50 series.
undefined
python scripts/check_system.py
--num-series 1000
--context-length 1024
--horizon 24
--batch-size 32
--estimate-only

该命令会显示估算的内存需求,并在数据集过大时发出警告。

**内存估算公式**:
`RAM ≈ 0.8 GB(模型) + 0.5 GB(开销) + (0.2 MB × num_series × context_length / 1000)`

**示例输出**:

✅ **数据集适配**:
Total CPU memory: 2.34 GB Total GPU memory: 2.15 GB

⚠️ **数据集过大**:
Dataset requires ~12.5 GB RAM but system has 8.0 GB. Try: context_length=512 or process in chunks of 50 series.
undefined

Hardware Requirements by Model Version

不同模型版本的硬件要求

ModelParametersRAM (CPU)VRAM (GPU)DiskContext
TimesFM 2.5 (recommended)200M≥ 4 GB≥ 2 GB~800 MBup to 16,384
TimesFM 2.0 (archived)500M≥ 16 GB≥ 8 GB~2 GBup to 2,048
TimesFM 1.0 (archived)200M≥ 8 GB≥ 4 GB~800 MBup to 2,048
Recommendation: Always use TimesFM 2.5 unless you have a specific reason to use an older checkpoint. It is smaller, faster, and supports 8× longer context.
模型参数数量CPU内存GPU显存磁盘占用上下文长度
TimesFM 2.5(推荐)200M≥ 4 GB≥ 2 GB~800 MB最高16384
TimesFM 2.0(已归档)500M≥ 16 GB≥ 8 GB~2 GB最高2048
TimesFM 1.0(已归档)200M≥ 8 GB≥ 4 GB~800 MB最高2048
建议:除非有特殊理由使用旧版本,否则始终使用TimesFM 2.5。它体积更小、速度更快,且支持8倍长度的上下文。

🔧 Installation

🔧 安装步骤

Step 1: Verify System (always first)

步骤1:验证系统(始终优先执行)

bash
python scripts/check_system.py
bash
python scripts/check_system.py

Step 2: Install TimesFM

步骤2:安装TimesFM

bash
undefined
bash
undefined

Using uv (fast)

使用uv(快速安装)

uv pip install timesfm[torch]
uv pip install timesfm[torch]

Or using pip

或使用pip

pip install timesfm[torch]
pip install timesfm[torch]

For JAX/Flax backend (faster on TPU/GPU)

如需JAX/Flax后端(TPU/GPU上速度更快)

uv pip install timesfm[flax]
undefined
uv pip install timesfm[flax]
undefined

Step 3: Install PyTorch for Your Hardware

步骤3:为您的硬件安装PyTorch

bash
undefined
bash
undefined

CUDA 12.1 (NVIDIA GPU)

CUDA 12.1(NVIDIA GPU)

pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121
pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121

CPU only

仅CPU版本

pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu
pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu

Apple Silicon (MPS)

Apple Silicon(MPS)

pip install torch>=2.0.0 # MPS support is built-in
undefined
pip install torch>=2.0.0 # MPS支持已内置
undefined

🎯 Quick Start

🎯 快速开始

Minimal Example

最简示例

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
])
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)),  # 任意一维数组
])

point.shape == (1, 24) — median forecast

point.shape == (1, 24) — 中位数预测值

quantiles.shape == (1, 24, 10) — 10th–90th percentile bands

quantiles.shape == (1, 24, 10) — 第10到第90百分位区间

undefined
undefined

Forecast with Covariates (XReg)

协变量预测(XReg)

TimesFM 2.5+ supports exogenous variables through
forecast_with_covariates()
. Requires
pip install timesfm[xreg]
.
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"
)
TimesFM 2.5及以上版本通过
forecast_with_covariates()
支持外生变量。需先执行
pip install timesfm[xreg]
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",  # 或 "timesfm + xreg"
)

Anomaly Detection (via 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)
SeverityConditionInterpretation
NormalInside 80% CIExpected behavior
WarningOutside 80% CIUnusual but possible
CriticalOutside 90% CIStatistically rare (< 10% probability)
See
examples/anomaly-detection/
for a complete worked example with visualization.
python
point, q = model.forecast(horizon=H, inputs=[values])

lower_90 = q[0, :, 1]  # 第10百分位
upper_90 = q[0, :, 9]  # 第90百分位

actual = test_values
anomalies = (actual < lower_90) | (actual > upper_90)
严重程度条件解释
正常在80%置信区间内预期行为
警告超出80%置信区间异常但可能发生
严重超出90%置信区间统计上罕见(概率<10%)
完整可视化示例请查看
examples/anomaly-detection/
目录。

📊 Understanding the Output

📊 输出结果说明

TimesFM returns
(point_forecast, quantile_forecast)
:
  • point_forecast
    : shape
    (batch, horizon)
    — the median (0.5 quantile)
  • quantile_forecast
    : shape
    (batch, horizon, 10)
    — ten quantile slices:
IndexQuantileUse
0MeanAverage prediction
10.1Lower bound of 80% PI
20.2Lower bound of 60% PI
50.5Median (=
point_forecast
)
80.8Upper bound of 60% PI
90.9Upper bound of 80% PI
python
point, q = model.forecast(horizon=H, inputs=data)

lower_80 = q[:, :, 1]  # 10th percentile
upper_80 = q[:, :, 9]  # 90th percentile
median   = q[:, :, 5]
TimesFM返回
(point_forecast, quantile_forecast)
  • point_forecast
    :形状为
    (batch, horizon)
    —— 中位数(0.5分位数)
  • quantile_forecast
    :形状为
    (batch, horizon, 10)
    —— 10个分位数切片:
索引分位数用途
0均值平均预测值
10.180%预测区间的下限
20.260%预测区间的下限
50.5中位数(与
point_forecast
一致)
80.860%预测区间的上限
90.980%预测区间的上限
python
point, q = model.forecast(horizon=H, inputs=data)

lower_80 = q[:, :, 1]  # 第10百分位
upper_80 = q[:, :, 9]  # 第90百分位
median   = q[:, :, 5]

🔧 ForecastConfig Reference

🔧 ForecastConfig 参数参考

All forecasting behavior is controlled by
timesfm.ForecastConfig
:
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)
)
ParameterDefaultWhen to Change
max_context
0Set to match your longest historical window
normalize_inputs
FalseAlways set True
use_continuous_quantile_head
FalseSet True for calibrated PIs
infer_is_positive
TrueSet False for series that can be negative
fix_quantile_crossing
FalseSet True for monotonic quantiles
See
references/api_reference.md
for the complete parameter reference.
所有预测行为由
timesfm.ForecastConfig
控制:
python
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,          # 确保f(-x) = -f(x)
    infer_is_positive=True,              # 当所有输入为正时,强制预测值≥0
    fix_quantile_crossing=True,          # 确保q10 ≤ q20 ≤ ... ≤ q90
    return_backcast=False,               # 返回反向预测(用于协变量工作流)
)
参数默认值调整场景
max_context
0设置为匹配您最长的历史窗口
normalize_inputs
False始终设置为True
use_continuous_quantile_head
False设置为True以获得校准后的预测区间
infer_is_positive
True当序列可能为负值时设置为False
fix_quantile_crossing
False设置为True以确保分位数单调递增
完整参数参考请查看
references/api_reference.md

📋 Common Workflows

📋 常见工作流

Single Series Forecast

单序列预测

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)
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="历史数据")
x_fc = range(len(values[-104:]), len(values[-104:]) + 52)
ax.plot(x_fc, point[0], label="预测值", color="tab:orange")
ax.fill_between(x_fc, quantiles[0, :, 1], quantiles[0, :, 9],
                alpha=0.2, color="tab:orange", label="80%预测区间")
ax.legend(); ax.set_title("52周需求预测")
plt.tight_layout(); plt.savefig("forecast.png", dpi=150)

Batch Forecasting (Many Series)

批量预测(多序列)

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)
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)

Evaluate Forecast Accuracy

预测准确性评估

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}%")
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%预测区间覆盖率: {coverage:.1f}%")

⚙️ Performance Tuning

⚙️ 性能调优

python
undefined
python
undefined

Always set on Ampere+ GPUs (A100, RTX 3090+)

Ampere及以上GPU(A100、RTX 3090+)请始终设置

torch.set_float32_matmul_precision("high")
torch.set_float32_matmul_precision("high")

Batch size guidelines:

批量大小参考:

GPU 8 GB VRAM: per_core_batch_size=64

GPU 8GB显存: per_core_batch_size=64

GPU 16 GB VRAM: per_core_batch_size=128

GPU 16GB显存: per_core_batch_size=128

CPU 8 GB RAM: per_core_batch_size=8

CPU 8GB内存: per_core_batch_size=8

CPU 16 GB RAM: per_core_batch_size=32

CPU 16GB内存: 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))
undefined
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))
undefined

📚 Available Scripts

📚 可用脚本

scripts/check_system.py

scripts/check_system.py

Mandatory preflight checker — run before first model load. Now includes dataset-aware memory estimation to prevent OOM errors before loading your data.
bash
undefined
强制预检脚本——首次加载模型前运行。现在新增了数据集感知内存估算功能,可在加载数据前避免内存不足错误。
bash
undefined

Basic system check

基础系统检查

python scripts/check_system.py
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
python scripts/check_system.py
--num-series 1000
--context-length 1024
--horizon 24
--batch-size 32

Quick memory estimate without system checks

仅快速估算内存,不进行系统检查

python scripts/check_system.py
--num-series 5000
--context-length 2048
--estimate-only

**What it checks**:

1. **Available RAM** — warns if below 4 GB, blocks if below 2 GB
2. **GPU availability** — detects CUDA/MPS devices and VRAM
3. **Disk space** — verifies room for the ~800 MB model download
4. **Python version** — requires 3.10+
5. **Existing installation** — checks if `timesfm` and `torch` are installed
6. **Dataset fit** (NEW) — estimates memory for your specific dataset and warns if it won't fit
python scripts/check_system.py
--num-series 5000
--context-length 2048
--estimate-only

**检查内容**:

1. **可用RAM** — 低于4GB时发出警告,低于2GB时阻止运行
2. **GPU可用性** — 检测CUDA/MPS设备及显存
3. **磁盘空间** — 验证是否有足够空间下载约800MB的模型
4. **Python版本** — 需要3.10及以上版本
5. **现有安装情况** — 检查`timesfm`和`torch`是否已安装
6. **数据集适配性**(新增)——估算您特定数据集的内存需求,并在过大时发出警告

scripts/forecast_csv.py

scripts/forecast_csv.py

End-to-end CSV forecasting CLI.
bash
python scripts/forecast_csv.py input.csv \
    --horizon 24 \
    --date-col date \
    --value-cols sales,revenue \
    --output forecasts.csv
端到端CSV预测命令行工具。
bash
python scripts/forecast_csv.py input.csv \
    --horizon 24 \
    --date-col date \
    --value-cols sales,revenue \
    --output forecasts.csv

📖 Reference Documentation

📖 参考文档

FileContents
references/system_requirements.md
Hardware tiers, GPU/CPU selection, memory estimation
references/api_reference.md
Full
ForecastConfig
docs, output shapes, model options
references/data_preparation.md
Input formats, NaN handling, CSV loading, covariate setup
文件内容
references/system_requirements.md
硬件层级、GPU/CPU选择、内存估算
references/api_reference.md
ForecastConfig
完整文档、输出形状、模型选项
references/data_preparation.md
输入格式、NaN处理、CSV加载、协变量设置

🧪 Examples

🧪 示例

ExampleDirectoryWhat It Demonstrates
Global Temperature Forecast
examples/global-temperature/
Basic
model.forecast()
, CSV → PNG → GIF pipeline
Anomaly Detection
examples/anomaly-detection/
Two-phase detrend + Z-score + quantile PI, 2-panel viz
Covariates (XReg)
examples/covariates-forecasting/
forecast_with_covariates()
, 2×2 shared-axis viz
bash
undefined
示例目录演示内容
全球温度预测
examples/global-temperature/
基础
model.forecast()
、CSV→PNG→GIF工作流
异常检测
examples/anomaly-detection/
两阶段去趋势+Z分数+分位数预测区间、双面板可视化
协变量预测(XReg)
examples/covariates-forecasting/
forecast_with_covariates()
、2×2共享轴可视化
bash
undefined

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
undefined
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
undefined

Expected Outputs

预期输出

ExampleKey output filesAcceptance criteria
global-temperature
output/forecast_output.json
,
output/forecast_visualization.png
point_forecast
has 12 values; PNG shows context + forecast + PI bands
anomaly-detection
output/anomaly_detection.json
,
output/anomaly_detection.png
Sep 2023 flagged CRITICAL (z ≥ 3.0)
covariates-forecasting
output/sales_with_covariates.csv
,
output/covariates_data.png
108 rows (3 stores × 36 weeks); distinct price arrays per store
示例关键输出文件验收标准
global-temperature
output/forecast_output.json
,
output/forecast_visualization.png
point_forecast
包含12个值;PNG显示上下文+预测值+预测区间
anomaly-detection
output/anomaly_detection.json
,
output/anomaly_detection.png
2023年9月被标记为严重异常(z ≥ 3.0)
covariates-forecasting
output/sales_with_covariates.csv
,
output/covariates_data.png
108行(3家门店×36周);每家门店有不同的价格数组

Model Versions

模型版本

VersionParamsContextStatusHuggingFace checkpoint
2.5200M16,384Latest
google/timesfm-2.5-200m-pytorch
2.0500M2,048Archived
google/timesfm-2.0-500m-pytorch
1.0200M2,048Archived
google/timesfm-1.0-200m-pytorch
  • TimesFM 1.0/2.0: must pass
    freq=[0]
    for monthly data
  • TimesFM 2.5: no frequency flag — it was removed
版本参数数量上下文长度状态HuggingFace checkpoint
2.5200M16384最新版
google/timesfm-2.5-200m-pytorch
2.0500M2048已归档
google/timesfm-2.0-500m-pytorch
1.0200M2048已归档
google/timesfm-1.0-200m-pytorch
  • TimesFM 1.0/2.0:处理月度数据时必须传入
    freq=[0]
  • TimesFM 2.5:无需频率参数——该参数已移除

Resources

资源

Quality Checklist

质量检查清单

Run after every TimesFM task before declaring success:
  • Output shape
    point_fc
    is
    (n_series, horizon)
    ,
    quant_fc
    is
    (n_series, horizon, 10)
  • Quantile indices — index 0 = mean, 1 = q10 ... 9 = q90. NOT 0 = q0.
  • Frequency flag — TimesFM 1.0/2.0: pass
    freq=[0]
    for monthly. TimesFM 2.5: omit.
  • Series length — context must be ≥ 32 data points.
  • No NaN
    np.isnan(point_fc).any()
    must be False.
  • Axes — multiple panels sharing data must use
    sharex=True
    .
  • matplotlib.use('Agg')
    — before any pyplot import when running headless.
  • infer_is_positive
    — set False for temperature, financial returns, negatives.
完成TimesFM任务后,在确认成功前请运行以下检查:
  • 输出形状
    point_fc
    (n_series, horizon)
    quant_fc
    (n_series, horizon, 10)
  • 分位数索引 — 索引0=均值,1=q10...9=q90。注意不是0=q0。
  • 频率参数 — TimesFM 1.0/2.0:月度数据需传入
    freq=[0]
    。TimesFM 2.5:无需传入。
  • 序列长度 — 上下文必须≥32个数据点。
  • 无NaN值
    np.isnan(point_fc).any()
    必须为False。
  • 坐标轴 — 共享数据的多面板图必须使用
    sharex=True
  • matplotlib.use('Agg')
    — 在无图形界面环境运行时,需在导入pyplot前设置。
  • infer_is_positive
    — 针对温度、金融收益等可能为负值的序列,设置为False。

Common Mistakes

常见错误

  1. Quantile index off-by-one
    quant_fc[..., 0]
    is the mean, not q0. q10 = index 1, q90 = index 9. Define:
    IDX_Q10, IDX_Q90 = 1, 9
    .
  2. Variable shadowing in covariate loops — don't use the outer loop variable as a comprehension variable when building per-series covariate dicts.
  3. Wrong CSV column name — global-temperature CSV uses
    anomaly_c
    , not
    anomaly
    . Print
    df.columns
    first.
  4. TimesFM 2.5 required for
    forecast_with_covariates()
    — TimesFM 1.0 does NOT have this method.
  5. Future covariates must span the full horizon — dynamic covariates need values for BOTH context AND forecast windows.
  6. Context anomaly detection uses residuals — detrend first, then Z-score. Raw Z-scores mislead on trending data.
  1. 分位数索引偏移
    quant_fc[..., 0]
    均值,不是q0。q10=索引1,q90=索引9。建议定义:
    IDX_Q10, IDX_Q90 = 1, 9
  2. 协变量循环中的变量遮蔽 — 构建逐序列协变量字典时,不要将外层循环变量用作推导式变量。
  3. CSV列名错误 — 全球温度CSV使用
    anomaly_c
    ,而非
    anomaly
    。请先打印
    df.columns
    确认。
  4. forecast_with_covariates()
    仅支持TimesFM 2.5
    — TimesFM 1.0没有此方法。
  5. 未来协变量需覆盖完整预测时长 — 动态协变量需要包含上下文和预测窗口的值。
  6. 上下文异常检测需使用残差 — 先去趋势,再计算Z分数。原始Z分数在趋势数据上会产生误导。

Validation & Verification

验证与确认

bash
undefined
bash
undefined

Anomaly detection regression:

异常检测回归测试:

python -c " 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')"
python -c " 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')"

Covariates regression:

协变量回归测试:

python -c " 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')"
undefined
python -c " 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')"
undefined