maggie_Ha/gpt-bird-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

🐦 Dreaming Bird — Flappy Bird 世界模型(昇腾 NPU 适配版)

本仓库 = 上游 gpt-bird 模型权重 + 自包含 PyTorch 实现 + FastAPI 服务化推理 + Ascend NPU 适配交付

上游 gmmeyer/gpt-bird 仓库只提供了 ONNX web 端推理 和 PyTorch 训练权重。本仓库在保留上游全部权重(model.onnx、small_pipes.pt、 nano_nopipes.pt、config.json)的前提下,新增了:

  1. dreaming_bird/ —— 自包含 PyTorch 模型实现,不依赖上游 dreaming_bird 包, 与上游 small_pipes.pt / nano_nopipes.pt 权重键完全兼容;
  2. inference.py —— FastAPI 服务化推理脚本,开箱即用地在 Ascend NPU 上 加载权重并对外提供 /health 与 /predict 接口;
  3. tests/test_inference.py —— 端到端测试用例,自动检查健康、单步推理、 10 步自回归、50 次稳态推理并落盘 test_result.json;
  4. assets/*.png —— NPU 设备调用截图、测试结果截图、适配过程流程图(均带 maggie_Ha 水印);
  5. requirements.txt —— 完整 Python 依赖清单。

🎮 浏览器原始 demo: https://gmmeyer.github.io/gpt-bird/
💻 上游源码: https://github.com/gmmeyer/gptbird


1. 模型简介

Dreaming Bird 是一个 decoder-only Transformer,被训练成「就是」Flappy Bird 本身。 给定近期帧状态 + 玩家动作(flap / no-flap),它输出下一帧的量化状态, 自回归循环就取代了游戏运行时引擎 —— 没有物理代码,神经网络 就是 物理。

  • 架构:6 层 Transformer block,d_model=384,n_head=6,block_size=1280
  • 词表:232(4 特殊 token + 128 bird_y bins + 64 pipe_dx bins + 32 gap_y bins + 2 status + 2 action)
  • 参数量:small_pipes.pt 11.29M,nano_nopipes.pt 1.9M
  • 训练指标(来自上游 README):bird_y 一步预测 98.6% exact / 100% within ±1 bin
  • 推理吞吐:上游 RTX 5090 上 ~125 fps;本仓库 Ascend 910 NPU 上单步 forward 2.97ms ≈ 336 fps

2. 昇腾 NPU 适配概览

2.1 适配过程(adapt-agent / ai4s-basic skill)

适配流程

2.2 设备调用

NPU 设备调用

本机实测环境:Ascend 910 × 2(其中 NPU:0 用于本服务)
torch 2.9.0 + torch_npu 2.9.0.post1+gitee7ba04 + CANN 8.5.1

2.3 测试结果

测试结果

指标CPU fp32NPU fp32加速比
单次 forward(B=1, T=64)26.19 ms2.97 ms≈ 8.8x
服务端 p50(50 次稳态)—2.855 ms—
服务端 p95—3.008 ms—
客户端 roundtrip p50—3.957 ms—
CPU/NPU argmax 一致—完全一致—

完整数据见 tests/test_result.json。


3. 目录结构

gpt-bird/
├── README.md                  (本文件)
├── config.json                (上游 tokenizer / engine 配置)
├── small_pipes.pt             (上游 11.29M PyTorch checkpoint)
├── nano_nopipes.pt            (上游 1.9M 无管子小模型, 同结构兼容)
├── model.onnx                 (上游 ONNX 导出, 浏览器 web 推理用)
├── requirements.txt           (Python 依赖)
├── inference.py               (FastAPI 服务化推理, 端口 8099)
├── dreaming_bird/             (自包含 PyTorch 实现)
│   ├── __init__.py
│   ├── model.py               (GPT/ModelConfig/TokenizerConfig/EngineConfig)
│   └── tokenizer.py           (BirdTokenizer/Frame 状态编解码)
├── tests/
│   ├── test_inference.py      (端到端测试用例)
│   ├── test_result.json       (本次运行结果)
│   └── _gen_npu_screenshot.py (截图生成脚本)
└── assets/
    ├── npu_device_call.png    (NPU 设备调用截图, 含 maggie_Ha 水印)
    ├── model_result.png       (测试结果截图, 含 maggie_Ha 水印)
    └── agent_workflow.png     (适配过程流程图, 含 maggie_Ha 水印)

4. 快速开始(Ascend NPU)

4.1 安装依赖

# 假设已安装 Ascend CANN 8.5.1 与 torch/torch_npu
pip install -r requirements.txt

4.2 启动服务

cd /opt/atomgit/gpt-bird
python inference.py
# 监听 0.0.0.0:8099

启动后会打印:

[gpt-bird] 启动服务: port=8099, checkpoint=/opt/atomgit/gpt-bird/small_pipes.pt
[gpt-bird] 加载 checkpoint: /opt/atomgit/gpt-bird/small_pipes.pt
[gpt-bird] 加载完成: device=npu, vocab=232, params=11,291,520, dt=1410.2ms

4.3 健康检查

curl -s http://localhost:8099/health | python -m json.tool
# {"status": "ok", "device": "npu", "vocab_size": 232,
#  "block_size": 1280, "n_layer": 6, "d_model": 384}

4.4 单步推理

curl -s -X POST http://localhost:8099/predict \
  -H "Content-Type: application/json" \
  -d '{
    "frames": [
      {"bird_y": 240, "pipe_dx": 240, "gap_y": 256, "status": "alive", "action": "noflap"},
      {"bird_y": 244, "pipe_dx": 230, "gap_y": 256, "status": "alive", "action": "noflap"},
      {"bird_y": 250, "pipe_dx": 220, "gap_y": 256, "status": "alive", "action": "noflap"},
      {"bird_y": 258, "pipe_dx": 210, "gap_y": 256, "status": "alive", "action": "noflap"}
    ],
    "n_steps": 1
  }' | python -m json.tool

返回示例:

{
  "next_frames": [
    {"bird_y": 32.0, "pipe_dx": 0.0, "gap_y": 288.0, "status": "alive", "action": "noflap"}
  ],
  "token_ids": [111, 132, 215, 229, 230],
  "timings_ms": {"encode": 0.03, "host_to_device": 0.25, "inference": 4.09, "total": 4.38},
  "device": "npu"
}

4.5 多步自回归

curl -s -X POST http://localhost:8099/predict \
  -H "Content-Type: application/json" \
  -d '{"frames":[{"bird_y":240,"pipe_dx":240,"gap_y":256,"status":"alive","action":"noflap"}], "n_steps":10}'

每次请求服务端都会打印一行中文日志: [gpt-bird] ctx_len=5 steps=10 encode=0.014ms h2d=0.067ms infer=8.895ms total=8.978ms device=npu

4.6 自定义参数

PORT=8080 CHECKPOINT=/opt/atomgit/gpt-bird/nano_nopipes.pt python inference.py

5. 测试用例

# 确保服务已启动
python tests/test_inference.py

输出示例(保存在 tests/test_result.json):

[1/4] 健康检查 ...
  ✓ health: device=npu, vocab=232, block=1280, n_layer=6, d_model=384
[2/4] 单步推理 ...
  ✓ 服务端 inference=4.095ms 客户端总耗时=5.667ms
  ✓ 预测下一帧: {'bird_y': 32.0, 'pipe_dx': 0.0, 'gap_y': 288.0, 'status': 'alive'}
[3/4] 自回归 10 步 ...
  ✓ 服务端 inference=35.235ms(3.523ms/步) 客户端总耗时=36.638ms
  ✓ 前 3 帧: alive → alive → dead
[4/4] 50 次稳态推理 ...
  ✓ server inference  p50=2.855ms  p95=3.008ms  mean=2.868ms
  ✓ client roundtrip   p50=3.957ms  p95=4.169ms  mean=3.980ms

6. 编程接口

6.1 直接调用模型(不需要服务)

import sys
sys.path.insert(0, "/opt/atomgit/gpt-bird")

from dreaming_bird.model import load_gptbird_checkpoint
from dreaming_bird.tokenizer import BirdTokenizer
import torch

# 加载到 NPU
model, mcfg, tcfg, ecfg, vocab_size = load_gptbird_checkpoint(
    "/opt/atomgit/gpt-bird/small_pipes.pt",
    device="npu",
)
model.eval()
tok = BirdTokenizer(tcfg, ecfg)

# 构造一段历史
history = []
for t in range(16):
    history.append({
        "bird_y": 240 + t * 1.2,
        "pipe_dx": 240 - t * 4.0,
        "gap_y": 256.0,
        "status": "alive",
        "action": "flap" if t % 3 == 0 else "noflap",
    })

ctx = [1]  # BOS
for f in history:
    ctx.extend(tok.encode_frame(**f))
ctx.append(3)  # SEP
idx = torch.tensor([ctx], dtype=torch.long, device="npu")

# 一次 forward(最后一帧 4 个 slot 的 logits)
with torch.no_grad():
    logits = model(idx)  # (1, 4, 232)

# 一次性取下一帧 4 个 token
with torch.no_grad():
    next_tokens = model.greedy_step(idx)  # (1, 4)

6.2 命令行推理调试

python -c "
import sys, torch
sys.path.insert(0, '/opt/atomgit/gpt-bird')
from dreaming_bird.model import load_gptbird_checkpoint
m, mc, tc, ec, vs = load_gptbird_checkpoint('/opt/atomgit/gpt-bird/small_pipes.pt', device='npu')
m.eval()
idx = torch.zeros((1, 32), dtype=torch.long, device='npu'); idx[0,0]=1
print('NPU 推理结果:', m.greedy_step(idx)[0].tolist())
"

7. 设计要点

7.1 权重兼容

上游权重键自包含实现
wte.weight (232, 384)self.wte = nn.Embedding(232, 384)
wpe.weight (1280, 384)self.wpe = nn.Embedding(1280, 384)
blocks.{i}.n1/n2.weightnn.LayerNorm(384, bias=False)
blocks.{i}.attn.qkv.weight (1152, 384)fused nn.Linear(384, 1152, bias=False)
blocks.{i}.attn.proj.weightnn.Linear(384, 384, bias=False)
blocks.{i}.mlp.fc.weight (1536, 384)nn.Linear(384, 1536, bias=False)
blocks.{i}.mlp.proj.weightnn.Linear(1536, 384, bias=False)
norm_f.weightnn.LayerNorm(384, bias=False)
lm_head.weight (232, 384)nn.Linear(384, 232, bias=False)(不与 wte 共享)

40 个键严格 1:1 对齐,因此 model.load_state_dict(state, strict=True) 直接成功。

7.2 NPU 算子适配

  • 注意力:使用 F.scaled_dot_product_attention(q, k, v, is_causal=True), 在 Ascend NPU 上会自动走 atb 融合算子实现;
  • LayerNorm:bias=False(与上游权重一致,避免引入额外参数);
  • MLP:nn.Linear → GELU → nn.Linear 标准 GPT 块;
  • Slot-constrained decoding:在 greedy_step 中按 slot 范围取 argmax, 避免 logits 越界,与上游 JS decode 循环语义一致。

7.3 服务化要点

  • 模型启动时一次性加载到 NPU(仅一次 H2D 拷贝);
  • 推理在 NPU 上跑 greedy_step,最后 5 个 token(含 action=230)追加到上下文 作为下一步输入,实现 O(T) 自回归;
  • 返回 timings_ms 含 encode / host_to_device / inference / total 四段耗时;
  • 进程可被 npu-smi 实时监控(见 assets/npu_device_call.png)。

8. 限制与已知问题

  • 训练数据来自上游 gmmeyer/gptbird,本仓库未重新训练,仅做部署与加速;
  • 推理精度 fp32,如需 bf16 可在 load_gptbird_checkpoint(... dtype=torch.bfloat16) 中切换;
  • 服务没有持久化历史,每次请求只处理请求体里的 frames;如需在服务端维护一段长上下文, 请改造 _MODEL.greedy_step 调用为流式(保留 KV cache);
  • 当前实现使用了 greedy decoding,若需要采样 gap_y(上游 JS demo 的特色),可改造 greedy_step 的第三段为 torch.multinomial(F.softmax(gap_y_logits / temp, dim=-1), 1)。

9. 引用与许可

  • 上游项目:https://github.com/gmmeyer/gptbird (MIT)
  • 本仓库附加代码(dreaming_bird/、inference.py、tests/、assets/、requirements.txt):MIT
  • 模型权重(small_pipes.pt、nano_nopipes.pt、model.onnx、config.json):MIT,源自上游

10. 联系

适配过程如有问题,可参考:

  • assets/agent_workflow.png —— 7 步适配流程
  • assets/npu_device_call.png —— NPU 设备调用与进程绑定
  • assets/model_result.png —— 性能/精度结果
  • tests/test_result.json —— 原始测试数据