shexingnayue/Chronos-2_NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Chronos-2 Ascend NPU 适配与优化

模型信息

  • 模型名称: amazon/chronos-2
  • 模型类型: 时间序列预测 (T5-based Encoder, 120M 参数)
  • 模型地址: https://huggingface.co/amazon/chronos-2
  • 适用任务: 单变量/多变量/协变量时间序列预测

硬件要求

项目最低要求推荐配置
NPUAscend 310PAscend 910
HBM2GB4GB+
CANN>= 8.0.RC2>= 8.5.1

环境准备

# 安装依赖
pip install torch==2.9.0+cpu
pip install torch_npu==2.9.0.post1
pip install transformers>=4.37.0
pip install chronos-forecasting>=0.3.0

# NPU 内存分配优化
export PYTORCH_NPU_ALLOC_CONF=max_split_size_mb:256

快速开始

1. 加载模型

import torch
from chronos_npu import NPUChronos2Pipeline, apply_npu_optimizations

apply_npu_optimizations()

# 推荐:FP16 混合精度
pipeline = NPUChronos2Pipeline.from_pretrained(
    "amazon/chronos-2",
    device_map="npu",
    dtype=torch.float16,
)

2. 标准推理(支持 DataFrame / 张量)

import pandas as pd

df = pd.DataFrame({
    "item_id": ["A"] * 50 + ["B"] * 50,
    "timestamp": pd.date_range("2024-01-01", periods=50, freq="D").tolist() * 2,
    "target": torch.randn(100).tolist(),
})

pred = pipeline.predict_df(
    df, prediction_length=12, quantile_levels=[0.1, 0.5, 0.9],
    id_column="item_id", timestamp_column="timestamp", target="target"
)

3. 高性能批量推理(推荐)

# predict_fast 绕过 DataLoader 开销,直接接收 NPU 张量
context = torch.randn(100, 512).to("npu", dtype=torch.float32)
predictions = pipeline.predict_fast(context, prediction_length=24)
# predictions shape: (batch_size, num_quantiles, prediction_length)

4. 使用 inference.py 脚本

# 高性能 batch 推理
python inference.py --input context.npy --output pred.npy --fast --dtype fp16

# 标准推理(支持 DataFrame / CSV)
python inference.py --input data.csv --output pred.csv --dtype fp16

# 合成数据 benchmark
python inference.py --benchmark --output benchmark_result.json --dtype fp16 --batch 100

性能优化指南

高吞吐量配置(推荐)

# 使用 predict_fast + FP16,batch_size=256 可达最高吞吐
context = torch.randn(256, 512).to("npu", dtype=torch.float32)
pipeline = NPUChronos2Pipeline.from_pretrained(
    "amazon/chronos-2", device_map="npu", dtype=torch.float16
)
predictions = pipeline.predict_fast(context, prediction_length=24)
# 实测吞吐量: 4349.7 series/s

低延迟配置

# batch=100, predict_fast + FP16 为延迟最优配置
context = torch.randn(100, 512).to("npu", dtype=torch.float32)
predictions = pipeline.predict_fast(context, prediction_length=24)
# 实测延迟: ~30.5ms

不建议的优化

优化项状态原因
torch.compile不支持CANN 8.5.1 BiShengHIR Triton 编译失败
NPU DataLoader pin_memory不支持NPU 不支持 pin_memory,已通过 predict_fast 绕过
NPU Graph 捕获不支持scaled_dot_product_attention 在 graph 模式下报错

精度验证

验证方法

对比 NPU 与 CPU 输出的一致性:

pipeline_npu = NPUChronos2Pipeline.from_pretrained(MODEL_PATH, device_map="npu")
pipeline_cpu = NPUChronos2Pipeline.from_pretrained(MODEL_PATH, device_map="cpu")

context = torch.randn(32, 1, 512)
pred_npu = pipeline_npu.predict(context.to("npu"), prediction_length=6)
pred_cpu = pipeline_cpu.predict(context.to("cpu"), prediction_length=6)

验证结果

对比项指标结果
NPU vs CPU (FP32)整体 MAPE0.000064%
NPU vs CPU (FP32)最大绝对误差4.53e-06
predict_fast vs predict最大绝对误差0.0
FP16 vs FP32最大绝对误差0.006365

结论: NPU 输出与 CPU 输出数值等价;FP16 误差在时序预测可接受范围内。

性能基线

API 对比(batch=100, ctx=512, pred=24)

API精度平均延迟吞吐量加速比
predict()FP1651.86 ms1928.3 series/s1.00x
predict_fast()FP3236.82 ms2715.9 series/s1.41x
predict_fast()FP1630.50 ms3279.0 series/s1.70x
predict_fast()BF1631.25 ms3200.2 series/s1.66x

不同 batch size 吞吐(predict_fast + FP16)

Batch Size延迟吞吐量
10030.50 ms3279.0 series/s
25658.85 ms4349.7 series/s
512144.65 ms3539.6 series/s

已知问题与解决

Issue 1: NPU DataLoader pin_memory 报错

现象: RuntimeError: cannot pin 'npuFloatType' only dense CPU tensors can be pinned

解决: _should_pin_memory() 对 NPU 返回 False;使用 predict_fast() 绕过 DataLoader 路径

Issue 2: torch.compile 失败

现象: BiShengHIR Triton 编译报错

解决: 当前 CANN 8.5.1 暂不启用 torch.compile,等待后续版本支持

Issue 3: CUDA 硬编码导致 NPU 功能降级

现象: 原始 chronos-forecasting 库多处硬编码 cuda 检查

解决: 创建 NPUChronos2Pipeline 继承 Chronos2Pipeline,重写 fit() / predict() / embed() 方法,将 CUDA 检测扩展为通用加速器检测

仓库结构

chronos_npu/            # NPU 适配核心代码
    __init__.py
    pipeline.py         # NPUChronos2Pipeline(predict_fast、fit、embed)
    layers.py           # RoPE NPU 兼容
    trainer.py          # seed_worker NPU 支持
    optimize.py         # NPU 性能调优配置
    benchmark.py        # 性能基准测试脚本
    demo.py             # 使用示例

scripts/                # 评测源代码
    test_cases.py       # 功能测试
    npu_vs_cpu.py       # 精度评测

verification/
    reports/            # JSON 评测报告
    logs/               # 文本运行日志

inference.py            # 推理脚本
README.md               # 本文件

参考资源

  • Chronos GitHub
  • HuggingFace Model
  • torch_npu 文档