Search

Search papers and lessons

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

Yupan Huang, Tengchao Lv, Lei Cui et al. · 2022

LayoutLMv3 pre-trains one transformer on text, layout and page patches with masking on both text and image, and a word-patch alignment task, reaching top scores on document benchmarks without a CNN or detector.

On this page

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

TL;DR

LayoutLMv3 is a transformer that reads a scanned document as two streams at once: the words, with their positions on the page, and the page itself, cut into small square patches. It is pre-trained with three objectives. Two of them hide parts of the text and parts of the image and ask the model to recover them. The third asks whether each unmasked word still has its image patches visible, which ties the two streams together. Unlike its predecessors, it does not need a convolutional network or an object detector to read the image, and it reaches top scores on form, receipt, page-classification and question-answering benchmarks.

Builds on: LayoutLM, Masked Autoencoder, Vector Quantization · Leads to: no lesson in the graph builds on it yet.

Why it mattered

Document AI systems need to work on text, layout and appearance together, and the earlier LayoutLM family handled the image with a convolutional network or a Faster R-CNN detector. Both are heavy, and the detector needs region annotations to train. The paper's point is that a page is also a sequence of patches, which a transformer can read directly, the same way a vision transformer reads an image. That removes the detector and most of the pre-processing.

The result is a single general model. The same pre-trained weights are fine-tuned for text-centric tasks such as forms, receipts and document question answering, and for image-centric tasks such as page classification and layout analysis. Earlier models were usually strong on one side and weaker on the other.

The paper's authors also note that many multimodal document models use masked language modeling for the text and a different, often noisier, objective for the image. Their unified masking aims to make the two modalities learn with the same kind of target.

The problem

Pre-training a multimodal model needs a target for each modality. For text, the standard target is a word token, as in BERT. For images, earlier document models used pixel reconstruction, which tends to learn noisy detail rather than the structure of the page, or regression of region features, which is harder to learn than choosing among a discrete set. The two targets have different granularities, so the model struggles to line up a word with the part of the page where it appears.

A second problem is the architecture. A convolutional or detector backbone adds parameters and needs object proposals. The paper asks whether a plain transformer on image patches can do the job, provided the image objective and the alignment between words and patches are designed well.

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 receipt line, "Total 12.50", whose two words sit in one segment, so they share one box. The box is given as fractions of the page width and height.

  1. Run OCR. An OCR toolkit gives the words "Total" and "12.50" and their positions. Because the two words form one segment, both get the same box: left 0.10, top 0.75, right 0.32, bottom 0.78. Check: the box is 0.32−0.10=0.220.32 - 0.10 = 0.22 of the page wide.
  2. Encode the layout. The four layout features, the x and y positions and the width and height, each go through their own embedding layer. The box is therefore encoded once for the segment, not once per word. Check: the two words use the same layout embedding.
  3. Encode the text. Each word is split into subword tokens, using byte-pair encoding, and the word embeddings start from RoBERTa's. A 1D position embedding gives each token its place in the sequence. Check: "12.50" may become several tokens, and they all carry the segment's layout embedding.
  4. Encode the image. The page is resized to 224×224224 \times 224 pixels and cut into 16×1616 \times 16 squares. That gives 196196 patches. Each patch is projected by a linear layer to the model's width, and a learnable 1D position embedding is added. Check: 224/16=14224 / 16 = 14, and 14×14=19614 \times 14 = 196.
  5. Concatenate. The text tokens and the image patches form one sequence, with special tokens marking the boundaries. Self-attention then lets every token look at every other token and patch. The attention also gets relative position biases for text and for image.
  6. Mask and predict. The text objective hides 30 percent of the text tokens, in spans, and predicts them. The image objective hides about 40 percent of the patches, in blocks, and predicts a discrete code for each hidden patch from a visual tokenizer with 8,192 codes. The alignment objective looks at each unmasked word: it is labelled aligned if all its patches are unmasked, and unaligned otherwise.
  7. Fine-tune. For forms and receipts, a linear layer labels each text token. For page classification, an MLP reads the [CLS] token. For document question answering, a classifier picks the start and end of the answer span among the text tokens. For layout analysis, the model is used as a backbone for a detector, with only the image side.
