2
gcw_BOxvkDDf/dqn-lunarlander-v2
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

DQN-LunarLander-v2 · 昇腾 NPU 适配

HuggingFace 模型 sb3/dqn-LunarLander-v2 (Stable-Baselines3 DQN 强化学习策略,非 LLM)在华为昇腾 NPU(torch_npu)上的推理适配。

  • 模型类型:SB3 DQN(深度 Q 网络,LunarLander-v2 环境)
  • 观察:8 维连续观测(Box(-inf, inf, (8,), float32))
  • 动作:4 维离散动作(Discrete(4),{0,1,2,3})
  • 默认权重:dqn-LunarLander-v2.zip(numpy 2.x 序列化,内置 pickle 兼容补丁)

环境

  • Ascend910,ASCEND_RT_VISIBLE_DEVICES=0
  • torch 2.9.0 + torch_npu 2.9.0.post1,python 3.11
  • stable-baselines3 2.9.0 + gymnasium 1.3.0

用法

# 权重缓存:model_weights/sb3/dqn-LunarLander-v2/dqn-LunarLander-v2.zip(存在即跳过下载)

# CLI 推理(缺省为 8 维零向量,或传 8 维 obs JSON)
python inference.py
python inference.py --input "[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"
python inference.py --img "[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"   # --img 为 --input 别名

# FastAPI 服务(端口 8022)
python inference.py --serve --port 8022
# GET /   -> 观测 JSON 文本框页面
# POST /predict -> {"obs": [8 浮点]} 或空体(用缺省观察)-> JSON

实现要点

  • policy.to("npu:0").eval(),模型/输入 tensor 全部 npu:0;get_device() 带 try-except
  • 手动前向:q_values = policy.q_net(obs_tensor) → action = q_values.argmax(dim=1)。 DQN 无 get_distribution(),且不使用 model.predict()(自带 device 管理)
  • action_space 由 custom_objects 重建 Discrete(4)(zip 内 _np_random Generator 无法被 numpy 1.26 反序列化)
  • 输出 JSON:{model, device, obs_dim, action_dim, q_values, action, ...}
  • numpy 2.x pickle 兼容补丁(zip 由 numpy 2.x 保存):numpy._core.* 子模块别名 + BitGenerator 反序列化
  • 工程 .py 无任何 CUDA 语句

结果

  • CLI:python inference.py --input "[0.0,...8个浮点]" → exit 0,npu:0 输出合法 JSON
  • FastAPI:POST /predict → 合法 JSON(缺省/自定义 obs 均可用)