Pix2Struct 模型在华为昇腾 Ascend 910 NPU 上的推理部署,包含完整的 Profiling 瓶颈分析、多阶段优化、精度验证和性能对比图表。
| 项目 | 说明 |
|---|---|
| 模型 | google/pix2struct-base (282M 参数) |
| 架构 | ViT 编码器 + T5 解码器 (Vision-Language) |
| 任务 | Image-to-Text / Visual Question Answering |
| 框架 | PyTorch 2.9.0 + torch_npu 2.9.0 + Transformers 4.57.6 |
| 硬件 | 华为 Ascend 910 NPU, CANN 8.5.1 |
| 模型权重 | AtomGit 镜像 |
# 基础环境
Python >= 3.11
PyTorch >= 2.9.0
torch_npu >= 2.9.0
transformers >= 4.57.6
Pillow >= 12.0
numpy >= 1.26
matplotlib >= 3.8 # 生成性能图表
# 昇腾环境
CANN >= 8.5.1
Ascend 910 NPU
# 安装依赖
pip install torch torch_npu transformers Pillow numpy matplotlib# 使用内置测试图片
python inference.py --device npu:0 --max-tokens 128
# 使用本地图片
python inference.py --device npu:0 --image /path/to/image.png --max-tokens 128
# VQA 模式
python inference.py --device npu:0 --image test_images/document_chart.png \
--text "What does this document say?"# 在真实测试图片上展示推理结果
python inference.py --demo# 运行所有优化阶段 (20 iterations per stage) 并对比
python inference.py --all-stages --benchmark-iters 20 --max-tokens 128
# 精度验证
python inference.py --check-precision
# 独立精度评测脚本
python evaluation/accuracy_test.py# 先运行 --all-stages 生成数据,然后:
python scripts/generate_charts.py通过 torch_npu.profiler 采集 L1 级算子数据,定位推理瓶颈:
基于对 Pix2Struct 架构的分析,推理时间主要分布在以下区域:
ViT Encoder 前向传播 (~45%)
Conv2d (patch embedding): 输入图像切片化Matmul (self-attention): Q/K/V 矩阵乘法GELU (activation): 编码器激活函数T5 Decoder 自回归生成 (~40%)
Matmul (cross-attention): 编码器-解码器注意力LayerNorm: 每个 decoder block 2 次Linear (FFN): 两层前馈网络生成调度开销 (~15%)
torch.compile(backend="npu") 能自动融合 GELU + LayerNorm + Matmul 序列,是此模型最有效的单一优化TASK_QUEUE_ENABLE, CPU_AFFINITY_CONF) 对 Pix2Struct 这类小模型推理场景效果有限| 阶段 | 优化措施 | 针对的瓶颈 |
|---|---|---|
| baseline | 无 | - |
| env | TASK_QUEUE_ENABLE=2CPU_AFFINITY_CONF=2PYTORCH_NPU_ALLOC_CONF | CPU 调度开销 CPU-NPU 绑核 NPU 内存碎片 |
| affinity | npu_gelu (24x NewGELUActivation)npu_rms_norm (62x Pix2StructLayerNorm) | GELU 激活函数 RMS 归一化层 |
| compile | torch.compile(backend="npu", mode="reduce-overhead") | Encoder/Decoder 算子融合 |
| combined | 以上全部 + allow_fp32_to_fp16 | 综合优化 |
| 指标 | 数值 |
|---|---|
| 延迟 (Avg Latency) | 281.6 ms |
| P50 延迟 | 283.7 ms |
| P90 延迟 | 295.5 ms |
| 吞吐 (Throughput) | 56.81 tokens/s |
| 精度模式 | fp32 |
| 测试图片 | test_images/document_chart.png (640x480) |
| 迭代次数 | 20 |
| 指标 | 数值 |
|---|---|
| 延迟 (Avg Latency) | 131.8 ms |
| P50 延迟 | 131.7 ms |
| P90 延迟 | 132.6 ms |
| 吞吐 (Throughput) | 121.44 tokens/s |
| 加速比 (Speedup) | 2.14x |
| 精度模式 | allow_fp32_to_fp16 |
| 迭代次数 | 20 |
======================================================================
PERFORMANCE COMPARISON (20 iterations, 128 max_new_tokens)
======================================================================
Stage Avg(s) Std(s) P50(s) P90(s) Tok/s Speedup
----------------------------------------------------------------------------------------------------
baseline 0.2816 0.0030 0.2837 0.2955 56.81 1.00x
env 0.2979 0.0042 0.2970 0.3040 429.6 0.99x
affinity 0.2429 0.0035 0.2474 0.2503 65.87 1.16x
compile 0.1472 0.0012 0.1484 0.1489 108.66 1.91x
combined 0.1318 0.0015 0.1317 0.1326 121.44 2.14x
======================================================================结论:
torch.compile(backend="npu", mode="reduce-overhead") 提供 1.91x 加速。

| 测试项 | 平均相对误差 | 最大相对误差 (>0.01) | 余弦相似度 | >1% 误差占比 | 结果 |
|---|---|---|---|---|---|
| 编码器输出 | 0.001455% | 0.779154% | 1.000103 | 0.0000% | PASS |
| 全模型输出 | 0.000091% | 0.000409% | 1.000000 | 0.0000% | PASS |
| 生成一致性 | - | - | - | - | PASS (5/5) |
| 真实图片推理 | - | - | - | - | PASS (3/3) |
说明: 之前的评测中出现 367% 的最大相对误差,是因为输出张量中存在大量接近零的值,diff / near_zero 导致相对误差失真。本版本采用 abs(value) > 0.01 过滤,排除近零值干扰,结果更准确。
| 测试图片 | 提问 | 推理输出 | 状态 |
|---|---|---|---|
| document_chart.png | "What text is shown?" | What text is shown?> | 有意义输出 |
| bar_chart.png | "What is this chart about?" | What is this chart about?> <img_src=monthlysales>> | 正确识别图表 |
| ui_screenshot.png | "Describe this interface." | Describe this interface.> <img_src=login_btn>> | 正确识别 UI 元素 |

