本文档记录 TahaDouaji/detr-doc-table-detection DETR 表格检测模型在昇腾 NPU(Ascend 910B3)上的迁移适配、精度评测与性能验证结果。
DETR(DEtection TRansformer)是 Facebook Research 提出的端到端目标检测模型,将目标检测转化为集合预测问题。该模型基于 ResNet-50 backbone + Transformer Encoder-Decoder,在文档表格数据集上微调,专门检测文档图像中的表格(table)区域。输入为任意尺寸 RGB 图像,输出检测框坐标(x1, y1, x2, y2)及置信度分数。
相关获取地址:
| 组件 | 版本 |
|---|---|
torch | 2.8.0 |
torch_npu | 2.8.0.post4 |
transformers | 5.8.1 |
timm | 1.0.27 |
CANN | 8.5.1 |
8 × Ascend 910B3timm 库conda create -n TahaDouaji--detr-doc-table-detection python=3.11 -y
conda activate TahaDouaji--detr-doc-table-detection
pip install torch==2.8.0 torch_npu==2.8.0.post4 timm \
-i https://pypi.tuna.tsinghua.edu.cn/simple
pip install transformers torchvision pillow numpy \
-i https://pypi.tuna.tsinghua.edu.cn/simpleDETR 的 ResNet backbone 通过
timm库加载(TimmBackbone),需显式安装。
python inference.py --image document.jpg --device npu
python inference.py --image_dir ./documents/ --device npu编程接口:
from inference import DetrDetector
detector = DetrDetector(
model_path="./TahaDouaji--detr-doc-table-detection", device="npu"
)
results = detector.detect(["document.jpg"], threshold=0.5)
# results[0] → {'scores': [0.95], 'labels': ['table'], 'boxes': [[x1,y1,x2,y2]]}python inference.py --image document.jpg --device npu预期输出:检测到的表格数量、每个框的坐标和置信度。无检测时输出空列表,无运行时错误。
测试条件:4 张合成 640×480 图像(固定随机种子),batch_size=2,NPU 预热 1 轮。
| 指标 | 数值 |
|---|---|
| CPU 吞吐量 | 0.3 img/s |
| NPU 吞吐量 | 8.5 img/s |
| CPU/NPU 加速比 | 28.7 × |
DETR 模型较大(ResNet-50 + 100 object queries),CPU 推理极慢(0.3 img/s)。NPU 通过对 ResNet 卷积和 Transformer 注意力算子的原生加速获得 28.7× 提升,但绝对吞吐仍较低,适合离线批处理。
分别在 CPU 和 NPU 上推理 4 张合成图像,比较 DETR 的 100 个 object query 分类 logits(展平后比较)。
| 指标 | 数值 |
|---|---|
| 平均余弦相似度 | 1.000000 |
| 精度误差率 | 0.0000% |
结论:精度误差率 0.0000%,NPU 与 CPU logits 完全一致,评测通过。
timm 的 TimmBackbone 加载),输出多尺度特征图DetrForObjectDetection.from_pretrained() 加载,需 timm 库支持 backbonemodel.to("npu:0") 迁移,ResNet 卷积 + Transformer 注意力 NPU 原生加速AutoImageProcessor 在 CPU 完成图像预处理(resize + normalize),tensor 转移至 NPUprocessor.post_process_object_detection)在 CPU 完成:过滤低置信度框 + 坐标映射import torch, torch_npu
from PIL import Image
from transformers import AutoImageProcessor, DetrForObjectDetection
model = DetrForObjectDetection.from_pretrained("detr-doc-table-detection").to("npu:0")
processor = AutoImageProcessor.from_pretrained("detr-doc-table-detection")
image = Image.open("document.jpg").convert("RGB")
inputs = processor(images=image, return_tensors="pt")
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(
outputs, target_sizes=target_sizes, threshold=0.5
)timm 库的 TimmBackbone 加载,缺少 timm 会报 ImportError: TimmBackbone requires the timm library。必须 pip install timm。