Back to paper library
Paper notesarXiv 2022ACM Multimedia 2022

LayoutLMv3

Where Did the CNN Go?

Original paper

LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking

Paper authors

Yupan Huang · Tengchao Lv · Lei Cui · Yutong Lu · Furu Wei

Publication
ACM Multimedia 2022Conference
First submitted to arXiv
arXiv:2204.08387
Cite this paper · BibTeX

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

@misc{documentunderstandinglayoutlmv32022,
  title = {{LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking}},
  author = {Yupan Huang and Tengchao Lv and Lei Cui and Yutong Lu and Furu Wei},
  year = {2022},
  eprint = {2204.08387},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2204.08387}
}
On this page

LayoutLMv2 let the model see the page during pretraining. The eye doing the seeing was a ResNeXt101-FPN trained for layout detection on PubLayNet; the whole page was resized to 224×224 and fed in, and the output was averaged down to 7×7 visual tokens.

That eye didn't come cheap. LayoutLMv2-base has about 200 million parameters in total, and its image backbone first had to be trained on a detection dataset annotated with layout boxes. Other document models of the period were similar. DocFormer extracted grid features with ResNet-50, and SelfDoc and UDoc extracted region features with Faster R-CNN.

In the third generation, the Microsoft Research Asia team (first author Yupan Huang was then a student at Sun Yat-sen University, interning at Microsoft) removed that eye entirely. The page is cut into 16×16 patches, each projected into a vector by a linear layer and placed directly in the same sequence as the text tokens. The base model drops to 133 million parameters and still achieves the best or near-best results of its time on five document tasks.

With the CNN gone, what does the image side learn from?

Defining the Problem

The authors first surveyed the multimodal document models of the time and found that on the text side everyone did the same thing, using BERT's masked language modeling (MLM) to mask some words and have the model guess them back, while on the image side everyone went their own way.

  • DocFormer uses a CNN decoder to reconstruct masked pixels. The authors argue this tends to learn noisy details rather than high-level structure such as layout.
  • SelfDoc masks some regions and has the model regress their region features. Continuous feature vectors are noisier than discrete classes, and harder to learn.
  • LayoutLMv2 has no image reconstruction and relies on two alignment tasks, TIA and TIM.

Text consists of discrete tokens, while images are continuous pixels or feature vectors, so the pretraining objectives on the two sides differ in granularity. The authors believe this mismatch makes cross-modal alignment harder to learn.

Another issue is the cost of the image embedding itself. CNN grid features are computationally heavy; Faster R-CNN region features require a detector first, and that detector must first be trained on annotated regions.

So the questions this paper wants to answer are whether text and images can be pretrained with the same kind of objective, and whether an image side reduced to a single linear layer can still support even a purely visual task like layout detection.

Solving the Problem

One Sequence