flowchart LR
  S["Scanned page"] --> O["OCR: words, segment boxes"]
  S --> P["224 by 224 page, 196 patches"]
  O --> T["Text tokens + 1D position + segment layout"]
  P --> V["Linear patch projection + 1D position"]
  T --> C["One sequence: text then patches"]
  V --> C
  C --> E["Transformer with 1D and 2D attention bias"]
  E --> L1["Masked text prediction"]
  E --> L2["Masked patch code prediction"]
  E --> L3["Word-patch alignment"]
  E --> F["Fine-tuning heads"]

The math

Step 2 in symbols: the layout embedding

Let boxℓ=(x,y,w,h)\text{box}_\ell = (x, y, w, h) be the normalized layout of the segment that token ℓ\ell belongs to, with coordinates divided by the image size as in LayoutLM. The layout part of the embedding is the sum of four lookups, added to the text embedding as LayoutLM adds its layout embeddings,

lℓ=exx+eyy+eww+ehh,\mathbf{l}_\ell = \mathbf{e}^{x}_{x} + \mathbf{e}^{y}_{y} + \mathbf{e}^{w}_{w} + \mathbf{e}^{h}_{h},

where each e\mathbf{e} is a learned embedding table indexed by the value of that feature. Tokens of the same segment share the same index, which is what makes the layout segment-level.

Step 4 in symbols: the image patches

The image is I∈RC×H×W\mathbf{I} \in \mathbb{R}^{C \times H \times W}, with C=3C = 3, H=W=224H = W = 224. It is split into P×PP \times P patches with P=16P = 16, and the number of patches is

M=HWP2=224×22416×16=196.M = \frac{HW}{P^{2}} = \frac{224 \times 224}{16 \times 16} = 196.

Each patch is flattened, projected linearly to the model width DD, and given a learnable 1D position embedding. The paper reports that 2D position embeddings for patches gave no gain in its preliminary tests.

Step 6 in symbols: the three losses

Let M′M' be the masked image positions and L′L' the masked text positions. The text objective predicts each masked token from the corrupted image and text,

