atlasleong/layoutlm-funsd-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

layoutlm-funsd — token-classification on Ascend NPU (torch_npu)

模型简介

philschmid/layoutlm-funsd is a LayoutLM (base, uncased) model fine-tuned on the FUNSD (Form Understanding in Noisy Scanned Documents) dataset for token-classification. It classifies each token of a form-like document image into FUNSD entity labels: O, B-HEADER, I-HEADER, B-QUESTION, I-QUESTION, B-ANSWER, I-ANSWER.

This repository adapts the pinned upstream revision 5dc97b05b27e5efed5f331a2216726dd7b338e43 for inference with torch_npu on the physical device npu:4 (Ascend 910B4-1). The local model directory is /work/pipeline/models/other40/layoutlm-funsd and the weight blob pytorch_model.bin is 450606565 bytes, SHA256 4f31380262cd4f276be211189196f190c0268e9cece977d500886a4e4c16fc07.

FieldValue
Modelphilschmid/layoutlm-funsd
Sourcehttps://huggingface.co/philschmid/layoutlm-funsd
Pinned revision5dc97b05b27e5efed5f331a2216726dd7b338e43
Tasktoken-classification (LayoutLMForTokenClassification)
Base architecturemicrosoft/layoutlm-base-uncased (hidden_size 768, 12 layers)
Label setO, B-/I-HEADER, B-/I-QUESTION, B-/I-ANSWER
Enginetorch_npu (top-level engine='torch_npu')
Requested / physical devicenpu:4 / 4 (direct, no ASCEND_RT_VISIBLE_DEVICES mapping)
Local weightspytorch_model.bin — 450606565 B, SHA256 4f313802...16fc07

环境依赖