Diagram of the LayoutLMv3 architecture. At the top are the three pretraining objectives: MLM guesses the masked words (30% masked, span length drawn from Poisson(3)), MIM guesses the token IDs of masked patches (about 40% masked, targets from DiT's tokenizer), and WPA decides whether the patch under an unmasked word is masked (binary: aligned or unaligned). In the middle is the multimodal Transformer, with 1D and 2D relative position biases added to self-attention. Below is the input sequence, [CLS], text tokens, and [SEP] on the left and image tokens on the right, up to 512 text tokens plus 196 image tokens. Of the two bottom panels, the left shows the text path: OCR (Read API) gives text lines, BPE tokens with word embeddings initialized from RoBERTa, plus a 1D position and a 2D segment position, with the example TOTAL $ 12 . 50 sharing one dashed box. The right shows the image path: the page is resized to 224×224 and cut into 196 patches of 16×16, and each patch is flattened to 768 values and projected to 768 dimensions (about 0.6M parameters). A note at the bottom says LayoutLMv2's image backbone is ResNeXt101-FPN and ResNet-101 has about 44M parameters.
Drawn for this note from Sections 2.1, 2.2, 3.1, and 3.5 of the paper.

Read this figure from the bottom up. As before, a document page takes two paths.

The text path is largely the same as in the previous two generations. OCR reads out the words and their boxes, the text is split into tokens with BPE, and the word embeddings are initialized from RoBERTa (the earlier generations used BERT or UniLMv2), up to 512 tokens, with [CLS] and [SEP] added at the ends. Each token gets a 1D position and a 2D layout position; following LayoutLM, the 2D position looks up x, y, width, and height in separate embedding tables.

What's new compared with the previous two generations is that the 2D position becomes segment-level. LayoutLM and LayoutLMv2 give each word its own box; LayoutLMv3 has all the words in the same text segment share one box, on the grounds that a segment of text usually expresses a single meaning. During pretraining, segments come from the OCR engine's text lines; the authors later explained on GitHub that they used the Microsoft Read API, whose output already records “which words belong to the same line.” This change has unexpected consequences on FUNSD, which we'll get to in the Discussion.

The image path is where this paper really changes things. The page is resized to 224×224 and cut into 16×16 patches, 14×14=19614 \times 14 = 196 in all. Each patch has 16×16×3=76816 \times 16 \times 3 = 768 pixel values; flatten them, multiply by a 768×768768 \times 768 matrix, add a bias, and you have a 768-dimensional vector:

768×768+768=590,592≈0.6M768 \times 768 + 768 = 590{,}592 \approx 0.6\text{M}

That's the parameter count of the entire image backbone. The ResNet-101 the paper uses for comparison has about 44 million.

Each patch vector then gets a learnable 1D position embedding. The authors say they tried 2D position embeddings in preliminary experiments, and they were no better.

The two paths join, and up to 512+196512 + 196 tokens enter one Transformer. Following LayoutLMv2, self-attention adds 1D and 2D relative position biases, for both text and image tokens. Architecturally it closely resembles ViLT; both linearly project image patches and feed them straight into the Transformer, bypassing any CNN.

Three Pretraining Objectives

The total loss is the sum of three terms:

L=LMLM+LMIM+LWPA\mathcal{L} = \mathcal{L}_{\text{MLM}} + \mathcal{L}_{\text{MIM}} + \mathcal{L}_{\text{WPA}}

MLM is an old friend on the text side, but the masking has changed. The earlier generations randomly masked 15% of individual tokens; here 30% are masked, in spans, with each span's length drawn from a Poisson distribution with λ=3\lambda = 3. Masked words keep their layout positions.

MIM is the new image-side objective, symmetric with MLM. About 40% of the image patches are masked in blocks, and at each masked position the model has to guess that patch's “visual token ID.” The IDs come from an image tokenizer that maps a patch of image to one of 8,192 IDs. LayoutLMv3's tokenizer is initialized from DiT's dictionary, the one trained on 42 million document pages.

The two objectives look almost identical as formulas:

LMLM=−∑ℓ=1L′log⁡pθ(yℓ∣XM′,YL′)LMIM=−∑m=1M′log⁡pθ(xm∣XM′,YL′)\begin{aligned} \mathcal{L}_{\text{MLM}} &= -\sum_{\ell=1}^{L'} \log p_\theta\left(y_\ell \mid X^{M'}, Y^{L'}\right) \\ \mathcal{L}_{\text{MIM}} &= -\sum_{m=1}^{M'} \log p_\theta\left(x_m \mid X^{M'}, Y^{L'}\right) \end{aligned}

XM′X^{M'} and YL′Y^{L'} are the masked image and text sequences, yℓy_\ell is a masked text token, and xmx_m is the visual token ID of a masked patch. Both sides “guess the masked discrete IDs, conditioned on the masked text plus image,” and that is the “unified” in the paper's title. The authors argue that guessing discrete IDs, more than reconstructing pixels, leads the model to learn layout structure rather than details like paper texture.

WPA (Word-Patch Alignment) is what ties the two sides together.

Diagram of WPA labels. On the left is a page of 14×14 patches with three lines of text: Invoice No. 1024, Date 2022-04-18, and TOTAL $12.50. MLM has replaced 1024 with [MASK], and MIM has masked in gray the block of patches on the left where Date sits plus two blocks at the top right and bottom right. On the right, a table lists for each text token whether MLM masked it, whether its patch is masked, and its WPA label: Invoice, No., 2022-04-18, TOTAL, and $12.50 are unmasked with unmasked patches, labeled aligned; 1024 was masked by MLM and is excluded; Date is unmasked but its patch is masked, labeled unaligned. A note below says words masked by MLM don't count toward the WPA loss, so the model doesn't learn to match masked words to image patches.
Drawn for this note from Section 2.2 of the paper; page content and mask positions are illustrative.

MLM and MIM each mask independently, and nothing between them tells the model “which part of the image this word is in.” WPA builds its questions from the masks that already exist. For each text token not masked by MLM, look at the image patch it corresponds to on the page. If MIM didn't mask the patch, the label is aligned; if it did, the label is unaligned. The model performs binary classification on the text token outputs with a two-layer MLP.

Walk through the figure above. Invoice and No. are both unmasked, and so are the patches they sit in, so they're labeled aligned. 1024 was replaced with [MASK] by MLM and doesn't count toward the WPA loss; the authors say this keeps the model from learning a correspondence between “masked words” and the image. Date itself is unmasked, but its part of the image was masked by MIM, so it's labeled unaligned. To get Date right, the model has to know which part of the image Date's coordinates fall in and then check whether that part is covered.

If you've read LayoutLMv2, this looks a lot like TIA. TIA has to separately paint over whole lines of text in the image and then ask whether each word was covered; WPA doesn't touch the image at all and simply borrows MIM's masks. The paper doesn't explain how “its patch is masked” is decided when a word spans several patches.

Training

The Transformer and text embeddings are initialized from RoBERTa, the image tokenizer from DiT, and the remaining parameters randomly. The pretraining data is again IIT-CDIP, of which the authors use only 11 million images; batch size 2,048, 500,000 steps, and no image augmentation. The base model uses a learning rate of 1e-4 with warmup over the first 4.8% of steps; the large model uses 5e-5 with 10% warmup. Model sizes match the previous two generations: base has 12 layers and 768 dimensions, large has 24 layers and 1,024 dimensions.

To stabilize mixed-precision training, the authors changed how attention scores are computed, borrowing a trick from CogView:

S=QK⊤αd,α=32S = \frac{QK^\top}{\alpha\sqrt{d}}, \qquad \alpha = 32 softmax⁡(QK⊤d)=softmax⁡(αS)=softmax⁡(α (S−max⁡S))\begin{aligned} & \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d}}\right) \\ &= \operatorname{softmax}(\alpha S) \\ &= \operatorname{softmax}\big(\alpha\,(S - \max S)\big) \end{aligned}

