s
stella4528/table-transformer-detection-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Table-Transformer-Detection (Ascend NPU 适配)

基于 microsoft/table-transformer-detection(Table Transformer,ECCV 2022)的表格检测模型,已适配在华为昇腾 Ascend 910 NPU 上直接运行(torch_npu),同时保留 CPU 回退能力。

  • 架构:TableTransformerForObjectDetection(ResNet-18 骨干 + 6 层编码器 + 6 层解码器 + DETR 检测头)
  • 检测头:15 个查询,2 类目标(table / table rotated)
  • 权重:model.safetensors(fp32,约 28.8M 参数,115MB)
  • 输入:RGB 图片(DetrImageProcessor 归一化 + resize 到 800)
  • 输出:logits [B,15,3](类别置信度)+ pred_boxes [B,15,4](归一化 cxcywh)
  • 后处理:post_process_object_detection → 原图坐标 xyxy 框 + label + score

输入 / 输出

项说明
输入任意尺寸 RGB 图片([B,3,H,W],经 DetrImageProcessor 归一化 + resize)
输出logits [B,15,3] + pred_boxes [B,15,4](归一化 cxcywh)
后处理post_process_object_detection → 原图坐标 xyxy 框 + label + score

环境依赖

见 requirements.txt:torch>=2.1、transformers>=4.30、timm、pillow、numpy;NPU 推理需 torch_npu(版本与 torch 匹配,如 torch 2.9.0 + torch_npu 2.9.0)。

注意:本适配使用 use_pretrained_backbone=False 加载(backbone 权重直接从本地 model.safetensors 读取),避免 timm 联网下载 ResNet-18 预训练权重,适用于网络受限的 NPU 环境。

推理示例

# 使用合成测试图(默认用例)
python3 inference.py

# 使用真实图片
python3 inference.py --image demo.jpg --threshold 0.7 --output result.json --save annotated.png

# 指定模型目录 / 设备
python3 inference.py --model-dir ./model --device npu

示例输出(Ascend 910 NPU 实测):

[device] 使用 npu:0
[model] 参数量: 28.80M
[infer] 推理耗时: 0.281s
[detect] table        score=0.9992 box=[55.1, 72.7, 633.3, 525.0]

验证证据

  • assets/model_result.png:检测结果可视化(合成表格图 + 检测框)
  • 推理输出 JSON:result.json(含 device / 推理耗时 / 检出框)

六件套复现脚本与验收结果(2026-08-24 实测)

脚本作用验收结果
common.py模型/processor 加载 + 合成测试图(公共模块)—
minimal_repro.pyminimal 前向 CPU vs NPU(logits/pred_boxes)rel-L2=8.37e-05 / cos=0.9999999 → PASS
accuracy_eval.pyCPU 与 NPU 独立子进程精度对齐logits rel-L2=8.37e-05,pred_boxes rel-L2=4.56e-05 → PASS
benchmark.pyNPU warmup5+正式20 次性能基准p50=15.963ms,mean=15.961ms,p95=16.186ms
stability.py20 轮 × batch1 逐位一致bitwise_identical=true,max_abs_diff=0.0 → PASS
inference.py推理演示(NPU/CPU,合成图或真实图)检出 table score≈0.999,全 finite

复现:pip install -r requirements.txt 后依次运行 python3 minimal_repro.py、 python3 accuracy_eval.py、python3 benchmark.py、python3 stability.py、python3 inference.py。 验收结果 JSON 落盘于 results/(minimal_result.json / accuracy_result.json / benchmark_result.json / stability_result.json)。

仓库文件

  • inference.py — 推理脚本(NPU/CPU 通用,支持本地权重、合成测试图、结果 JSON 与标注图输出)
  • common.py / minimal_repro.py / accuracy_eval.py / benchmark.py / stability.py — 六件套复现脚本
  • config.json / preprocessor_config.json / model.safetensors — 模型权重与配置(Git LFS)
  • requirements.txt — 环境依赖清单