Verified on (this delivery's real tested environment):

ComponentVersion
OSopenEuler 24.03 (LTS-SP2), aarch64
NPUAscend 910B4-1 (npu:4), 8 devices present
CANNAscend-cann-toolkit 8.5.1
Driver / npu-smi25.5.1 (firmware 7.8.0.6.201)
Python3.11.14
torch2.9.0+cpu (preinstalled, matched pair)
torch_npu2.9.0 (preinstalled, matched pair)
transformers4.40.1
tokenizers0.19.1
numpy1.26.4
Pillow12.3.0
huggingface-hub0.36.2
safetensors0.8.0

Important: the container already provides a matched torch/torch_npu pair. Do not replace them with ordinary PyPI wheels. Install only the remaining Python dependencies listed in requirements.txt using the configured package mirror.

Files

inference.py                  End-to-end NPU inference script (no CPU fallback, npu:4)
run_npu_inference.sh          Monitored runner (concurrent npu-smi + ps -> canonical logs)
requirements.txt              Python dependencies
readme.md / README.md         This document
scripts/render_assets.py      Renders the four evidence screenshots from real logs
scripts/validate_delivery.py  Delivery validator
scripts/validate_metadata.py  Metadata/evidence validator (cross-checks real weights)
assets/agent_workflow.png     Adaptation workflow diagram (real values)
assets/modelagent_live_session.png  Sanitized Agent live-session dialogue
assets/npu_device_call.png    Real npu-smi device-call capture for npu:4
assets/model_result.png       Real model output / acceptance summary
assets/synthetic_invoice.png  Rendered synthetic test input (CC0-1.0)
logs/npu_inference.log        Raw inference log (this round)
logs/npu_device_call.log      Canonical npu-smi + PID capture (this round)
logs/npu_result.json          Structured result JSON
logs/modelagent_dialogue_sanitized.txt  Sanitized Agent dialogue (this round)

Install dependencies

export PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/
export PIP_TRUSTED_HOST=mirrors.aliyun.com
pip install -r requirements.txt

requirements.txt deliberately does not pin torch/torch_npu; they must come from the container's matched NPU environment.

推理步骤

Monitored run (recommended, produces the canonical logs)

./run_npu_inference.sh npu:4 512

This runs inference.py on the physical device npu:4, writes stdout to logs/npu_inference.log, and concurrently samples npu-smi info + ps into logs/npu_device_call.log (correlating the container Python PID with the host-side device PID). Exit code is propagated.

Direct run

python3 inference.py --device npu:4 --max-length 512 --out-dir logs

The script:

  1. Checks torch.npu.is_available() and fails non-zero if the NPU is not available (no CPU fallback).
  2. Sets the device to the physical npu:4 and refuses any ASCEND_RT_VISIBLE_DEVICES remapping.
  3. Loads the local model and verifies the pinned weight SHA256 / size (no re-download).
  4. Moves the model to npu:4 and asserts the first parameter is on npu:4.
  5. Tokenizes the synthetic invoice (CPU, required by the tokenizer library).
  6. Moves every input tensor (input_ids, token_type_ids, attention_mask, bbox) to npu:4.
  7. Runs the forward pass in torch.inference_mode().
  8. Post-processes predictions on CPU and prints token-level FUNSD labels.
  9. Writes logs/npu_result.json with top-level engine='torch_npu', requested_device='npu:4', physical_device=4, and input_device/model_device/output_device='npu:4'.

Optional arguments (inference.py)

ArgumentDefaultDescription
--model-dir/work/pipeline/models/other40/layoutlm-funsdlocal model directory
--devicenpu:4physical NPU device (must be npu:4)
--max-length512tokenizer/sequence max length
--out-dir<workdir>/logsoutput directory for logs
--no-render-imageTruedisable rendering the synthetic invoice image

Test input (redistributable, license recorded)

The inference uses a synthetic fake-invoice document (header + question/answer pairs) whose words and normalized bounding boxes are defined in inference.py.

  • Source: synthetic — generated by inference.py; also rendered to assets/synthetic_invoice.png.
  • License: CC0-1.0 (public domain).

No OCR dependency is required; the words + boxes are fed directly to LayoutLMv2Tokenizer, which is exactly the deterministic input path the model expects.

完整测试用例与输出结果

Command (this round, 2026-08-22T19:44:07Z):

PYTHON=python3 ./run_npu_inference.sh npu:4 512

Monitor summary:

[monitor] python PID=197568
[monitor] exit_code=0 samples=18 pid=197568

Exit code: 0 — elapsed: 24.9370 s (forward pass 0.2953 s).

Input: 17 words, max_length=512, all inputs placed on npu:4 (input_ids (1,512), bbox (1,512,4), token_type_ids (1,512), attention_mask (1,512)).

Output: logits shape (1, 512, 7), device npu:4.

Real predictions from logs/npu_inference.log:

[LAYOUTLM-NPU] [7] Running NPU inference on npu:4 (inference_mode)
[LAYOUTLM-NPU]   forward elapsed = 0.2953s
[LAYOUTLM-NPU]   logits shape    = (1, 512, 7)  device = npu:4
[LAYOUTLM-NPU] [8] Post-processing
[LAYOUTLM-NPU]   total decoded tokens = 41
[LAYOUTLM-NPU]   non-O predictions    = 40
[LAYOUTLM-NPU]   tok  1  B-HEADER   0.9827  'in'   bbox=[300, 20, 700, 80]
[LAYOUTLM-NPU]   tok  4  B-QUESTION 0.9966  'date' bbox=[50, 120, 150, 160]
[LAYOUTLM-NPU]   tok  5  B-ANSWER   0.9874  '202'  bbox=[170, 120, 320, 160]
[LAYOUTLM-NPU]   tok 10  I-ANSWER   0.9380  '21'   bbox=[170, 120, 320, 160]
[LAYOUTLM-NPU]   tok 28  B-QUESTION 0.9984  'total' bbox=[50, 360, 170, 400]
[LAYOUTLM-NPU]   tok 30  B-ANSWER   0.9890  'usd'  bbox=[280, 360, 330, 400]
[LAYOUTLM-NPU]   tok 31  I-ANSWER   0.9624  '500'  bbox=[340, 360, 460, 400]
[LAYOUTLM-NPU]   tok 34  B-QUESTION 0.9982  'due'  bbox=[50, 440, 150, 480]
[LAYOUTLM-NPU]   tok 36  B-ANSWER   0.9876  '202'  bbox=[240, 440, 380, 480]
[LAYOUTLM-NPU]   ...
[LAYOUTLM-NPU]   label distribution = {'B-HEADER': 1, 'I-HEADER': 3,
[LAYOUTLM-NPU]                          'B-QUESTION': 5, 'B-ANSWER': 6,
[LAYOUTLM-NPU]                          'I-ANSWER': 20, 'I-QUESTION': 5}
[LAYOUTLM-NPU] [9] Done. exit_code=0 elapsed=24.9370s

Structured result (logs/npu_result.json):

KeyValue
enginetorch_npu
exit_code0
npu_availabletrue
requested_devicenpu:4
physical_device4
input_device / model_device / output_devicenpu:4
output.logits_shape[1, 512, 7]
model.weight_sha2564f31380262cd4f276be211189196f190c0268e9cece977d500886a4e4c16fc07
timing.forward_elapsed_s0.2953
timing.total_elapsed_s24.937

Device-call evidence (logs/npu_device_call.log): container PID 197568 (python3 inference.py ... --device npu:4) correlates with the device 4 process table host PID 3583292; NPU 4 HBM rose 3400 -> 3535 -> 3400 MB (confirms the model weights were resident on device 4) and device power peaked at 100.2 W. AICore sampled at 0% at the 1 s cadence — the 0.2953 s forward burst is shorter than the sampling interval, so the instantaneous AICore column does not capture it.

The model correctly identifies the invoice header, field labels as QUESTION, and the corresponding values as ANSWER — meaningful token-classification output on the NPU.

Checks performed

  • python3 -m py_compile inference.py — syntax OK.
  • Static scan for CUDA/CPU-fallback patterns (torch.cuda, silent .cpu() model placement) — none in the model path; .cpu() calls exist only for post-processing output tensors.
  • Fresh end-to-end NPU inference on npu:4 — exit code 0, logits on npu:4, meaningful predictions, result JSON written with the normative top-level fields.
  • scripts/validate_delivery.py and scripts/validate_metadata.py run twice and passing; sha256sum -c SHA256SUMS passing; secret/artifact scan clean.

The SLAI check_adaptation.py / check_accuracy_run.py checkers target the SLAI adaptations/<name>/demo.py + pyproject.toml + uv.lock layout and are therefore not directly applicable to this standalone inference.py deliverable; the equivalent checks above (syntax + static + end-to-end NPU) are used instead.

Model card summary (from upstream)

This model is a fine-tuned version of microsoft/layoutlm-base-uncased on the funsd dataset. Evaluation results: overall Precision 0.7599, Recall 0.8083, F1 0.7866, Accuracy 0.8106.

验收截图

Agent 完整适配工作流

Agent 完整适配工作流

Agent 真实脱敏对话

Agent 真实脱敏对话

NPU 硬件设备调用日志

NPU 硬件设备调用日志

模型最终适配验收结果

模型最终适配验收结果