These three lines are mathematically identical. Subtracting the same constant from every element leaves softmax unchanged; dividing by α\alpha, subtracting the maximum, and multiplying α\alpha back in only reorders the computation. The difference is numerical. Half-precision floats top out at 65,504, so large elements of QK⊤QK^\top overflow; dividing by 32 first and then subtracting keeps the intermediate values in a safe range.

Discussion

The downstream tasks fall into two groups. The text-centric ones are FUNSD (forms), CORD (receipts), and DocVQA (document question answering); the image-centric ones are RVL-CDIP (document classification) and PubLayNet (layout analysis). Text for RVL-CDIP and DocVQA is extracted with the Read API; FUNSD and CORD use the OCR annotations that come with the datasets.

Forms and Receipts

ModelParamsFUNSDCORD
LayoutLMv2-base200M82.7694.95
DocFormer-base183M83.3496.33
LiLT-base–88.4196.07
LayoutLMv3-base133M90.2996.56
LayoutLMv2-large426M84.2096.01
BROS-large340M84.5297.40
StructuralLM-large355M85.14–
DocFormer-large536M84.5596.99
LayoutLMv3-large368M92.0897.46

Compiled from Table 1 of the paper; F1 (×100).

The FUNSD column stands out. LayoutLMv3-large's 92.08 is nearly 7 points above the previous best, StructuralLM; even the base model's 90.29 beats every large model. The gap on CORD is much smaller, with the large model just 0.06 above BROS.

In the text, the authors make a point of noting that LayoutLMv3 and StructuralLM use segment-level layout positions while other work uses word-level ones, that segment-level positions may favor entity labeling on FUNSD, and that the two kinds of results therefore can't be compared directly. That sentence matters a lot, yet the table carries no mark for it.

Document Classification and Question Answering

ModelParamsRVL-CDIPDocVQA
LayoutLMv2-base200M95.2578.08
DocFormer-base183M96.17–
LayoutLMv3-base133M95.4478.76
LayoutLMv2-large426M95.6483.48
StructuralLM-large355M96.0883.94‡
TILT-large780M95.5287.05‡
LayoutLMv3-large368M95.9383.37

Compiled from Table 1 of the paper; accuracy for RVL-CDIP and ANLS for DocVQA (both ×100). ‡ Trained on more data for DocVQA.

These two columns tell a different story. On RVL-CDIP, LayoutLMv3-large's 95.93 is below StructuralLM's 96.08, and also below DocFormer-base's 96.17. On DocVQA, LayoutLMv3-large's 83.37 is slightly lower than the previous generation's LayoutLMv2-large at 83.48.

The authors' wording is “better or comparable,” with fewer parameters and a much simpler image embedding. That description is accurate; it's just that anyone reading the abstract could easily come away thinking all five tasks set new records.

Layout Analysis

