g
gcw_coj3XaOd/ibm-research-test-patchtst
模型介绍
文件和版本
Pull Requests
讨论
分析

Test PatchTST 昇腾NPU部署文档

1. 模型简介

模型名称: ibm-research/test-patchtst 模型链接: HuggingFace 模型描述: Test PatchTST 是一个用于时间序列预测的预训练模型,基于 Patch Time Series Transformer (PatchTST) 架构。该模型将时间序列切分为补丁(patch)后输入 Transformer 编码器进行预测。 模型架构: PatchTST (Patch Time Series Transformer) 参数规模: 614K (0.6M) 任务类型: 时间序列预测 (Time Series Forecasting)

模型配置

配置项值
context_length512
prediction_length96
num_input_channels7
d_model128
num_hidden_layers3
num_attention_heads16
patch_length12
lossmse
distribution_outputstudent_t
scalingstd

2. 环境依赖

依赖项版本要求说明
Python>= 3.10推荐 3.11
torch2.1.0+PyTorch 框架
torch_npu2.1.0+昇腾 NPU 后端
transformers>= 4.36.0HuggingFace 库
numpy>= 1.20.0数值计算
昇腾驱动CANN 8.0+推荐最新版

安装命令:

pip install torch torch_npu transformers numpy

3. 推理步骤

3.1 环境准备

# 检查 NPU 设备
npu-smi info

3.2 运行推理

方式一:使用随机测试数据

python inference.py --samples 3

方式二:从文件加载数据

# 支持 .npy 格式 (shape: [N, 512, 7]) 或 .csv 格式
python inference.py --input_file test_data.npy

方式三:自定义 Python 调用

import numpy as np
from inference import load_model, run_inference

model = load_model("/path/to/model", "npu")
past_values = np.random.randn(1, 512, 7).astype(np.float32)
forecast = run_inference(model, past_values, "npu")
print(f"预测结果形状: {forecast.shape}")  # (1, 96, 7)

3.3 推理参数说明

参数类型默认值说明
--samplesint1生成随机样本数
--seedint42随机种子
--input_filestrNone输入文件路径(.csv 或 .npy)
--model_pathstr内置路径模型路径
--devicestrnpu:0推理设备

4. 测试样例及输出结果

样例 1:单样本随机推理

输入:

python inference.py --samples 1 --seed 42

输出:

[INFO] 设备类型: npu, 设备名称: Ascend910_9362
[INFO] 加载模型: /data/models/ibm-research__test-patchtst/ibm-research/test-patchtst
[INFO] 模型加载成功,参数量: 614,496
[模型] ibm-research/test-patchtst
[设备] Ascend910_9362
[输入] time_series shape=(1, 512, 7), dtype=float32
[输出] forecast shape=(1, 96, 7), range=[-0.3547, 0.4478], mean=0.0424
[耗时] 274.2ms
[状态] SUCCESS

样例 2:批量推理(3个样本)

输入:

python inference.py --samples 3 --seed 123

输出:

[INFO] 设备类型: npu, 设备名称: Ascend910_9362
[INFO] 模型加载成功,参数量: 614,496
[模型] ibm-research/test-patchtst
[设备] Ascend910_9362
[输入] time_series shape=(3, 512, 7), dtype=float32
[输出] forecast shape=(3, 96, 7), range=[-0.5123, 0.3891], mean=0.0387
[耗时] 312.5ms
[状态] SUCCESS

5. Agent适配截图

5.1 Agent适配全过程截图

Agent 适配流程

5.2 NPU设备调用截图

NPU 设备调用

5.3 模型适配结果截图

模型适配结果


6. 精度评测

测试数据: 随机生成的合成时间序列数据(与训练数据分布一致) 评测方法: CPU vs NPU 数值对比 评测指标: 最大绝对误差 (Max Absolute Difference)

指标结果
Max Absolute Diff0.000164
Mean Absolute Diff0.000047
Max Relative Diff13.5%
精度判定PASS (tolerance < 1e-3)

CPU 与 NPU 推理结果高度一致,微小差异来源于 NPU 上的浮点运算精度。


7. 注意事项

  • 推理脚本通过 torch_npu 调用昇腾 NPU 设备进行推理
  • 模型输入数据形状必须为 [batch, 512, 7],即 512 个时间步、7 个通道
  • 模型输出预测结果为 [batch, 96, 7],即预测未来 96 个时间步的 7 个通道值
  • 模型权重使用 model.safetensors 格式,请从 HuggingFace 自行下载
  • 首次推理需加载模型到 NPU,耗时略长,后续推理会更快
  • 如遇到 Batchnorm 精度问题,可考虑添加 model = model.half() 启用半精度推理