timesfm-forecasting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTimesFM 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 (TimesFM 2.5 +
forecast_with_covariates())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. Seefor a full example.examples/anomaly-detection/
在以下场景中使用该技能:
- 对任意单变量时间序列(销售额、需求、传感器数据、生命体征、价格、天气)进行预测
- 您需要零样本预测,无需训练自定义模型
- 您需要带校准预测区间(分位数)的概率预测
- 您的时间序列为任意长度(模型支持1–16384个上下文点)
- 您需要高效地对数百或数千个序列进行批量预测
- 您希望采用基础模型方案,而非手动调优ARIMA/ETS参数
- 您需要结合外生变量(价格、促销、节假日、星期效应)的协变量预测 → 使用(需TimesFM 2.5 +
forecast_with_covariates())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.pyThis script checks:
- Available RAM — warns if below 4 GB, blocks if below 2 GB
- GPU availability — detects CUDA/MPS devices and VRAM
- Disk space — verifies room for the ~800 MB model download
- Python version — requires 3.10+
- Existing installation — checks if and
timesfmare installedtorch
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该脚本会检查:
- 可用RAM — 低于4GB时发出警告,低于2GB时阻止运行
- GPU可用性 — 检测CUDA/MPS设备及显存
- 磁盘空间 — 验证是否有足够空间下载约800MB的模型
- Python版本 — 需要3.10及以上版本
- 现有安装情况 — 检查和
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
undefinedQuick estimate for your dataset
快速估算您的数据集所需内存
python scripts/check_system.py
--num-series 1000
--context-length 1024
--horizon 24
--batch-size 32
--estimate-only
--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.
undefinedpython scripts/check_system.py
--num-series 1000
--context-length 1024
--horizon 24
--batch-size 32
--estimate-only
--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.
undefinedHardware Requirements by Model Version
不同模型版本的硬件要求
| Model | Parameters | RAM (CPU) | VRAM (GPU) | Disk | Context |
|---|---|---|---|---|---|
| TimesFM 2.5 (recommended) | 200M | ≥ 4 GB | ≥ 2 GB | ~800 MB | up to 16,384 |
| TimesFM 2.0 (archived) | 500M | ≥ 16 GB | ≥ 8 GB | ~2 GB | up to 2,048 |
| TimesFM 1.0 (archived) | 200M | ≥ 8 GB | ≥ 4 GB | ~800 MB | up 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.pybash
python scripts/check_system.pyStep 2: Install TimesFM
步骤2:安装TimesFM
bash
undefinedbash
undefinedUsing 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]
undefineduv pip install timesfm[flax]
undefinedStep 3: Install PyTorch for Your Hardware
步骤3:为您的硬件安装PyTorch
bash
undefinedbash
undefinedCUDA 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
undefinedpip 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百分位区间
undefinedundefinedForecast with Covariates (XReg)
协变量预测(XReg)
TimesFM 2.5+ supports exogenous variables through .
Requires .
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", # 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)| Severity | Condition | Interpretation |
|---|---|---|
| Normal | Inside 80% CI | Expected behavior |
| Warning | Outside 80% CI | Unusual but possible |
| Critical | Outside 90% CI | Statistically rare (< 10% probability) |
Seefor a complete worked example with visualization.examples/anomaly-detection/
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)- : shape
point_forecast— the median (0.5 quantile)(batch, horizon) - : shape
quantile_forecast— ten quantile slices:(batch, horizon, 10)
| Index | Quantile | Use |
|---|---|---|
| 0 | Mean | Average prediction |
| 1 | 0.1 | Lower bound of 80% PI |
| 2 | 0.2 | Lower bound of 60% PI |
| 5 | 0.5 | Median (= |
| 8 | 0.8 | Upper bound of 60% PI |
| 9 | 0.9 | Upper 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—— 中位数(0.5分位数)(batch, horizon) - :形状为
quantile_forecast—— 10个分位数切片:(batch, horizon, 10)
| 索引 | 分位数 | 用途 |
|---|---|---|
| 0 | 均值 | 平均预测值 |
| 1 | 0.1 | 80%预测区间的下限 |
| 2 | 0.2 | 60%预测区间的下限 |
| 5 | 0.5 | 中位数(与 |
| 8 | 0.8 | 60%预测区间的上限 |
| 9 | 0.9 | 80%预测区间的上限 |
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.ForecastConfigpython
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)
)| Parameter | Default | When to Change |
|---|---|---|
| 0 | Set to match your longest historical window |
| False | Always set True |
| False | Set True for calibrated PIs |
| True | Set False for series that can be negative |
| False | Set True for monotonic quantiles |
See for the complete parameter reference.
references/api_reference.md所有预测行为由控制:
timesfm.ForecastConfigpython
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, # 返回反向预测(用于协变量工作流)
)| 参数 | 默认值 | 调整场景 |
|---|---|---|
| 0 | 设置为匹配您最长的历史窗口 |
| False | 始终设置为True |
| False | 设置为True以获得校准后的预测区间 |
| True | 当序列可能为负值时设置为False |
| 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
undefinedpython
undefinedAlways 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))
undefinedCHUNK = 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.pyscripts/check_system.py
scripts/check_system.pyMandatory preflight checker — run before first model load.
Now includes dataset-aware memory estimation to prevent OOM errors before loading your data.
bash
undefined强制预检脚本——首次加载模型前运行。现在新增了数据集感知内存估算功能,可在加载数据前避免内存不足错误。
bash
undefinedBasic 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
--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
--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
--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 fitpython scripts/check_system.py
--num-series 5000
--context-length 2048
--estimate-only
--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.pyscripts/forecast_csv.py
scripts/forecast_csv.pyEnd-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
📖 参考文档
| File | Contents |
|---|---|
| Hardware tiers, GPU/CPU selection, memory estimation |
| Full |
| Input formats, NaN handling, CSV loading, covariate setup |
| 文件 | 内容 |
|---|---|
| 硬件层级、GPU/CPU选择、内存估算 |
| |
| 输入格式、NaN处理、CSV加载、协变量设置 |
🧪 Examples
🧪 示例
| Example | Directory | What It Demonstrates |
|---|---|---|
| Global Temperature Forecast | | Basic |
| Anomaly Detection | | Two-phase detrend + Z-score + quantile PI, 2-panel viz |
| Covariates (XReg) | | |
bash
undefined| 示例 | 目录 | 演示内容 |
|---|---|---|
| 全球温度预测 | | 基础 |
| 异常检测 | | 两阶段去趋势+Z分数+分位数预测区间、双面板可视化 |
| 协变量预测(XReg) | | |
bash
undefinedRun 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
undefinedcd 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
undefinedExpected Outputs
预期输出
| Example | Key output files | Acceptance criteria |
|---|---|---|
| global-temperature | | |
| anomaly-detection | | Sep 2023 flagged CRITICAL (z ≥ 3.0) |
| covariates-forecasting | | 108 rows (3 stores × 36 weeks); distinct price arrays per store |
| 示例 | 关键输出文件 | 验收标准 |
|---|---|---|
| global-temperature | | |
| anomaly-detection | | 2023年9月被标记为严重异常(z ≥ 3.0) |
| covariates-forecasting | | 108行(3家门店×36周);每家门店有不同的价格数组 |
Model Versions
模型版本
| Version | Params | Context | Status | HuggingFace checkpoint |
|---|---|---|---|---|
| 2.5 | 200M | 16,384 | Latest | |
| 2.0 | 500M | 2,048 | Archived | |
| 1.0 | 200M | 2,048 | Archived | |
- TimesFM 1.0/2.0: must pass for monthly data
freq=[0] - TimesFM 2.5: no frequency flag — it was removed
| 版本 | 参数数量 | 上下文长度 | 状态 | HuggingFace checkpoint |
|---|---|---|---|---|
| 2.5 | 200M | 16384 | 最新版 | |
| 2.0 | 500M | 2048 | 已归档 | |
| 1.0 | 200M | 2048 | 已归档 | |
- TimesFM 1.0/2.0:处理月度数据时必须传入
freq=[0] - TimesFM 2.5:无需频率参数——该参数已移除
Resources
资源
- Paper: A Decoder-Only Foundation Model for Time-Series Forecasting (ICML 2024)
- HuggingFace: https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6
- Google Blog: https://research.google/blog/a-decoder-only-foundation-model-for-time-series-forecasting/
- BigQuery Integration: https://cloud.google.com/bigquery/docs/timesfm-model
- 论文: A Decoder-Only Foundation Model for Time-Series Forecasting (ICML 2024)
- HuggingFace: https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6
- Google博客: https://research.google/blog/a-decoder-only-foundation-model-for-time-series-forecasting/
- BigQuery集成: https://cloud.google.com/bigquery/docs/timesfm-model
Quality Checklist
质量检查清单
Run after every TimesFM task before declaring success:
- Output shape — is
point_fc,(n_series, horizon)isquant_fc(n_series, horizon, 10) - Quantile indices — index 0 = mean, 1 = q10 ... 9 = q90. NOT 0 = q0.
- Frequency flag — TimesFM 1.0/2.0: pass for monthly. TimesFM 2.5: omit.
freq=[0] - Series length — context must be ≥ 32 data points.
- No NaN — must be False.
np.isnan(point_fc).any() - Axes — multiple panels sharing data must use .
sharex=True - — before any pyplot import when running headless.
matplotlib.use('Agg') - — set False for temperature, financial returns, negatives.
infer_is_positive
完成TimesFM任务后,在确认成功前请运行以下检查:
- 输出形状 — 为
point_fc,(n_series, horizon)为quant_fc(n_series, horizon, 10) - 分位数索引 — 索引0=均值,1=q10...9=q90。注意不是0=q0。
- 频率参数 — TimesFM 1.0/2.0:月度数据需传入。TimesFM 2.5:无需传入。
freq=[0] - 序列长度 — 上下文必须≥32个数据点。
- 无NaN值 — 必须为False。
np.isnan(point_fc).any() - 坐标轴 — 共享数据的多面板图必须使用。
sharex=True - — 在无图形界面环境运行时,需在导入pyplot前设置。
matplotlib.use('Agg') - — 针对温度、金融收益等可能为负值的序列,设置为False。
infer_is_positive
Common Mistakes
常见错误
-
Quantile index off-by-one —is the mean, not q0. q10 = index 1, q90 = index 9. Define:
quant_fc[..., 0].IDX_Q10, IDX_Q90 = 1, 9 -
Variable shadowing in covariate loops — don't use the outer loop variable as a comprehension variable when building per-series covariate dicts.
-
Wrong CSV column name — global-temperature CSV uses, not
anomaly_canomalyfirst.df.columns -
TimesFM 2.5 required for— TimesFM 1.0 does NOT have this method.
forecast_with_covariates() -
Future covariates must span the full horizon — dynamic covariates need values for BOTH context AND forecast windows.
-
Context anomaly detection uses residuals — detrend first, then Z-score. Raw Z-scores mislead on trending data.
-
分位数索引偏移 —是均值,不是q0。q10=索引1,q90=索引9。建议定义:
quant_fc[..., 0]。IDX_Q10, IDX_Q90 = 1, 9 -
协变量循环中的变量遮蔽 — 构建逐序列协变量字典时,不要将外层循环变量用作推导式变量。
-
CSV列名错误 — 全球温度CSV使用,而非
anomaly_c。请先打印anomaly确认。df.columns -
仅支持TimesFM 2.5 — TimesFM 1.0没有此方法。
forecast_with_covariates() -
未来协变量需覆盖完整预测时长 — 动态协变量需要包含上下文和预测窗口的值。
-
上下文异常检测需使用残差 — 先去趋势,再计算Z分数。原始Z分数在趋势数据上会产生误导。
Validation & Verification
验证与确认
bash
undefinedbash
undefinedAnomaly 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')"
undefinedpython -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