Back to paper library
Paper notesarXiv 2020ACL-IJCNLP 2021

LayoutLMv2

This Time It Really Looks

Original paper

LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding

Paper authors

Yang Xu · Yiheng Xu · Tengchao Lv …

Show all 12 authors

Yang Xu · Yiheng Xu · Tengchao Lv · Lei Cui · Furu Wei · Guoxin Wang · Yijuan Lu · Dinei Florencio · Cha Zhang · Wanxiang Che · Min Zhang · Lidong Zhou

Publication
ACL-IJCNLP 2021Conference
First submitted to arXiv
arXiv:2012.14740
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{documentunderstandinglayoutlmv22020,
  title = {{LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding}},
  author = {Yang Xu and Yiheng Xu and Tengchao Lv and Lei Cui and Furu Wei and Guoxin Wang and Yijuan Lu and Dinei Florencio and Cha Zhang and Wanxiang Che and Min Zhang and Lidong Zhou},
  year = {2020},
  eprint = {2012.14740},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2012.14740}
}
On this page

LayoutLM added a table lookup of each word's coordinates to BERT and set the state of the art at the time on forms, receipts and document classification. But it had something it didn't like to bring up. During pretraining, the model never actually saw the page.

The image features were attached from a Faster R-CNN only at fine-tuning, and the code for that branch was never released. All LayoutLM learned from 11 million pages of scanned documents was text and coordinates.

A year later, the same team, joined by colleagues from Microsoft Azure AI, delivered the second generation. This time the page image enters the Transformer from the very first step of pretraining; coordinates are not only looked up in tables but also written directly into the attention scores; and there are two new pretraining tasks dedicated to aligning text with the image.

Defining the Problem

The authors split research on Visually-rich Document Understanding (VrDU) at the time into two directions.

The first is shallow fusion. Text goes through a pretrained NLP model and the image through a pretrained CV model, each extracts its own features, and the features are combined and trained with supervision on labeled data. It works reasonably well, but every new kind of document means retraining, and what was learned doesn't carry over. Layout regularities that different documents share, such as "keys and values sit side by side" or "tables are laid out in a grid," can't be put to good use either.

The second is deep fusion, meaning cross-modal pretraining on large amounts of unlabeled documents. LayoutLM belongs here.

LayoutLMv2 takes the second direction and sets out to answer two questions LayoutLM left behind:

  1. How do you bring the image in during pretraining? If the model can see the page directly, won't the words hidden by masked language modeling simply be read off the pixels?
  2. LayoutLM's coordinates are absolute positions, so "these two words are on the same line, one on the left and one on the right" can only be inferred by the Transformer from the summed vectors. Can attention be told about relative positions explicitly?

Solving the Problem

Original Figure 1: LayoutLMv2's architecture and pretraining tasks. At the bottom right, an OCR/PDF parser extracts text lines from the document page; Line 1 is covered and Line 2 is not, and some tokens are masked as [MASK]. On the left, the page with some text lines covered goes through the visual encoder, giving a feature map split into four pieces, V1 to V4. In the middle, from bottom to top, are the visual and text token embeddings, the 2D position embeddings (Box_V1 to Box_V4, Box_PAD, Box_T1 to Box_T7), the 1D position embeddings (0 to 3 for visual tokens, 0 to 8 for text tokens) and the segment embeddings (C for visual, A for text), all fed into a Transformer with spatial-aware self-attention. At the top are three pretraining objectives: #1 masked visual-language modeling predicts T2 and T4; #2 text-image alignment marks T1 and T3 as Covered and T5 to T7 as Not Covered; #3 text-image matching outputs Matched on [CLS].
Original Figure 1, Xu et al., from ACL PDF page 3, CC BY 4.0.

Start at the very bottom of this figure. A document page goes two ways. To the right, it goes to OCR and comes back as lines of text; to the left, it goes to the visual encoder and comes back as a feature map, cut into four pieces, V1 to V4 (there are actually 49; the figure draws four to illustrate).

The tokens from both paths sit in one sequence, visual tokens first and text tokens after, and each gets 2D position, 1D position and segment embeddings stacked on. Look at the 1D position row. The visual tokens are numbered 0 to 3, the text tokens start again from 0, and both share the same 1D position table.

In the middle is the Transformer, with every layer switched to spatial-aware self-attention. At the top are the three pretraining tasks, which we'll take one at a time.

