本仓库基于 Microsoft 的 LayoutLM 模型架构,在 FUNSD(Form Understanding in Noisy Scanned Documents)数据集上进行了微调,用于文档布局分析和表单理解任务。模型能够对扫描文档中的文本进行语义标注,识别出 HEADER(标题)、QUESTION(问题)、ANSWER(答案)等关键信息类型。
通过本推理服务,用户可以将模型部署到华为昇腾 Ascend NPU 上运行,实现对文档图像的智能解析和信息抽取。模型权重来自 philschmid/layoutlm-funsd,采用 LayoutLMForTokenClassification 架构,具备 12 层 Transformer 编码器,隐藏维度 768。该模型在 FUNSD 评测集上取得了整体 F1 分数 78.66%、准确率 81.06% 的成绩。
LayoutLM 是专为文档理解设计的预训练模型,其核心创新在于将文本语义与二维版面布局信息深度融合。与标准 BERT 模型不同,LayoutLM 在 Embedding 层额外引入了四组位置编码:
这些位置编码与标准 word_embeddings、position_embeddings、token_type_embeddings 相加后输入 Transformer 编码器,使模型能够同时感知"是什么词"和"在文档的什么位置"。编码器由 12 层 LayoutLMAttention 组成,每层包含 12 个注意力头,隐藏层维度 768,前馈网络维度 3072。
模型在 FUNSD 数据集上经过 15 个 epoch 的训练,使用 Adam 优化器(学习率 3e-5),批大小 16,最终输出 7 类标签的 token 级分类结果。
| 组件 | 版本 |
|---|---|
| 操作系统 | Linux 5.10.0 (aarch64) |
| NPU 硬件 | Ascend 910B (64GB HBM) |
| CANN | 8.5.1 |
| Python | 3.11.14 |
| PyTorch | 2.9.0 |
| torch_npu | 2.9.0.post1 |
| transformers | 4.57.6 |
| fastapi | 0.123.10 |
| uvicorn | 0.46.0 |
| 推理框架 | FastAPI + torch_npu |
# 进入模型目录
cd /opt/atomgit/layoutlm-funsd
# 启动服务(默认监听 8000 端口)
python3 inference.py服务启动后会自动加载模型至 NPU 设备,并自动完成一次预热推理以确保服务就绪。启动过程约需 2.2 秒(含模型加载和预热)。可通过以下方式验证服务状态:
curl http://localhost:8000/health预期返回:
{"status":"healthy","device":"npu:0","model":"philschmid/layoutlm-funsd","model_type":"LayoutLMForTokenClassification"}# 使用 NPU 设备 1,端口 8080
DEVICE_ID=1 PORT=8080 python3 inference.pynohup python3 inference.py > service.log 2>&1 &
echo $! > service.pid
# 查看日志
tail -f service.logcurl -s http://localhost:8000/health | python3 -m json.toolimport requests
import json
payload = {
"words": ["INVOICE", "Date:", "2024-01-15", "Total:", "$1,234.56"],
"boxes": [[50,20,200,60], [50,80,120,105], [130,80,230,105],
[50,120,130,145], [140,120,250,145]],
"max_length": 512
}
r = requests.post("http://localhost:8000/inference", json=payload)
result = r.json()
print(f"推理耗时: {result['inference_time_ms']} ms")
print(f"实体数量: {len(result['entities'])}")
for entity in result['entities']:
print(f" [{entity['type']}] {entity['text']} (score: {entity['score']})")import requests, time
# 准备多组测试数据
test_cases = [
{"words": ["Name:", "John Doe", "Age:", "30"], "boxes": [[0,0,80,30],[90,0,200,30],[0,40,80,70],[90,40,200,70]]},
{"words": ["Title:", "Report", "Date:", "2024-06-01"], "boxes": [[0,0,80,30],[90,0,200,30],[0,40,80,70],[90,40,200,70]]},
{"words": ["Amount:", "$500", "Status:", "Paid"], "boxes": [[0,0,100,30],[110,0,200,30],[0,40,100,70],[110,40,200,70]]},
]
times = []
for case in test_cases:
t0 = time.time()
r = requests.post("http://localhost:8000/inference", json=case)
times.append((time.time() - t0) * 1000)
print(f"平均耗时: {sum(times)/len(times):.1f} ms")
print(f"最小耗时: {min(times):.1f} ms")
print(f"最大耗时: {max(times):.1f} ms")| 指标 | 数值 |
|---|---|
| 模型参数量 | 113M |
| 推理时延(单次,27词) | ~33 ms |
| 推理时延(单次,4词) | ~25 ms |
| 推理时延(单次,512词满长) | ~85 ms |
| NPU 显存占用 | ~632 MB |
| 模型加载时间 | ~2.2 s |
| 输入最大长度 | 512 tokens |
| 支持标签类型 | 7 类(O, B-HEADER, I-HEADER, B-QUESTION, I-QUESTION, B-ANSWER, I-ANSWER) |
| 模型文件大小 | 430 MB(pytorch_model.bin) |
| 支持的并发连接数 | 建议 ≤ 4(单卡单进程) |
推理性能数据基于 Ascend 910B 设备,单次请求单文档输入测得。时延会随输入长度线性增加,满长 512 token 时约 85ms。
模型在 FUNSD 评测集上的详细指标如下:
| 类别 | 样本数 | 精确率 | 召回率 | F1 分数 |
|---|---|---|---|---|
| Answer | 809 | 73.48% | 80.84% | 76.99% |
| Header | 119 | 44.29% | 52.10% | 47.88% |
| Question | 1065 | 82.11% | 84.04% | 83.06% |
| 整体 | 1993 | 75.99% | 80.83% | 78.66% |
整体准确率(Accuracy)达 81.06%。从数据可以看出,Question 类别因样本量充足(1065 个)表现最优,F1 达到 83.06%;Header 类别因样本量较少(119 个)且语义边界模糊,指标相对偏低,实际使用中可考虑对 Header 预测结果做二次校验。
# 使用测试脚本进行批量推理验证
python3 -c "
import requests
test_cases = [
(['INVOICE', 'Date:', '2024-01-15'], [[50,20,200,60], [50,80,120,105], [130,80,230,105]]),
(['Customer:', 'Acme Corp', 'Total:', '\$350.00'], [[50,160,160,185], [170,160,280,185], [280,400,400,425], [410,400,490,425]]),
(['Payment Terms:', 'Net 30', 'Due Date:', '2024-02-15'], [[50,450,200,475], [210,450,290,475], [50,500,160,525], [170,500,290,525]]),
]
for words, boxes in test_cases:
r = requests.post('http://localhost:8000/inference', json={'words': words, 'boxes': boxes})
result = r.json()
print(f'Input: {words}')
for entity in result['entities']:
print(f' [{entity[\"type\"]}] {entity[\"text\"]} (conf: {entity[\"score\"]})')
print()
"以下是一个完整的端到端推理示例,展示了如何将 OCR 结果与模型结合使用:
import requests
# 假设通过 OCR 从文档中提取了以下信息
ocr_results = [
("INVOICE", 50, 20, 200, 60),
("Date:", 50, 80, 120, 105),
("2024-01-15", 130, 80, 230, 105),
("Total:", 50, 120, 130, 145),
("$1,234.56", 140, 120, 250, 145),
]
# 转换为模型输入格式
words = [r[0] for r in ocr_results]
boxes = [[r[1], r[2], r[3], r[4]] for r in ocr_results]
# 发送推理请求
resp = requests.post("http://localhost:8000/inference", json={
"words": words, "boxes": boxes, "max_length": 512
}).json()
# 解析结果
if resp["success"]:
print(f"推理完成,耗时 {resp['inference_time_ms']}ms")
print(f"文档结构:")
for entity in resp["entities"]:
print(f" [{entity['type']}] {entity['text']}")