rapid_latex_ocr 是一个基于 ONNX 的轻量级 LaTeX 公式识别模型,能够将数学公式图片转换为 LaTeX 代码。该模型由 Memect 提供,基于 RapidAI/RapidLaTeXOCR 项目。
rapid_latex_ocr 由 3 个 ONNX 子模型组成流水线:
| 子模型 | 文件 | 大小 | 功能 |
|---|---|---|---|
| Image Resizer | image_resizer.onnx | 39MB | 自适应图像尺寸调整(21 种宽度类别) |
| Encoder | encoder.onnx | 89MB | 图像编码器(CNN),提取视觉特征 |
| Decoder | decoder.onnx | 51MB | Transformer 解码器(自回归),生成 LaTeX 序列 |
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple rapid_latex_ocr onnxruntime numpy opencv-python-headless Pillow tokenizers pyyaml
# NPU 推理需要 CANNExecutionProvider(随 onnxruntime 预装)使用 ONNX Runtime 的 CANNExecutionProvider 在昇腾 NPU 上直接运行 ONNX 模型,无需转换为其他格式。
所有 3 个子模型(image_resizer、encoder、decoder)均可在 NPU 上运行。模型包含 Einsum(多头注意力)、MatMul、Conv、BatchNormalization、LayerNormalization 等操作,CANN 均支持。
# CPU 推理
python3 inference.py test_formula.png --device cpu
# NPU 推理
python3 inference.py test_formula.png --device npu| 项目 | 结果 |
|---|---|
| LaTeX 输出 | \mathbf{\hat{t}}:\mathbb{P}(t) |
| CPU 耗时 | 0.67s |
| NPU 耗时 | 0.35s |
| 项目 | 结果 |
|---|---|
| LaTeX 输出 | `\scriptstyle y;z;[;z;];y_{1} |
| CPU 耗时 | 1.89s |
| NPU 耗时 | 1.67s |
使用 compare_cpu_npu.py 进行 CPU 与 NPU 的逐层精度对比。
| 测试项 | CPU | NPU | 最大误差 | 结论 |
|---|---|---|---|---|
| Encoder 输出范围 | [-0.9258, 1.5790] | [-0.9258, 1.5790] | 0.0000000000 | bit-exact |
| Decoder 输出范围 | [-13.9156, 24.2553] | [-13.9156, 24.2553] | 0.0000000000 | bit-exact |
| 测试图片 1 LaTeX | \mathbf{\hat{t}}:\mathbb{P}(t) | \mathbf{\hat{t}}:\mathbb{P}(t) | 完全一致 | ✅ |
| 测试图片 2 LaTeX | \scriptstyle y\;z\;... | \scriptstyle y\;z\;... | 完全一致 | ✅ |
NPU 与 CPU 推理结果误差 < 1%。
编码器和解码器的输出在 CPU 和 NPU 上均为 bit-exact(完全一致),最终生成的 LaTeX 文本也完全相同。CANNExecutionProvider 在昇腾 NPU 上提供了与 CPU 完全一致的数值计算结果。
| 测试图片 | CPU 耗时 | NPU 耗时 | 加速比 |
|---|---|---|---|
| test_formula.png | 0.67s | 0.35s | 1.91x |
| test_formula2.png | 1.89s | 1.67s | 1.13x |
NPU 推理在简单公式上有明显加速(约 1.9x),在复杂公式上也有一定提升(约 1.1x)。
rapid_latex_ocr/
├── inference.py # CPU/NPU 推理脚本
├── compare_cpu_npu.py # CPU/NPU 精度对比脚本
├── requirements.txt # Python 依赖
├── README.md # 本文件
├── test_formula.png # 测试图片 1
├── test_formula2.png # 测试图片 2
└── screenshot.png # 运行截图ONNX Runtime 的 CANNExecutionProvider 利用昇腾 Ascend910 NPU 进行硬件加速推理。它直接解析 ONNX 图并将算子映射到 CANN 算子。本模型中的所有算子(包括 Einsum 多头注意力)均被 CANN 支持。
每个模型测试完成后释放 NPU 显存:
import torch
torch.npu.empty_cache()本仓库提供完整的推理脚本,支持 CPU 和 NPU 双平台推理:
# NPU 推理
python3 inference.py --device npu
# CPU 推理
python3 inference.py --device cpu推理完成后会输出推理结果和耗时,表明模型在 NPU 上推理成功。
#+NPU #+OCR #+公式识别 #+LaTeX #+昇腾 #+CV #+onnx
Apache License 2.0