LMLM=−∑ℓ∈L′log⁡pθ(yℓ∣XM′,YL′),\mathcal{L}_{\text{MLM}} = -\sum_{\ell \in L'} \log p_\theta\big(y_\ell \mid \mathbf{X}^{M'}, \mathbf{Y}^{L'}\big),

and the image objective predicts the discrete code of each masked patch in the same way,

LMIM=−∑m∈M′log⁡pθ(xm∣XM′,YL′).\mathcal{L}_{\text{MIM}} = -\sum_{m \in M'} \log p_\theta\big(x_m \mid \mathbf{X}^{M'}, \mathbf{Y}^{L'}\big).

The codes come from a discrete tokenizer with 8,192 entries, initialized from a document image transformer called DiT. The idea is the same as the discrete latent codes of VQ-VAE and DALL-E.

The alignment objective is a binary classification over the unmasked text tokens. Let zℓ∈{0,1}z_\ell \in \{0, 1\} be 1 when the word's patches are all unmasked. A two-layer head predicts zℓz_\ell with binary cross-entropy, and masked text tokens are excluded so the model cannot learn the position of a hidden word from its patches.

The total objective is the sum of the three,

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

The text masking uses spans whose lengths follow a Poisson distribution with mean 3. The image masking is blockwise, following BEiT.

Results

Form, receipt, page-classification and question-answering benchmarks. The table below uses the base model, which has 133 million parameters, and the large model, which has 368 million. F1 is the score on FUNSD and CORD, accuracy on RVL-CDIP, and ANLS on DocVQA, the edit-distance-based score used for that dataset. Some rows are from earlier papers.

ModelImage embeddingFUNSD F1CORD F1RVL-CDIP accuracyDocVQA ANLS
BERT basenone60.2689.6889.8163.72
LayoutLM baseResNet-101, fine-tuned79.27not reported94.42not reported
LayoutLMv2 baseResNeXt-101 FPN, grid82.7694.9595.2578.08
LayoutLMv3 baselinear patches90.2996.5695.4478.76
LayoutLMv2 largeResNeXt-101 FPN, grid84.2096.0195.6483.48
LayoutLMv3 largelinear patches92.0897.4695.9383.37

The paper's comparisons show that the base model improves on LayoutLMv2 base by 0.19 points on RVL-CDIP and by 0.7 ANLS points on DocVQA. For the large size, the paper reports an absolute ANLS gain of 4.61 over LayoutLMv3 base on DocVQA. The large model's FUNSD score, 92.08, is ahead of the 85.14 reported for StructuralLM. The paper cautions that StructuralLM and LayoutLMv3 both use segment-level layout, while many other models use word-level layout, so these FUNSD scores are not strictly like for like.

Document layout analysis (PubLayNet). Here the model is a backbone for a Cascade R-CNN detector, with no text. The overall mean average precision is 95.1, against 94.5 for the DiT base backbone with the same detector, 93.9 for UDoc and 91.0 for the original PubLayNet ResNet-101 baseline. The largest gain is on the title category, which the paper attributes to the language modality learned in pre-training.

What each part contributes. Table 3 of the paper is an ablation at the base size, trained on one million documents for 150,000 steps. It starts from a text-and-layout model with masked text pre-training only, and adds one piece at a time.

SettingImage embedding and objectivesFUNSD F1CORD F1RVL-CDIP accuracyPubLayNet mAP
1none, masked text only88.6496.2795.33not applicable
2linear patches, masked text only89.3996.1195.00loss diverged
3linear patches, masked text and masked image89.1996.3095.4294.38
4linear patches, all three objectives89.7896.4995.5394.43

Two findings stand out. Adding patches without an image objective hurt on CORD and RVL-CDIP, and the PubLayNet loss did not converge. Masked image modeling fixed the convergence and helped on CORD and RVL-CDIP. The alignment objective improved every task. The paper also reports that the linear patch projection adds only 0.6 million parameters, against 44 million for a ResNet-101 backbone.

Limits. The model reads at most 512 text tokens and a 224×224224 \times 224 image, so very dense pages lose detail. Pre-training uses 11 million of the document images in IIT-CDIP, with no image augmentation. Some benchmarks use text extracted by different OCR systems: the paper uses Microsoft's Read API for RVL-CDIP and DocVQA, and the official OCR for CORD. Scores across rows of a table are therefore not always from identical inputs. The paper also notes that the image tokenizer is a separate module and is not counted in the parameter totals.

Reading guide

Read the paper in this order, with these prerequisites:

Check yourself

QuestionWhat does each of the three pre-training objectives predict?Show answer
The masked language objective predicts the hidden text tokens. The masked image objective predicts a discrete code for each hidden image patch. The word-patch alignment objective predicts, for each unmasked word, whether all of its image patches are unmasked.
QuestionA page is resized to 224 by 224 pixels and cut into 16 by 16 patches. A text sequence has 40 tokens, and 30 percent of them are masked for the text objective. How many image patches does the model see, and how many text tokens are masked?Show answer
The model sees 224/16=14224 / 16 = 14 patches per side, so 14×14=19614 \times 14 = 196 patches. The text objective masks 0.30×40=120.30 \times 40 = 12 tokens.
QuestionWhy does LayoutLMv3 give all the words of one segment the same layout embedding, rather than one embedding per word?Show answer
Words in one segment usually express one meaning and occupy one region, so a single segment-level position is a cleaner signal and matches how the paper's authors model layout. The trade-off is that segment-level scores on FUNSD are not strictly comparable with models that use word-level layout.
QuestionA team classifies scanned pages on a small GPU budget. The paper's RVL-CDIP scores are 95.44 percent for the base model with 133 million parameters and 95.93 percent for the large model with 368 million. Which would you choose, and why?Show answer
The base model. It is within half a point of the large model on that task while being about a third of the size, and its image side is a linear patch projection, so it stays light on memory. The gap is small enough that the memory saving is usually the better trade, though the team should check the gap on its own pages.

Sources

Read the full paper

Yupan Huang, Tengchao Lv, Lei Cui et al., 2022. arXiv:2204.08387