PubLayNet is a pure image task, so the authors drop the text embeddings and use only image patches. The hookup is the same as DiT's: features are taken from layers 4, 6, 8, and 12 of the base model, resized, and fed to FPN and Cascade R-CNN.

LayoutLMv3-base reaches an overall mAP of 95.1, compared with 94.5 for DiT-base, also with Cascade R-CNN, and 91.0 for the Mask R-CNN in the original PubLayNet paper. Of the five classes, titles show the largest gap, 90.6 vs. 88.9. The authors speculate that titles are usually small and recognizable only from the content of the words, and that because LayoutLMv3 saw text during pretraining, its image representation carries some linguistic information. This is speculation; the paper runs no experiment to separate the factors.

A multimodal model whose image embedding has only 0.6M parameters beats DiT, a dedicated image backbone, on a pure image detection task. This is the paper's most convincing result.

Ablation

SettingFUNSDCORDRVL-CDIPPubLayNet
#1 No image, MLM88.6496.2795.33N/A
#2 Linear patch, MLM89.3996.1195.00Diverged
#3 Linear patch, MLM+MIM89.1996.3095.4294.38
#4 Linear patch, MLM+MIM+WPA89.7896.4995.5394.43

Compiled from Table 3 of the paper. All base size, pretrained for only 150,000 steps on 1 million samples, so the numbers are lower than in the main table.

