本仓库 = 上游 gpt-bird 模型权重 + 自包含 PyTorch 实现 + FastAPI 服务化推理 + Ascend NPU 适配交付
上游 gmmeyer/gpt-bird 仓库只提供了 ONNX web 端推理
和 PyTorch 训练权重。本仓库在保留上游全部权重(model.onnx、small_pipes.pt、
nano_nopipes.pt、config.json)的前提下,新增了:
dreaming_bird/ —— 自包含 PyTorch 模型实现,不依赖上游 dreaming_bird 包,
与上游 small_pipes.pt / nano_nopipes.pt 权重键完全兼容;inference.py —— FastAPI 服务化推理脚本,开箱即用地在 Ascend NPU 上
加载权重并对外提供 /health 与 /predict 接口;tests/test_inference.py —— 端到端测试用例,自动检查健康、单步推理、
10 步自回归、50 次稳态推理并落盘 test_result.json;assets/*.png —— NPU 设备调用截图、测试结果截图、适配过程流程图(均带 maggie_Ha 水印);requirements.txt —— 完整 Python 依赖清单。🎮 浏览器原始 demo: https://gmmeyer.github.io/gpt-bird/
💻 上游源码: https://github.com/gmmeyer/gptbird
Dreaming Bird 是一个 decoder-only Transformer,被训练成「就是」Flappy Bird 本身。 给定近期帧状态 + 玩家动作(flap / no-flap),它输出下一帧的量化状态, 自回归循环就取代了游戏运行时引擎 —— 没有物理代码,神经网络 就是 物理。
small_pipes.pt 11.29M,nano_nopipes.pt 1.9M

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

| 指标 | CPU fp32 | NPU fp32 | 加速比 |
|---|---|---|---|
| 单次 forward(B=1, T=64) | 26.19 ms | 2.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。
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 水印)# 假设已安装 Ascend CANN 8.5.1 与 torch/torch_npu
pip install -r requirements.txtcd /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.2mscurl -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}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"
}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
PORT=8080 CHECKPOINT=/opt/atomgit/gpt-bird/nano_nopipes.pt python inference.py# 确保服务已启动
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.980msimport 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)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())
"| 上游权重键 | 自包含实现 |
|---|---|
wte.weight (232, 384) | self.wte = nn.Embedding(232, 384) |
wpe.weight (1280, 384) | self.wpe = nn.Embedding(1280, 384) |
blocks.{i}.n1/n2.weight | nn.LayerNorm(384, bias=False) |
blocks.{i}.attn.qkv.weight (1152, 384) | fused nn.Linear(384, 1152, bias=False) |
blocks.{i}.attn.proj.weight | nn.Linear(384, 384, bias=False) |
blocks.{i}.mlp.fc.weight (1536, 384) | nn.Linear(384, 1536, bias=False) |
blocks.{i}.mlp.proj.weight | nn.Linear(1536, 384, bias=False) |
norm_f.weight | nn.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) 直接成功。
F.scaled_dot_product_attention(q, k, v, is_causal=True),
在 Ascend NPU 上会自动走 atb 融合算子实现;nn.Linear → GELU → nn.Linear 标准 GPT 块;greedy_step 中按 slot 范围取 argmax,
避免 logits 越界,与上游 JS decode 循环语义一致。greedy_step,最后 5 个 token(含 action=230)追加到上下文
作为下一步输入,实现 O(T) 自回归;timings_ms 含 encode / host_to_device / inference / total 四段耗时;npu-smi 实时监控(见 assets/npu_device_call.png)。gmmeyer/gptbird,本仓库未重新训练,仅做部署与加速;load_gptbird_checkpoint(... dtype=torch.bfloat16) 中切换;_MODEL.greedy_step 调用为流式(保留 KV cache);gap_y(上游 JS demo 的特色),可改造
greedy_step 的第三段为 torch.multinomial(F.softmax(gap_y_logits / temp, dim=-1), 1)。dreaming_bird/、inference.py、tests/、assets/、requirements.txt):MITsmall_pipes.pt、nano_nopipes.pt、model.onnx、config.json):MIT,源自上游适配过程如有问题,可参考:
assets/agent_workflow.png —— 7 步适配流程assets/npu_device_call.png —— NPU 设备调用与进程绑定assets/model_result.png —— 性能/精度结果tests/test_result.json —— 原始测试数据