w
willwell888/gpt-bird
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

gpt-bird on Ascend NPU

1. 简介

本文档记录 gpt-bird 在华为 Ascend NPU 上的推理适配与验证结果。gpt-bird 是由 Gregory Meyer 开发的神经网络 Flappy Bird 世界模型,一个纯基于神经网络的游戏物理引擎替代品。

该模型是一个 6 层 Decoder-only Transformer(d_model=384),输入为 Flappy Bird 游戏的帧状态 token 和玩家动作(flap/noflap),输出为下一帧的量化状态。循环自回归运行(~30-60 fps)时,模型完全替代了游戏物理引擎。

模型链接(HuggingFace):https://huggingface.co/gmmeyer/gpt-bird

参考文档:

  • 官方代码库:https://github.com/gmmeyer/gptbird
  • 在线演示:https://gmmeyer.github.io/gpt-bird/(ONNX + WebGPU 浏览器推理)

2. 验证环境

组件版本
torch2.9.0+cpu
torch_npu2.9.0.post1+gitee7ba04
numpy1.26.4
onnx1.22.0
CANN8.5.1
  • NPU:Ascend 910(单卡)
  • 模型路径:/opt/atomgit/0821/gpt-bird
  • Python:3.11

3. 依赖安装

pip install -r requirements.txt

如需使用阿里云镜像:

pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ --extra-index-url https://pypi.org/simple/

4. 模型推理

推理脚本 inference.py 自动检测可用设备(优先 NPU),从 ONNX 权重加载并执行自回归解码:

python inference.py

指定设备:

python inference.py --device npu:0
python inference.py --device cpu

5. Smoke 验证

python inference.py

验证结果:

  • 模型加载成功,参数量 12,087,168(约 12M)
  • ONNX 权重正确加载到 NPU 设备
  • 自回归解码正常输出 token 序列
  • NPU 进程峰值内存:约 182 MB HBM

推理日志(run_npu.log)中包含完整终端输出和 npu-smi 进程占用采样:

[INFO] 模型加载成功 | 参数量: 12,087,168 | 耗时: 1.30s
[INFO] 生成 token 数: 51
[INFO] 生成序列: [1, 85, 187, 187, 227, 187, 187, 187, 227, 227, ...]

NPU 进程占用:

| NPU     Chip              | Process id    | Process name             | Process memory(MB)      |
| 7       0                 | 14135         | python3                  | 182                     |

6. 模型结构

6.1 整体架构

组件参数
嵌入层vocab=232, d_model=384
位置编码可学习绝对位置编码,block_size=1280
Transformer 层数6
注意力Gated Linear Attention(6 头,d_kv=64)
MLPSwishGLU(d_ff=1536)
输出层权重绑定(lm_head = wte.weight.T)

总计约 12M 参数。

6.2 SwishGLU MLP

MLP 采用 SwishGLU 变体,公式为:

output = 0.5 * (1 + erf(x @ w_fc / sqrt(2))) * (x @ w_fc) @ w_down

验证自 ONNX 图节点序列:fc/MatMul → Div(sqrt(2)) → Erf → Add(1) → Mul(fc_out) → Mul(0.5) → proj/MatMul

6.3 状态 Token 格式

每帧包含 4 个 token:

Slot含义范围
bird_y小鸟垂直位置128 bins
pipe_dx管道水平距离64 bins
gap_y管道间隙垂直位置32 bins
status存活状态alive/dead

7. 推理结果示例

输入:[BOS token = 1] 输出 token 序列(部分):[1, 85, 187, 187, 227, 187, 187, 187, 227, 227, 227, ...]

  • Token 1 (BOS):序列起始
  • Token 227:status_dead token,表示游戏结束
  • Token 85/187:bird_y 和 pipe_dx 的量化 bin ID

8. 注意事项

  • 权重从 model.onnx 提取并加载到 PyTorch nn.Module,避免使用 onnx2torch GraphModule(后者存在 torch_npu 兼容问题)
  • 自回归解码最大长度 50 tokens,遇到 EOS token(2)提前终止
  • 推理脚本无外部依赖(onnx2torch 仅用于参考验证,已移除)
  • 浏览器演示(gmmeyer.github.io)使用 onnxruntime-web + WebGPU,无需服务器端推理