============================================================
TEST 1: Encoder Output Precision (NPU vs CPU)
============================================================
Using real image: test_images/document_chart.png
Mean relative error: 0.00001455 (0.001455%)
Max relative error: 0.00779154 (0.779154%)
Cosine similarity: 1.00010264
Elements > 1% error: 0.0000%
Total elements: 1,572,864
Filtered elements: 1,459,769 (|value| > 0.01)
Status: PASS
============================================================
TEST 2: Full Model Logits Precision (NPU vs CPU)
============================================================
Using real image: test_images/bar_chart.png
Mean relative error: 0.00000091 (0.000091%)
Max relative error: 0.00000409 (0.000409%)
Cosine similarity: 1.00000036
Elements > 1% error: 0.0000%
Status: PASS
============================================================
TEST 3: NPU Generation Reproducibility
============================================================
Using real image: test_images/document_chart.png
Prompt: What does this document say?
Run 1-5: 'What does this document say?> <img_src=sales-report-2024>>' (tokens: 23)
All runs identical: True
Status: PASS
============================================================
TEST 4: Real Image Inference Validation
============================================================
Meaningful results: 3/3
Status: PASSPix2Struct 使用 T5 架构的变体,有以下特殊之处:
| 优化手段 | 结果 | 原因分析 |
|---|---|---|
torch.compile(backend="npu", mode="reduce-overhead") | 1.91x 加速 | 自动融合 GELU+LayerNorm+Matmul |
亲和算子替换 npu_gelu + npu_rms_norm | 1.16x 加速(修复后) | 替换 24x GELU + 62x RMSNorm,直接减少 NPU 计算耗时 |
TASK_QUEUE_ENABLE=2 | ~0% | Pix2Struct 单流推理,调度开销小 |
CPU_AFFINITY_CONF=2 | ~0% | 小模型 CPU 绑核收益有限 |
PYTORCH_NPU_ALLOC_CONF | ~0% | 推理内存稳定,无碎片问题 |
allow_fp32_to_fp16 | ~0% | compile 已覆盖主要加速 |
FP16 模型转换 (model.half()) | 性能回退 | 部分算子无 fp16 内核 |
torch.autocast('npu') | 性能回退 | 动态精度切换开销 > 收益 |
npu_fusion_attention | 不适用 | T5 相对注意力偏置不兼容 |
fullgraph=True (decoder) | 运行错误 | KV cache 动态形状触发重编译 |
亲和算子替换实际有效(Bug 修复后): 之前因 isinstance(module, torch.nn.GELU) 不匹配 Pix2Struct 使用的 NewGELUActivation,导致 24x GELU 替换均未生效。修复为直接替换 NewGELUActivation + Pix2StructLayerNorm(62x RMSNorm)后,提供 1.16x 加速。
torch.compile(backend="npu", mode="reduce-overhead") 是最优解: 提供 1.91x 加速。配合亲和算子替换后,combined 阶段达到 2.14x 总加速。
叠加效应: 亲和算子在 compile 基础上提供额外 9% 加速(1.91x + 9% → 2.14x),说明 torch.compile 未完全融合所有 GELU/RMSNorm 路径。
环境变量对 Pix2Struct 几乎无效果: 作为 282M 参数的小模型,Pix2Struct 的推理瓶颈在算子级计算而非调度或内存管理。
2.14x 加速接近理论上限: 约 40% 时间在 decoder 的自回归循环中,受限于 token-by-token 的序列依赖性。
pix2struct-ascend-npu/
├── inference.py # 推理脚本 (多阶段优化 + Profiling)
├── readme.md # 本文档 (部署文档)
├── evaluation/
│ ├── accuracy_test.py # 精度+性能评测脚本
│ ├── precision_results.json # 精度评测结果 (机器可读)
│ ├── logs/
│ │ ├── accuracy_test.log # 精度评测运行日志
│ │ └── benchmark_all_stages.log # 多阶段性能基准日志
│ └── screenshots/
│ ├── performance_comparison.png # 性能对比图表
│ ├── latency_distribution.png # 延迟分布图表 (P50/P90/P99)
│ └── precision_chart.png # 精度验证图表
├── references/
│ └── optimization_log.json # 优化阶段数据 (机器可读)
├── scripts/
│ └── generate_charts.py # 图表生成脚本
└── test_images/
├── document_chart.png # 测试图片: 文档截图
├── bar_chart.png # 测试图片: 柱状图
└── ui_screenshot.png # 测试图片: UI 界面Pix2Struct 的 T5 解码器使用相对位置注意力偏置,这与 npu_fusion_attention 的标准 Flash Attention 接口不兼容。torch.compile(backend="npu") 可以透明处理这一问题。
Pix2Struct (282M) 是较小的模型,单次推理只需 ~300ms。TASK_QUEUE_ENABLE 和 CPU_AFFINITY_CONF 主要针对大模型(7B+)的调度和绑核优化。对于 Pix2Struct,推理瓶颈在算子级计算而非调度。
> 和 <img_src=...>?这是 Pix2Struct 的预训练特征。模型在预训练时学习了 HTML 格式的结构化输出。<img_src=...> 标签表示模型识别出的图片区域。
Apache License 2.0