TL;DR
Most language models read a document as a flat list of words, which throws away where each word sits on the page. LayoutLM is a BERT-style model that adds two inputs to each word: its position in a 2-D coordinate system and an image of the word. It is pre-trained on about 11 million scanned document images, using the text and the positions, with the collection's document tags as an optional extra signal. Fine-tuned on forms, receipts and page classification, it beats text-only BERT and RoBERTa on each task it is tested on.
Builds on: BERT, Optical Character Recognition, Faster R-CNN · Leads to: LayoutLMv3
Why it mattered
Businesses receive large volumes of invoices, receipts, forms and letters. Pulling the amount, date, vendor and line items out of them used to need hand-written rules for each layout. The paper's authors observed that the layout carries meaning: a value is usually to the right of or below its label, such as "Passport ID:". A text-only model has to infer that from word order, which is unreliable on a scanned page.
The paper showed that one model pre-trained on unlabeled scans could be fine-tuned on several document tasks with small labeled sets. On the FUNSD form benchmark, which has 149 training forms, its best model reached an F1 score of 0.7927, against 0.6026 for BERT base. Later document models build on the same idea, including LayoutLMv3.
The history is short. BERT had shown that a model pre-trained on large text corpora with a masked-word task transferred well to many language tasks. Document systems had mostly used either vision models or language models on their own. The paper claims that it was the first to pre-train textual and layout information from scanned images in a single framework, and it adds image features on top of that.
The problem
Scanned documents are hard for three reasons, and the paper names them. The layouts vary from one template to the next. Scans are often noisy. And the information is often in tables, forms and boxes whose meaning depends on where the text sits.
Before LayoutLM, two families of approach existed. Vision approaches looked at the page as an image and could see fonts and boxes, but had little language understanding. Language approaches such as BERT read the words well, but saw only a sequence and ignored the page. Both also depended on a small amount of labeled data for each task. The authors asked how self-supervised pre-training could cover text and layout together, using the large collections of unlabeled scans that companies and archives already hold.
The method needs two extra inputs for this. It needs the position of each word on the page, which the paper gets from OCR, and an image crop of each word, which it gets from a detector. OCR is the step that turns the scanned page into text and boxes, and the paper uses the open-source Tesseract engine for it.
How it works
The steps below follow the order in which the model runs, from scanned page to output. The numbers are illustrative: we imagine a page 850 pixels wide and 1,100 pixels tall, with one word, "Total", in a box at pixel positions (100, 500) to (180, 520).
- Run OCR. The page is passed through OCR, which gives the word "Total" and its box in pixel coordinates: left 100, top 500, right 180, bottom 520. Check: the box is 80 pixels wide and 20 pixels high.
- Scale the coordinates. Every coordinate is rescaled to a virtual page that runs from 0 to 1,000 in both directions. The left edge becomes , the top , the right and the bottom . Check: the scaled box is wide and high. The scaling lets pages of different sizes share one set of position embeddings.
- Make the image embedding. The word's box is cut out of the page image, and a Faster R-CNN detector turns the crop into a vector. For the special
[CLS]token, the detector gets the whole page as its region, so that token summarizes the page. - Tokenize the text. The word is split into subword pieces with WordPiece, as in BERT. Every piece of a word shares that word's box and image vector. Check: a word split into three pieces gives three inputs, each with the same box.
- Add the embeddings. For each token the input vector is the sum of its word embedding, its ordinary position embedding, the four 2-D position embeddings for , , and , and the image embedding. Check: removing the 2-D embeddings leaves a plain BERT input, which is why the model starts from BERT's weights.
- Run the transformer. The sum goes through the BERT layers, and each token comes out as a vector that now depends on the words and the positions of all other tokens on the page.
- Pre-train on two tasks. The masked visual-language task hides 15 percent of the tokens and asks the model to predict them, keeping their 2-D positions. The multi-label document classification task uses the page's tags from the collection to supervise the document-level representation. Check: the masked word "Total" must be predicted from its neighbours and from the fact that its box sits in the middle of the page.
- Fine-tune on a task. For forms and receipts, a linear layer and a softmax label each token. For page classification, the
[CLS]vector, concatenated with the whole-page image vector, goes through a softmax over the classes.
flowchart LR S["Scanned page"] --> O["OCR: words and pixel boxes"] O --> B["Scale boxes to 0 to 1000"] O --> W["Words and subword tokens"] S --> I["Faster R-CNN crop of each word"] B --> E["Sum of word, position and 2-D box embeddings"] W --> E I --> E E --> T["BERT transformer layers"] T --> P["Pre-training: masked words and page tags"] T --> F["Fine-tuning: labels per token or per page"]
The math
Step 5 in symbols: the input vector
Let token have word embedding , ordinary position embedding , and the four box coordinates of its word, , each in the scaled range. Let be its image embedding. The input vector is
Here and come from one shared table indexed by the horizontal coordinate, and and come from a second table indexed by the vertical coordinate. The paper states that layers for the same dimension share a table, so the left and right edges of a box use the same horizontal table.
Step 6 in symbols: the transformer
The vectors go through transformer layers, as in a transformer encoder. The base model has 12 layers with hidden size 768 and 12 attention heads, about 113 million parameters. The large model has 24 layers, hidden size 1,024, 16 heads, and about 343 million parameters.
Step 7 in symbols: the two pre-training losses
For the masked visual-language task, let be the set of masked positions. The model predicts the original token at each masked position from the whole context, and the loss is a sum of cross-entropy terms:
Of the 15 percent of tokens chosen, 80 percent are replaced by the [MASK] token, 10 percent by a random token and 10 percent are left unchanged. This follows BERT's masking scheme.
For the multi-label document classification task, a page can carry several tags at once. The usual loss for that setting is a sum of binary cross-entropies, one term per tag. The paper describes the loss in words, and the multi-label form given here is the standard one. Both losses are used in the same pre-training run.
Step 8 in symbols: fine-tuning
For form and receipt extraction, the paper tags each token with one of for the beginning, inside, end and single parts of an entity, and the outside label. Each token's final vector goes through a linear layer and a Softmax, which gives a probability for each tag. For page classification, the output for [CLS] is concatenated with the page image vector before the softmax over the 16 classes.
Results
Form understanding (FUNSD). The table below shows word-level F1 on FUNSD, which has 149 training forms and 50 test forms. F1 is the harmonic mean of precision and recall, so it penalises a model that either misses entities or invents them.
| Model | Pre-training data | F1 |
|---|---|---|
| BERT base, text only | Standard text corpora | 0.6026 |
| RoBERTa base, text only | Standard text corpora | 0.6648 |
| BERT large, text only | Standard text corpora | 0.6563 |
| RoBERTa large, text only | Standard text corpora | 0.7072 |
| LayoutLM base, text and layout | 1M scans, 6 epochs | 0.7299 |
| LayoutLM base, text and layout | 11M scans, 2 epochs | 0.7866 |
| LayoutLM large, text and layout | 11M scans, 1 epoch | 0.7789 |
| LayoutLM base, text, layout and image | 11M scans, 2 epochs | 0.7927 |
Table 2 of the paper shows that, for the base model, more scans and more epochs each raise the score. The best setting with 11 million scans and 2 epochs reaches 0.7866 without image features. Initialising from RoBERTa base instead of BERT base adds about 2.1 points (0.7514 against 0.7299), and training from scratch gives 0.6130.
Receipt extraction (SROIE). The receipts dataset has 626 training and 347 test receipts, with four fields: company, date, address and total. The score is exact-match F1. Each receipt in the dataset is already given as text lines with bounding boxes, so the comparison does not depend on the OCR step. The large LayoutLM trained on 11 million scans gets 0.9524, against 0.9200 for BERT large and 0.9402 for the top entry in the competition.
Document image classification (RVL-CDIP). The collection has 400,000 grayscale images in 16 classes, split 320,000, 40,000 and 40,000. Accuracy is shown below.
| Model | Accuracy |
|---|---|
| BERT base, text only | 89.81% |
| LayoutLM base, text and layout, 11M scans | 91.78% |
| Multimodal ensemble from prior work | 93.07% |
| LayoutLM base, text, layout and image, 11M scans | 94.42% |
The paper's conclusion from this table is that text alone is not enough for page classification, and that layout helps even without the image. Adding the image gives the largest gain.
Limits. The authors pre-train on scans only, and they leave semantic linking out of scope. The pre-training tags come from metadata that the authors say contains errors and inconsistencies. Semantic linking in FUNSD, which relates one field to another, is out of scope. Pre-training with the multi-label task is optional, and the authors note that it may not be practical for larger datasets where tags are missing. Pre-training is expensive: the base model takes about 80 hours per epoch over the 11 million documents on eight V100 GPUs, and the large model about 170 hours.
Reading guide
Read the paper in this order, with these prerequisites:
- Section 1, Introduction: the problem and the three benchmarks. Needs Optical Character Recognition for the idea of words with boxes.
- Section 2.1 and 2.2, BERT and the LayoutLM idea: Needs BERT and Transformer.
- Section 2.3, Model architecture: the 2-D position embedding and the image embedding. Needs Positional Encoding for the ordinary position embedding, convolutional features for the image, and Faster R-CNN for the region features. The box coordinates are described in Axis-Aligned Bounding Box.
- Section 2.4 and 2.5, Pre-training and fine-tuning: the two tasks and the tagging. Needs Masked Language Modeling, Cross-Entropy Loss, Softmax and Self-Supervised Learning.
- Section 3.1 to 3.4, Data, pre-processing and training: the IIT-CDIP collection, Tesseract OCR, and the optimizer setup. Needs Adam Optimizer, Subword Tokenization and Transfer Learning.
- Section 3.6, Results: Tables 1 to 5. Needs RoBERTa for the comparison, and Object Detection for the image side.
- Section 4 and 5, Related work and conclusion: rule-based and learned document analysis, then the future directions.
Check yourself
QuestionBesides the usual word and position embeddings, what two embeddings does LayoutLM add to each token?Show answer
[CLS] token uses an image embedding of the whole page.QuestionA word's box on the 0 to 1,000 scale is . What are its width and height on that scale?Show answer
QuestionIn the masked visual-language task, why does the model keep the 2-D position embedding of a masked token?Show answer
QuestionA team has 5,000 unlabeled scanned invoices with OCR output and only 100 labeled ones. Which parts of LayoutLM would you reuse, and what does the paper suggest about the trade-off?Show answer
Sources
- Xu, Y. et al. (2019). LayoutLM: Pre-training of Text and Layout for Document Image Understanding. arXiv: https://arxiv.org/abs/1912.13318
- Jaume, G. et al. (2019). FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents. https://guillaumejaume.github.io/FUNSD/
- Ren, S. et al. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. arXiv: https://arxiv.org/abs/1506.01497