One Receipt, Two Kinds of Tokens

We'll reuse the receipt from the previous note, a 600×800600 \times 800 pixel image whose bottom line reads "TOTAL" and "$12.50", with normalized boxes (100,875,250,905)(100, 875, 250, 905) and (700,875,866,905)(700, 875, 866, 905).

The text path is the same as in LayoutLM. WordPiece splits it into [CLS] total $ 12 . 50 [SEP], then pads with [PAD] up to the maximum length L=512L = 512. Each text token's embedding is:

ti=TokEmb(wi)+PosEmb1D(i)+SegEmb(si)\begin{aligned} \mathbf{t}_i = {} & \mathrm{TokEmb}(w_i) + \mathrm{PosEmb1D}(i) \\ & + \mathrm{SegEmb}(s_i) \end{aligned}

The image path is new. The whole page is first shrunk to 224×224224 \times 224 and fed into a ResNeXt101-FPN. The official implementation takes the output of the FPN's finest level, with stride 4, so the feature map is 56×56×25656 \times 56 \times 256; this is then average-pooled to 7×77 \times 7 and flattened into 49 vectors of 256 dimensions, which a linear layer projects to 768 dimensions:

vi=Proj(VisTokEmb(I)i)+PosEmb1D(i)+SegEmb([C])\begin{aligned} \mathbf{v}_i = {} & \mathrm{Proj}\big(\mathrm{VisTokEmb}(I)_i\big) \\ & + \mathrm{PosEmb1D}(i) + \mathrm{SegEmb}([\texttt{C}]) \end{aligned}

ii runs from 0 to 48, and the segment is always [C], reserved for visual tokens.

Stop and think about the resolution for a moment. Shrink an A4 document to 224×224224 \times 224 and ordinary body text is only a pixel or two tall, basically unreadable. Average that down to 7×77 \times 7 and each visual token covers a seventh of the page's width and a seventh of its height. So what the visual tokens bring in is mainly the look of the layout, such as where there's a big block of table, where there's a title bar, where there's white space, rather than the words themselves.

Visual tokens need boxes too. A CNN computes locally, so each visual token maps to exactly one cell of the page, with no overlaps and no gaps. The official code divides 0 to 1000 into seven equal parts, with boundaries at 0, 142, 285, 428, 571, 714, 857 and 1000. Our TOTAL line has yy between 875 and 905, so it falls in the bottom row (857 to 1000); TOTAL itself spans columns 0 and 1, and the amount spans columns 4 to 6.

Put the two paths together and the sequence length is 49+512=56149 + 512 = 561.

Layout Embedding: From Sum to Concatenation

LayoutLM looked up a 768-dimensional vector for each of the four coordinates and simply added them. LayoutLMv2 assembles things differently. Each box contributes six features (xmin⁡,xmax⁡,ymin⁡,ymax⁡,width,height)(x_{\min}, x_{\max}, y_{\min}, y_{\max}, \text{width}, \text{height}), each looked up as a shorter vector, and these are concatenated into one:

li=Concat(lix, liy)lix=PosEmb2Dx(xmin⁡,xmax⁡,width)liy=PosEmb2Dy(ymin⁡,ymax⁡,height)\begin{aligned} \mathbf{l}_i &= \mathrm{Concat}\big(\mathbf{l}^x_i,\ \mathbf{l}^y_i\big) \\ \mathbf{l}^x_i &= \mathrm{PosEmb2D}_x(x_{\min}, x_{\max}, \text{width}) \\ \mathbf{l}^y_i &= \mathrm{PosEmb2D}_y(y_{\min}, y_{\max}, \text{height}) \end{aligned}

In the official implementation each piece has 128 dimensions, and the six pieces concatenated give exactly 6×128=7686 \times 128 = 768. For TOTAL:

ltotal=[ X[100]; Y[875]; X[250];Y[905]; H[30]; W[150] ]\begin{aligned} \mathbf{l}_{\texttt{total}} = \big[\, & X[100];\ Y[875];\ X[250]; \\ & Y[905];\ H[30];\ W[150] \,\big] \end{aligned}

The width 150 and height 30 each look up their own separate table. Visual tokens use the box of their own cell; [CLS], [SEP] and [PAD] use an all-zero box.

Finally, the input to the Transformer's first layer is the embedding plus the layout:

