Search

Search papers and lessons

LayoutLM: Pre-training of Text and Layout for Document Image Understanding

Yiheng Xu, Minghao Li, Lei Cui et al. · 2019

LayoutLM extends BERT with each word's position on the page and an image of the word, pre-trains on millions of scanned documents without labels, and beats text-only models on forms, receipts and document classification.

On this page

  • Colour = topic mix
  • Discrete math
  • Architectures
  • Computer vision
  • Calculus
  • Neural network basics
  • Linear algebra
  • ReadReady to readNot yet

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).

  1. 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.
  2. 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 100/850×1000≈118100 / 850 \times 1000 \approx 118, the top 500/1100×1000≈455500 / 1100 \times 1000 \approx 455, the right 180/850×1000≈212180 / 850 \times 1000 \approx 212 and the bottom 520/1100×1000≈473520 / 1100 \times 1000 \approx 473. Check: the scaled box is 212−118=94212 - 118 = 94 wide and 473−455=18473 - 455 = 18 high. The scaling lets pages of different sizes share one set of position embeddings.
  3. 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.
  4. 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.
  5. 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 x0x_0, y0y_0, x1x_1 and y1y_1, 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.
  6. 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.
  7. 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.
  8. 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 ii have word embedding eiword\mathbf{e}^{\text{word}}_i, ordinary position embedding eipos\mathbf{e}^{\text{pos}}_i, and the four box coordinates of its word, (x0,y0,x1,y1)(x_0, y_0, x_1, y_1), each in the scaled range. Let eiimg\mathbf{e}^{\text{img}}_i be its image embedding. The input vector is

hi=eiword+eipos+ex0(i)x0+ey0(i)y0+ex1(i)x1+ey1(i)y1+eiimg.\mathbf{h}_i = \mathbf{e}^{\text{word}}_i + \mathbf{e}^{\text{pos}}_i + \mathbf{e}^{x_0}_{x_0(i)} + \mathbf{e}^{y_0}_{y_0(i)} + \mathbf{e}^{x_1}_{x_1(i)} + \mathbf{e}^{y_1}_{y_1(i)} + \mathbf{e}^{\text{img}}_i.

Here ex0\mathbf{e}^{x_0} and ex1\mathbf{e}^{x_1} come from one shared table indexed by the horizontal coordinate, and ey0\mathbf{e}^{y_0} and ey1\mathbf{e}^{y_1} 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 h1,…,hn\mathbf{h}_1, \dots, \mathbf{h}_n go through LL 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 MM be the set of masked positions. The model predicts the original token tit_i at each masked position from the whole context, and the loss is a sum of cross-entropy terms:

LMVLM=−∑i∈Mlog⁡P(ti∣context).\mathcal{L}_{\text{MVLM}} = -\sum_{i \in M} \log P(t_i \mid \text{context}).

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 {B,I,E,S,O}\{B, I, E, S, O\} 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.

ModelPre-training dataF1
BERT base, text onlyStandard text corpora0.6026
RoBERTa base, text onlyStandard text corpora0.6648
BERT large, text onlyStandard text corpora0.6563
RoBERTa large, text onlyStandard text corpora0.7072
LayoutLM base, text and layout1M scans, 6 epochs0.7299
LayoutLM base, text and layout11M scans, 2 epochs0.7866
LayoutLM large, text and layout11M scans, 1 epoch0.7789
LayoutLM base, text, layout and image11M scans, 2 epochs0.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.

ModelAccuracy
BERT base, text only89.81%
LayoutLM base, text and layout, 11M scans91.78%
Multimodal ensemble from prior work93.07%
LayoutLM base, text, layout and image, 11M scans94.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:

Check yourself

QuestionBesides the usual word and position embeddings, what two embeddings does LayoutLM add to each token?Show answer
A 2-D position embedding made from the four box coordinates, x0x_0, y0y_0, x1x_1 and y1y_1, and an image embedding of the word's crop from a Faster R-CNN detector. The [CLS] token uses an image embedding of the whole page.
QuestionA word's box on the 0 to 1,000 scale is (118,455,212,473)(118, 455, 212, 473). What are its width and height on that scale?Show answer
The width is 212−118=94212 - 118 = 94 and the height is 473−455=18473 - 455 = 18.
QuestionIn the masked visual-language task, why does the model keep the 2-D position embedding of a masked token?Show answer
The model must predict the hidden word from its context and from where it sits on the page. Keeping the position lets the model learn the link between layout and meaning, such as a value that sits to the right of its label. Removing the position would reduce the task to plain BERT.
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
Start from a pre-trained LayoutLM checkpoint and fine-tune it on the 100 labeled invoices, the way the paper fine-tunes on the 149 training forms of FUNSD. Optionally, continue pre-training on the team's own unlabeled scans, because the masked task needs no labels. The paper's cost figures, about 80 hours per epoch on 11 million scans for the base model, show that this continued pre-training is a substantial compute decision.

Sources

Read the full paper

Yiheng Xu, Minghao Li, Lei Cui et al., 2019. arXiv:1912.13318