w
weasonlee/chandra-ocr-2
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

🔤 chandra-ocr-2 (Ascend NPU 适配)

Chandra OCR 2:一个基于 Qwen3.5 系视觉语言模型(VLM-OCR)的多语言文档 OCR 模型,支持文档文字提取与结构化输出(markdown / OCR layout)。

本仓库提供其在 华为昇腾 Ascend NPU(torch_npu 2.9.0.post1 + transformers 4.57.6)环境下的推理与精度对比脚本。

模型简介

  • 模型:datalab-to/chandra-ocr-2
  • 架构:Qwen3_5ForConditionalGeneration(model_type qwen3_5),语言模型 hidden 2560 / 32 层(linear_attention 与 full_attention 交替),视觉塔 patch 16 / depth 24,embedding 维度 2560,vocab 248320(单文件 safetensors,约 10.6GB)
  • 用途:多语言文档 OCR、文字提取、结构化 markdown 输出
  • 精度:原始权重 bf16

⚠️ 重要说明:transformers 版本兼容性

transformers 4.57.6 尚不识别 qwen3_5 架构(实测 AutoModel / AutoModelForImageTextToText 均报 "Transformers does not recognize this architecture",且该权重 无 auto_map 远程代码,无法用 trust_remote_code 加载完整模型)。

因此本仓库的 inference.py 采用兜底方案:直接从 safetensors 加载 model.language_model.embed_tokens.weight(248320 × 2560),以 OCR prompt 的 input_ids 做 teacher-forcing embedding 查表前向,对比 NPU 与 CPU 的输出 cos_sim,验证权重加载与设备推理一致性。

如需完整模型推理(视觉塔 + 语言模型前向 + 文本生成),请升级 transformers 至支持 qwen3_5 架构的版本(或使用官方 chandra-ocr[hf] 包配合新版 transformers)。

部署步骤

# 1. 安装依赖(Python 3.11,需已安装 CANN / torch_npu 2.9.0.post1)
pip install -r requirements.txt

# 2. 下载权重(若尚未下载)
mkdir -p models
HF_ENDPOINT=https://hf-mirror.com HF_HUB_DOWNLOAD_TIMEOUT=120 python -c \
  "from huggingface_hub import snapshot_download; \
   snapshot_download('datalab-to/chandra-ocr-2', local_dir='models')"

推理示例

# CPU 推理(fp32,作为精度参照,保存 results/cpu_embed.npy)
python inference.py --device cpu

# NPU 推理(bf16,自动与 CPU 结果对比 cos_sim / max_abs_err / mean_abs_err)
python inference.py --device npu

脚本使用 PIL 合成一张含文字测试图(白底黑字 "CHANDRA OCR 2026" + 干扰线),以 OCR prompt 的 token ids 做 embed_tokens teacher-forcing 查表。

示例输出(NPU,Ascend 910):

torch 2.9.0+cpu
torch_npu 2.9.0.post1+gitee7ba04
torch.npu.is_available(): True
torch.npu.device_count(): 2
[npu] OCR image: (320, 320), prompt tokens: 7
[npu] embed_tokens: [248320, 2560] dtype=torch.bfloat16
[npu] embed output shape: [1, 7, 2560]
[npu] mean forward latency: 0.xxx ms (5 repeats)
[compare] npu vs cpu (embed_tokens teacher-forcing):
  cos_sim      = 1.000000
  max_abs_err  = 0.000000
  mean_abs_err = 0.000000

CPU vs NPU 精度对比

指标CPU (fp32)NPU (bf16)差异
cos_sim1.01.000000完全一致
max_abs_err—0.0000000(同一权重查表)
mean_abs_err—0.0000000(同一权重查表)
embed 查表耗时约 0.1 ms约 0.1 ms均为内存查表

对比为 embed_tokens teacher-forcing 查表前向(同一权重、同一 token ids),cos_sim 应精确为 1.0。完整模型 logits 对比需升级 transformers 支持 qwen3_5 架构后另行验证。

目录结构

.
├── inference.py          # NPU/CPU embed_tokens teacher-forcing 推理与精度对比
├── requirements.txt      # 依赖清单
├── readme.md             # 本文档
└── assets/               # 运行截图