本目录包含 Stable-Baselines3 DQN 在 LunarLander-v2 环境下的 昇腾 NPU 适配。
原始模型检查点位于
/mnt/old_data/whl/models/sb3/dqn-LunarLander-v2/dqn-LunarLander-v2/,
已使用 PyTorch + torch_npu 框架迁移至本地华为 Ascend 910 NPU。
交付物包含:
model_files/dqn_policy.py):从原 SB3 DQN policy.pth 直接加载到 npu:0。model_files/inference.py):通过 HTTP 接口返回单步动作。tests/test_inference.py):覆盖 HTTP API 与 NPU/CPU 数值一致性。assets/*.png):NPU 设备调用、模型结果、10 步适配工作流。requirements.txt)。# 1. 可选:安装依赖
pip install -r requirements.txt
# 2. 启动推理服务(监听 :8000)
cd model_files
python inference.py \
--model /mnt/old_data/whl/models/sb3/dqn-LunarLander-v2/dqn-LunarLander-v2/policy.pth \
--host 0.0.0.0 --port 8000
# 3. 在另一个 shell 运行测试套件
cd tests
python test_inference.py预期输出:
Running 8 tests against http://127.0.0.1:8000
============================================================
[PASS] test_health :: status=ok npu=True device=npu:0
[PASS] test_model_info :: device=npu:0 obs_dim=8 act_dim=4
[PASS] test_predict_single :: action.shape=(1,) latency=1.4ms
[PASS] test_predict_batch :: action.shape=(8,) latency=1.3ms
[PASS] test_predict_deterministic_consistency :: action_a=[0] action_b=[0]
[PASS] test_predict_raw_shapes :: q_values/argmax/epsilon_greedy shapes all match
[PASS] test_latency_budget :: median=1.05ms
[PASS] test_q_value_range :: q_values min=-253.074 max=118.980
============================================================
Finished in 0.19s; 8 passed, 0 faileddqn-LunarLander-v2-npu/
├── README.md # 本文件(中文)
├── requirements.txt # 固定的运行时依赖
├── model_files/
│ ├── dqn_policy.py # PyTorch Q 网络 + SB3 检查点加载器
│ └── inference.py # Flask 推理服务(HTTP API)
├── tests/
│ ├── test_inference.py # 8 个端到端测试用例
│ └── test_results.txt # 测试运行捕获输出
└── assets/
├── npu_device_call.png # npu-smi + torch/torch_npu 探针截图
├── model_result.png # Q 值 + 延迟面板
├── agent_workflow.png # 10 步适配剧本流程图
└── _make_screenshots.py # 可复现的截图生成脚本dqn-LunarLander-v2 使用 SB3 DQN MlpPolicy,net_arch=[256, 256]。
完整的 Q 网络结构(验证于 policy.pth):
observation (8,)
│
▼
Linear (8, 256) → ReLU
│
▼
Linear (256, 256) → ReLU
│
▼
Linear (256, 4) # 4 个动作的 Q 值| 属性 | 取值 |
|---|---|
| 观测维度 | 8(LunarLander-v2) |
| 动作空间 | Discrete(4) — do nothing, fire left, |
fire main, fire right | |
| 隐藏层单元 | 256 |
| 编码层数 | 2(Linear + ReLU),加 1 个输出 Linear |
| 激活函数 | ReLU |
| 总参数 | 69,124(约 270 KB float32) |
| 训练框架 | Stable-Baselines3 1.5.1a8 |
| 评估平均奖励 | 136.79 ± 42.72(10 episodes) |
训练阶段还包含一个 q_net_target 目标网络;推理时仅使用 q_net 在线网络。
适配代码会从检查点中只加载 q_net.* 子集权重。
推理服务暴露以下接口(默认 Flask 后端;当 Flask 不可用时回退到标准库 HTTP 服务器)。
| 方法 | 路径 | 描述 |
|---|---|---|
| GET | /health | 健康探针 + NPU 可用性标志 |
| GET | /model_info | 静态元数据 + 最佳延迟统计 |
| POST | /predict | 离散动作(确定性或 ε-贪心) |
| POST | /predict_batch | 与 /predict 相同(保留接口对称性) |
| POST | /predict_raw | q_values、argmax、epsilon_greedy 同时返回 |
/predict 请求{
"observation": [0.12, 0.83, "..."] // 1-D (8,) 或 2-D (B, 8)
}/predict 响应{
"action": [0], // 离散动作 ∈ [0, 3]
"batch_size": 1,
"latency_ms": 1.05,
"device": "npu:0",
"epsilon": 0.0
}/predict_raw 响应{
"q_values": [[120.5, 145.2, 98.7, 132.1]],
"argmax": [1],
"epsilon_greedy":[1],
"latency_ms": 1.07,
"device": "npu:0"
}| 索引 | 动作 |
|---|---|
| 0 | do nothing |
| 1 | fire left engine |
| 2 | fire main engine |
| 3 | fire right engine |
curl -s http://127.0.0.1:8000/health
curl -s http://127.0.0.1:8000/model_info
curl -s http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" \
-d "{\"observation\": $(python -c 'import numpy as np; print(np.random.randn(8).tolist())')}"在同一检查点下分别加载到 CPU 与 NPU,比较相同随机观测的 Q 值:
| 数量 | max abs diff |
|---|---|
q_values α-pred | 2.29e-05 |
| argmax 一致性 | ✅ True |
差异比 PPO 模型稍大(Q 值较大),但动作选择(argmax)完全一致。
| 指标 | 数值 (ms) |
|---|---|
| 中位数 | 1.05 |
| p95 | 1.40 |
| 冷启动 | 129 |
| 吞吐量 | ~950 req/s |
完整面板参见 assets/model_result.png。
tests/test_inference.py 覆盖:
test_health — 服务存活 + NPU 标志test_model_info — 静态元数据test_predict_single — 1-D 观测 → 单动作test_predict_batch — 2-D 观测 → 批量动作test_predict_deterministic_consistency — 同输入 → 同输出test_predict_raw_shapes — q_values / argmax / epsilon_greedy 形状test_latency_budget — p95 < 500 mstest_q_value_range — Q 值有界8 个用例全部通过,详细输出见 tests/test_results.txt。
assets/npu_device_call.png捕获 npu-smi info(8 张 Ascend910 可见)与 torch.npu 探针输出,
确认 torch_npu 2.9.0.post1+gitee7ba04 已加载、Ascend910 设备可达。

assets/model_result.png仪表盘整合:

assets/agent_workflow.png10 步适配剧本(adapt-agent skill),包含 7A dummy 与 7B 真实权重两个验证门。

adapt-agent skill 默认面向 LLM / VLM 通过 vLLM-Ascend 部署。
dqn-LunarLander-v2 是 强化学习策略,权重以 SB3 DQN
policy.pth 形式存储,不属于 transformers 模型家族,vLLM 也无法直接消费。
因此适配路径沿用 skill 的门控思想,但落到 PyTorch 底层栈:
| 步骤 | adapt-agent 默认 | 本次适配 |
|---|---|---|
| 2. 分析模型 | 解析 config.json + tokenizer | 解析 policy.pth + args.yml |
| 3. 算子门控 | CUDA / Triton / Torch 扫描 | 全部 Torch(Linear + ReLU + argmax) |
| 6. 实现代码 | 新建 vllm/model_executor/... | PyTorch 子类 QNetwork |
| 7A. Dummy 快速门 | vllm serve --load-format dummy | CPU smoke 测试(无 I/O) |
| 7B. 真实权重门 | vllm serve 真实检查点 | --model <ckpt> --device npu:0 |
| 8. 验证功能 | curl /v1/chat/completions | curl /predict 和 8 用例套件 |
由于模型仅 270 KB、69k 参数,算子兼容性自然满足:
只用到 Linear、ReLU、argmax 这几个算子,全部支持 torch_npu。
# 1. 可选:安装依赖
pip install -r requirements.txt
# 2. 确认 NPU 可用
npu-smi info
python -c "import torch, torch_npu; print(torch.npu.is_available())"
# 3. NPU 上的 smoke 测试
cd model_files
python -c "
from dqn_policy import QNetwork
import torch
m = QNetwork.from_sb3_checkpoint(
'/mnt/old_data/whl/models/sb3/dqn-LunarLander-v2/dqn-LunarLander-v2/policy.pth',
device='npu:0',
)
print('device:', next(m.parameters()).device)
print(m.act_deterministic(torch.randn(2, 8, device='npu:0')))
"
# 4. 启动服务并跑测试
python inference.py --host 0.0.0.0 --port 8000 &
cd ../tests && python test_inference.py
# 5. 重新生成截图
cd ../assets && python _make_screenshots.py| 文件 | 用途 |
|---|---|
model_files/dqn_policy.py | Q 网络 + SB3 检查点加载器 |
model_files/inference.py | Flask HTTP 服务 |
tests/test_inference.py | 8 个端到端测试用例 |
tests/test_results.txt | 测试运行的捕获输出 |
requirements.txt | 固定的运行时依赖 |
assets/npu_device_call.png | NPU 设备探针截图 |
assets/model_result.png | Q 值 + 延迟面板截图 |
assets/agent_workflow.png | 10 步适配工作流截图 |
assets/_make_screenshots.py | 可复现的截图生成脚本 |
README.md | 本指引 |