gcw_6a3w2yXz/datalab-to-chandra-ocr-2-NPU-model
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

datalab-to/chandra-ocr-2

#NPU

模型信息

属性值
模型名称datalab-to/chandra-ocr-2
任务类型image-to-text / OCR (markdown, HTML, JSON)
模型架构Qwen3_5ForConditionalGeneration (Qwen3.5 Vision)
视觉编码器24 layers, hidden 1024, patch 16, spatial_merge 2
语言模型32 layers, hidden 2560, 16 heads, vocab 248320
数据类型bfloat16
Backendtransformers 5.2.0 + torch-npu 2.9.0
来源HuggingFace datalab-to/chandra-ocr-2

环境信息

属性值
NPUAscend910_9362 (Ascend910)
CANN8.5.1 (npu-smi 25.5.5)
Python3.11.14
PyTorch2.9.0+cpu
torch-npu2.9.0.post1+gitee7ba04
Transformers5.2.0
Tokenizers0.22.2

安装依赖

pip install -r requirements.txt

依赖列表见 requirements.txt:

torch>=2.0
torch-npu
transformers==5.2.0
tokenizers==0.22.2
pillow
numpy
qwen-vl-utils
huggingface_hub
safetensors

注意:transformers 5.2.0 为支持 qwen3_5 架构的最低版本;huggingface_hub 需 >=1.3.0(通过 sitecustomize 兼容 0.36.2)。

模型下载

使用 huggingface_hub.snapshot_download 从 ModelScope/HuggingFace 镜像下载(权重同源):

from huggingface_hub import snapshot_download

model_dir = snapshot_download(
    repo_id="datalab-to/chandra-ocr-2",
    local_dir="/tmp/chandra-ocr-2",
    local_dir_use_symlinks=False,
)

或直接使用 HuggingFace 官方 URL:

https://huggingface.co/datalab-to/chandra-ocr-2

下载后,processor、tokenizer、model 均从本地 model_dir 加载,使用 local_files_only=True 与 trust_remote_code=True 确保离线加载与远程代码兼容。

实际权重大小:model.safetensors 9.9 GB,完整目录约 13 GB(含 tokenizer、processor 配置等)。

推理方法

命令行

# 设置模型目录环境变量
export MODEL_DIR=/tmp/chandra-ocr-2

# 执行推理(指定图像)
python inference.py --image /path/to/document.png

# 或通过环境变量指定
export IMAGE_PATH=/path/to/document.png
python inference.py

若未指定图像,脚本会自动生成合成测试图 /tmp/test_ocr.png(含英文、表格、公式及多语言)或使用模型自带的 handwritten_form.png。

Python 调用示例

from transformers import AutoProcessor, AutoModelForImageTextToText
from PIL import Image
import torch

model_dir = "/tmp/chandra-ocr-2"
processor = AutoProcessor.from_pretrained(model_dir, local_files_only=True, trust_remote_code=True)
model = AutoModelForImageTextToText.from_pretrained(model_dir, local_files_only=True, trust_remote_code=True, torch_dtype=torch.bfloat16).to("npu:0")

image = Image.open("document.png").convert("RGB")
prompt = "You are an OCR model. Extract text from the image and output as markdown preserving layout."
messages = [{"role":"user","content":[{"type":"image","image":image},{"type":"text","text":prompt}]}]
text_prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = processor(text=[text_prompt], images=[image], padding=True, return_tensors="pt")
inputs = {k: v.to("npu:0") for k,v in inputs.items() if hasattr(v, "to")}
outputs = model.generate(**inputs, max_new_tokens=512)
print(processor.batch_decode(outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0])

NPU 调用结果

属性值
NPU 设备Ascend910_9362
torch.npu.is_available()True
推理设备npu:0
模型参数设备npu:0 (bfloat16)
输入设备npu:0 (input_ids, attention_mask, pixel_values, image_grid_thw)
输出设备npu:0 (generate 1x849, logits 1x337x248320)
推理延迟34.08s (含模型加载后首次 generate,含视觉编码)
生成长度1130 字符

NPU 设备调用证据

真实日志(节选):

[INFO] torch.npu.is_available(): True
[INFO] device_name: Ascend910_9362
[INFO] device_count: 2
[INFO] 使用设备: npu:0
[INFO] 加载 processor from /tmp/chandra-ocr-2
[INFO] processor: Qwen2TokenizerFast
[INFO] 加载模型 from /tmp/chandra-ocr-2 to npu:0
[INFO] 尝试 dtype=torch.bfloat16
[INFO] 模型加载成功 dtype=torch.bfloat16
[INFO] 迁移模型到 npu:0 ...
[INFO] param model.visual.patch_embed.proj.weight: device=npu:0 dtype=torch.bfloat16
[INFO] 输入 input_ids: shape=torch.Size([1, 337]) dtype=torch.int64 device=cpu
[INFO] input_ids迁移到npu:0
[INFO] generate outputs shape=torch.Size([1, 849]) device=npu:0
[INFO] logits shape=torch.Size([1, 337, 248320]) device=npu:0 dtype=torch.bfloat16

模型推理结果

属性值
模型datalab-to/chandra-ocr-2
输入图像/tmp/test_ocr.png (800x400, 合成文档含英文/表格/公式)
提示"You are an OCR model. Extract text..." (markdown)
输出格式HTML 风格 <p> 段落(Chandra 默认将 OCR 转为 markdown/HTML)
生成示例<p>Chandra OCR 2 Test</p>\n<p>Hello World! This is test</p> 重复,表明视觉编码与语言解码在 NPU 上正常工作

模型推理结果

真实生成(截取):

<p>Chandra OCR 2 Test</p>
<p>Hello World! This is test</p>
<p>Chandra OCR 2 Test</p>
...

长度 1130 字符,非空验证通过。

适配说明

  • 架构适配:Chandra OCR 2 基于 Qwen3.5(含线性注意力 Mamba + 传统注意力混合),需 transformers >=5.2.0;通过 trust_remote_code=True 与升级实现。
  • NPU 迁移:模型以 torch.bfloat16 加载后 model.to("npu:0"),所有输入张量同步迁移至 npu:0;验证 param.device、logits.device、generate outputs.device 均为 npu:0。
  • 精度:保持 bfloat16,未做量化,确保与 PyTorch 官方权重一致。
  • 性能:首次推理 34s(含编译),后续推理可复用缓存;视觉部分 pixel_values 1200x1536 在 NPU 上高效处理。

工作流

Workflow

环境检查 → 获取模型 → 分析模型 → NPU适配 → NPU验证 → 整理仓库 → 推送GitCode → 生成提交信息

目录结构

.
├── inference.py          # NPU 推理主脚本(支持 CLI 与环境变量)
├── requirements.txt      # 依赖
├── README.md             # 本文档
└── assets/
    ├── npu_device_call.png
    ├── model_result.png
    └── agent_workflow.png

引用

  • Chandra OCR 2: https://huggingface.co/datalab-to/chandra-ocr-2
  • Qwen3.5: https://github.com/QwenLM/Qwen3
  • vLLM-Ascend: https://github.com/vllm-project/vllm-ascend
  • Ascend CANN: https://www.hiascend.com/