xi(0)=Xi+liX={v0,…,v48,t0,…,t511}\begin{aligned} \mathbf{x}_i^{(0)} &= \mathbf{X}_i + \mathbf{l}_i \\ \mathbf{X} &= \{\mathbf{v}_0, \dots, \mathbf{v}_{48}, \mathbf{t}_0, \dots, \mathbf{t}_{511}\} \end{aligned}

Spatial-Aware Self-Attention

So far, coordinates still appear only at the input. The standard self-attention score is:

αij=1dhead(xiWQ)(xjWK)⊤\alpha_{ij} = \frac{1}{\sqrt{d_{\text{head}}}} \big(\mathbf{x}_i \mathbf{W}^Q\big)\big(\mathbf{x}_j \mathbf{W}^K\big)^\top

This score looks only at the contents of the two vectors. Whether two words are on the same line, the model has to puzzle out for itself from the position vectors mixed into xi\mathbf{x}_i and xj\mathbf{x}_j.

LayoutLMv2 borrows the relative position bias that T5 and UniLMv2 use on one-dimensional sequences, extends it to two dimensions, and adds three scalars directly to the score:

αij′=αij+bj−i(1D)+bxj−xi(2Dx)+byj−yi(2Dy)\alpha'_{ij} = \alpha_{ij} + b^{(1D)}_{j-i} + b^{(2D_x)}_{x_j - x_i} + b^{(2D_y)}_{y_j - y_i}

All three bb terms are learnable lookup values; each attention head has its own set, shared across all layers. Note that they depend only on the relative distance between the two tokens, not on the tokens' content.

Relative distances span a wide range; in the x direction they can run from −1000 to +1000, and there's no way to give every value its own parameter. The official implementation uses T5's bucketing, with one bucket per step at short distances, logarithmic merging at long ones, and everything beyond the cap squeezed into the last bucket. The 2D directions use 64 buckets with a cap of 256; the 1D direction uses 32 buckets with a cap of 128; positive and negative directions each get half the buckets.

Let's take total as the query and see which buckets a few other tokens land in:

keyxj−xix_j - x_ix bucketyj−yiy_j - y_iy bucket
12 (same line, far right)+6006300
Adjacent word right, same line+305100
Word directly above, line above00−3019

Computed for this note with the official implementation's bucketing function.

12 is 600 units to the right of total, well past the cap of 256, so it lands in the farthest bucket; it's on the same line as total, so the yy difference is 0. The word on the line above lands in a negative-direction bucket. Each attention head learns its own preferences; one head, for example, might give a high bias to "same line, to the right" and specialize in finding field values.

These three biases form a 12×561×56112 \times 561 \times 561 tensor (12 heads in BASE), added to the attention scores before the softmax:

hi=∑jexp⁡(αij′)∑kexp⁡(αik′) xjWV\mathbf{h}_i = \sum_j \frac{\exp(\alpha'_{ij})}{\sum_k \exp(\alpha'_{ik})}\, \mathbf{x}_j \mathbf{W}^V

Three Pretraining Tasks

Original Figure 1, top half: the three pretraining objectives. The bottom row holds the output representations of the visual and text tokens, V1 to V4, [CLS], T1, [MASK], T3, [MASK], T5 to T7 and [SEP]; #1 masked visual-language modeling predicts T2 and T4 at the two [MASK] positions; #2 text-image alignment marks T1 and T3 as Covered and T5, T6 and T7 as Not Covered; #3 text-image matching outputs Matched on [CLS].
Original Figure 1, top half, Xu et al., from ACL PDF page 3, CC BY 4.0.

From the bottom up, these three rows are the three tasks. In the figure, the first text line is T1, [MASK], T3 and the second is [MASK], T5, T6, T7; the first line is covered in the image, the second is not.

Masked Visual-Language Modeling (MVLM). As in LayoutLM, 15% of the text tokens are masked at random, their coordinates kept, and the model predicts the original words. The new problem is that the model can now see the page. If 12 is replaced with [MASK], that spot on the page still has 12 printed on it, and the visual tokens could leak the answer. The authors' fix is to also blot out the regions of the masked tokens in the original page image before it goes into the visual encoder.

Text-Image Alignment (TIA). 15% of the text lines are picked at random and covered entirely in the image. Every text token has to decide whether its own region on the page has been covered, outputting [Covered] or [Not Covered], trained with binary cross-entropy.