Going down row by row:

  1. Linear patches attached, but no image objective (#1 → #2). FUNSD rises 0.75, while CORD and RVL-CDIP drop; PubLayNet's fine-tuning loss diverges outright. The authors tried three learning rates and two batch sizes, and the mAP stayed close to 0 every time. With no image objective during pretraining, the linear layer can't learn a useful image representation.
  2. Adding MIM (#2 → #3). PubLayNet converges, with an mAP of 94.38, and CORD and RVL-CDIP recover. FUNSD dips slightly, by 0.2. MIM is what lets this “eye without a CNN” learn at all.
  3. Adding WPA (#3 → #4). All four tasks improve, by between 0.05 and 0.59, and PubLayNet's fine-tuning loss is lower too.

The table hides one more thing. The first row has no image at all, only text and segment-level layout, yet FUNSD is already at 88.64, nearly 6 points above LayoutLMv2-base's 82.76 in the main table; attaching the image and adding MIM and WPA adds 1.1 more in total. The two tables use different pretraining scales, so you can't subtract one from the other directly, but the direction is clear. LayoutLMv3's big lead on FUNSD mostly doesn't come from the image.

So where does it come from?

That Box in FUNSD

Three ways of giving coordinates to the same line of text, using Registration No. 533 from FUNSD as the example. The first row is LayoutLM and LayoutLMv2, one box per word: Registration (94, 169, 168, 186), No. (170, 169, 191, 183), 533 (209, 169, 236, 182). The second row is LayoutLMv3 pretraining: if OCR reads this as one line, the three words share one box (94, 169, 236, 186), hiding where the field name ends and the answer begins. The third row is LayoutLMv3 fine-tuned on FUNSD, with the dataset's entities as segments: the question box (94, 169, 191, 186) encloses Registration No., the answer box (209, 169, 236, 182) encloses 533, and the box boundaries are exactly the annotated entity boundaries.
Drawn for this note from Section 2.1 of the paper, the official FUNSD preprocessing code (layoutlmft/data/funsd.py), and GitHub issues #793 and #838; coordinates are from the FUNSD annotation example.

In pretraining, segments are the text lines OCR provides. A single line can contain both a field name and its answer, as in the second row of the figure above, where the three words share one box and the box itself gives no hint of which is the question and which the answer.

Fine-tuning on FUNSD is a different story. FUNSD's annotation files consist of semantic entities, each with its own words and box. In July 2022, someone pointed out on GitHub (issue #793) that the official FUNSD preprocessing code reads the data entity by entity and merges the word boxes within each entity into a single box, used as the segment position for those words. That's the third row of the figure: “Registration No.” shares one box, and “533” gets another.

The box boundaries are the annotated entity boundaries. The model is supposed to judge which words belong to the same entity, and the input already spells it out.

The maintainer replied that downstream tasks use the segments the dataset provides directly, and only pretraining uses OCR text lines. The first author added that LayoutLMv3 performs the task as the original FUNSD paper defines it, the “labeling of already grouped entities,” and that the paper already says the results can't be compared directly; the next day, they also confirmed that LayoutLMv2 did not use this grouping information, adding that, as far as they knew, only LayoutLMv3 and StructuralLM did.

How much that “not directly comparable” is worth was later measured. The authors of EC-FUNSD re-annotated FUNSD with text lines and entities labeled separately, and also ran several controlled comparisons on the original FUNSD:

Bar chart of FUNSD entity labeling F1 under different box settings. Blue bars come from the LayoutLMv3 paper: LayoutLMv2-base with word boxes 82.76; LayoutLMv3 with no image and segment boxes (ablation #1) 88.64; LayoutLMv3-base with segment boxes 90.29. Orange bars come from the EC-FUNSD paper: LayoutLMv3-base with segment boxes, rerun by EC-FUNSD, 90.85; the same model given word boxes at inference 22.75; word boxes for both fine-tuning and testing 81.06; the same setup on the EC-FUNSD dataset 82.30. A note says ablation #1 was pretrained on only 1M pages for 150K steps, and that EC-FUNSD labels segments (text lines) and entities separately.
Drawn for this note from Tables 1 and 3 of the LayoutLMv3 paper and the experimental results of the EC-FUNSD paper (2402.02379v2) on FUNSD and EC-FUNSD.

The same LayoutLMv3-base, fine-tuned with entity boxes and given entity boxes at test time, scores an F1 of 90.85; give it word boxes at test time instead, and it drops to 22.75. With word boxes from start to finish, it scores 81.06, about the same as LayoutLMv2-base's 82.76. On EC-FUNSD, where text lines and entities are labeled separately, it scores 82.30.

So most of LayoutLMv3's lead over word-level models like LayoutLMv2 comes from the entity boxes, not the model. Only the comparison with StructuralLM, which also uses segment positions (92.08 vs. 85.14), pits like inputs against like. The paper includes one sentence saying the results aren't directly comparable, yet the table puts 92.08 and 84.20 in the same column without any mark (we all know how many readers stop at the table).

The Chinese Version

The appendix also trains a LayoutLMv3-Chinese base model, pretrained on 50 million pages of public digital-born Chinese documents, with the text side initialized from XLM-R. On EPHOIE (information extraction from the header sections of Chinese exam papers, 10 field classes), its average F1 is 99.21, against 97.95 for the previous leader, StrucTexT.

A few familiar faces show up in this table too. Alibaba's graph-convolution model for extracting invoice information scores 92.55, GraphIE 90.26, and BiLSTM-CRF 89.10. On the same dataset, going from sequence labeling to graph convolution to pretrained models, scores climb all the way from 89 to 99.

Code and License

The official unilm repo has fine-tuning code for FUNSD, CORD, and XFUND and detection configs for PubLayNet, and the pretrained base, large, and Chinese weights are all on Hugging Face.

The pretraining code isn't there. When someone asked in May 2022, the maintainer replied, “We do not have plans to release the pre-training code right now” (issue #733). In June, someone implementing MIM on their own asked how to apply the masks, was advised to consult the paper and BEiT's code, and was told that the released models are mainly for fine-tuning and don't include the parameters used in pretraining (issue #772). DiT's document dictionary isn't public either, so when the community redoes the pretraining, the targets have to come from DALL-E's dVAE instead.

The license story is even more tangled. The unilm repo itself is MIT, yet LayoutLMv3's README states that the whole directory is under CC BY-NC-SA 4.0, and the weights on Hugging Face are marked non-commercial too. In September 2022, someone noticed that the Hugging Face model card had changed to MIT; people got two days of celebration before it was changed back (issue #863). That November, a maintainer settled the matter in issue #873 with one sentence, “All pre-trained LayoutLMv2/v3 models are currently under a non-commercial license.”

In February 2024, someone asked in issue #1463 whether they could pay for a commercial license. No official reply came; two months later, the person who asked left a comment saying they'd have to switch to Azure's document service instead (wallet out, and no checkout in sight).

Conclusion

LayoutLMv3 replaces the CNN in document models with a 0.6M-parameter linear layer, pretrains both text and image by “guessing masked discrete IDs,” and uses WPA to align words with the image by borrowing the masks from both sides. The ablation makes it clear that what lets linear patches carry layout detection is MIM; without it, PubLayNet training doesn't even converge. On the pure-image PubLayNet, it beats the dedicated image backbone DiT.

The other half of the conclusion has to be read out of the ablation and the FUNSD boxes. Its big lead over word-level models on FUNSD comes mainly from segment-level positions, and during fine-tuning the segments are the annotated entities; on RVL-CDIP and DocVQA, it roughly ties the previous generation and its contemporaries.

For research, the weights and fine-tuning code are all there, and it's easy to get started. For a product, the non-commercial license stands in the way; someone who wanted to buy a license asked on GitHub in 2024 and has yet to get an answer.