gcw_mXoV1I2Z/ppo-Huggy
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

ppo-Huggy · 昇腾 NPU 适配

Unity ML-Agents PPO 策略(非图像模型)。输入为环境观测状态(vector observation),输出为连续动作。已在昇腾 Ascend910(torch-npu)上完成适配与验证。

模型说明

  • 来源: PaulVialard/ppo-Huggy(Huggy 环境训练产物)
  • 策略类型: ML-Agents PPO,network_settings: hidden_units=512, num_layers=3, normalize=true
  • 模型文件: model_weights/PaulVialard/ppo-Huggy/Huggy.onnx(2.27 MB)+ configuration.yaml + config.json
  • 观测空间: 59 维浮点向量(obs_0)
  • 动作空间: 21 维连续动作,输出范围 [-1, 1](内部 clip [-3,3] 后除以 3);无离散动作分支

说明: ONNX 图内无 value/critic 与离散动作输出分支,仅包含 actor 的连续动作输出 (continuous_actions 随机采样 / deterministic_continuous_actions 确定性),本适配以确定性动作为主结果。

昇腾 NPU 适配点

  1. 全代码域无 CUDA:删除 .cuda() / torch.cuda.* 等全部 CUDA 调用,模型与输入 Tensor 统一 .to("npu:0")。
  2. NPU 初始化:import torch_npu + torch.npu.set_device(0),try-except 捕获失败即抛错,不做 CPU/CUDA 回退。
  3. ONNX 权重迁移:onnx2torch 因 RandomNormalLike 节点无法直接转换,故用 onnx.numpy_helper 手工抽取全连接层权重(weight/bias),构建等价 PyTorch MLP:
    • normalizer(running_mean/std 固化为常数,clip ±5)
    • 3 × Linear(512) + Swish 隐藏层
    • mu → 21 连续动作输出,clip(mu,±3)/3
    • 已用 onnxruntime 做 CPU 对照,最大绝对误差 5.96e-07(fp32)
  4. 推理:
    with torch.inference_mode():
        sampled, deterministic, mu = model(obs_tensor.to(DEVICE))
    torch.npu.synchronize()

环境要求

项目要求
硬件Ascend 910(本适配在 64GB HBM 单卡验证)
OSopenEuler / KylinOS / Ubuntu(aarch64)
CANN≥ 8.0(本适配 CANN 8.5.1)
Python3.11
PyTorch / torch_npu2.9.0 / 2.9.0.post1

安装

pip install -r requirements.txt

用法

CLI 单次推理(输入观测状态 JSON)

python inference.py --img test_state.json

test_state.json 格式:

{"observation": [59 个 float]}

输出示例(JSON):continuous_actions(确定性动作)、sampled_continuous_actions(随机采样)、action_means、inference_ms 等。

FastAPI 服务

python inference.py --serve --port 8000
curl -F "file=@test_state.json" http://127.0.0.1:8000/predict

返回与 CLI 相同的推理 JSON。

验证结果

  • CLI: python inference.py --img test_state.json ✅ 输出 21 维连续动作
  • FastAPI: POST /predict 上传 JSON 返回动作 ✅
  • 设备: npu:0(Ascend910),torch.npu.synchronize() 后取结果
  • 证据截图: assets/agent_workflow.png(部署启动日志)、assets/npu_device_call.png(CLI 推理)、assets/model_result.png(FastAPI 返回)

目录结构

.
├── inference.py               # 双模式推理入口(CLI + FastAPI)
├── test_state.json            # 测试观测状态(59 维)
├── requirements.txt           # 依赖
├── model_weights/             # 权重缓存(不入库)
└── assets/                    # 适配证据截图