Y
gcw_hhrLdMXW/ts-transformer-tourism-npu-deployment
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

time-series-transformer-tourism-monthly 昇腾 NPU 部署文档

1. 模型简介

模型名称: Time Series Transformer(huggingface/time-series-transformer-tourism-monthly)

模型链接:

  • Hugging Face: https://huggingface.co/huggingface/time-series-transformer-tourism-monthly
  • AtomGit: https://ai.gitcode.com/hf_mirrors/huggingface/time-series-transformer-tourism-monthly

模型描述: HuggingFace 官方教学模型,在 monash_tsf 的 tourism-monthly 数据集(澳大利亚月度旅游人数)上训练 30 epochs。采用 vanilla encoder-decoder Transformer 结构,训练方式类似机器翻译;推理时从 Student-T 分布逐时间步采样生成。支持静态类别特征(366 个目的地)、静态实数特征、时间特征与 16 个 lag 特征(最大 lag=37)。本部署在昇腾 NPU 上完成 61→24 步预测与分布采样。

模型架构: encoder-decoder Transformer(编码器/解码器各 2 层,d_model=26,2 头注意力)+ Student-T 分布头 + 16 个 lag 特征 + 时间特征。

参数规模: 约 30.5K 参数(轻量教学模型)。

适配引擎: 昇腾 torch_npu(torch.npu 设备接口调用 NPU)。

2. 环境依赖

依赖项版本要求说明
Python>= 3.10(推荐 3.11)本机 3.11.14
CANN Toolkit8.0.RC2+本机 8.5.1
torch2.9.0+cpu本机
torch_npu2.9.0.post1昇腾 NPU 适配层
transformers4.57.6模型加载/推理
safetensors0.4.3+权重加载

硬件: 昇腾 Ascend910_9362(64GB HBM ×2)。

3. 推理步骤

3.1 获取权重

# 方式一:推理脚本自动下载(推荐)
python3 inference.py --device npu:0

# 方式二:手动下载
mkdir -p model
curl -sSL -o model/config.json "https://hf-mirror.com/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json"
curl -sSL -o model/model.safetensors "https://hf-mirror.com/huggingface/time-series-transformer-tourism-monthly/resolve/main/model.safetensors"

3.2 检查 NPU 设备

npu-smi info
python3 -c "import torch, torch_npu; print(torch.npu.device_count())"   # 输出 2

3.3 运行推理

python3 inference.py --device npu:0 --warmup 1 --runs 3

4. 测试样例及输出结果

命令:

python3 inference.py --device npu:0 --warmup 1 --runs 3

输出(关键部分):

[模型加载] 完成, 参数量 30.5K, 设备 npu:0
  配置: context=24, prediction=24, 分布=student_t
[推理] 合成旅游月度数据: 61 步历史(含37步lag) -> 24 步预测 (Student-T 分布采样 x10000)
  历史末值 11.356 / 预测均值前 5 步 [18.146, 19.062, 18.35, 18.18, 18.764]
  预测均值范围: [17.853, 19.869]
  单样本范围: [-14.117, 23.935]
[性能基准] device=npu:0 warmup=1 runs=3
  平均推理时延 = 225.00 ms/条 (4.4 FPS)
  (输入 61 步历史 -> 输出 24 步)

结果分析: 模型在昇腾 NPU 上完成 61→24 步旅游人数预测,Student-T 分布采样正常,预测均值 [17.85, 19.87] 落在合理旅游人次区间(历史末值 11.36 之后的季节性回升),单样本展现合理波动,验收通过。

5. 注意事项

  • 标准 transformers 模型(TimeSeriesTransformerForPrediction),无需 trust_remote_code。
  • past 长度要求:past_values 序列长度须 ≥ context_length + max_lag = 24 + 37 = 61,否则报 lags cannot go further than history length。
  • transformers 4.57 API 变化:forward 输出不再有 prediction_distribution(params 仅在提供 future_values 时计算);应使用 model.generate() 做推理采样(返回 SampleTSPredictionOutput.sequences)。
  • generate 输出形状在空 target_shape 下有 reshape 怪癖(本环境 [100,100,24]),统一 reshape(-1, pred_len) 处理。
  • 需提供:past_values / past_time_features / past_observed_mask / static_categorical_features / static_real_features / future_time_features。
  • 首次前向算子编译需预热。