1
gcw_xUvjaUyi/sundial-base-128m-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

sundial-base-128m · 昇腾 NPU 适配 (Ascend 910)

本项目将 thuml/sundial-base-128m(Sundial / Timer 3.0,生成式时间序列基础模型,128M 参数) 适配到 昇腾 Ascend NPU 上运行。代码不含任何 CUDA 调用,模型与输入 Tensor 全部运行在 npu:0。

  • 模型: thuml/sundial-base-128m(HF,ICML 2025 Oral,零样本点/概率预测)
  • 设备: 昇腾 Ascend 910 × 2(torch_npu),固定使用 npu:0
  • 输入: 数值时间序列(JSON 数组),如 [1.0, 2.1, 3.2, 4.0]
  • 输出: 未来 horizon 步的预测序列(samples > 1 时同时给出多个概率样本的均值与明细)

环境

  • Python 3.11、torch 2.9.0+cpu + torch_npu 2.9.0、transformers 4.57.6
  • 依赖见 requirements.txt:pip install -r requirements.txt

权重

启动时优先加载本地缓存 ./model_weights/thuml__sundial-base-128m/; 若未命中(首次部署),自动通过 HF 镜像 https://hf-mirror.com 下载到该目录,并同样应用兼容补丁。 模型文件含自定义代码 modeling_sundial.py / configuration_sundial.py / ts_generation_mixin.py, 通过 trust_remote_code=True + local_files_only=True 加载。权重目录已加入 .gitignore,不会提交。

使用方式

1) 命令行单次推理

python3 inference.py --text "[1.0, 2.1, 3.2, 4.0]"
# 可选参数:
python3 inference.py --text "[...]" --horizon 96 --samples 5

输出为 JSON:model / device / lookback / horizon / samples / shape / forecast。

2) FastAPI 服务

uvicorn inference:app --host 0.0.0.0 --port 8000

POST /predict:

curl -X POST http://127.0.0.1:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"text": [1.0, 2.1, 3.2, 4.0], "horizon": 96, "samples": 1}'

返回预测 JSON(forecast 为未来 96 步预测序列)。

昇腾 NPU 适配要点

  1. 无 CUDA:全局不出现 .cuda() / cuda:;模型用 model.to("npu:0"),输入 Tensor 用 device="npu:0"。
  2. NPU 初始化保护:init_npu() 以 try-except 包裹 torch_npu 导入与 npu:0 可用性检查, 失败时打印清晰错误并优雅退出/返回 500。
  3. transformers>=4.55 缓存 API 兼容补丁(幂等,inference.py 内 _apply_file_patches()):
    • 官方模型基于 transformers 4.40 编写;4.55+ 移除了 DynamicCache.get_usable_length、 seen_tokens、get_max_length → 统一替换为 get_seq_length()。
    • 4.55+ 将 GREEDY_SEARCH 解码并入 _sample,导致模型自带的按 patch 粒度解码 _greedy_search(含 attention_mask 分 token 截断、多 patch 预测取中位数)不再被调用 → _force_greedy_dispatch() 将 GENERATION_MODES_MAPPING[GREEDY_SEARCH] 强制映射回 _greedy_search,保证预测语义正确。
    • 4.55+ 移除了 _extract_past_from_model_output → ts_generation_mixin.py 中改用 ALL_CACHE_NAMES 扫描提取 KV Cache。
    • 4.55+ 解码前会预创建/预填充 DynamicCache,旧的 past_key_values is None 首步判断失效 → _greedy_search 中改用 generate_results is None 判定首步。
  4. 本地缓存优先:权重加载走 ./model_weights/thuml__sundial-base-128m/,未命中才下载。

验证

  • python3 inference.py --text "[1.0, 2.1, 3.2, 4.0]" 在 npu:0 成功推理,输出 shape (1, 1, 96)。
  • FastAPI POST /predict 返回预测 JSON。
  • 更多截图见 assets/。