Say the TOTAL line is chosen. That line is blacked out in the image, the labels for total, $, 12, . and 50 are all [Covered], and the words on every other line are [Not Covered]. To get this right, the model has to know which cell of the image its coordinates point to and then check whether that cell is black. That is the fine-grained alignment the authors were after.

Why cover whole lines instead of single words? Because at 224×224224 \times 224 the resolution is too low, and a word shrinks to a few pixels in the image; bars and symbols in charts can also look like covered words. At the word level the signal is too noisy.

The two [MASK] tokens in the figure also have no TIA arrows, because tokens masked by MVLM don't count toward the TIA loss; otherwise the model would learn a useless shortcut like "see [MASK], answer [Covered]."

Text-Image Matching (TIM). This is a coarse-grained task common in vision-language pretraining, in which [CLS] decides whether the image and the text come from the same page. There are two kinds of negatives: 15% of the images are swapped for a page from another document, and 5% are dropped altogether. To keep the model from cheating on traces such as "has something been blacked out," the negatives get the same masking and covering, and the TIA labels of every token in a negative sample are set to [Covered].

Initialization and Training

LayoutLMv2's text side and Transformer encoder follow UniLMv2's architecture and are also initialized from UniLMv2; BASE has about 200M parameters and LARGE about 426M.

The visual backbone has an unusual pedigree. The ResNeXt101-FPN comes from a Mask R-CNN trained on the PubLayNet layout dataset, and the paper's footnote points to a community project on GitHub, hpanwar08/detectron2. In other words, the visual encoder already knows how to find titles, paragraphs, tables and figures on research-paper pages before training even starts.

The pretraining data is still IIT-CDIP's 11 million pages, but OCR switched from Tesseract to Microsoft's own Read API. BASE trains for 5 epochs with a batch size of 64; LARGE trains for 20 epochs with a batch size of 2048. Compared with LayoutLM-large, which ran for just 1 epoch, this generation trains far more.

Discussion

There are six downstream tasks:

  • Entity extraction: FUNSD (forms), CORD (receipts, 30 fields), SROIE (receipts, 4 fields) and Kleister-NDA (non-disclosure agreements from the US SEC's EDGAR database, long documents), all treated as BIO sequence labeling and evaluated with entity-level F1.
  • Document classification: RVL-CDIP, classified from [CLS] plus pooled visual features.
  • Document question answering: DocVQA, treated as extractive QA by predicting the start and end positions of the answer on the text output.

Entity Extraction

ModelFUNSDCORDSROIEKleister-NDA
UniLMv2-large0.70720.92050.94880.8180
LayoutLM-large0.78950.94930.95240.8340
BROS0.81210.95360.9548–
LayoutLMv2-base0.82760.94950.96250.8330
LayoutLMv2-large0.84200.96010.97810.8520

Compiled from Table 2 of the paper. Kleister-NDA scores are on the validation set, since the test labels and submission site were not yet open at the time. LayoutLM-large's FUNSD score of 0.7895 is the number in this table; in the LayoutLM paper, the LARGE model pretrained for only 1 epoch scores 0.7789.

FUNSD shows the clearest gain, with LayoutLMv2-large 5.3 points above LayoutLM-large; even the BASE version, at 0.8276, already beats the previous generation's LARGE. The gaps on CORD and Kleister-NDA are much smaller, and on those two datasets the BASE version roughly ties LayoutLM-large.

The SROIE column deserves a second look.

Document Classification

On RVL-CDIP, the text-only UniLMv2-large gets only 90.20%; LayoutLM, with images, gets 94.42% (BASE) and 94.43% (LARGE); LayoutLMv2 gets 95.25% (BASE) and 95.64% (LARGE). That is 1.2 points above the previous best result.

DocVQA

DocVQA gives a document image and a question, and the answer is usually a span of text on the page. The metric is ANLS, which uses edit distance to measure how close a prediction is to the reference answer.

ModelFine-tuned onANLS
BERT-largetrain0.6768
UniLMv2-largetrain0.7709
LayoutLM-largetrain0.7259
LayoutLMv2-basetrain0.7808
LayoutLMv2-largetrain0.8348
LayoutLMv2-largetrain+dev0.8529
LayoutLMv2-large + QGtrain+dev0.8672
Leaderboard top (30-model ensemble)–0.8506

Compiled from Table 4 of the paper, test set.

Start with the two text-only rows. Going from BERT-large to UniLMv2-large lifts ANLS from 0.6768 to 0.7709, 4.5 points above LayoutLM-large's 0.7259. LayoutLM adding layout on top of BERT brought 4.9 points; switching to a better language model brought 9.4. LayoutLMv2 is initialized from UniLMv2, so that bonus gets credited to it as well.

The QG in the last LayoutLMv2 row is data augmentation. The DocVQA paper found that BERT fine-tuned on SQuAD first did better; so the authors took a question generation model trained on SQuAD, produced nearly 1 million question-answer pairs, fine-tuned LayoutLMv2-large on those first, and then fine-tuned on DocVQA. That took a single model to 0.8672, beating the leaderboard's ensemble of 30 models.

Ablation: What Each Part Is Worth

The ablations are run on the DocVQA validation set, with every model at BASE size and pretrained for 1 epoch on the full IIT-CDIP.

#Arch.Init.Spatial attn.TasksANLS
1LayoutLMBERTMVLM0.6841
2aLayoutLMv2BERT + X101-FPNMVLM0.6915
2bLayoutLMv2BERT + X101-FPNMVLM + TIA0.7061
2cLayoutLMv2BERT + X101-FPNMVLM + TIM0.6955
2dLayoutLMv2BERT + X101-FPNMVLM + TIA + TIM0.7124
3LayoutLMv2BERT + X101-FPN✓MVLM + TIA + TIM0.7217
4LayoutLMv2UniLMv2 + X101-FPN✓MVLM + TIA + TIM0.7421

Compiled from Table 5 of the paper, DocVQA validation set.

Reading down row by row:

  1. Adding only the image (#1 → #2a): +0.74. With the image pretrained on MVLM alone, it already helps.
  2. TIA (#2a → #2b): +1.46; TIM (#2a → #2c): +0.40. The fine-grained task the authors proposed is worth more than three times the generic TIM; using both (#2d) gives +2.09.
  3. Spatial-aware attention (#2d → #3): +0.93.
  4. Switching to UniLMv2 initialization (#3 → #4): +2.04.

From #1 to #3, with the same initialization and amount of training, LayoutLMv2's new design adds 3.76 points in total. Switching the initialization alone is worth 2.04 points, more than twice the spatial-aware attention. When you look at the gap between LayoutLMv2 and its predecessor, count these two parts separately.

On Reproducing It

The paper was uploaded at the end of December 2020; the code didn't come out until May 2021, and it went into a different directory called layoutlmft, leaving only a README in the layoutlmv2 directory (two months later, people were still asking in the issues why that directory was empty). The pretraining code was never released; issue #505, opened in November 2021, still has no official reply.

The DocVQA score is hard to reproduce, too. In August 2021 someone asked how to reproduce DocVQA, and a maintainer replied in #415, "This question has nothing to do with this repo. You should ask the author of DocVQA about how to process the dataset." In February 2022, a user in #616 got only about 74 with LayoutLMv2-base, against the paper's 78.08 for BASE fine-tuned on train alone. The maintainer replied, "We mentioned that we have used augmented samples from question generation methods." Yet in the paper's table, QG appears only in the LARGE, train+dev row.

The missing 4 points are probably hiding in the preprocessing that maps OCR output to answers (which happens to be exactly the part declared "out of the scope of this repo").

Conclusion

LayoutLMv2 lets the model see the page during pretraining and lets attention know the relative position of two words directly. To keep the image from leaking masked words, the authors blot those words out of the image as well, then use TIA to force the model to match each word to its cell in the image. In the ablation, TIA is the most effective of the new designs.

Keep in mind, though, that its gap over LayoutLM isn't all thanks to the architecture. UniLMv2 initialization, OCR switched to the Read API, and several times more training are all mixed into the numbers in the main tables; under the same conditions, the new design is worth 3.76 points on the DocVQA validation set.

If you actually use Hugging Face's LayoutLMv2, two things trip people up. First, its visual backbone comes from Detectron2 and expects BGR, not RGB. Second, LayoutLMv2Processor uses Tesseract for OCR by default, but during pretraining the model saw Read API output, which splits words and draws boxes differently.

Get either of these wrong and the code won't make a peep. You have to check them yourself.